Debian Codegraph @

source/code/Libs/imgui/imgui_widgets.cpp

raw symbols SCIP
1 // dear imgui, v1.92.3
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" // warning: format specifies type 'int' but the argument has type 'unsigned int'
74 #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.
75 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
76 #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.
77 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
78 #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.
79 #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
80 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
81 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
82 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
83 #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
84 #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
85 #elif defined(__GNUC__)
86 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
87 #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
88 #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
89 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
90 #pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
91 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
92 #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when simplifying division / ..when changing X +- C1 cmp C2 to X cmp C2 -+ C1
93 #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
94 #pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
95 #endif
96
97 //-------------------------------------------------------------------------
98 // Data
99 //-------------------------------------------------------------------------
100
101 // Widgets
102 static const float DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f; // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior.
103 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.
104
105 // Those MIN/MAX values are not define because we need to point to them
106 static const signed char IM_S8_MIN = -128;
107 static const signed char IM_S8_MAX = 127;
108 static const unsigned char IM_U8_MIN = 0;
109 static const unsigned char IM_U8_MAX = 0xFF;
110 static const signed short IM_S16_MIN = -32768;
111 static const signed short IM_S16_MAX = 32767;
112 static const unsigned short IM_U16_MIN = 0;
113 static const unsigned short IM_U16_MAX = 0xFFFF;
114 static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000);
115 static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF)
116 static const ImU32 IM_U32_MIN = 0;
117 static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF)
118 #ifdef LLONG_MIN
119 static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll);
120 static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll);
121 #else
122 static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1;
123 static const ImS64 IM_S64_MAX = 9223372036854775807LL;
124 #endif
125 static const ImU64 IM_U64_MIN = 0;
126 #ifdef ULLONG_MAX
127 static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);
128 #else
129 static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
130 #endif
131
132 //-------------------------------------------------------------------------
133 // [SECTION] Forward Declarations
134 //-------------------------------------------------------------------------
135
136 // For InputTextEx()
137 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false);
138 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining = NULL, ImVec2* out_offset = NULL, ImDrawTextFlags flags = 0);
139
140 //-------------------------------------------------------------------------
141 // [SECTION] Widgets: Text, etc.
142 //-------------------------------------------------------------------------
143 // - TextEx() [Internal]
144 // - TextUnformatted()
145 // - Text()
146 // - TextV()
147 // - TextColored()
148 // - TextColoredV()
149 // - TextDisabled()
150 // - TextDisabledV()
151 // - TextWrapped()
152 // - TextWrappedV()
153 // - LabelText()
154 // - LabelTextV()
155 // - BulletText()
156 // - BulletTextV()
157 //-------------------------------------------------------------------------
158
159 void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
160 {
161 ImGuiWindow* window = GetCurrentWindow();
162 if (window->SkipItems)
163 return;
164 ImGuiContext& g = *GImGui;
165
166 // Accept null ranges
167 if (text == text_end)
168 text = text_end = "";
169
170 // Calculate length
171 const char* text_begin = text;
172 if (text_end == NULL)
173 text_end = text + ImStrlen(text); // FIXME-OPT
174
175 const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
176 const float wrap_pos_x = window->DC.TextWrapPos;
177 const bool wrap_enabled = (wrap_pos_x >= 0.0f);
178 if (text_end - text <= 2000 || wrap_enabled)
179 {
180 // Common case
181 const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
182 const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
183
184 ImRect bb(text_pos, text_pos + text_size);
185 ItemSize(text_size, 0.0f);
186 if (!ItemAdd(bb, 0))
187 return;
188
189 // Render (we don't hide text after ## in this end-user function)
190 RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
191 }
192 else
193 {
194 // Long text!
195 // Perform manual coarse clipping to optimize for long multi-line text
196 // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
197 // - 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.
198 // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
199 const char* line = text;
200 const float line_height = GetTextLineHeight();
201 ImVec2 text_size(0, 0);
202
203 // Lines to skip (can't skip when logging text)
204 ImVec2 pos = text_pos;
205 if (!g.LogEnabled)
206 {
207 int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
208 if (lines_skippable > 0)
209 {
210 int lines_skipped = 0;
211 while (line < text_end && lines_skipped < lines_skippable)
212 {
213 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
214 if (!line_end)
215 line_end = text_end;
216 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
217 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
218 line = line_end + 1;
219 lines_skipped++;
220 }
221 pos.y += lines_skipped * line_height;
222 }
223 }
224
225 // Lines to render
226 if (line < text_end)
227 {
228 ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
229 while (line < text_end)
230 {
231 if (IsClippedEx(line_rect, 0))
232 break;
233
234 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
235 if (!line_end)
236 line_end = text_end;
237 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
238 RenderText(pos, line, line_end, false);
239 line = line_end + 1;
240 line_rect.Min.y += line_height;
241 line_rect.Max.y += line_height;
242 pos.y += line_height;
243 }
244
245 // Count remaining lines
246 int lines_skipped = 0;
247 while (line < text_end)
248 {
249 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
250 if (!line_end)
251 line_end = text_end;
252 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
253 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
254 line = line_end + 1;
255 lines_skipped++;
256 }
257 pos.y += lines_skipped * line_height;
258 }
259 text_size.y = (pos - text_pos).y;
260
261 ImRect bb(text_pos, text_pos + text_size);
262 ItemSize(text_size, 0.0f);
263 ItemAdd(bb, 0);
264 }
265 }
266
267 void ImGui::TextUnformatted(const char* text, const char* text_end)
268 {
269 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
270 }
271
272 void ImGui::Text(const char* fmt, ...)
273 {
274 va_list args;
275 va_start(args, fmt);
276 TextV(fmt, args);
277 va_end(args);
278 }
279
280 void ImGui::TextV(const char* fmt, va_list args)
281 {
282 ImGuiWindow* window = GetCurrentWindow();
283 if (window->SkipItems)
284 return;
285
286 const char* text, *text_end;
287 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
288 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
289 }
290
291 void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
292 {
293 va_list args;
294 va_start(args, fmt);
295 TextColoredV(col, fmt, args);
296 va_end(args);
297 }
298
299 void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
300 {
301 PushStyleColor(ImGuiCol_Text, col);
302 TextV(fmt, args);
303 PopStyleColor();
304 }
305
306 void ImGui::TextDisabled(const char* fmt, ...)
307 {
308 va_list args;
309 va_start(args, fmt);
310 TextDisabledV(fmt, args);
311 va_end(args);
312 }
313
314 void ImGui::TextDisabledV(const char* fmt, va_list args)
315 {
316 ImGuiContext& g = *GImGui;
317 PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
318 TextV(fmt, args);
319 PopStyleColor();
320 }
321
322 void ImGui::TextWrapped(const char* fmt, ...)
323 {
324 va_list args;
325 va_start(args, fmt);
326 TextWrappedV(fmt, args);
327 va_end(args);
328 }
329
330 void ImGui::TextWrappedV(const char* fmt, va_list args)
331 {
332 ImGuiContext& g = *GImGui;
333 const bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
334 if (need_backup)
335 PushTextWrapPos(0.0f);
336 TextV(fmt, args);
337 if (need_backup)
338 PopTextWrapPos();
339 }
340
341 void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...)
342 {
343 va_list args;
344 va_start(args, fmt);
345 TextAlignedV(align_x, size_x, fmt, args);
346 va_end(args);
347 }
348
349 // align_x: 0.0f = left, 0.5f = center, 1.0f = right.
350 // size_x : 0.0f = shortcut for GetContentRegionAvail().x
351 // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024)
352 void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args)
353 {
354 ImGuiWindow* window = GetCurrentWindow();
355 if (window->SkipItems)
356 return;
357
358 const char* text, *text_end;
359 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
360 const ImVec2 text_size = CalcTextSize(text, text_end);
361 size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x;
362
363 ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
364 ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y);
365 ImVec2 size(ImMin(size_x, text_size.x), text_size.y);
366 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x);
367 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x);
368 if (align_x > 0.0f && text_size.x < size_x)
369 pos.x += ImTrunc((size_x - text_size.x) * align_x);
370 RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size);
371
372 const ImVec2 backup_max_pos = window->DC.CursorMaxPos;
373 ItemSize(size);
374 ItemAdd(ImRect(pos, pos + size), 0);
375 window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up.
376
377 if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip))
378 SetTooltip("%.*s", (int)(text_end - text), text);
379 }
380
381 void ImGui::LabelText(const char* label, const char* fmt, ...)
382 {
383 va_list args;
384 va_start(args, fmt);
385 LabelTextV(label, fmt, args);
386 va_end(args);
387 }
388
389 // Add a label+text combo aligned to other label+value widgets
390 void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
391 {
392 ImGuiWindow* window = GetCurrentWindow();
393 if (window->SkipItems)
394 return;
395
396 ImGuiContext& g = *GImGui;
397 const ImGuiStyle& style = g.Style;
398 const float w = CalcItemWidth();
399
400 const char* value_text_begin, *value_text_end;
401 ImFormatStringToTempBufferV(&value_text_begin, &value_text_end, fmt, args);
402 const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false);
403 const ImVec2 label_size = CalcTextSize(label, NULL, true);
404
405 const ImVec2 pos = window->DC.CursorPos;
406 const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2));
407 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));
408 ItemSize(total_bb, style.FramePadding.y);
409 if (!ItemAdd(total_bb, 0))
410 return;
411
412 // Render
413 RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f));
414 if (label_size.x > 0.0f)
415 RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
416 }
417
418 void ImGui::BulletText(const char* fmt, ...)
419 {
420 va_list args;
421 va_start(args, fmt);
422 BulletTextV(fmt, args);
423 va_end(args);
424 }
425
426 // Text with a little bullet aligned to the typical tree node.
427 void ImGui::BulletTextV(const char* fmt, va_list args)
428 {
429 ImGuiWindow* window = GetCurrentWindow();
430 if (window->SkipItems)
431 return;
432
433 ImGuiContext& g = *GImGui;
434 const ImGuiStyle& style = g.Style;
435
436 const char* text_begin, *text_end;
437 ImFormatStringToTempBufferV(&text_begin, &text_end, fmt, args);
438 const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
439 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
440 ImVec2 pos = window->DC.CursorPos;
441 pos.y += window->DC.CurrLineTextBaseOffset;
442 ItemSize(total_size, 0.0f);
443 const ImRect bb(pos, pos + total_size);
444 if (!ItemAdd(bb, 0))
445 return;
446
447 // Render
448 ImU32 text_col = GetColorU32(ImGuiCol_Text);
449 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col);
450 RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);
451 }
452
453 //-------------------------------------------------------------------------
454 // [SECTION] Widgets: Main
455 //-------------------------------------------------------------------------
456 // - ButtonBehavior() [Internal]
457 // - Button()
458 // - SmallButton()
459 // - InvisibleButton()
460 // - ArrowButton()
461 // - CloseButton() [Internal]
462 // - CollapseButton() [Internal]
463 // - GetWindowScrollbarID() [Internal]
464 // - GetWindowScrollbarRect() [Internal]
465 // - Scrollbar() [Internal]
466 // - ScrollbarEx() [Internal]
467 // - Image()
468 // - ImageButton()
469 // - Checkbox()
470 // - CheckboxFlagsT() [Internal]
471 // - CheckboxFlags()
472 // - RadioButton()
473 // - ProgressBar()
474 // - Bullet()
475 // - Hyperlink()
476 //-------------------------------------------------------------------------
477
478 // The ButtonBehavior() function is key to many interactions and used by many/most widgets.
479 // Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),
480 // this code is a little complex.
481 // By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.
482 // See the series of events below and the corresponding state reported by dear imgui:
483 //------------------------------------------------------------------------------------------------------------------------------------------------
484 // with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
485 // Frame N+0 (mouse is outside bb) - - - - - -
486 // Frame N+1 (mouse moves inside bb) - true - - - -
487 // Frame N+2 (mouse button is down) - true true true - true
488 // Frame N+3 (mouse button is down) - true true - - -
489 // Frame N+4 (mouse moves outside bb) - - true - - -
490 // Frame N+5 (mouse moves inside bb) - true true - - -
491 // Frame N+6 (mouse button is released) true true - - true -
492 // Frame N+7 (mouse button is released) - true - - - -
493 // Frame N+8 (mouse moves outside bb) - - - - - -
494 //------------------------------------------------------------------------------------------------------------------------------------------------
495 // with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
496 // Frame N+2 (mouse button is down) true true true true - true
497 // Frame N+3 (mouse button is down) - true true - - -
498 // Frame N+6 (mouse button is released) - true - - true -
499 // Frame N+7 (mouse button is released) - true - - - -
500 //------------------------------------------------------------------------------------------------------------------------------------------------
501 // with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
502 // Frame N+2 (mouse button is down) - true - - - true
503 // Frame N+3 (mouse button is down) - true - - - -
504 // Frame N+6 (mouse button is released) true true - - - -
505 // Frame N+7 (mouse button is released) - true - - - -
506 //------------------------------------------------------------------------------------------------------------------------------------------------
507 // with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
508 // Frame N+0 (mouse button is down) - true - - - true
509 // Frame N+1 (mouse button is down) - true - - - -
510 // Frame N+2 (mouse button is released) - true - - - -
511 // Frame N+3 (mouse button is released) - true - - - -
512 // Frame N+4 (mouse button is down) true true true true - true
513 // Frame N+5 (mouse button is down) - true true - - -
514 // Frame N+6 (mouse button is released) - true - - true -
515 // Frame N+7 (mouse button is released) - true - - - -
516 //------------------------------------------------------------------------------------------------------------------------------------------------
517 // Note that some combinations are supported,
518 // - PressedOnDragDropHold can generally be associated with any flag.
519 // - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
520 //------------------------------------------------------------------------------------------------------------------------------------------------
521 // The behavior of the return-value changes when ImGuiItemFlags_ButtonRepeat is set:
522 // Repeat+ Repeat+ Repeat+ Repeat+
523 // PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
524 //-------------------------------------------------------------------------------------------------------------------------------------------------
525 // Frame N+0 (mouse button is down) - true - true
526 // ... - - - -
527 // Frame N + RepeatDelay true true - true
528 // ... - - - -
529 // Frame N + RepeatDelay + RepeatRate*N true true - true
530 //-------------------------------------------------------------------------------------------------------------------------------------------------
531
532 // - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc.
533 // And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
534 // For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
535 // - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature.
536 // One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior()
537 // with same ID and different MouseButton (see #8030). You can fix it by:
538 // (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags.
539 // or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
540 bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
541 {
542 ImGuiContext& g = *GImGui;
543 ImGuiWindow* window = GetCurrentWindow();
544
545 // Default behavior inherited from item flags
546 // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
547 ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
548 if (flags & ImGuiButtonFlags_AllowOverlap)
549 item_flags |= ImGuiItemFlags_AllowOverlap;
550 if (item_flags & ImGuiItemFlags_NoFocus)
551 flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus;
552
553 // Default only reacts to left mouse button
554 if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
555 flags |= ImGuiButtonFlags_MouseButtonLeft;
556
557 // Default behavior requires click + release inside bounding box
558 if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
559 flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_;
560
561 ImGuiWindow* backup_hovered_window = g.HoveredWindow;
562 const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree;
563 if (flatten_hovered_children)
564 g.HoveredWindow = window;
565
566 #ifdef IMGUI_ENABLE_TEST_ENGINE
567 // Alternate registration spot, for when caller didn't use ItemAdd()
568 if (g.LastItemData.ID != id)
569 IMGUI_TEST_ENGINE_ITEM_ADD(id, bb, NULL);
570 #endif
571
572 bool pressed = false;
573 bool hovered = ItemHoverable(bb, id, item_flags);
574
575 // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.)
576 // where holding the button pressed for a long time while drag a payload item triggers the button.
577 if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
578 if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
579 {
580 hovered = true;
581 SetHoveredID(id);
582 if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER)
583 {
584 pressed = true;
585 g.DragDropHoldJustPressedId = id;
586 FocusWindow(window);
587 }
588 }
589
590 if (flatten_hovered_children)
591 g.HoveredWindow = backup_hovered_window;
592
593 // Mouse handling
594 const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
595 if (hovered)
596 {
597 IM_ASSERT(id != 0); // Lazily check inside rare path.
598
599 // Poll mouse buttons
600 // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId.
601 // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine.
602 int mouse_button_clicked = -1;
603 int mouse_button_released = -1;
604 for (int button = 0; button < 3; button++)
605 if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here.
606 {
607 if (IsMouseClicked(button, ImGuiInputFlags_None, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; }
608 if (IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; }
609 }
610
611 // Process initial action
612 const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt);
613 if (mods_ok)
614 {
615 if (mouse_button_clicked != -1 && g.ActiveId != id)
616 {
617 if (!(flags & ImGuiButtonFlags_NoSetKeyOwner))
618 SetKeyOwner(MouseButtonToKey(mouse_button_clicked), id);
619 if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
620 {
621 SetActiveID(id, window);
622 g.ActiveIdMouseButton = mouse_button_clicked;
623 if (!(flags & ImGuiButtonFlags_NoNavFocus))
624 {
625 SetFocusID(id, window);
626 FocusWindow(window);
627 }
628 else if (!(flags & ImGuiButtonFlags_NoFocus))
629 {
630 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
631 }
632 }
633 if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))
634 {
635 pressed = true;
636 if (flags & ImGuiButtonFlags_NoHoldingActiveId)
637 ClearActiveID();
638 else
639 SetActiveID(id, window); // Hold on ID
640 g.ActiveIdMouseButton = mouse_button_clicked;
641 if (!(flags & ImGuiButtonFlags_NoNavFocus))
642 {
643 SetFocusID(id, window);
644 FocusWindow(window);
645 }
646 else if (!(flags & ImGuiButtonFlags_NoFocus))
647 {
648 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
649 }
650 }
651 }
652 if (flags & ImGuiButtonFlags_PressedOnRelease)
653 {
654 if (mouse_button_released != -1)
655 {
656 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
657 if (!has_repeated_at_least_once)
658 pressed = true;
659 if (!(flags & ImGuiButtonFlags_NoNavFocus))
660 SetFocusID(id, window); // FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why.
661 ClearActiveID();
662 }
663 }
664
665 // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
666 // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
667 if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat))
668 if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id))
669 pressed = true;
670 }
671
672 if (pressed && g.IO.ConfigNavCursorVisibleAuto)
673 g.NavCursorVisible = false;
674 }
675
676 // Keyboard/Gamepad navigation handling
677 // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
678 if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav)
679 if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
680 hovered = true;
681 if (g.NavActivateDownId == id)
682 {
683 bool nav_activated_by_code = (g.NavActivateId == id);
684 bool nav_activated_by_inputs = (g.NavActivatePressedId == id);
685 if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat))
686 {
687 // Avoid pressing multiple keys from triggering excessive amount of repeat events
688 const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space);
689 const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter);
690 const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate);
691 const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration);
692 nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
693 }
694 if (nav_activated_by_code || nav_activated_by_inputs)
695 {
696 // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
697 pressed = true;
698 SetActiveID(id, window);
699 g.ActiveIdSource = g.NavInputSource;
700 if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut))
701 SetFocusID(id, window);
702 if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)
703 g.ActiveIdFromShortcut = true;
704 }
705 }
706
707 // Process while held
708 bool held = false;
709 if (g.ActiveId == id)
710 {
711 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
712 {
713 if (g.ActiveIdIsJustActivated)
714 g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
715
716 const int mouse_button = g.ActiveIdMouseButton;
717 if (mouse_button == -1)
718 {
719 // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
720 ClearActiveID();
721 }
722 else if (IsMouseDown(mouse_button, test_owner_id))
723 {
724 held = true;
725 }
726 else
727 {
728 bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
729 bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
730 if ((release_in || release_anywhere) && !g.DragDropActive)
731 {
732 // Report as pressed when releasing the mouse (this is the most common path)
733 bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;
734 bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
735 bool is_button_avail_or_owned = TestKeyOwner(MouseButtonToKey(mouse_button), test_owner_id);
736 if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned)
737 pressed = true;
738 }
739 ClearActiveID();
740 }
741 if (!(flags & ImGuiButtonFlags_NoNavFocus) && g.IO.ConfigNavCursorVisibleAuto)
742 g.NavCursorVisible = false;
743 }
744 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
745 {
746 // When activated using Nav, we hold on the ActiveID until activation button is released
747 if (g.NavActivateDownId == id)
748 held = true; // hovered == true not true as we are already likely hovered on direct activation.
749 else
750 ClearActiveID();
751 }
752 if (pressed)
753 g.ActiveIdHasBeenPressedBefore = true;
754 }
755
756 // Activation highlight (this may be a remote activation)
757 if (g.NavHighlightActivatedId == id)
758 hovered = true;
759
760 if (out_hovered) *out_hovered = hovered;
761 if (out_held) *out_held = held;
762
763 return pressed;
764 }
765
766 bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
767 {
768 ImGuiWindow* window = GetCurrentWindow();
769 if (window->SkipItems)
770 return false;
771
772 ImGuiContext& g = *GImGui;
773 const ImGuiStyle& style = g.Style;
774 const ImGuiID id = window->GetID(label);
775 const ImVec2 label_size = CalcTextSize(label, NULL, true);
776
777 ImVec2 pos = window->DC.CursorPos;
778 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)
779 pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
780 ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
781
782 const ImRect bb(pos, pos + size);
783 ItemSize(size, style.FramePadding.y);
784 if (!ItemAdd(bb, id))
785 return false;
786
787 bool hovered, held;
788 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
789
790 // Render
791 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
792 RenderNavCursor(bb, id);
793 RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
794
795 if (g.LogEnabled)
796 LogSetNextTextDecoration("[", "]");
797 RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
798
799 // Automatically close popups
800 //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
801 // CloseCurrentPopup();
802
803 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
804 return pressed;
805 }
806
807 bool ImGui::Button(const char* label, const ImVec2& size_arg)
808 {
809 return ButtonEx(label, size_arg, ImGuiButtonFlags_None);
810 }
811
812 // Small buttons fits within text without additional vertical spacing.
813 bool ImGui::SmallButton(const char* label)
814 {
815 ImGuiContext& g = *GImGui;
816 float backup_padding_y = g.Style.FramePadding.y;
817 g.Style.FramePadding.y = 0.0f;
818 bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
819 g.Style.FramePadding.y = backup_padding_y;
820 return pressed;
821 }
822
823 // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
824 // 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)
825 bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags)
826 {
827 ImGuiContext& g = *GImGui;
828 ImGuiWindow* window = GetCurrentWindow();
829 if (window->SkipItems)
830 return false;
831
832 // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
833 IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
834
835 const ImGuiID id = window->GetID(str_id);
836 ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
837 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
838 ItemSize(size);
839 if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav))
840 return false;
841
842 bool hovered, held;
843 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
844 RenderNavCursor(bb, id);
845
846 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
847 return pressed;
848 }
849
850 bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
851 {
852 ImGuiContext& g = *GImGui;
853 ImGuiWindow* window = GetCurrentWindow();
854 if (window->SkipItems)
855 return false;
856
857 const ImGuiID id = window->GetID(str_id);
858 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
859 const float default_size = GetFrameHeight();
860 ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f);
861 if (!ItemAdd(bb, id))
862 return false;
863
864 bool hovered, held;
865 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
866
867 // Render
868 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
869 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
870 RenderNavCursor(bb, id);
871 RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
872 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);
873
874 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
875 return pressed;
876 }
877
878 bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
879 {
880 float sz = GetFrameHeight();
881 return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);
882 }
883
884 // Button to close a window
885 bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)
886 {
887 ImGuiContext& g = *GImGui;
888 ImGuiWindow* window = g.CurrentWindow;
889
890 // 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)
891 // 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?
892 const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
893 ImRect bb_interact = bb;
894 const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea();
895 if (area_to_visible_ratio < 1.5f)
896 bb_interact.Expand(ImTrunc(bb_interact.GetSize() * -0.25f));
897
898 // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window.
899 // (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).
900 bool is_clipped = !ItemAdd(bb_interact, id);
901
902 bool hovered, held;
903 bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held);
904 if (is_clipped)
905 return pressed;
906
907 // Render
908 ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
909 if (hovered)
910 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
911 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
912 const ImU32 cross_col = GetColorU32(ImGuiCol_Text);
913 const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
914 const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
915 const float cross_thickness = 1.0f; // FIXME-DPI
916 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness);
917 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness);
918
919 return pressed;
920 }
921
922 // The Collapse button also functions as a Dock Menu button.
923 bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node)
924 {
925 ImGuiContext& g = *GImGui;
926 ImGuiWindow* window = g.CurrentWindow;
927
928 ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
929 bool is_clipped = !ItemAdd(bb, id);
930 bool hovered, held;
931 bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
932 if (is_clipped)
933 return pressed;
934
935 // Render
936 //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed);
937 ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
938 ImU32 text_col = GetColorU32(ImGuiCol_Text);
939 if (hovered || held)
940 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
941 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
942
943 if (dock_node)
944 RenderArrowDockMenu(window->DrawList, bb.Min, g.FontSize, text_col);
945 else
946 RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
947
948 // Switch to moving the window after mouse is moved beyond the initial drag threshold
949 if (IsItemActive() && IsMouseDragging(0))
950 StartMouseMovingWindowOrNode(window, dock_node, true); // Undock from window/collapse menu button
951
952 return pressed;
953 }
954
955 ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
956 {
957 return window->GetID(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
958 }
959
960 // Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
961 ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
962 {
963 ImGuiContext& g = *GImGui;
964 const ImRect outer_rect = window->Rect();
965 const ImRect inner_rect = window->InnerRect;
966 const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
967 IM_ASSERT(scrollbar_size >= 0.0f);
968 const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f);
969 const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 0.0f;
970 if (axis == ImGuiAxis_X)
971 return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size);
972 else
973 return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y + border_top, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size);
974 }
975
976 void ImGui::Scrollbar(ImGuiAxis axis)
977 {
978 ImGuiContext& g = *GImGui;
979 ImGuiWindow* window = g.CurrentWindow;
980 const ImGuiID id = GetWindowScrollbarID(window, axis);
981
982 // Calculate scrollbar bounding box
983 ImRect bb = GetWindowScrollbarRect(window, axis);
984 ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone;
985 if (axis == ImGuiAxis_X)
986 {
987 rounding_corners |= ImDrawFlags_RoundCornersBottomLeft;
988 if (!window->ScrollbarY)
989 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
990 }
991 else
992 {
993 if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))
994 rounding_corners |= ImDrawFlags_RoundCornersTopRight;
995 if (!window->ScrollbarX)
996 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
997 }
998 float size_visible = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];
999 float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;
1000 ImS64 scroll = (ImS64)window->Scroll[axis];
1001 ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_visible, (ImS64)size_contents, rounding_corners);
1002 window->Scroll[axis] = (float)scroll;
1003 }
1004
1005 // Vertical/Horizontal scrollbar
1006 // The entire piece of code below is rather confusing because:
1007 // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
1008 // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
1009 // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
1010 // Still, the code should probably be made simpler..
1011 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)
1012 {
1013 ImGuiContext& g = *GImGui;
1014 ImGuiWindow* window = g.CurrentWindow;
1015 if (window->SkipItems)
1016 return false;
1017
1018 const float bb_frame_width = bb_frame.GetWidth();
1019 const float bb_frame_height = bb_frame.GetHeight();
1020 if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
1021 return false;
1022
1023 // 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)
1024 float alpha = 1.0f;
1025 if ((axis == ImGuiAxis_Y) && bb_frame_height < bb_frame_width)
1026 alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0f, 1.0f));
1027 if (alpha <= 0.0f)
1028 return false;
1029
1030 const ImGuiStyle& style = g.Style;
1031 const bool allow_interaction = (alpha >= 1.0f);
1032
1033 ImRect bb = bb_frame;
1034 float padding = IM_TRUNC(ImMin(style.ScrollbarPadding, ImMin(bb_frame_width, bb_frame_height) * 0.5f));
1035 bb.Expand(-padding);
1036
1037 // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
1038 const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
1039
1040 // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
1041 // But we maintain a minimum size in pixel to allow for the user to still aim inside.
1042 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.
1043 const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1);
1044 const float grab_h_minsize = ImMin(bb.GetSize()[axis], style.GrabMinSize);
1045 const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), grab_h_minsize, scrollbar_size_v);
1046 const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
1047
1048 // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
1049 bool held = false;
1050 bool hovered = false;
1051 ItemAdd(bb_frame, id, NULL, ImGuiItemFlags_NoNav);
1052 ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
1053
1054 const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_visible_v);
1055 float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
1056 float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space
1057 if (held && allow_interaction && grab_h_norm < 1.0f)
1058 {
1059 const float scrollbar_pos_v = bb.Min[axis];
1060 const float mouse_pos_v = g.IO.MousePos[axis];
1061
1062 // Click position in scrollbar normalized space (0.0f->1.0f)
1063 const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
1064
1065 const int held_dir = (clicked_v_norm < grab_v_norm) ? -1 : (clicked_v_norm > grab_v_norm + grab_h_norm) ? +1 : 0;
1066 if (g.ActiveIdIsJustActivated)
1067 {
1068 // On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab
1069 const bool scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false || g.IO.KeyShift || held_dir == 0);
1070 g.ScrollbarSeekMode = scroll_to_clicked_location ? 0 : (short)held_dir;
1071 g.ScrollbarClickDeltaToGrabCenter = (held_dir == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
1072 }
1073
1074 // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
1075 // 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
1076 if (g.ScrollbarSeekMode == 0)
1077 {
1078 // Absolute seeking
1079 const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
1080 *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max);
1081 }
1082 else
1083 {
1084 // Page by page
1085 if (IsMouseClicked(ImGuiMouseButton_Left, ImGuiInputFlags_Repeat) && held_dir == g.ScrollbarSeekMode)
1086 {
1087 float page_dir = (g.ScrollbarSeekMode > 0.0f) ? +1.0f : -1.0f;
1088 *p_scroll_v = ImClamp(*p_scroll_v + (ImS64)(page_dir * size_visible_v), (ImS64)0, scroll_max);
1089 }
1090 }
1091
1092 // Update values for rendering
1093 scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
1094 grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
1095
1096 // Update distance to grab now that we have seek'ed and saturated
1097 //if (seek_absolute)
1098 // g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
1099 }
1100
1101 // Render
1102 const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
1103 const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
1104 window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags);
1105 ImRect grab_rect;
1106 if (axis == ImGuiAxis_X)
1107 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);
1108 else
1109 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);
1110 window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
1111
1112 return held;
1113 }
1114
1115 // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
1116 // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
1117 void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
1118 {
1119 ImGuiContext& g = *GImGui;
1120 ImGuiWindow* window = GetCurrentWindow();
1121 if (window->SkipItems)
1122 return;
1123
1124 const ImVec2 padding(g.Style.ImageBorderSize, g.Style.ImageBorderSize);
1125 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1126 ItemSize(bb);
1127 if (!ItemAdd(bb, 0))
1128 return;
1129
1130 // Render
1131 if (g.Style.ImageBorderSize > 0.0f)
1132 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize);
1133 if (bg_col.w > 0.0f)
1134 window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
1135 window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1136 }
1137
1138 void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1)
1139 {
1140 ImageWithBg(tex_ref, image_size, uv0, uv1);
1141 }
1142
1143 // 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238)
1144 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1145 void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
1146 {
1147 ImGuiContext& g = *GImGui;
1148 PushStyleVar(ImGuiStyleVar_ImageBorderSize, (border_col.w > 0.0f) ? ImMax(1.0f, g.Style.ImageBorderSize) : 0.0f); // Preserve legacy behavior where border is always visible when border_col's Alpha is >0.0f
1149 PushStyleColor(ImGuiCol_Border, border_col);
1150 ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col);
1151 PopStyleColor();
1152 PopStyleVar();
1153 }
1154 #endif
1155
1156 bool ImGui::ImageButtonEx(ImGuiID id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
1157 {
1158 ImGuiContext& g = *GImGui;
1159 ImGuiWindow* window = GetCurrentWindow();
1160 if (window->SkipItems)
1161 return false;
1162
1163 const ImVec2 padding = g.Style.FramePadding;
1164 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1165 ItemSize(bb);
1166 if (!ItemAdd(bb, id))
1167 return false;
1168
1169 bool hovered, held;
1170 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
1171
1172 // Render
1173 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1174 RenderNavCursor(bb, id);
1175 RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
1176 if (bg_col.w > 0.0f)
1177 window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
1178 window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1179
1180 return pressed;
1181 }
1182
1183 // - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
1184 // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design?
1185 bool ImGui::ImageButton(const char* str_id, ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
1186 {
1187 ImGuiContext& g = *GImGui;
1188 ImGuiWindow* window = g.CurrentWindow;
1189 if (window->SkipItems)
1190 return false;
1191
1192 return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col);
1193 }
1194
1195 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1196 // Legacy API obsoleted in 1.89. Two differences with new ImageButton()
1197 // - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
1198 // - new ImageButton() requires an explicit 'const char* str_id'
1199 // - old ImageButton() had frame_padding' override argument.
1200 // - new ImageButton() always use style.FramePadding.
1201 /*
1202 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)
1203 {
1204 // Default to using texture ID as ID. User can still push string/integer prefixes.
1205 PushID((ImTextureID)(intptr_t)user_texture_id);
1206 if (frame_padding >= 0)
1207 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding));
1208 bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col);
1209 if (frame_padding >= 0)
1210 PopStyleVar();
1211 PopID();
1212 return ret;
1213 }
1214 */
1215 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1216
1217 bool ImGui::Checkbox(const char* label, bool* v)
1218 {
1219 ImGuiWindow* window = GetCurrentWindow();
1220 if (window->SkipItems)
1221 return false;
1222
1223 ImGuiContext& g = *GImGui;
1224 const ImGuiStyle& style = g.Style;
1225 const ImGuiID id = window->GetID(label);
1226 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1227
1228 const float square_sz = GetFrameHeight();
1229 const ImVec2 pos = window->DC.CursorPos;
1230 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));
1231 ItemSize(total_bb, style.FramePadding.y);
1232 const bool is_visible = ItemAdd(total_bb, id);
1233 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
1234 if (!is_visible)
1235 if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support
1236 {
1237 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1238 return false;
1239 }
1240
1241 // Range-Selection/Multi-selection support (header)
1242 bool checked = *v;
1243 if (is_multi_select)
1244 MultiSelectItemHeader(id, &checked, NULL);
1245
1246 bool hovered, held;
1247 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1248
1249 // Range-Selection/Multi-selection support (footer)
1250 if (is_multi_select)
1251 MultiSelectItemFooter(id, &checked, &pressed);
1252 else if (pressed)
1253 checked = !checked;
1254
1255 if (*v != checked)
1256 {
1257 *v = checked;
1258 pressed = true; // return value
1259 MarkItemEdited(id);
1260 }
1261
1262 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1263 const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
1264 if (is_visible)
1265 {
1266 RenderNavCursor(total_bb, id);
1267 RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
1268 ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
1269 if (mixed_value)
1270 {
1271 // Undocumented tristate/mixed/indeterminate checkbox (#2644)
1272 // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox)
1273 ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)));
1274 window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
1275 }
1276 else if (*v)
1277 {
1278 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1279 RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f);
1280 }
1281 }
1282 const ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1283 if (g.LogEnabled)
1284 LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]");
1285 if (is_visible && label_size.x > 0.0f)
1286 RenderText(label_pos, label);
1287
1288 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1289 return pressed;
1290 }
1291
1292 template<typename T>
1293 bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value)
1294 {
1295 bool all_on = (*flags & flags_value) == flags_value;
1296 bool any_on = (*flags & flags_value) != 0;
1297 bool pressed;
1298 if (!all_on && any_on)
1299 {
1300 ImGuiContext& g = *GImGui;
1301 g.NextItemData.ItemFlags |= ImGuiItemFlags_MixedValue;
1302 pressed = Checkbox(label, &all_on);
1303 }
1304 else
1305 {
1306 pressed = Checkbox(label, &all_on);
1307
1308 }
1309 if (pressed)
1310 {
1311 if (all_on)
1312 *flags |= flags_value;
1313 else
1314 *flags &= ~flags_value;
1315 }
1316 return pressed;
1317 }
1318
1319 bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value)
1320 {
1321 return CheckboxFlagsT(label, flags, flags_value);
1322 }
1323
1324 bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
1325 {
1326 return CheckboxFlagsT(label, flags, flags_value);
1327 }
1328
1329 bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value)
1330 {
1331 return CheckboxFlagsT(label, flags, flags_value);
1332 }
1333
1334 bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value)
1335 {
1336 return CheckboxFlagsT(label, flags, flags_value);
1337 }
1338
1339 bool ImGui::RadioButton(const char* label, bool active)
1340 {
1341 ImGuiWindow* window = GetCurrentWindow();
1342 if (window->SkipItems)
1343 return false;
1344
1345 ImGuiContext& g = *GImGui;
1346 const ImGuiStyle& style = g.Style;
1347 const ImGuiID id = window->GetID(label);
1348 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1349
1350 const float square_sz = GetFrameHeight();
1351 const ImVec2 pos = window->DC.CursorPos;
1352 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1353 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));
1354 ItemSize(total_bb, style.FramePadding.y);
1355 if (!ItemAdd(total_bb, id))
1356 return false;
1357
1358 ImVec2 center = check_bb.GetCenter();
1359 center.x = IM_ROUND(center.x);
1360 center.y = IM_ROUND(center.y);
1361 const float radius = (square_sz - 1.0f) * 0.5f;
1362
1363 bool hovered, held;
1364 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1365 if (pressed)
1366 MarkItemEdited(id);
1367
1368 RenderNavCursor(total_bb, id);
1369 const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius);
1370 window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), num_segment);
1371 if (active)
1372 {
1373 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1374 window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark));
1375 }
1376
1377 if (style.FrameBorderSize > 0.0f)
1378 {
1379 window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), num_segment, style.FrameBorderSize);
1380 window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), num_segment, style.FrameBorderSize);
1381 }
1382
1383 ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1384 if (g.LogEnabled)
1385 LogRenderedText(&label_pos, active ? "(x)" : "( )");
1386 if (label_size.x > 0.0f)
1387 RenderText(label_pos, label);
1388
1389 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1390 return pressed;
1391 }
1392
1393 // 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..
1394 bool ImGui::RadioButton(const char* label, int* v, int v_button)
1395 {
1396 const bool pressed = RadioButton(label, *v == v_button);
1397 if (pressed)
1398 *v = v_button;
1399 return pressed;
1400 }
1401
1402 // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
1403 void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
1404 {
1405 ImGuiWindow* window = GetCurrentWindow();
1406 if (window->SkipItems)
1407 return;
1408
1409 ImGuiContext& g = *GImGui;
1410 const ImGuiStyle& style = g.Style;
1411
1412 ImVec2 pos = window->DC.CursorPos;
1413 ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f);
1414 ImRect bb(pos, pos + size);
1415 ItemSize(size, style.FramePadding.y);
1416 if (!ItemAdd(bb, 0))
1417 return;
1418
1419 // Fraction < 0.0f will display an indeterminate progress bar animation
1420 // The value must be animated along with time, so e.g. passing '-1.0f * ImGui::GetTime()' as fraction works.
1421 const bool is_indeterminate = (fraction < 0.0f);
1422 if (!is_indeterminate)
1423 fraction = ImSaturate(fraction);
1424
1425 // Out of courtesy we accept a NaN fraction without crashing
1426 float fill_n0 = 0.0f;
1427 float fill_n1 = (fraction == fraction) ? fraction : 0.0f;
1428
1429 if (is_indeterminate)
1430 {
1431 const float fill_width_n = 0.2f;
1432 fill_n0 = ImFmod(-fraction, 1.0f) * (1.0f + fill_width_n) - fill_width_n;
1433 fill_n1 = ImSaturate(fill_n0 + fill_width_n);
1434 fill_n0 = ImSaturate(fill_n0);
1435 }
1436
1437 // Render
1438 RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
1439 bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
1440 RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_n0, fill_n1, style.FrameRounding);
1441
1442 // Default displaying the fraction as percentage string, but user can override it
1443 // Don't display text for indeterminate bars by default
1444 char overlay_buf[32];
1445 if (!is_indeterminate || overlay != NULL)
1446 {
1447 if (!overlay)
1448 {
1449 ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f);
1450 overlay = overlay_buf;
1451 }
1452
1453 ImVec2 overlay_size = CalcTextSize(overlay, NULL);
1454 if (overlay_size.x > 0.0f)
1455 {
1456 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;
1457 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);
1458 }
1459 }
1460 }
1461
1462 void ImGui::Bullet()
1463 {
1464 ImGuiWindow* window = GetCurrentWindow();
1465 if (window->SkipItems)
1466 return;
1467
1468 ImGuiContext& g = *GImGui;
1469 const ImGuiStyle& style = g.Style;
1470 const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize);
1471 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
1472 ItemSize(bb);
1473 if (!ItemAdd(bb, 0))
1474 {
1475 SameLine(0, style.FramePadding.x * 2);
1476 return;
1477 }
1478
1479 // Render and stay on same line
1480 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1481 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col);
1482 SameLine(0, style.FramePadding.x * 2.0f);
1483 }
1484
1485 // This is provided as a convenience for being an often requested feature.
1486 // FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system.
1487 // Because of this we currently don't provide many styling options for this widget
1488 // (e.g. hovered/active colors are automatically inferred from a single color).
1489 bool ImGui::TextLink(const char* label)
1490 {
1491 ImGuiWindow* window = GetCurrentWindow();
1492 if (window->SkipItems)
1493 return false;
1494
1495 ImGuiContext& g = *GImGui;
1496 const ImGuiID id = window->GetID(label);
1497 const char* label_end = FindRenderedTextEnd(label);
1498
1499 ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
1500 ImVec2 size = CalcTextSize(label, label_end, true);
1501 ImRect bb(pos, pos + size);
1502 ItemSize(size, 0.0f);
1503 if (!ItemAdd(bb, id))
1504 return false;
1505
1506 bool hovered, held;
1507 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
1508 RenderNavCursor(bb, id);
1509
1510 if (hovered)
1511 SetMouseCursor(ImGuiMouseCursor_Hand);
1512
1513 ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink];
1514 ImVec4 line_colf = text_colf;
1515 {
1516 // FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets,
1517 // as we are currently experimenting/planning a different styling system.
1518 float h, s, v;
1519 ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z, h, s, v);
1520 if (held || hovered)
1521 {
1522 v = ImSaturate(v + (held ? 0.4f : 0.3f));
1523 h = ImFmod(h + 0.02f, 1.0f);
1524 }
1525 ColorConvertHSVtoRGB(h, s, v, text_colf.x, text_colf.y, text_colf.z);
1526 v = ImSaturate(v - 0.20f);
1527 ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z);
1528 }
1529
1530 float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f);
1531 window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI
1532
1533 PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf));
1534 RenderText(bb.Min, label, label_end);
1535 PopStyleColor();
1536
1537 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1538 return pressed;
1539 }
1540
1541 bool ImGui::TextLinkOpenURL(const char* label, const char* url)
1542 {
1543 ImGuiContext& g = *GImGui;
1544 if (url == NULL)
1545 url = label;
1546 bool pressed = TextLink(label);
1547 if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL)
1548 g.PlatformIO.Platform_OpenInShellFn(&g, url);
1549 SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label
1550 if (BeginPopupContextItem())
1551 {
1552 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink)))
1553 SetClipboardText(url);
1554 EndPopup();
1555 }
1556 return pressed;
1557 }
1558
1559 //-------------------------------------------------------------------------
1560 // [SECTION] Widgets: Low-level Layout helpers
1561 //-------------------------------------------------------------------------
1562 // - Spacing()
1563 // - Dummy()
1564 // - NewLine()
1565 // - AlignTextToFramePadding()
1566 // - SeparatorEx() [Internal]
1567 // - Separator()
1568 // - SplitterBehavior() [Internal]
1569 // - ShrinkWidths() [Internal]
1570 //-------------------------------------------------------------------------
1571
1572 void ImGui::Spacing()
1573 {
1574 ImGuiWindow* window = GetCurrentWindow();
1575 if (window->SkipItems)
1576 return;
1577 ItemSize(ImVec2(0, 0));
1578 }
1579
1580 void ImGui::Dummy(const ImVec2& size)
1581 {
1582 ImGuiWindow* window = GetCurrentWindow();
1583 if (window->SkipItems)
1584 return;
1585
1586 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
1587 ItemSize(size);
1588 ItemAdd(bb, 0);
1589 }
1590
1591 void ImGui::NewLine()
1592 {
1593 ImGuiWindow* window = GetCurrentWindow();
1594 if (window->SkipItems)
1595 return;
1596
1597 ImGuiContext& g = *GImGui;
1598 const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
1599 window->DC.LayoutType = ImGuiLayoutType_Vertical;
1600 window->DC.IsSameLine = false;
1601 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.
1602 ItemSize(ImVec2(0, 0));
1603 else
1604 ItemSize(ImVec2(0.0f, g.FontSize));
1605 window->DC.LayoutType = backup_layout_type;
1606 }
1607
1608 void ImGui::AlignTextToFramePadding()
1609 {
1610 ImGuiWindow* window = GetCurrentWindow();
1611 if (window->SkipItems)
1612 return;
1613
1614 ImGuiContext& g = *GImGui;
1615 window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
1616 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
1617 }
1618
1619 // Horizontal/vertical separating line
1620 // FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues.
1621 // Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are.
1622 void ImGui::SeparatorEx(ImGuiSeparatorFlags flags, float thickness)
1623 {
1624 ImGuiWindow* window = GetCurrentWindow();
1625 if (window->SkipItems)
1626 return;
1627
1628 ImGuiContext& g = *GImGui;
1629 IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
1630 IM_ASSERT(thickness > 0.0f);
1631
1632 if (flags & ImGuiSeparatorFlags_Vertical)
1633 {
1634 // Vertical separator, for menu bars (use current line height).
1635 float y1 = window->DC.CursorPos.y;
1636 float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;
1637 const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness, y2));
1638 ItemSize(ImVec2(thickness, 0.0f));
1639 if (!ItemAdd(bb, 0))
1640 return;
1641
1642 // Draw
1643 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1644 if (g.LogEnabled)
1645 LogText(" |");
1646 }
1647 else if (flags & ImGuiSeparatorFlags_Horizontal)
1648 {
1649 // Horizontal Separator
1650 float x1 = window->DC.CursorPos.x;
1651 float x2 = window->WorkRect.Max.x;
1652
1653 // Preserve legacy behavior inside Columns()
1654 // Before Tables API happened, we relied on Separator() to span all columns of a Columns() set.
1655 // We currently don't need to provide the same feature for tables because tables naturally have border features.
1656 ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
1657 if (columns)
1658 {
1659 x1 = window->Pos.x + window->DC.Indent.x; // Used to be Pos.x before 2023/10/03
1660 x2 = window->Pos.x + window->Size.x;
1661 PushColumnsBackground();
1662 }
1663
1664 // We don't provide our width to the layout so that it doesn't get feed back into AutoFit
1665 // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell)
1666 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.
1667 const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness));
1668 ItemSize(ImVec2(0.0f, thickness_for_layout));
1669
1670 if (ItemAdd(bb, 0))
1671 {
1672 // Draw
1673 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1674 if (g.LogEnabled)
1675 LogRenderedText(&bb.Min, "--------------------------------\n");
1676
1677 }
1678 if (columns)
1679 {
1680 PopColumnsBackground();
1681 columns->LineMinY = window->DC.CursorPos.y;
1682 }
1683 }
1684 }
1685
1686 void ImGui::Separator()
1687 {
1688 ImGuiContext& g = *GImGui;
1689 ImGuiWindow* window = g.CurrentWindow;
1690 if (window->SkipItems)
1691 return;
1692
1693 // Those flags should eventually be configurable by the user
1694 // FIXME: We cannot g.Style.SeparatorTextBorderSize for thickness as it relates to SeparatorText() which is a decorated separator, not defaulting to 1.0f.
1695 ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
1696
1697 // Only applies to legacy Columns() api as they relied on Separator() a lot.
1698 if (window->DC.CurrentColumns)
1699 flags |= ImGuiSeparatorFlags_SpanAllColumns;
1700
1701 SeparatorEx(flags, 1.0f);
1702 }
1703
1704 void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_w)
1705 {
1706 ImGuiContext& g = *GImGui;
1707 ImGuiWindow* window = g.CurrentWindow;
1708 ImGuiStyle& style = g.Style;
1709
1710 const ImVec2 label_size = CalcTextSize(label, label_end, false);
1711 const ImVec2 pos = window->DC.CursorPos;
1712 const ImVec2 padding = style.SeparatorTextPadding;
1713
1714 const float separator_thickness = style.SeparatorTextBorderSize;
1715 const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness));
1716 const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y));
1717 const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f));
1718 ItemSize(min_size, text_baseline_y);
1719 if (!ItemAdd(bb, id))
1720 return;
1721
1722 const float sep1_x1 = pos.x;
1723 const float sep2_x2 = bb.Max.x;
1724 const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.99999f);
1725
1726 const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f);
1727 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
1728
1729 // This allows using SameLine() to position something in the 'extra_w'
1730 window->DC.CursorPosPrevLine.x = label_pos.x + label_size.x;
1731
1732 const ImU32 separator_col = GetColorU32(ImGuiCol_Separator);
1733 if (label_size.x > 0.0f)
1734 {
1735 const float sep1_x2 = label_pos.x - style.ItemSpacing.x;
1736 const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x;
1737 if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f)
1738 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep1_x2, seps_y), separator_col, separator_thickness);
1739 if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f)
1740 window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1741 if (g.LogEnabled)
1742 LogSetNextTextDecoration("---", NULL);
1743 RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size);
1744 }
1745 else
1746 {
1747 if (g.LogEnabled)
1748 LogText("---");
1749 if (separator_thickness > 0.0f)
1750 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1751 }
1752 }
1753
1754 void ImGui::SeparatorText(const char* label)
1755 {
1756 ImGuiWindow* window = GetCurrentWindow();
1757 if (window->SkipItems)
1758 return;
1759
1760 // The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want:
1761 // - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight)
1762 // - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string)
1763 // - because of this we probably can't turn 'const char* label' into 'const char* fmt, ...'
1764 // Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item,
1765 // and then we can turn this into a format function.
1766 SeparatorTextEx(0, label, FindRenderedTextEnd(label), 0.0f);
1767 }
1768
1769 // 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.
1770 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)
1771 {
1772 ImGuiContext& g = *GImGui;
1773 ImGuiWindow* window = g.CurrentWindow;
1774
1775 if (!ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav))
1776 return false;
1777
1778 // FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags_AllowOverlap here is
1779 // to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item.
1780 // Nowadays we would instead want to use SetNextItemAllowOverlap() before the item.
1781 ImGuiButtonFlags button_flags = ImGuiButtonFlags_FlattenChildren;
1782 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1783 button_flags |= ImGuiButtonFlags_AllowOverlap;
1784 #endif
1785
1786 bool hovered, held;
1787 ImRect bb_interact = bb;
1788 bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
1789 ButtonBehavior(bb_interact, id, &hovered, &held, button_flags);
1790 if (hovered)
1791 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb
1792
1793 if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
1794 SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
1795
1796 ImRect bb_render = bb;
1797 if (held)
1798 {
1799 float mouse_delta = (g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min)[axis];
1800
1801 // Minimum pane size
1802 float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
1803 float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
1804 if (mouse_delta < -size_1_maximum_delta)
1805 mouse_delta = -size_1_maximum_delta;
1806 if (mouse_delta > size_2_maximum_delta)
1807 mouse_delta = size_2_maximum_delta;
1808
1809 // Apply resize
1810 if (mouse_delta != 0.0f)
1811 {
1812 *size1 = ImMax(*size1 + mouse_delta, min_size1);
1813 *size2 = ImMax(*size2 - mouse_delta, min_size2);
1814 bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
1815 MarkItemEdited(id);
1816 }
1817 }
1818
1819 // Render at new position
1820 if (bg_col & IM_COL32_A_MASK)
1821 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0f);
1822 const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
1823 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);
1824
1825 return held;
1826 }
1827
1828 static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
1829 {
1830 const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;
1831 const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;
1832 if (int d = (int)(b->Width - a->Width))
1833 return d;
1834 return (b->Index - a->Index);
1835 }
1836
1837 // Shrink excess width from a set of item, by removing width from the larger items first.
1838 // Set items Width to -1.0f to disable shrinking this item.
1839 void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min)
1840 {
1841 if (count == 1)
1842 {
1843 if (items[0].Width >= 0.0f)
1844 items[0].Width = ImMax(items[0].Width - width_excess, width_min);
1845 return;
1846 }
1847 ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last.
1848 int count_same_width = 1;
1849 while (width_excess > 0.001f && count_same_width < count)
1850 {
1851 while (count_same_width < count && items[0].Width <= items[count_same_width].Width)
1852 count_same_width++;
1853 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);
1854 max_width_to_remove_per_item = ImMin(items[0].Width - width_min, max_width_to_remove_per_item);
1855 if (max_width_to_remove_per_item <= 0.0f)
1856 break;
1857 float base_width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);
1858 for (int item_n = 0; item_n < count_same_width; item_n++)
1859 {
1860 float width_to_remove_for_this_item = ImMin(base_width_to_remove_per_item, items[item_n].Width - width_min);
1861 items[item_n].Width -= width_to_remove_for_this_item;
1862 width_excess -= width_to_remove_for_this_item;
1863 }
1864 }
1865
1866 // Round width and redistribute remainder
1867 // 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.
1868 width_excess = 0.0f;
1869 for (int n = 0; n < count; n++)
1870 {
1871 float width_rounded = ImTrunc(items[n].Width);
1872 width_excess += items[n].Width - width_rounded;
1873 items[n].Width = width_rounded;
1874 }
1875 while (width_excess > 0.0f)
1876 for (int n = 0; n < count && width_excess > 0.0f; n++)
1877 {
1878 float width_to_add = ImMin(items[n].InitialWidth - items[n].Width, 1.0f);
1879 items[n].Width += width_to_add;
1880 width_excess -= width_to_add;
1881 }
1882 }
1883
1884 //-------------------------------------------------------------------------
1885 // [SECTION] Widgets: ComboBox
1886 //-------------------------------------------------------------------------
1887 // - CalcMaxPopupHeightFromItemCount() [Internal]
1888 // - BeginCombo()
1889 // - BeginComboPopup() [Internal]
1890 // - EndCombo()
1891 // - BeginComboPreview() [Internal]
1892 // - EndComboPreview() [Internal]
1893 // - Combo()
1894 //-------------------------------------------------------------------------
1895
1896 static float CalcMaxPopupHeightFromItemCount(int items_count)
1897 {
1898 ImGuiContext& g = *GImGui;
1899 if (items_count <= 0)
1900 return FLT_MAX;
1901 return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
1902 }
1903
1904 bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
1905 {
1906 ImGuiContext& g = *GImGui;
1907 ImGuiWindow* window = GetCurrentWindow();
1908
1909 ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.HasFlags;
1910 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
1911 if (window->SkipItems)
1912 return false;
1913
1914 const ImGuiStyle& style = g.Style;
1915 const ImGuiID id = window->GetID(label);
1916 IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
1917 if (flags & ImGuiComboFlags_WidthFitPreview)
1918 IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0);
1919
1920 const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
1921 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1922 const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && (preview_value != NULL)) ? CalcTextSize(preview_value, NULL, true).x : 0.0f;
1923 const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : ((flags & ImGuiComboFlags_WidthFitPreview) ? (arrow_size + preview_width + style.FramePadding.x * 2.0f) : CalcItemWidth());
1924 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
1925 const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
1926 ItemSize(total_bb, style.FramePadding.y);
1927 if (!ItemAdd(total_bb, id, &bb))
1928 return false;
1929
1930 // Open on click
1931 bool hovered, held;
1932 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
1933 const ImGuiID popup_id = ImHashStr("##ComboPopup", 0, id);
1934 bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None);
1935 if (pressed && !popup_open)
1936 {
1937 OpenPopupEx(popup_id, ImGuiPopupFlags_None);
1938 popup_open = true;
1939 }
1940
1941 // Render shape
1942 const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
1943 const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size);
1944 RenderNavCursor(bb, id);
1945 if (!(flags & ImGuiComboFlags_NoPreview))
1946 window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft);
1947 if (!(flags & ImGuiComboFlags_NoArrowButton))
1948 {
1949 ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1950 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1951 window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight);
1952 if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x)
1953 RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);
1954 }
1955 RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding);
1956
1957 // Custom preview
1958 if (flags & ImGuiComboFlags_CustomPreview)
1959 {
1960 g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y);
1961 IM_ASSERT(preview_value == NULL || preview_value[0] == 0);
1962 preview_value = NULL;
1963 }
1964
1965 // Render preview and label
1966 if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
1967 {
1968 if (g.LogEnabled)
1969 LogSetNextTextDecoration("{", "}");
1970 RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL);
1971 }
1972 if (label_size.x > 0)
1973 RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label);
1974
1975 if (!popup_open)
1976 return false;
1977
1978 g.NextWindowData.HasFlags = backup_next_window_data_flags;
1979 return BeginComboPopup(popup_id, bb, flags);
1980 }
1981
1982 bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags)
1983 {
1984 ImGuiContext& g = *GImGui;
1985 if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None))
1986 {
1987 g.NextWindowData.ClearFlags();
1988 return false;
1989 }
1990
1991 // Set popup size
1992 float w = bb.GetWidth();
1993 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
1994 {
1995 g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
1996 }
1997 else
1998 {
1999 if ((flags & ImGuiComboFlags_HeightMask_) == 0)
2000 flags |= ImGuiComboFlags_HeightRegular;
2001 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
2002 int popup_max_height_in_items = -1;
2003 if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
2004 else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
2005 else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
2006 ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX);
2007 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size
2008 constraint_min.x = w;
2009 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f)
2010 constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
2011 SetNextWindowSizeConstraints(constraint_min, constraint_max);
2012 }
2013
2014 // This is essentially a specialized version of BeginPopupEx()
2015 char name[16];
2016 ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth
2017
2018 // Set position given a custom constraint (peak into expected window size so we can position it)
2019 // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function?
2020 // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()?
2021 if (ImGuiWindow* popup_window = FindWindowByName(name))
2022 if (popup_window->WasActive)
2023 {
2024 // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.
2025 ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window);
2026 popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = "Below, Toward Left", Down = "Below, Toward Right (default)"
2027 ImRect r_outer = GetPopupAllowedExtentRect(popup_window);
2028 ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox);
2029 SetNextWindowPos(pos);
2030 }
2031
2032 // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()
2033 ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove;
2034 PushStyleVarX(ImGuiStyleVar_WindowPadding, g.Style.FramePadding.x); // Horizontally align ourselves with the framed text
2035 bool ret = Begin(name, NULL, window_flags);
2036 PopStyleVar();
2037 if (!ret)
2038 {
2039 EndPopup();
2040 if (!g.IO.ConfigDebugBeginReturnValueOnce && !g.IO.ConfigDebugBeginReturnValueLoop) // Begin may only return false with those debug tools activated.
2041 IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
2042 return false;
2043 }
2044 g.BeginComboDepth++;
2045 return true;
2046 }
2047
2048 void ImGui::EndCombo()
2049 {
2050 ImGuiContext& g = *GImGui;
2051 EndPopup();
2052 g.BeginComboDepth--;
2053 }
2054
2055 // Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements
2056 // (Experimental, see GitHub issues: #1658, #4168)
2057 bool ImGui::BeginComboPreview()
2058 {
2059 ImGuiContext& g = *GImGui;
2060 ImGuiWindow* window = g.CurrentWindow;
2061 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
2062
2063 if (window->SkipItems || !(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible))
2064 return false;
2065 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?
2066 if (!window->ClipRect.Overlaps(preview_data->PreviewRect)) // Narrower test (optional)
2067 return false;
2068
2069 // FIXME: This could be contained in a PushWorkRect() api
2070 preview_data->BackupCursorPos = window->DC.CursorPos;
2071 preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos;
2072 preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
2073 preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
2074 preview_data->BackupLayout = window->DC.LayoutType;
2075 window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding;
2076 window->DC.CursorMaxPos = window->DC.CursorPos;
2077 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
2078 window->DC.IsSameLine = false;
2079 PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true);
2080
2081 return true;
2082 }
2083
2084 void ImGui::EndComboPreview()
2085 {
2086 ImGuiContext& g = *GImGui;
2087 ImGuiWindow* window = g.CurrentWindow;
2088 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
2089
2090 // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future
2091 ImDrawList* draw_list = window->DrawList;
2092 if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y)
2093 if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command
2094 {
2095 draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect;
2096 draw_list->_TryMergeDrawCmds();
2097 }
2098 PopClipRect();
2099 window->DC.CursorPos = preview_data->BackupCursorPos;
2100 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos);
2101 window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine;
2102 window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset;
2103 window->DC.LayoutType = preview_data->BackupLayout;
2104 window->DC.IsSameLine = false;
2105 preview_data->PreviewRect = ImRect();
2106 }
2107
2108 // Getter for the old Combo() API: const char*[]
2109 static const char* Items_ArrayGetter(void* data, int idx)
2110 {
2111 const char* const* items = (const char* const*)data;
2112 return items[idx];
2113 }
2114
2115 // Getter for the old Combo() API: "item1\0item2\0item3\0"
2116 static const char* Items_SingleStringGetter(void* data, int idx)
2117 {
2118 const char* items_separated_by_zeros = (const char*)data;
2119 int items_count = 0;
2120 const char* p = items_separated_by_zeros;
2121 while (*p)
2122 {
2123 if (idx == items_count)
2124 break;
2125 p += ImStrlen(p) + 1;
2126 items_count++;
2127 }
2128 return *p ? p : NULL;
2129 }
2130
2131 // Old API, prefer using BeginCombo() nowadays if you can.
2132 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)
2133 {
2134 ImGuiContext& g = *GImGui;
2135
2136 // Call the getter to obtain the preview string which is a parameter to BeginCombo()
2137 const char* preview_value = NULL;
2138 if (*current_item >= 0 && *current_item < items_count)
2139 preview_value = getter(user_data, *current_item);
2140
2141 // 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.
2142 if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint))
2143 SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
2144
2145 if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
2146 return false;
2147
2148 // Display items
2149 bool value_changed = false;
2150 ImGuiListClipper clipper;
2151 clipper.Begin(items_count);
2152 clipper.IncludeItemByIndex(*current_item);
2153 while (clipper.Step())
2154 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
2155 {
2156 const char* item_text = getter(user_data, i);
2157 if (item_text == NULL)
2158 item_text = "*Unknown item*";
2159
2160 PushID(i);
2161 const bool item_selected = (i == *current_item);
2162 if (Selectable(item_text, item_selected) && *current_item != i)
2163 {
2164 value_changed = true;
2165 *current_item = i;
2166 }
2167 if (item_selected)
2168 SetItemDefaultFocus();
2169 PopID();
2170 }
2171
2172 EndCombo();
2173 if (value_changed)
2174 MarkItemEdited(g.LastItemData.ID);
2175
2176 return value_changed;
2177 }
2178
2179 // Combo box helper allowing to pass an array of strings.
2180 bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
2181 {
2182 const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
2183 return value_changed;
2184 }
2185
2186 // Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
2187 bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
2188 {
2189 int items_count = 0;
2190 const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
2191 while (*p)
2192 {
2193 p += ImStrlen(p) + 1;
2194 items_count++;
2195 }
2196 bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
2197 return value_changed;
2198 }
2199
2200 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2201
2202 struct ImGuiGetNameFromIndexOldToNewCallbackData { void* UserData; bool (*OldCallback)(void*, int, const char**); };
2203 static const char* ImGuiGetNameFromIndexOldToNewCallback(void* user_data, int idx)
2204 {
2205 ImGuiGetNameFromIndexOldToNewCallbackData* data = (ImGuiGetNameFromIndexOldToNewCallbackData*)user_data;
2206 const char* s = NULL;
2207 data->OldCallback(data->UserData, idx, &s);
2208 return s;
2209 }
2210
2211 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)
2212 {
2213 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2214 return ListBox(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, height_in_items);
2215 }
2216 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)
2217 {
2218 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2219 return Combo(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, popup_max_height_in_items);
2220 }
2221
2222 #endif
2223
2224 //-------------------------------------------------------------------------
2225 // [SECTION] Data Type and Data Formatting Helpers [Internal]
2226 //-------------------------------------------------------------------------
2227 // - DataTypeGetInfo()
2228 // - DataTypeFormatString()
2229 // - DataTypeApplyOp()
2230 // - DataTypeApplyFromText()
2231 // - DataTypeCompare()
2232 // - DataTypeClamp()
2233 // - GetMinimumStepAtDecimalPrecision
2234 // - RoundScalarWithFormat<>()
2235 //-------------------------------------------------------------------------
2236
2237 static const ImGuiDataTypeInfo GDataTypeInfo[] =
2238 {
2239 { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8
2240 { sizeof(unsigned char), "U8", "%u", "%u" },
2241 { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16
2242 { sizeof(unsigned short), "U16", "%u", "%u" },
2243 { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32
2244 { sizeof(unsigned int), "U32", "%u", "%u" },
2245 #ifdef _MSC_VER
2246 { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64
2247 { sizeof(ImU64), "U64", "%I64u","%I64u" },
2248 #else
2249 { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64
2250 { sizeof(ImU64), "U64", "%llu", "%llu" },
2251 #endif
2252 { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
2253 { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
2254 { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool
2255 { 0, "char*","%s", "%s" }, // ImGuiDataType_String
2256 };
2257 IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
2258
2259 const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)
2260 {
2261 IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
2262 return &GDataTypeInfo[data_type];
2263 }
2264
2265 int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format)
2266 {
2267 // Signedness doesn't matter when pushing integer arguments
2268 if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
2269 return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data);
2270 if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
2271 return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data);
2272 if (data_type == ImGuiDataType_Float)
2273 return ImFormatString(buf, buf_size, format, *(const float*)p_data);
2274 if (data_type == ImGuiDataType_Double)
2275 return ImFormatString(buf, buf_size, format, *(const double*)p_data);
2276 if (data_type == ImGuiDataType_S8)
2277 return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data);
2278 if (data_type == ImGuiDataType_U8)
2279 return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data);
2280 if (data_type == ImGuiDataType_S16)
2281 return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data);
2282 if (data_type == ImGuiDataType_U16)
2283 return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data);
2284 IM_ASSERT(0);
2285 return 0;
2286 }
2287
2288 void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2)
2289 {
2290 IM_ASSERT(op == '+' || op == '-');
2291 switch (data_type)
2292 {
2293 case ImGuiDataType_S8:
2294 if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2295 if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2296 return;
2297 case ImGuiDataType_U8:
2298 if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2299 if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2300 return;
2301 case ImGuiDataType_S16:
2302 if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2303 if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2304 return;
2305 case ImGuiDataType_U16:
2306 if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2307 if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2308 return;
2309 case ImGuiDataType_S32:
2310 if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2311 if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2312 return;
2313 case ImGuiDataType_U32:
2314 if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2315 if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2316 return;
2317 case ImGuiDataType_S64:
2318 if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2319 if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2320 return;
2321 case ImGuiDataType_U64:
2322 if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2323 if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2324 return;
2325 case ImGuiDataType_Float:
2326 if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
2327 if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
2328 return;
2329 case ImGuiDataType_Double:
2330 if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
2331 if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
2332 return;
2333 case ImGuiDataType_COUNT: break;
2334 }
2335 IM_ASSERT(0);
2336 }
2337
2338 // User can input math operators (e.g. +100) to edit a numerical values.
2339 // NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
2340 bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty)
2341 {
2342 // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
2343 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
2344 ImGuiDataTypeStorage data_backup;
2345 memcpy(&data_backup, p_data, type_info->Size);
2346
2347 while (ImCharIsBlankA(*buf))
2348 buf++;
2349 if (!buf[0])
2350 {
2351 if (p_data_when_empty != NULL)
2352 {
2353 memcpy(p_data, p_data_when_empty, type_info->Size);
2354 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2355 }
2356 return false;
2357 }
2358
2359 // Sanitize format
2360 // - 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
2361 // - In theory could treat empty format as using default, but this would only cover rare/bizarre case of using InputScalar() + integer + format string without %.
2362 char format_sanitized[32];
2363 if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
2364 format = type_info->ScanFmt;
2365 else
2366 format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_ARRAYSIZE(format_sanitized));
2367
2368 // Small types need a 32-bit buffer to receive the result from scanf()
2369 int v32 = 0;
2370 if (sscanf(buf, format, type_info->Size >= 4 ? p_data : &v32) < 1)
2371 return false;
2372 if (type_info->Size < 4)
2373 {
2374 if (data_type == ImGuiDataType_S8)
2375 *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
2376 else if (data_type == ImGuiDataType_U8)
2377 *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
2378 else if (data_type == ImGuiDataType_S16)
2379 *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
2380 else if (data_type == ImGuiDataType_U16)
2381 *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
2382 else
2383 IM_ASSERT(0);
2384 }
2385
2386 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2387 }
2388
2389 template<typename T>
2390 static int DataTypeCompareT(const T* lhs, const T* rhs)
2391 {
2392 if (*lhs < *rhs) return -1;
2393 if (*lhs > *rhs) return +1;
2394 return 0;
2395 }
2396
2397 int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2)
2398 {
2399 switch (data_type)
2400 {
2401 case ImGuiDataType_S8: return DataTypeCompareT<ImS8 >((const ImS8* )arg_1, (const ImS8* )arg_2);
2402 case ImGuiDataType_U8: return DataTypeCompareT<ImU8 >((const ImU8* )arg_1, (const ImU8* )arg_2);
2403 case ImGuiDataType_S16: return DataTypeCompareT<ImS16 >((const ImS16* )arg_1, (const ImS16* )arg_2);
2404 case ImGuiDataType_U16: return DataTypeCompareT<ImU16 >((const ImU16* )arg_1, (const ImU16* )arg_2);
2405 case ImGuiDataType_S32: return DataTypeCompareT<ImS32 >((const ImS32* )arg_1, (const ImS32* )arg_2);
2406 case ImGuiDataType_U32: return DataTypeCompareT<ImU32 >((const ImU32* )arg_1, (const ImU32* )arg_2);
2407 case ImGuiDataType_S64: return DataTypeCompareT<ImS64 >((const ImS64* )arg_1, (const ImS64* )arg_2);
2408 case ImGuiDataType_U64: return DataTypeCompareT<ImU64 >((const ImU64* )arg_1, (const ImU64* )arg_2);
2409 case ImGuiDataType_Float: return DataTypeCompareT<float >((const float* )arg_1, (const float* )arg_2);
2410 case ImGuiDataType_Double: return DataTypeCompareT<double>((const double*)arg_1, (const double*)arg_2);
2411 case ImGuiDataType_COUNT: break;
2412 }
2413 IM_ASSERT(0);
2414 return 0;
2415 }
2416
2417 template<typename T>
2418 static bool DataTypeClampT(T* v, const T* v_min, const T* v_max)
2419 {
2420 // Clamp, both sides are optional, return true if modified
2421 if (v_min && *v < *v_min) { *v = *v_min; return true; }
2422 if (v_max && *v > *v_max) { *v = *v_max; return true; }
2423 return false;
2424 }
2425
2426 bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)
2427 {
2428 switch (data_type)
2429 {
2430 case ImGuiDataType_S8: return DataTypeClampT<ImS8 >((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max);
2431 case ImGuiDataType_U8: return DataTypeClampT<ImU8 >((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max);
2432 case ImGuiDataType_S16: return DataTypeClampT<ImS16 >((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max);
2433 case ImGuiDataType_U16: return DataTypeClampT<ImU16 >((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max);
2434 case ImGuiDataType_S32: return DataTypeClampT<ImS32 >((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max);
2435 case ImGuiDataType_U32: return DataTypeClampT<ImU32 >((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max);
2436 case ImGuiDataType_S64: return DataTypeClampT<ImS64 >((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max);
2437 case ImGuiDataType_U64: return DataTypeClampT<ImU64 >((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max);
2438 case ImGuiDataType_Float: return DataTypeClampT<float >((float* )p_data, (const float* )p_min, (const float* )p_max);
2439 case ImGuiDataType_Double: return DataTypeClampT<double>((double*)p_data, (const double*)p_min, (const double*)p_max);
2440 case ImGuiDataType_COUNT: break;
2441 }
2442 IM_ASSERT(0);
2443 return false;
2444 }
2445
2446 bool ImGui::DataTypeIsZero(ImGuiDataType data_type, const void* p_data)
2447 {
2448 ImGuiContext& g = *GImGui;
2449 return DataTypeCompare(data_type, p_data, &g.DataTypeZeroValue) == 0;
2450 }
2451
2452 static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
2453 {
2454 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 };
2455 if (decimal_precision < 0)
2456 return FLT_MIN;
2457 return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
2458 }
2459
2460 template<typename TYPE>
2461 TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
2462 {
2463 IM_UNUSED(data_type);
2464 IM_ASSERT(data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
2465 const char* fmt_start = ImParseFormatFindStart(format);
2466 if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
2467 return v;
2468
2469 // Sanitize format
2470 char fmt_sanitized[32];
2471 ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized));
2472 fmt_start = fmt_sanitized;
2473
2474 // Format value with our rounding, and read back
2475 char v_str[64];
2476 ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
2477 const char* p = v_str;
2478 while (*p == ' ')
2479 p++;
2480 v = (TYPE)ImAtof(p);
2481
2482 return v;
2483 }
2484
2485 //-------------------------------------------------------------------------
2486 // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
2487 //-------------------------------------------------------------------------
2488 // - DragBehaviorT<>() [Internal]
2489 // - DragBehavior() [Internal]
2490 // - DragScalar()
2491 // - DragScalarN()
2492 // - DragFloat()
2493 // - DragFloat2()
2494 // - DragFloat3()
2495 // - DragFloat4()
2496 // - DragFloatRange2()
2497 // - DragInt()
2498 // - DragInt2()
2499 // - DragInt3()
2500 // - DragInt4()
2501 // - DragIntRange2()
2502 //-------------------------------------------------------------------------
2503
2504 // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
2505 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2506 bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags)
2507 {
2508 ImGuiContext& g = *GImGui;
2509 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
2510 const bool is_bounded = (v_min < v_max) || ((v_min == v_max) && (v_min != 0.0f || (flags & ImGuiSliderFlags_ClampZeroRange)));
2511 const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround);
2512 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
2513 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
2514
2515 // Default tweak speed
2516 if (v_speed == 0.0f && is_bounded && (v_max - v_min < FLT_MAX))
2517 v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
2518
2519 // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
2520 float adjust_delta = 0.0f;
2521 if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2522 {
2523 adjust_delta = g.IO.MouseDelta[axis];
2524 if (g.IO.KeyAlt && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
2525 adjust_delta *= 1.0f / 100.0f;
2526 if (g.IO.KeyShift && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
2527 adjust_delta *= 10.0f;
2528 }
2529 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
2530 {
2531 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
2532 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
2533 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
2534 const float tweak_factor = (flags & ImGuiSliderFlags_NoSpeedTweaks) ? 1.0f : tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
2535 adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor;
2536 v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
2537 }
2538 adjust_delta *= v_speed;
2539
2540 // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
2541 if (axis == ImGuiAxis_Y)
2542 adjust_delta = -adjust_delta;
2543
2544 // For logarithmic use our range is effectively 0..1 so scale the delta into that range
2545 if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0
2546 adjust_delta /= (float)(v_max - v_min);
2547
2548 // Clear current value on activation
2549 // 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.
2550 const bool is_just_activated = g.ActiveIdIsJustActivated;
2551 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));
2552 if (is_just_activated || is_already_past_limits_and_pushing_outward)
2553 {
2554 g.DragCurrentAccum = 0.0f;
2555 g.DragCurrentAccumDirty = false;
2556 }
2557 else if (adjust_delta != 0.0f)
2558 {
2559 g.DragCurrentAccum += adjust_delta;
2560 g.DragCurrentAccumDirty = true;
2561 }
2562
2563 if (!g.DragCurrentAccumDirty)
2564 return false;
2565
2566 TYPE v_cur = *v;
2567 FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
2568
2569 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
2570 const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)
2571 if (is_logarithmic)
2572 {
2573 // 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.
2574 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
2575 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
2576
2577 // Convert to parametric space, apply delta, convert back
2578 float v_old_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2579 float v_new_parametric = v_old_parametric + g.DragCurrentAccum;
2580 v_cur = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2581 v_old_ref_for_accum_remainder = v_old_parametric;
2582 }
2583 else
2584 {
2585 v_cur += (SIGNEDTYPE)g.DragCurrentAccum;
2586 }
2587
2588 // Round to user desired precision based on format string
2589 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
2590 v_cur = RoundScalarWithFormatT<TYPE>(format, data_type, v_cur);
2591
2592 // Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
2593 g.DragCurrentAccumDirty = false;
2594 if (is_logarithmic)
2595 {
2596 // Convert to parametric space, apply delta, convert back
2597 float v_new_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2598 g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);
2599 }
2600 else
2601 {
2602 g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
2603 }
2604
2605 // Lose zero sign for float/double
2606 if (v_cur == (TYPE)-0)
2607 v_cur = (TYPE)0;
2608
2609 if (*v != v_cur && is_bounded)
2610 {
2611 if (is_wrapped)
2612 {
2613 // Wrap values
2614 if (v_cur < v_min)
2615 v_cur += v_max - v_min + (is_floating_point ? 0 : 1);
2616 if (v_cur > v_max)
2617 v_cur -= v_max - v_min + (is_floating_point ? 0 : 1);
2618 }
2619 else
2620 {
2621 // Clamp values + handle overflow/wrap-around for integer types.
2622 if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point))
2623 v_cur = v_min;
2624 if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point))
2625 v_cur = v_max;
2626 }
2627 }
2628
2629 // Apply result
2630 if (*v == v_cur)
2631 return false;
2632 *v = v_cur;
2633 return true;
2634 }
2635
2636 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)
2637 {
2638 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
2639 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.");
2640
2641 ImGuiContext& g = *GImGui;
2642 if (g.ActiveId == id)
2643 {
2644 // Those are the things we can do easily outside the DragBehaviorT<> template, saves code generation.
2645 if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
2646 ClearActiveID();
2647 else if ((g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
2648 ClearActiveID();
2649 }
2650 if (g.ActiveId != id)
2651 return false;
2652 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
2653 return false;
2654
2655 switch (data_type)
2656 {
2657 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; }
2658 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; }
2659 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; }
2660 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; }
2661 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);
2662 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);
2663 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);
2664 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);
2665 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);
2666 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);
2667 case ImGuiDataType_COUNT: break;
2668 }
2669 IM_ASSERT(0);
2670 return false;
2671 }
2672
2673 // 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.
2674 // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
2675 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)
2676 {
2677 ImGuiWindow* window = GetCurrentWindow();
2678 if (window->SkipItems)
2679 return false;
2680
2681 ImGuiContext& g = *GImGui;
2682 const ImGuiStyle& style = g.Style;
2683 const ImGuiID id = window->GetID(label);
2684 const float w = CalcItemWidth();
2685
2686 const ImVec2 label_size = CalcTextSize(label, NULL, true);
2687 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
2688 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));
2689
2690 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
2691 ItemSize(total_bb, style.FramePadding.y);
2692 if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))
2693 return false;
2694
2695 // Default format string when passing NULL
2696 if (format == NULL)
2697 format = DataTypeGetInfo(data_type)->PrintFmt;
2698
2699 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
2700 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
2701 if (!temp_input_is_active)
2702 {
2703 // Tabbing or CTRL+click on Drag turns it into an InputText
2704 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
2705 const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id));
2706 const bool make_active = (clicked || double_clicked || g.NavActivateId == id);
2707 if (make_active && (clicked || double_clicked))
2708 SetKeyOwner(ImGuiKey_MouseLeft, id);
2709 if (make_active && temp_input_allowed)
2710 if ((clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
2711 temp_input_is_active = true;
2712
2713 // (Optional) simple click (without moving) turns Drag into an InputText
2714 if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active)
2715 if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2716 {
2717 g.NavActivateId = id;
2718 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
2719 temp_input_is_active = true;
2720 }
2721
2722 // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
2723 if (make_active)
2724 memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
2725
2726 if (make_active && !temp_input_is_active)
2727 {
2728 SetActiveID(id, window);
2729 SetFocusID(id, window);
2730 FocusWindow(window);
2731 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
2732 }
2733 }
2734
2735 if (temp_input_is_active)
2736 {
2737 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
2738 bool clamp_enabled = false;
2739 if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL))
2740 {
2741 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
2742 if (p_min == NULL || p_max == NULL || clamp_range_dir < 0)
2743 clamp_enabled = true;
2744 else if (clamp_range_dir == 0)
2745 clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true;
2746 }
2747 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
2748 }
2749
2750 // Draw frame
2751 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
2752 RenderNavCursor(frame_bb, id);
2753 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
2754
2755 // Drag behavior
2756 const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags);
2757 if (value_changed)
2758 MarkItemEdited(id);
2759
2760 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
2761 char value_buf[64];
2762 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
2763 if (g.LogEnabled)
2764 LogSetNextTextDecoration("{", "}");
2765 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
2766
2767 if (label_size.x > 0.0f)
2768 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
2769
2770 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
2771 return value_changed;
2772 }
2773
2774 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)
2775 {
2776 ImGuiWindow* window = GetCurrentWindow();
2777 if (window->SkipItems)
2778 return false;
2779
2780 ImGuiContext& g = *GImGui;
2781 bool value_changed = false;
2782 BeginGroup();
2783 PushID(label);
2784 PushMultiItemsWidths(components, CalcItemWidth());
2785 size_t type_size = GDataTypeInfo[data_type].Size;
2786 for (int i = 0; i < components; i++)
2787 {
2788 PushID(i);
2789 if (i > 0)
2790 SameLine(0, g.Style.ItemInnerSpacing.x);
2791 value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags);
2792 PopID();
2793 PopItemWidth();
2794 p_data = (void*)((char*)p_data + type_size);
2795 }
2796 PopID();
2797
2798 const char* label_end = FindRenderedTextEnd(label);
2799 if (label != label_end)
2800 {
2801 SameLine(0, g.Style.ItemInnerSpacing.x);
2802 TextEx(label, label_end);
2803 }
2804
2805 EndGroup();
2806 return value_changed;
2807 }
2808
2809 bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2810 {
2811 return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags);
2812 }
2813
2814 bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2815 {
2816 return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags);
2817 }
2818
2819 bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2820 {
2821 return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags);
2822 }
2823
2824 bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2825 {
2826 return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags);
2827 }
2828
2829 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
2830 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)
2831 {
2832 ImGuiWindow* window = GetCurrentWindow();
2833 if (window->SkipItems)
2834 return false;
2835
2836 ImGuiContext& g = *GImGui;
2837 PushID(label);
2838 BeginGroup();
2839 PushMultiItemsWidths(2, CalcItemWidth());
2840
2841 float min_min = (v_min >= v_max) ? -FLT_MAX : v_min;
2842 float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
2843 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
2844 bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags);
2845 PopItemWidth();
2846 SameLine(0, g.Style.ItemInnerSpacing.x);
2847
2848 float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
2849 float max_max = (v_min >= v_max) ? FLT_MAX : v_max;
2850 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
2851 value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags);
2852 PopItemWidth();
2853 SameLine(0, g.Style.ItemInnerSpacing.x);
2854
2855 TextEx(label, FindRenderedTextEnd(label));
2856 EndGroup();
2857 PopID();
2858
2859 return value_changed;
2860 }
2861
2862 // NB: v_speed is float to allow adjusting the drag speed with more precision
2863 bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2864 {
2865 return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags);
2866 }
2867
2868 bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2869 {
2870 return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags);
2871 }
2872
2873 bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2874 {
2875 return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags);
2876 }
2877
2878 bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2879 {
2880 return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags);
2881 }
2882
2883 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
2884 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)
2885 {
2886 ImGuiWindow* window = GetCurrentWindow();
2887 if (window->SkipItems)
2888 return false;
2889
2890 ImGuiContext& g = *GImGui;
2891 PushID(label);
2892 BeginGroup();
2893 PushMultiItemsWidths(2, CalcItemWidth());
2894
2895 int min_min = (v_min >= v_max) ? INT_MIN : v_min;
2896 int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
2897 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
2898 bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags);
2899 PopItemWidth();
2900 SameLine(0, g.Style.ItemInnerSpacing.x);
2901
2902 int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
2903 int max_max = (v_min >= v_max) ? INT_MAX : v_max;
2904 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
2905 value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags);
2906 PopItemWidth();
2907 SameLine(0, g.Style.ItemInnerSpacing.x);
2908
2909 TextEx(label, FindRenderedTextEnd(label));
2910 EndGroup();
2911 PopID();
2912
2913 return value_changed;
2914 }
2915
2916 //-------------------------------------------------------------------------
2917 // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
2918 //-------------------------------------------------------------------------
2919 // - ScaleRatioFromValueT<> [Internal]
2920 // - ScaleValueFromRatioT<> [Internal]
2921 // - SliderBehaviorT<>() [Internal]
2922 // - SliderBehavior() [Internal]
2923 // - SliderScalar()
2924 // - SliderScalarN()
2925 // - SliderFloat()
2926 // - SliderFloat2()
2927 // - SliderFloat3()
2928 // - SliderFloat4()
2929 // - SliderAngle()
2930 // - SliderInt()
2931 // - SliderInt2()
2932 // - SliderInt3()
2933 // - SliderInt4()
2934 // - VSliderScalar()
2935 // - VSliderFloat()
2936 // - VSliderInt()
2937 //-------------------------------------------------------------------------
2938
2939 // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT)
2940 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2941 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)
2942 {
2943 if (v_min == v_max)
2944 return 0.0f;
2945 IM_UNUSED(data_type);
2946
2947 const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
2948 if (is_logarithmic)
2949 {
2950 bool flipped = v_max < v_min;
2951
2952 if (flipped) // Handle the case where the range is backwards
2953 ImSwap(v_min, v_max);
2954
2955 // Fudge min/max to avoid getting close to log(0)
2956 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
2957 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
2958
2959 // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
2960 if ((v_min == 0.0f) && (v_max < 0.0f))
2961 v_min_fudged = -logarithmic_zero_epsilon;
2962 else if ((v_max == 0.0f) && (v_min < 0.0f))
2963 v_max_fudged = -logarithmic_zero_epsilon;
2964
2965 float result;
2966 if (v_clamped <= v_min_fudged)
2967 result = 0.0f; // Workaround for values that are in-range but below our fudge
2968 else if (v_clamped >= v_max_fudged)
2969 result = 1.0f; // Workaround for values that are in-range but above our fudge
2970 else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions
2971 {
2972 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)
2973 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
2974 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
2975 if (v == 0.0f)
2976 result = zero_point_center; // Special case for exactly zero
2977 else if (v < 0.0f)
2978 result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L;
2979 else
2980 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));
2981 }
2982 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
2983 result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged));
2984 else
2985 result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged));
2986
2987 return flipped ? (1.0f - result) : result;
2988 }
2989 else
2990 {
2991 // Linear slider
2992 return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min));
2993 }
2994 }
2995
2996 // Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)
2997 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2998 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)
2999 {
3000 // We special-case the extents because otherwise our logarithmic fudging can lead to "mathematically correct"
3001 // but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value. Also generally simpler.
3002 if (t <= 0.0f || v_min == v_max)
3003 return v_min;
3004 if (t >= 1.0f)
3005 return v_max;
3006
3007 TYPE result = (TYPE)0;
3008 if (is_logarithmic)
3009 {
3010 // Fudge min/max to avoid getting silly results close to zero
3011 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
3012 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
3013
3014 const bool flipped = v_max < v_min; // Check if range is "backwards"
3015 if (flipped)
3016 ImSwap(v_min_fudged, v_max_fudged);
3017
3018 // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
3019 if ((v_max == 0.0f) && (v_min < 0.0f))
3020 v_max_fudged = -logarithmic_zero_epsilon;
3021
3022 float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range
3023
3024 if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts
3025 {
3026 float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space
3027 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
3028 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
3029 if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R)
3030 result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise)
3031 else if (t_with_flip < zero_point_center)
3032 result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L))));
3033 else
3034 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))));
3035 }
3036 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
3037 result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip)));
3038 else
3039 result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip));
3040 }
3041 else
3042 {
3043 // Linear slider
3044 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
3045 if (is_floating_point)
3046 {
3047 result = ImLerp(v_min, v_max, t);
3048 }
3049 else if (t < 1.0)
3050 {
3051 // - For integer values we want the clicking position to match the grab box so we round above
3052 // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
3053 // - 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
3054 // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits.
3055 FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t;
3056 result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5)));
3057 }
3058 }
3059
3060 return result;
3061 }
3062
3063 // FIXME: Try to move more of the code into shared SliderBehavior()
3064 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
3065 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)
3066 {
3067 ImGuiContext& g = *GImGui;
3068 const ImGuiStyle& style = g.Style;
3069
3070 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
3071 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
3072 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
3073 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.
3074
3075 // Calculate bounds
3076 const float grab_padding = 2.0f; // FIXME: Should be part of style.
3077 const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
3078 float grab_sz = style.GrabMinSize;
3079 if (!is_floating_point && v_range_f >= 0.0f) // v_range_f < 0 may happen on integer overflows
3080 grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
3081 grab_sz = ImMin(grab_sz, slider_sz);
3082 const float slider_usable_sz = slider_sz - grab_sz;
3083 const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;
3084 const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;
3085
3086 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
3087 float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true
3088 if (is_logarithmic)
3089 {
3090 // 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.
3091 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
3092 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
3093 zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f);
3094 }
3095
3096 // Process interacting with the slider
3097 bool value_changed = false;
3098 if (g.ActiveId == id)
3099 {
3100 bool set_new_value = false;
3101 float clicked_t = 0.0f;
3102 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
3103 {
3104 if (!g.IO.MouseDown[0])
3105 {
3106 ClearActiveID();
3107 }
3108 else
3109 {
3110 const float mouse_abs_pos = g.IO.MousePos[axis];
3111 if (g.ActiveIdIsJustActivated)
3112 {
3113 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3114 if (axis == ImGuiAxis_Y)
3115 grab_t = 1.0f - grab_t;
3116 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3117 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.
3118 g.SliderGrabClickOffset = (clicked_around_grab && is_floating_point) ? mouse_abs_pos - grab_pos : 0.0f;
3119 }
3120 if (slider_usable_sz > 0.0f)
3121 clicked_t = ImSaturate((mouse_abs_pos - g.SliderGrabClickOffset - slider_usable_pos_min) / slider_usable_sz);
3122 if (axis == ImGuiAxis_Y)
3123 clicked_t = 1.0f - clicked_t;
3124 set_new_value = true;
3125 }
3126 }
3127 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
3128 {
3129 if (g.ActiveIdIsJustActivated)
3130 {
3131 g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation
3132 g.SliderCurrentAccumDirty = false;
3133 }
3134
3135 float input_delta = (axis == ImGuiAxis_X) ? GetNavTweakPressedAmount(axis) : -GetNavTweakPressedAmount(axis);
3136 if (input_delta != 0.0f)
3137 {
3138 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
3139 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
3140 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
3141 if (decimal_precision > 0)
3142 {
3143 input_delta /= 100.0f; // Keyboard/Gamepad tweak speeds in % of slider bounds
3144 if (tweak_slow)
3145 input_delta /= 10.0f;
3146 }
3147 else
3148 {
3149 if ((v_range_f >= -100.0f && v_range_f <= 100.0f && v_range_f != 0.0f) || tweak_slow)
3150 input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Keyboard/Gamepad tweak speeds in integer steps
3151 else
3152 input_delta /= 100.0f;
3153 }
3154 if (tweak_fast)
3155 input_delta *= 10.0f;
3156
3157 g.SliderCurrentAccum += input_delta;
3158 g.SliderCurrentAccumDirty = true;
3159 }
3160
3161 float delta = g.SliderCurrentAccum;
3162 if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
3163 {
3164 ClearActiveID();
3165 }
3166 else if (g.SliderCurrentAccumDirty)
3167 {
3168 clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3169
3170 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
3171 {
3172 set_new_value = false;
3173 g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate
3174 }
3175 else
3176 {
3177 set_new_value = true;
3178 float old_clicked_t = clicked_t;
3179 clicked_t = ImSaturate(clicked_t + delta);
3180
3181 // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator
3182 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3183 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3184 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3185 float new_clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3186
3187 if (delta > 0)
3188 g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta);
3189 else
3190 g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta);
3191 }
3192
3193 g.SliderCurrentAccumDirty = false;
3194 }
3195 }
3196
3197 if (set_new_value)
3198 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
3199 set_new_value = false;
3200
3201 if (set_new_value)
3202 {
3203 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3204
3205 // Round to user desired precision based on format string
3206 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3207 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3208
3209 // Apply result
3210 if (*v != v_new)
3211 {
3212 *v = v_new;
3213 value_changed = true;
3214 }
3215 }
3216 }
3217
3218 if (slider_sz < 1.0f)
3219 {
3220 *out_grab_bb = ImRect(bb.Min, bb.Min);
3221 }
3222 else
3223 {
3224 // Output grab position so it can be displayed by the caller
3225 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3226 if (axis == ImGuiAxis_Y)
3227 grab_t = 1.0f - grab_t;
3228 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3229 if (axis == ImGuiAxis_X)
3230 *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);
3231 else
3232 *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);
3233 }
3234
3235 return value_changed;
3236 }
3237
3238 // For 32-bit and larger types, slider bounds are limited to half the natural type range.
3239 // 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.
3240 // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
3241 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)
3242 {
3243 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
3244 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.");
3245 IM_ASSERT((flags & ImGuiSliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX()
3246
3247 switch (data_type)
3248 {
3249 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; }
3250 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; }
3251 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; }
3252 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; }
3253 case ImGuiDataType_S32:
3254 IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2);
3255 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);
3256 case ImGuiDataType_U32:
3257 IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2);
3258 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);
3259 case ImGuiDataType_S64:
3260 IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2);
3261 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);
3262 case ImGuiDataType_U64:
3263 IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2);
3264 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);
3265 case ImGuiDataType_Float:
3266 IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f);
3267 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);
3268 case ImGuiDataType_Double:
3269 IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f);
3270 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);
3271 case ImGuiDataType_COUNT: break;
3272 }
3273 IM_ASSERT(0);
3274 return false;
3275 }
3276
3277 // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required.
3278 // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3279 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)
3280 {
3281 ImGuiWindow* window = GetCurrentWindow();
3282 if (window->SkipItems)
3283 return false;
3284
3285 ImGuiContext& g = *GImGui;
3286 const ImGuiStyle& style = g.Style;
3287 const ImGuiID id = window->GetID(label);
3288 const float w = CalcItemWidth();
3289
3290 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3291 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
3292 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));
3293
3294 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
3295 ItemSize(total_bb, style.FramePadding.y);
3296 if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))
3297 return false;
3298
3299 // Default format string when passing NULL
3300 if (format == NULL)
3301 format = DataTypeGetInfo(data_type)->PrintFmt;
3302
3303 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3304 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
3305 if (!temp_input_is_active)
3306 {
3307 // Tabbing or CTRL+click on Slider turns it into an input box
3308 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3309 const bool make_active = (clicked || g.NavActivateId == id);
3310 if (make_active && clicked)
3311 SetKeyOwner(ImGuiKey_MouseLeft, id);
3312 if (make_active && temp_input_allowed)
3313 if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
3314 temp_input_is_active = true;
3315
3316 // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
3317 if (make_active)
3318 memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
3319
3320 if (make_active && !temp_input_is_active)
3321 {
3322 SetActiveID(id, window);
3323 SetFocusID(id, window);
3324 FocusWindow(window);
3325 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
3326 }
3327 }
3328
3329 if (temp_input_is_active)
3330 {
3331 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
3332 const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0;
3333 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
3334 }
3335
3336 // Draw frame
3337 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3338 RenderNavCursor(frame_bb, id);
3339 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3340
3341 // Slider behavior
3342 ImRect grab_bb;
3343 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb);
3344 if (value_changed)
3345 MarkItemEdited(id);
3346
3347 // Render grab
3348 if (grab_bb.Max.x > grab_bb.Min.x)
3349 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3350
3351 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3352 char value_buf[64];
3353 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3354 if (g.LogEnabled)
3355 LogSetNextTextDecoration("{", "}");
3356 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
3357
3358 if (label_size.x > 0.0f)
3359 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3360
3361 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
3362 return value_changed;
3363 }
3364
3365 // Add multiple sliders on 1 line for compact edition of multiple components
3366 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)
3367 {
3368 ImGuiWindow* window = GetCurrentWindow();
3369 if (window->SkipItems)
3370 return false;
3371
3372 ImGuiContext& g = *GImGui;
3373 bool value_changed = false;
3374 BeginGroup();
3375 PushID(label);
3376 PushMultiItemsWidths(components, CalcItemWidth());
3377 size_t type_size = GDataTypeInfo[data_type].Size;
3378 for (int i = 0; i < components; i++)
3379 {
3380 PushID(i);
3381 if (i > 0)
3382 SameLine(0, g.Style.ItemInnerSpacing.x);
3383 value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags);
3384 PopID();
3385 PopItemWidth();
3386 v = (void*)((char*)v + type_size);
3387 }
3388 PopID();
3389
3390 const char* label_end = FindRenderedTextEnd(label);
3391 if (label != label_end)
3392 {
3393 SameLine(0, g.Style.ItemInnerSpacing.x);
3394 TextEx(label, label_end);
3395 }
3396
3397 EndGroup();
3398 return value_changed;
3399 }
3400
3401 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3402 {
3403 return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3404 }
3405
3406 bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3407 {
3408 return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags);
3409 }
3410
3411 bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3412 {
3413 return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags);
3414 }
3415
3416 bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3417 {
3418 return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags);
3419 }
3420
3421 bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags)
3422 {
3423 if (format == NULL)
3424 format = "%.0f deg";
3425 float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
3426 bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags);
3427 if (value_changed)
3428 *v_rad = v_deg * (2 * IM_PI) / 360.0f;
3429 return value_changed;
3430 }
3431
3432 bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3433 {
3434 return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3435 }
3436
3437 bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3438 {
3439 return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags);
3440 }
3441
3442 bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3443 {
3444 return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags);
3445 }
3446
3447 bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3448 {
3449 return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags);
3450 }
3451
3452 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)
3453 {
3454 ImGuiWindow* window = GetCurrentWindow();
3455 if (window->SkipItems)
3456 return false;
3457
3458 ImGuiContext& g = *GImGui;
3459 const ImGuiStyle& style = g.Style;
3460 const ImGuiID id = window->GetID(label);
3461
3462 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3463 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
3464 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));
3465
3466 ItemSize(bb, style.FramePadding.y);
3467 if (!ItemAdd(frame_bb, id))
3468 return false;
3469
3470 // Default format string when passing NULL
3471 if (format == NULL)
3472 format = DataTypeGetInfo(data_type)->PrintFmt;
3473
3474 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3475 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3476 if (clicked || g.NavActivateId == id)
3477 {
3478 if (clicked)
3479 SetKeyOwner(ImGuiKey_MouseLeft, id);
3480 SetActiveID(id, window);
3481 SetFocusID(id, window);
3482 FocusWindow(window);
3483 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
3484 }
3485
3486 // Draw frame
3487 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3488 RenderNavCursor(frame_bb, id);
3489 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3490
3491 // Slider behavior
3492 ImRect grab_bb;
3493 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb);
3494 if (value_changed)
3495 MarkItemEdited(id);
3496
3497 // Render grab
3498 if (grab_bb.Max.y > grab_bb.Min.y)
3499 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3500
3501 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3502 // For the vertical slider we allow centered text to overlap the frame padding
3503 char value_buf[64];
3504 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3505 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));
3506 if (label_size.x > 0.0f)
3507 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3508
3509 return value_changed;
3510 }
3511
3512 bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3513 {
3514 return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3515 }
3516
3517 bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3518 {
3519 return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3520 }
3521
3522 //-------------------------------------------------------------------------
3523 // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
3524 //-------------------------------------------------------------------------
3525 // - ImParseFormatFindStart() [Internal]
3526 // - ImParseFormatFindEnd() [Internal]
3527 // - ImParseFormatTrimDecorations() [Internal]
3528 // - ImParseFormatSanitizeForPrinting() [Internal]
3529 // - ImParseFormatSanitizeForScanning() [Internal]
3530 // - ImParseFormatPrecision() [Internal]
3531 // - TempInputTextScalar() [Internal]
3532 // - InputScalar()
3533 // - InputScalarN()
3534 // - InputFloat()
3535 // - InputFloat2()
3536 // - InputFloat3()
3537 // - InputFloat4()
3538 // - InputInt()
3539 // - InputInt2()
3540 // - InputInt3()
3541 // - InputInt4()
3542 // - InputDouble()
3543 //-------------------------------------------------------------------------
3544
3545 // We don't use strchr() because our strings are usually very short and often start with '%'
3546 const char* ImParseFormatFindStart(const char* fmt)
3547 {
3548 while (char c = fmt[0])
3549 {
3550 if (c == '%' && fmt[1] != '%')
3551 return fmt;
3552 else if (c == '%')
3553 fmt++;
3554 fmt++;
3555 }
3556 return fmt;
3557 }
3558
3559 const char* ImParseFormatFindEnd(const char* fmt)
3560 {
3561 // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
3562 if (fmt[0] != '%')
3563 return fmt;
3564 const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
3565 const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
3566 for (char c; (c = *fmt) != 0; fmt++)
3567 {
3568 if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
3569 return fmt + 1;
3570 if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
3571 return fmt + 1;
3572 }
3573 return fmt;
3574 }
3575
3576 // Extract the format out of a format string with leading or trailing decorations
3577 // fmt = "blah blah" -> return ""
3578 // fmt = "%.3f" -> return fmt
3579 // fmt = "hello %.3f" -> return fmt + 6
3580 // fmt = "%.3f hello" -> return buf written with "%.3f"
3581 const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
3582 {
3583 const char* fmt_start = ImParseFormatFindStart(fmt);
3584 if (fmt_start[0] != '%')
3585 return "";
3586 const char* fmt_end = ImParseFormatFindEnd(fmt_start);
3587 if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
3588 return fmt_start;
3589 ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
3590 return buf;
3591 }
3592
3593 // Sanitize format
3594 // - Zero terminate so extra characters after format (e.g. "%f123") don't confuse atof/atoi
3595 // - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi.
3596 void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3597 {
3598 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3599 IM_UNUSED(fmt_out_size);
3600 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3601 while (fmt_in < fmt_end)
3602 {
3603 char c = *fmt_in++;
3604 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3605 *(fmt_out++) = c;
3606 }
3607 *fmt_out = 0; // Zero-terminate
3608 }
3609
3610 // - 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"
3611 const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3612 {
3613 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3614 const char* fmt_out_begin = fmt_out;
3615 IM_UNUSED(fmt_out_size);
3616 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3617 bool has_type = false;
3618 while (fmt_in < fmt_end)
3619 {
3620 char c = *fmt_in++;
3621 if (!has_type && ((c >= '0' && c <= '9') || c == '.' || c == '+' || c == '#'))
3622 continue;
3623 has_type |= ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); // Stop skipping digits
3624 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3625 *(fmt_out++) = c;
3626 }
3627 *fmt_out = 0; // Zero-terminate
3628 return fmt_out_begin;
3629 }
3630
3631 template<typename TYPE>
3632 static const char* ImAtoi(const char* src, TYPE* output)
3633 {
3634 int negative = 0;
3635 if (*src == '-') { negative = 1; src++; }
3636 if (*src == '+') { src++; }
3637 TYPE v = 0;
3638 while (*src >= '0' && *src <= '9')
3639 v = (v * 10) + (*src++ - '0');
3640 *output = negative ? -v : v;
3641 return src;
3642 }
3643
3644 // Parse display precision back from the display format string
3645 // 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.
3646 int ImParseFormatPrecision(const char* fmt, int default_precision)
3647 {
3648 fmt = ImParseFormatFindStart(fmt);
3649 if (fmt[0] != '%')
3650 return default_precision;
3651 fmt++;
3652 while (*fmt >= '0' && *fmt <= '9')
3653 fmt++;
3654 int precision = INT_MAX;
3655 if (*fmt == '.')
3656 {
3657 fmt = ImAtoi<int>(fmt + 1, &precision);
3658 if (precision < 0 || precision > 99)
3659 precision = default_precision;
3660 }
3661 if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
3662 precision = -1;
3663 if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
3664 precision = -1;
3665 return (precision == INT_MAX) ? default_precision : precision;
3666 }
3667
3668 // Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
3669 // FIXME: Facilitate using this in variety of other situations.
3670 // FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but
3671 // the expected relationship between TempInputXXX functions and LastItemData is a little fishy.
3672 bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)
3673 {
3674 // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
3675 // We clear ActiveID on the first frame to allow the InputText() taking it back.
3676 ImGuiContext& g = *GImGui;
3677 const bool init = (g.TempInputId != id);
3678 if (init)
3679 ClearActiveID();
3680
3681 g.CurrentWindow->DC.CursorPos = bb.Min;
3682 g.LastItemData.ItemFlags |= ImGuiItemFlags_AllowDuplicateId;
3683 bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);
3684 if (init)
3685 {
3686 // First frame we started displaying the InputText widget, we expect it to take the active id.
3687 IM_ASSERT(g.ActiveId == id);
3688 g.TempInputId = g.ActiveId;
3689 }
3690 return value_changed;
3691 }
3692
3693 // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set!
3694 // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility.
3695 // However this may not be ideal for all uses, as some user code may break on out of bound values.
3696 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)
3697 {
3698 // FIXME: May need to clarify display behavior if format doesn't contain %.
3699 // "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405
3700 ImGuiContext& g = *GImGui;
3701 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
3702 char fmt_buf[32];
3703 char data_buf[32];
3704 format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
3705 if (format[0] == 0)
3706 format = type_info->PrintFmt;
3707 DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);
3708 ImStrTrimBlanks(data_buf);
3709
3710 ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3711 g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData.
3712 bool value_changed = false;
3713 if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))
3714 {
3715 // Backup old value
3716 size_t data_type_size = type_info->Size;
3717 ImGuiDataTypeStorage data_backup;
3718 memcpy(&data_backup, p_data, data_type_size);
3719
3720 // Apply new value (or operations) then clamp
3721 DataTypeApplyFromText(data_buf, data_type, p_data, format, NULL);
3722 if (p_clamp_min || p_clamp_max)
3723 {
3724 if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0)
3725 ImSwap(p_clamp_min, p_clamp_max);
3726 DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max);
3727 }
3728
3729 // Only mark as edited if new value is different
3730 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
3731 value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;
3732 if (value_changed)
3733 MarkItemEdited(id);
3734 }
3735 return value_changed;
3736 }
3737
3738 void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data)
3739 {
3740 ImGuiContext& g = *GImGui;
3741 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasRefVal;
3742 memcpy(&g.NextItemData.RefVal, p_data, DataTypeGetInfo(data_type)->Size);
3743 }
3744
3745 // 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.
3746 // Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3747 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)
3748 {
3749 ImGuiWindow* window = GetCurrentWindow();
3750 if (window->SkipItems)
3751 return false;
3752
3753 ImGuiContext& g = *GImGui;
3754 ImGuiStyle& style = g.Style;
3755 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()!
3756
3757 if (format == NULL)
3758 format = DataTypeGetInfo(data_type)->PrintFmt;
3759
3760 void* p_data_default = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue;
3761
3762 char buf[64];
3763 if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0)
3764 buf[0] = 0;
3765 else
3766 DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);
3767
3768 // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited.
3769 // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
3770 g.NextItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited;
3771 flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3772
3773 bool value_changed = false;
3774 if (p_step == NULL)
3775 {
3776 if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
3777 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3778 }
3779 else
3780 {
3781 const float button_size = GetFrameHeight();
3782
3783 BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
3784 PushID(label);
3785 SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
3786 if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
3787 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3788 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
3789
3790 // Step buttons
3791 const ImVec2 backup_frame_padding = style.FramePadding;
3792 style.FramePadding.x = style.FramePadding.y;
3793 if (flags & ImGuiInputTextFlags_ReadOnly)
3794 BeginDisabled();
3795 PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
3796 SameLine(0, style.ItemInnerSpacing.x);
3797 if (ButtonEx("-", ImVec2(button_size, button_size)))
3798 {
3799 DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
3800 value_changed = true;
3801 }
3802 SameLine(0, style.ItemInnerSpacing.x);
3803 if (ButtonEx("+", ImVec2(button_size, button_size)))
3804 {
3805 DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
3806 value_changed = true;
3807 }
3808 PopItemFlag();
3809 if (flags & ImGuiInputTextFlags_ReadOnly)
3810 EndDisabled();
3811
3812 const char* label_end = FindRenderedTextEnd(label);
3813 if (label != label_end)
3814 {
3815 SameLine(0, style.ItemInnerSpacing.x);
3816 TextEx(label, label_end);
3817 }
3818 style.FramePadding = backup_frame_padding;
3819
3820 PopID();
3821 EndGroup();
3822 }
3823
3824 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
3825 if (value_changed)
3826 MarkItemEdited(g.LastItemData.ID);
3827
3828 return value_changed;
3829 }
3830
3831 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)
3832 {
3833 ImGuiWindow* window = GetCurrentWindow();
3834 if (window->SkipItems)
3835 return false;
3836
3837 ImGuiContext& g = *GImGui;
3838 bool value_changed = false;
3839 BeginGroup();
3840 PushID(label);
3841 PushMultiItemsWidths(components, CalcItemWidth());
3842 size_t type_size = GDataTypeInfo[data_type].Size;
3843 for (int i = 0; i < components; i++)
3844 {
3845 PushID(i);
3846 if (i > 0)
3847 SameLine(0, g.Style.ItemInnerSpacing.x);
3848 value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags);
3849 PopID();
3850 PopItemWidth();
3851 p_data = (void*)((char*)p_data + type_size);
3852 }
3853 PopID();
3854
3855 const char* label_end = FindRenderedTextEnd(label);
3856 if (label != label_end)
3857 {
3858 SameLine(0.0f, g.Style.ItemInnerSpacing.x);
3859 TextEx(label, label_end);
3860 }
3861
3862 EndGroup();
3863 return value_changed;
3864 }
3865
3866 bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
3867 {
3868 return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags);
3869 }
3870
3871 bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
3872 {
3873 return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
3874 }
3875
3876 bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
3877 {
3878 return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
3879 }
3880
3881 bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
3882 {
3883 return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
3884 }
3885
3886 bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
3887 {
3888 // 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.
3889 const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
3890 return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags);
3891 }
3892
3893 bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
3894 {
3895 return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
3896 }
3897
3898 bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
3899 {
3900 return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
3901 }
3902
3903 bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
3904 {
3905 return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
3906 }
3907
3908 bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
3909 {
3910 return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags);
3911 }
3912
3913 //-------------------------------------------------------------------------
3914 // [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
3915 //-------------------------------------------------------------------------
3916 // - imstb_textedit.h include
3917 // - InputText()
3918 // - InputTextWithHint()
3919 // - InputTextMultiline()
3920 // - InputTextEx() [Internal]
3921 // - DebugNodeInputTextState() [Internal]
3922 //-------------------------------------------------------------------------
3923
3924 namespace ImStb
3925 {
3926 #include "imstb_textedit.h"
3927 }
3928
3929 bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3930 {
3931 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
3932 return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
3933 }
3934
3935 bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3936 {
3937 return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
3938 }
3939
3940 bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3941 {
3942 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint.
3943 return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
3944 }
3945
3946 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end_display, const char* text_end, const char** out_remaining, ImVec2* out_offset, ImDrawTextFlags flags)
3947 {
3948 ImGuiContext& g = *ctx;
3949 ImGuiInputTextState* obj = &g.InputTextState;
3950 return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj->WrapWidth, text_begin, text_end_display, text_end, out_remaining, out_offset, flags);
3951 }
3952
3953 // 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)
3954 // With our UTF-8 use of stb_textedit:
3955 // - 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.
3956 // - 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).
3957 // - ...but we don't use that feature.
3958 namespace ImStb
3959 {
3960 static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; }
3961 static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx >= 0 && idx <= obj->TextLen); return obj->TextSrc[idx]; }
3962 static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextSrc + line_start_idx + char_idx, obj->TextSrc + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.FontBaked->GetCharAdvance((ImWchar)c) * g.FontBakedScale; }
3963 static char STB_TEXTEDIT_NEWLINE = '\n';
3964 static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
3965 {
3966 const char* text = obj->TextSrc;
3967 const char* text_remaining = NULL;
3968 const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, text + obj->TextLen, &text_remaining, NULL, ImDrawTextFlags_StopOnNewLine | ImDrawTextFlags_WrapKeepBlanks);
3969 r->x0 = 0.0f;
3970 r->x1 = size.x;
3971 r->baseline_y_delta = size.y;
3972 r->ymin = 0.0f;
3973 r->ymax = size.y;
3974 r->num_chars = (int)(text_remaining - (text + line_start_idx));
3975 }
3976
3977 #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
3978 #define IMSTB_TEXTEDIT_GETPREVCHARINDEX IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
3979
3980 static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
3981 {
3982 if (idx >= obj->TextLen)
3983 return obj->TextLen + 1;
3984 unsigned int c;
3985 return idx + ImTextCharFromUtf8(&c, obj->TextSrc + idx, obj->TextSrc + obj->TextLen);
3986 }
3987
3988 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
3989 {
3990 if (idx <= 0)
3991 return -1;
3992 const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, obj->TextSrc + idx);
3993 return (int)(p - obj->TextSrc);
3994 }
3995
3996 static bool ImCharIsSeparatorW(unsigned int c)
3997 {
3998 static const unsigned int separator_list[] =
3999 {
4000 ',', 0x3001, '.', 0x3002, ';', 0xFF1B, '(', 0xFF08, ')', 0xFF09, '{', 0xFF5B, '}', 0xFF5D,
4001 '[', 0x300C, ']', 0x300D, '|', 0xFF5C, '!', 0xFF01, '\\', 0xFFE5, '/', 0x30FB, 0xFF0F,
4002 '\n', '\r',
4003 };
4004 for (unsigned int separator : separator_list)
4005 if (c == separator)
4006 return true;
4007 return false;
4008 }
4009
4010 static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
4011 {
4012 // 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.
4013 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
4014 return 0;
4015
4016 const char* curr_p = obj->TextSrc + idx;
4017 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
4018 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextSrc + obj->TextLen);
4019 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextSrc + obj->TextLen);
4020
4021 bool prev_white = ImCharIsBlankW(prev_c);
4022 bool prev_separ = ImCharIsSeparatorW(prev_c);
4023 bool curr_white = ImCharIsBlankW(curr_c);
4024 bool curr_separ = ImCharIsSeparatorW(curr_c);
4025 return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
4026 }
4027 static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
4028 {
4029 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
4030 return 0;
4031
4032 const char* curr_p = obj->TextSrc + idx;
4033 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
4034 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextSrc + obj->TextLen);
4035 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextSrc + obj->TextLen);
4036
4037 bool prev_white = ImCharIsBlankW(prev_c);
4038 bool prev_separ = ImCharIsSeparatorW(prev_c);
4039 bool curr_white = ImCharIsBlankW(curr_c);
4040 bool curr_separ = ImCharIsSeparatorW(curr_c);
4041 return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
4042 }
4043 static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
4044 {
4045 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4046 while (idx >= 0 && !is_word_boundary_from_right(obj, idx))
4047 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4048 return idx < 0 ? 0 : idx;
4049 }
4050 static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
4051 {
4052 int len = obj->TextLen;
4053 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4054 while (idx < len && !is_word_boundary_from_left(obj, idx))
4055 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4056 return idx > len ? len : idx;
4057 }
4058 static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
4059 {
4060 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4061 int len = obj->TextLen;
4062 while (idx < len && !is_word_boundary_from_right(obj, idx))
4063 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4064 return idx > len ? len : idx;
4065 }
4066 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); }
4067 #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
4068 #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
4069
4070 // Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping.
4071 static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor)
4072 {
4073 if (state->single_line)
4074 return 0;
4075
4076 if (obj->WrapWidth > 0.0f)
4077 {
4078 ImGuiContext& g = *obj->Ctx;
4079 const char* p_cursor = obj->TextSrc + cursor;
4080 const char* p_bol = ImStrbol(p_cursor, obj->TextSrc);
4081 const char* p = p_bol;
4082 const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough
4083 while (p >= p_bol)
4084 {
4085 const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks);
4086 if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below)
4087 return (int)(p_bol - obj->TextSrc);
4088 if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left)
4089 return (int)(p_bol - obj->TextSrc);
4090 if (p_eol >= p_cursor)
4091 return (int)(p - obj->TextSrc);
4092 p = (*p_eol == '\n') ? p_eol + 1 : p_eol;
4093 }
4094 }
4095
4096 // Regular handler, same as stb_textedit_move_line_start()
4097 while (cursor > 0)
4098 {
4099 int prev_cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, cursor);
4100 if (STB_TEXTEDIT_GETCHAR(obj, prev_cursor) == STB_TEXTEDIT_NEWLINE)
4101 break;
4102 cursor = prev_cursor;
4103 }
4104 return cursor;
4105 }
4106
4107 static int STB_TEXTEDIT_MOVELINEEND_IMPL(ImGuiInputTextState* obj, ImStb::STB_TexteditState* state, int cursor)
4108 {
4109 int n = STB_TEXTEDIT_STRINGLEN(obj);
4110 if (state->single_line)
4111 return n;
4112
4113 if (obj->WrapWidth > 0.0f)
4114 {
4115 ImGuiContext& g = *obj->Ctx;
4116 const char* p_cursor = obj->TextSrc + cursor;
4117 const char* p = ImStrbol(p_cursor, obj->TextSrc);
4118 const char* text_end = obj->TextSrc + obj->TextLen; // End of line would be enough
4119 while (p < text_end)
4120 {
4121 const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks);
4122 cursor = (int)(p_eol - obj->TextSrc);
4123 if (p_eol == p_cursor && obj->LastMoveDirectionLR != ImGuiDir_Left) // If we are already on a visible end-of-line, switch to regular handle
4124 break;
4125 if (p_eol > p_cursor)
4126 return cursor;
4127 p = (*p_eol == '\n') ? p_eol + 1 : p_eol;
4128 }
4129 }
4130 // Regular handler, same as stb_textedit_move_line_end()
4131 while (cursor < n && STB_TEXTEDIT_GETCHAR(obj, cursor) != STB_TEXTEDIT_NEWLINE)
4132 cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, cursor);
4133 return cursor;
4134 }
4135
4136 #define STB_TEXTEDIT_MOVELINESTART STB_TEXTEDIT_MOVELINESTART_IMPL
4137 #define STB_TEXTEDIT_MOVELINEEND STB_TEXTEDIT_MOVELINEEND_IMPL
4138
4139 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
4140 {
4141 // Offset remaining text (+ copy zero terminator)
4142 IM_ASSERT(obj->TextSrc == obj->TextA.Data);
4143 char* dst = obj->TextA.Data + pos;
4144 char* src = obj->TextA.Data + pos + n;
4145 memmove(dst, src, obj->TextLen - n - pos + 1);
4146 obj->Edited = true;
4147 obj->TextLen -= n;
4148 }
4149
4150 static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
4151 {
4152 const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4153 const int text_len = obj->TextLen;
4154 IM_ASSERT(pos <= text_len);
4155
4156 if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity))
4157 return false;
4158
4159 // Grow internal buffer if needed
4160 IM_ASSERT(obj->TextSrc == obj->TextA.Data);
4161 if (new_text_len + text_len + 1 > obj->TextA.Size)
4162 {
4163 if (!is_resizable)
4164 return false;
4165 obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
4166 obj->TextSrc = obj->TextA.Data;
4167 }
4168
4169 char* text = obj->TextA.Data;
4170 if (pos != text_len)
4171 memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos));
4172 memcpy(text + pos, new_text, (size_t)new_text_len);
4173
4174 obj->Edited = true;
4175 obj->TextLen += new_text_len;
4176 obj->TextA[obj->TextLen] = '\0';
4177
4178 return true;
4179 }
4180
4181 // 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)
4182 #define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left
4183 #define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right
4184 #define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up
4185 #define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down
4186 #define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line
4187 #define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line
4188 #define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text
4189 #define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text
4190 #define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor
4191 #define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor
4192 #define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo
4193 #define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo
4194 #define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word
4195 #define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word
4196 #define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page
4197 #define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page
4198 #define STB_TEXTEDIT_K_SHIFT 0x400000
4199
4200 #define IMSTB_TEXTEDIT_IMPLEMENTATION
4201 #define IMSTB_TEXTEDIT_memmove memmove
4202 #include "imstb_textedit.h"
4203
4204 // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling
4205 // the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
4206 static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
4207 {
4208 stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len);
4209 ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen);
4210 state->cursor = state->select_start = state->select_end = 0;
4211 if (text_len <= 0)
4212 return;
4213 if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len))
4214 {
4215 state->cursor = state->select_start = state->select_end = text_len;
4216 state->has_preferred_x = 0;
4217 return;
4218 }
4219 IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()
4220 }
4221
4222 } // namespace ImStb
4223
4224 // We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators.
4225 ImGuiInputTextState::ImGuiInputTextState()
4226 {
4227 memset(this, 0, sizeof(*this));
4228 Stb = IM_NEW(ImStbTexteditState);
4229 memset(Stb, 0, sizeof(*Stb));
4230 }
4231
4232 ImGuiInputTextState::~ImGuiInputTextState()
4233 {
4234 IM_DELETE(Stb);
4235 }
4236
4237 void ImGuiInputTextState::OnKeyPressed(int key)
4238 {
4239 stb_textedit_key(this, Stb, key);
4240 CursorFollow = true;
4241 CursorAnimReset();
4242 const int key_u = (key & ~STB_TEXTEDIT_K_SHIFT);
4243 if (key_u == STB_TEXTEDIT_K_LEFT || key_u == STB_TEXTEDIT_K_LINESTART || key_u == STB_TEXTEDIT_K_TEXTSTART || key_u == STB_TEXTEDIT_K_BACKSPACE || key_u == STB_TEXTEDIT_K_WORDLEFT)
4244 LastMoveDirectionLR = ImGuiDir_Left;
4245 else if (key_u == STB_TEXTEDIT_K_RIGHT || key_u == STB_TEXTEDIT_K_LINEEND || key_u == STB_TEXTEDIT_K_TEXTEND || key_u == STB_TEXTEDIT_K_DELETE || key_u == STB_TEXTEDIT_K_WORDRIGHT)
4246 LastMoveDirectionLR = ImGuiDir_Right;
4247 }
4248
4249 void ImGuiInputTextState::OnCharPressed(unsigned int c)
4250 {
4251 // Convert the key to a UTF8 byte sequence.
4252 // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
4253 char utf8[5];
4254 ImTextCharToUtf8(utf8, c);
4255 stb_textedit_text(this, Stb, utf8, (int)ImStrlen(utf8));
4256 CursorFollow = true;
4257 CursorAnimReset();
4258 }
4259
4260 // Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
4261 void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
4262 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); }
4263 bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; }
4264 void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; }
4265 int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; }
4266 int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; }
4267 int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; }
4268 float ImGuiInputTextState::GetPreferredOffsetX() const { return Stb->has_preferred_x ? Stb->preferred_x : -1; }
4269 void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
4270 void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
4271 void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
4272 void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { WantReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
4273
4274 ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
4275 {
4276 memset(this, 0, sizeof(*this));
4277 }
4278
4279 // Public API to manipulate UTF-8 text from within a callback.
4280 // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
4281 // Historically they existed because STB_TEXTEDIT_INSERTCHARS() etc. worked on our ImWchar
4282 // buffer, but nowadays they both work on UTF-8 data. Should aim to merge both.
4283 void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
4284 {
4285 IM_ASSERT(pos + bytes_count <= BufTextLen);
4286 char* dst = Buf + pos;
4287 const char* src = Buf + pos + bytes_count;
4288 memmove(dst, src, BufTextLen - bytes_count - pos + 1);
4289
4290 if (CursorPos >= pos + bytes_count)
4291 CursorPos -= bytes_count;
4292 else if (CursorPos >= pos)
4293 CursorPos = pos;
4294 SelectionStart = SelectionEnd = CursorPos;
4295 BufDirty = true;
4296 BufTextLen -= bytes_count;
4297 }
4298
4299 void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
4300 {
4301 // Accept null ranges
4302 if (new_text == new_text_end)
4303 return;
4304
4305 ImGuiContext& g = *Ctx;
4306 ImGuiInputTextState* obj = &g.InputTextState;
4307 IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID);
4308
4309 // Grow internal buffer if needed
4310 const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4311 const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text);
4312 if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0)
4313 {
4314 if (!is_resizable)
4315 return;
4316
4317 IM_ASSERT(Buf == obj->TextA.Data);
4318 int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
4319 obj->TextA.resize(new_buf_size + 1);
4320 obj->TextSrc = obj->TextA.Data;
4321 Buf = obj->TextA.Data;
4322 BufSize = obj->BufCapacity = new_buf_size;
4323 }
4324
4325 if (BufTextLen != pos)
4326 memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
4327 memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
4328 Buf[BufTextLen + new_text_len] = '\0';
4329
4330 if (CursorPos >= pos)
4331 CursorPos += new_text_len;
4332 SelectionStart = SelectionEnd = CursorPos;
4333 BufDirty = true;
4334 BufTextLen += new_text_len;
4335 }
4336
4337 void ImGui::PushPasswordFont()
4338 {
4339 ImGuiContext& g = *GImGui;
4340 ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
4341 IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
4342 ImFontGlyph* glyph = g.FontBaked->FindGlyph('*');
4343 g.InputTextPasswordFontBackupFlags = g.Font->Flags;
4344 backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex;
4345 backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX;
4346 backup->IndexLookup.swap(g.FontBaked->IndexLookup);
4347 backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX);
4348 g.Font->Flags |= ImFontFlags_NoLoadGlyphs;
4349 g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph);
4350 g.FontBaked->FallbackAdvanceX = glyph->AdvanceX;
4351 }
4352
4353 void ImGui::PopPasswordFont()
4354 {
4355 ImGuiContext& g = *GImGui;
4356 ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
4357 g.Font->Flags = g.InputTextPasswordFontBackupFlags;
4358 g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex;
4359 g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX;
4360 g.FontBaked->IndexLookup.swap(backup->IndexLookup);
4361 g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX);
4362 IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
4363 }
4364
4365 // Return false to discard a character.
4366 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard)
4367 {
4368 unsigned int c = *p_char;
4369
4370 // Filter non-printable (NB: isprint is unreliable! see #2467)
4371 bool apply_named_filters = true;
4372 if (c < 0x20)
4373 {
4374 bool pass = false;
4375 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)
4376 if (c == '\n' && input_source_is_clipboard && (flags & ImGuiInputTextFlags_Multiline) == 0) // In single line mode, replace \n with a space
4377 {
4378 c = *p_char = ' ';
4379 pass = true;
4380 }
4381 pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0;
4382 pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0;
4383 if (!pass)
4384 return false;
4385 apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted.
4386 }
4387
4388 if (input_source_is_clipboard == false)
4389 {
4390 // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
4391 if (c == 127)
4392 return false;
4393
4394 // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
4395 if (c >= 0xE000 && c <= 0xF8FF)
4396 return false;
4397 }
4398
4399 // Filter Unicode ranges we are not handling in this build
4400 if (c > IM_UNICODE_CODEPOINT_MAX)
4401 return false;
4402
4403 // Generic named filters
4404 if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint)))
4405 {
4406 // 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 '.'.
4407 // The standard mandate that programs starts in the "C" locale where the decimal point is '.'.
4408 // 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.
4409 // Change the default decimal_point with:
4410 // ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point;
4411 // 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.
4412 ImGuiContext& g = *ctx;
4413 const unsigned c_decimal_point = (unsigned int)g.PlatformIO.Platform_LocaleDecimalPoint;
4414 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint))
4415 if (c == '.' || c == ',')
4416 c = c_decimal_point;
4417
4418 // Full-width -> half-width conversion for numeric fields: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
4419 // While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may
4420 // scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font.
4421 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal))
4422 if (c >= 0xFF01 && c <= 0xFF5E)
4423 c = c - 0xFF01 + 0x21;
4424
4425 // Allow 0-9 . - + * /
4426 if (flags & ImGuiInputTextFlags_CharsDecimal)
4427 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
4428 return false;
4429
4430 // Allow 0-9 . - + * / e E
4431 if (flags & ImGuiInputTextFlags_CharsScientific)
4432 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
4433 return false;
4434
4435 // Allow 0-9 a-F A-F
4436 if (flags & ImGuiInputTextFlags_CharsHexadecimal)
4437 if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
4438 return false;
4439
4440 // Turn a-z into A-Z
4441 if (flags & ImGuiInputTextFlags_CharsUppercase)
4442 if (c >= 'a' && c <= 'z')
4443 c += (unsigned int)('A' - 'a');
4444
4445 if (flags & ImGuiInputTextFlags_CharsNoBlank)
4446 if (ImCharIsBlankW(c))
4447 return false;
4448
4449 *p_char = c;
4450 }
4451
4452 // Custom callback filter
4453 if (flags & ImGuiInputTextFlags_CallbackCharFilter)
4454 {
4455 ImGuiContext& g = *GImGui;
4456 ImGuiInputTextCallbackData callback_data;
4457 callback_data.Ctx = &g;
4458 callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
4459 callback_data.EventChar = (ImWchar)c;
4460 callback_data.Flags = flags;
4461 callback_data.UserData = user_data;
4462 if (callback(&callback_data) != 0)
4463 return false;
4464 *p_char = callback_data.EventChar;
4465 if (!callback_data.EventChar)
4466 return false;
4467 }
4468
4469 return true;
4470 }
4471
4472 // Find the shortest single replacement we can make to get from old_buf to new_buf
4473 // Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately.
4474 // 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.
4475 static void InputTextReconcileUndoState(ImGuiInputTextState* state, const char* old_buf, int old_length, const char* new_buf, int new_length)
4476 {
4477 const int shorter_length = ImMin(old_length, new_length);
4478 int first_diff;
4479 for (first_diff = 0; first_diff < shorter_length; first_diff++)
4480 if (old_buf[first_diff] != new_buf[first_diff])
4481 break;
4482 if (first_diff == old_length && first_diff == new_length)
4483 return;
4484
4485 int old_last_diff = old_length - 1;
4486 int new_last_diff = new_length - 1;
4487 for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
4488 if (old_buf[old_last_diff] != new_buf[new_last_diff])
4489 break;
4490
4491 const int insert_len = new_last_diff - first_diff + 1;
4492 const int delete_len = old_last_diff - first_diff + 1;
4493 if (insert_len > 0 || delete_len > 0)
4494 if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len))
4495 for (int i = 0; i < delete_len; i++)
4496 p[i] = old_buf[first_diff + i];
4497 }
4498
4499 // As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables)
4500 // we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714)
4501 // It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick,
4502 // but that more likely be attractive when we do have _NoLiveEdit flag available.
4503 void ImGui::InputTextDeactivateHook(ImGuiID id)
4504 {
4505 ImGuiContext& g = *GImGui;
4506 ImGuiInputTextState* state = &g.InputTextState;
4507 if (id == 0 || state->ID != id)
4508 return;
4509 g.InputTextDeactivatedState.ID = state->ID;
4510 if (state->Flags & ImGuiInputTextFlags_ReadOnly)
4511 {
4512 g.InputTextDeactivatedState.TextA.resize(0); // In theory this data won't be used, but clear to be neat.
4513 }
4514 else
4515 {
4516 IM_ASSERT(state->TextA.Data != 0);
4517 IM_ASSERT(state->TextA[state->TextLen] == 0);
4518 g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1);
4519 memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1);
4520 }
4521 }
4522
4523 static int* ImLowerBound(int* in_begin, int* in_end, int v)
4524 {
4525 int* in_p = in_begin;
4526 for (size_t count = (size_t)(in_end - in_p); count > 0; )
4527 {
4528 size_t count2 = count >> 1;
4529 int* mid = in_p + count2;
4530 if (*mid < v)
4531 {
4532 in_p = ++mid;
4533 count -= count2 + 1;
4534 }
4535 else
4536 {
4537 count = count2;
4538 }
4539 }
4540 return in_p;
4541 }
4542
4543 // FIXME-WORDWRAP: Bundle some of this into ImGuiTextIndex and/or extract as a different tool?
4544 // 'max_output_buffer_size' happens to be a meaningful optimization to avoid writing the full line_index when not necessarily needed (e.g. very large buffer, scrolled up, inactive)
4545 static int InputTextLineIndexBuild(ImGuiInputTextFlags flags, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, float wrap_width, int max_output_buffer_size, const char** out_buf_end)
4546 {
4547 ImGuiContext& g = *GImGui;
4548 int size = 0;
4549 const char* s;
4550 if (flags & ImGuiInputTextFlags_WordWrap)
4551 {
4552 for (s = buf; s < buf_end; s = (*s == '\n') ? s + 1 : s)
4553 {
4554 if (size++ <= max_output_buffer_size)
4555 line_index->Offsets.push_back((int)(s - buf));
4556 s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, s, buf_end, wrap_width, ImDrawTextFlags_WrapKeepBlanks);
4557 }
4558 }
4559 else if (buf_end != NULL)
4560 {
4561 for (s = buf; s < buf_end; s = s ? s + 1 : buf_end)
4562 {
4563 if (size++ <= max_output_buffer_size)
4564 line_index->Offsets.push_back((int)(s - buf));
4565 s = (const char*)ImMemchr(s, '\n', buf_end - s);
4566 }
4567 }
4568 else
4569 {
4570 const char* s_eol;
4571 for (s = buf; ; s = s_eol + 1)
4572 {
4573 if (size++ <= max_output_buffer_size)
4574 line_index->Offsets.push_back((int)(s - buf));
4575 if ((s_eol = strchr(s, '\n')) != NULL)
4576 continue;
4577 s += strlen(s);
4578 break;
4579 }
4580 }
4581 if (out_buf_end != NULL)
4582 *out_buf_end = buf_end = s;
4583 if (size == 0)
4584 {
4585 line_index->Offsets.push_back(0);
4586 size++;
4587 }
4588 if (buf_end > buf && buf_end[-1] == '\n' && size <= max_output_buffer_size)
4589 {
4590 line_index->Offsets.push_back((int)(buf_end - buf));
4591 size++;
4592 }
4593 return size;
4594 }
4595
4596 static ImVec2 InputTextLineIndexGetPosOffset(ImGuiContext& g, ImGuiInputTextState* state, ImGuiTextIndex* line_index, const char* buf, const char* buf_end, int cursor_n)
4597 {
4598 const char* cursor_ptr = buf + cursor_n;
4599 int* it_begin = line_index->Offsets.begin();
4600 int* it_end = line_index->Offsets.end();
4601 const int* it = ImLowerBound(it_begin, it_end, cursor_n);
4602 if (it > it_begin)
4603 if (it == it_end || *it != cursor_n || (state != NULL && state->WrapWidth > 0.0f && state->LastMoveDirectionLR == ImGuiDir_Right && cursor_ptr[-1] != '\n' && cursor_ptr[-1] != 0))
4604 it--;
4605
4606 const int line_no = (it == it_begin) ? 0 : line_index->Offsets.index_from_ptr(it);
4607 const char* line_start = line_index->get_line_begin(buf, line_no);
4608 ImVec2 offset;
4609 offset.x = InputTextCalcTextSize(&g, line_start, cursor_ptr, buf_end, NULL, NULL, ImDrawTextFlags_WrapKeepBlanks).x;
4610 offset.y = (line_no + 1) * g.FontSize;
4611 return offset;
4612 }
4613
4614 // Edit a string of text
4615 // - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
4616 // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
4617 // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
4618 // - 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.
4619 // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
4620 // (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
4621 // 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)
4622 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)
4623 {
4624 ImGuiWindow* window = GetCurrentWindow();
4625 if (window->SkipItems)
4626 return false;
4627
4628 IM_ASSERT(buf != NULL && buf_size >= 0);
4629 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
4630 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
4631 IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming
4632 IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode.
4633 IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode.
4634
4635 ImGuiContext& g = *GImGui;
4636 ImGuiIO& io = g.IO;
4637 const ImGuiStyle& style = g.Style;
4638
4639 const bool RENDER_SELECTION_WHEN_INACTIVE = false;
4640 const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
4641
4642 if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar)
4643 BeginGroup();
4644 const ImGuiID id = window->GetID(label);
4645 const ImVec2 label_size = CalcTextSize(label, NULL, true);
4646 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
4647 const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y);
4648
4649 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
4650 const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size);
4651
4652 ImGuiWindow* draw_window = window;
4653 ImVec2 inner_size = frame_size;
4654 ImGuiLastItemData item_data_backup;
4655 if (is_multiline)
4656 {
4657 ImVec2 backup_pos = window->DC.CursorPos;
4658 ItemSize(total_bb, style.FramePadding.y);
4659 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4660 {
4661 EndGroup();
4662 return false;
4663 }
4664 item_data_backup = g.LastItemData;
4665 window->DC.CursorPos = backup_pos;
4666
4667 // Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping.
4668 if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && !(g.NavActivateFlags & ImGuiActivateFlags_FromFocusApi) && (flags & ImGuiInputTextFlags_AllowTabInput))
4669 g.NavActivateId = 0;
4670
4671 // Prevent NavActivate reactivating in BeginChild() when we are already active.
4672 const ImGuiID backup_activate_id = g.NavActivateId;
4673 if (g.ActiveId == id) // Prevent reactivation
4674 g.NavActivateId = 0;
4675
4676 // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug.
4677 PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
4678 PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
4679 PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
4680 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges
4681 bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove);
4682 g.NavActivateId = backup_activate_id;
4683 PopStyleVar(3);
4684 PopStyleColor();
4685 if (!child_visible)
4686 {
4687 EndChild();
4688 EndGroup();
4689 return false;
4690 }
4691 draw_window = g.CurrentWindow; // Child window
4692 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.
4693 draw_window->DC.CursorPos += style.FramePadding;
4694 inner_size.x -= draw_window->ScrollbarSizes.x;
4695 }
4696 else
4697 {
4698 // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd)
4699 ItemSize(total_bb, style.FramePadding.y);
4700 if (!(flags & ImGuiInputTextFlags_MergedItem))
4701 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4702 return false;
4703 }
4704
4705 // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
4706 bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover);
4707 if (hovered)
4708 SetMouseCursor(ImGuiMouseCursor_TextInput);
4709 if (hovered && g.NavHighlightItemUnderNav)
4710 hovered = false;
4711
4712 // We are only allowed to access the state if we are already the active widget.
4713 ImGuiInputTextState* state = GetInputTextState(id);
4714
4715 if (g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly)
4716 flags |= ImGuiInputTextFlags_ReadOnly;
4717 const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
4718 const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
4719 const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
4720 const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
4721 if (is_resizable)
4722 IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
4723
4724 // Word-wrapping: enforcing a fixed width not altered by vertical scrollbar makes things easier, notably to track cursor reliably and avoid one-frame glitches.
4725 // Instead of using ImGuiWindowFlags_AlwaysVerticalScrollbar we account for that space if the scrollbar is not visible.
4726 const bool is_wordwrap = (flags & ImGuiInputTextFlags_WordWrap) != 0;
4727 float wrap_width = 0.0f;
4728 if (is_wordwrap)
4729 wrap_width = ImMax(1.0f, GetContentRegionAvail().x + (draw_window->ScrollbarY ? 0.0f : -g.Style.ScrollbarSize));
4730
4731 const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard)));
4732
4733 const bool user_clicked = hovered && io.MouseClicked[0];
4734 const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4735 const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4736 bool clear_active_id = false;
4737 bool select_all = false;
4738
4739 float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;
4740
4741 const bool init_reload_from_user_buf = (state != NULL && state->WantReloadUserBuf);
4742 const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
4743 const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
4744 const bool init_state = (init_make_active || user_scroll_active);
4745 if (init_reload_from_user_buf)
4746 {
4747 int new_len = (int)ImStrlen(buf);
4748 IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?");
4749 state->WantReloadUserBuf = false;
4750 InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len);
4751 state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
4752 state->TextLen = new_len;
4753 memcpy(state->TextA.Data, buf, state->TextLen + 1);
4754 state->Stb->select_start = state->ReloadSelectionStart;
4755 state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
4756 state->CursorClamp();
4757 }
4758 else if ((init_state && g.ActiveId != id) || init_changed_specs)
4759 {
4760 // Access state even if we don't own it yet.
4761 state = &g.InputTextState;
4762 state->CursorAnimReset();
4763
4764 // 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)
4765 InputTextDeactivateHook(state->ID);
4766
4767 // Take a copy of the initial buffer value.
4768 // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
4769 const int buf_len = (int)ImStrlen(buf);
4770 IM_ASSERT(((buf_len + 1 <= buf_size) || (buf_len == 0 && buf_size == 0)) && "Is your input buffer properly zero-terminated?");
4771 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.
4772 memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
4773
4774 // Preserve cursor position and undo/redo stack if we come back to same widget
4775 // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
4776 bool recycle_state = (state->ID == id && !init_changed_specs);
4777 if (recycle_state && (state->TextLen != buf_len || (state->TextA.Data == NULL || strncmp(state->TextA.Data, buf, buf_len) != 0)))
4778 recycle_state = false;
4779
4780 // Start edition
4781 state->ID = id;
4782 state->TextLen = buf_len;
4783 if (!is_readonly)
4784 {
4785 state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
4786 memcpy(state->TextA.Data, buf, state->TextLen + 1);
4787 }
4788
4789 // Find initial scroll position for right alignment
4790 state->Scroll = ImVec2(0.0f, 0.0f);
4791 if (flags & ImGuiInputTextFlags_ElideLeft)
4792 state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
4793
4794 // Recycle existing cursor/selection/undo stack but clamp position
4795 // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
4796 if (recycle_state)
4797 state->CursorClamp();
4798 else
4799 stb_textedit_initialize_state(state->Stb, !is_multiline);
4800
4801 if (!is_multiline)
4802 {
4803 if (flags & ImGuiInputTextFlags_AutoSelectAll)
4804 select_all = true;
4805 if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState)))
4806 select_all = true;
4807 if (user_clicked && io.KeyCtrl)
4808 select_all = true;
4809 }
4810
4811 if (flags & ImGuiInputTextFlags_AlwaysOverwrite)
4812 state->Stb->insert_mode = 1; // stb field name is indeed incorrect (see #2863)
4813 }
4814
4815 const bool is_osx = io.ConfigMacOSXBehaviors;
4816 if (g.ActiveId != id && init_make_active)
4817 {
4818 IM_ASSERT(state && state->ID == id);
4819 SetActiveID(id, window);
4820 SetFocusID(id, window);
4821 FocusWindow(window);
4822 }
4823 if (g.ActiveId == id)
4824 {
4825 // Declare some inputs, the other are registered and polled via Shortcut() routing system.
4826 // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts.
4827 const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End };
4828 for (ImGuiKey key : always_owned_keys)
4829 SetKeyOwner(key, id);
4830 if (user_clicked)
4831 SetKeyOwner(ImGuiKey_MouseLeft, id);
4832 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
4833 if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
4834 {
4835 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
4836 SetKeyOwner(ImGuiKey_UpArrow, id);
4837 SetKeyOwner(ImGuiKey_DownArrow, id);
4838 }
4839 if (is_multiline)
4840 {
4841 SetKeyOwner(ImGuiKey_PageUp, id);
4842 SetKeyOwner(ImGuiKey_PageDown, id);
4843 }
4844 // FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu
4845 if (is_osx)
4846 SetKeyOwner(ImGuiMod_Alt, id);
4847
4848 // Expose scroll in a manner that is agnostic to us using a child window
4849 if (is_multiline && state != NULL)
4850 state->Scroll.y = draw_window->Scroll.y;
4851
4852 // Read-only mode always ever read from source buffer. Refresh TextLen when active.
4853 if (is_readonly && state != NULL)
4854 state->TextLen = (int)ImStrlen(buf);
4855 //if (is_readonly && state != NULL)
4856 // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation.
4857 }
4858 if (state != NULL)
4859 state->TextSrc = is_readonly ? buf : state->TextA.Data;
4860
4861 // 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)
4862 if (g.ActiveId == id && state == NULL)
4863 ClearActiveID();
4864
4865 // Release focus when we click outside
4866 if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
4867 clear_active_id = true;
4868
4869 // Lock the decision of whether we are going to take the path displaying the cursor or selection
4870 bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
4871 bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
4872 bool value_changed = false;
4873 bool validated = false;
4874
4875 // Select the buffer to render.
4876 const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state;
4877 bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
4878
4879 // Password pushes a temporary font with only a fallback glyph
4880 if (is_password && !is_displaying_hint)
4881 PushPasswordFont();
4882
4883 // Word-wrapping: attempt to keep cursor in view while resizing frame/parent
4884 // FIXME-WORDWRAP: It would be better to preserve same relative offset.
4885 if (is_wordwrap && state != NULL && state->ID == id && state->WrapWidth != wrap_width)
4886 {
4887 state->CursorCenterY = true;
4888 state->WrapWidth = wrap_width;
4889 render_cursor = true;
4890 }
4891
4892 // Process mouse inputs and character inputs
4893 if (g.ActiveId == id)
4894 {
4895 IM_ASSERT(state != NULL);
4896 state->Edited = false;
4897 state->BufCapacity = buf_size;
4898 state->Flags = flags;
4899 state->WrapWidth = wrap_width;
4900
4901 // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
4902 // Down the line we should have a cleaner library-wide concept of Selected vs Active.
4903 g.ActiveIdAllowOverlap = !io.MouseDown[0];
4904
4905 // Edit in progress
4906 const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->Scroll.x;
4907 const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f));
4908
4909 if (select_all)
4910 {
4911 state->SelectAll();
4912 state->SelectedAllMouseLock = true;
4913 }
4914 else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift)
4915 {
4916 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
4917 const int multiclick_count = (io.MouseClickedCount[0] - 2);
4918 if ((multiclick_count % 2) == 0)
4919 {
4920 // Double-click: Select word
4921 // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant:
4922 // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS)
4923 const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n';
4924 if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol)
4925 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
4926 //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
4927 if (!STB_TEXT_HAS_SELECTION(state->Stb))
4928 ImStb::stb_textedit_prep_selection_at_cursor(state->Stb);
4929 state->Stb->cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb->cursor);
4930 state->Stb->select_end = state->Stb->cursor;
4931 ImStb::stb_textedit_clamp(state, state->Stb);
4932 }
4933 else
4934 {
4935 // Triple-click: Select line
4936 const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n';
4937 state->WrapWidth = 0.0f; // Temporarily disable wrapping so we use real line start.
4938 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART);
4939 state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT);
4940 state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT);
4941 state->WrapWidth = wrap_width;
4942 if (!is_eol && is_multiline)
4943 {
4944 ImSwap(state->Stb->select_start, state->Stb->select_end);
4945 state->Stb->cursor = state->Stb->select_end;
4946 }
4947 state->CursorFollow = false;
4948 }
4949 state->CursorAnimReset();
4950 }
4951 else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
4952 {
4953 if (hovered)
4954 {
4955 if (io.KeyShift)
4956 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
4957 else
4958 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
4959 state->CursorAnimReset();
4960 }
4961 }
4962 else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
4963 {
4964 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
4965 state->CursorAnimReset();
4966 state->CursorFollow = true;
4967 }
4968 if (state->SelectedAllMouseLock && !io.MouseDown[0])
4969 state->SelectedAllMouseLock = false;
4970
4971 // We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336)
4972 // (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)
4973 if ((flags & ImGuiInputTextFlags_AllowTabInput) && !is_readonly)
4974 {
4975 if (Shortcut(ImGuiKey_Tab, ImGuiInputFlags_Repeat, id))
4976 {
4977 unsigned int c = '\t'; // Insert TAB
4978 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
4979 state->OnCharPressed(c);
4980 }
4981 // FIXME: Implement Shift+Tab
4982 /*
4983 if (Shortcut(ImGuiKey_Tab | ImGuiMod_Shift, ImGuiInputFlags_Repeat, id))
4984 {
4985 }
4986 */
4987 }
4988
4989 // Process regular text input (before we check for Return because using some IME will effectively send a Return?)
4990 // 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.
4991 const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeyCtrl);
4992 if (io.InputQueueCharacters.Size > 0)
4993 {
4994 if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav)
4995 for (int n = 0; n < io.InputQueueCharacters.Size; n++)
4996 {
4997 // Insert character if they pass filtering
4998 unsigned int c = (unsigned int)io.InputQueueCharacters[n];
4999 if (c == '\t') // Skip Tab, see above.
5000 continue;
5001 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
5002 state->OnCharPressed(c);
5003 }
5004
5005 // Consume characters
5006 io.InputQueueCharacters.resize(0);
5007 }
5008 }
5009
5010 // Process other shortcuts/key-presses
5011 bool revert_edit = false;
5012 if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
5013 {
5014 IM_ASSERT(state != NULL);
5015
5016 const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1);
5017 state->Stb->row_count_per_page = row_count_per_page;
5018
5019 const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
5020 const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
5021 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
5022
5023 // 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: former would be handled by InputText)
5024 // Otherwise we could simply assume that we own the keys as we are active.
5025 const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat;
5026 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());
5027 const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection());
5028 const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly;
5029 const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
5030 const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
5031 const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id);
5032
5033 // 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.
5034 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
5035 const bool is_enter_pressed = IsKeyPressed(ImGuiKey_Enter, true) || IsKeyPressed(ImGuiKey_KeypadEnter, true);
5036 const bool is_gamepad_validate = nav_gamepad_active && (IsKeyPressed(ImGuiKey_NavGamepadActivate, false) || IsKeyPressed(ImGuiKey_NavGamepadInput, false));
5037 const bool is_cancel = Shortcut(ImGuiKey_Escape, f_repeat, id) || (nav_gamepad_active && Shortcut(ImGuiKey_NavGamepadCancel, f_repeat, id));
5038
5039 // FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of.
5040 // FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line.
5041 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); }
5042 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); }
5043 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); }
5044 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); }
5045 else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; }
5046 else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; }
5047 else if (IsKeyPressed(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
5048 else if (IsKeyPressed(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
5049 else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut)
5050 {
5051 if (!state->HasSelection())
5052 {
5053 // 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)
5054 if (is_wordmove_key_down)
5055 state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
5056 }
5057 state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask);
5058 }
5059 else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly)
5060 {
5061 if (!state->HasSelection())
5062 {
5063 if (is_wordmove_key_down)
5064 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT);
5065 else if (is_osx && io.KeyCtrl && !io.KeyAlt && !io.KeySuper)
5066 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT);
5067 }
5068 state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
5069 }
5070 else if (is_enter_pressed || is_gamepad_validate)
5071 {
5072 // Determine if we turn Enter into a \n character
5073 bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
5074 if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != io.KeyCtrl))
5075 {
5076 validated = true;
5077 if (io.ConfigInputTextEnterKeepActive && !is_multiline)
5078 state->SelectAll(); // No need to scroll
5079 else
5080 clear_active_id = true;
5081 }
5082 else if (!is_readonly)
5083 {
5084 unsigned int c = '\n'; // Insert new line
5085 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
5086 state->OnCharPressed(c);
5087 }
5088 }
5089 else if (is_cancel)
5090 {
5091 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
5092 {
5093 if (state->TextA.Data[0] != 0)
5094 {
5095 revert_edit = true;
5096 }
5097 else
5098 {
5099 render_cursor = render_selection = false;
5100 clear_active_id = true;
5101 }
5102 }
5103 else
5104 {
5105 clear_active_id = revert_edit = true;
5106 render_cursor = render_selection = false;
5107 }
5108 }
5109 else if (is_undo || is_redo)
5110 {
5111 state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
5112 state->ClearSelection();
5113 }
5114 else if (is_select_all)
5115 {
5116 state->SelectAll();
5117 state->CursorFollow = true;
5118 }
5119 else if (is_cut || is_copy)
5120 {
5121 // Cut, Copy
5122 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5123 {
5124 // SetClipboardText() only takes null terminated strings + state->TextSrc may point to read-only user buffer, so we need to make a copy.
5125 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
5126 const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
5127 g.TempBuffer.reserve(ie - ib + 1);
5128 memcpy(g.TempBuffer.Data, state->TextSrc + ib, ie - ib);
5129 g.TempBuffer.Data[ie - ib] = 0;
5130 SetClipboardText(g.TempBuffer.Data);
5131 }
5132 if (is_cut)
5133 {
5134 if (!state->HasSelection())
5135 state->SelectAll();
5136 state->CursorFollow = true;
5137 stb_textedit_cut(state, state->Stb);
5138 }
5139 }
5140 else if (is_paste)
5141 {
5142 if (const char* clipboard = GetClipboardText())
5143 {
5144 // Filter pasted buffer
5145 const int clipboard_len = (int)ImStrlen(clipboard);
5146 ImVector<char> clipboard_filtered;
5147 clipboard_filtered.reserve(clipboard_len + 1);
5148 for (const char* s = clipboard; *s != 0; )
5149 {
5150 unsigned int c;
5151 int in_len = ImTextCharFromUtf8(&c, s, NULL);
5152 s += in_len;
5153 if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
5154 continue;
5155 char c_utf8[5];
5156 ImTextCharToUtf8(c_utf8, c);
5157 int out_len = (int)ImStrlen(c_utf8);
5158 clipboard_filtered.resize(clipboard_filtered.Size + out_len);
5159 memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len);
5160 }
5161 if (clipboard_filtered.Size > 0) // If everything was filtered, ignore the pasting operation
5162 {
5163 clipboard_filtered.push_back(0);
5164 stb_textedit_paste(state, state->Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1);
5165 state->CursorFollow = true;
5166 }
5167 }
5168 }
5169
5170 // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
5171 render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
5172 }
5173
5174 // Process callbacks and apply result back to user's buffer.
5175 const char* apply_new_text = NULL;
5176 int apply_new_text_length = 0;
5177 if (g.ActiveId == id)
5178 {
5179 IM_ASSERT(state != NULL);
5180 if (revert_edit && !is_readonly)
5181 {
5182 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
5183 {
5184 // Clear input
5185 IM_ASSERT(state->TextA.Data[0] != 0);
5186 apply_new_text = "";
5187 apply_new_text_length = 0;
5188 value_changed = true;
5189 char empty_string = 0;
5190 stb_textedit_replace(state, state->Stb, &empty_string, 0);
5191 }
5192 else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0)
5193 {
5194 apply_new_text = state->TextToRevertTo.Data;
5195 apply_new_text_length = state->TextToRevertTo.Size - 1;
5196
5197 // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
5198 // Push records into the undo stack so we can CTRL+Z the revert operation itself
5199 value_changed = true;
5200 stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1);
5201 }
5202 }
5203
5204 // FIXME-OPT: We always reapply the live buffer back to the input buffer before clearing ActiveId,
5205 // even though strictly speaking it wasn't modified on this frame. Should mark dirty state from the stb_textedit callbacks.
5206 // If we do that, need to ensure that as special case, 'validated == true' also writes back.
5207 // This also allows the user to use InputText() without maintaining any user-side storage.
5208 // (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object
5209 // unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).
5210 const bool apply_edit_back_to_user_buffer = true;// !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
5211 if (apply_edit_back_to_user_buffer)
5212 {
5213 // Apply current edited text immediately.
5214 // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
5215
5216 // User callback
5217 if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0)
5218 {
5219 IM_ASSERT(callback != NULL);
5220
5221 // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
5222 ImGuiInputTextFlags event_flag = 0;
5223 ImGuiKey event_key = ImGuiKey_None;
5224 if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && Shortcut(ImGuiKey_Tab, 0, id))
5225 {
5226 event_flag = ImGuiInputTextFlags_CallbackCompletion;
5227 event_key = ImGuiKey_Tab;
5228 }
5229 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow))
5230 {
5231 event_flag = ImGuiInputTextFlags_CallbackHistory;
5232 event_key = ImGuiKey_UpArrow;
5233 }
5234 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow))
5235 {
5236 event_flag = ImGuiInputTextFlags_CallbackHistory;
5237 event_key = ImGuiKey_DownArrow;
5238 }
5239 else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited)
5240 {
5241 event_flag = ImGuiInputTextFlags_CallbackEdit;
5242 }
5243 else if (flags & ImGuiInputTextFlags_CallbackAlways)
5244 {
5245 event_flag = ImGuiInputTextFlags_CallbackAlways;
5246 }
5247
5248 if (event_flag)
5249 {
5250 ImGuiInputTextCallbackData callback_data;
5251 callback_data.Ctx = &g;
5252 callback_data.EventFlag = event_flag;
5253 callback_data.Flags = flags;
5254 callback_data.UserData = callback_user_data;
5255
5256 // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
5257 char* callback_buf = is_readonly ? buf : state->TextA.Data;
5258 IM_ASSERT(callback_buf == state->TextSrc);
5259 state->CallbackTextBackup.resize(state->TextLen + 1);
5260 memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1);
5261
5262 callback_data.EventKey = event_key;
5263 callback_data.Buf = callback_buf;
5264 callback_data.BufTextLen = state->TextLen;
5265 callback_data.BufSize = state->BufCapacity;
5266 callback_data.BufDirty = false;
5267
5268 const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
5269 const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start;
5270 const int utf8_selection_end = callback_data.SelectionEnd = state->Stb->select_end;
5271
5272 // Call user code
5273 callback(&callback_data);
5274
5275 // Read back what user may have modified
5276 callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback
5277 IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields
5278 IM_ASSERT(callback_data.BufSize == state->BufCapacity);
5279 IM_ASSERT(callback_data.Flags == flags);
5280 const bool buf_dirty = callback_data.BufDirty;
5281 if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
5282 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; }
5283 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; }
5284 if (buf_dirty)
5285 {
5286 // Callback may update buffer and thus set buf_dirty even in read-only mode.
5287 IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
5288 InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen);
5289 state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
5290 state->CursorAnimReset();
5291 }
5292 }
5293 }
5294
5295 // Will copy result string if modified
5296 if (!is_readonly && strcmp(state->TextSrc, buf) != 0)
5297 {
5298 apply_new_text = state->TextSrc;
5299 apply_new_text_length = state->TextLen;
5300 value_changed = true;
5301 }
5302 }
5303 }
5304
5305 // Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details)
5306 if (g.InputTextDeactivatedState.ID == id)
5307 {
5308 if (g.ActiveId != id && IsItemDeactivatedAfterEdit() && !is_readonly && strcmp(g.InputTextDeactivatedState.TextA.Data, buf) != 0)
5309 {
5310 apply_new_text = g.InputTextDeactivatedState.TextA.Data;
5311 apply_new_text_length = g.InputTextDeactivatedState.TextA.Size - 1;
5312 value_changed = true;
5313 //IMGUI_DEBUG_LOG("InputText(): apply Deactivated data for 0x%08X: \"%.*s\".\n", id, apply_new_text_length, apply_new_text);
5314 }
5315 g.InputTextDeactivatedState.ID = 0;
5316 }
5317
5318 // Copy result to user buffer. This can currently only happen when (g.ActiveId == id)
5319 if (apply_new_text != NULL)
5320 {
5321 //// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
5322 //// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
5323 //// without any storage on user's side.
5324 IM_ASSERT(apply_new_text_length >= 0);
5325 if (is_resizable)
5326 {
5327 ImGuiInputTextCallbackData callback_data;
5328 callback_data.Ctx = &g;
5329 callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
5330 callback_data.Flags = flags;
5331 callback_data.Buf = buf;
5332 callback_data.BufTextLen = apply_new_text_length;
5333 callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
5334 callback_data.UserData = callback_user_data;
5335 callback(&callback_data);
5336 buf = callback_data.Buf;
5337 buf_size = callback_data.BufSize;
5338 apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
5339 IM_ASSERT(apply_new_text_length <= buf_size);
5340 }
5341 //IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length);
5342
5343 // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
5344 ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
5345 }
5346
5347 // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
5348 // Otherwise request text input ahead for next frame.
5349 if (g.ActiveId == id && clear_active_id)
5350 ClearActiveID();
5351
5352 // Render frame
5353 if (!is_multiline)
5354 {
5355 RenderNavCursor(frame_bb, id);
5356 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
5357 }
5358
5359 ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
5360 ImVec2 text_size(0.0f, 0.0f);
5361 ImRect 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
5362 if (is_multiline)
5363 clip_rect.ClipWith(draw_window->ClipRect);
5364
5365 // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
5366 // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
5367 // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
5368 const int buf_display_max_length = 2 * 1024 * 1024;
5369 const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
5370 const char* buf_display_end = NULL; // We have specialized paths below for setting the length
5371
5372 // Display hint when contents is empty
5373 // At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368)
5374 const bool new_is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
5375 if (new_is_displaying_hint != is_displaying_hint)
5376 {
5377 if (is_password && !is_displaying_hint)
5378 PopPasswordFont();
5379 is_displaying_hint = new_is_displaying_hint;
5380 if (is_password && !is_displaying_hint)
5381 PushPasswordFont();
5382 }
5383 if (is_displaying_hint)
5384 {
5385 buf_display = hint;
5386 buf_display_end = hint + ImStrlen(hint);
5387 }
5388 else
5389 {
5390 if (render_cursor || render_selection || g.ActiveId == id)
5391 buf_display_end = buf_display + state->TextLen; //-V595
5392 else if (is_multiline && !is_wordwrap)
5393 buf_display_end = NULL; // Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path.
5394 else
5395 buf_display_end = buf_display + ImStrlen(buf_display);
5396 }
5397
5398 // Calculate visibility
5399 int line_visible_n0 = 0, line_visible_n1 = 1;
5400 if (is_multiline)
5401 CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1);
5402
5403 // Build line index for easy data access (makes code below simpler and faster)
5404 ImGuiTextIndex* line_index = &g.InputTextLineIndex;
5405 line_index->Offsets.resize(0);
5406 int line_count = 1;
5407 if (is_multiline)
5408 line_count = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, (render_cursor && state && state->CursorFollow) ? INT_MAX : line_visible_n1 + 1, buf_display_end ? NULL : &buf_display_end);
5409 line_index->EndOffset = (int)(buf_display_end - buf_display);
5410 line_visible_n1 = ImMin(line_visible_n1, line_count);
5411
5412 // Store text height (we don't need width)
5413 text_size = ImVec2(inner_size.x, line_count * g.FontSize);
5414 //GetForegroundDrawList()->AddRect(draw_pos + ImVec2(0, line_visible_n0 * g.FontSize), draw_pos + ImVec2(frame_size.x, line_visible_n1 * g.FontSize), IM_COL32(255, 0, 0, 255));
5415
5416 // Calculate blinking cursor position
5417 const ImVec2 cursor_offset = render_cursor && state ? InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state->Stb->cursor) : ImVec2(0.0f, 0.0f);
5418 ImVec2 draw_scroll;
5419
5420 // Render text. We currently only render selection when the widget is active or while scrolling.
5421 const ImU32 text_col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
5422 if (render_cursor || render_selection)
5423 {
5424 // Render text (with cursor and selection)
5425 // This is going to be messy. We need to:
5426 // - Display the text (this alone can be more easily clipped)
5427 // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
5428 // - Measure text height (for scrollbar)
5429 // 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)
5430 // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
5431 IM_ASSERT(state != NULL);
5432 state->LineCount = line_count;
5433
5434 // Scroll
5435 float new_scroll_y = scroll_y;
5436 if (render_cursor && state->CursorFollow)
5437 {
5438 // Horizontal scroll in chunks of quarter width
5439 if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
5440 {
5441 const float scroll_increment_x = inner_size.x * 0.25f;
5442 const float visible_width = inner_size.x - style.FramePadding.x;
5443 if (cursor_offset.x < state->Scroll.x)
5444 state->Scroll.x = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x));
5445 else if (cursor_offset.x - visible_width >= state->Scroll.x)
5446 state->Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x);
5447 }
5448 else
5449 {
5450 state->Scroll.x = 0.0f;
5451 }
5452
5453 // Vertical scroll
5454 if (is_multiline)
5455 {
5456 // Test if cursor is vertically visible
5457 if (cursor_offset.y - g.FontSize < scroll_y)
5458 new_scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
5459 else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y)
5460 new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;
5461 }
5462 state->CursorFollow = false;
5463 }
5464 if (state->CursorCenterY)
5465 {
5466 if (is_multiline)
5467 new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5f - style.FramePadding.y);
5468 state->CursorCenterY = false;
5469 render_cursor = false;
5470 }
5471 if (new_scroll_y != scroll_y)
5472 {
5473 const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);
5474 scroll_y = ImClamp(new_scroll_y, 0.0f, scroll_max_y);
5475 draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
5476 draw_window->Scroll.y = scroll_y;
5477 CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize, &line_visible_n0, &line_visible_n1);
5478 line_visible_n1 = ImMin(line_visible_n1, line_count);
5479 }
5480
5481 // Draw selection
5482 draw_scroll.x = state->Scroll.x;
5483 if (render_selection)
5484 {
5485 const 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.
5486 const 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.
5487 const float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
5488 const float bg_eol_width = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
5489
5490 const char* text_selected_begin = buf_display + ImMin(state->Stb->select_start, state->Stb->select_end);
5491 const char* text_selected_end = buf_display + ImMax(state->Stb->select_start, state->Stb->select_end);
5492 for (int line_n = line_visible_n0; line_n < line_visible_n1; line_n++)
5493 {
5494 const char* p = line_index->get_line_begin(buf_display, line_n);
5495 const char* p_eol = line_index->get_line_end(buf_display, line_n);
5496 const bool p_eol_is_wrap = (p_eol < buf_display_end && *p_eol != '\n');
5497 if (p_eol_is_wrap)
5498 p_eol++;
5499 const char* line_selected_begin = (text_selected_begin > p) ? text_selected_begin : p;
5500 const char* line_selected_end = (text_selected_end < p_eol) ? text_selected_end : p_eol;
5501
5502 float rect_width = 0.0f;
5503 if (line_selected_begin < line_selected_end)
5504 rect_width += CalcTextSize(line_selected_begin, line_selected_end).x;
5505 if (text_selected_begin <= p_eol && text_selected_end > p_eol && !p_eol_is_wrap)
5506 rect_width += bg_eol_width; // So we can see selected empty lines
5507 if (rect_width == 0.0f)
5508 continue;
5509
5510 ImRect rect;
5511 rect.Min.x = draw_pos.x - draw_scroll.x + CalcTextSize(p, line_selected_begin).x;
5512 rect.Min.y = draw_pos.y - draw_scroll.y + line_n * g.FontSize;
5513 rect.Max.x = rect.Min.x + rect_width;
5514 rect.Max.y = rect.Min.y + bg_offy_dn + g.FontSize;
5515 rect.Min.y -= bg_offy_up;
5516 rect.ClipWith(clip_rect);
5517 draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
5518 }
5519 }
5520 }
5521
5522 // Find render position for right alignment (single-line only)
5523 if (g.ActiveId != id && flags & ImGuiInputTextFlags_ElideLeft)
5524 draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x);
5525 //draw_scroll.x = state->Scroll.x; // Preserve scroll when inactive?
5526
5527 // Render text
5528 if ((is_multiline || (buf_display_end - buf_display) < buf_display_max_length) && (text_col & IM_COL32_A_MASK) && (line_visible_n0 < line_visible_n1))
5529 g.Font->RenderText(draw_window->DrawList, g.FontSize,
5530 draw_pos - draw_scroll + ImVec2(0.0f, line_visible_n0 * g.FontSize),
5531 text_col, clip_rect.AsVec4(),
5532 line_index->get_line_begin(buf_display, line_visible_n0),
5533 line_index->get_line_end(buf_display, line_visible_n1 - 1),
5534 wrap_width, ImDrawTextFlags_WrapKeepBlanks);
5535
5536 // Render blinking cursor
5537 if (render_cursor)
5538 {
5539 state->CursorAnim += io.DeltaTime;
5540 bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
5541 ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll);
5542 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);
5543 if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
5544 draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031)
5545
5546 // 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.)
5547 // This is required for some backends (SDL3) to start emitting character/text inputs.
5548 // As per #6341, make sure we don't set that on the deactivating frame.
5549 if (!is_readonly && g.ActiveId == id)
5550 {
5551 ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler)
5552 ime_data->WantVisible = true;
5553 ime_data->WantTextInput = true;
5554 ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
5555 ime_data->InputLineHeight = g.FontSize;
5556 ime_data->ViewportId = window->Viewport->ID;
5557 }
5558 }
5559
5560 if (is_password && !is_displaying_hint)
5561 PopPasswordFont();
5562
5563 if (is_multiline)
5564 {
5565 // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)...
5566 Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y));
5567 g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop;
5568 EndChild();
5569 item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow);
5570
5571 // ...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...
5572 // FIXME: This quite messy/tricky, should attempt to get rid of the child window.
5573 EndGroup();
5574 if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y))
5575 {
5576 g.LastItemData.ID = id;
5577 g.LastItemData.ItemFlags = item_data_backup.ItemFlags;
5578 g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
5579 }
5580 }
5581 if (state)
5582 state->TextSrc = NULL;
5583
5584 // Log as text
5585 if (g.LogEnabled && (!is_password || is_displaying_hint))
5586 {
5587 LogSetNextTextDecoration("{", "}");
5588 LogRenderedText(&draw_pos, buf_display, buf_display_end);
5589 }
5590
5591 if (label_size.x > 0)
5592 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
5593
5594 if (value_changed)
5595 MarkItemEdited(id);
5596
5597 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
5598 if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
5599 return validated;
5600 else
5601 return value_changed;
5602 }
5603
5604 void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
5605 {
5606 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5607 ImGuiContext& g = *GImGui;
5608 ImStb::STB_TexteditState* stb_state = state->Stb;
5609 ImStb::StbUndoState* undo_state = &stb_state->undostate;
5610 Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
5611 DebugLocateItemOnHover(state->ID);
5612 Text("TextLen: %d, Cursor: %d%s, Selection: %d..%d", state->TextLen, stb_state->cursor,
5613 (state->Flags & ImGuiInputTextFlags_WordWrap) ? (state->LastMoveDirectionLR == ImGuiDir_Left ? " (L)" : " (R)") : "",
5614 stb_state->select_start, stb_state->select_end);
5615 Text("BufCapacity: %d, LineCount: %d", state->BufCapacity, state->LineCount);
5616 Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
5617 Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
5618 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);
5619 if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state
5620 {
5621 PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
5622 for (int n = 0; n < IMSTB_TEXTEDIT_UNDOSTATECOUNT; n++)
5623 {
5624 ImStb::StbUndoRecord* undo_rec = &undo_state->undo_rec[n];
5625 const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' ';
5626 if (undo_rec_type == ' ')
5627 BeginDisabled();
5628 const int buf_preview_len = (undo_rec_type != ' ' && undo_rec->char_storage != -1) ? undo_rec->insert_length : 0;
5629 const char* buf_preview_str = undo_state->undo_char + undo_rec->char_storage;
5630 Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"",
5631 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);
5632 if (undo_rec_type == ' ')
5633 EndDisabled();
5634 }
5635 PopStyleVar();
5636 }
5637 EndChild();
5638 #else
5639 IM_UNUSED(state);
5640 #endif
5641 }
5642
5643 //-------------------------------------------------------------------------
5644 // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
5645 //-------------------------------------------------------------------------
5646 // - ColorEdit3()
5647 // - ColorEdit4()
5648 // - ColorPicker3()
5649 // - RenderColorRectWithAlphaCheckerboard() [Internal]
5650 // - ColorPicker4()
5651 // - ColorButton()
5652 // - SetColorEditOptions()
5653 // - ColorTooltip() [Internal]
5654 // - ColorEditOptionsPopup() [Internal]
5655 // - ColorPickerOptionsPopup() [Internal]
5656 //-------------------------------------------------------------------------
5657
5658 bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
5659 {
5660 return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
5661 }
5662
5663 static void ColorEditRestoreH(const float* col, float* H)
5664 {
5665 ImGuiContext& g = *GImGui;
5666 IM_ASSERT(g.ColorEditCurrentID != 0);
5667 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5668 return;
5669 *H = g.ColorEditSavedHue;
5670 }
5671
5672 // ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation.
5673 // Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting.
5674 static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V)
5675 {
5676 ImGuiContext& g = *GImGui;
5677 IM_ASSERT(g.ColorEditCurrentID != 0);
5678 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5679 return;
5680
5681 // When S == 0, H is undefined.
5682 // When H == 1 it wraps around to 0.
5683 if (*S == 0.0f || (*H == 0.0f && g.ColorEditSavedHue == 1))
5684 *H = g.ColorEditSavedHue;
5685
5686 // When V == 0, S is undefined.
5687 if (*V == 0.0f)
5688 *S = g.ColorEditSavedSat;
5689 }
5690
5691 // Edit colors components (each component in 0.0f..1.0f range).
5692 // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
5693 // 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.
5694 bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
5695 {
5696 ImGuiWindow* window = GetCurrentWindow();
5697 if (window->SkipItems)
5698 return false;
5699
5700 ImGuiContext& g = *GImGui;
5701 const ImGuiStyle& style = g.Style;
5702 const float square_sz = GetFrameHeight();
5703 const char* label_display_end = FindRenderedTextEnd(label);
5704 float w_full = CalcItemWidth();
5705 g.NextItemData.ClearFlags();
5706
5707 BeginGroup();
5708 PushID(label);
5709 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
5710 if (set_current_color_edit_id)
5711 g.ColorEditCurrentID = window->IDStack.back();
5712
5713 // If we're not showing any slider there's no point in doing any HSV conversions
5714 const ImGuiColorEditFlags flags_untouched = flags;
5715 if (flags & ImGuiColorEditFlags_NoInputs)
5716 flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
5717
5718 // Context menu: display and modify options (before defaults are applied)
5719 if (!(flags & ImGuiColorEditFlags_NoOptions))
5720 ColorEditOptionsPopup(col, flags);
5721
5722 // Read stored options
5723 if (!(flags & ImGuiColorEditFlags_DisplayMask_))
5724 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_);
5725 if (!(flags & ImGuiColorEditFlags_DataTypeMask_))
5726 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_);
5727 if (!(flags & ImGuiColorEditFlags_PickerMask_))
5728 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_);
5729 if (!(flags & ImGuiColorEditFlags_InputMask_))
5730 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_);
5731 flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_));
5732 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected
5733 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
5734
5735 const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
5736 const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
5737 const int components = alpha ? 4 : 3;
5738 const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
5739 const float w_inputs = ImMax(w_full - w_button, 1.0f);
5740 w_full = w_inputs + w_button;
5741
5742 // Convert to the formats we need
5743 float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
5744 if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
5745 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5746 else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
5747 {
5748 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
5749 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5750 ColorEditRestoreHS(col, &f[0], &f[1], &f[2]);
5751 }
5752 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]) };
5753
5754 bool value_changed = false;
5755 bool value_changed_as_float = false;
5756
5757 const ImVec2 pos = window->DC.CursorPos;
5758 const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;
5759 window->DC.CursorPos.x = pos.x + inputs_offset_x;
5760
5761 if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5762 {
5763 // RGB/HSV 0..255 Sliders
5764 const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1);
5765
5766 const bool hide_prefix = (IM_TRUNC(w_items / components) <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
5767 static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
5768 static const char* fmt_table_int[3][4] =
5769 {
5770 { "%3d", "%3d", "%3d", "%3d" }, // Short display
5771 { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
5772 { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
5773 };
5774 static const char* fmt_table_float[3][4] =
5775 {
5776 { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
5777 { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
5778 { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
5779 };
5780 const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
5781
5782 float prev_split = 0.0f;
5783 for (int n = 0; n < components; n++)
5784 {
5785 if (n > 0)
5786 SameLine(0, style.ItemInnerSpacing.x);
5787 float next_split = IM_TRUNC(w_items * (n + 1) / components);
5788 SetNextItemWidth(ImMax(next_split - prev_split, 1.0f));
5789 prev_split = next_split;
5790
5791 // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0.
5792 if (flags & ImGuiColorEditFlags_Float)
5793 {
5794 value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
5795 value_changed_as_float |= value_changed;
5796 }
5797 else
5798 {
5799 value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
5800 }
5801 if (!(flags & ImGuiColorEditFlags_NoOptions))
5802 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5803 }
5804 }
5805 else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5806 {
5807 // RGB Hexadecimal Input
5808 char buf[64];
5809 if (alpha)
5810 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));
5811 else
5812 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255));
5813 SetNextItemWidth(w_inputs);
5814 if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsUppercase))
5815 {
5816 value_changed = true;
5817 char* p = buf;
5818 while (*p == '#' || ImCharIsBlankA(*p))
5819 p++;
5820 i[0] = i[1] = i[2] = 0;
5821 i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha)
5822 int r;
5823 if (alpha)
5824 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)
5825 else
5826 r = sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
5827 IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'.
5828 }
5829 if (!(flags & ImGuiColorEditFlags_NoOptions))
5830 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5831 }
5832
5833 ImGuiWindow* picker_active_window = NULL;
5834 if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
5835 {
5836 const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;
5837 window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);
5838
5839 const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
5840 if (ColorButton("##ColorButton", col_v4, flags))
5841 {
5842 if (!(flags & ImGuiColorEditFlags_NoPicker))
5843 {
5844 // Store current color and open a picker
5845 g.ColorPickerRef = col_v4;
5846 OpenPopup("picker");
5847 SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y));
5848 }
5849 }
5850 if (!(flags & ImGuiColorEditFlags_NoOptions))
5851 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5852
5853 if (BeginPopup("picker"))
5854 {
5855 if (g.CurrentWindow->BeginCount == 1)
5856 {
5857 picker_active_window = g.CurrentWindow;
5858 if (label != label_display_end)
5859 {
5860 TextEx(label, label_display_end);
5861 Spacing();
5862 }
5863 ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
5864 ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
5865 SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
5866 value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
5867 }
5868 EndPopup();
5869 }
5870 }
5871
5872 if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
5873 {
5874 // Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left),
5875 // but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this.
5876 SameLine(0.0f, style.ItemInnerSpacing.x);
5877 window->DC.CursorPos.x = pos.x + ((flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x);
5878 TextEx(label, label_display_end);
5879 }
5880
5881 // Convert back
5882 if (value_changed && picker_active_window == NULL)
5883 {
5884 if (!value_changed_as_float)
5885 for (int n = 0; n < 4; n++)
5886 f[n] = i[n] / 255.0f;
5887 if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
5888 {
5889 g.ColorEditSavedHue = f[0];
5890 g.ColorEditSavedSat = f[1];
5891 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5892 g.ColorEditSavedID = g.ColorEditCurrentID;
5893 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0));
5894 }
5895 if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
5896 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5897
5898 col[0] = f[0];
5899 col[1] = f[1];
5900 col[2] = f[2];
5901 if (alpha)
5902 col[3] = f[3];
5903 }
5904
5905 if (set_current_color_edit_id)
5906 g.ColorEditCurrentID = 0;
5907 PopID();
5908 EndGroup();
5909
5910 // Drag and Drop Target
5911 // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
5912 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
5913 {
5914 bool accepted_drag_drop = false;
5915 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
5916 {
5917 memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 //-V1086
5918 value_changed = accepted_drag_drop = true;
5919 }
5920 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
5921 {
5922 memcpy((float*)col, payload->Data, sizeof(float) * components);
5923 value_changed = accepted_drag_drop = true;
5924 }
5925
5926 // Drag-drop payloads are always RGB
5927 if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
5928 ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
5929 EndDragDropTarget();
5930 }
5931
5932 // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
5933 if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
5934 g.LastItemData.ID = g.ActiveId;
5935
5936 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
5937 MarkItemEdited(g.LastItemData.ID);
5938
5939 return value_changed;
5940 }
5941
5942 bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
5943 {
5944 float col4[4] = { col[0], col[1], col[2], 1.0f };
5945 if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
5946 return false;
5947 col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
5948 return true;
5949 }
5950
5951 // Helper for ColorPicker4()
5952 static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha)
5953 {
5954 ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha);
5955 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));
5956 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8));
5957 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));
5958 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8));
5959 }
5960
5961 // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
5962 // (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.)
5963 // 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..)
5964 // 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)
5965 bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
5966 {
5967 ImGuiContext& g = *GImGui;
5968 ImGuiWindow* window = GetCurrentWindow();
5969 if (window->SkipItems)
5970 return false;
5971
5972 ImDrawList* draw_list = window->DrawList;
5973 ImGuiStyle& style = g.Style;
5974 ImGuiIO& io = g.IO;
5975
5976 const float width = CalcItemWidth();
5977 const bool is_readonly = ((g.NextItemData.ItemFlags | g.CurrentItemFlags) & ImGuiItemFlags_ReadOnly) != 0;
5978 g.NextItemData.ClearFlags();
5979
5980 PushID(label);
5981 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
5982 if (set_current_color_edit_id)
5983 g.ColorEditCurrentID = window->IDStack.back();
5984 BeginGroup();
5985
5986 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
5987 flags |= ImGuiColorEditFlags_NoSmallPreview;
5988
5989 // Context menu: display and store options.
5990 if (!(flags & ImGuiColorEditFlags_NoOptions))
5991 ColorPickerOptionsPopup(col, flags);
5992
5993 // Read stored options
5994 if (!(flags & ImGuiColorEditFlags_PickerMask_))
5995 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_;
5996 if (!(flags & ImGuiColorEditFlags_InputMask_))
5997 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_;
5998 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected
5999 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
6000 if (!(flags & ImGuiColorEditFlags_NoOptions))
6001 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
6002
6003 // Setup
6004 int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
6005 bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
6006 ImVec2 picker_pos = window->DC.CursorPos;
6007 float square_sz = GetFrameHeight();
6008 float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
6009 float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
6010 float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
6011 float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
6012 float bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20f);
6013
6014 float backup_initial_col[4];
6015 memcpy(backup_initial_col, col, components * sizeof(float));
6016
6017 float wheel_thickness = sv_picker_size * 0.08f;
6018 float wheel_r_outer = sv_picker_size * 0.50f;
6019 float wheel_r_inner = wheel_r_outer - wheel_thickness;
6020 ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f);
6021
6022 // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
6023 float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
6024 ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
6025 ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
6026 ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
6027
6028 float H = col[0], S = col[1], V = col[2];
6029 float R = col[0], G = col[1], B = col[2];
6030 if (flags & ImGuiColorEditFlags_InputRGB)
6031 {
6032 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
6033 ColorConvertRGBtoHSV(R, G, B, H, S, V);
6034 ColorEditRestoreHS(col, &H, &S, &V);
6035 }
6036 else if (flags & ImGuiColorEditFlags_InputHSV)
6037 {
6038 ColorConvertHSVtoRGB(H, S, V, R, G, B);
6039 }
6040
6041 bool value_changed = false, value_changed_h = false, value_changed_sv = false;
6042
6043 PushItemFlag(ImGuiItemFlags_NoNav, true);
6044 if (flags & ImGuiColorEditFlags_PickerHueWheel)
6045 {
6046 // Hue wheel + SV triangle logic
6047 InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
6048 if (IsItemActive() && !is_readonly)
6049 {
6050 ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
6051 ImVec2 current_off = g.IO.MousePos - wheel_center;
6052 float initial_dist2 = ImLengthSqr(initial_off);
6053 if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1))
6054 {
6055 // Interactive with Hue wheel
6056 H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f;
6057 if (H < 0.0f)
6058 H += 1.0f;
6059 value_changed = value_changed_h = true;
6060 }
6061 float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
6062 float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
6063 if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
6064 {
6065 // Interacting with SV triangle
6066 ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
6067 if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
6068 current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
6069 float uu, vv, ww;
6070 ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
6071 V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
6072 S = ImClamp(uu / V, 0.0001f, 1.0f);
6073 value_changed = value_changed_sv = true;
6074 }
6075 }
6076 if (!(flags & ImGuiColorEditFlags_NoOptions))
6077 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
6078 }
6079 else if (flags & ImGuiColorEditFlags_PickerHueBar)
6080 {
6081 // SV rectangle logic
6082 InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
6083 if (IsItemActive() && !is_readonly)
6084 {
6085 S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1));
6086 V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6087 ColorEditRestoreH(col, &H); // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square.
6088 value_changed = value_changed_sv = true;
6089 }
6090 if (!(flags & ImGuiColorEditFlags_NoOptions))
6091 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
6092
6093 // Hue bar logic
6094 SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
6095 InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
6096 if (IsItemActive() && !is_readonly)
6097 {
6098 H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6099 value_changed = value_changed_h = true;
6100 }
6101 }
6102
6103 // Alpha bar logic
6104 if (alpha_bar)
6105 {
6106 SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
6107 InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
6108 if (IsItemActive())
6109 {
6110 col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6111 value_changed = true;
6112 }
6113 }
6114 PopItemFlag(); // ImGuiItemFlags_NoNav
6115
6116 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
6117 {
6118 SameLine(0, style.ItemInnerSpacing.x);
6119 BeginGroup();
6120 }
6121
6122 if (!(flags & ImGuiColorEditFlags_NoLabel))
6123 {
6124 const char* label_display_end = FindRenderedTextEnd(label);
6125 if (label != label_display_end)
6126 {
6127 if ((flags & ImGuiColorEditFlags_NoSidePreview))
6128 SameLine(0, style.ItemInnerSpacing.x);
6129 TextEx(label, label_display_end);
6130 }
6131 }
6132
6133 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
6134 {
6135 PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
6136 ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6137 if ((flags & ImGuiColorEditFlags_NoLabel))
6138 Text("Current");
6139
6140 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoTooltip;
6141 ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
6142 if (ref_col != NULL)
6143 {
6144 Text("Original");
6145 ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
6146 if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
6147 {
6148 memcpy(col, ref_col, components * sizeof(float));
6149 value_changed = true;
6150 }
6151 }
6152 PopItemFlag();
6153 EndGroup();
6154 }
6155
6156 // Convert back color to RGB
6157 if (value_changed_h || value_changed_sv)
6158 {
6159 if (flags & ImGuiColorEditFlags_InputRGB)
6160 {
6161 ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]);
6162 g.ColorEditSavedHue = H;
6163 g.ColorEditSavedSat = S;
6164 g.ColorEditSavedID = g.ColorEditCurrentID;
6165 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0));
6166 }
6167 else if (flags & ImGuiColorEditFlags_InputHSV)
6168 {
6169 col[0] = H;
6170 col[1] = S;
6171 col[2] = V;
6172 }
6173 }
6174
6175 // R,G,B and H,S,V slider color editor
6176 bool value_changed_fix_hue_wrap = false;
6177 if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
6178 {
6179 PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
6180 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview;
6181 ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
6182 if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6183 if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
6184 {
6185 // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
6186 // 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)
6187 value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
6188 value_changed = true;
6189 }
6190 if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6191 value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
6192 if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6193 value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
6194 PopItemWidth();
6195 }
6196
6197 // Try to cancel hue wrap (after ColorEdit4 call), if any
6198 if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
6199 {
6200 float new_H, new_S, new_V;
6201 ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
6202 if (new_H <= 0 && H > 0)
6203 {
6204 if (new_V <= 0 && V != new_V)
6205 ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
6206 else if (new_S <= 0)
6207 ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
6208 }
6209 }
6210
6211 if (value_changed)
6212 {
6213 if (flags & ImGuiColorEditFlags_InputRGB)
6214 {
6215 R = col[0];
6216 G = col[1];
6217 B = col[2];
6218 ColorConvertRGBtoHSV(R, G, B, H, S, V);
6219 ColorEditRestoreHS(col, &H, &S, &V); // Fix local Hue as display below will use it immediately.
6220 }
6221 else if (flags & ImGuiColorEditFlags_InputHSV)
6222 {
6223 H = col[0];
6224 S = col[1];
6225 V = col[2];
6226 ColorConvertHSVtoRGB(H, S, V, R, G, B);
6227 }
6228 }
6229
6230 const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha);
6231 const ImU32 col_black = IM_COL32(0,0,0,style_alpha8);
6232 const ImU32 col_white = IM_COL32(255,255,255,style_alpha8);
6233 const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8);
6234 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) };
6235
6236 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);
6237 ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
6238 ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!!
6239
6240 ImVec2 sv_cursor_pos;
6241
6242 if (flags & ImGuiColorEditFlags_PickerHueWheel)
6243 {
6244 // Render Hue Wheel
6245 const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
6246 const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
6247 for (int n = 0; n < 6; n++)
6248 {
6249 const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
6250 const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
6251 const int vert_start_idx = draw_list->VtxBuffer.Size;
6252 draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
6253 draw_list->PathStroke(col_white, 0, wheel_thickness);
6254 const int vert_end_idx = draw_list->VtxBuffer.Size;
6255
6256 // Paint colors over existing vertices
6257 ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
6258 ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
6259 ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]);
6260 }
6261
6262 // Render Cursor + preview on Hue Wheel
6263 float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
6264 float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
6265 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);
6266 float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
6267 int hue_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(hue_cursor_rad); // Lock segment count so the +1 one matches others.
6268 draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
6269 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments);
6270 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments);
6271
6272 // Render SV triangle (rotated according to hue)
6273 ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
6274 ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
6275 ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
6276 ImVec2 uv_white = GetFontTexUvWhitePixel();
6277 draw_list->PrimReserve(3, 3);
6278 draw_list->PrimVtx(tra, uv_white, hue_color32);
6279 draw_list->PrimVtx(trb, uv_white, col_black);
6280 draw_list->PrimVtx(trc, uv_white, col_white);
6281 draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f);
6282 sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
6283 }
6284 else if (flags & ImGuiColorEditFlags_PickerHueBar)
6285 {
6286 // Render SV Square
6287 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white);
6288 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black);
6289 RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);
6290 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
6291 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);
6292
6293 // Render Hue Bar
6294 for (int i = 0; i < 6; ++i)
6295 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]);
6296 float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size);
6297 RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
6298 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);
6299 }
6300
6301 // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
6302 float sv_cursor_rad = value_changed_sv ? wheel_thickness * 0.55f : wheel_thickness * 0.40f;
6303 int sv_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(sv_cursor_rad); // Lock segment count so the +1 one matches others.
6304 draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments);
6305 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments);
6306 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments);
6307
6308 // Render alpha bar
6309 if (alpha_bar)
6310 {
6311 float alpha = ImSaturate(col[3]);
6312 ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
6313 RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
6314 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);
6315 float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size);
6316 RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
6317 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);
6318 }
6319
6320 EndGroup();
6321
6322 if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
6323 value_changed = false;
6324 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
6325 MarkItemEdited(g.LastItemData.ID);
6326
6327 if (set_current_color_edit_id)
6328 g.ColorEditCurrentID = 0;
6329 PopID();
6330
6331 return value_changed;
6332 }
6333
6334 // A little color square. Return true when clicked.
6335 // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
6336 // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
6337 // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
6338 bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg)
6339 {
6340 ImGuiWindow* window = GetCurrentWindow();
6341 if (window->SkipItems)
6342 return false;
6343
6344 ImGuiContext& g = *GImGui;
6345 const ImGuiID id = window->GetID(desc_id);
6346 const float default_size = GetFrameHeight();
6347 const ImVec2 size(size_arg.x == 0.0f ? default_size : size_arg.x, size_arg.y == 0.0f ? default_size : size_arg.y);
6348 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
6349 ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
6350 if (!ItemAdd(bb, id))
6351 return false;
6352
6353 bool hovered, held;
6354 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
6355
6356 if (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque))
6357 flags &= ~(ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf);
6358
6359 ImVec4 col_rgb = col;
6360 if (flags & ImGuiColorEditFlags_InputHSV)
6361 ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
6362
6363 ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
6364 float grid_step = ImMin(size.x, size.y) / 2.99f;
6365 float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
6366 ImRect bb_inner = bb;
6367 float off = 0.0f;
6368 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6369 {
6370 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.
6371 bb_inner.Expand(off);
6372 }
6373 if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
6374 {
6375 float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);
6376 if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
6377 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);
6378 else
6379 window->DrawList->AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight);
6380 window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft);
6381 }
6382 else
6383 {
6384 // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
6385 ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaOpaque) ? col_rgb_without_alpha : col_rgb;
6386 if (col_source.w < 1.0f && (flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
6387 RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
6388 else
6389 window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);
6390 }
6391 RenderNavCursor(bb, id);
6392 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6393 {
6394 if (g.Style.FrameBorderSize > 0.0f)
6395 RenderFrameBorder(bb.Min, bb.Max, rounding);
6396 else
6397 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI
6398 }
6399
6400 // Drag and Drop Source
6401 // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
6402 if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
6403 {
6404 if (flags & ImGuiColorEditFlags_NoAlpha)
6405 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
6406 else
6407 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
6408 ColorButton(desc_id, col, flags);
6409 SameLine();
6410 TextEx("Color");
6411 EndDragDropSource();
6412 }
6413
6414 // Tooltip
6415 if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip))
6416 ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_));
6417
6418 return pressed;
6419 }
6420
6421 // Initialize/override default color options
6422 void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
6423 {
6424 ImGuiContext& g = *GImGui;
6425 if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6426 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_;
6427 if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0)
6428 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_;
6429 if ((flags & ImGuiColorEditFlags_PickerMask_) == 0)
6430 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_;
6431 if ((flags & ImGuiColorEditFlags_InputMask_) == 0)
6432 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_;
6433 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected
6434 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_)); // Check only 1 option is selected
6435 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check only 1 option is selected
6436 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check only 1 option is selected
6437 g.ColorEditOptions = flags;
6438 }
6439
6440 // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
6441 void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
6442 {
6443 ImGuiContext& g = *GImGui;
6444
6445 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
6446 return;
6447 const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
6448 if (text_end > text)
6449 {
6450 TextEx(text, text_end);
6451 Separator();
6452 }
6453
6454 ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
6455 ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6456 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]);
6457 ImGuiColorEditFlags flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_;
6458 ColorButton("##preview", cf, (flags & flags_to_forward) | ImGuiColorEditFlags_NoTooltip, sz);
6459 SameLine();
6460 if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_))
6461 {
6462 if (flags & ImGuiColorEditFlags_NoAlpha)
6463 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]);
6464 else
6465 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]);
6466 }
6467 else if (flags & ImGuiColorEditFlags_InputHSV)
6468 {
6469 if (flags & ImGuiColorEditFlags_NoAlpha)
6470 Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
6471 else
6472 Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
6473 }
6474 EndTooltip();
6475 }
6476
6477 void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
6478 {
6479 bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_);
6480 bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_);
6481 if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
6482 return;
6483
6484 ImGuiContext& g = *GImGui;
6485 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6486 ImGuiColorEditFlags opts = g.ColorEditOptions;
6487 if (allow_opt_inputs)
6488 {
6489 if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB;
6490 if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV;
6491 if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex;
6492 }
6493 if (allow_opt_datatype)
6494 {
6495 if (allow_opt_inputs) Separator();
6496 if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8;
6497 if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float;
6498 }
6499
6500 if (allow_opt_inputs || allow_opt_datatype)
6501 Separator();
6502 if (Button("Copy as..", ImVec2(-1, 0)))
6503 OpenPopup("Copy");
6504 if (BeginPopup("Copy"))
6505 {
6506 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]);
6507 char buf[64];
6508 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6509 if (Selectable(buf))
6510 SetClipboardText(buf);
6511 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
6512 if (Selectable(buf))
6513 SetClipboardText(buf);
6514 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb);
6515 if (Selectable(buf))
6516 SetClipboardText(buf);
6517 if (!(flags & ImGuiColorEditFlags_NoAlpha))
6518 {
6519 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca);
6520 if (Selectable(buf))
6521 SetClipboardText(buf);
6522 }
6523 EndPopup();
6524 }
6525
6526 g.ColorEditOptions = opts;
6527 PopItemFlag();
6528 EndPopup();
6529 }
6530
6531 void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
6532 {
6533 bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_);
6534 bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
6535 if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
6536 return;
6537
6538 ImGuiContext& g = *GImGui;
6539 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6540 if (allow_opt_picker)
6541 {
6542 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
6543 PushItemWidth(picker_size.x);
6544 for (int picker_type = 0; picker_type < 2; picker_type++)
6545 {
6546 // Draw small/thumbnail version of each picker type (over an invisible button for selection)
6547 if (picker_type > 0) Separator();
6548 PushID(picker_type);
6549 ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha);
6550 if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
6551 if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
6552 ImVec2 backup_pos = GetCursorScreenPos();
6553 if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
6554 g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_);
6555 SetCursorScreenPos(backup_pos);
6556 ImVec4 previewing_ref_col;
6557 memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
6558 ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags);
6559 PopID();
6560 }
6561 PopItemWidth();
6562 }
6563 if (allow_opt_alpha_bar)
6564 {
6565 if (allow_opt_picker) Separator();
6566 CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
6567 }
6568 PopItemFlag();
6569 EndPopup();
6570 }
6571
6572 //-------------------------------------------------------------------------
6573 // [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
6574 //-------------------------------------------------------------------------
6575 // - TreeNode()
6576 // - TreeNodeV()
6577 // - TreeNodeEx()
6578 // - TreeNodeExV()
6579 // - TreeNodeStoreStackData() [Internal]
6580 // - TreeNodeBehavior() [Internal]
6581 // - TreePush()
6582 // - TreePop()
6583 // - GetTreeNodeToLabelSpacing()
6584 // - SetNextItemOpen()
6585 // - CollapsingHeader()
6586 //-------------------------------------------------------------------------
6587
6588 bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
6589 {
6590 va_list args;
6591 va_start(args, fmt);
6592 bool is_open = TreeNodeExV(str_id, 0, fmt, args);
6593 va_end(args);
6594 return is_open;
6595 }
6596
6597 bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
6598 {
6599 va_list args;
6600 va_start(args, fmt);
6601 bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
6602 va_end(args);
6603 return is_open;
6604 }
6605
6606 bool ImGui::TreeNode(const char* label)
6607 {
6608 ImGuiWindow* window = GetCurrentWindow();
6609 if (window->SkipItems)
6610 return false;
6611 ImGuiID id = window->GetID(label);
6612 return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL);
6613 }
6614
6615 bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
6616 {
6617 return TreeNodeExV(str_id, 0, fmt, args);
6618 }
6619
6620 bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
6621 {
6622 return TreeNodeExV(ptr_id, 0, fmt, args);
6623 }
6624
6625 bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
6626 {
6627 ImGuiWindow* window = GetCurrentWindow();
6628 if (window->SkipItems)
6629 return false;
6630 ImGuiID id = window->GetID(label);
6631 return TreeNodeBehavior(id, flags, label, NULL);
6632 }
6633
6634 bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6635 {
6636 va_list args;
6637 va_start(args, fmt);
6638 bool is_open = TreeNodeExV(str_id, flags, fmt, args);
6639 va_end(args);
6640 return is_open;
6641 }
6642
6643 bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6644 {
6645 va_list args;
6646 va_start(args, fmt);
6647 bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
6648 va_end(args);
6649 return is_open;
6650 }
6651
6652 bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6653 {
6654 ImGuiWindow* window = GetCurrentWindow();
6655 if (window->SkipItems)
6656 return false;
6657
6658 ImGuiID id = window->GetID(str_id);
6659 const char* label, *label_end;
6660 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6661 return TreeNodeBehavior(id, flags, label, label_end);
6662 }
6663
6664 bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6665 {
6666 ImGuiWindow* window = GetCurrentWindow();
6667 if (window->SkipItems)
6668 return false;
6669
6670 ImGuiID id = window->GetID(ptr_id);
6671 const char* label, *label_end;
6672 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6673 return TreeNodeBehavior(id, flags, label, label_end);
6674 }
6675
6676 bool ImGui::TreeNodeGetOpen(ImGuiID storage_id)
6677 {
6678 ImGuiContext& g = *GImGui;
6679 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6680 return storage->GetInt(storage_id, 0) != 0;
6681 }
6682
6683 void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open)
6684 {
6685 ImGuiContext& g = *GImGui;
6686 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6687 storage->SetInt(storage_id, open ? 1 : 0);
6688 }
6689
6690 bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags)
6691 {
6692 if (flags & ImGuiTreeNodeFlags_Leaf)
6693 return true;
6694
6695 // We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function
6696 ImGuiContext& g = *GImGui;
6697 ImGuiWindow* window = g.CurrentWindow;
6698 ImGuiStorage* storage = window->DC.StateStorage;
6699
6700 bool is_open;
6701 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasOpen)
6702 {
6703 if (g.NextItemData.OpenCond & ImGuiCond_Always)
6704 {
6705 is_open = g.NextItemData.OpenVal;
6706 TreeNodeSetOpen(storage_id, is_open);
6707 }
6708 else
6709 {
6710 // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
6711 const int stored_value = storage->GetInt(storage_id, -1);
6712 if (stored_value == -1)
6713 {
6714 is_open = g.NextItemData.OpenVal;
6715 TreeNodeSetOpen(storage_id, is_open);
6716 }
6717 else
6718 {
6719 is_open = stored_value != 0;
6720 }
6721 }
6722 }
6723 else
6724 {
6725 is_open = storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
6726 }
6727
6728 // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
6729 // NB- If we are above max depth we still allow manually opened nodes to be logged.
6730 if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
6731 is_open = true;
6732
6733 return is_open;
6734 }
6735
6736 // Store ImGuiTreeNodeStackData for just submitted node.
6737 // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase.
6738 static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1)
6739 {
6740 ImGuiContext& g = *GImGui;
6741 ImGuiWindow* window = g.CurrentWindow;
6742
6743 g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1);
6744 ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
6745 tree_node_data->ID = g.LastItemData.ID;
6746 tree_node_data->TreeFlags = flags;
6747 tree_node_data->ItemFlags = g.LastItemData.ItemFlags;
6748 tree_node_data->NavRect = g.LastItemData.NavRect;
6749
6750 // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees.
6751 const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0;
6752 tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX;
6753 tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1;
6754 tree_node_data->DrawLinesToNodesY2 = -FLT_MAX;
6755 window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
6756 if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes)
6757 window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth);
6758 }
6759
6760 // 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.
6761 bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
6762 {
6763 ImGuiWindow* window = GetCurrentWindow();
6764 if (window->SkipItems)
6765 return false;
6766
6767 ImGuiContext& g = *GImGui;
6768 const ImGuiStyle& style = g.Style;
6769 const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
6770 const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y));
6771
6772 if (!label_end)
6773 label_end = FindRenderedTextEnd(label);
6774 const ImVec2 label_size = CalcTextSize(label, label_end, false);
6775
6776 const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing
6777 const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
6778 const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow
6779
6780 // We vertically grow up to current line height up the typical widget height.
6781 const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
6782 const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL);
6783 const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL);
6784 ImRect frame_bb;
6785 frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;
6786 frame_bb.Min.y = window->DC.CursorPos.y;
6787 frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanLabelWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x;
6788 frame_bb.Max.y = window->DC.CursorPos.y + frame_height;
6789 if (display_frame)
6790 {
6791 const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits
6792 frame_bb.Min.x -= outer_extend;
6793 frame_bb.Max.x += outer_extend;
6794 }
6795
6796 ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y);
6797 ItemSize(ImVec2(text_width, frame_height), padding.y);
6798
6799 // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
6800 ImRect interact_bb = frame_bb;
6801 if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanLabelWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0)
6802 interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f);
6803
6804 // Compute open and multi-select states before ItemAdd() as it clear NextItem data.
6805 ImGuiID storage_id = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id;
6806 bool is_open = TreeNodeUpdateNextOpen(storage_id, flags);
6807
6808 bool is_visible;
6809 if (span_all_columns || span_all_columns_label)
6810 {
6811 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
6812 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
6813 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
6814 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
6815 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
6816 is_visible = ItemAdd(interact_bb, id);
6817 window->ClipRect.Min.x = backup_clip_rect_min_x;
6818 window->ClipRect.Max.x = backup_clip_rect_max_x;
6819 }
6820 else
6821 {
6822 is_visible = ItemAdd(interact_bb, id);
6823 }
6824 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
6825 g.LastItemData.DisplayRect = frame_bb;
6826
6827 // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled:
6828 // Store data for the current depth to allow returning to this node from any child item.
6829 // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
6830 // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle.
6831 bool store_tree_node_stack_data = false;
6832 if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0)
6833 flags |= g.Style.TreeLinesFlags;
6834 const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f);
6835 if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6836 {
6837 store_tree_node_stack_data = draw_tree_lines;
6838 if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive)
6839 if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
6840 store_tree_node_stack_data = true;
6841 }
6842
6843 const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
6844 if (!is_visible)
6845 {
6846 if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1))))
6847 {
6848 ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
6849 parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, window->DC.CursorPos.y); // Don't need to aim to mid Y position as we are clipped anyway.
6850 if (frame_bb.Min.y >= window->ClipRect.Max.y)
6851 window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done
6852 }
6853 if (is_open && store_tree_node_stack_data)
6854 TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
6855 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6856 TreePushOverrideID(id);
6857 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
6858 return is_open;
6859 }
6860
6861 if (span_all_columns || span_all_columns_label)
6862 {
6863 TablePushBackgroundChannel();
6864 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
6865 g.LastItemData.ClipRect = window->ClipRect;
6866 }
6867
6868 ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;
6869 if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap))
6870 button_flags |= ImGuiButtonFlags_AllowOverlap;
6871 if (!is_leaf)
6872 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
6873
6874 // We allow clicking on the arrow section with keyboard modifiers held, in order to easily
6875 // allow browsing a tree while preserving selection with code implementing multi-selection patterns.
6876 // When clicking on the rest of the tree node we always disallow keyboard modifiers.
6877 const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x;
6878 const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;
6879 const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);
6880
6881 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
6882 if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default
6883 flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow;
6884
6885 // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags.
6886 // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support.
6887 // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0)
6888 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0)
6889 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1)
6890 // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1)
6891 // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0)
6892 // It is rather standard that arrow click react on Down rather than Up.
6893 // 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.
6894 if (is_mouse_x_over_arrow)
6895 button_flags |= ImGuiButtonFlags_PressedOnClick;
6896 else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
6897 button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
6898 else
6899 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
6900 if (flags & ImGuiTreeNodeFlags_NoNavFocus)
6901 button_flags |= ImGuiButtonFlags_NoNavFocus;
6902
6903 bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
6904 const bool was_selected = selected;
6905
6906 // Multi-selection support (header)
6907 if (is_multi_select)
6908 {
6909 // Handle multi-select + alter button flags for it
6910 MultiSelectItemHeader(id, &selected, &button_flags);
6911 if (is_mouse_x_over_arrow)
6912 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
6913 }
6914 else
6915 {
6916 if (window != g.HoveredWindow || !is_mouse_x_over_arrow)
6917 button_flags |= ImGuiButtonFlags_NoKeyModsAllowed;
6918 }
6919
6920 bool hovered, held;
6921 bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
6922 bool toggled = false;
6923 if (!is_leaf)
6924 {
6925 if (pressed && g.DragDropHoldJustPressedId != id)
6926 {
6927 if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select))
6928 toggled = true; // Single click
6929 if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
6930 toggled |= is_mouse_x_over_arrow && !g.NavHighlightItemUnderNav; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
6931 if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)
6932 toggled = true; // Double click
6933 }
6934 else if (pressed && g.DragDropHoldJustPressedId == id)
6935 {
6936 IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);
6937 if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
6938 toggled = true;
6939 else
6940 pressed = false; // Cancel press so it doesn't trigger selection.
6941 }
6942
6943 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)
6944 {
6945 toggled = true;
6946 NavClearPreferredPosForAxis(ImGuiAxis_X);
6947 NavMoveRequestCancel();
6948 }
6949 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?
6950 {
6951 toggled = true;
6952 NavClearPreferredPosForAxis(ImGuiAxis_X);
6953 NavMoveRequestCancel();
6954 }
6955
6956 if (toggled)
6957 {
6958 is_open = !is_open;
6959 window->DC.StateStorage->SetInt(storage_id, is_open);
6960 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;
6961 }
6962 }
6963
6964 // Multi-selection support (footer)
6965 if (is_multi_select)
6966 {
6967 bool pressed_copy = pressed && !toggled;
6968 MultiSelectItemFooter(id, &selected, &pressed_copy);
6969 if (pressed)
6970 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb);
6971 }
6972
6973 if (selected != was_selected)
6974 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
6975
6976 // Render
6977 {
6978 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
6979 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact;
6980 if (is_multi_select)
6981 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
6982 if (display_frame)
6983 {
6984 // Framed type
6985 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
6986 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
6987 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
6988 if (span_all_columns && !span_all_columns_label)
6989 TablePopBackgroundChannel();
6990 if (flags & ImGuiTreeNodeFlags_Bullet)
6991 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
6992 else if (!is_leaf)
6993 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);
6994 else // Leaf without bullet, left-adjusted text
6995 text_pos.x -= text_offset_x - padding.x;
6996 if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)
6997 frame_bb.Max.x -= g.FontSize + style.FramePadding.x;
6998 if (g.LogEnabled)
6999 LogSetNextTextDecoration("###", "###");
7000 }
7001 else
7002 {
7003 // Unframed typed for tree nodes
7004 if (hovered || selected)
7005 {
7006 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7007 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
7008 }
7009 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
7010 if (span_all_columns && !span_all_columns_label)
7011 TablePopBackgroundChannel();
7012 if (flags & ImGuiTreeNodeFlags_Bullet)
7013 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);
7014 else if (!is_leaf)
7015 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);
7016 if (g.LogEnabled)
7017 LogSetNextTextDecoration(">", NULL);
7018 }
7019
7020 if (draw_tree_lines)
7021 TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f));
7022
7023 // Label
7024 if (display_frame)
7025 RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
7026 else
7027 RenderText(text_pos, label, label_end, false);
7028
7029 if (span_all_columns_label)
7030 TablePopBackgroundChannel();
7031 }
7032
7033 if (is_open && store_tree_node_stack_data)
7034 TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
7035 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
7036 TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice
7037
7038 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
7039 return is_open;
7040 }
7041
7042 // Draw horizontal line from our parent node
7043 // This is only called for visible child nodes so we are not too fussy anymore about performances
7044 void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos)
7045 {
7046 ImGuiContext& g = *GImGui;
7047 ImGuiWindow* window = g.CurrentWindow;
7048 if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0)
7049 return;
7050
7051 ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
7052 float x1 = ImTrunc(parent_data->DrawLinesX1);
7053 float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x);
7054 float y = ImTrunc(target_pos.y);
7055 float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f;
7056 parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding);
7057 if (x1 >= x2)
7058 return;
7059 if (rounding > 0.0f)
7060 {
7061 x1 += 0.5f + rounding;
7062 window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3);
7063 if (x1 < x2)
7064 window->DrawList->PathLineTo(ImVec2(x2, y));
7065 window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize);
7066 }
7067 else
7068 {
7069 window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
7070 }
7071 }
7072
7073 // Draw vertical line of the hierarchy
7074 void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data)
7075 {
7076 ImGuiContext& g = *GImGui;
7077 ImGuiWindow* window = g.CurrentWindow;
7078 float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y);
7079 float y2 = data->DrawLinesToNodesY2;
7080 if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull)
7081 {
7082 float y2_full = window->DC.CursorPos.y;
7083 if (g.CurrentTable)
7084 y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full);
7085 y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f);
7086 if (y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full) // FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y
7087 y2 = y2_full;
7088 }
7089 y2 = ImMin(y2, window->ClipRect.Max.y);
7090 if (y2 <= y1)
7091 return;
7092 float x = ImTrunc(data->DrawLinesX1);
7093 if (data->DrawLinesTableColumn != -1)
7094 TablePushColumnChannel(data->DrawLinesTableColumn);
7095 window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
7096 if (data->DrawLinesTableColumn != -1)
7097 TablePopColumnChannel();
7098 }
7099
7100 void ImGui::TreePush(const char* str_id)
7101 {
7102 ImGuiWindow* window = GetCurrentWindow();
7103 Indent();
7104 window->DC.TreeDepth++;
7105 PushID(str_id);
7106 }
7107
7108 void ImGui::TreePush(const void* ptr_id)
7109 {
7110 ImGuiWindow* window = GetCurrentWindow();
7111 Indent();
7112 window->DC.TreeDepth++;
7113 PushID(ptr_id);
7114 }
7115
7116 void ImGui::TreePushOverrideID(ImGuiID id)
7117 {
7118 ImGuiContext& g = *GImGui;
7119 ImGuiWindow* window = g.CurrentWindow;
7120 Indent();
7121 window->DC.TreeDepth++;
7122 PushOverrideID(id);
7123 }
7124
7125 void ImGui::TreePop()
7126 {
7127 ImGuiContext& g = *GImGui;
7128 ImGuiWindow* window = g.CurrentWindow;
7129 Unindent();
7130
7131 window->DC.TreeDepth--;
7132 ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);
7133
7134 if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask)
7135 {
7136 const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
7137 IM_ASSERT(data->ID == window->IDStack.back());
7138
7139 // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled)
7140 if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent)
7141 if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
7142 NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data);
7143
7144 // Draw hierarchy lines
7145 if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y)
7146 TreeNodeDrawLineToTreePop(data);
7147
7148 g.TreeNodeStack.pop_back();
7149 window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask;
7150 window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask;
7151 }
7152
7153 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.
7154 PopID();
7155 }
7156
7157 // Horizontal distance preceding label when using TreeNode() or Bullet()
7158 float ImGui::GetTreeNodeToLabelSpacing()
7159 {
7160 ImGuiContext& g = *GImGui;
7161 return g.FontSize + (g.Style.FramePadding.x * 2.0f);
7162 }
7163
7164 // Set next TreeNode/CollapsingHeader open state.
7165 void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
7166 {
7167 ImGuiContext& g = *GImGui;
7168 if (g.CurrentWindow->SkipItems)
7169 return;
7170 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasOpen;
7171 g.NextItemData.OpenVal = is_open;
7172 g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always);
7173 }
7174
7175 // Set next TreeNode/CollapsingHeader storage id.
7176 void ImGui::SetNextItemStorageID(ImGuiID storage_id)
7177 {
7178 ImGuiContext& g = *GImGui;
7179 if (g.CurrentWindow->SkipItems)
7180 return;
7181 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasStorageID;
7182 g.NextItemData.StorageId = storage_id;
7183 }
7184
7185 // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
7186 // 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().
7187 bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
7188 {
7189 ImGuiWindow* window = GetCurrentWindow();
7190 if (window->SkipItems)
7191 return false;
7192 ImGuiID id = window->GetID(label);
7193 return TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
7194 }
7195
7196 // p_visible == NULL : regular collapsing header
7197 // 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
7198 // p_visible != NULL && *p_visible == false : do not show the header at all
7199 // Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen.
7200 bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags)
7201 {
7202 ImGuiWindow* window = GetCurrentWindow();
7203 if (window->SkipItems)
7204 return false;
7205
7206 if (p_visible && !*p_visible)
7207 return false;
7208
7209 ImGuiID id = window->GetID(label);
7210 flags |= ImGuiTreeNodeFlags_CollapsingHeader;
7211 if (p_visible)
7212 flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton;
7213 bool is_open = TreeNodeBehavior(id, flags, label);
7214 if (p_visible != NULL)
7215 {
7216 // Create a small overlapping close button
7217 // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
7218 // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.
7219 ImGuiContext& g = *GImGui;
7220 ImGuiLastItemData last_item_backup = g.LastItemData;
7221 float button_size = g.FontSize;
7222 float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x - button_size);
7223 float button_y = g.LastItemData.Rect.Min.y + g.Style.FramePadding.y;
7224 ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id);
7225 if (CloseButton(close_button_id, ImVec2(button_x, button_y)))
7226 *p_visible = false;
7227 g.LastItemData = last_item_backup;
7228 }
7229
7230 return is_open;
7231 }
7232
7233 //-------------------------------------------------------------------------
7234 // [SECTION] Widgets: Selectable
7235 //-------------------------------------------------------------------------
7236 // - Selectable()
7237 //-------------------------------------------------------------------------
7238
7239 // Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image.
7240 // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
7241 // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags.
7242 // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.
7243 bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
7244 {
7245 ImGuiWindow* window = GetCurrentWindow();
7246 if (window->SkipItems)
7247 return false;
7248
7249 ImGuiContext& g = *GImGui;
7250 const ImGuiStyle& style = g.Style;
7251
7252 // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.
7253 ImGuiID id = window->GetID(label);
7254 ImVec2 label_size = CalcTextSize(label, NULL, true);
7255 ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
7256 ImVec2 pos = window->DC.CursorPos;
7257 pos.y += window->DC.CurrLineTextBaseOffset;
7258 ItemSize(size, 0.0f);
7259
7260 // Fill horizontal space
7261 // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets.
7262 const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0;
7263 const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x;
7264 const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x;
7265 if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))
7266 size.x = ImMax(label_size.x, max_x - min_x);
7267
7268 // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
7269 // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
7270 ImRect bb(min_x, pos.y, min_x + size.x, pos.y + size.y);
7271 if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0)
7272 {
7273 const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x;
7274 const float spacing_y = style.ItemSpacing.y;
7275 const float spacing_L = IM_TRUNC(spacing_x * 0.50f);
7276 const float spacing_U = IM_TRUNC(spacing_y * 0.50f);
7277 bb.Min.x -= spacing_L;
7278 bb.Min.y -= spacing_U;
7279 bb.Max.x += (spacing_x - spacing_L);
7280 bb.Max.y += (spacing_y - spacing_U);
7281 }
7282 //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); }
7283
7284 const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0;
7285 const ImGuiItemFlags extra_item_flags = disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None;
7286 bool is_visible;
7287 if (span_all_columns)
7288 {
7289 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
7290 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
7291 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
7292 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
7293 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
7294 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
7295 window->ClipRect.Min.x = backup_clip_rect_min_x;
7296 window->ClipRect.Max.x = backup_clip_rect_max_x;
7297 }
7298 else
7299 {
7300 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
7301 }
7302
7303 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
7304 if (!is_visible)
7305 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)
7306 return false;
7307
7308 const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7309 if (disabled_item && !disabled_global) // Only testing this as an optimization
7310 BeginDisabled();
7311
7312 // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,
7313 // which would be advantageous since most selectable are not selected.
7314 if (span_all_columns)
7315 {
7316 if (g.CurrentTable)
7317 TablePushBackgroundChannel();
7318 else if (window->DC.CurrentColumns)
7319 PushColumnsBackground();
7320 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
7321 g.LastItemData.ClipRect = window->ClipRect;
7322 }
7323
7324 // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
7325 ImGuiButtonFlags button_flags = 0;
7326 if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }
7327 if (flags & ImGuiSelectableFlags_NoSetKeyOwner) { button_flags |= ImGuiButtonFlags_NoSetKeyOwner; }
7328 if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }
7329 if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }
7330 if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }
7331 if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; }
7332
7333 // Multi-selection support (header)
7334 const bool was_selected = selected;
7335 if (is_multi_select)
7336 {
7337 // Handle multi-select + alter button flags for it
7338 MultiSelectItemHeader(id, &selected, &button_flags);
7339 }
7340
7341 bool hovered, held;
7342 bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
7343 bool auto_selected = false;
7344
7345 // Multi-selection support (footer)
7346 if (is_multi_select)
7347 {
7348 MultiSelectItemFooter(id, &selected, &pressed);
7349 }
7350 else
7351 {
7352 // Auto-select when moved into
7353 // - This will be more fully fleshed in the range-select branch
7354 // - This is not exposed as it won't nicely work with some user side handling of shift/control
7355 // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons
7356 // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())
7357 // - (2) usage will fail with clipped items
7358 // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
7359 if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId)
7360 if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0)
7361 selected = pressed = auto_selected = true;
7362 }
7363
7364 // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
7365 if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
7366 {
7367 if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
7368 {
7369 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
7370 if (g.IO.ConfigNavCursorVisibleAuto)
7371 g.NavCursorVisible = false;
7372 }
7373 }
7374 if (pressed)
7375 MarkItemEdited(id);
7376
7377 if (selected != was_selected)
7378 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
7379
7380 // Render
7381 if (is_visible)
7382 {
7383 const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight);
7384 if (highlighted || selected)
7385 {
7386 // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
7387 ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7388 RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
7389 }
7390 if (g.NavId == id)
7391 {
7392 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding;
7393 if (is_multi_select)
7394 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
7395 RenderNavCursor(bb, id, nav_render_cursor_flags);
7396 }
7397 }
7398
7399 if (span_all_columns)
7400 {
7401 if (g.CurrentTable)
7402 TablePopBackgroundChannel();
7403 else if (window->DC.CurrentColumns)
7404 PopColumnsBackground();
7405 }
7406
7407 // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns.
7408 if (is_visible)
7409 RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb);
7410
7411 // Automatically close popups
7412 if (pressed && !auto_selected && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
7413 CloseCurrentPopup();
7414
7415 if (disabled_item && !disabled_global)
7416 EndDisabled();
7417
7418 // Selectable() always returns a pressed state!
7419 // Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve
7420 // selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect().
7421 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
7422 return pressed; //-V1020
7423 }
7424
7425 bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
7426 {
7427 if (Selectable(label, *p_selected, flags, size_arg))
7428 {
7429 *p_selected = !*p_selected;
7430 return true;
7431 }
7432 return false;
7433 }
7434
7435
7436 //-------------------------------------------------------------------------
7437 // [SECTION] Widgets: Typing-Select support
7438 //-------------------------------------------------------------------------
7439
7440 // [Experimental] Currently not exposed in public API.
7441 // Consume character inputs and return search request, if any.
7442 // This would typically only be called on the focused window or location you want to grab inputs for, e.g.
7443 // if (ImGui::IsWindowFocused(...))
7444 // if (ImGuiTypingSelectRequest* req = ImGui::GetTypingSelectRequest())
7445 // focus_idx = ImGui::TypingSelectFindMatch(req, my_items.size(), [](void*, int n) { return my_items[n]->Name; }, &my_items, -1);
7446 // However the code is written in a way where calling it from multiple locations is safe (e.g. to obtain buffer).
7447 ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags flags)
7448 {
7449 ImGuiContext& g = *GImGui;
7450 ImGuiTypingSelectState* data = &g.TypingSelectState;
7451 ImGuiTypingSelectRequest* out_request = &data->Request;
7452
7453 // Clear buffer
7454 const float TYPING_SELECT_RESET_TIMER = 1.80f; // FIXME: Potentially move to IO config.
7455 const int TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK = 4; // Lock single char matching when repeating same char 4 times
7456 if (data->SearchBuffer[0] != 0)
7457 {
7458 bool clear_buffer = false;
7459 clear_buffer |= (g.NavFocusScopeId != data->FocusScope);
7460 clear_buffer |= (data->LastRequestTime + TYPING_SELECT_RESET_TIMER < g.Time);
7461 clear_buffer |= g.NavAnyRequest;
7462 clear_buffer |= g.ActiveId != 0 && g.NavActivateId == 0; // Allow temporary SPACE activation to not interfere
7463 clear_buffer |= IsKeyPressed(ImGuiKey_Escape) || IsKeyPressed(ImGuiKey_Enter);
7464 clear_buffer |= IsKeyPressed(ImGuiKey_Backspace) && (flags & ImGuiTypingSelectFlags_AllowBackspace) == 0;
7465 //if (clear_buffer) { IMGUI_DEBUG_LOG("GetTypingSelectRequest(): Clear SearchBuffer.\n"); }
7466 if (clear_buffer)
7467 data->Clear();
7468 }
7469
7470 // Append to buffer
7471 const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1;
7472 int buffer_len = (int)ImStrlen(data->SearchBuffer);
7473 bool select_request = false;
7474 for (ImWchar w : g.IO.InputQueueCharacters)
7475 {
7476 const int w_len = ImTextCountUtf8BytesFromStr(&w, &w + 1);
7477 if (w < 32 || (buffer_len == 0 && ImCharIsBlankW(w)) || (buffer_len + w_len > buffer_max_len)) // Ignore leading blanks
7478 continue;
7479 char w_buf[5];
7480 ImTextCharToUtf8(w_buf, (unsigned int)w);
7481 if (data->SingleCharModeLock && w_len == out_request->SingleCharSize && memcmp(w_buf, data->SearchBuffer, w_len) == 0)
7482 {
7483 select_request = true; // Same character: don't need to append to buffer.
7484 continue;
7485 }
7486 if (data->SingleCharModeLock)
7487 {
7488 data->Clear(); // Different character: clear
7489 buffer_len = 0;
7490 }
7491 memcpy(data->SearchBuffer + buffer_len, w_buf, w_len + 1); // Append
7492 buffer_len += w_len;
7493 select_request = true;
7494 }
7495 g.IO.InputQueueCharacters.resize(0);
7496
7497 // Handle backspace
7498 if ((flags & ImGuiTypingSelectFlags_AllowBackspace) && IsKeyPressed(ImGuiKey_Backspace, ImGuiInputFlags_Repeat))
7499 {
7500 char* p = (char*)(void*)ImTextFindPreviousUtf8Codepoint(data->SearchBuffer, data->SearchBuffer + buffer_len);
7501 *p = 0;
7502 buffer_len = (int)(p - data->SearchBuffer);
7503 }
7504
7505 // Return request if any
7506 if (buffer_len == 0)
7507 return NULL;
7508 if (select_request)
7509 {
7510 data->FocusScope = g.NavFocusScopeId;
7511 data->LastRequestFrame = g.FrameCount;
7512 data->LastRequestTime = (float)g.Time;
7513 }
7514 out_request->Flags = flags;
7515 out_request->SearchBufferLen = buffer_len;
7516 out_request->SearchBuffer = data->SearchBuffer;
7517 out_request->SelectRequest = (data->LastRequestFrame == g.FrameCount);
7518 out_request->SingleCharMode = false;
7519 out_request->SingleCharSize = 0;
7520
7521 // Calculate if buffer contains the same character repeated.
7522 // - This can be used to implement a special search mode on first character.
7523 // - Performed on UTF-8 codepoint for correctness.
7524 // - SingleCharMode is always set for first input character, because it usually leads to a "next".
7525 if (flags & ImGuiTypingSelectFlags_AllowSingleCharMode)
7526 {
7527 const char* buf_begin = out_request->SearchBuffer;
7528 const char* buf_end = out_request->SearchBuffer + out_request->SearchBufferLen;
7529 const int c0_len = ImTextCountUtf8BytesFromChar(buf_begin, buf_end);
7530 const char* p = buf_begin + c0_len;
7531 for (; p < buf_end; p += c0_len)
7532 if (memcmp(buf_begin, p, (size_t)c0_len) != 0)
7533 break;
7534 const int single_char_count = (p == buf_end) ? (out_request->SearchBufferLen / c0_len) : 0;
7535 out_request->SingleCharMode = (single_char_count > 0 || data->SingleCharModeLock);
7536 out_request->SingleCharSize = (ImS8)c0_len;
7537 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.
7538 }
7539
7540 return out_request;
7541 }
7542
7543 static int ImStrimatchlen(const char* s1, const char* s1_end, const char* s2)
7544 {
7545 int match_len = 0;
7546 while (s1 < s1_end && ImToUpper(*s1++) == ImToUpper(*s2++))
7547 match_len++;
7548 return match_len;
7549 }
7550
7551 // Default handler for finding a result for typing-select. You may implement your own.
7552 // You might want to display a tooltip to visualize the current request SearchBuffer
7553 // When SingleCharMode is set:
7554 // - it is better to NOT display a tooltip of other on-screen display indicator.
7555 // - the index of the currently focused item is required.
7556 // if your SetNextItemSelectionUserData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData.
7557 int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7558 {
7559 if (req == NULL || req->SelectRequest == false) // Support NULL parameter so both calls can be done from same spot.
7560 return -1;
7561 int idx = -1;
7562 if (req->SingleCharMode && (req->Flags & ImGuiTypingSelectFlags_AllowSingleCharMode))
7563 idx = TypingSelectFindNextSingleCharMatch(req, items_count, get_item_name_func, user_data, nav_item_idx);
7564 else
7565 idx = TypingSelectFindBestLeadingMatch(req, items_count, get_item_name_func, user_data);
7566 if (idx != -1)
7567 SetNavCursorVisibleAfterMove();
7568 return idx;
7569 }
7570
7571 // Special handling when a single character is repeated: perform search on a single letter and goes to next.
7572 int ImGui::TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7573 {
7574 // FIXME: Assume selection user data is index. Would be extremely practical.
7575 //if (nav_item_idx == -1)
7576 // nav_item_idx = (int)g.NavLastValidSelectionUserData;
7577
7578 int first_match_idx = -1;
7579 bool return_next_match = false;
7580 for (int idx = 0; idx < items_count; idx++)
7581 {
7582 const char* item_name = get_item_name_func(user_data, idx);
7583 if (ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SingleCharSize, item_name) < req->SingleCharSize)
7584 continue;
7585 if (return_next_match) // Return next matching item after current item.
7586 return idx;
7587 if (first_match_idx == -1 && nav_item_idx == -1) // Return first match immediately if we don't have a nav_item_idx value.
7588 return idx;
7589 if (first_match_idx == -1) // Record first match for wrapping.
7590 first_match_idx = idx;
7591 if (nav_item_idx == idx) // Record that we encountering nav_item so we can return next match.
7592 return_next_match = true;
7593 }
7594 return first_match_idx; // First result
7595 }
7596
7597 int ImGui::TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data)
7598 {
7599 int longest_match_idx = -1;
7600 int longest_match_len = 0;
7601 for (int idx = 0; idx < items_count; idx++)
7602 {
7603 const char* item_name = get_item_name_func(user_data, idx);
7604 const int match_len = ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SearchBufferLen, item_name);
7605 if (match_len <= longest_match_len)
7606 continue;
7607 longest_match_idx = idx;
7608 longest_match_len = match_len;
7609 if (match_len == req->SearchBufferLen)
7610 break;
7611 }
7612 return longest_match_idx;
7613 }
7614
7615 void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data)
7616 {
7617 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7618 Text("SearchBuffer = \"%s\"", data->SearchBuffer);
7619 Text("SingleCharMode = %d, Size = %d, Lock = %d", data->Request.SingleCharMode, data->Request.SingleCharSize, data->SingleCharModeLock);
7620 Text("LastRequest = time: %.2f, frame: %d", data->LastRequestTime, data->LastRequestFrame);
7621 #else
7622 IM_UNUSED(data);
7623 #endif
7624 }
7625
7626 //-------------------------------------------------------------------------
7627 // [SECTION] Widgets: Box-Select support
7628 // This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet.
7629 //-------------------------------------------------------------------------
7630 // Extra logic in MultiSelectItemFooter() and ImGuiListClipper::Step()
7631 //-------------------------------------------------------------------------
7632 // - BoxSelectPreStartDrag() [Internal]
7633 // - BoxSelectActivateDrag() [Internal]
7634 // - BoxSelectDeactivateDrag() [Internal]
7635 // - BoxSelectScrollWithMouseDrag() [Internal]
7636 // - BeginBoxSelect() [Internal]
7637 // - EndBoxSelect() [Internal]
7638 //-------------------------------------------------------------------------
7639
7640 // Call on the initial click.
7641 static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item)
7642 {
7643 ImGuiContext& g = *GImGui;
7644 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7645 bs->ID = id;
7646 bs->IsStarting = true; // Consider starting box-select.
7647 bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid);
7648 bs->IsStartedSetNavIdOnce = bs->IsStartedFromVoid;
7649 bs->KeyMods = g.IO.KeyMods;
7650 bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos);
7651 bs->ScrollAccum = ImVec2(0.0f, 0.0f);
7652 }
7653
7654 static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window)
7655 {
7656 ImGuiContext& g = *GImGui;
7657 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Activate\n", bs->ID);
7658 bs->IsActive = true;
7659 bs->Window = window;
7660 bs->IsStarting = false;
7661 ImGui::SetActiveID(bs->ID, window);
7662 ImGui::SetActiveIdUsingAllKeyboardKeys();
7663 if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0)
7664 bs->RequestClear = true;
7665 }
7666
7667 static void BoxSelectDeactivateDrag(ImGuiBoxSelectState* bs)
7668 {
7669 ImGuiContext& g = *GImGui;
7670 bs->IsActive = bs->IsStarting = false;
7671 if (g.ActiveId == bs->ID)
7672 {
7673 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Deactivate\n", bs->ID);
7674 ImGui::ClearActiveID();
7675 }
7676 bs->ID = 0;
7677 }
7678
7679 static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window, const ImRect& inner_r)
7680 {
7681 ImGuiContext& g = *GImGui;
7682 IM_ASSERT(bs->Window == window);
7683 for (int n = 0; n < 2; n++) // each axis
7684 {
7685 const float mouse_pos = g.IO.MousePos[n];
7686 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;
7687 const float scroll_curr = window->Scroll[n];
7688 if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n]))
7689 continue;
7690
7691 const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance
7692 const float scroll_step = g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime;
7693 bs->ScrollAccum[n] += scroll_step;
7694
7695 // Accumulate into a stored value so we can handle high-framerate
7696 const float scroll_step_i = ImFloor(bs->ScrollAccum[n]);
7697 if (scroll_step_i == 0.0f)
7698 continue;
7699 if (n == 0)
7700 ImGui::SetScrollX(window, scroll_curr + scroll_step_i);
7701 else
7702 ImGui::SetScrollY(window, scroll_curr + scroll_step_i);
7703 bs->ScrollAccum[n] -= scroll_step_i;
7704 }
7705 }
7706
7707 bool ImGui::BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags)
7708 {
7709 ImGuiContext& g = *GImGui;
7710 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7711 KeepAliveID(box_select_id);
7712 if (bs->ID != box_select_id)
7713 return false;
7714
7715 // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry.
7716 bs->UnclipMode = false;
7717 bs->RequestClear = false;
7718 if (bs->IsStarting && IsMouseDragPastThreshold(0))
7719 BoxSelectActivateDrag(bs, window);
7720 else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false)
7721 BoxSelectDeactivateDrag(bs);
7722 if (!bs->IsActive)
7723 return false;
7724
7725 // Current frame absolute prev/current rectangles are used to toggle selection.
7726 // They are derived from positions relative to scrolling space.
7727 ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel);
7728 ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already
7729 ImVec2 curr_end_pos_abs = g.IO.MousePos;
7730 if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow
7731 curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max);
7732 bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs);
7733 bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs);
7734 bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs);
7735 bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs);
7736
7737 // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper)
7738 // Storing an extra rect used by widgets supporting box-select.
7739 if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d)
7740 if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x)
7741 {
7742 bs->UnclipMode = true;
7743 bs->UnclipRect = bs->BoxSelectRectPrev; // FIXME-OPT: UnclipRect x coordinates could be intersection of Prev and Curr rect on X axis.
7744 bs->UnclipRect.Add(bs->BoxSelectRectCurr);
7745 }
7746
7747 //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7748 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectPrev.Min, bs->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7749 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectCurr.Min, bs->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f);
7750 return true;
7751 }
7752
7753 void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags)
7754 {
7755 ImGuiContext& g = *GImGui;
7756 ImGuiWindow* window = g.CurrentWindow;
7757 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7758 IM_ASSERT(bs->IsActive);
7759 bs->UnclipMode = false;
7760
7761 // Render selection rectangle
7762 bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view
7763 ImRect box_select_r = bs->BoxSelectRectCurr;
7764 box_select_r.ClipWith(scope_rect);
7765 window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling
7766 window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling
7767
7768 // Scroll
7769 const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0;
7770 if (enable_scroll)
7771 {
7772 ImRect scroll_r = scope_rect;
7773 scroll_r.Expand(-g.FontSize);
7774 //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255));
7775 if (!scroll_r.Contains(g.IO.MousePos))
7776 BoxSelectScrollWithMouseDrag(bs, window, scroll_r);
7777 }
7778 }
7779
7780 //-------------------------------------------------------------------------
7781 // [SECTION] Widgets: Multi-Select support
7782 //-------------------------------------------------------------------------
7783 // - DebugLogMultiSelectRequests() [Internal]
7784 // - CalcScopeRect() [Internal]
7785 // - BeginMultiSelect()
7786 // - EndMultiSelect()
7787 // - SetNextItemSelectionUserData()
7788 // - MultiSelectItemHeader() [Internal]
7789 // - MultiSelectItemFooter() [Internal]
7790 // - DebugNodeMultiSelectState() [Internal]
7791 //-------------------------------------------------------------------------
7792
7793 static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io)
7794 {
7795 ImGuiContext& g = *GImGui;
7796 IM_UNUSED(function);
7797 for (const ImGuiSelectionRequest& req : io->Requests)
7798 {
7799 if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear");
7800 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);
7801 }
7802 }
7803
7804 static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window)
7805 {
7806 ImGuiContext& g = *GImGui;
7807 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
7808 {
7809 // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only
7810 return ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin));
7811 }
7812 else
7813 {
7814 // When a table, pull HostClipRect, which allows us to predict ClipRect before first row/layout is performed. (#7970)
7815 ImRect scope_rect = window->InnerClipRect;
7816 if (g.CurrentTable != NULL)
7817 scope_rect = g.CurrentTable->HostClipRect;
7818
7819 // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect?
7820 scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max);
7821 return scope_rect;
7822 }
7823 }
7824
7825 // Return ImGuiMultiSelectIO structure.
7826 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
7827 // Passing 'selection_size' and 'items_count' parameters is currently optional.
7828 // - 'selection_size' is useful to disable some shortcut routing: e.g. ImGuiMultiSelectFlags_ClearOnEscape won't claim Escape key when selection_size 0,
7829 // allowing a first press to clear selection THEN the second press to leave child window and return to parent.
7830 // - '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).
7831 // - If they are costly for you to compute (e.g. external intrusive selection without maintaining size), you may avoid them and pass -1.
7832 // - 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.
7833 ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size, int items_count)
7834 {
7835 ImGuiContext& g = *GImGui;
7836 ImGuiWindow* window = g.CurrentWindow;
7837
7838 if (++g.MultiSelectTempDataStacked > g.MultiSelectTempData.Size)
7839 g.MultiSelectTempData.resize(g.MultiSelectTempDataStacked, ImGuiMultiSelectTempData());
7840 ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1];
7841 IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that.
7842 g.CurrentMultiSelect = ms;
7843 if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0)
7844 flags |= ImGuiMultiSelectFlags_ScopeWindow;
7845 if (flags & ImGuiMultiSelectFlags_SingleSelect)
7846 flags &= ~(ImGuiMultiSelectFlags_BoxSelect2d | ImGuiMultiSelectFlags_BoxSelect1d);
7847 if (flags & ImGuiMultiSelectFlags_BoxSelect2d)
7848 flags &= ~ImGuiMultiSelectFlags_BoxSelect1d;
7849
7850 // FIXME: Workaround to the fact we override CursorMaxPos, meaning size measurement are lost. (#8250)
7851 // They should perhaps be stacked properly?
7852 if (ImGuiTable* table = g.CurrentTable)
7853 if (table->CurrentColumn != -1)
7854 TableEndCell(table); // This is currently safe to call multiple time. If that properly is lost we can extract the "save measurement" part of it.
7855
7856 // FIXME: BeginFocusScope()
7857 const ImGuiID id = window->IDStack.back();
7858 ms->Clear();
7859 ms->FocusScopeId = id;
7860 ms->Flags = flags;
7861 ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId);
7862 ms->BackupCursorMaxPos = window->DC.CursorMaxPos;
7863 ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos;
7864 PushFocusScope(ms->FocusScopeId);
7865 if (flags & ImGuiMultiSelectFlags_ScopeWindow) // Mark parent child window as navigable into, with highlight. Assume user will always submit interactive items.
7866 window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main;
7867
7868 // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame.
7869 ms->KeyMods = g.NavJustMovedToId ? (g.NavJustMovedToIsTabbing ? 0 : g.NavJustMovedToKeyMods) : g.IO.KeyMods;
7870 if (flags & ImGuiMultiSelectFlags_NoRangeSelect)
7871 ms->KeyMods &= ~ImGuiMod_Shift;
7872
7873 // Bind storage
7874 ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id);
7875 storage->ID = id;
7876 storage->LastFrameActive = g.FrameCount;
7877 storage->LastSelectionSize = selection_size;
7878 storage->Window = window;
7879 ms->Storage = storage;
7880
7881 // Output to user
7882 ms->IO.Requests.resize(0);
7883 ms->IO.RangeSrcItem = storage->RangeSrcItem;
7884 ms->IO.NavIdItem = storage->NavIdItem;
7885 ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false;
7886 ms->IO.ItemsCount = items_count;
7887
7888 // Clear when using Navigation to move within the scope
7889 // (we compare FocusScopeId so it possible to use multiple selections inside a same window)
7890 bool request_clear = false;
7891 bool request_select_all = false;
7892 if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData)
7893 {
7894 if (ms->KeyMods & ImGuiMod_Shift)
7895 ms->IsKeyboardSetRange = true;
7896 if (ms->IsKeyboardSetRange)
7897 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear?
7898 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
7899 request_clear = true;
7900 }
7901 else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId)
7902 {
7903 // Also clear on leaving scope (may be optional?)
7904 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
7905 request_clear = true;
7906 }
7907
7908 // Box-select handling: update active state.
7909 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7910 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
7911 {
7912 ms->BoxSelectId = GetID("##BoxSelect");
7913 if (BeginBoxSelect(CalcScopeRect(ms, window), window, ms->BoxSelectId, flags))
7914 request_clear |= bs->RequestClear;
7915 }
7916
7917 if (ms->IsFocused)
7918 {
7919 // Shortcut: Clear selection (Escape)
7920 // - Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window.
7921 // - Box select also handle Escape and needs to pass an id to bypass ActiveIdUsingAllKeyboardKeys lock.
7922 if (flags & ImGuiMultiSelectFlags_ClearOnEscape)
7923 {
7924 if (selection_size != 0 || bs->IsActive)
7925 if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_None, bs->IsActive ? bs->ID : 0))
7926 {
7927 request_clear = true;
7928 if (bs->IsActive)
7929 BoxSelectDeactivateDrag(bs);
7930 }
7931 }
7932
7933 // Shortcut: Select all (CTRL+A)
7934 if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll))
7935 if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A))
7936 request_select_all = true;
7937 }
7938
7939 if (request_clear || request_select_all)
7940 {
7941 MultiSelectAddSetAll(ms, request_select_all);
7942 if (!request_select_all)
7943 storage->LastSelectionSize = 0;
7944 }
7945 ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1;
7946 ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid;
7947
7948 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
7949 DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO);
7950
7951 return &ms->IO;
7952 }
7953
7954 // Return updated ImGuiMultiSelectIO structure.
7955 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
7956 ImGuiMultiSelectIO* ImGui::EndMultiSelect()
7957 {
7958 ImGuiContext& g = *GImGui;
7959 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
7960 ImGuiMultiSelectState* storage = ms->Storage;
7961 ImGuiWindow* window = g.CurrentWindow;
7962 IM_ASSERT_USER_ERROR(ms->FocusScopeId == g.CurrentFocusScopeId, "EndMultiSelect() FocusScope mismatch!");
7963 IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow);
7964 IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect);
7965
7966 ImRect scope_rect = CalcScopeRect(ms, window);
7967 if (ms->IsFocused)
7968 {
7969 // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here.
7970 if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at beginning of the scope (see tests for easy failure)
7971 {
7972 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId.
7973 storage->RangeSrcItem = ImGuiSelectionUserData_Invalid;
7974 }
7975 if (ms->NavIdPassedBy == false && storage->NavIdItem != ImGuiSelectionUserData_Invalid)
7976 {
7977 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n");
7978 storage->NavIdItem = ImGuiSelectionUserData_Invalid;
7979 storage->NavIdSelected = -1;
7980 }
7981
7982 if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId))
7983 EndBoxSelect(scope_rect, ms->Flags);
7984 }
7985
7986 if (ms->IsEndIO == false)
7987 ms->IO.Requests.resize(0);
7988
7989 // Clear selection when clicking void?
7990 // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection!
7991 // The InnerRect test is necessary for non-child/decorated windows.
7992 bool scope_hovered = IsWindowHovered() && window->InnerRect.Contains(g.IO.MousePos);
7993 if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect))
7994 scope_hovered &= scope_rect.Contains(g.IO.MousePos);
7995 if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0)
7996 {
7997 if (ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
7998 {
7999 if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1)
8000 {
8001 BoxSelectPreStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid);
8002 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
8003 SetHoveredID(ms->BoxSelectId);
8004 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
8005 SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from void to box-select.
8006 }
8007 }
8008
8009 if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid)
8010 if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None)
8011 MultiSelectAddSetAll(ms, false);
8012 }
8013
8014 // Courtesy nav wrapping helper flag
8015 if (ms->Flags & ImGuiMultiSelectFlags_NavWrapX)
8016 {
8017 IM_ASSERT(ms->Flags & ImGuiMultiSelectFlags_ScopeWindow); // Only supported at window scope
8018 ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX);
8019 }
8020
8021 // Unwind
8022 window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos);
8023 PopFocusScope();
8024
8025 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
8026 DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO);
8027
8028 ms->FocusScopeId = 0;
8029 ms->Flags = ImGuiMultiSelectFlags_None;
8030 g.CurrentMultiSelect = (--g.MultiSelectTempDataStacked > 0) ? &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] : NULL;
8031
8032 return &ms->IO;
8033 }
8034
8035 void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data)
8036 {
8037 // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code!
8038 // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api.
8039 ImGuiContext& g = *GImGui;
8040 g.NextItemData.SelectionUserData = selection_user_data;
8041 g.NextItemData.FocusScopeId = g.CurrentFocusScopeId;
8042
8043 if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect)
8044 {
8045 // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping)
8046 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect;
8047 if (ms->IO.RangeSrcItem == selection_user_data)
8048 ms->RangeSrcPassedBy = true;
8049 }
8050 else
8051 {
8052 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData;
8053 }
8054 }
8055
8056 // In charge of:
8057 // - Applying SetAll for submitted items.
8058 // - Applying SetRange for submitted items and record end points.
8059 // - Altering button behavior flags to facilitate use with drag and drop.
8060 void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags)
8061 {
8062 ImGuiContext& g = *GImGui;
8063 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
8064
8065 bool selected = *p_selected;
8066 if (ms->IsFocused)
8067 {
8068 ImGuiMultiSelectState* storage = ms->Storage;
8069 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
8070 IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope");
8071
8072 // Apply SetAll (Clear/SelectAll) requests requested by BeginMultiSelect().
8073 // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper.
8074 // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect()
8075 if (ms->LoopRequestSetAll != -1)
8076 selected = (ms->LoopRequestSetAll == 1);
8077
8078 // 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)
8079 // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function)
8080 if (ms->IsKeyboardSetRange)
8081 {
8082 IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0);
8083 const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped.
8084 if (is_range_dst)
8085 ms->RangeDstPassedBy = true;
8086 if (is_range_dst && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst
8087 {
8088 storage->RangeSrcItem = item_data;
8089 storage->RangeSelected = selected ? 1 : 0;
8090 }
8091 const bool is_range_src = storage->RangeSrcItem == item_data;
8092 if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy)
8093 {
8094 // Apply range-select value to visible items
8095 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1);
8096 selected = (storage->RangeSelected != 0);
8097 }
8098 else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0 && (ms->Flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
8099 {
8100 // Clear other items
8101 selected = false;
8102 }
8103 }
8104 *p_selected = selected;
8105 }
8106
8107 // Alter button behavior flags
8108 // To handle drag and drop of multiple items we need to avoid clearing selection on click.
8109 // 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.
8110 if (p_button_flags != NULL)
8111 {
8112 ImGuiButtonFlags button_flags = *p_button_flags;
8113 button_flags |= ImGuiButtonFlags_NoHoveredOnFocus;
8114 if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease))
8115 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
8116 else
8117 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
8118 *p_button_flags = button_flags;
8119 }
8120 }
8121
8122 // In charge of:
8123 // - Auto-select on navigation.
8124 // - Box-select toggle handling.
8125 // - Right-click handling.
8126 // - Altering selection based on Ctrl/Shift modifiers, both for keyboard and mouse.
8127 // - Record current selection state for RangeSrc
8128 // This is all rather complex, best to run and refer to "widgets_multiselect_xxx" tests in imgui_test_suite.
8129 void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed)
8130 {
8131 ImGuiContext& g = *GImGui;
8132 ImGuiWindow* window = g.CurrentWindow;
8133
8134 bool selected = *p_selected;
8135 bool pressed = *p_pressed;
8136 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
8137 ImGuiMultiSelectState* storage = ms->Storage;
8138 if (pressed)
8139 ms->IsFocused = true;
8140
8141 bool hovered = false;
8142 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)
8143 hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
8144 if (!ms->IsFocused && !hovered)
8145 return;
8146
8147 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
8148
8149 ImGuiMultiSelectFlags flags = ms->Flags;
8150 const bool is_singleselect = (flags & ImGuiMultiSelectFlags_SingleSelect) != 0;
8151 bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0;
8152 bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0;
8153
8154 bool apply_to_range_src = false;
8155
8156 if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
8157 apply_to_range_src = true;
8158 if (ms->IsEndIO == false)
8159 {
8160 ms->IO.Requests.resize(0);
8161 ms->IsEndIO = true;
8162 }
8163
8164 // Auto-select as you navigate a list
8165 if (g.NavJustMovedToId == id)
8166 {
8167 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8168 {
8169 if (is_ctrl && is_shift)
8170 pressed = true;
8171 else if (!is_ctrl)
8172 selected = pressed = true;
8173 }
8174 else
8175 {
8176 // With NoAutoSelect, using Shift+keyboard performs a write/copy
8177 if (is_shift)
8178 pressed = true;
8179 else if (!is_ctrl)
8180 apply_to_range_src = true; // Since if (pressed) {} main block is not running we update this
8181 }
8182 }
8183
8184 if (apply_to_range_src)
8185 {
8186 storage->RangeSrcItem = item_data;
8187 storage->RangeSelected = selected; // Will be updated at the end of this function anyway.
8188 }
8189
8190 // Box-select toggle handling
8191 if (ms->BoxSelectId != 0)
8192 if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId))
8193 {
8194 const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect);
8195 const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect);
8196 if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr))
8197 {
8198 if (storage->LastSelectionSize <= 0 && bs->IsStartedSetNavIdOnce)
8199 {
8200 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)
8201 bs->IsStartedSetNavIdOnce = false;
8202 }
8203 else
8204 {
8205 selected = !selected;
8206 MultiSelectAddSetRange(ms, selected, +1, item_data, item_data);
8207 }
8208 storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1);
8209 }
8210 }
8211
8212 // Right-click handling.
8213 // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816
8214 if (hovered && IsMouseClicked(1) && (flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8215 {
8216 if (g.ActiveId != 0 && g.ActiveId != id)
8217 ClearActiveID();
8218 SetFocusID(id, window);
8219 if (!pressed && !selected)
8220 {
8221 pressed = true;
8222 is_ctrl = is_shift = false;
8223 }
8224 }
8225
8226 // Unlike Space, Enter doesn't alter selection (but can still return a press) unless current item is not selected.
8227 // The later, "unless current item is not select", may become optional? It seems like a better default if Enter doesn't necessarily open something
8228 // (unlike e.g. Windows explorer). For use case where Enter always open something, we might decide to make this optional?
8229 const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput);
8230
8231 // Alter selection
8232 if (pressed && (!enter_pressed || !selected))
8233 {
8234 // Box-select
8235 ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
8236 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
8237 if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1)
8238 BoxSelectPreStartDrag(ms->BoxSelectId, item_data);
8239
8240 //----------------------------------------------------------------------------------------
8241 // ACTION | Begin | Pressed/Activated | End
8242 //----------------------------------------------------------------------------------------
8243 // Keys Navigated: | Clear | Src=item, Sel=1 SetRange 1
8244 // Keys Navigated: Ctrl | n/a | n/a
8245 // Keys Navigated: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
8246 // Keys Navigated: Ctrl+Shift | n/a | Dst=item, Sel=Src => Clear + SetRange Src-Dst
8247 // Keys Activated: | n/a | Src=item, Sel=1 => Clear + SetRange 1
8248 // Keys Activated: Ctrl | n/a | Src=item, Sel=!Sel => SetSange 1
8249 // Keys Activated: Shift | n/a | Dst=item, Sel=1 => Clear + SetSange 1
8250 //----------------------------------------------------------------------------------------
8251 // Mouse Pressed: | n/a | Src=item, Sel=1, => Clear + SetRange 1
8252 // Mouse Pressed: Ctrl | n/a | Src=item, Sel=!Sel => SetRange 1
8253 // Mouse Pressed: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
8254 // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst
8255 //----------------------------------------------------------------------------------------
8256
8257 if ((flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
8258 {
8259 bool request_clear = false;
8260 if (is_singleselect)
8261 request_clear = true;
8262 else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl)
8263 request_clear = (flags & ImGuiMultiSelectFlags_NoAutoClearOnReselect) ? !selected : true;
8264 else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl)
8265 request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again.
8266 if (request_clear)
8267 MultiSelectAddSetAll(ms, false);
8268 }
8269
8270 int range_direction;
8271 bool range_selected;
8272 if (is_shift && !is_singleselect)
8273 {
8274 //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue);
8275 if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
8276 storage->RangeSrcItem = item_data;
8277 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8278 {
8279 // Shift+Arrow always select
8280 // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected)
8281 range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
8282 }
8283 else
8284 {
8285 // Shift+Arrow copy source selection state
8286 // Shift+Click always copy from target selection state
8287 if (ms->IsKeyboardSetRange)
8288 range_selected = (storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
8289 else
8290 range_selected = !selected;
8291 }
8292 range_direction = ms->RangeSrcPassedBy ? +1 : -1;
8293 }
8294 else
8295 {
8296 // Ctrl inverts selection, otherwise always select
8297 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8298 selected = is_ctrl ? !selected : true;
8299 else
8300 selected = !selected;
8301 storage->RangeSrcItem = item_data;
8302 range_selected = selected;
8303 range_direction = +1;
8304 }
8305 MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data);
8306 }
8307
8308 // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect)
8309 if (storage->RangeSrcItem == item_data)
8310 storage->RangeSelected = selected ? 1 : 0;
8311
8312 // Update/store the selection state of focused item
8313 if (g.NavId == id)
8314 {
8315 storage->NavIdItem = item_data;
8316 storage->NavIdSelected = selected ? 1 : 0;
8317 }
8318 if (storage->NavIdItem == item_data)
8319 ms->NavIdPassedBy = true;
8320 ms->LastSubmittedItem = item_data;
8321
8322 *p_selected = selected;
8323 *p_pressed = pressed;
8324 }
8325
8326 void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected)
8327 {
8328 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid };
8329 ms->IO.Requests.resize(0); // Can always clear previous requests
8330 ms->IO.Requests.push_back(req); // Add new request
8331 }
8332
8333 void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item)
8334 {
8335 // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges)
8336 if (ms->IO.Requests.Size > 0 && first_item == last_item && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0)
8337 {
8338 ImGuiSelectionRequest* prev = &ms->IO.Requests.Data[ms->IO.Requests.Size - 1];
8339 if (prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->LastSubmittedItem && prev->Selected == selected)
8340 {
8341 prev->RangeLastItem = last_item;
8342 return;
8343 }
8344 }
8345
8346 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item };
8347 ms->IO.Requests.push_back(req); // Add new request
8348 }
8349
8350 void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage)
8351 {
8352 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8353 const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
8354 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
8355 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*");
8356 if (!is_active) { PopStyleColor(); }
8357 if (!open)
8358 return;
8359 Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected);
8360 Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected);
8361 Text("LastSelectionSize = %d", storage->LastSelectionSize); // Provided by user
8362 TreePop();
8363 #else
8364 IM_UNUSED(storage);
8365 #endif
8366 }
8367
8368 //-------------------------------------------------------------------------
8369 // [SECTION] Widgets: Multi-Select helpers
8370 //-------------------------------------------------------------------------
8371 // - ImGuiSelectionBasicStorage
8372 // - ImGuiSelectionExternalStorage
8373 //-------------------------------------------------------------------------
8374
8375 ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage()
8376 {
8377 Size = 0;
8378 PreserveOrder = false;
8379 UserData = NULL;
8380 AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; };
8381 _SelectionOrder = 1; // Always >0
8382 }
8383
8384 void ImGuiSelectionBasicStorage::Clear()
8385 {
8386 Size = 0;
8387 _SelectionOrder = 1; // Always >0
8388 _Storage.Data.resize(0);
8389 }
8390
8391 void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r)
8392 {
8393 ImSwap(Size, r.Size);
8394 ImSwap(_SelectionOrder, r._SelectionOrder);
8395 _Storage.Data.swap(r._Storage.Data);
8396 }
8397
8398 bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const
8399 {
8400 return _Storage.GetInt(id, 0) != 0;
8401 }
8402
8403 static int IMGUI_CDECL PairComparerByValueInt(const void* lhs, const void* rhs)
8404 {
8405 int lhs_v = ((const ImGuiStoragePair*)lhs)->val_i;
8406 int rhs_v = ((const ImGuiStoragePair*)rhs)->val_i;
8407 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
8408 }
8409
8410 // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user.
8411 // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector<ImGuiID> instead of ImGuiStorage...)
8412 bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id)
8413 {
8414 ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it;
8415 ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size;
8416 if (PreserveOrder && it == NULL && it_end != NULL)
8417 ImQsort(_Storage.Data.Data, (size_t)_Storage.Data.Size, sizeof(ImGuiStoragePair), PairComparerByValueInt); // ~ImGuiStorage::BuildSortByValueInt()
8418 if (it == NULL)
8419 it = _Storage.Data.Data;
8420 IM_ASSERT(it >= _Storage.Data.Data && it <= it_end);
8421 if (it != it_end)
8422 while (it->val_i == 0 && it < it_end)
8423 it++;
8424 const bool has_more = (it != it_end);
8425 *opaque_it = has_more ? (void**)(it + 1) : (void**)(it);
8426 *out_id = has_more ? it->key : 0;
8427 if (PreserveOrder && !has_more)
8428 _Storage.BuildSortByKey();
8429 return has_more;
8430 }
8431
8432 void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected)
8433 {
8434 int* p_int = _Storage.GetIntRef(id, 0);
8435 if (selected && *p_int == 0) { *p_int = _SelectionOrder++; Size++; }
8436 else if (!selected && *p_int != 0) { *p_int = 0; Size--; }
8437 }
8438
8439 // Optimized for batch edits (with same value of 'selected')
8440 static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends, int selection_order)
8441 {
8442 ImGuiStorage* storage = &selection->_Storage;
8443 ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id);
8444 const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id);
8445 if (selected == (is_contained && it->val_i != 0))
8446 return;
8447 if (selected && !is_contained)
8448 storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish()
8449 else if (is_contained)
8450 it->val_i = selected ? selection_order : 0; // Modify in-place.
8451 selection->Size += selected ? +1 : -1;
8452 }
8453
8454 static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends)
8455 {
8456 ImGuiStorage* storage = &selection->_Storage;
8457 if (selected && selection->Size != size_before_amends)
8458 storage->BuildSortByKey(); // When done selecting: sort everything
8459 }
8460
8461 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8462 // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen.
8463 // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem.
8464 // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection.
8465 // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform
8466 // a lookup in order to have some way to iterate/interpolate between two items.
8467 // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices
8468 // and constructing a view index <> object id/ptr data structure anyway.
8469 // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ImGuiSelectionBasicStorage' INDIRECTION LOGIC.
8470 // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters.
8471 // The most simple implementation (using indices everywhere) would look like:
8472 // for (ImGuiSelectionRequest& req : ms_io->Requests)
8473 // {
8474 // if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { SetItemSelected(n, true); } }
8475 // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { SetItemSelected(n, ms_io->Selected); } }
8476 // }
8477 void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8478 {
8479 // For convenience we obtain ItemsCount as passed to BeginMultiSelect(), which is optional.
8480 // It makes sense when using ImGuiSelectionBasicStorage to simply pass your items count to BeginMultiSelect().
8481 // Other scheme may handle SetAll differently.
8482 IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!");
8483 IM_ASSERT(AdapterIndexToStorageId != NULL);
8484
8485 // This is optimized/specialized to cope with very large selections (e.g. 100k+ items)
8486 // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish().
8487 // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass.
8488 // - 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.
8489 // - 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
8490 // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.
8491 // FIXME-OPT: For each block of consecutive SetRange request:
8492 // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage.
8493 // - rewrite sorted storage a single time.
8494 for (ImGuiSelectionRequest& req : ms_io->Requests)
8495 {
8496 if (req.Type == ImGuiSelectionRequestType_SetAll)
8497 {
8498 Clear();
8499 if (req.Selected)
8500 {
8501 _Storage.Data.reserve(ms_io->ItemsCount);
8502 const int size_before_amends = _Storage.Data.Size;
8503 for (int idx = 0; idx < ms_io->ItemsCount; idx++, _SelectionOrder++)
8504 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, _SelectionOrder);
8505 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8506 }
8507 }
8508 else if (req.Type == ImGuiSelectionRequestType_SetRange)
8509 {
8510 const int selection_changes = (int)req.RangeLastItem - (int)req.RangeFirstItem + 1;
8511 //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);
8512 if (selection_changes == 1 || (selection_changes < Size / 100))
8513 {
8514 // Multiple sorted insertion + copy likely to be faster.
8515 // Technically we could do a single copy with a little more work (sort sequential SetRange requests)
8516 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8517 SetItemSelected(GetStorageIdFromIndex(idx), req.Selected);
8518 }
8519 else
8520 {
8521 // Append insertion + single sort likely be faster.
8522 // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1
8523 const int size_before_amends = _Storage.Data.Size;
8524 int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0);
8525 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection)
8526 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order);
8527 if (req.Selected)
8528 _SelectionOrder += selection_changes;
8529 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8530 }
8531 }
8532 }
8533 }
8534
8535 //-------------------------------------------------------------------------
8536
8537 ImGuiSelectionExternalStorage::ImGuiSelectionExternalStorage()
8538 {
8539 UserData = NULL;
8540 AdapterSetItemSelected = NULL;
8541 }
8542
8543 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8544 // We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage
8545 // This makes no assumption about underlying storage.
8546 void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8547 {
8548 IM_ASSERT(AdapterSetItemSelected);
8549 for (ImGuiSelectionRequest& req : ms_io->Requests)
8550 {
8551 if (req.Type == ImGuiSelectionRequestType_SetAll)
8552 for (int idx = 0; idx < ms_io->ItemsCount; idx++)
8553 AdapterSetItemSelected(this, idx, req.Selected);
8554 if (req.Type == ImGuiSelectionRequestType_SetRange)
8555 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8556 AdapterSetItemSelected(this, idx, req.Selected);
8557 }
8558 }
8559
8560 //-------------------------------------------------------------------------
8561 // [SECTION] Widgets: ListBox
8562 //-------------------------------------------------------------------------
8563 // - BeginListBox()
8564 // - EndListBox()
8565 // - ListBox()
8566 //-------------------------------------------------------------------------
8567
8568 // This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
8569 // This handle some subtleties with capturing info from the label.
8570 // If you don't need a label you can pretty much directly use ImGui::BeginChild() with ImGuiChildFlags_FrameStyle.
8571 // Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty"
8572 // 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.5f * item_height).
8573 bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)
8574 {
8575 ImGuiContext& g = *GImGui;
8576 ImGuiWindow* window = GetCurrentWindow();
8577 if (window->SkipItems)
8578 return false;
8579
8580 const ImGuiStyle& style = g.Style;
8581 const ImGuiID id = GetID(label);
8582 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8583
8584 // Size default to hold ~7.25 items.
8585 // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
8586 ImVec2 size = ImTrunc(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f));
8587 ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
8588 ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8589 ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
8590 g.NextItemData.ClearFlags();
8591
8592 if (!IsRectVisible(bb.Min, bb.Max))
8593 {
8594 ItemSize(bb.GetSize(), style.FramePadding.y);
8595 ItemAdd(bb, 0, &frame_bb);
8596 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8597 return false;
8598 }
8599
8600 // FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well.
8601 BeginGroup();
8602 if (label_size.x > 0.0f)
8603 {
8604 ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y);
8605 RenderText(label_pos, label);
8606 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size);
8607 AlignTextToFramePadding();
8608 }
8609
8610 BeginChild(id, frame_bb.GetSize(), ImGuiChildFlags_FrameStyle);
8611 return true;
8612 }
8613
8614 void ImGui::EndListBox()
8615 {
8616 ImGuiContext& g = *GImGui;
8617 ImGuiWindow* window = g.CurrentWindow;
8618 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?");
8619 IM_UNUSED(window);
8620
8621 EndChild();
8622 EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label
8623 }
8624
8625 bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
8626 {
8627 const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
8628 return value_changed;
8629 }
8630
8631 // This is merely a helper around BeginListBox(), EndListBox().
8632 // Considering using those directly to submit custom data or store selection differently.
8633 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)
8634 {
8635 ImGuiContext& g = *GImGui;
8636
8637 // Calculate size from "height_in_items"
8638 if (height_in_items < 0)
8639 height_in_items = ImMin(items_count, 7);
8640 float height_in_items_f = height_in_items + 0.25f;
8641 ImVec2 size(0.0f, ImTrunc(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f));
8642
8643 if (!BeginListBox(label, size))
8644 return false;
8645
8646 // Assume all items have even height (= 1 line of text). If you need items of different height,
8647 // you can create a custom version of ListBox() in your code without using the clipper.
8648 bool value_changed = false;
8649 ImGuiListClipper clipper;
8650 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.
8651 clipper.IncludeItemByIndex(*current_item);
8652 while (clipper.Step())
8653 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
8654 {
8655 const char* item_text = getter(user_data, i);
8656 if (item_text == NULL)
8657 item_text = "*Unknown item*";
8658
8659 PushID(i);
8660 const bool item_selected = (i == *current_item);
8661 if (Selectable(item_text, item_selected))
8662 {
8663 *current_item = i;
8664 value_changed = true;
8665 }
8666 if (item_selected)
8667 SetItemDefaultFocus();
8668 PopID();
8669 }
8670 EndListBox();
8671
8672 if (value_changed)
8673 MarkItemEdited(g.LastItemData.ID);
8674
8675 return value_changed;
8676 }
8677
8678 //-------------------------------------------------------------------------
8679 // [SECTION] Widgets: PlotLines, PlotHistogram
8680 //-------------------------------------------------------------------------
8681 // - PlotEx() [Internal]
8682 // - PlotLines()
8683 // - PlotHistogram()
8684 //-------------------------------------------------------------------------
8685 // Plot/Graph widgets are not very good.
8686 // Consider writing your own, or using a third-party one, see:
8687 // - ImPlot https://github.com/epezent/implot
8688 // - others https://github.com/ocornut/imgui/wiki/Useful-Extensions
8689 //-------------------------------------------------------------------------
8690
8691 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)
8692 {
8693 ImGuiContext& g = *GImGui;
8694 ImGuiWindow* window = GetCurrentWindow();
8695 if (window->SkipItems)
8696 return -1;
8697
8698 const ImGuiStyle& style = g.Style;
8699 const ImGuiID id = window->GetID(label);
8700
8701 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8702 const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f);
8703
8704 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8705 const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
8706 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));
8707 ItemSize(total_bb, style.FramePadding.y);
8708 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav))
8709 return -1;
8710 bool hovered;
8711 ButtonBehavior(frame_bb, id, &hovered, NULL);
8712
8713 // Determine scale from values if not specified
8714 if (scale_min == FLT_MAX || scale_max == FLT_MAX)
8715 {
8716 float v_min = FLT_MAX;
8717 float v_max = -FLT_MAX;
8718 for (int i = 0; i < values_count; i++)
8719 {
8720 const float v = values_getter(data, i);
8721 if (v != v) // Ignore NaN values
8722 continue;
8723 v_min = ImMin(v_min, v);
8724 v_max = ImMax(v_max, v);
8725 }
8726 if (scale_min == FLT_MAX)
8727 scale_min = v_min;
8728 if (scale_max == FLT_MAX)
8729 scale_max = v_max;
8730 }
8731
8732 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
8733
8734 const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
8735 int idx_hovered = -1;
8736 if (values_count >= values_count_min)
8737 {
8738 int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8739 int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8740
8741 // Tooltip on hover
8742 if (hovered && inner_bb.Contains(g.IO.MousePos))
8743 {
8744 const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
8745 const int v_idx = (int)(t * item_count);
8746 IM_ASSERT(v_idx >= 0 && v_idx < values_count);
8747
8748 const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
8749 const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
8750 if (plot_type == ImGuiPlotType_Lines)
8751 SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1);
8752 else if (plot_type == ImGuiPlotType_Histogram)
8753 SetTooltip("%d: %8.4g", v_idx, v0);
8754 idx_hovered = v_idx;
8755 }
8756
8757 const float t_step = 1.0f / (float)res_w;
8758 const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
8759
8760 float v0 = values_getter(data, (0 + values_offset) % values_count);
8761 float t0 = 0.0f;
8762 ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
8763 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
8764
8765 const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
8766 const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
8767
8768 for (int n = 0; n < res_w; n++)
8769 {
8770 const float t1 = t0 + t_step;
8771 const int v1_idx = (int)(t0 * item_count + 0.5f);
8772 IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
8773 const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
8774 const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
8775
8776 // 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.
8777 ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
8778 ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
8779 if (plot_type == ImGuiPlotType_Lines)
8780 {
8781 window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8782 }
8783 else if (plot_type == ImGuiPlotType_Histogram)
8784 {
8785 if (pos1.x >= pos0.x + 2.0f)
8786 pos1.x -= 1.0f;
8787 window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8788 }
8789
8790 t0 = t1;
8791 tp0 = tp1;
8792 }
8793 }
8794
8795 // Text overlay
8796 if (overlay_text)
8797 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));
8798
8799 if (label_size.x > 0.0f)
8800 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
8801
8802 // Return hovered index or -1 if none are hovered.
8803 // 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().
8804 return idx_hovered;
8805 }
8806
8807 struct ImGuiPlotArrayGetterData
8808 {
8809 const float* Values;
8810 int Stride;
8811
8812 ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
8813 };
8814
8815 static float Plot_ArrayGetter(void* data, int idx)
8816 {
8817 ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
8818 const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
8819 return v;
8820 }
8821
8822 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)
8823 {
8824 ImGuiPlotArrayGetterData data(values, stride);
8825 PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8826 }
8827
8828 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)
8829 {
8830 PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8831 }
8832
8833 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)
8834 {
8835 ImGuiPlotArrayGetterData data(values, stride);
8836 PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8837 }
8838
8839 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)
8840 {
8841 PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8842 }
8843
8844 //-------------------------------------------------------------------------
8845 // [SECTION] Widgets: Value helpers
8846 // Those is not very useful, legacy API.
8847 //-------------------------------------------------------------------------
8848 // - Value()
8849 //-------------------------------------------------------------------------
8850
8851 void ImGui::Value(const char* prefix, bool b)
8852 {
8853 Text("%s: %s", prefix, (b ? "true" : "false"));
8854 }
8855
8856 void ImGui::Value(const char* prefix, int v)
8857 {
8858 Text("%s: %d", prefix, v);
8859 }
8860
8861 void ImGui::Value(const char* prefix, unsigned int v)
8862 {
8863 Text("%s: %d", prefix, v);
8864 }
8865
8866 void ImGui::Value(const char* prefix, float v, const char* float_format)
8867 {
8868 if (float_format)
8869 {
8870 char fmt[64];
8871 ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
8872 Text(fmt, prefix, v);
8873 }
8874 else
8875 {
8876 Text("%s: %.3f", prefix, v);
8877 }
8878 }
8879
8880 //-------------------------------------------------------------------------
8881 // [SECTION] MenuItem, BeginMenu, EndMenu, etc.
8882 //-------------------------------------------------------------------------
8883 // - ImGuiMenuColumns [Internal]
8884 // - BeginMenuBar()
8885 // - EndMenuBar()
8886 // - BeginMainMenuBar()
8887 // - EndMainMenuBar()
8888 // - BeginMenu()
8889 // - EndMenu()
8890 // - MenuItemEx() [Internal]
8891 // - MenuItem()
8892 //-------------------------------------------------------------------------
8893
8894 // Helpers for internal use
8895 void ImGuiMenuColumns::Update(float spacing, bool window_reappearing)
8896 {
8897 if (window_reappearing)
8898 memset(Widths, 0, sizeof(Widths));
8899 Spacing = (ImU16)spacing;
8900 CalcNextTotalWidth(true);
8901 memset(Widths, 0, sizeof(Widths));
8902 TotalWidth = NextTotalWidth;
8903 NextTotalWidth = 0;
8904 }
8905
8906 void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets)
8907 {
8908 ImU16 offset = 0;
8909 bool want_spacing = false;
8910 for (int i = 0; i < IM_ARRAYSIZE(Widths); i++)
8911 {
8912 ImU16 width = Widths[i];
8913 if (want_spacing && width > 0)
8914 offset += Spacing;
8915 want_spacing |= (width > 0);
8916 if (update_offsets)
8917 {
8918 if (i == 1) { OffsetLabel = offset; }
8919 if (i == 2) { OffsetShortcut = offset; }
8920 if (i == 3) { OffsetMark = offset; }
8921 }
8922 offset += width;
8923 }
8924 NextTotalWidth = offset;
8925 }
8926
8927 float ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark)
8928 {
8929 Widths[0] = ImMax(Widths[0], (ImU16)w_icon);
8930 Widths[1] = ImMax(Widths[1], (ImU16)w_label);
8931 Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut);
8932 Widths[3] = ImMax(Widths[3], (ImU16)w_mark);
8933 CalcNextTotalWidth(false);
8934 return (float)ImMax(TotalWidth, NextTotalWidth);
8935 }
8936
8937 // FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
8938 // Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
8939 // 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.
8940 // Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
8941 bool ImGui::BeginMenuBar()
8942 {
8943 ImGuiWindow* window = GetCurrentWindow();
8944 if (window->SkipItems)
8945 return false;
8946 if (!(window->Flags & ImGuiWindowFlags_MenuBar))
8947 return false;
8948
8949 IM_ASSERT(!window->DC.MenuBarAppending);
8950 BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
8951 PushID("##MenuBar");
8952
8953 // 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.
8954 // 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.
8955 const float border_top = ImMax(IM_ROUND(window->WindowBorderSize * 0.5f - window->TitleBarHeight), 0.0f);
8956 const float border_half = IM_ROUND(window->WindowBorderSize * 0.5f);
8957 ImRect bar_rect = window->MenuBarRect();
8958 ImRect clip_rect(ImFloor(bar_rect.Min.x + border_half), ImFloor(bar_rect.Min.y + border_top), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, border_half))), ImFloor(bar_rect.Max.y));
8959 clip_rect.ClipWith(window->OuterRectClipped);
8960 PushClipRect(clip_rect.Min, clip_rect.Max, false);
8961
8962 // 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).
8963 window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
8964 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
8965 window->DC.IsSameLine = false;
8966 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8967 window->DC.MenuBarAppending = true;
8968 AlignTextToFramePadding();
8969 return true;
8970 }
8971
8972 void ImGui::EndMenuBar()
8973 {
8974 ImGuiWindow* window = GetCurrentWindow();
8975 if (window->SkipItems)
8976 return;
8977 ImGuiContext& g = *GImGui;
8978
8979 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
8980 IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
8981 IM_ASSERT(window->DC.MenuBarAppending);
8982
8983 // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
8984 if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
8985 {
8986 // Try to find out if the request is for one of our child menu
8987 ImGuiWindow* nav_earliest_child = g.NavWindow;
8988 while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
8989 nav_earliest_child = nav_earliest_child->ParentWindow;
8990 if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
8991 {
8992 // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
8993 // 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)
8994 const ImGuiNavLayer layer = ImGuiNavLayer_Menu;
8995 IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary)
8996 FocusWindow(window);
8997 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
8998 // FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto?
8999 if (g.NavCursorVisible)
9000 {
9001 g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again
9002 g.NavCursorHideFrames = 2;
9003 }
9004 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
9005 NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
9006 }
9007 }
9008
9009 PopClipRect();
9010 PopID();
9011 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
9012 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.
9013
9014 // FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here.
9015 ImGuiGroupData& group_data = g.GroupStack.back();
9016 group_data.EmitItem = false;
9017 ImVec2 restore_cursor_max_pos = group_data.BackupCursorMaxPos;
9018 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, window->DC.CursorMaxPos.x - window->Scroll.x); // Convert ideal extents for scrolling layer equivalent.
9019 EndGroup(); // Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore
9020 window->DC.LayoutType = ImGuiLayoutType_Vertical;
9021 window->DC.IsSameLine = false;
9022 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
9023 window->DC.MenuBarAppending = false;
9024 window->DC.CursorMaxPos = restore_cursor_max_pos;
9025 }
9026
9027 // Important: calling order matters!
9028 // FIXME: Somehow overlapping with docking tech.
9029 // FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts)
9030 bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags)
9031 {
9032 IM_ASSERT(dir != ImGuiDir_None);
9033
9034 ImGuiWindow* bar_window = FindWindowByName(name);
9035 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport());
9036 if (bar_window == NULL || bar_window->BeginCount == 0)
9037 {
9038 // Calculate and set window size/position
9039 ImRect avail_rect = viewport->GetBuildWorkRect();
9040 ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
9041 ImVec2 pos = avail_rect.Min;
9042 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
9043 pos[axis] = avail_rect.Max[axis] - axis_size;
9044 ImVec2 size = avail_rect.GetSize();
9045 size[axis] = axis_size;
9046 SetNextWindowPos(pos);
9047 SetNextWindowSize(size);
9048
9049 // Report our size into work area (for next frame) using actual window size
9050 if (dir == ImGuiDir_Up || dir == ImGuiDir_Left)
9051 viewport->BuildWorkInsetMin[axis] += axis_size;
9052 else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right)
9053 viewport->BuildWorkInsetMax[axis] += axis_size;
9054 }
9055
9056 window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
9057 SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set.
9058 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
9059 PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint
9060 bool is_open = Begin(name, NULL, window_flags);
9061 PopStyleVar(2);
9062
9063 return is_open;
9064 }
9065
9066 bool ImGui::BeginMainMenuBar()
9067 {
9068 ImGuiContext& g = *GImGui;
9069 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
9070
9071 // Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change
9072 SetCurrentViewport(NULL, viewport);
9073
9074 // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
9075 // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea?
9076 // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings.
9077 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
9078 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
9079 float height = GetFrameHeight();
9080 bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags);
9081 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
9082 if (!is_open)
9083 {
9084 End();
9085 return false;
9086 }
9087
9088 // Temporarily disable _NoSavedSettings, in the off-chance that tables or child windows submitted within the menu-bar may want to use settings. (#8356)
9089 g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings;
9090 BeginMenuBar();
9091 return is_open;
9092 }
9093
9094 void ImGui::EndMainMenuBar()
9095 {
9096 ImGuiContext& g = *GImGui;
9097 if (!g.CurrentWindow->DC.MenuBarAppending)
9098 {
9099 IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar
9100 return;
9101 }
9102
9103 EndMenuBar();
9104 g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356)
9105
9106 // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
9107 // FIXME: With this strategy we won't be able to restore a NULL focus.
9108 if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0)
9109 FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild);
9110
9111 End();
9112 }
9113
9114 static bool IsRootOfOpenMenuSet()
9115 {
9116 ImGuiContext& g = *GImGui;
9117 ImGuiWindow* window = g.CurrentWindow;
9118 if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu))
9119 return false;
9120
9121 // Initially we used 'upper_popup->OpenParentId == window->IDStack.back()' to differentiate multiple menu sets from each others
9122 // (e.g. inside menu bar vs loose menu items) based on parent ID.
9123 // This would however prevent the use of e.g. PushID() user code submitting menus.
9124 // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag,
9125 // making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects.
9126 // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup
9127 // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu.
9128 // 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.
9129 // 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
9130 // 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
9131 // it likely won't be a problem anyone runs into.
9132 const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size];
9133 if (window->DC.NavLayerCurrent != upper_popup->ParentNavLayer)
9134 return false;
9135 return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true, false);
9136 }
9137
9138 bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
9139 {
9140 ImGuiWindow* window = GetCurrentWindow();
9141 if (window->SkipItems)
9142 return false;
9143
9144 ImGuiContext& g = *GImGui;
9145 const ImGuiStyle& style = g.Style;
9146 const ImGuiID id = window->GetID(label);
9147 bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None);
9148
9149 // 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)
9150 // 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.
9151 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
9152 if (window->Flags & ImGuiWindowFlags_ChildMenu)
9153 window_flags |= ImGuiWindowFlags_ChildWindow;
9154
9155 // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().
9156 // 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.
9157 // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used.
9158 if (g.MenusIdSubmittedThisFrame.contains(id))
9159 {
9160 if (menu_is_open)
9161 menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
9162 else
9163 g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values
9164 return menu_is_open;
9165 }
9166
9167 // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu
9168 g.MenusIdSubmittedThisFrame.push_back(id);
9169
9170 ImVec2 label_size = CalcTextSize(label, NULL, true);
9171
9172 // 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)
9173 // This is only done for items for the menu set and not the full parent window.
9174 const bool menuset_is_open = IsRootOfOpenMenuSet();
9175 if (menuset_is_open)
9176 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
9177
9178 // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
9179 // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().
9180 // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
9181 ImVec2 popup_pos, pos = window->DC.CursorPos;
9182 PushID(label);
9183 if (!enabled)
9184 BeginDisabled();
9185 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
9186 bool pressed;
9187
9188 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
9189 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups;
9190 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9191 {
9192 // Menu inside a horizontal menu bar
9193 // Selectable extend their highlight by half ItemSpacing in each direction.
9194 // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
9195 popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight);
9196 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
9197 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
9198 float w = label_size.x;
9199 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9200 pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y));
9201 LogSetNextTextDecoration("[", "]");
9202 RenderText(text_pos, label);
9203 PopStyleVar();
9204 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().
9205 }
9206 else
9207 {
9208 // Menu inside a regular/vertical menu
9209 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
9210 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.)
9211 popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
9212 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
9213 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
9214 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame
9215 float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
9216 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9217 pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
9218 LogSetNextTextDecoration("", ">");
9219 RenderText(text_pos, label);
9220 if (icon_w > 0.0f)
9221 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
9222 RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right);
9223 }
9224 if (!enabled)
9225 EndDisabled();
9226
9227 const bool hovered = (g.HoveredId == id) && enabled && !g.NavHighlightItemUnderNav;
9228 if (menuset_is_open)
9229 PopItemFlag();
9230
9231 bool want_open = false;
9232 bool want_open_nav_init = false;
9233 bool want_close = false;
9234 if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
9235 {
9236 // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
9237 // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
9238 bool moving_toward_child_menu = false;
9239 ImGuiPopupData* child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) ? &g.OpenPopupStack[g.BeginPopupStack.Size] : NULL; // Popup candidate (testing below)
9240 ImGuiWindow* child_menu_window = (child_popup && child_popup->Window && child_popup->Window->ParentWindow == window) ? child_popup->Window : NULL;
9241 if (g.HoveredWindow == window && child_menu_window != NULL)
9242 {
9243 const float ref_unit = g.FontSize; // FIXME-DPI
9244 const float child_dir = (window->Pos.x < child_menu_window->Pos.x) ? 1.0f : -1.0f;
9245 const ImRect next_window_rect = child_menu_window->Rect();
9246 ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta);
9247 ImVec2 tb = (child_dir > 0.0f) ? next_window_rect.GetTL() : next_window_rect.GetTR();
9248 ImVec2 tc = (child_dir > 0.0f) ? next_window_rect.GetBL() : next_window_rect.GetBR();
9249 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.
9250 ta.x += child_dir * -0.5f;
9251 tb.x += child_dir * ref_unit;
9252 tc.x += child_dir * ref_unit;
9253 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
9254 tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, +ref_unit * 8.0f);
9255 moving_toward_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
9256 //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
9257 }
9258
9259 // 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)
9260 // 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.
9261 // (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.)
9262 if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavHighlightItemUnderNav && g.ActiveId == 0)
9263 want_close = true;
9264
9265 // Open
9266 // (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test)
9267 if (!menu_is_open && pressed) // Click/activate to open
9268 want_open = true;
9269 else if (!menu_is_open && hovered && !moving_toward_child_menu) // Hover to open
9270 want_open = true;
9271 else if (!menu_is_open && hovered && g.HoveredIdTimer >= 0.30f && g.MouseStationaryTimer >= 0.30f) // Hover to open (timer fallback)
9272 want_open = true;
9273 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
9274 {
9275 want_open = want_open_nav_init = true;
9276 NavMoveRequestCancel();
9277 SetNavCursorVisibleAfterMove();
9278 }
9279 }
9280 else
9281 {
9282 // Menu bar
9283 if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
9284 {
9285 want_close = true;
9286 want_open = menu_is_open = false;
9287 }
9288 else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
9289 {
9290 want_open = true;
9291 }
9292 else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
9293 {
9294 want_open = true;
9295 NavMoveRequestCancel();
9296 }
9297 }
9298
9299 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.. }'
9300 want_close = true;
9301 if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))
9302 ClosePopupToLevel(g.BeginPopupStack.Size, true);
9303
9304 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
9305 PopID();
9306
9307 if (want_open && !menu_is_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
9308 {
9309 // 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.
9310 OpenPopup(label);
9311 }
9312 else if (want_open)
9313 {
9314 menu_is_open = true;
9315 OpenPopup(label, ImGuiPopupFlags_NoReopen);// | (want_open_nav_init ? ImGuiPopupFlags_NoReopenAlwaysNavInit : 0));
9316 }
9317
9318 if (menu_is_open)
9319 {
9320 ImGuiLastItemData last_item_in_parent = g.LastItemData;
9321 SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos.
9322 PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding
9323 menu_is_open = BeginPopupMenuEx(id, label, window_flags); // menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display)
9324 PopStyleVar();
9325 if (menu_is_open)
9326 {
9327 // Implement what ImGuiPopupFlags_NoReopenAlwaysNavInit would do:
9328 // Perform an init request in the case the popup was already open (via a previous mouse hover)
9329 if (want_open && want_open_nav_init && !g.NavInitRequest)
9330 {
9331 FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags_UnlessBelowModal);
9332 NavInitWindow(g.CurrentWindow, false);
9333 }
9334
9335 // Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu()
9336 // (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags_NoWindowHoverableCheck)
9337 g.LastItemData = last_item_in_parent;
9338 if (g.HoveredWindow == window)
9339 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
9340 }
9341 }
9342 else
9343 {
9344 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
9345 }
9346
9347 return menu_is_open;
9348 }
9349
9350 bool ImGui::BeginMenu(const char* label, bool enabled)
9351 {
9352 return BeginMenuEx(label, NULL, enabled);
9353 }
9354
9355 void ImGui::EndMenu()
9356 {
9357 // Nav: When a left move request our menu failed, close ourselves.
9358 ImGuiContext& g = *GImGui;
9359 ImGuiWindow* window = g.CurrentWindow;
9360 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginMenu()/EndMenu() calls
9361 ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert.
9362 if (window->BeginCount == window->BeginCountPreviousFrame)
9363 if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet())
9364 if (g.NavWindow && (g.NavWindow->RootWindowForNav == window) && parent_window->DC.LayoutType == ImGuiLayoutType_Vertical)
9365 {
9366 ClosePopupToLevel(g.BeginPopupStack.Size - 1, true);
9367 NavMoveRequestCancel();
9368 }
9369
9370 EndPopup();
9371 }
9372
9373 bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled)
9374 {
9375 ImGuiWindow* window = GetCurrentWindow();
9376 if (window->SkipItems)
9377 return false;
9378
9379 ImGuiContext& g = *GImGui;
9380 ImGuiStyle& style = g.Style;
9381 ImVec2 pos = window->DC.CursorPos;
9382 ImVec2 label_size = CalcTextSize(label, NULL, true);
9383
9384 // See BeginMenuEx() for comments about this.
9385 const bool menuset_is_open = IsRootOfOpenMenuSet();
9386 if (menuset_is_open)
9387 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
9388
9389 // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
9390 // 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.
9391 bool pressed;
9392 PushID(label);
9393 if (!enabled)
9394 BeginDisabled();
9395
9396 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
9397 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SetNavIdOnHover;
9398 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
9399 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9400 {
9401 // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
9402 // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark.
9403 float w = label_size.x;
9404 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
9405 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9406 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
9407 pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f));
9408 PopStyleVar();
9409 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9410 RenderText(text_pos, label);
9411 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().
9412 }
9413 else
9414 {
9415 // Menu item inside a vertical menu
9416 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
9417 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.)
9418 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
9419 float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f;
9420 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
9421 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame
9422 float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
9423 pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
9424 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9425 {
9426 RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label);
9427 if (icon_w > 0.0f)
9428 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
9429 if (shortcut_w > 0.0f)
9430 {
9431 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
9432 LogSetNextTextDecoration("(", ")");
9433 RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);
9434 PopStyleColor();
9435 }
9436 if (selected)
9437 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);
9438 }
9439 }
9440 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
9441 if (!enabled)
9442 EndDisabled();
9443 PopID();
9444 if (menuset_is_open)
9445 PopItemFlag();
9446
9447 return pressed;
9448 }
9449
9450 bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
9451 {
9452 return MenuItemEx(label, NULL, shortcut, selected, enabled);
9453 }
9454
9455 bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
9456 {
9457 if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled))
9458 {
9459 if (p_selected)
9460 *p_selected = !*p_selected;
9461 return true;
9462 }
9463 return false;
9464 }
9465
9466 //-------------------------------------------------------------------------
9467 // [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
9468 //-------------------------------------------------------------------------
9469 // - BeginTabBar()
9470 // - BeginTabBarEx() [Internal]
9471 // - EndTabBar()
9472 // - TabBarLayout() [Internal]
9473 // - TabBarCalcTabID() [Internal]
9474 // - TabBarCalcMaxTabWidth() [Internal]
9475 // - TabBarFindTabById() [Internal]
9476 // - TabBarFindTabByOrder() [Internal]
9477 // - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal]
9478 // - TabBarGetCurrentTab() [Internal]
9479 // - TabBarGetTabName() [Internal]
9480 // - TabBarAddTab() [Internal]
9481 // - TabBarRemoveTab() [Internal]
9482 // - TabBarCloseTab() [Internal]
9483 // - TabBarScrollClamp() [Internal]
9484 // - TabBarScrollToTab() [Internal]
9485 // - TabBarQueueFocus() [Internal]
9486 // - TabBarQueueReorder() [Internal]
9487 // - TabBarProcessReorderFromMousePos() [Internal]
9488 // - TabBarProcessReorder() [Internal]
9489 // - TabBarScrollingButtons() [Internal]
9490 // - TabBarTabListPopupButton() [Internal]
9491 //-------------------------------------------------------------------------
9492
9493 struct ImGuiTabBarSection
9494 {
9495 int TabCount; // Number of tabs in this section.
9496 float Width; // Sum of width of tabs in this section (after shrinking down)
9497 float WidthAfterShrinkMinWidth;
9498 float Spacing; // Horizontal spacing at the end of the section.
9499
9500 ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); }
9501 };
9502
9503 namespace ImGui
9504 {
9505 static void TabBarLayout(ImGuiTabBar* tab_bar);
9506 static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window);
9507 static float TabBarCalcMaxTabWidth();
9508 static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
9509 static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections);
9510 static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
9511 static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
9512 }
9513
9514 ImGuiTabBar::ImGuiTabBar()
9515 {
9516 memset(this, 0, sizeof(*this));
9517 CurrFrameVisible = PrevFrameVisible = -1;
9518 LastTabItemIdx = -1;
9519 }
9520
9521 static inline int TabItemGetSectionIdx(const ImGuiTabItem* tab)
9522 {
9523 return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1;
9524 }
9525
9526 static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs)
9527 {
9528 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9529 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9530 const int a_section = TabItemGetSectionIdx(a);
9531 const int b_section = TabItemGetSectionIdx(b);
9532 if (a_section != b_section)
9533 return a_section - b_section;
9534 return (int)(a->IndexDuringLayout - b->IndexDuringLayout);
9535 }
9536
9537 static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs)
9538 {
9539 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9540 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9541 return (int)(a->BeginOrder - b->BeginOrder);
9542 }
9543
9544 static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)
9545 {
9546 ImGuiContext& g = *GImGui;
9547 return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);
9548 }
9549
9550 static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
9551 {
9552 ImGuiContext& g = *GImGui;
9553 if (g.TabBars.Contains(tab_bar))
9554 return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));
9555 return ImGuiPtrOrIndex(tab_bar);
9556 }
9557
9558 ImGuiTabBar* ImGui::TabBarFindByID(ImGuiID id)
9559 {
9560 ImGuiContext& g = *GImGui;
9561 return g.TabBars.GetByKey(id);
9562 }
9563
9564 // Remove TabBar data (currently only used by TestEngine)
9565 void ImGui::TabBarRemove(ImGuiTabBar* tab_bar)
9566 {
9567 ImGuiContext& g = *GImGui;
9568 g.TabBars.Remove(tab_bar->ID, tab_bar);
9569 }
9570
9571 bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
9572 {
9573 ImGuiContext& g = *GImGui;
9574 ImGuiWindow* window = g.CurrentWindow;
9575 if (window->SkipItems)
9576 return false;
9577
9578 ImGuiID id = window->GetID(str_id);
9579 ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
9580 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);
9581 tab_bar->ID = id;
9582 tab_bar->SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f);
9583 tab_bar->SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f);
9584 //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false))
9585 flags |= ImGuiTabBarFlags_IsFocused;
9586 return BeginTabBarEx(tab_bar, tab_bar_bb, flags);
9587 }
9588
9589 bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
9590 {
9591 ImGuiContext& g = *GImGui;
9592 ImGuiWindow* window = g.CurrentWindow;
9593 if (window->SkipItems)
9594 return false;
9595
9596 IM_ASSERT(tab_bar->ID != 0);
9597 if ((flags & ImGuiTabBarFlags_DockNode) == 0)
9598 PushOverrideID(tab_bar->ID);
9599
9600 // Add to stack
9601 g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
9602 g.CurrentTabBar = tab_bar;
9603 tab_bar->Window = window;
9604
9605 // Append with multiple BeginTabBar()/EndTabBar() pairs.
9606 tab_bar->BackupCursorPos = window->DC.CursorPos;
9607 if (tab_bar->CurrFrameVisible == g.FrameCount)
9608 {
9609 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9610 tab_bar->BeginCount++;
9611 return true;
9612 }
9613
9614 // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable
9615 if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable)))
9616 if ((flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid
9617 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder);
9618 tab_bar->TabsAddedNew = false;
9619
9620 // Flags
9621 if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
9622 flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
9623
9624 tab_bar->Flags = flags;
9625 tab_bar->BarRect = tab_bar_bb;
9626 tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
9627 tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
9628 tab_bar->CurrFrameVisible = g.FrameCount;
9629 tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight;
9630 tab_bar->CurrTabsContentsHeight = 0.0f;
9631 tab_bar->ItemSpacingY = g.Style.ItemSpacing.y;
9632 tab_bar->FramePadding = g.Style.FramePadding;
9633 tab_bar->TabsActiveCount = 0;
9634 tab_bar->LastTabItemIdx = -1;
9635 tab_bar->BeginCount = 1;
9636
9637 // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap
9638 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9639
9640 // Draw separator
9641 // (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable)
9642 const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected);
9643 if (g.Style.TabBarBorderSize > 0.0f)
9644 {
9645 const float y = tab_bar->BarRect.Max.y;
9646 window->DrawList->AddRectFilled(ImVec2(tab_bar->SeparatorMinX, y - g.Style.TabBarBorderSize), ImVec2(tab_bar->SeparatorMaxX, y), col);
9647 }
9648 return true;
9649 }
9650
9651 void ImGui::EndTabBar()
9652 {
9653 ImGuiContext& g = *GImGui;
9654 ImGuiWindow* window = g.CurrentWindow;
9655 if (window->SkipItems)
9656 return;
9657
9658 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9659 if (tab_bar == NULL)
9660 {
9661 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!");
9662 return;
9663 }
9664
9665 // Fallback in case no TabItem have been submitted
9666 if (tab_bar->WantLayout)
9667 TabBarLayout(tab_bar);
9668
9669 // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
9670 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
9671 if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
9672 {
9673 tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight);
9674 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight;
9675 }
9676 else
9677 {
9678 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight;
9679 }
9680 if (tab_bar->BeginCount > 1)
9681 window->DC.CursorPos = tab_bar->BackupCursorPos;
9682
9683 tab_bar->LastTabItemIdx = -1;
9684 if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
9685 PopID();
9686
9687 g.CurrentTabBarStack.pop_back();
9688 g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
9689 }
9690
9691 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
9692 static float TabBarCalcScrollableWidth(ImGuiTabBar* tab_bar, ImGuiTabBarSection* sections)
9693 {
9694 return tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing;
9695 }
9696
9697 // This is called only once a frame before by the first call to ItemTab()
9698 // The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
9699 static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
9700 {
9701 ImGuiContext& g = *GImGui;
9702 tab_bar->WantLayout = false;
9703
9704 // Track selected tab when resizing our parent down
9705 const bool scroll_to_selected_tab = (tab_bar->BarRectPrevWidth > tab_bar->BarRect.GetWidth());
9706 tab_bar->BarRectPrevWidth = tab_bar->BarRect.GetWidth();
9707
9708 // Garbage collect by compacting list
9709 // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)
9710 int tab_dst_n = 0;
9711 bool need_sort_by_section = false;
9712 ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing
9713 for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
9714 {
9715 ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
9716 if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose)
9717 {
9718 // Remove tab
9719 if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; }
9720 if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; }
9721 if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; }
9722 continue;
9723 }
9724 if (tab_dst_n != tab_src_n)
9725 tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
9726
9727 tab = &tab_bar->Tabs[tab_dst_n];
9728 tab->IndexDuringLayout = (ImS16)tab_dst_n;
9729
9730 // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another)
9731 int curr_tab_section_n = TabItemGetSectionIdx(tab);
9732 if (tab_dst_n > 0)
9733 {
9734 ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1];
9735 int prev_tab_section_n = TabItemGetSectionIdx(prev_tab);
9736 if (curr_tab_section_n == 0 && prev_tab_section_n != 0)
9737 need_sort_by_section = true;
9738 if (prev_tab_section_n == 2 && curr_tab_section_n != 2)
9739 need_sort_by_section = true;
9740 }
9741
9742 sections[curr_tab_section_n].TabCount++;
9743 tab_dst_n++;
9744 }
9745 if (tab_bar->Tabs.Size != tab_dst_n)
9746 tab_bar->Tabs.resize(tab_dst_n);
9747
9748 if (need_sort_by_section)
9749 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection);
9750
9751 // Calculate spacing between sections
9752 sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9753 sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9754
9755 // Setup next selected tab
9756 ImGuiID scroll_to_tab_id = 0;
9757 if (tab_bar->NextSelectedTabId)
9758 {
9759 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
9760 tab_bar->NextSelectedTabId = 0;
9761 scroll_to_tab_id = tab_bar->SelectedTabId;
9762 }
9763
9764 // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
9765 if (tab_bar->ReorderRequestTabId != 0)
9766 {
9767 if (TabBarProcessReorder(tab_bar))
9768 if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId)
9769 scroll_to_tab_id = tab_bar->ReorderRequestTabId;
9770 tab_bar->ReorderRequestTabId = 0;
9771 }
9772
9773 // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
9774 const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
9775 if (tab_list_popup_button)
9776 if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x!
9777 scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
9778
9779 // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central
9780 // (whereas our tabs are stored as: leading, central, trailing)
9781 int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount };
9782 g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
9783
9784 // Minimum shrink width
9785 const float shrink_min_width = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed) ? g.Style.TabMinWidthShrink : 1.0f;
9786
9787 // Compute ideal tabs widths + store them into shrink buffer
9788 ImGuiTabItem* most_recently_selected_tab = NULL;
9789 int curr_section_n = -1;
9790 bool found_selected_tab_id = false;
9791 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
9792 {
9793 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
9794 IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
9795
9796 if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button))
9797 most_recently_selected_tab = tab;
9798 if (tab->ID == tab_bar->SelectedTabId)
9799 found_selected_tab_id = true;
9800 if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID)
9801 scroll_to_tab_id = tab->ID;
9802
9803 // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
9804 // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
9805 // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
9806 const char* tab_name = TabBarGetTabName(tab_bar, tab);
9807 const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
9808 tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x;
9809 if ((tab->Flags & ImGuiTabItemFlags_Button) == 0)
9810 tab->ContentWidth = ImMax(tab->ContentWidth, g.Style.TabMinWidthBase);
9811
9812 int section_n = TabItemGetSectionIdx(tab);
9813 ImGuiTabBarSection* section = &sections[section_n];
9814 section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
9815 section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
9816 curr_section_n = section_n;
9817
9818 // Store data so we can build an array sorted by width if we need to shrink tabs down
9819 IM_MSVC_WARNING_SUPPRESS(6385);
9820 ImGuiShrinkWidthItem* shrink_width_item = &g.ShrinkWidthBuffer[shrink_buffer_indexes[section_n]++];
9821 shrink_width_item->Index = tab_n;
9822 shrink_width_item->Width = shrink_width_item->InitialWidth = tab->ContentWidth;
9823 tab->Width = ImMax(tab->ContentWidth, 1.0f);
9824 }
9825
9826 // Compute total ideal width (used for e.g. auto-resizing a window)
9827 float width_all_tabs_after_min_width_shrink = 0.0f;
9828 tab_bar->WidthAllTabsIdeal = 0.0f;
9829 for (int section_n = 0; section_n < 3; section_n++)
9830 {
9831 tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing;
9832 width_all_tabs_after_min_width_shrink += sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing;
9833 }
9834
9835 // Horizontal scrolling buttons
9836 // Important: note that TabBarScrollButtons() will alter BarRect.Max.x.
9837 const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
9838 const float width_all_tabs_to_use_for_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) ? tab_bar->WidthAllTabs : width_all_tabs_after_min_width_shrink;
9839 tab_bar->ScrollButtonEnabled = ((width_all_tabs_to_use_for_scroll > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && can_scroll);
9840 if (tab_bar->ScrollButtonEnabled)
9841 if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar))
9842 {
9843 scroll_to_tab_id = scroll_and_select_tab->ID;
9844 if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0)
9845 tab_bar->SelectedTabId = scroll_to_tab_id;
9846 }
9847 if (scroll_to_tab_id == 0 && scroll_to_selected_tab)
9848 scroll_to_tab_id = tab_bar->SelectedTabId;
9849
9850 // Shrink widths if full tabs don't fit in their allocated space
9851 float section_0_w = sections[0].Width + sections[0].Spacing;
9852 float section_1_w = sections[1].Width + sections[1].Spacing;
9853 float section_2_w = sections[2].Width + sections[2].Spacing;
9854 bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth();
9855 float width_excess;
9856 if (central_section_is_visible)
9857 width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section
9858 else
9859 width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section
9860
9861 // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore
9862 const bool can_shrink = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
9863 if (width_excess >= 1.0f && (can_shrink || !central_section_is_visible))
9864 {
9865 int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount);
9866 int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0);
9867 ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess, shrink_min_width);
9868
9869 // Apply shrunk values into tabs and sections
9870 for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++)
9871 {
9872 ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index];
9873 float shrinked_width = IM_TRUNC(g.ShrinkWidthBuffer[tab_n].Width);
9874 if (shrinked_width < 0.0f)
9875 continue;
9876
9877 shrinked_width = ImMax(1.0f, shrinked_width);
9878 int section_n = TabItemGetSectionIdx(tab);
9879 sections[section_n].Width -= (tab->Width - shrinked_width);
9880 tab->Width = shrinked_width;
9881 }
9882 }
9883
9884 // Layout all active tabs
9885 int section_tab_index = 0;
9886 float tab_offset = 0.0f;
9887 tab_bar->WidthAllTabs = 0.0f;
9888 for (int section_n = 0; section_n < 3; section_n++)
9889 {
9890 ImGuiTabBarSection* section = &sections[section_n];
9891 if (section_n == 2)
9892 tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset);
9893
9894 for (int tab_n = 0; tab_n < section->TabCount; tab_n++)
9895 {
9896 ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n];
9897 tab->Offset = tab_offset;
9898 tab->NameOffset = -1;
9899 tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f);
9900 }
9901 tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f);
9902 tab_offset += section->Spacing;
9903 section_tab_index += section->TabCount;
9904 }
9905
9906 // Clear name buffers
9907 tab_bar->TabsNames.Buf.resize(0);
9908
9909 // If we have lost the selected tab, select the next most recently active one
9910 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
9911 if (found_selected_tab_id == false && !tab_bar_appearing)
9912 tab_bar->SelectedTabId = 0;
9913 if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
9914 scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
9915
9916 // Lock in visible tab
9917 tab_bar->VisibleTabId = tab_bar->SelectedTabId;
9918 tab_bar->VisibleTabWasSubmitted = false;
9919
9920 // CTRL+TAB can override visible tab temporarily
9921 if (g.NavWindowingTarget != NULL && g.NavWindowingTarget->DockNode && g.NavWindowingTarget->DockNode->TabBar == tab_bar)
9922 tab_bar->VisibleTabId = scroll_to_tab_id = g.NavWindowingTarget->TabId;
9923
9924 // Apply request requests
9925 if (scroll_to_tab_id != 0)
9926 TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections);
9927 else if (tab_bar->ScrollButtonEnabled && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow))
9928 {
9929 const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH;
9930 const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX;
9931 if (TestKeyOwner(wheel_key, tab_bar->ID) && wheel != 0.0f)
9932 {
9933 const float scroll_step = wheel * TabBarCalcScrollableWidth(tab_bar, sections) / 3.0f;
9934 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
9935 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget - scroll_step);
9936 }
9937 SetKeyOwner(wheel_key, tab_bar->ID);
9938 }
9939
9940 // Update scrolling
9941 tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
9942 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
9943 if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
9944 {
9945 // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
9946 // Teleport if we are aiming far off the visible line
9947 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
9948 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
9949 const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
9950 tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
9951 }
9952 else
9953 {
9954 tab_bar->ScrollingSpeed = 0.0f;
9955 }
9956 tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing;
9957 tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing;
9958
9959 // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame)
9960 ImGuiWindow* window = g.CurrentWindow;
9961 window->DC.CursorPos = tab_bar->BarRect.Min;
9962 ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y);
9963 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal);
9964 }
9965
9966 // Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack.
9967 static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window)
9968 {
9969 if (docked_window != NULL)
9970 {
9971 IM_UNUSED(tab_bar);
9972 IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode);
9973 ImGuiID id = docked_window->TabId;
9974 KeepAliveID(id);
9975 return id;
9976 }
9977 else
9978 {
9979 ImGuiWindow* window = GImGui->CurrentWindow;
9980 return window->GetID(label);
9981 }
9982 }
9983
9984 static float ImGui::TabBarCalcMaxTabWidth()
9985 {
9986 ImGuiContext& g = *GImGui;
9987 return g.FontSize * 20.0f;
9988 }
9989
9990 ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
9991 {
9992 if (tab_id != 0)
9993 for (int n = 0; n < tab_bar->Tabs.Size; n++)
9994 if (tab_bar->Tabs[n].ID == tab_id)
9995 return &tab_bar->Tabs[n];
9996 return NULL;
9997 }
9998
9999 // Order = visible order, not submission order! (which is tab->BeginOrder)
10000 ImGuiTabItem* ImGui::TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order)
10001 {
10002 if (order < 0 || order >= tab_bar->Tabs.Size)
10003 return NULL;
10004 return &tab_bar->Tabs[order];
10005 }
10006
10007 // FIXME: See references to #2304 in TODO.txt
10008 ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar)
10009 {
10010 ImGuiTabItem* most_recently_selected_tab = NULL;
10011 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
10012 {
10013 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
10014 if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected)
10015 if (tab->Window && tab->Window->WasActive)
10016 most_recently_selected_tab = tab;
10017 }
10018 return most_recently_selected_tab;
10019 }
10020
10021 ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar)
10022 {
10023 if (tab_bar->LastTabItemIdx < 0 || tab_bar->LastTabItemIdx >= tab_bar->Tabs.Size)
10024 return NULL;
10025 return &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10026 }
10027
10028 const char* ImGui::TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10029 {
10030 if (tab->Window)
10031 return tab->Window->Name;
10032 if (tab->NameOffset == -1)
10033 return "N/A";
10034 IM_ASSERT(tab->NameOffset < tab_bar->TabsNames.Buf.Size);
10035 return tab_bar->TabsNames.Buf.Data + tab->NameOffset;
10036 }
10037
10038 // The purpose of this call is to register tab in advance so we can control their order at the time they appear.
10039 // Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function.
10040 void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window)
10041 {
10042 ImGuiContext& g = *GImGui;
10043 IM_ASSERT(TabBarFindTabByID(tab_bar, window->TabId) == NULL);
10044 IM_ASSERT(g.CurrentTabBar != tab_bar); // Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar->CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame)
10045
10046 if (!window->HasCloseButton)
10047 tab_flags |= ImGuiTabItemFlags_NoCloseButton; // Set _NoCloseButton immediately because it will be used for first-frame width calculation.
10048
10049 ImGuiTabItem new_tab;
10050 new_tab.ID = window->TabId;
10051 new_tab.Flags = tab_flags;
10052 new_tab.LastFrameVisible = tab_bar->CurrFrameVisible; // Required so BeginTabBar() doesn't ditch the tab
10053 if (new_tab.LastFrameVisible == -1)
10054 new_tab.LastFrameVisible = g.FrameCount - 1;
10055 new_tab.Window = window; // Required so tab bar layout can compute the tab width before tab submission
10056 tab_bar->Tabs.push_back(new_tab);
10057 }
10058
10059 // The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
10060 void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
10061 {
10062 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
10063 tab_bar->Tabs.erase(tab);
10064 if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
10065 if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
10066 if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
10067 }
10068
10069 // Called on manual closure attempt
10070 void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10071 {
10072 if (tab->Flags & ImGuiTabItemFlags_Button)
10073 return; // A button appended with TabItemButton().
10074
10075 if ((tab->Flags & (ImGuiTabItemFlags_UnsavedDocument | ImGuiTabItemFlags_NoAssumedClosure)) == 0)
10076 {
10077 // This will remove a frame of lag for selecting another tab on closure.
10078 // 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
10079 tab->WantClose = true;
10080 if (tab_bar->VisibleTabId == tab->ID)
10081 {
10082 tab->LastFrameVisible = -1;
10083 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
10084 }
10085 }
10086 else
10087 {
10088 // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup)
10089 if (tab_bar->VisibleTabId != tab->ID)
10090 TabBarQueueFocus(tab_bar, tab);
10091 }
10092 }
10093
10094 static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
10095 {
10096 scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth());
10097 return ImMax(scrolling, 0.0f);
10098 }
10099
10100 // Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys
10101 static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections)
10102 {
10103 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id);
10104 if (tab == NULL)
10105 return;
10106 if (tab->Flags & ImGuiTabItemFlags_SectionMask_)
10107 return;
10108
10109 ImGuiContext& g = *GImGui;
10110 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)
10111 int order = TabBarGetTabOrder(tab_bar, tab);
10112
10113 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
10114 float scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections);
10115
10116 // We make all tabs positions all relative Sections[0].Width to make code simpler
10117 float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f);
10118 float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f);
10119 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
10120 if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width))
10121 {
10122 // Scroll to the left
10123 tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
10124 tab_bar->ScrollingTarget = tab_x1;
10125 }
10126 else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width)
10127 {
10128 // Scroll to the right
10129 tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f);
10130 tab_bar->ScrollingTarget = tab_x2 - scrollable_width;
10131 }
10132 }
10133
10134 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10135 {
10136 tab_bar->NextSelectedTabId = tab->ID;
10137 }
10138
10139 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name)
10140 {
10141 IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars
10142 ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name, NULL);
10143 tab_bar->NextSelectedTabId = tab_id;
10144 }
10145
10146 void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset)
10147 {
10148 IM_ASSERT(offset != 0);
10149 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
10150 tab_bar->ReorderRequestTabId = tab->ID;
10151 tab_bar->ReorderRequestOffset = (ImS16)offset;
10152 }
10153
10154 void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* src_tab, ImVec2 mouse_pos)
10155 {
10156 ImGuiContext& g = *GImGui;
10157 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
10158 if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0)
10159 return;
10160
10161 const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
10162 const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0);
10163
10164 // Count number of contiguous tabs we are crossing over
10165 const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1;
10166 const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab);
10167 int dst_idx = src_idx;
10168 for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir)
10169 {
10170 // Reordered tabs must share the same section
10171 const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i];
10172 if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder)
10173 break;
10174 if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_))
10175 break;
10176 dst_idx = i;
10177
10178 // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered.
10179 const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x;
10180 const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x;
10181 //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255));
10182 if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2))
10183 break;
10184 }
10185
10186 if (dst_idx != src_idx)
10187 TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx);
10188 }
10189
10190 bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar)
10191 {
10192 ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId);
10193 if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder))
10194 return false;
10195
10196 //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
10197 int tab2_order = TabBarGetTabOrder(tab_bar, tab1) + tab_bar->ReorderRequestOffset;
10198 if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size)
10199 return false;
10200
10201 // Reordered tabs must share the same section
10202 // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too)
10203 ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
10204 if (tab2->Flags & ImGuiTabItemFlags_NoReorder)
10205 return false;
10206 if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_))
10207 return false;
10208
10209 ImGuiTabItem item_tmp = *tab1;
10210 ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2;
10211 ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1;
10212 const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset;
10213 memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem));
10214 *tab2 = item_tmp;
10215
10216 if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
10217 MarkIniSettingsDirty();
10218 return true;
10219 }
10220
10221 static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
10222 {
10223 ImGuiContext& g = *GImGui;
10224 ImGuiWindow* window = g.CurrentWindow;
10225
10226 const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
10227 const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
10228
10229 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
10230 //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));
10231
10232 int select_dir = 0;
10233 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
10234 arrow_col.w *= 0.5f;
10235
10236 PushStyleColor(ImGuiCol_Text, arrow_col);
10237 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
10238 PushItemFlag(ImGuiItemFlags_ButtonRepeat | ImGuiItemFlags_NoNav, true);
10239 const float backup_repeat_delay = g.IO.KeyRepeatDelay;
10240 const float backup_repeat_rate = g.IO.KeyRepeatRate;
10241 g.IO.KeyRepeatDelay = 0.250f;
10242 g.IO.KeyRepeatRate = 0.200f;
10243 float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width);
10244 window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y);
10245 if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
10246 select_dir = -1;
10247 window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y);
10248 if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
10249 select_dir = +1;
10250 PopItemFlag();
10251 PopStyleColor(2);
10252 g.IO.KeyRepeatRate = backup_repeat_rate;
10253 g.IO.KeyRepeatDelay = backup_repeat_delay;
10254
10255 ImGuiTabItem* tab_to_scroll_to = NULL;
10256 if (select_dir != 0)
10257 if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
10258 {
10259 int selected_order = TabBarGetTabOrder(tab_bar, tab_item);
10260 int target_order = selected_order + select_dir;
10261
10262 // Skip tab item buttons until another tab item is found or end is reached
10263 while (tab_to_scroll_to == NULL)
10264 {
10265 // If we are at the end of the list, still scroll to make our tab visible
10266 tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order];
10267
10268 // Cross through buttons
10269 // (even if first/last item is a button, return it so we can update the scroll)
10270 if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button)
10271 {
10272 target_order += select_dir;
10273 selected_order += select_dir;
10274 tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL;
10275 }
10276 }
10277 }
10278 window->DC.CursorPos = backup_cursor_pos;
10279 tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
10280
10281 return tab_to_scroll_to;
10282 }
10283
10284 static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
10285 {
10286 ImGuiContext& g = *GImGui;
10287 ImGuiWindow* window = g.CurrentWindow;
10288
10289 // We use g.Style.FramePadding.y to match the square ArrowButton size
10290 const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
10291 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
10292 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
10293 tab_bar->BarRect.Min.x += tab_list_popup_button_width;
10294
10295 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
10296 arrow_col.w *= 0.5f;
10297 PushStyleColor(ImGuiCol_Text, arrow_col);
10298 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
10299 bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest);
10300 PopStyleColor(2);
10301
10302 ImGuiTabItem* tab_to_select = NULL;
10303 if (open)
10304 {
10305 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
10306 {
10307 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
10308 if (tab->Flags & ImGuiTabItemFlags_Button)
10309 continue;
10310
10311 const char* tab_name = TabBarGetTabName(tab_bar, tab);
10312 if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
10313 tab_to_select = tab;
10314 }
10315 EndCombo();
10316 }
10317
10318 window->DC.CursorPos = backup_cursor_pos;
10319 return tab_to_select;
10320 }
10321
10322 //-------------------------------------------------------------------------
10323 // [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
10324 //-------------------------------------------------------------------------
10325 // - BeginTabItem()
10326 // - EndTabItem()
10327 // - TabItemButton()
10328 // - TabItemEx() [Internal]
10329 // - SetTabItemClosed()
10330 // - TabItemCalcSize() [Internal]
10331 // - TabItemBackground() [Internal]
10332 // - TabItemLabelAndCloseButton() [Internal]
10333 //-------------------------------------------------------------------------
10334
10335 bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
10336 {
10337 ImGuiContext& g = *GImGui;
10338 ImGuiWindow* window = g.CurrentWindow;
10339 if (window->SkipItems)
10340 return false;
10341
10342 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10343 if (tab_bar == NULL)
10344 {
10345 IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!");
10346 return false;
10347 }
10348 IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!
10349
10350 bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL);
10351 if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
10352 {
10353 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10354 PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
10355 }
10356 return ret;
10357 }
10358
10359 void ImGui::EndTabItem()
10360 {
10361 ImGuiContext& g = *GImGui;
10362 ImGuiWindow* window = g.CurrentWindow;
10363 if (window->SkipItems)
10364 return;
10365
10366 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10367 if (tab_bar == NULL)
10368 {
10369 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10370 return;
10371 }
10372 IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
10373 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10374 if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
10375 PopID();
10376 }
10377
10378 bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags)
10379 {
10380 ImGuiContext& g = *GImGui;
10381 ImGuiWindow* window = g.CurrentWindow;
10382 if (window->SkipItems)
10383 return false;
10384
10385 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10386 if (tab_bar == NULL)
10387 {
10388 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10389 return false;
10390 }
10391 return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL);
10392 }
10393
10394 void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width)
10395 {
10396 ImGuiContext& g = *GImGui;
10397 ImGuiWindow* window = g.CurrentWindow;
10398 if (window->SkipItems)
10399 return;
10400
10401 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10402 if (tab_bar == NULL)
10403 {
10404 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10405 return;
10406 }
10407 SetNextItemWidth(width);
10408 TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL);
10409 }
10410
10411 bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window)
10412 {
10413 // Layout whole tab bar if not already done
10414 ImGuiContext& g = *GImGui;
10415 if (tab_bar->WantLayout)
10416 {
10417 ImGuiNextItemData backup_next_item_data = g.NextItemData;
10418 TabBarLayout(tab_bar);
10419 g.NextItemData = backup_next_item_data;
10420 }
10421 ImGuiWindow* window = g.CurrentWindow;
10422 if (window->SkipItems)
10423 return false;
10424
10425 const ImGuiStyle& style = g.Style;
10426 const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window);
10427
10428 // If the user called us with *p_open == false, we early out and don't render.
10429 // 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.
10430 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
10431 if (p_open && !*p_open)
10432 {
10433 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
10434 return false;
10435 }
10436
10437 IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button));
10438 IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing
10439
10440 // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)
10441 if (flags & ImGuiTabItemFlags_NoCloseButton)
10442 p_open = NULL;
10443 else if (p_open == NULL)
10444 flags |= ImGuiTabItemFlags_NoCloseButton;
10445
10446 // Acquire tab data
10447 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
10448 bool tab_is_new = false;
10449 if (tab == NULL)
10450 {
10451 tab_bar->Tabs.push_back(ImGuiTabItem());
10452 tab = &tab_bar->Tabs.back();
10453 tab->ID = id;
10454 tab_bar->TabsAddedNew = tab_is_new = true;
10455 }
10456 tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab);
10457
10458 // Calculate tab contents size
10459 ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument));
10460 tab->RequestedWidth = -1.0f;
10461 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
10462 size.x = tab->RequestedWidth = g.NextItemData.Width;
10463 if (tab_is_new)
10464 tab->Width = ImMax(1.0f, size.x);
10465 tab->ContentWidth = size.x;
10466 tab->BeginOrder = tab_bar->TabsActiveCount++;
10467
10468 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
10469 const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
10470 const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
10471 const bool tab_just_unsaved = (flags & ImGuiTabItemFlags_UnsavedDocument) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
10472 const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0;
10473 tab->LastFrameVisible = g.FrameCount;
10474 tab->Flags = flags;
10475 tab->Window = docked_window;
10476
10477 // Append name _WITH_ the zero-terminator
10478 // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar)
10479 if (docked_window != NULL)
10480 {
10481 IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode);
10482 tab->NameOffset = -1;
10483 }
10484 else
10485 {
10486 tab->NameOffset = (ImS32)tab_bar->TabsNames.size();
10487 tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1);
10488 }
10489
10490 // Update selected tab
10491 if (!is_tab_button)
10492 {
10493 if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
10494 if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
10495 TabBarQueueFocus(tab_bar, tab); // New tabs gets activated
10496 if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // _SetSelected can only be passed on explicit tab bar
10497 TabBarQueueFocus(tab_bar, tab);
10498 }
10499
10500 // Lock visibility
10501 // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)
10502 bool tab_contents_visible = (tab_bar->VisibleTabId == id);
10503 if (tab_contents_visible)
10504 tab_bar->VisibleTabWasSubmitted = true;
10505
10506 // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
10507 if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing && docked_window == NULL)
10508 if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
10509 tab_contents_visible = true;
10510
10511 // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted
10512 // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'.
10513 if (tab_appearing && (!tab_bar_appearing || tab_is_new))
10514 {
10515 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
10516 if (is_tab_button)
10517 return false;
10518 return tab_contents_visible;
10519 }
10520
10521 if (tab_bar->SelectedTabId == id)
10522 tab->LastFrameSelected = g.FrameCount;
10523
10524 // Backup current layout position
10525 const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
10526
10527 // Layout
10528 const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
10529 size.x = tab->Width;
10530 if (is_central_section)
10531 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_TRUNC(tab->Offset - tab_bar->ScrollingAnim), 0.0f);
10532 else
10533 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f);
10534 ImVec2 pos = window->DC.CursorPos;
10535 ImRect bb(pos, pos + size);
10536
10537 // 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)
10538 const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX);
10539 if (want_clip_rect)
10540 PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true);
10541
10542 ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
10543 ItemSize(bb.GetSize(), style.FramePadding.y);
10544 window->DC.CursorMaxPos = backup_cursor_max_pos;
10545
10546 if (!ItemAdd(bb, id))
10547 {
10548 if (want_clip_rect)
10549 PopClipRect();
10550 window->DC.CursorPos = backup_main_cursor_pos;
10551 return tab_contents_visible;
10552 }
10553
10554 // Click to Select a tab
10555 ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap);
10556 if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this
10557 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
10558 bool hovered, held, pressed;
10559 if (flags & ImGuiTabItemFlags_Invisible)
10560 hovered = held = pressed = false;
10561 else
10562 pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
10563 if (pressed && !is_tab_button)
10564 TabBarQueueFocus(tab_bar, tab);
10565
10566 // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow()
10567 // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id.
10568 if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated)
10569 g.ActiveIdWindow = docked_window;
10570
10571 // Drag and drop a single floating window node moves it
10572 ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL;
10573 const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1);
10574 if (held && single_floating_window_node && IsMouseDragging(0, 0.0f))
10575 {
10576 // Move
10577 StartMouseMovingWindow(docked_window);
10578 }
10579 else if (held && !tab_appearing && IsMouseDragging(0))
10580 {
10581 // Drag and drop: re-order tabs
10582 int drag_dir = 0;
10583 float drag_distance_from_edge_x = 0.0f;
10584 if (!g.DragDropActive && ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (docked_window != NULL)))
10585 {
10586 // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
10587 if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
10588 {
10589 drag_dir = -1;
10590 drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x;
10591 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10592 }
10593 else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
10594 {
10595 drag_dir = +1;
10596 drag_distance_from_edge_x = g.IO.MousePos.x - bb.Max.x;
10597 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10598 }
10599 }
10600
10601 // Extract a Dockable window out of it's tab bar
10602 const bool can_undock = docked_window != NULL && !(docked_window->Flags & ImGuiWindowFlags_NoMove) && !(node->MergedFlags & ImGuiDockNodeFlags_NoUndocking);
10603 if (can_undock)
10604 {
10605 // We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar
10606 bool undocking_tab = (g.DragDropActive && g.DragDropPayload.SourceId == id);
10607 if (!undocking_tab) //&& (!g.IO.ConfigDockingWithShift || g.IO.KeyShift)
10608 {
10609 float threshold_base = g.FontSize;
10610 float threshold_x = (threshold_base * 2.2f);
10611 float threshold_y = (threshold_base * 1.5f) + ImClamp((ImFabs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0f) * 0.20f, 0.0f, threshold_base * 4.0f);
10612 //GetForegroundDrawList()->AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE); // [DEBUG]
10613
10614 float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y);
10615 if (distance_from_edge_y >= threshold_y)
10616 undocking_tab = true;
10617 if (drag_distance_from_edge_x > threshold_x)
10618 if ((drag_dir < 0 && TabBarGetTabOrder(tab_bar, tab) == 0) || (drag_dir > 0 && TabBarGetTabOrder(tab_bar, tab) == tab_bar->Tabs.Size - 1))
10619 undocking_tab = true;
10620 }
10621
10622 if (undocking_tab)
10623 {
10624 // Undock
10625 // FIXME: refactor to share more code with e.g. StartMouseMovingWindow
10626 DockContextQueueUndockWindow(&g, docked_window);
10627 g.MovingWindow = docked_window;
10628 SetActiveID(g.MovingWindow->MoveId, g.MovingWindow);
10629 g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min;
10630 g.ActiveIdNoClearOnFocusLoss = true;
10631 SetActiveIdUsingAllKeyboardKeys();
10632 }
10633 }
10634 }
10635
10636 #if 0
10637 if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth)
10638 {
10639 // Enlarge tab display when hovering
10640 bb.Max.x = bb.Min.x + IM_TRUNC(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)));
10641 display_draw_list = GetForegroundDrawList(window);
10642 TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
10643 }
10644 #endif
10645
10646 // Render tab shape
10647 const bool is_visible = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && !(flags & ImGuiTabItemFlags_Invisible);
10648 if (is_visible)
10649 {
10650 ImDrawList* display_draw_list = window->DrawList;
10651 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));
10652 TabItemBackground(display_draw_list, bb, flags, tab_col);
10653 if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f)
10654 {
10655 // Might be moved to TabItemBackground() ?
10656 ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale);
10657 ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale);
10658 ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline);
10659 if (style.TabRounding > 0.0f)
10660 {
10661 float rounding = style.TabRounding;
10662 display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9);
10663 display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11);
10664 display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize);
10665 }
10666 else
10667 {
10668 display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize);
10669 }
10670 }
10671 RenderNavCursor(bb, id);
10672
10673 // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
10674 const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
10675 if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button)
10676 TabBarQueueFocus(tab_bar, tab);
10677
10678 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
10679 flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
10680
10681 // Render tab label, process close button
10682 const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0;
10683 bool just_closed;
10684 bool text_clipped;
10685 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);
10686 if (just_closed && p_open != NULL)
10687 {
10688 *p_open = false;
10689 TabBarCloseTab(tab_bar, tab);
10690 }
10691
10692 // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent)
10693 // That state is copied to window->DockTabItemStatusFlags by our caller.
10694 if (docked_window && (hovered || g.HoveredId == close_button_id))
10695 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10696
10697 // Tooltip
10698 // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)
10699 // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)
10700 // FIXME: This is a mess.
10701 // FIXME: We may want disabled tab to still display the tooltip?
10702 if (text_clipped && g.HoveredId == id && !held)
10703 if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))
10704 SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
10705 }
10706
10707 // Restore main window position so user can draw there
10708 if (want_clip_rect)
10709 PopClipRect();
10710 window->DC.CursorPos = backup_main_cursor_pos;
10711
10712 IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected
10713 if (is_tab_button)
10714 return pressed;
10715 return tab_contents_visible;
10716 }
10717
10718 // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
10719 // To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar().
10720 // Tabs closed by the close button will automatically be flagged to avoid this issue.
10721 void ImGui::SetTabItemClosed(const char* label)
10722 {
10723 ImGuiContext& g = *GImGui;
10724 bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
10725 if (is_within_manual_tab_bar)
10726 {
10727 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10728 ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL);
10729 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
10730 tab->WantClose = true; // Will be processed by next call to TabBarLayout()
10731 }
10732 else if (ImGuiWindow* window = FindWindowByName(label))
10733 {
10734 if (window->DockIsActive)
10735 if (ImGuiDockNode* node = window->DockNode)
10736 {
10737 ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window);
10738 TabBarRemoveTab(node->TabBar, tab_id);
10739 window->DockTabWantClose = true;
10740 }
10741 }
10742 }
10743
10744 ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker)
10745 {
10746 ImGuiContext& g = *GImGui;
10747 ImVec2 label_size = CalcTextSize(label, NULL, true);
10748 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
10749 if (has_close_button_or_unsaved_marker)
10750 size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
10751 else
10752 size.x += g.Style.FramePadding.x + 1.0f;
10753 return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
10754 }
10755
10756 ImVec2 ImGui::TabItemCalcSize(ImGuiWindow* window)
10757 {
10758 return TabItemCalcSize(window->Name, window->HasCloseButton || (window->Flags & ImGuiWindowFlags_UnsavedDocument));
10759 }
10760
10761 void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
10762 {
10763 // 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.
10764 ImGuiContext& g = *GImGui;
10765 const float width = bb.GetWidth();
10766 IM_UNUSED(flags);
10767 IM_ASSERT(width > 0.0f);
10768 const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f));
10769 const float y1 = bb.Min.y + 1.0f;
10770 const float y2 = bb.Max.y - g.Style.TabBarBorderSize;
10771 draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
10772 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
10773 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
10774 draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
10775 draw_list->PathFillConvex(col);
10776 if (g.Style.TabBorderSize > 0.0f)
10777 {
10778 draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
10779 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
10780 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
10781 draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
10782 draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize);
10783 }
10784 }
10785
10786 // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
10787 // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
10788 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)
10789 {
10790 ImGuiContext& g = *GImGui;
10791 ImVec2 label_size = CalcTextSize(label, NULL, true);
10792
10793 if (out_just_closed)
10794 *out_just_closed = false;
10795 if (out_text_clipped)
10796 *out_text_clipped = false;
10797
10798 if (bb.GetWidth() <= 1.0f)
10799 return;
10800
10801 // In Style V2 we'll have full override of all colors per state (e.g. focused, selected)
10802 // But right now if you want to alter text color of tabs this is what you need to do.
10803 #if 0
10804 const float backup_alpha = g.Style.Alpha;
10805 if (!is_contents_visible)
10806 g.Style.Alpha *= 0.7f;
10807 #endif
10808
10809 // Render text label (with clipping + alpha gradient) + unsaved marker
10810 ImRect text_ellipsis_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
10811
10812 // Return clipped state ignoring the close button
10813 if (out_text_clipped)
10814 {
10815 *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x;
10816 //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));
10817 }
10818
10819 const float button_sz = g.FontSize;
10820 const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y);
10821
10822 // Close Button & Unsaved Marker
10823 // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
10824 // 'hovered' will be true when hovering the Tab but NOT when hovering the close button
10825 // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
10826 // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
10827 bool close_button_pressed = false;
10828 bool close_button_visible = false;
10829 bool is_hovered = g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id; // Any interaction account for this too.
10830
10831 if (close_button_id != 0)
10832 {
10833 if (is_contents_visible)
10834 close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected));
10835 else
10836 close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected));
10837 }
10838
10839 // When tabs/document is unsaved, the unsaved marker takes priority over the close button.
10840 const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered);
10841 if (unsaved_marker_visible)
10842 {
10843 const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz));
10844 RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));
10845 }
10846 else if (close_button_visible)
10847 {
10848 ImGuiLastItemData last_item_backup = g.LastItemData;
10849 if (CloseButton(close_button_id, button_pos))
10850 close_button_pressed = true;
10851 g.LastItemData = last_item_backup;
10852
10853 // Close with middle mouse button
10854 if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
10855 close_button_pressed = true;
10856 }
10857
10858 // This is all rather complicated
10859 // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position)
10860 // 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..
10861 float ellipsis_max_x = text_ellipsis_clip_bb.Max.x;
10862 if (close_button_visible || unsaved_marker_visible)
10863 {
10864 const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f;
10865 if (visible_without_hover)
10866 {
10867 text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f;
10868 ellipsis_max_x -= button_sz * 0.90f;
10869 }
10870 else
10871 {
10872 text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f;
10873 }
10874 }
10875 LogSetNextTextDecoration("/", "\\");
10876 RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size);
10877
10878 #if 0
10879 if (!is_contents_visible)
10880 g.Style.Alpha = backup_alpha;
10881 #endif
10882
10883 if (out_just_closed)
10884 *out_just_closed = close_button_pressed;
10885 }
10886
10887
10888 #endif // #ifndef IMGUI_DISABLE