Debian Codegraph @

extern/imgui_patched/imgui_widgets.cpp

raw
1 // dear imgui, v1.92.2b
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 // TODO: implement functions for multiline input with word wrap again.
138 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false);
139 static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
140 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
141
142 //-------------------------------------------------------------------------
143 // [SECTION] Widgets: Text, etc.
144 //-------------------------------------------------------------------------
145 // - TextEx() [Internal]
146 // - TextUnformatted()
147 // - Text()
148 // - TextV()
149 // - TextColored()
150 // - TextColoredV()
151 // - TextDisabled()
152 // - TextDisabledV()
153 // - TextWrapped()
154 // - TextWrappedV()
155 // - LabelText()
156 // - LabelTextV()
157 // - BulletText()
158 // - BulletTextV()
159 //-------------------------------------------------------------------------
160
161 void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
162 {
163 ImGuiWindow* window = GetCurrentWindow();
164 if (window->SkipItems)
165 return;
166 ImGuiContext& g = *GImGui;
167
168 // Accept null ranges
169 if (text == text_end)
170 text = text_end = "";
171
172 // Calculate length
173 const char* text_begin = text;
174 if (text_end == NULL)
175 text_end = text + ImStrlen(text); // FIXME-OPT
176
177 text_end = FindRenderedTextEnd(text, text_end); //hides everything after ##
178
179 const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
180 const float wrap_pos_x = window->DC.TextWrapPos;
181 const bool wrap_enabled = (wrap_pos_x >= 0.0f);
182 if (text_end - text <= 2000 || wrap_enabled)
183 {
184 // Common case
185 const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
186 const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
187
188 ImRect bb(text_pos, text_pos + text_size);
189 ItemSize(text_size, 0.0f);
190 if (!ItemAdd(bb, 0))
191 return;
192
193 // Render (we don't hide text after ## in this end-user function)
194 RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
195 }
196 else
197 {
198 // Long text!
199 // Perform manual coarse clipping to optimize for long multi-line text
200 // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
201 // - 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.
202 // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
203 const char* line = text;
204 const float line_height = GetTextLineHeight();
205 ImVec2 text_size(0, 0);
206
207 // Lines to skip (can't skip when logging text)
208 ImVec2 pos = text_pos;
209 if (!g.LogEnabled)
210 {
211 int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
212 if (lines_skippable > 0)
213 {
214 int lines_skipped = 0;
215 while (line < text_end && lines_skipped < lines_skippable)
216 {
217 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
218 if (!line_end)
219 line_end = text_end;
220 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
221 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
222 line = line_end + 1;
223 lines_skipped++;
224 }
225 pos.y += lines_skipped * line_height;
226 }
227 }
228
229 // Lines to render
230 if (line < text_end)
231 {
232 ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
233 while (line < text_end)
234 {
235 if (IsClippedEx(line_rect, 0))
236 break;
237
238 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
239 if (!line_end)
240 line_end = text_end;
241 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
242 RenderText(pos, line, line_end, false);
243 line = line_end + 1;
244 line_rect.Min.y += line_height;
245 line_rect.Max.y += line_height;
246 pos.y += line_height;
247 }
248
249 // Count remaining lines
250 int lines_skipped = 0;
251 while (line < text_end)
252 {
253 const char* line_end = (const char*)ImMemchr(line, '\n', text_end - line);
254 if (!line_end)
255 line_end = text_end;
256 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
257 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
258 line = line_end + 1;
259 lines_skipped++;
260 }
261 pos.y += lines_skipped * line_height;
262 }
263 text_size.y = (pos - text_pos).y;
264
265 ImRect bb(text_pos, text_pos + text_size);
266 ItemSize(text_size, 0.0f);
267 ItemAdd(bb, 0);
268 }
269 }
270
271 void ImGui::TextExNoHashHide(const char* text, const char* text_end, ImGuiTextFlags flags)
272 {
273 ImGuiWindow* window = GetCurrentWindow();
274 if (window->SkipItems)
275 return;
276 ImGuiContext& g = *GImGui;
277
278 // Accept null ranges
279 if (text == text_end)
280 text = text_end = "";
281
282 // Calculate length
283 const char* text_begin = text;
284 if (text_end == NULL)
285 text_end = text + strlen(text); // FIXME-OPT
286
287 //text_end = FindRenderedTextEnd(text, text_end); //hides everything after ##
288
289 const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
290 const float wrap_pos_x = window->DC.TextWrapPos;
291 const bool wrap_enabled = (wrap_pos_x >= 0.0f);
292 if (text_end - text <= 2000 || wrap_enabled)
293 {
294 // Common case
295 const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
296 const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
297
298 ImRect bb(text_pos, text_pos + text_size);
299 ItemSize(text_size, 0.0f);
300 if (!ItemAdd(bb, 0))
301 return;
302
303 // Render (we don't hide text after ## in this end-user function)
304 RenderTextWrappedNoHashHide(bb.Min, text_begin, text_end, wrap_width);
305 }
306 else
307 {
308 // Long text!
309 // Perform manual coarse clipping to optimize for long multi-line text
310 // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
311 // - 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.
312 // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
313 const char* line = text;
314 const float line_height = GetTextLineHeight();
315 ImVec2 text_size(0, 0);
316
317 // Lines to skip (can't skip when logging text)
318 ImVec2 pos = text_pos;
319 if (!g.LogEnabled)
320 {
321 int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
322 if (lines_skippable > 0)
323 {
324 int lines_skipped = 0;
325 while (line < text_end && lines_skipped < lines_skippable)
326 {
327 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
328 if (!line_end)
329 line_end = text_end;
330 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
331 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end, false).x);
332 line = line_end + 1;
333 lines_skipped++;
334 }
335 pos.y += lines_skipped * line_height;
336 }
337 }
338
339 // Lines to render
340 if (line < text_end)
341 {
342 ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
343 while (line < text_end)
344 {
345 if (IsClippedEx(line_rect, 0))
346 break;
347
348 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
349 if (!line_end)
350 line_end = text_end;
351 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end, false).x);
352 RenderText(pos, line, line_end, false);
353 line = line_end + 1;
354 line_rect.Min.y += line_height;
355 line_rect.Max.y += line_height;
356 pos.y += line_height;
357 }
358
359 // Count remaining lines
360 int lines_skipped = 0;
361 while (line < text_end)
362 {
363 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
364 if (!line_end)
365 line_end = text_end;
366 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
367 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end, false).x);
368 line = line_end + 1;
369 lines_skipped++;
370 }
371 pos.y += lines_skipped * line_height;
372 }
373 text_size.y = (pos - text_pos).y;
374
375 ImRect bb(text_pos, text_pos + text_size);
376 ItemSize(text_size, 0.0f);
377 ItemAdd(bb, 0);
378 }
379 }
380
381 void ImGui::TextUnformatted(const char* text, const char* text_end)
382 {
383 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
384 }
385
386 void ImGui::Text(const char* fmt, ...)
387 {
388 va_list args;
389 va_start(args, fmt);
390 TextV(fmt, args);
391 va_end(args);
392 }
393
394 void ImGui::TextNoHashHide(const char* fmt, ...)
395 {
396 va_list args;
397 va_start(args, fmt);
398
399 ImGuiWindow* window = GetCurrentWindow();
400 if (window->SkipItems)
401 return;
402
403 const char* text, *text_end;
404 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
405 TextExNoHashHide(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
406
407 va_end(args);
408 }
409
410 void ImGui::TextV(const char* fmt, va_list args)
411 {
412 ImGuiWindow* window = GetCurrentWindow();
413 if (window->SkipItems)
414 return;
415
416 const char* text, *text_end;
417 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
418 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
419 }
420
421 void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
422 {
423 va_list args;
424 va_start(args, fmt);
425 TextColoredV(col, fmt, args);
426 va_end(args);
427 }
428
429 void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
430 {
431 PushStyleColor(ImGuiCol_Text, col);
432 TextV(fmt, args);
433 PopStyleColor();
434 }
435
436 void ImGui::TextDisabled(const char* fmt, ...)
437 {
438 va_list args;
439 va_start(args, fmt);
440 TextDisabledV(fmt, args);
441 va_end(args);
442 }
443
444 void ImGui::TextDisabledV(const char* fmt, va_list args)
445 {
446 ImGuiContext& g = *GImGui;
447 PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
448 TextV(fmt, args);
449 PopStyleColor();
450 }
451
452 void ImGui::TextWrapped(const char* fmt, ...)
453 {
454 va_list args;
455 va_start(args, fmt);
456 TextWrappedV(fmt, args);
457 va_end(args);
458 }
459
460 void ImGui::TextWrappedV(const char* fmt, va_list args)
461 {
462 ImGuiContext& g = *GImGui;
463 const bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
464 if (need_backup)
465 PushTextWrapPos(0.0f);
466 TextV(fmt, args);
467 if (need_backup)
468 PopTextWrapPos();
469 }
470
471 void ImGui::TextAligned(float align_x, float size_x, const char* fmt, ...)
472 {
473 va_list args;
474 va_start(args, fmt);
475 TextAlignedV(align_x, size_x, fmt, args);
476 va_end(args);
477 }
478
479 // align_x: 0.0f = left, 0.5f = center, 1.0f = right.
480 // size_x : 0.0f = shortcut for GetContentRegionAvail().x
481 // FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024)
482 void ImGui::TextAlignedV(float align_x, float size_x, const char* fmt, va_list args)
483 {
484 ImGuiWindow* window = GetCurrentWindow();
485 if (window->SkipItems)
486 return;
487
488 const char* text, *text_end;
489 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
490 const ImVec2 text_size = CalcTextSize(text, text_end);
491 size_x = CalcItemSize(ImVec2(size_x, 0.0f), 0.0f, text_size.y).x;
492
493 ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
494 ImVec2 pos_max(pos.x + size_x, window->ClipRect.Max.y);
495 ImVec2 size(ImMin(size_x, text_size.x), text_size.y);
496 window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, pos.x + text_size.x);
497 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, pos.x + text_size.x);
498 if (align_x > 0.0f && text_size.x < size_x)
499 pos.x += ImTrunc((size_x - text_size.x) * align_x);
500 RenderTextEllipsis(window->DrawList, pos, pos_max, pos_max.x, text, text_end, &text_size);
501
502 const ImVec2 backup_max_pos = window->DC.CursorMaxPos;
503 ItemSize(size);
504 ItemAdd(ImRect(pos, pos + size), 0);
505 window->DC.CursorMaxPos.x = backup_max_pos.x; // Cancel out extending content size because right-aligned text would otherwise mess it up.
506
507 if (size_x < text_size.x && IsItemHovered(ImGuiHoveredFlags_NoNavOverride | ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_ForTooltip))
508 SetTooltip("%.*s", (int)(text_end - text), text);
509 }
510
511 void ImGui::LabelText(const char* label, const char* fmt, ...)
512 {
513 va_list args;
514 va_start(args, fmt);
515 LabelTextV(label, fmt, args);
516 va_end(args);
517 }
518
519 // Add a label+text combo aligned to other label+value widgets
520 void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
521 {
522 ImGuiWindow* window = GetCurrentWindow();
523 if (window->SkipItems)
524 return;
525
526 ImGuiContext& g = *GImGui;
527 const ImGuiStyle& style = g.Style;
528 const float w = CalcItemWidth();
529
530 const char* value_text_begin, *value_text_end;
531 ImFormatStringToTempBufferV(&value_text_begin, &value_text_end, fmt, args);
532 const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false);
533 const ImVec2 label_size = CalcTextSize(label, NULL, true);
534
535 const ImVec2 pos = window->DC.CursorPos;
536 const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2));
537 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));
538 ItemSize(total_bb, style.FramePadding.y);
539 if (!ItemAdd(total_bb, 0))
540 return;
541
542 // Render
543 RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f));
544 if (label_size.x > 0.0f)
545 RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
546 }
547
548 void ImGui::BulletText(const char* fmt, ...)
549 {
550 va_list args;
551 va_start(args, fmt);
552 BulletTextV(fmt, args);
553 va_end(args);
554 }
555
556 // Text with a little bullet aligned to the typical tree node.
557 void ImGui::BulletTextV(const char* fmt, va_list args)
558 {
559 ImGuiWindow* window = GetCurrentWindow();
560 if (window->SkipItems)
561 return;
562
563 ImGuiContext& g = *GImGui;
564 const ImGuiStyle& style = g.Style;
565
566 const char* text_begin, *text_end;
567 ImFormatStringToTempBufferV(&text_begin, &text_end, fmt, args);
568 const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
569 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
570 ImVec2 pos = window->DC.CursorPos;
571 pos.y += window->DC.CurrLineTextBaseOffset;
572 ItemSize(total_size, 0.0f);
573 const ImRect bb(pos, pos + total_size);
574 if (!ItemAdd(bb, 0))
575 return;
576
577 // Render
578 ImU32 text_col = GetColorU32(ImGuiCol_Text);
579 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col);
580 RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);
581 }
582
583 //-------------------------------------------------------------------------
584 // [SECTION] Widgets: ScrollText (tildearrow)
585 //-------------------------------------------------------------------------
586 // - ScrollText()
587 //-------------------------------------------------------------------------
588
589 void ImGui::ScrollText(ImGuiID id, const char* text, const ImVec2& pos, ImVec2 size, bool alwaysScroll) {
590 ImGuiContext& g = *GImGui;
591 ImGuiWindow* window=g.CurrentWindow;
592 ImDrawList* dl=window->DrawList;
593 ImGuiStorage* storage=GetStateStorage();
594
595 ImVec2 textSize=ImGui::CalcTextSize(text, NULL, true);
596 bool mustNotScroll=false;
597
598 if (size.x==0) {
599 size.x=((window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max).x-pos.x;
600 if (textSize.x<size.x) {
601 size.x=textSize.x;
602 mustNotScroll=true;
603 }
604 }
605 if (size.y==0) {
606 size.y=ImGui::GetFontSize();
607 }
608
609 ImVec2 minArea=pos;
610 ImVec2 maxArea=ImVec2(
611 minArea.x+size.x,
612 minArea.y+size.y
613 );
614 ImRect rect=ImRect(minArea,maxArea);
615 bool hovered=ImGui::IsMouseHoveringRect(rect.Min,rect.Max);
616 float textPos=storage->GetFloat(id,0.0f);
617
618 dl->PushClipRect(minArea,maxArea,true);
619 if (hovered || alwaysScroll || g.IO.AlwaysScrollText) {
620 minArea.x-=textPos;
621 }
622 dl->AddText(minArea,ImGui::GetColorU32(ImGuiCol_Text),text);
623 if ((hovered || alwaysScroll || g.IO.AlwaysScrollText) && !mustNotScroll) {
624 textPos+=g.IO.DeltaTime*g.IO.ScrollTextSpeed;
625 if (textPos>textSize.x) {
626 textPos-=textSize.x+size.x+g.IO.ScrollTextSpacing;
627 }
628 g.IO.IsSomethingHappening=true;
629 } else {
630 textPos=0.0;
631 }
632 storage->SetFloat(id,textPos);
633 dl->PopClipRect();
634 }
635
636 //-------------------------------------------------------------------------
637 // [SECTION] Widgets: Main
638 //-------------------------------------------------------------------------
639 // - ButtonBehavior() [Internal]
640 // - Button()
641 // - SmallButton()
642 // - InvisibleButton()
643 // - ArrowButton()
644 // - CloseButton() [Internal]
645 // - CollapseButton() [Internal]
646 // - GetWindowScrollbarID() [Internal]
647 // - GetWindowScrollbarRect() [Internal]
648 // - Scrollbar() [Internal]
649 // - ScrollbarEx() [Internal]
650 // - Image()
651 // - ImageButton()
652 // - Checkbox()
653 // - CheckboxFlagsT() [Internal]
654 // - CheckboxFlags()
655 // - RadioButton()
656 // - ProgressBar()
657 // - Bullet()
658 // - Hyperlink()
659 //-------------------------------------------------------------------------
660
661 // The ButtonBehavior() function is key to many interactions and used by many/most widgets.
662 // Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),
663 // this code is a little complex.
664 // By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.
665 // See the series of events below and the corresponding state reported by dear imgui:
666 //------------------------------------------------------------------------------------------------------------------------------------------------
667 // with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
668 // Frame N+0 (mouse is outside bb) - - - - - -
669 // Frame N+1 (mouse moves inside bb) - true - - - -
670 // Frame N+2 (mouse button is down) - true true true - true
671 // Frame N+3 (mouse button is down) - true true - - -
672 // Frame N+4 (mouse moves outside bb) - - true - - -
673 // Frame N+5 (mouse moves inside bb) - true true - - -
674 // Frame N+6 (mouse button is released) true true - - true -
675 // Frame N+7 (mouse button is released) - true - - - -
676 // Frame N+8 (mouse moves outside bb) - - - - - -
677 //------------------------------------------------------------------------------------------------------------------------------------------------
678 // with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
679 // Frame N+2 (mouse button is down) true true true true - true
680 // Frame N+3 (mouse button is down) - true true - - -
681 // Frame N+6 (mouse button is released) - true - - true -
682 // Frame N+7 (mouse button is released) - true - - - -
683 //------------------------------------------------------------------------------------------------------------------------------------------------
684 // with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
685 // Frame N+2 (mouse button is down) - true - - - true
686 // Frame N+3 (mouse button is down) - true - - - -
687 // Frame N+6 (mouse button is released) true true - - - -
688 // Frame N+7 (mouse button is released) - true - - - -
689 //------------------------------------------------------------------------------------------------------------------------------------------------
690 // with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
691 // Frame N+0 (mouse button is down) - true - - - true
692 // Frame N+1 (mouse button is down) - true - - - -
693 // Frame N+2 (mouse button is released) - true - - - -
694 // Frame N+3 (mouse button is released) - true - - - -
695 // Frame N+4 (mouse button is down) true true true true - true
696 // Frame N+5 (mouse button is down) - true true - - -
697 // Frame N+6 (mouse button is released) - true - - true -
698 // Frame N+7 (mouse button is released) - true - - - -
699 //------------------------------------------------------------------------------------------------------------------------------------------------
700 // Note that some combinations are supported,
701 // - PressedOnDragDropHold can generally be associated with any flag.
702 // - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
703 //------------------------------------------------------------------------------------------------------------------------------------------------
704 // The behavior of the return-value changes when ImGuiItemFlags_ButtonRepeat is set:
705 // Repeat+ Repeat+ Repeat+ Repeat+
706 // PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
707 //-------------------------------------------------------------------------------------------------------------------------------------------------
708 // Frame N+0 (mouse button is down) - true - true
709 // ... - - - -
710 // Frame N + RepeatDelay true true - true
711 // ... - - - -
712 // Frame N + RepeatDelay + RepeatRate*N true true - true
713 //-------------------------------------------------------------------------------------------------------------------------------------------------
714
715 // - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc.
716 // And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
717 // For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
718 // - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature.
719 // One idiom which was previously valid which will now emit a warning is when using multiple overlaid ButtonBehavior()
720 // with same ID and different MouseButton (see #8030). You can fix it by:
721 // (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags.
722 // or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
723 bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
724 {
725 ImGuiContext& g = *GImGui;
726 ImGuiWindow* window = GetCurrentWindow();
727
728 // Default behavior inherited from item flags
729 // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
730 ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
731 if (flags & ImGuiButtonFlags_AllowOverlap)
732 item_flags |= ImGuiItemFlags_AllowOverlap;
733 if (item_flags & ImGuiItemFlags_NoFocus)
734 flags |= ImGuiButtonFlags_NoFocus | ImGuiButtonFlags_NoNavFocus;
735
736 // Default only reacts to left mouse button
737 if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
738 flags |= ImGuiButtonFlags_MouseButtonLeft;
739
740 // Default behavior requires click + release inside bounding box
741 if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
742 flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_;
743
744 ImGuiWindow* backup_hovered_window = g.HoveredWindow;
745 const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindowDockTree == window->RootWindowDockTree;
746 if (flatten_hovered_children)
747 g.HoveredWindow = window;
748
749 #ifdef IMGUI_ENABLE_TEST_ENGINE
750 // Alternate registration spot, for when caller didn't use ItemAdd()
751 if (g.LastItemData.ID != id)
752 IMGUI_TEST_ENGINE_ITEM_ADD(id, bb, NULL);
753 #endif
754
755 bool pressed = false;
756 bool hovered = ItemHoverable(bb, id, item_flags);
757
758 // Special mode for Drag and Drop used by openables (tree nodes, tabs etc.)
759 // where holding the button pressed for a long time while drag a payload item triggers the button.
760 if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
761 if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
762 {
763 hovered = true;
764 SetHoveredID(id);
765 if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER)
766 {
767 pressed = true;
768 g.DragDropHoldJustPressedId = id;
769 FocusWindow(window);
770 }
771 }
772
773 if (flatten_hovered_children)
774 g.HoveredWindow = backup_hovered_window;
775
776 // Mouse handling
777 const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
778 if (hovered)
779 {
780 IM_ASSERT(id != 0); // Lazily check inside rare path.
781
782 // Poll mouse buttons
783 // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId.
784 // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine.
785 int mouse_button_clicked = -1;
786 int mouse_button_released = -1;
787 for (int button = 0; button < 3; button++)
788 if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here.
789 {
790 if (IsMouseClicked(button, ImGuiInputFlags_None, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; }
791 if (IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; }
792 }
793
794 // Process initial action
795 const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt);
796 if (mods_ok)
797 {
798 if (mouse_button_clicked != -1 && g.ActiveId != id)
799 {
800 if (!(flags & ImGuiButtonFlags_NoSetKeyOwner))
801 SetKeyOwner(MouseButtonToKey(mouse_button_clicked), id);
802 if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
803 {
804 SetActiveID(id, window);
805 g.ActiveIdMouseButton = mouse_button_clicked;
806 if (!(flags & ImGuiButtonFlags_NoNavFocus))
807 {
808 SetFocusID(id, window);
809 FocusWindow(window);
810 }
811 else if (!(flags & ImGuiButtonFlags_NoFocus))
812 {
813 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
814 }
815 }
816 if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))
817 {
818 pressed = true;
819 if (flags & ImGuiButtonFlags_NoHoldingActiveId)
820 ClearActiveID();
821 else
822 SetActiveID(id, window); // Hold on ID
823 g.ActiveIdMouseButton = mouse_button_clicked;
824 if (!(flags & ImGuiButtonFlags_NoNavFocus))
825 {
826 SetFocusID(id, window);
827 FocusWindow(window);
828 }
829 else if (!(flags & ImGuiButtonFlags_NoFocus))
830 {
831 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
832 }
833 }
834 }
835 if (flags & ImGuiButtonFlags_PressedOnRelease)
836 {
837 if (mouse_button_released != -1)
838 {
839 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
840 if (!has_repeated_at_least_once)
841 pressed = true;
842 if (!(flags & ImGuiButtonFlags_NoNavFocus))
843 SetFocusID(id, window); // FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why.
844 ClearActiveID();
845 }
846 }
847
848 // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
849 // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
850 if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat))
851 if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id))
852 pressed = true;
853 }
854
855 if (pressed && g.IO.ConfigNavCursorVisibleAuto)
856 g.NavCursorVisible = false;
857 }
858
859 // Keyboard/Gamepad navigation handling
860 // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
861 if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav)
862 if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
863 hovered = true;
864 if (g.NavActivateDownId == id)
865 {
866 bool nav_activated_by_code = (g.NavActivateId == id);
867 bool nav_activated_by_inputs = (g.NavActivatePressedId == id);
868 if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat))
869 {
870 // Avoid pressing multiple keys from triggering excessive amount of repeat events
871 const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space);
872 const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter);
873 const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate);
874 const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration);
875 nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
876 }
877 if (nav_activated_by_code || nav_activated_by_inputs)
878 {
879 // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
880 pressed = true;
881 SetActiveID(id, window);
882 g.ActiveIdSource = g.NavInputSource;
883 if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut))
884 SetFocusID(id, window);
885 if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)
886 g.ActiveIdFromShortcut = true;
887 }
888 }
889
890 // Process while held
891 bool held = false;
892 if (g.ActiveId == id)
893 {
894 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
895 {
896 if (g.ActiveIdIsJustActivated)
897 g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
898
899 const int mouse_button = g.ActiveIdMouseButton;
900 if (mouse_button == -1)
901 {
902 // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
903 ClearActiveID();
904 }
905 else if (IsMouseDown(mouse_button, test_owner_id))
906 {
907 held = true;
908 }
909 else
910 {
911 bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
912 bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
913 if ((release_in || release_anywhere) && !g.DragDropActive)
914 {
915 // Report as pressed when releasing the mouse (this is the most common path)
916 bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;
917 bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
918 bool is_button_avail_or_owned = TestKeyOwner(MouseButtonToKey(mouse_button), test_owner_id);
919 if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned)
920 pressed = true;
921 }
922 ClearActiveID();
923 }
924 if (!(flags & ImGuiButtonFlags_NoNavFocus) && g.IO.ConfigNavCursorVisibleAuto)
925 g.NavCursorVisible = false;
926 }
927 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
928 {
929 // When activated using Nav, we hold on the ActiveID until activation button is released
930 if (g.NavActivateDownId == id)
931 held = true; // hovered == true not true as we are already likely hovered on direct activation.
932 else
933 ClearActiveID();
934 }
935 if (pressed)
936 g.ActiveIdHasBeenPressedBefore = true;
937 }
938
939 // Activation highlight (this may be a remote activation)
940 if (g.NavHighlightActivatedId == id)
941 hovered = true;
942
943 if (out_hovered) *out_hovered = hovered;
944 if (out_held) *out_held = held;
945
946 return pressed;
947 }
948
949 bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
950 {
951 ImGuiWindow* window = GetCurrentWindow();
952 if (window->SkipItems)
953 return false;
954
955 ImGuiContext& g = *GImGui;
956 const ImGuiStyle& style = g.Style;
957 const ImGuiID id = window->GetID(label);
958 const ImVec2 label_size = CalcTextSize(label, NULL, (flags&ImGuiButtonFlags_NoHashTextHide)?false:true);
959
960 ImVec2 pos = window->DC.CursorPos;
961 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)
962 pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
963 ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
964
965 const ImRect bb(pos, pos + size);
966 ItemSize(size, style.FramePadding.y);
967 if (!ItemAdd(bb, id))
968 return false;
969
970 bool hovered, held;
971 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
972
973 // Render
974 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
975 RenderNavCursor(bb, id);
976 RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
977
978 if (g.LogEnabled)
979 LogSetNextTextDecoration("[", "]");
980
981 if (flags & ImGuiButtonFlags_NoHashTextHide) {
982 RenderTextClippedNoHashHide(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
983 } else {
984 RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
985 }
986
987 // Automatically close popups
988 //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
989 // CloseCurrentPopup();
990
991 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
992 return pressed;
993 }
994
995 bool ImGui::Button(const char* label, const ImVec2& size_arg)
996 {
997 return ButtonEx(label, size_arg, ImGuiButtonFlags_None);
998 }
999
1000 // Small buttons fits within text without additional vertical spacing.
1001 bool ImGui::SmallButton(const char* label)
1002 {
1003 ImGuiContext& g = *GImGui;
1004 float backup_padding_y = g.Style.FramePadding.y;
1005 g.Style.FramePadding.y = 0.0f;
1006 bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
1007 g.Style.FramePadding.y = backup_padding_y;
1008 return pressed;
1009 }
1010
1011 // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
1012 // 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)
1013 bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags)
1014 {
1015 ImGuiContext& g = *GImGui;
1016 ImGuiWindow* window = GetCurrentWindow();
1017 if (window->SkipItems)
1018 return false;
1019
1020 // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
1021 IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
1022
1023 const ImGuiID id = window->GetID(str_id);
1024 ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
1025 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
1026 ItemSize(size);
1027 if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav))
1028 return false;
1029
1030 bool hovered, held;
1031 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
1032 RenderNavCursor(bb, id);
1033
1034 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
1035 return pressed;
1036 }
1037
1038 bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
1039 {
1040 ImGuiContext& g = *GImGui;
1041 ImGuiWindow* window = GetCurrentWindow();
1042 if (window->SkipItems)
1043 return false;
1044
1045 const ImGuiID id = window->GetID(str_id);
1046 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
1047 const float default_size = GetFrameHeight();
1048 ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f);
1049 if (!ItemAdd(bb, id))
1050 return false;
1051
1052 bool hovered, held;
1053 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
1054
1055 // Render
1056 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1057 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
1058 RenderNavCursor(bb, id);
1059 RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
1060 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);
1061
1062 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
1063 return pressed;
1064 }
1065
1066 bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
1067 {
1068 float sz = GetFrameHeight();
1069 return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);
1070 }
1071
1072 // Button to close a window
1073 bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)
1074 {
1075 ImGuiContext& g = *GImGui;
1076 ImGuiWindow* window = g.CurrentWindow;
1077
1078 // 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)
1079 // 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?
1080 const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
1081 ImRect bb_interact = bb;
1082 const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea();
1083 if (area_to_visible_ratio < 1.5f)
1084 bb_interact.Expand(ImTrunc(bb_interact.GetSize() * -0.25f));
1085
1086 // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window.
1087 // (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).
1088 bool is_clipped = !ItemAdd(bb_interact, id);
1089
1090 bool hovered, held;
1091 bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held);
1092 if (is_clipped)
1093 return pressed;
1094
1095 // Render
1096 ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
1097 if (hovered)
1098 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
1099 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
1100 const ImU32 cross_col = GetColorU32(ImGuiCol_Text);
1101 const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
1102 const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
1103 const float cross_thickness = 1.0f; // FIXME-DPI
1104 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness);
1105 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, cross_thickness);
1106
1107 return pressed;
1108 }
1109
1110 // The Collapse button also functions as a Dock Menu button.
1111 bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos, ImGuiDockNode* dock_node)
1112 {
1113 ImGuiContext& g = *GImGui;
1114 ImGuiWindow* window = g.CurrentWindow;
1115
1116 ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
1117 bool is_clipped = !ItemAdd(bb, id);
1118 bool hovered, held;
1119 bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
1120 if (is_clipped)
1121 return pressed;
1122
1123 // Render
1124 //bool is_dock_menu = (window->DockNodeAsHost && !window->Collapsed);
1125 ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1126 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1127 if (hovered || held)
1128 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
1129 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
1130
1131 if (dock_node)
1132 RenderArrowDockMenu(window->DrawList, bb.Min, g.FontSize, text_col);
1133 else
1134 RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
1135
1136 // Switch to moving the window after mouse is moved beyond the initial drag threshold
1137 if (IsItemActive() && IsMouseDragging(0))
1138 StartMouseMovingWindowOrNode(window, dock_node, true); // Undock from window/collapse menu button
1139
1140 return pressed;
1141 }
1142
1143 ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
1144 {
1145 return window->GetID(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
1146 }
1147
1148 // Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
1149 ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
1150 {
1151 ImGuiContext& g = *GImGui;
1152 const ImRect outer_rect = window->Rect();
1153 const ImRect inner_rect = window->InnerRect;
1154 const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
1155 IM_ASSERT(scrollbar_size >= 0.0f);
1156 const float border_size = IM_ROUND(window->WindowBorderSize * 0.5f);
1157 const float border_top = (window->Flags & ImGuiWindowFlags_MenuBar) ? IM_ROUND(g.Style.FrameBorderSize * 0.5f) : 0.0f;
1158 if (axis == ImGuiAxis_X)
1159 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);
1160 else
1161 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);
1162 }
1163
1164 void ImGui::Scrollbar(ImGuiAxis axis)
1165 {
1166 ImGuiContext& g = *GImGui;
1167 ImGuiWindow* window = g.CurrentWindow;
1168 const ImGuiID id = GetWindowScrollbarID(window, axis);
1169
1170 // Calculate scrollbar bounding box
1171 ImRect bb = GetWindowScrollbarRect(window, axis);
1172 ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone;
1173 if (axis == ImGuiAxis_X)
1174 {
1175 rounding_corners |= ImDrawFlags_RoundCornersBottomLeft;
1176 if (!window->ScrollbarY)
1177 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
1178 }
1179 else
1180 {
1181 if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))
1182 rounding_corners |= ImDrawFlags_RoundCornersTopRight;
1183 if (!window->ScrollbarX)
1184 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
1185 }
1186 float size_visible = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];
1187 float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;
1188 ImS64 scroll = (ImS64)window->Scroll[axis];
1189 ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_visible, (ImS64)size_contents, rounding_corners);
1190 window->Scroll[axis] = (float)scroll;
1191 }
1192
1193 // Vertical/Horizontal scrollbar
1194 // The entire piece of code below is rather confusing because:
1195 // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
1196 // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
1197 // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
1198 // Still, the code should probably be made simpler..
1199 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)
1200 {
1201 ImGuiContext& g = *GImGui;
1202 ImGuiWindow* window = g.CurrentWindow;
1203 if (window->SkipItems)
1204 return false;
1205
1206 const float bb_frame_width = bb_frame.GetWidth();
1207 const float bb_frame_height = bb_frame.GetHeight();
1208 if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
1209 return false;
1210
1211 // 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)
1212 float alpha = 1.0f;
1213 if ((axis == ImGuiAxis_Y) && bb_frame_height < bb_frame_width)
1214 alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0f, 1.0f));
1215 if (alpha <= 0.0f)
1216 return false;
1217
1218 const ImGuiStyle& style = g.Style;
1219 const bool allow_interaction = (alpha >= 1.0f);
1220
1221 ImRect bb = bb_frame;
1222 bb.Expand(ImVec2(-ImClamp(IM_TRUNC((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_TRUNC((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
1223
1224 // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
1225 const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
1226
1227 // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
1228 // But we maintain a minimum size in pixel to allow for the user to still aim inside.
1229 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.
1230 const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1);
1231 const float grab_h_minsize = ImMin(bb.GetSize()[axis], style.GrabMinSize);
1232 const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), grab_h_minsize, scrollbar_size_v);
1233 const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
1234
1235 // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
1236 bool held = false;
1237 bool hovered = false;
1238 ItemAdd(bb_frame, id, NULL, ImGuiItemFlags_NoNav);
1239 ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
1240
1241 const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_visible_v);
1242 float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
1243 float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space
1244 if (held && allow_interaction && grab_h_norm < 1.0f)
1245 {
1246 const float scrollbar_pos_v = bb.Min[axis];
1247 const float mouse_pos_v = g.IO.MousePos[axis];
1248
1249 // Click position in scrollbar normalized space (0.0f->1.0f)
1250 const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
1251
1252 const int held_dir = (clicked_v_norm < grab_v_norm) ? -1 : (clicked_v_norm > grab_v_norm + grab_h_norm) ? +1 : 0;
1253 if (g.ActiveIdIsJustActivated)
1254 {
1255 // On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab
1256 const bool scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false || g.IO.KeyShift || held_dir == 0);
1257 g.ScrollbarSeekMode = scroll_to_clicked_location ? 0 : (short)held_dir;
1258 g.ScrollbarClickDeltaToGrabCenter = (held_dir == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
1259 }
1260
1261 // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
1262 // 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
1263 if (g.ScrollbarSeekMode == 0)
1264 {
1265 // Absolute seeking
1266 const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
1267 *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max);
1268 }
1269 else
1270 {
1271 // Page by page
1272 if (IsMouseClicked(ImGuiMouseButton_Left, ImGuiInputFlags_Repeat) && held_dir == g.ScrollbarSeekMode)
1273 {
1274 float page_dir = (g.ScrollbarSeekMode > 0.0f) ? +1.0f : -1.0f;
1275 *p_scroll_v = ImClamp(*p_scroll_v + (ImS64)(page_dir * size_visible_v), (ImS64)0, scroll_max);
1276 }
1277 }
1278
1279 // Update values for rendering
1280 scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
1281 grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
1282
1283 // Update distance to grab now that we have seek'ed and saturated
1284 //if (seek_absolute)
1285 // g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
1286 }
1287
1288 // Render
1289 const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
1290 const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : (hovered && !(g.IO.ConfigFlags&ImGuiConfigFlags_NoHoverColors)) ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
1291 window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags);
1292 ImRect grab_rect;
1293 if (axis == ImGuiAxis_X)
1294 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);
1295 else
1296 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);
1297 window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
1298
1299 return held;
1300 }
1301
1302 // - Read about ImTextureID/ImTextureRef here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
1303 // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
1304 void ImGui::ImageWithBg(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
1305 {
1306 ImGuiContext& g = *GImGui;
1307 ImGuiWindow* window = GetCurrentWindow();
1308 if (window->SkipItems)
1309 return;
1310
1311 const ImVec2 padding(g.Style.ImageBorderSize, g.Style.ImageBorderSize);
1312 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1313 ItemSize(bb);
1314 if (!ItemAdd(bb, 0))
1315 return;
1316
1317 // Render
1318 if (g.Style.ImageBorderSize > 0.0f)
1319 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border), 0.0f, ImDrawFlags_None, g.Style.ImageBorderSize);
1320 if (bg_col.w > 0.0f)
1321 window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
1322 window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1323 }
1324
1325 void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1)
1326 {
1327 ImageWithBg(tex_ref, image_size, uv0, uv1);
1328 }
1329
1330 // 1.91.9 (February 2025) removed 'tint_col' and 'border_col' parameters, made border size not depend on color value. (#8131, #8238)
1331 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1332 void ImGui::Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
1333 {
1334 ImGuiContext& g = *GImGui;
1335 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
1336 PushStyleColor(ImGuiCol_Border, border_col);
1337 ImageWithBg(tex_ref, image_size, uv0, uv1, ImVec4(0, 0, 0, 0), tint_col);
1338 PopStyleColor();
1339 PopStyleVar();
1340 }
1341 #endif
1342
1343 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)
1344 {
1345 ImGuiContext& g = *GImGui;
1346 ImGuiWindow* window = GetCurrentWindow();
1347 if (window->SkipItems)
1348 return false;
1349
1350 const ImVec2 padding = g.Style.FramePadding;
1351 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1352 ItemSize(bb);
1353 if (!ItemAdd(bb, id))
1354 return false;
1355
1356 bool hovered, held;
1357 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
1358
1359 // Render
1360 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1361 RenderNavCursor(bb, id);
1362 RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
1363 if (bg_col.w > 0.0f)
1364 window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
1365 window->DrawList->AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1366
1367 return pressed;
1368 }
1369
1370 // - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
1371 // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design?
1372 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)
1373 {
1374 ImGuiContext& g = *GImGui;
1375 ImGuiWindow* window = g.CurrentWindow;
1376 if (window->SkipItems)
1377 return false;
1378
1379 return ImageButtonEx(window->GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col);
1380 }
1381
1382 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1383 // Legacy API obsoleted in 1.89. Two differences with new ImageButton()
1384 // - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
1385 // - new ImageButton() requires an explicit 'const char* str_id'
1386 // - old ImageButton() had frame_padding' override argument.
1387 // - new ImageButton() always use style.FramePadding.
1388 /*
1389 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)
1390 {
1391 // Default to using texture ID as ID. User can still push string/integer prefixes.
1392 PushID((ImTextureID)(intptr_t)user_texture_id);
1393 if (frame_padding >= 0)
1394 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding));
1395 bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col);
1396 if (frame_padding >= 0)
1397 PopStyleVar();
1398 PopID();
1399 return ret;
1400 }
1401 */
1402 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1403
1404 bool ImGui::Checkbox(const char* label, bool* v)
1405 {
1406 ImGuiWindow* window = GetCurrentWindow();
1407 if (window->SkipItems)
1408 return false;
1409
1410 ImGuiContext& g = *GImGui;
1411 const ImGuiStyle& style = g.Style;
1412 const ImGuiID id = window->GetID(label);
1413 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1414
1415 const float square_sz = GetFrameHeight();
1416 const ImVec2 pos = window->DC.CursorPos;
1417 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));
1418 ItemSize(total_bb, style.FramePadding.y);
1419 const bool is_visible = ItemAdd(total_bb, id);
1420 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
1421 if (!is_visible)
1422 if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support
1423 {
1424 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1425 return false;
1426 }
1427
1428 // Range-Selection/Multi-selection support (header)
1429 bool checked = *v;
1430 if (is_multi_select)
1431 MultiSelectItemHeader(id, &checked, NULL);
1432
1433 bool hovered, held;
1434 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1435
1436 // Range-Selection/Multi-selection support (footer)
1437 if (is_multi_select)
1438 MultiSelectItemFooter(id, &checked, &pressed);
1439 else if (pressed)
1440 checked = !checked;
1441
1442 if (*v != checked)
1443 {
1444 *v = checked;
1445 pressed = true; // return value
1446 MarkItemEdited(id);
1447 }
1448
1449 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1450 const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
1451 if (is_visible)
1452 {
1453 RenderNavCursor(total_bb, id);
1454 RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
1455 ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
1456 if (mixed_value)
1457 {
1458 // Undocumented tristate/mixed/indeterminate checkbox (#2644)
1459 // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox)
1460 ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)));
1461 window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
1462 }
1463 else if (*v)
1464 {
1465 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1466 RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f);
1467 }
1468 }
1469 const ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1470 if (g.LogEnabled)
1471 LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]");
1472 if (is_visible && label_size.x > 0.0f) {
1473 ScrollText(id, label, label_pos, ImVec2(0,0), hovered);
1474 }
1475
1476 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1477 return pressed;
1478 }
1479
1480 template<typename T>
1481 bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value)
1482 {
1483 bool all_on = (*flags & flags_value) == flags_value;
1484 bool any_on = (*flags & flags_value) != 0;
1485 bool pressed;
1486 if (!all_on && any_on)
1487 {
1488 ImGuiContext& g = *GImGui;
1489 g.NextItemData.ItemFlags |= ImGuiItemFlags_MixedValue;
1490 pressed = Checkbox(label, &all_on);
1491 }
1492 else
1493 {
1494 pressed = Checkbox(label, &all_on);
1495
1496 }
1497 if (pressed)
1498 {
1499 if (all_on)
1500 *flags |= flags_value;
1501 else
1502 *flags &= ~flags_value;
1503 }
1504 return pressed;
1505 }
1506
1507 bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value)
1508 {
1509 return CheckboxFlagsT(label, flags, flags_value);
1510 }
1511
1512 bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
1513 {
1514 return CheckboxFlagsT(label, flags, flags_value);
1515 }
1516
1517 bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value)
1518 {
1519 return CheckboxFlagsT(label, flags, flags_value);
1520 }
1521
1522 bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value)
1523 {
1524 return CheckboxFlagsT(label, flags, flags_value);
1525 }
1526
1527 bool ImGui::RadioButton(const char* label, bool active)
1528 {
1529 ImGuiWindow* window = GetCurrentWindow();
1530 if (window->SkipItems)
1531 return false;
1532
1533 ImGuiContext& g = *GImGui;
1534 const ImGuiStyle& style = g.Style;
1535 const ImGuiID id = window->GetID(label);
1536 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1537
1538 const float square_sz = GetFrameHeight();
1539 const ImVec2 pos = window->DC.CursorPos;
1540 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1541 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));
1542 ItemSize(total_bb, style.FramePadding.y);
1543 if (!ItemAdd(total_bb, id))
1544 return false;
1545
1546 ImVec2 center = check_bb.GetCenter();
1547 center.x = IM_ROUND(center.x);
1548 center.y = IM_ROUND(center.y);
1549 const float radius = (square_sz - 1.0f) * 0.5f;
1550
1551 bool hovered, held;
1552 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1553 if (pressed)
1554 MarkItemEdited(id);
1555
1556 RenderNavCursor(total_bb, id);
1557 const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius);
1558 window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), num_segment);
1559 if (active)
1560 {
1561 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1562 window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark));
1563 }
1564
1565 if (style.FrameBorderSize > 0.0f)
1566 {
1567 window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), num_segment, style.FrameBorderSize);
1568 window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), num_segment, style.FrameBorderSize);
1569 }
1570
1571 ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1572 if (g.LogEnabled)
1573 LogRenderedText(&label_pos, active ? "(x)" : "( )");
1574 if (label_size.x > 0.0f)
1575 RenderText(label_pos, label);
1576
1577 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1578 return pressed;
1579 }
1580
1581 // 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..
1582 bool ImGui::RadioButton(const char* label, int* v, int v_button)
1583 {
1584 const bool pressed = RadioButton(label, *v == v_button);
1585 if (pressed)
1586 *v = v_button;
1587 return pressed;
1588 }
1589
1590 // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
1591 void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
1592 {
1593 ImGuiWindow* window = GetCurrentWindow();
1594 if (window->SkipItems)
1595 return;
1596
1597 ImGuiContext& g = *GImGui;
1598 const ImGuiStyle& style = g.Style;
1599
1600 ImVec2 pos = window->DC.CursorPos;
1601 ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f);
1602 ImRect bb(pos, pos + size);
1603 ItemSize(size, style.FramePadding.y);
1604 if (!ItemAdd(bb, 0))
1605 return;
1606
1607 // Fraction < 0.0f will display an indeterminate progress bar animation
1608 // The value must be animated along with time, so e.g. passing '-1.0f * ImGui::GetTime()' as fraction works.
1609 const bool is_indeterminate = (fraction < 0.0f);
1610 if (!is_indeterminate)
1611 fraction = ImSaturate(fraction);
1612
1613 // Out of courtesy we accept a NaN fraction without crashing
1614 float fill_n0 = 0.0f;
1615 float fill_n1 = (fraction == fraction) ? fraction : 0.0f;
1616
1617 if (is_indeterminate)
1618 {
1619 const float fill_width_n = 0.2f;
1620 fill_n0 = ImFmod(-fraction, 1.0f) * (1.0f + fill_width_n) - fill_width_n;
1621 fill_n1 = ImSaturate(fill_n0 + fill_width_n);
1622 fill_n0 = ImSaturate(fill_n0);
1623 }
1624
1625 // Render
1626 RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
1627 bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
1628 RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_n0, fill_n1, style.FrameRounding);
1629
1630 // Default displaying the fraction as percentage string, but user can override it
1631 // Don't display text for indeterminate bars by default
1632 char overlay_buf[32];
1633 if (!is_indeterminate || overlay != NULL)
1634 {
1635 if (!overlay)
1636 {
1637 ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f);
1638 overlay = overlay_buf;
1639 }
1640
1641 ImVec2 overlay_size = CalcTextSize(overlay, NULL);
1642 if (overlay_size.x > 0.0f)
1643 {
1644 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;
1645 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);
1646 }
1647 }
1648 }
1649
1650 void ImGui::Bullet()
1651 {
1652 ImGuiWindow* window = GetCurrentWindow();
1653 if (window->SkipItems)
1654 return;
1655
1656 ImGuiContext& g = *GImGui;
1657 const ImGuiStyle& style = g.Style;
1658 const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize);
1659 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
1660 ItemSize(bb);
1661 if (!ItemAdd(bb, 0))
1662 {
1663 SameLine(0, style.FramePadding.x * 2);
1664 return;
1665 }
1666
1667 // Render and stay on same line
1668 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1669 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col);
1670 SameLine(0, style.FramePadding.x * 2.0f);
1671 }
1672
1673 // This is provided as a convenience for being an often requested feature.
1674 // FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system.
1675 // Because of this we currently don't provide many styling options for this widget
1676 // (e.g. hovered/active colors are automatically inferred from a single color).
1677 bool ImGui::TextLink(const char* label)
1678 {
1679 ImGuiWindow* window = GetCurrentWindow();
1680 if (window->SkipItems)
1681 return false;
1682
1683 ImGuiContext& g = *GImGui;
1684 const ImGuiID id = window->GetID(label);
1685 const char* label_end = FindRenderedTextEnd(label);
1686
1687 ImVec2 pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
1688 ImVec2 size = CalcTextSize(label, label_end, true);
1689 ImRect bb(pos, pos + size);
1690 ItemSize(size, 0.0f);
1691 if (!ItemAdd(bb, id))
1692 return false;
1693
1694 bool hovered, held;
1695 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
1696 RenderNavCursor(bb, id);
1697
1698 if (hovered)
1699 SetMouseCursor(ImGuiMouseCursor_Hand);
1700
1701 ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink];
1702 ImVec4 line_colf = text_colf;
1703 {
1704 // FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets,
1705 // as we are currently experimenting/planning a different styling system.
1706 float h, s, v;
1707 ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z, h, s, v);
1708 if (held || hovered)
1709 {
1710 v = ImSaturate(v + (held ? 0.4f : 0.3f));
1711 h = ImFmod(h + 0.02f, 1.0f);
1712 }
1713 ColorConvertHSVtoRGB(h, s, v, text_colf.x, text_colf.y, text_colf.z);
1714 v = ImSaturate(v - 0.20f);
1715 ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z);
1716 }
1717
1718 float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f);
1719 window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode // FIXME-DPI
1720
1721 PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf));
1722 RenderText(bb.Min, label, label_end);
1723 PopStyleColor();
1724
1725 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1726 return pressed;
1727 }
1728
1729 bool ImGui::TextLinkOpenURL(const char* label, const char* url)
1730 {
1731 ImGuiContext& g = *GImGui;
1732 if (url == NULL)
1733 url = label;
1734 bool pressed = TextLink(label);
1735 if (pressed && g.PlatformIO.Platform_OpenInShellFn != NULL)
1736 g.PlatformIO.Platform_OpenInShellFn(&g, url);
1737 SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label
1738 if (BeginPopupContextItem())
1739 {
1740 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink)))
1741 SetClipboardText(url);
1742 EndPopup();
1743 }
1744 return pressed;
1745 }
1746
1747 //-------------------------------------------------------------------------
1748 // [SECTION] Widgets: Low-level Layout helpers
1749 //-------------------------------------------------------------------------
1750 // - Spacing()
1751 // - Dummy()
1752 // - NewLine()
1753 // - AlignTextToFramePadding()
1754 // - SeparatorEx() [Internal]
1755 // - Separator()
1756 // - SplitterBehavior() [Internal]
1757 // - ShrinkWidths() [Internal]
1758 //-------------------------------------------------------------------------
1759
1760 void ImGui::Spacing()
1761 {
1762 ImGuiWindow* window = GetCurrentWindow();
1763 if (window->SkipItems)
1764 return;
1765 ItemSize(ImVec2(0, 0));
1766 }
1767
1768 void ImGui::Dummy(const ImVec2& size)
1769 {
1770 ImGuiWindow* window = GetCurrentWindow();
1771 if (window->SkipItems)
1772 return;
1773
1774 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
1775 ItemSize(size);
1776 ItemAdd(bb, 0);
1777 }
1778
1779 void ImGui::NewLine()
1780 {
1781 ImGuiWindow* window = GetCurrentWindow();
1782 if (window->SkipItems)
1783 return;
1784
1785 ImGuiContext& g = *GImGui;
1786 const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
1787 window->DC.LayoutType = ImGuiLayoutType_Vertical;
1788 window->DC.IsSameLine = false;
1789 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.
1790 ItemSize(ImVec2(0, 0));
1791 else
1792 ItemSize(ImVec2(0.0f, g.FontSize));
1793 window->DC.LayoutType = backup_layout_type;
1794 }
1795
1796 void ImGui::AlignTextToFramePadding()
1797 {
1798 ImGuiWindow* window = GetCurrentWindow();
1799 if (window->SkipItems)
1800 return;
1801
1802 ImGuiContext& g = *GImGui;
1803 window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
1804 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
1805 }
1806
1807 // Horizontal/vertical separating line
1808 // FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues.
1809 // Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are.
1810 void ImGui::SeparatorEx(ImGuiSeparatorFlags flags, float thickness)
1811 {
1812 ImGuiWindow* window = GetCurrentWindow();
1813 if (window->SkipItems)
1814 return;
1815
1816 ImGuiContext& g = *GImGui;
1817 IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
1818 IM_ASSERT(thickness > 0.0f);
1819
1820 if (flags & ImGuiSeparatorFlags_Vertical)
1821 {
1822 // Vertical separator, for menu bars (use current line height).
1823 float y1 = window->DC.CursorPos.y;
1824 float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;
1825 const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness, y2));
1826 ItemSize(ImVec2(thickness, 0.0f));
1827 if (!ItemAdd(bb, 0))
1828 return;
1829
1830 // Draw
1831 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1832 if (g.LogEnabled)
1833 LogText(" |");
1834 }
1835 else if (flags & ImGuiSeparatorFlags_Horizontal)
1836 {
1837 // Horizontal Separator
1838 float x1 = window->DC.CursorPos.x;
1839 float x2 = window->WorkRect.Max.x;
1840
1841 // Preserve legacy behavior inside Columns()
1842 // Before Tables API happened, we relied on Separator() to span all columns of a Columns() set.
1843 // We currently don't need to provide the same feature for tables because tables naturally have border features.
1844 ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
1845 if (columns)
1846 {
1847 x1 = window->Pos.x + window->DC.Indent.x; // Used to be Pos.x before 2023/10/03
1848 x2 = window->Pos.x + window->Size.x;
1849 PushColumnsBackground();
1850 }
1851
1852 // We don't provide our width to the layout so that it doesn't get feed back into AutoFit
1853 // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell)
1854 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.
1855 const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness));
1856 ItemSize(ImVec2(0.0f, thickness_for_layout));
1857
1858 if (ItemAdd(bb, 0))
1859 {
1860 // Draw
1861 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1862 if (g.LogEnabled)
1863 LogRenderedText(&bb.Min, "--------------------------------\n");
1864
1865 }
1866 if (columns)
1867 {
1868 PopColumnsBackground();
1869 columns->LineMinY = window->DC.CursorPos.y;
1870 }
1871 }
1872 }
1873
1874 void ImGui::Separator()
1875 {
1876 ImGuiContext& g = *GImGui;
1877 ImGuiWindow* window = g.CurrentWindow;
1878 if (window->SkipItems)
1879 return;
1880
1881 // Those flags should eventually be configurable by the user
1882 // FIXME: We cannot g.Style.SeparatorTextBorderSize for thickness as it relates to SeparatorText() which is a decorated separator, not defaulting to 1.0f.
1883 ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
1884
1885 // Only applies to legacy Columns() api as they relied on Separator() a lot.
1886 if (window->DC.CurrentColumns)
1887 flags |= ImGuiSeparatorFlags_SpanAllColumns;
1888
1889 SeparatorEx(flags, 1.0f);
1890 }
1891
1892 void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_w)
1893 {
1894 ImGuiContext& g = *GImGui;
1895 ImGuiWindow* window = g.CurrentWindow;
1896 ImGuiStyle& style = g.Style;
1897
1898 const ImVec2 label_size = CalcTextSize(label, label_end, false);
1899 const ImVec2 pos = window->DC.CursorPos;
1900 const ImVec2 padding = style.SeparatorTextPadding;
1901
1902 const float separator_thickness = style.SeparatorTextBorderSize;
1903 const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness));
1904 const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y));
1905 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));
1906 ItemSize(min_size, text_baseline_y);
1907 if (!ItemAdd(bb, id))
1908 return;
1909
1910 const float sep1_x1 = pos.x;
1911 const float sep2_x2 = bb.Max.x;
1912 const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.99999f);
1913
1914 const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f);
1915 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
1916
1917 // This allows using SameLine() to position something in the 'extra_w'
1918 window->DC.CursorPosPrevLine.x = label_pos.x + label_size.x;
1919
1920 const ImU32 separator_col = GetColorU32(ImGuiCol_Separator);
1921 if (label_size.x > 0.0f)
1922 {
1923 const float sep1_x2 = label_pos.x - style.ItemSpacing.x;
1924 const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x;
1925 if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f)
1926 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep1_x2, seps_y), separator_col, separator_thickness);
1927 if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f)
1928 window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1929 if (g.LogEnabled)
1930 LogSetNextTextDecoration("---", NULL);
1931 RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size);
1932 }
1933 else
1934 {
1935 if (g.LogEnabled)
1936 LogText("---");
1937 if (separator_thickness > 0.0f)
1938 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1939 }
1940 }
1941
1942 void ImGui::SeparatorText(const char* label)
1943 {
1944 ImGuiWindow* window = GetCurrentWindow();
1945 if (window->SkipItems)
1946 return;
1947
1948 // The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want:
1949 // - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight)
1950 // - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string)
1951 // - because of this we probably can't turn 'const char* label' into 'const char* fmt, ...'
1952 // Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item,
1953 // and then we can turn this into a format function.
1954 SeparatorTextEx(0, label, FindRenderedTextEnd(label), 0.0f);
1955 }
1956
1957 // 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.
1958 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)
1959 {
1960 ImGuiContext& g = *GImGui;
1961 ImGuiWindow* window = g.CurrentWindow;
1962
1963 if (!ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav))
1964 return false;
1965
1966 // FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags_AllowOverlap here is
1967 // to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item.
1968 // Nowadays we would instead want to use SetNextItemAllowOverlap() before the item.
1969 ImGuiButtonFlags button_flags = ImGuiButtonFlags_FlattenChildren;
1970 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1971 button_flags |= ImGuiButtonFlags_AllowOverlap;
1972 #endif
1973
1974 bool hovered, held;
1975 ImRect bb_interact = bb;
1976 bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
1977 ButtonBehavior(bb_interact, id, &hovered, &held, button_flags);
1978 if (hovered)
1979 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb
1980
1981 if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
1982 SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
1983
1984 ImRect bb_render = bb;
1985 if (held)
1986 {
1987 float mouse_delta = (g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min)[axis];
1988
1989 // Minimum pane size
1990 float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
1991 float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
1992 if (mouse_delta < -size_1_maximum_delta)
1993 mouse_delta = -size_1_maximum_delta;
1994 if (mouse_delta > size_2_maximum_delta)
1995 mouse_delta = size_2_maximum_delta;
1996
1997 // Apply resize
1998 if (mouse_delta != 0.0f)
1999 {
2000 *size1 = ImMax(*size1 + mouse_delta, min_size1);
2001 *size2 = ImMax(*size2 - mouse_delta, min_size2);
2002 bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
2003 MarkItemEdited(id);
2004 }
2005 }
2006
2007 // Render at new position
2008 if (bg_col & IM_COL32_A_MASK)
2009 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0f);
2010 const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
2011 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);
2012
2013 return held;
2014 }
2015
2016 static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
2017 {
2018 const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;
2019 const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;
2020 if (int d = (int)(b->Width - a->Width))
2021 return d;
2022 return (b->Index - a->Index);
2023 }
2024
2025 // Shrink excess width from a set of item, by removing width from the larger items first.
2026 // Set items Width to -1.0f to disable shrinking this item.
2027 void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess, float width_min)
2028 {
2029 if (count == 1)
2030 {
2031 if (items[0].Width >= 0.0f)
2032 items[0].Width = ImMax(items[0].Width - width_excess, width_min);
2033 return;
2034 }
2035 ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer); // Sort largest first, smallest last.
2036 int count_same_width = 1;
2037 while (width_excess > 0.001f && count_same_width < count)
2038 {
2039 while (count_same_width < count && items[0].Width <= items[count_same_width].Width)
2040 count_same_width++;
2041 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);
2042 max_width_to_remove_per_item = ImMin(items[0].Width - width_min, max_width_to_remove_per_item);
2043 if (max_width_to_remove_per_item <= 0.0f)
2044 break;
2045 float base_width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);
2046 for (int item_n = 0; item_n < count_same_width; item_n++)
2047 {
2048 float width_to_remove_for_this_item = ImMin(base_width_to_remove_per_item, items[item_n].Width - width_min);
2049 items[item_n].Width -= width_to_remove_for_this_item;
2050 width_excess -= width_to_remove_for_this_item;
2051 }
2052 }
2053
2054 // Round width and redistribute remainder
2055 // 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.
2056 width_excess = 0.0f;
2057 for (int n = 0; n < count; n++)
2058 {
2059 float width_rounded = ImTrunc(items[n].Width);
2060 width_excess += items[n].Width - width_rounded;
2061 items[n].Width = width_rounded;
2062 }
2063 while (width_excess > 0.0f)
2064 for (int n = 0; n < count && width_excess > 0.0f; n++)
2065 {
2066 float width_to_add = ImMin(items[n].InitialWidth - items[n].Width, 1.0f);
2067 items[n].Width += width_to_add;
2068 width_excess -= width_to_add;
2069 }
2070 }
2071
2072 //-------------------------------------------------------------------------
2073 // [SECTION] Widgets: ComboBox
2074 //-------------------------------------------------------------------------
2075 // - CalcMaxPopupHeightFromItemCount() [Internal]
2076 // - BeginCombo()
2077 // - BeginComboPopup() [Internal]
2078 // - EndCombo()
2079 // - BeginComboPreview() [Internal]
2080 // - EndComboPreview() [Internal]
2081 // - Combo()
2082 //-------------------------------------------------------------------------
2083
2084 static float CalcMaxPopupHeightFromItemCount(int items_count)
2085 {
2086 ImGuiContext& g = *GImGui;
2087 if (items_count <= 0)
2088 return FLT_MAX;
2089 return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
2090 }
2091
2092 bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
2093 {
2094 ImGuiContext& g = *GImGui;
2095 ImGuiWindow* window = GetCurrentWindow();
2096
2097 ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.HasFlags;
2098 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
2099 if (window->SkipItems)
2100 return false;
2101
2102 const ImGuiStyle& style = g.Style;
2103 const ImGuiID id = window->GetID(label);
2104 IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
2105 if (flags & ImGuiComboFlags_WidthFitPreview)
2106 IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0);
2107
2108 const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
2109 const ImVec2 label_size = CalcTextSize(label, NULL, true);
2110 const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && (preview_value != NULL)) ? CalcTextSize(preview_value, NULL, true).x : 0.0f;
2111 const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : ((flags & ImGuiComboFlags_WidthFitPreview) ? (arrow_size + preview_width + style.FramePadding.x * 2.0f) : CalcItemWidth());
2112 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
2113 const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
2114 ItemSize(total_bb, style.FramePadding.y);
2115 if (!ItemAdd(total_bb, id, &bb))
2116 return false;
2117
2118 // Open on click
2119 bool hovered, held;
2120 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
2121 const ImGuiID popup_id = ImHashStr("##ComboPopup", 0, id);
2122 bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None);
2123 if (pressed && !popup_open)
2124 {
2125 OpenPopupEx(popup_id, ImGuiPopupFlags_None);
2126 popup_open = true;
2127 }
2128
2129 // Render shape
2130 const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
2131 const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size);
2132 RenderNavCursor(bb, id);
2133 if (!(flags & ImGuiComboFlags_NoPreview))
2134 window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft);
2135 if (!(flags & ImGuiComboFlags_NoArrowButton))
2136 {
2137 ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
2138 ImU32 text_col = GetColorU32(ImGuiCol_Text);
2139 window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight);
2140 if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x)
2141 RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);
2142 }
2143 RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding);
2144
2145 // Custom preview
2146 if (flags & ImGuiComboFlags_CustomPreview)
2147 {
2148 g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y);
2149 IM_ASSERT(preview_value == NULL || preview_value[0] == 0);
2150 preview_value = NULL;
2151 }
2152
2153 // Render preview and label
2154 if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
2155 {
2156 if (g.LogEnabled)
2157 LogSetNextTextDecoration("{", "}");
2158 RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL);
2159 }
2160 if (label_size.x > 0)
2161 RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label);
2162
2163 if (!popup_open)
2164 return false;
2165
2166 g.NextWindowData.HasFlags = backup_next_window_data_flags;
2167 return BeginComboPopup(popup_id, bb, flags);
2168 }
2169
2170 bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags)
2171 {
2172 ImGuiContext& g = *GImGui;
2173 if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None))
2174 {
2175 g.NextWindowData.ClearFlags();
2176 return false;
2177 }
2178
2179 // Set popup size
2180 float w = bb.GetWidth();
2181 if (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint)
2182 {
2183 g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
2184 }
2185 else
2186 {
2187 if ((flags & ImGuiComboFlags_HeightMask_) == 0)
2188 flags |= ImGuiComboFlags_HeightRegular;
2189 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
2190 int popup_max_height_in_items = -1;
2191 if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
2192 else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
2193 else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
2194 ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX);
2195 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size
2196 constraint_min.x = w;
2197 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f)
2198 constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
2199 SetNextWindowSizeConstraints(constraint_min, constraint_max);
2200 }
2201
2202 // This is essentially a specialized version of BeginPopupEx()
2203 char name[16];
2204 ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth
2205
2206 // Set position given a custom constraint (peak into expected window size so we can position it)
2207 // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function?
2208 // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()?
2209 if (ImGuiWindow* popup_window = FindWindowByName(name))
2210 if (popup_window->WasActive)
2211 {
2212 // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.
2213 ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window);
2214 popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = "Below, Toward Left", Down = "Below, Toward Right (default)"
2215 ImRect r_outer = GetPopupAllowedExtentRect(popup_window);
2216 ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox);
2217 SetNextWindowPos(pos);
2218 }
2219
2220 // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()
2221 ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove;
2222 PushStyleVarX(ImGuiStyleVar_WindowPadding, g.Style.FramePadding.x); // Horizontally align ourselves with the framed text
2223 bool ret = Begin(name, NULL, window_flags);
2224 PopStyleVar();
2225 if (!ret)
2226 {
2227 EndPopup();
2228 IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
2229 return false;
2230 }
2231 g.BeginComboDepth++;
2232 return true;
2233 }
2234
2235 void ImGui::EndCombo()
2236 {
2237 ImGuiContext& g = *GImGui;
2238 EndPopup();
2239 g.BeginComboDepth--;
2240 }
2241
2242 // Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements
2243 // (Experimental, see GitHub issues: #1658, #4168)
2244 bool ImGui::BeginComboPreview()
2245 {
2246 ImGuiContext& g = *GImGui;
2247 ImGuiWindow* window = g.CurrentWindow;
2248 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
2249
2250 if (window->SkipItems || !(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible))
2251 return false;
2252 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?
2253 if (!window->ClipRect.Overlaps(preview_data->PreviewRect)) // Narrower test (optional)
2254 return false;
2255
2256 // FIXME: This could be contained in a PushWorkRect() api
2257 preview_data->BackupCursorPos = window->DC.CursorPos;
2258 preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos;
2259 preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
2260 preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
2261 preview_data->BackupLayout = window->DC.LayoutType;
2262 window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding;
2263 window->DC.CursorMaxPos = window->DC.CursorPos;
2264 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
2265 window->DC.IsSameLine = false;
2266 PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true);
2267
2268 return true;
2269 }
2270
2271 void ImGui::EndComboPreview()
2272 {
2273 ImGuiContext& g = *GImGui;
2274 ImGuiWindow* window = g.CurrentWindow;
2275 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
2276
2277 // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future
2278 ImDrawList* draw_list = window->DrawList;
2279 if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y)
2280 if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command
2281 {
2282 draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect;
2283 draw_list->_TryMergeDrawCmds();
2284 }
2285 PopClipRect();
2286 window->DC.CursorPos = preview_data->BackupCursorPos;
2287 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos);
2288 window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine;
2289 window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset;
2290 window->DC.LayoutType = preview_data->BackupLayout;
2291 window->DC.IsSameLine = false;
2292 preview_data->PreviewRect = ImRect();
2293 }
2294
2295 // Getter for the old Combo() API: const char*[]
2296 static const char* Items_ArrayGetter(void* data, int idx)
2297 {
2298 const char* const* items = (const char* const*)data;
2299 return items[idx];
2300 }
2301
2302 // Getter for the old Combo() API: "item1\0item2\0item3\0"
2303 static const char* Items_SingleStringGetter(void* data, int idx)
2304 {
2305 const char* items_separated_by_zeros = (const char*)data;
2306 int items_count = 0;
2307 const char* p = items_separated_by_zeros;
2308 while (*p)
2309 {
2310 if (idx == items_count)
2311 break;
2312 p += ImStrlen(p) + 1;
2313 items_count++;
2314 }
2315 return *p ? p : NULL;
2316 }
2317
2318 // Old API, prefer using BeginCombo() nowadays if you can.
2319 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)
2320 {
2321 ImGuiContext& g = *GImGui;
2322
2323 // Call the getter to obtain the preview string which is a parameter to BeginCombo()
2324 const char* preview_value = NULL;
2325 if (*current_item >= 0 && *current_item < items_count)
2326 preview_value = getter(user_data, *current_item);
2327
2328 // 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.
2329 if (popup_max_height_in_items != -1 && !(g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasSizeConstraint))
2330 SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
2331
2332 if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
2333 return false;
2334
2335 // Display items
2336 bool value_changed = false;
2337 ImGuiListClipper clipper;
2338 clipper.Begin(items_count);
2339 clipper.IncludeItemByIndex(*current_item);
2340 while (clipper.Step())
2341 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
2342 {
2343 const char* item_text = getter(user_data, i);
2344 if (item_text == NULL)
2345 item_text = "*Unknown item*";
2346
2347 PushID(i);
2348 const bool item_selected = (i == *current_item);
2349 if (Selectable(item_text, item_selected) && *current_item != i)
2350 {
2351 value_changed = true;
2352 *current_item = i;
2353 }
2354 if (item_selected)
2355 SetItemDefaultFocus();
2356 PopID();
2357 }
2358
2359 EndCombo();
2360 if (value_changed)
2361 MarkItemEdited(g.LastItemData.ID);
2362
2363 return value_changed;
2364 }
2365
2366 // Combo box helper allowing to pass an array of strings.
2367 bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
2368 {
2369 const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
2370 return value_changed;
2371 }
2372
2373 // Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
2374 bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
2375 {
2376 int items_count = 0;
2377 const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
2378 while (*p)
2379 {
2380 p += ImStrlen(p) + 1;
2381 items_count++;
2382 }
2383 bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
2384 return value_changed;
2385 }
2386
2387 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2388
2389 struct ImGuiGetNameFromIndexOldToNewCallbackData { void* UserData; bool (*OldCallback)(void*, int, const char**); };
2390 static const char* ImGuiGetNameFromIndexOldToNewCallback(void* user_data, int idx)
2391 {
2392 ImGuiGetNameFromIndexOldToNewCallbackData* data = (ImGuiGetNameFromIndexOldToNewCallbackData*)user_data;
2393 const char* s = NULL;
2394 data->OldCallback(data->UserData, idx, &s);
2395 return s;
2396 }
2397
2398 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)
2399 {
2400 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2401 return ListBox(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, height_in_items);
2402 }
2403 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)
2404 {
2405 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2406 return Combo(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, popup_max_height_in_items);
2407 }
2408
2409 #endif
2410
2411 //-------------------------------------------------------------------------
2412 // [SECTION] Data Type and Data Formatting Helpers [Internal]
2413 //-------------------------------------------------------------------------
2414 // - DataTypeGetInfo()
2415 // - DataTypeFormatString()
2416 // - DataTypeApplyOp()
2417 // - DataTypeApplyFromText()
2418 // - DataTypeCompare()
2419 // - DataTypeClamp()
2420 // - GetMinimumStepAtDecimalPrecision
2421 // - RoundScalarWithFormat<>()
2422 //-------------------------------------------------------------------------
2423
2424 static const ImGuiDataTypeInfo GDataTypeInfo[] =
2425 {
2426 { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8
2427 { sizeof(unsigned char), "U8", "%u", "%u" },
2428 { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16
2429 { sizeof(unsigned short), "U16", "%u", "%u" },
2430 { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32
2431 { sizeof(unsigned int), "U32", "%u", "%u" },
2432 #ifdef _MSC_VER
2433 { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64
2434 { sizeof(ImU64), "U64", "%I64u","%I64u" },
2435 #else
2436 { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64
2437 { sizeof(ImU64), "U64", "%llu", "%llu" },
2438 #endif
2439 { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
2440 { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
2441 { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool
2442 { 0, "char*","%s", "%s" }, // ImGuiDataType_String
2443 };
2444 IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
2445
2446 const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)
2447 {
2448 IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
2449 return &GDataTypeInfo[data_type];
2450 }
2451
2452 int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format)
2453 {
2454 // Signedness doesn't matter when pushing integer arguments
2455 if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
2456 return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data);
2457 if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
2458 return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data);
2459 if (data_type == ImGuiDataType_Float)
2460 return ImFormatString(buf, buf_size, format, *(const float*)p_data);
2461 if (data_type == ImGuiDataType_Double)
2462 return ImFormatString(buf, buf_size, format, *(const double*)p_data);
2463 if (data_type == ImGuiDataType_S8)
2464 return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data);
2465 if (data_type == ImGuiDataType_U8)
2466 return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data);
2467 if (data_type == ImGuiDataType_S16)
2468 return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data);
2469 if (data_type == ImGuiDataType_U16)
2470 return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data);
2471 IM_ASSERT(0);
2472 return 0;
2473 }
2474
2475 void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2)
2476 {
2477 IM_ASSERT(op == '+' || op == '-');
2478 switch (data_type)
2479 {
2480 case ImGuiDataType_S8:
2481 if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2482 if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2483 return;
2484 case ImGuiDataType_U8:
2485 if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2486 if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2487 return;
2488 case ImGuiDataType_S16:
2489 if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2490 if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2491 return;
2492 case ImGuiDataType_U16:
2493 if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2494 if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2495 return;
2496 case ImGuiDataType_S32:
2497 if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2498 if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2499 return;
2500 case ImGuiDataType_U32:
2501 if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2502 if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2503 return;
2504 case ImGuiDataType_S64:
2505 if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2506 if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2507 return;
2508 case ImGuiDataType_U64:
2509 if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2510 if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2511 return;
2512 case ImGuiDataType_Float:
2513 if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
2514 if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
2515 return;
2516 case ImGuiDataType_Double:
2517 if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
2518 if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
2519 return;
2520 case ImGuiDataType_COUNT: break;
2521 }
2522 IM_ASSERT(0);
2523 }
2524
2525 // User can input math operators (e.g. +100) to edit a numerical values.
2526 // NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
2527 bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty)
2528 {
2529 // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
2530 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
2531 ImGuiDataTypeStorage data_backup;
2532 memcpy(&data_backup, p_data, type_info->Size);
2533
2534 while (ImCharIsBlankA(*buf))
2535 buf++;
2536 if (!buf[0])
2537 {
2538 if (p_data_when_empty != NULL)
2539 {
2540 memcpy(p_data, p_data_when_empty, type_info->Size);
2541 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2542 }
2543 return false;
2544 }
2545
2546 // Sanitize format
2547 // - 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
2548 // - In theory could treat empty format as using default, but this would only cover rare/bizarre case of using InputScalar() + integer + format string without %.
2549 char format_sanitized[32];
2550 if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
2551 format = type_info->ScanFmt;
2552 else
2553 format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_ARRAYSIZE(format_sanitized));
2554
2555 // Small types need a 32-bit buffer to receive the result from scanf()
2556 int v32 = 0;
2557 if (sscanf(buf, format, type_info->Size >= 4 ? p_data : &v32) < 1)
2558 return false;
2559 if (type_info->Size < 4)
2560 {
2561 if (data_type == ImGuiDataType_S8)
2562 *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
2563 else if (data_type == ImGuiDataType_U8)
2564 *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
2565 else if (data_type == ImGuiDataType_S16)
2566 *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
2567 else if (data_type == ImGuiDataType_U16)
2568 *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
2569 else
2570 IM_ASSERT(0);
2571 }
2572
2573 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2574 }
2575
2576 template<typename T>
2577 static int DataTypeCompareT(const T* lhs, const T* rhs)
2578 {
2579 if (*lhs < *rhs) return -1;
2580 if (*lhs > *rhs) return +1;
2581 return 0;
2582 }
2583
2584 int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2)
2585 {
2586 switch (data_type)
2587 {
2588 case ImGuiDataType_S8: return DataTypeCompareT<ImS8 >((const ImS8* )arg_1, (const ImS8* )arg_2);
2589 case ImGuiDataType_U8: return DataTypeCompareT<ImU8 >((const ImU8* )arg_1, (const ImU8* )arg_2);
2590 case ImGuiDataType_S16: return DataTypeCompareT<ImS16 >((const ImS16* )arg_1, (const ImS16* )arg_2);
2591 case ImGuiDataType_U16: return DataTypeCompareT<ImU16 >((const ImU16* )arg_1, (const ImU16* )arg_2);
2592 case ImGuiDataType_S32: return DataTypeCompareT<ImS32 >((const ImS32* )arg_1, (const ImS32* )arg_2);
2593 case ImGuiDataType_U32: return DataTypeCompareT<ImU32 >((const ImU32* )arg_1, (const ImU32* )arg_2);
2594 case ImGuiDataType_S64: return DataTypeCompareT<ImS64 >((const ImS64* )arg_1, (const ImS64* )arg_2);
2595 case ImGuiDataType_U64: return DataTypeCompareT<ImU64 >((const ImU64* )arg_1, (const ImU64* )arg_2);
2596 case ImGuiDataType_Float: return DataTypeCompareT<float >((const float* )arg_1, (const float* )arg_2);
2597 case ImGuiDataType_Double: return DataTypeCompareT<double>((const double*)arg_1, (const double*)arg_2);
2598 case ImGuiDataType_COUNT: break;
2599 }
2600 IM_ASSERT(0);
2601 return 0;
2602 }
2603
2604 template<typename T>
2605 static bool DataTypeClampT(T* v, const T* v_min, const T* v_max)
2606 {
2607 // Clamp, both sides are optional, return true if modified
2608 if (v_min && *v < *v_min) { *v = *v_min; return true; }
2609 if (v_max && *v > *v_max) { *v = *v_max; return true; }
2610 return false;
2611 }
2612
2613 bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)
2614 {
2615 switch (data_type)
2616 {
2617 case ImGuiDataType_S8: return DataTypeClampT<ImS8 >((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max);
2618 case ImGuiDataType_U8: return DataTypeClampT<ImU8 >((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max);
2619 case ImGuiDataType_S16: return DataTypeClampT<ImS16 >((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max);
2620 case ImGuiDataType_U16: return DataTypeClampT<ImU16 >((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max);
2621 case ImGuiDataType_S32: return DataTypeClampT<ImS32 >((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max);
2622 case ImGuiDataType_U32: return DataTypeClampT<ImU32 >((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max);
2623 case ImGuiDataType_S64: return DataTypeClampT<ImS64 >((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max);
2624 case ImGuiDataType_U64: return DataTypeClampT<ImU64 >((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max);
2625 case ImGuiDataType_Float: return DataTypeClampT<float >((float* )p_data, (const float* )p_min, (const float* )p_max);
2626 case ImGuiDataType_Double: return DataTypeClampT<double>((double*)p_data, (const double*)p_min, (const double*)p_max);
2627 case ImGuiDataType_COUNT: break;
2628 }
2629 IM_ASSERT(0);
2630 return false;
2631 }
2632
2633 bool ImGui::DataTypeIsZero(ImGuiDataType data_type, const void* p_data)
2634 {
2635 ImGuiContext& g = *GImGui;
2636 return DataTypeCompare(data_type, p_data, &g.DataTypeZeroValue) == 0;
2637 }
2638
2639 static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
2640 {
2641 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 };
2642 if (decimal_precision < 0)
2643 return FLT_MIN;
2644 return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
2645 }
2646
2647 template<typename TYPE>
2648 TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
2649 {
2650 IM_UNUSED(data_type);
2651 IM_ASSERT(data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
2652 const char* fmt_start = ImParseFormatFindStart(format);
2653 if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
2654 return v;
2655
2656 // Sanitize format
2657 char fmt_sanitized[32];
2658 ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized));
2659 fmt_start = fmt_sanitized;
2660
2661 // Format value with our rounding, and read back
2662 char v_str[64];
2663 ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
2664 const char* p = v_str;
2665 while (*p == ' ')
2666 p++;
2667 v = (TYPE)ImAtof(p);
2668
2669 return v;
2670 }
2671
2672 //-------------------------------------------------------------------------
2673 // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
2674 //-------------------------------------------------------------------------
2675 // - DragBehaviorT<>() [Internal]
2676 // - DragBehavior() [Internal]
2677 // - DragScalar()
2678 // - DragScalarN()
2679 // - DragFloat()
2680 // - DragFloat2()
2681 // - DragFloat3()
2682 // - DragFloat4()
2683 // - DragFloatRange2()
2684 // - DragInt()
2685 // - DragInt2()
2686 // - DragInt3()
2687 // - DragInt4()
2688 // - DragIntRange2()
2689 //-------------------------------------------------------------------------
2690
2691 // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
2692 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2693 bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags)
2694 {
2695 ImGuiContext& g = *GImGui;
2696 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
2697 const bool is_bounded = (v_min < v_max) || ((v_min == v_max) && (v_min != 0.0f || (flags & ImGuiSliderFlags_ClampZeroRange)));
2698 const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround);
2699 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
2700 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
2701
2702 // Default tweak speed
2703 if (v_speed == 0.0f && is_bounded && (v_max - v_min < FLT_MAX))
2704 v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
2705
2706 // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
2707 float adjust_delta = 0.0f;
2708 if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2709 {
2710 adjust_delta = g.IO.MouseDelta[axis];
2711 if (g.IO.KeyAlt && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
2712 adjust_delta *= 1.0f / 100.0f;
2713 if (g.IO.KeyShift && !(flags & ImGuiSliderFlags_NoSpeedTweaks))
2714 adjust_delta *= 10.0f;
2715 }
2716 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
2717 {
2718 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
2719 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
2720 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
2721 const float tweak_factor = (flags & ImGuiSliderFlags_NoSpeedTweaks) ? 1.0f : tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
2722 adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor;
2723 v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
2724 }
2725 adjust_delta *= v_speed;
2726
2727 // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
2728 if (axis == ImGuiAxis_Y)
2729 adjust_delta = -adjust_delta;
2730
2731 // For logarithmic use our range is effectively 0..1 so scale the delta into that range
2732 if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0
2733 adjust_delta /= (float)(v_max - v_min);
2734
2735 // Clear current value on activation
2736 // 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.
2737 const bool is_just_activated = g.ActiveIdIsJustActivated;
2738 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));
2739 if (is_just_activated || is_already_past_limits_and_pushing_outward)
2740 {
2741 g.DragCurrentAccum = 0.0f;
2742 g.DragCurrentAccumDirty = false;
2743 }
2744 else if (adjust_delta != 0.0f)
2745 {
2746 g.DragCurrentAccum += adjust_delta;
2747 g.DragCurrentAccumDirty = true;
2748 }
2749
2750 if (!g.DragCurrentAccumDirty)
2751 return false;
2752
2753 TYPE v_cur = *v;
2754 FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
2755
2756 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
2757 const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)
2758 if (is_logarithmic)
2759 {
2760 // 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.
2761 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
2762 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
2763
2764 // Convert to parametric space, apply delta, convert back
2765 float v_old_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2766 float v_new_parametric = v_old_parametric + g.DragCurrentAccum;
2767 v_cur = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2768 v_old_ref_for_accum_remainder = v_old_parametric;
2769 }
2770 else
2771 {
2772 v_cur += (SIGNEDTYPE)g.DragCurrentAccum;
2773 }
2774
2775 // Round to user desired precision based on format string
2776 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
2777 v_cur = RoundScalarWithFormatT<TYPE>(format, data_type, v_cur);
2778
2779 // Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
2780 g.DragCurrentAccumDirty = false;
2781 if (is_logarithmic)
2782 {
2783 // Convert to parametric space, apply delta, convert back
2784 float v_new_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2785 g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);
2786 }
2787 else
2788 {
2789 g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
2790 }
2791
2792 // Lose zero sign for float/double
2793 if (v_cur == (TYPE)-0)
2794 v_cur = (TYPE)0;
2795
2796 if (*v != v_cur && is_bounded)
2797 {
2798 if (is_wrapped)
2799 {
2800 // Wrap values
2801 if (v_cur < v_min)
2802 v_cur += v_max - v_min + (is_floating_point ? 0 : 1);
2803 if (v_cur > v_max)
2804 v_cur -= v_max - v_min + (is_floating_point ? 0 : 1);
2805 }
2806 else
2807 {
2808 // Clamp values + handle overflow/wrap-around for integer types.
2809 if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point))
2810 v_cur = v_min;
2811 if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point))
2812 v_cur = v_max;
2813 }
2814 }
2815
2816 // Apply result
2817 if (*v == v_cur)
2818 return false;
2819 *v = v_cur;
2820 return true;
2821 }
2822
2823 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)
2824 {
2825 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
2826 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.");
2827
2828 ImGuiContext& g = *GImGui;
2829 if (g.ActiveId == id)
2830 {
2831 // Those are the things we can do easily outside the DragBehaviorT<> template, saves code generation.
2832 if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
2833 ClearActiveID();
2834 else if ((g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
2835 ClearActiveID();
2836 }
2837 if (g.ActiveId != id)
2838 return false;
2839 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
2840 return false;
2841
2842 switch (data_type)
2843 {
2844 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; }
2845 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; }
2846 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; }
2847 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; }
2848 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);
2849 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);
2850 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);
2851 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);
2852 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);
2853 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);
2854 case ImGuiDataType_COUNT: break;
2855 }
2856 IM_ASSERT(0);
2857 return false;
2858 }
2859
2860 // 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.
2861 // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
2862 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)
2863 {
2864 ImGuiWindow* window = GetCurrentWindow();
2865 if (window->SkipItems)
2866 return false;
2867
2868 ImGuiContext& g = *GImGui;
2869 const ImGuiStyle& style = g.Style;
2870 const ImGuiID id = window->GetID(label);
2871 const float w = CalcItemWidth();
2872
2873 const ImVec2 label_size = CalcTextSize(label, NULL, true);
2874 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
2875 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));
2876
2877 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
2878 ItemSize(total_bb, style.FramePadding.y);
2879 if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))
2880 return false;
2881
2882 // Default format string when passing NULL
2883 if (format == NULL)
2884 format = DataTypeGetInfo(data_type)->PrintFmt;
2885
2886 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
2887 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
2888 if (!temp_input_is_active)
2889 {
2890 // Tabbing or CTRL+click on Drag turns it into an InputText
2891 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
2892 const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id));
2893 const bool make_active = (clicked || double_clicked || g.NavActivateId == id);
2894 if (make_active && (clicked || double_clicked))
2895 SetKeyOwner(ImGuiKey_MouseLeft, id);
2896 if (make_active && temp_input_allowed)
2897 if ((clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
2898 temp_input_is_active = true;
2899
2900 // (Optional) simple click (without moving) turns Drag into an InputText
2901 if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active)
2902 if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2903 {
2904 g.NavActivateId = id;
2905 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
2906 temp_input_is_active = true;
2907 }
2908
2909 // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
2910 if (make_active)
2911 memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
2912
2913 if (make_active && !temp_input_is_active)
2914 {
2915 SetActiveID(id, window);
2916 SetFocusID(id, window);
2917 FocusWindow(window);
2918 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
2919 }
2920 }
2921
2922 if (temp_input_is_active)
2923 {
2924 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
2925 bool clamp_enabled = false;
2926 if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL))
2927 {
2928 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
2929 if (p_min == NULL || p_max == NULL || clamp_range_dir < 0)
2930 clamp_enabled = true;
2931 else if (clamp_range_dir == 0)
2932 clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true;
2933 }
2934 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
2935 }
2936
2937 // Draw frame
2938 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
2939 RenderNavCursor(frame_bb, id);
2940 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
2941
2942 // Drag behavior
2943 const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags);
2944 if (value_changed)
2945 MarkItemEdited(id);
2946
2947 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
2948 char value_buf[64];
2949 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
2950 if (g.LogEnabled)
2951 LogSetNextTextDecoration("{", "}");
2952 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
2953
2954 if (label_size.x > 0.0f)
2955 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
2956
2957 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
2958 return value_changed;
2959 }
2960
2961 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)
2962 {
2963 ImGuiWindow* window = GetCurrentWindow();
2964 if (window->SkipItems)
2965 return false;
2966
2967 ImGuiContext& g = *GImGui;
2968 bool value_changed = false;
2969 BeginGroup();
2970 PushID(label);
2971 PushMultiItemsWidths(components, CalcItemWidth());
2972 size_t type_size = GDataTypeInfo[data_type].Size;
2973 for (int i = 0; i < components; i++)
2974 {
2975 PushID(i);
2976 if (i > 0)
2977 SameLine(0, g.Style.ItemInnerSpacing.x);
2978 value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags);
2979 PopID();
2980 PopItemWidth();
2981 p_data = (void*)((char*)p_data + type_size);
2982 }
2983 PopID();
2984
2985 const char* label_end = FindRenderedTextEnd(label);
2986 if (label != label_end)
2987 {
2988 SameLine(0, g.Style.ItemInnerSpacing.x);
2989 TextEx(label, label_end);
2990 }
2991
2992 EndGroup();
2993 return value_changed;
2994 }
2995
2996 bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2997 {
2998 return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags);
2999 }
3000
3001 bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3002 {
3003 return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags);
3004 }
3005
3006 bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3007 {
3008 return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags);
3009 }
3010
3011 bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3012 {
3013 return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags);
3014 }
3015
3016 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
3017 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)
3018 {
3019 ImGuiWindow* window = GetCurrentWindow();
3020 if (window->SkipItems)
3021 return false;
3022
3023 ImGuiContext& g = *GImGui;
3024 PushID(label);
3025 BeginGroup();
3026 PushMultiItemsWidths(2, CalcItemWidth());
3027
3028 float min_min = (v_min >= v_max) ? -FLT_MAX : v_min;
3029 float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
3030 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
3031 bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags);
3032 PopItemWidth();
3033 SameLine(0, g.Style.ItemInnerSpacing.x);
3034
3035 float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
3036 float max_max = (v_min >= v_max) ? FLT_MAX : v_max;
3037 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
3038 value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags);
3039 PopItemWidth();
3040 SameLine(0, g.Style.ItemInnerSpacing.x);
3041
3042 TextEx(label, FindRenderedTextEnd(label));
3043 EndGroup();
3044 PopID();
3045
3046 return value_changed;
3047 }
3048
3049 // NB: v_speed is float to allow adjusting the drag speed with more precision
3050 bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3051 {
3052 return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags);
3053 }
3054
3055 bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3056 {
3057 return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags);
3058 }
3059
3060 bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3061 {
3062 return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags);
3063 }
3064
3065 bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3066 {
3067 return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags);
3068 }
3069
3070 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
3071 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)
3072 {
3073 ImGuiWindow* window = GetCurrentWindow();
3074 if (window->SkipItems)
3075 return false;
3076
3077 ImGuiContext& g = *GImGui;
3078 PushID(label);
3079 BeginGroup();
3080 PushMultiItemsWidths(2, CalcItemWidth());
3081
3082 int min_min = (v_min >= v_max) ? INT_MIN : v_min;
3083 int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
3084 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
3085 bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags);
3086 PopItemWidth();
3087 SameLine(0, g.Style.ItemInnerSpacing.x);
3088
3089 int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
3090 int max_max = (v_min >= v_max) ? INT_MAX : v_max;
3091 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
3092 value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags);
3093 PopItemWidth();
3094 SameLine(0, g.Style.ItemInnerSpacing.x);
3095
3096 TextEx(label, FindRenderedTextEnd(label));
3097 EndGroup();
3098 PopID();
3099
3100 return value_changed;
3101 }
3102
3103 //-------------------------------------------------------------------------
3104 // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
3105 //-------------------------------------------------------------------------
3106 // - ScaleRatioFromValueT<> [Internal]
3107 // - ScaleValueFromRatioT<> [Internal]
3108 // - SliderBehaviorT<>() [Internal]
3109 // - SliderBehavior() [Internal]
3110 // - SliderScalar()
3111 // - SliderScalarN()
3112 // - SliderFloat()
3113 // - SliderFloat2()
3114 // - SliderFloat3()
3115 // - SliderFloat4()
3116 // - SliderAngle()
3117 // - SliderInt()
3118 // - SliderInt2()
3119 // - SliderInt3()
3120 // - SliderInt4()
3121 // - VSliderScalar()
3122 // - VSliderFloat()
3123 // - VSliderInt()
3124 //-------------------------------------------------------------------------
3125
3126 // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT)
3127 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
3128 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)
3129 {
3130 if (v_min == v_max)
3131 return 0.0f;
3132 IM_UNUSED(data_type);
3133
3134 const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
3135 if (is_logarithmic)
3136 {
3137 bool flipped = v_max < v_min;
3138
3139 if (flipped) // Handle the case where the range is backwards
3140 ImSwap(v_min, v_max);
3141
3142 // Fudge min/max to avoid getting close to log(0)
3143 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
3144 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
3145
3146 // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
3147 if ((v_min == 0.0f) && (v_max < 0.0f))
3148 v_min_fudged = -logarithmic_zero_epsilon;
3149 else if ((v_max == 0.0f) && (v_min < 0.0f))
3150 v_max_fudged = -logarithmic_zero_epsilon;
3151
3152 float result;
3153 if (v_clamped <= v_min_fudged)
3154 result = 0.0f; // Workaround for values that are in-range but below our fudge
3155 else if (v_clamped >= v_max_fudged)
3156 result = 1.0f; // Workaround for values that are in-range but above our fudge
3157 else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions
3158 {
3159 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)
3160 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
3161 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
3162 if (v == 0.0f)
3163 result = zero_point_center; // Special case for exactly zero
3164 else if (v < 0.0f)
3165 result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L;
3166 else
3167 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));
3168 }
3169 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
3170 result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged));
3171 else
3172 result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged));
3173
3174 return flipped ? (1.0f - result) : result;
3175 }
3176 else
3177 {
3178 // Linear slider
3179 return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min));
3180 }
3181 }
3182
3183 // Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)
3184 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
3185 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)
3186 {
3187 // We special-case the extents because otherwise our logarithmic fudging can lead to "mathematically correct"
3188 // but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value. Also generally simpler.
3189 if (t <= 0.0f || v_min == v_max)
3190 return v_min;
3191 if (t >= 1.0f)
3192 return v_max;
3193
3194 TYPE result = (TYPE)0;
3195 if (is_logarithmic)
3196 {
3197 // Fudge min/max to avoid getting silly results close to zero
3198 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
3199 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
3200
3201 const bool flipped = v_max < v_min; // Check if range is "backwards"
3202 if (flipped)
3203 ImSwap(v_min_fudged, v_max_fudged);
3204
3205 // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
3206 if ((v_max == 0.0f) && (v_min < 0.0f))
3207 v_max_fudged = -logarithmic_zero_epsilon;
3208
3209 float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range
3210
3211 if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts
3212 {
3213 float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space
3214 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
3215 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
3216 if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R)
3217 result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise)
3218 else if (t_with_flip < zero_point_center)
3219 result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L))));
3220 else
3221 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))));
3222 }
3223 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
3224 result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip)));
3225 else
3226 result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip));
3227 }
3228 else
3229 {
3230 // Linear slider
3231 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
3232 if (is_floating_point)
3233 {
3234 result = ImLerp(v_min, v_max, t);
3235 }
3236 else if (t < 1.0)
3237 {
3238 // - For integer values we want the clicking position to match the grab box so we round above
3239 // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
3240 // - 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
3241 // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits.
3242 FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t;
3243 result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5)));
3244 }
3245 }
3246
3247 return result;
3248 }
3249
3250 // FIXME: Try to move more of the code into shared SliderBehavior()
3251 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
3252 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)
3253 {
3254 ImGuiContext& g = *GImGui;
3255 const ImGuiStyle& style = g.Style;
3256
3257 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
3258 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
3259 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
3260 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.
3261
3262 // Calculate bounds
3263 const float grab_padding = 2.0f; // FIXME: Should be part of style.
3264 const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
3265 float grab_sz = style.GrabMinSize;
3266 if (!is_floating_point && v_range_f >= 0.0f) // v_range_f < 0 may happen on integer overflows
3267 grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
3268 grab_sz = ImMin(grab_sz, slider_sz);
3269 const float slider_usable_sz = slider_sz - grab_sz;
3270 const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;
3271 const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;
3272
3273 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
3274 float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true
3275 if (is_logarithmic)
3276 {
3277 // 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.
3278 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
3279 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
3280 zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f);
3281 }
3282
3283 // Process interacting with the slider
3284 bool value_changed = false;
3285 if (g.ActiveId == id)
3286 {
3287 bool set_new_value = false;
3288 float clicked_t = 0.0f;
3289 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
3290 {
3291 if (!g.IO.MouseDown[0])
3292 {
3293 ClearActiveID();
3294 }
3295 else
3296 {
3297 const float mouse_abs_pos = g.IO.MousePos[axis];
3298 if (g.ActiveIdIsJustActivated)
3299 {
3300 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3301 if (axis == ImGuiAxis_Y)
3302 grab_t = 1.0f - grab_t;
3303 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3304 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.
3305 g.SliderGrabClickOffset = (clicked_around_grab && is_floating_point) ? mouse_abs_pos - grab_pos : 0.0f;
3306 }
3307 if (slider_usable_sz > 0.0f)
3308 clicked_t = ImSaturate((mouse_abs_pos - g.SliderGrabClickOffset - slider_usable_pos_min) / slider_usable_sz);
3309 if (axis == ImGuiAxis_Y)
3310 clicked_t = 1.0f - clicked_t;
3311 set_new_value = true;
3312 }
3313 }
3314 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
3315 {
3316 if (g.ActiveIdIsJustActivated)
3317 {
3318 g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation
3319 g.SliderCurrentAccumDirty = false;
3320 }
3321
3322 float input_delta = (axis == ImGuiAxis_X) ? GetNavTweakPressedAmount(axis) : -GetNavTweakPressedAmount(axis);
3323 if (input_delta != 0.0f)
3324 {
3325 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
3326 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
3327 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
3328 if (decimal_precision > 0)
3329 {
3330 input_delta /= 100.0f; // Keyboard/Gamepad tweak speeds in % of slider bounds
3331 if (tweak_slow)
3332 input_delta /= 10.0f;
3333 }
3334 else
3335 {
3336 if ((v_range_f >= -100.0f && v_range_f <= 100.0f && v_range_f != 0.0f) || tweak_slow)
3337 input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Keyboard/Gamepad tweak speeds in integer steps
3338 else
3339 input_delta /= 100.0f;
3340 }
3341 if (tweak_fast)
3342 input_delta *= 10.0f;
3343
3344 g.SliderCurrentAccum += input_delta;
3345 g.SliderCurrentAccumDirty = true;
3346 }
3347
3348 float delta = g.SliderCurrentAccum;
3349 if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
3350 {
3351 ClearActiveID();
3352 }
3353 else if (g.SliderCurrentAccumDirty)
3354 {
3355 clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3356
3357 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
3358 {
3359 set_new_value = false;
3360 g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate
3361 }
3362 else
3363 {
3364 set_new_value = true;
3365 float old_clicked_t = clicked_t;
3366 clicked_t = ImSaturate(clicked_t + delta);
3367
3368 // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator
3369 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3370 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3371 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3372 float new_clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3373
3374 if (delta > 0)
3375 g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta);
3376 else
3377 g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta);
3378 }
3379
3380 g.SliderCurrentAccumDirty = false;
3381 }
3382 }
3383
3384 if (set_new_value)
3385 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
3386 set_new_value = false;
3387
3388 if (set_new_value)
3389 {
3390 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3391
3392 // Round to user desired precision based on format string
3393 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3394 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3395
3396 // Apply result
3397 if (*v != v_new)
3398 {
3399 *v = v_new;
3400 value_changed = true;
3401 }
3402 }
3403 }
3404
3405 if (slider_sz < 1.0f)
3406 {
3407 *out_grab_bb = ImRect(bb.Min, bb.Min);
3408 }
3409 else
3410 {
3411 // Output grab position so it can be displayed by the caller
3412 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3413 if (axis == ImGuiAxis_Y)
3414 grab_t = 1.0f - grab_t;
3415 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3416 if (axis == ImGuiAxis_X)
3417 *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);
3418 else
3419 *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);
3420 }
3421
3422 return value_changed;
3423 }
3424
3425 // For 32-bit and larger types, slider bounds are limited to half the natural type range.
3426 // 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.
3427 // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
3428 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)
3429 {
3430 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
3431 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.");
3432 IM_ASSERT((flags & ImGuiSliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX()
3433
3434 switch (data_type)
3435 {
3436 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; }
3437 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; }
3438 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; }
3439 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; }
3440 case ImGuiDataType_S32:
3441 IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2);
3442 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);
3443 case ImGuiDataType_U32:
3444 IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2);
3445 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);
3446 case ImGuiDataType_S64:
3447 IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2);
3448 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);
3449 case ImGuiDataType_U64:
3450 IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2);
3451 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);
3452 case ImGuiDataType_Float:
3453 IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f);
3454 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);
3455 case ImGuiDataType_Double:
3456 IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f);
3457 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);
3458 case ImGuiDataType_COUNT: break;
3459 }
3460 IM_ASSERT(0);
3461 return false;
3462 }
3463
3464 // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required.
3465 // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3466 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)
3467 {
3468 ImGuiWindow* window = GetCurrentWindow();
3469 if (window->SkipItems)
3470 return false;
3471
3472 ImGuiContext& g = *GImGui;
3473 const ImGuiStyle& style = g.Style;
3474 const ImGuiID id = window->GetID(label);
3475 const float w = CalcItemWidth();
3476
3477 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3478 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
3479 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));
3480
3481 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
3482 ItemSize(total_bb, style.FramePadding.y);
3483 if (!ItemAdd(total_bb, id, &frame_bb, (temp_input_allowed ? ImGuiItemFlags_Inputable : 0) | ImGuiItemFlags_NoInertialScroll))
3484 return false;
3485
3486 // Default format string when passing NULL
3487 if (format == NULL)
3488 format = DataTypeGetInfo(data_type)->PrintFmt;
3489
3490 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3491 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
3492 if (!temp_input_is_active)
3493 {
3494 // Tabbing or CTRL+click on Slider turns it into an input box
3495 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3496 const bool make_active = (clicked || g.NavActivateId == id);
3497 if (make_active && clicked)
3498 SetKeyOwner(ImGuiKey_MouseLeft, id);
3499 if (make_active && temp_input_allowed)
3500 if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
3501 temp_input_is_active = true;
3502
3503 // Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
3504 if (make_active)
3505 memcpy(&g.ActiveIdValueOnActivation, p_data, DataTypeGetInfo(data_type)->Size);
3506
3507 if (make_active && !temp_input_is_active)
3508 {
3509 SetActiveID(id, window);
3510 SetFocusID(id, window);
3511 FocusWindow(window);
3512 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
3513 }
3514 }
3515
3516 if (temp_input_is_active)
3517 {
3518 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
3519 const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0;
3520 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
3521 }
3522
3523 // Draw frame
3524 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3525 RenderNavCursor(frame_bb, id);
3526 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3527
3528 // Slider behavior
3529 ImRect grab_bb;
3530 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb);
3531 if (value_changed)
3532 MarkItemEdited(id);
3533
3534 // Render grab
3535 if (grab_bb.Max.x > grab_bb.Min.x)
3536 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3537
3538 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3539 char value_buf[64];
3540 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3541 if (g.LogEnabled)
3542 LogSetNextTextDecoration("{", "}");
3543 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
3544
3545 if (label_size.x > 0.0f)
3546 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3547
3548 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
3549 return value_changed;
3550 }
3551
3552 // Add multiple sliders on 1 line for compact edition of multiple components
3553 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)
3554 {
3555 ImGuiWindow* window = GetCurrentWindow();
3556 if (window->SkipItems)
3557 return false;
3558
3559 ImGuiContext& g = *GImGui;
3560 bool value_changed = false;
3561 BeginGroup();
3562 PushID(label);
3563 PushMultiItemsWidths(components, CalcItemWidth());
3564 size_t type_size = GDataTypeInfo[data_type].Size;
3565 for (int i = 0; i < components; i++)
3566 {
3567 PushID(i);
3568 if (i > 0)
3569 SameLine(0, g.Style.ItemInnerSpacing.x);
3570 value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags);
3571 PopID();
3572 PopItemWidth();
3573 v = (void*)((char*)v + type_size);
3574 }
3575 PopID();
3576
3577 const char* label_end = FindRenderedTextEnd(label);
3578 if (label != label_end)
3579 {
3580 SameLine(0, g.Style.ItemInnerSpacing.x);
3581 TextEx(label, label_end);
3582 }
3583
3584 EndGroup();
3585 return value_changed;
3586 }
3587
3588 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3589 {
3590 return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3591 }
3592
3593 bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3594 {
3595 return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags);
3596 }
3597
3598 bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3599 {
3600 return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags);
3601 }
3602
3603 bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3604 {
3605 return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags);
3606 }
3607
3608 bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags)
3609 {
3610 if (format == NULL)
3611 format = "%.0f deg";
3612 float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
3613 bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags);
3614 if (value_changed)
3615 *v_rad = v_deg * (2 * IM_PI) / 360.0f;
3616 return value_changed;
3617 }
3618
3619 bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3620 {
3621 return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3622 }
3623
3624 bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3625 {
3626 return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags);
3627 }
3628
3629 bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3630 {
3631 return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags);
3632 }
3633
3634 bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3635 {
3636 return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags);
3637 }
3638
3639 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)
3640 {
3641 ImGuiWindow* window = GetCurrentWindow();
3642 if (window->SkipItems)
3643 return false;
3644
3645 ImGuiContext& g = *GImGui;
3646 const ImGuiStyle& style = g.Style;
3647 const ImGuiID id = window->GetID(label);
3648
3649 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3650 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
3651 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));
3652
3653 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
3654 ItemSize(bb, style.FramePadding.y);
3655 if (!ItemAdd(frame_bb, id, NULL, (temp_input_allowed ? ImGuiItemFlags_Inputable : 0) | ImGuiItemFlags_NoInertialScroll))
3656 return false;
3657
3658 // Default format string when passing NULL
3659 if (format == NULL)
3660 format = DataTypeGetInfo(data_type)->PrintFmt;
3661
3662 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3663 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
3664 if (!temp_input_is_active)
3665 {
3666 // Tabbing or CTRL+click on Slider turns it into an input box
3667 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3668 const bool make_active = (clicked || g.NavActivateId == id);
3669 if (make_active && clicked)
3670 SetKeyOwner(ImGuiKey_MouseLeft, id);
3671 if (make_active && temp_input_allowed)
3672 if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
3673 temp_input_is_active = true;
3674
3675 if (make_active && !temp_input_is_active)
3676 {
3677 SetActiveID(id, window);
3678 SetFocusID(id, window);
3679 FocusWindow(window);
3680 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
3681 }
3682 }
3683
3684 if (temp_input_is_active)
3685 {
3686 // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set
3687 const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0;
3688 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL);
3689 }
3690
3691 // Draw frame
3692 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3693 RenderNavCursor(frame_bb, id);
3694 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3695
3696 // Slider behavior
3697 ImRect grab_bb;
3698 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb);
3699 if (value_changed)
3700 MarkItemEdited(id);
3701
3702 // Render grab
3703 if (grab_bb.Max.y > grab_bb.Min.y)
3704 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3705
3706 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3707 // For the vertical slider we allow centered text to overlap the frame padding
3708 char value_buf[64];
3709 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3710 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));
3711 if (label_size.x > 0.0f)
3712 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3713
3714 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
3715 return value_changed;
3716 }
3717
3718 bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3719 {
3720 return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3721 }
3722
3723 bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3724 {
3725 return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3726 }
3727
3728 //-------------------------------------------------------------------------
3729 // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
3730 //-------------------------------------------------------------------------
3731 // - ImParseFormatFindStart() [Internal]
3732 // - ImParseFormatFindEnd() [Internal]
3733 // - ImParseFormatTrimDecorations() [Internal]
3734 // - ImParseFormatSanitizeForPrinting() [Internal]
3735 // - ImParseFormatSanitizeForScanning() [Internal]
3736 // - ImParseFormatPrecision() [Internal]
3737 // - TempInputTextScalar() [Internal]
3738 // - InputScalar()
3739 // - InputScalarN()
3740 // - InputFloat()
3741 // - InputFloat2()
3742 // - InputFloat3()
3743 // - InputFloat4()
3744 // - InputInt()
3745 // - InputInt2()
3746 // - InputInt3()
3747 // - InputInt4()
3748 // - InputDouble()
3749 //-------------------------------------------------------------------------
3750
3751 // We don't use strchr() because our strings are usually very short and often start with '%'
3752 const char* ImParseFormatFindStart(const char* fmt)
3753 {
3754 while (char c = fmt[0])
3755 {
3756 if (c == '%' && fmt[1] != '%')
3757 return fmt;
3758 else if (c == '%')
3759 fmt++;
3760 fmt++;
3761 }
3762 return fmt;
3763 }
3764
3765 const char* ImParseFormatFindEnd(const char* fmt)
3766 {
3767 // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
3768 if (fmt[0] != '%')
3769 return fmt;
3770 const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
3771 const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
3772 for (char c; (c = *fmt) != 0; fmt++)
3773 {
3774 if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
3775 return fmt + 1;
3776 if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
3777 return fmt + 1;
3778 }
3779 return fmt;
3780 }
3781
3782 // Extract the format out of a format string with leading or trailing decorations
3783 // fmt = "blah blah" -> return ""
3784 // fmt = "%.3f" -> return fmt
3785 // fmt = "hello %.3f" -> return fmt + 6
3786 // fmt = "%.3f hello" -> return buf written with "%.3f"
3787 const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
3788 {
3789 const char* fmt_start = ImParseFormatFindStart(fmt);
3790 if (fmt_start[0] != '%')
3791 return "";
3792 const char* fmt_end = ImParseFormatFindEnd(fmt_start);
3793 if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
3794 return fmt_start;
3795 ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
3796 return buf;
3797 }
3798
3799 // Sanitize format
3800 // - Zero terminate so extra characters after format (e.g. "%f123") don't confuse atof/atoi
3801 // - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi.
3802 void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3803 {
3804 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3805 IM_UNUSED(fmt_out_size);
3806 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3807 while (fmt_in < fmt_end)
3808 {
3809 char c = *fmt_in++;
3810 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3811 *(fmt_out++) = c;
3812 }
3813 *fmt_out = 0; // Zero-terminate
3814 }
3815
3816 // - 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"
3817 const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3818 {
3819 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3820 const char* fmt_out_begin = fmt_out;
3821 IM_UNUSED(fmt_out_size);
3822 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3823 bool has_type = false;
3824 while (fmt_in < fmt_end)
3825 {
3826 char c = *fmt_in++;
3827 if (!has_type && ((c >= '0' && c <= '9') || c == '.' || c == '+' || c == '#'))
3828 continue;
3829 has_type |= ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); // Stop skipping digits
3830 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3831 *(fmt_out++) = c;
3832 }
3833 *fmt_out = 0; // Zero-terminate
3834 return fmt_out_begin;
3835 }
3836
3837 template<typename TYPE>
3838 static const char* ImAtoi(const char* src, TYPE* output)
3839 {
3840 int negative = 0;
3841 if (*src == '-') { negative = 1; src++; }
3842 if (*src == '+') { src++; }
3843 TYPE v = 0;
3844 while (*src >= '0' && *src <= '9')
3845 v = (v * 10) + (*src++ - '0');
3846 *output = negative ? -v : v;
3847 return src;
3848 }
3849
3850 // Parse display precision back from the display format string
3851 // 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.
3852 int ImParseFormatPrecision(const char* fmt, int default_precision)
3853 {
3854 fmt = ImParseFormatFindStart(fmt);
3855 if (fmt[0] != '%')
3856 return default_precision;
3857 fmt++;
3858 while (*fmt >= '0' && *fmt <= '9')
3859 fmt++;
3860 int precision = INT_MAX;
3861 if (*fmt == '.')
3862 {
3863 fmt = ImAtoi<int>(fmt + 1, &precision);
3864 if (precision < 0 || precision > 99)
3865 precision = default_precision;
3866 }
3867 if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
3868 precision = -1;
3869 if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
3870 precision = -1;
3871 return (precision == INT_MAX) ? default_precision : precision;
3872 }
3873
3874 // Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
3875 // FIXME: Facilitate using this in variety of other situations.
3876 // FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but
3877 // the expected relationship between TempInputXXX functions and LastItemData is a little fishy.
3878 bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)
3879 {
3880 // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
3881 // We clear ActiveID on the first frame to allow the InputText() taking it back.
3882 ImGuiContext& g = *GImGui;
3883 const bool init = (g.TempInputId != id);
3884 if (init)
3885 ClearActiveID();
3886
3887 g.CurrentWindow->DC.CursorPos = bb.Min;
3888 g.LastItemData.ItemFlags |= ImGuiItemFlags_AllowDuplicateId;
3889 bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);
3890 if (init)
3891 {
3892 // First frame we started displaying the InputText widget, we expect it to take the active id.
3893 IM_ASSERT(g.ActiveId == id);
3894 g.TempInputId = g.ActiveId;
3895 }
3896 return value_changed;
3897 }
3898
3899 // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set!
3900 // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility.
3901 // However this may not be ideal for all uses, as some user code may break on out of bound values.
3902 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)
3903 {
3904 // FIXME: May need to clarify display behavior if format doesn't contain %.
3905 // "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405
3906 ImGuiContext& g = *GImGui;
3907 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
3908 char fmt_buf[32];
3909 char data_buf[32];
3910 format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
3911 if (format[0] == 0)
3912 format = type_info->PrintFmt;
3913 DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);
3914 ImStrTrimBlanks(data_buf);
3915
3916 ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3917 g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData.
3918 bool value_changed = false;
3919 if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))
3920 {
3921 // Backup old value
3922 size_t data_type_size = type_info->Size;
3923 ImGuiDataTypeStorage data_backup;
3924 memcpy(&data_backup, p_data, data_type_size);
3925
3926 // Apply new value (or operations) then clamp
3927 DataTypeApplyFromText(data_buf, data_type, p_data, format, NULL);
3928 if (p_clamp_min || p_clamp_max)
3929 {
3930 if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0)
3931 ImSwap(p_clamp_min, p_clamp_max);
3932 DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max);
3933 }
3934
3935 // Only mark as edited if new value is different
3936 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
3937 value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;
3938 if (value_changed)
3939 MarkItemEdited(id);
3940 }
3941 return value_changed;
3942 }
3943
3944 void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data)
3945 {
3946 ImGuiContext& g = *GImGui;
3947 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasRefVal;
3948 memcpy(&g.NextItemData.RefVal, p_data, DataTypeGetInfo(data_type)->Size);
3949 }
3950
3951 // 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.
3952 // Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3953 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)
3954 {
3955 ImGuiWindow* window = GetCurrentWindow();
3956 if (window->SkipItems)
3957 return false;
3958
3959 ImGuiContext& g = *GImGui;
3960 ImGuiStyle& style = g.Style;
3961 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()!
3962
3963 if (format == NULL)
3964 format = DataTypeGetInfo(data_type)->PrintFmt;
3965
3966 void* p_data_default = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue;
3967
3968 char buf[64];
3969 if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0)
3970 buf[0] = 0;
3971 else
3972 DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);
3973
3974 // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited.
3975 // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
3976 g.NextItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited;
3977 flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3978
3979 bool value_changed = false;
3980 if (p_step == NULL)
3981 {
3982 if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
3983 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3984 }
3985 else
3986 {
3987 const float button_size = GetFrameHeight();
3988
3989 BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
3990 PushID(label);
3991 SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
3992 if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
3993 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3994 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
3995
3996 // Step buttons
3997 const ImVec2 backup_frame_padding = style.FramePadding;
3998 style.FramePadding.x = style.FramePadding.y;
3999 if (flags & ImGuiInputTextFlags_ReadOnly)
4000 BeginDisabled();
4001 PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
4002 SameLine(0, style.ItemInnerSpacing.x);
4003 if (ButtonEx("-", ImVec2(button_size, button_size)))
4004 {
4005 DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
4006 value_changed = true;
4007 }
4008 SameLine(0, style.ItemInnerSpacing.x);
4009 if (ButtonEx("+", ImVec2(button_size, button_size)))
4010 {
4011 DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
4012 value_changed = true;
4013 }
4014 PopItemFlag();
4015 if (flags & ImGuiInputTextFlags_ReadOnly)
4016 EndDisabled();
4017
4018 const char* label_end = FindRenderedTextEnd(label);
4019 if (label != label_end)
4020 {
4021 SameLine(0, style.ItemInnerSpacing.x);
4022 TextEx(label, label_end);
4023 }
4024 style.FramePadding = backup_frame_padding;
4025
4026 PopID();
4027 EndGroup();
4028 }
4029
4030 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
4031 if (value_changed)
4032 MarkItemEdited(g.LastItemData.ID);
4033
4034 return value_changed;
4035 }
4036
4037 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)
4038 {
4039 ImGuiWindow* window = GetCurrentWindow();
4040 if (window->SkipItems)
4041 return false;
4042
4043 ImGuiContext& g = *GImGui;
4044 bool value_changed = false;
4045 BeginGroup();
4046 PushID(label);
4047 PushMultiItemsWidths(components, CalcItemWidth());
4048 size_t type_size = GDataTypeInfo[data_type].Size;
4049 for (int i = 0; i < components; i++)
4050 {
4051 PushID(i);
4052 if (i > 0)
4053 SameLine(0, g.Style.ItemInnerSpacing.x);
4054 value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags);
4055 PopID();
4056 PopItemWidth();
4057 p_data = (void*)((char*)p_data + type_size);
4058 }
4059 PopID();
4060
4061 const char* label_end = FindRenderedTextEnd(label);
4062 if (label != label_end)
4063 {
4064 SameLine(0.0f, g.Style.ItemInnerSpacing.x);
4065 TextEx(label, label_end);
4066 }
4067
4068 EndGroup();
4069 return value_changed;
4070 }
4071
4072 bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
4073 {
4074 return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags);
4075 }
4076
4077 bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
4078 {
4079 return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
4080 }
4081
4082 bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
4083 {
4084 return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
4085 }
4086
4087 bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
4088 {
4089 return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
4090 }
4091
4092 bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
4093 {
4094 // 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.
4095 const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
4096 return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags);
4097 }
4098
4099 bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
4100 {
4101 return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
4102 }
4103
4104 bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
4105 {
4106 return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
4107 }
4108
4109 bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
4110 {
4111 return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
4112 }
4113
4114 bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
4115 {
4116 return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags);
4117 }
4118
4119 //-------------------------------------------------------------------------
4120 // [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
4121 //-------------------------------------------------------------------------
4122 // - imstb_textedit.h include
4123 // - InputText()
4124 // - InputTextWithHint()
4125 // - InputTextMultiline()
4126 // - InputTextGetCharInfo() [Internal]
4127 // - InputTextReindexLines() [Internal]
4128 // - InputTextReindexLinesRange() [Internal]
4129 // - InputTextEx() [Internal]
4130 // - DebugNodeInputTextState() [Internal]
4131 //-------------------------------------------------------------------------
4132
4133 namespace ImStb
4134 {
4135 #include "imstb_textedit.h"
4136 }
4137
4138 bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
4139 {
4140 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
4141 return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
4142 }
4143
4144 bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
4145 {
4146 return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
4147 }
4148
4149 bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
4150 {
4151 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint.
4152 return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
4153 }
4154
4155 // This is only used in the path where the multiline widget is inactive.
4156 static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
4157 {
4158 int line_count = 0;
4159 const char* s = text_begin;
4160 while (true)
4161 {
4162 const char* s_eol = strchr(s, '\n');
4163 line_count++;
4164 if (s_eol == NULL)
4165 {
4166 s = s + ImStrlen(s);
4167 break;
4168 }
4169 s = s_eol + 1;
4170 }
4171 *out_text_end = s;
4172 return line_count;
4173 }
4174
4175 // FIXME: Ideally we'd share code with ImFont::CalcTextSizeA()
4176 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line)
4177 {
4178 ImGuiContext& g = *ctx;
4179 //ImFont* font = g.Font;
4180 ImFontBaked* baked = g.FontBaked;
4181 const float line_height = g.FontSize;
4182 const float scale = line_height / baked->Size;
4183
4184 ImVec2 text_size = ImVec2(0, 0);
4185 float line_width = 0.0f;
4186
4187 const char* s = text_begin;
4188 while (s < text_end)
4189 {
4190 unsigned int c = (unsigned int)*s;
4191 if (c < 0x80)
4192 s += 1;
4193 else
4194 s += ImTextCharFromUtf8(&c, s, text_end);
4195
4196 if (c == '\n')
4197 {
4198 text_size.x = ImMax(text_size.x, line_width);
4199 text_size.y += line_height;
4200 line_width = 0.0f;
4201 if (stop_on_new_line)
4202 break;
4203 continue;
4204 }
4205 if (c == '\r')
4206 continue;
4207
4208 line_width += baked->GetCharAdvance((ImWchar)c) * scale;
4209 }
4210
4211 if (text_size.x < line_width)
4212 text_size.x = line_width;
4213
4214 if (out_offset)
4215 *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
4216
4217 if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
4218 text_size.y += line_height;
4219
4220 if (remaining)
4221 *remaining = s;
4222
4223 return text_size;
4224 }
4225
4226 // 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)
4227 // With our UTF-8 use of stb_textedit:
4228 // - 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.
4229 // - 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).
4230 // - ...but we don't use that feature.
4231 namespace ImStb
4232 {
4233 static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; }
4234 static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextSrc[idx]; }
4235 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; }
4236 static char STB_TEXTEDIT_NEWLINE = '\n';
4237 static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
4238 {
4239 const char* text = obj->TextSrc;
4240 const char* text_remaining = NULL;
4241 const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, &text_remaining, NULL, true);
4242 r->x0 = 0.0f;
4243 r->x1 = size.x;
4244 r->baseline_y_delta = size.y;
4245 r->ymin = 0.0f;
4246 r->ymax = size.y;
4247 r->num_chars = (int)(text_remaining - (text + line_start_idx));
4248 }
4249
4250 #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
4251 #define IMSTB_TEXTEDIT_GETPREVCHARINDEX IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
4252
4253 static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
4254 {
4255 if (idx >= obj->TextLen)
4256 return obj->TextLen + 1;
4257 unsigned int c;
4258 return idx + ImTextCharFromUtf8(&c, obj->TextSrc + idx, obj->TextSrc + obj->TextLen);
4259 }
4260
4261 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
4262 {
4263 if (idx <= 0)
4264 return -1;
4265 const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, obj->TextSrc + idx);
4266 return (int)(p - obj->TextSrc);
4267 }
4268
4269 static bool ImCharIsSeparatorW(unsigned int c)
4270 {
4271 static const unsigned int separator_list[] =
4272 {
4273 ',', 0x3001, '.', 0x3002, ';', 0xFF1B, '(', 0xFF08, ')', 0xFF09, '{', 0xFF5B, '}', 0xFF5D,
4274 '[', 0x300C, ']', 0x300D, '|', 0xFF5C, '!', 0xFF01, '\\', 0xFFE5, '/', 0x30FB, 0xFF0F,
4275 '\n', '\r',
4276 };
4277 for (unsigned int separator : separator_list)
4278 if (c == separator)
4279 return true;
4280 return false;
4281 }
4282
4283 static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
4284 {
4285 // 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.
4286 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
4287 return 0;
4288
4289 const char* curr_p = obj->TextSrc + idx;
4290 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
4291 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextSrc + obj->TextLen);
4292 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextSrc + obj->TextLen);
4293
4294 bool prev_white = ImCharIsBlankW(prev_c);
4295 bool prev_separ = ImCharIsSeparatorW(prev_c);
4296 bool curr_white = ImCharIsBlankW(curr_c);
4297 bool curr_separ = ImCharIsSeparatorW(curr_c);
4298 return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
4299 }
4300 static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
4301 {
4302 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
4303 return 0;
4304
4305 const char* curr_p = obj->TextSrc + idx;
4306 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextSrc, curr_p);
4307 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextSrc + obj->TextLen);
4308 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextSrc + obj->TextLen);
4309
4310 bool prev_white = ImCharIsBlankW(prev_c);
4311 bool prev_separ = ImCharIsSeparatorW(prev_c);
4312 bool curr_white = ImCharIsBlankW(curr_c);
4313 bool curr_separ = ImCharIsSeparatorW(curr_c);
4314 return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
4315 }
4316 static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
4317 {
4318 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4319 while (idx >= 0 && !is_word_boundary_from_right(obj, idx))
4320 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4321 return idx < 0 ? 0 : idx;
4322 }
4323 static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
4324 {
4325 int len = obj->TextLen;
4326 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4327 while (idx < len && !is_word_boundary_from_left(obj, idx))
4328 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4329 return idx > len ? len : idx;
4330 }
4331 static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
4332 {
4333 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4334 int len = obj->TextLen;
4335 while (idx < len && !is_word_boundary_from_right(obj, idx))
4336 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4337 return idx > len ? len : idx;
4338 }
4339 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); }
4340 #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
4341 #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
4342
4343 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
4344 {
4345 // Offset remaining text (+ copy zero terminator)
4346 IM_ASSERT(obj->TextSrc == obj->TextA.Data);
4347 char* dst = obj->TextA.Data + pos;
4348 char* src = obj->TextA.Data + pos + n;
4349 memmove(dst, src, obj->TextLen - n - pos + 1);
4350 obj->Edited = true;
4351 obj->TextLen -= n;
4352 }
4353
4354 static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
4355 {
4356 const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4357 const int text_len = obj->TextLen;
4358 if (pos > text_len) {
4359 printf("failing STB_TEXTEDIT_INSERTCHARS assertion! oh man...\n");
4360 obj->Edited = true; // ???
4361 obj->ClearText();
4362 return false;
4363 }
4364
4365 if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity))
4366 return false;
4367
4368 // Grow internal buffer if needed
4369 IM_ASSERT(obj->TextSrc == obj->TextA.Data);
4370 if (new_text_len + text_len + 1 > obj->TextA.Size)
4371 {
4372 if (!is_resizable)
4373 return false;
4374 obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
4375 obj->TextSrc = obj->TextA.Data;
4376 }
4377
4378 char* text = obj->TextA.Data;
4379 if (pos != text_len)
4380 memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos));
4381 memcpy(text + pos, new_text, (size_t)new_text_len);
4382
4383 obj->Edited = true;
4384 obj->TextLen += new_text_len;
4385 obj->TextA[obj->TextLen] = '\0';
4386
4387 return true;
4388 }
4389
4390 // 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)
4391 #define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left
4392 #define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right
4393 #define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up
4394 #define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down
4395 #define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line
4396 #define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line
4397 #define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text
4398 #define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text
4399 #define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor
4400 #define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor
4401 #define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo
4402 #define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo
4403 #define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word
4404 #define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word
4405 #define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page
4406 #define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page
4407 #define STB_TEXTEDIT_K_SHIFT 0x400000
4408
4409 #define IMSTB_TEXTEDIT_IMPLEMENTATION
4410 #define IMSTB_TEXTEDIT_memmove memmove
4411 #include "imstb_textedit.h"
4412
4413 // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling
4414 // the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
4415 static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
4416 {
4417 stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len);
4418 ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen);
4419 state->cursor = state->select_start = state->select_end = 0;
4420 if (text_len <= 0)
4421 return;
4422 if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len))
4423 {
4424 state->cursor = state->select_start = state->select_end = text_len;
4425 state->has_preferred_x = 0;
4426 return;
4427 } else {
4428 state->cursor = 0;
4429 printf("STB_TEXTEDIT_INSERTCHARS fail!\n");
4430 }
4431 //IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()
4432 }
4433
4434 } // namespace ImStb
4435
4436 // We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators.
4437 ImGuiInputTextState::ImGuiInputTextState()
4438 {
4439 memset(this, 0, sizeof(*this));
4440 Stb = IM_NEW(ImStbTexteditState);
4441 memset(Stb, 0, sizeof(*Stb));
4442 }
4443
4444 ImGuiInputTextState::~ImGuiInputTextState()
4445 {
4446 IM_DELETE(Stb);
4447 }
4448
4449 void ImGuiInputTextState::OnKeyPressed(int key)
4450 {
4451 stb_textedit_key(this, Stb, key);
4452 CursorFollow = true;
4453 CursorAnimReset();
4454 }
4455
4456 void ImGuiInputTextState::OnCharPressed(unsigned int c)
4457 {
4458 // Convert the key to a UTF8 byte sequence.
4459 // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
4460 char utf8[5];
4461 ImTextCharToUtf8(utf8, c);
4462 stb_textedit_text(this, Stb, utf8, (int)ImStrlen(utf8));
4463 CursorFollow = true;
4464 CursorAnimReset();
4465 }
4466
4467 // Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
4468 void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
4469 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); }
4470 bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; }
4471 void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; }
4472 int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; }
4473 int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; }
4474 int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; }
4475 void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
4476 void ImGuiInputTextState::ReloadUserBufAndSelectAll() { WantReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
4477 void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { WantReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
4478 void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { WantReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
4479
4480 ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
4481 {
4482 memset(this, 0, sizeof(*this));
4483 }
4484
4485 // Public API to manipulate UTF-8 text from within a callback.
4486 // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
4487 // Historically they existed because STB_TEXTEDIT_INSERTCHARS() etc. worked on our ImWchar
4488 // buffer, but nowadays they both work on UTF-8 data. Should aim to merge both.
4489 void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
4490 {
4491 IM_ASSERT(pos + bytes_count <= BufTextLen);
4492 char* dst = Buf + pos;
4493 const char* src = Buf + pos + bytes_count;
4494 memmove(dst, src, BufTextLen - bytes_count - pos + 1);
4495
4496 if (CursorPos >= pos + bytes_count)
4497 CursorPos -= bytes_count;
4498 else if (CursorPos >= pos)
4499 CursorPos = pos;
4500 SelectionStart = SelectionEnd = CursorPos;
4501 BufDirty = true;
4502 BufTextLen -= bytes_count;
4503 }
4504
4505 void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
4506 {
4507 // Accept null ranges
4508 if (new_text == new_text_end)
4509 return;
4510
4511 ImGuiContext& g = *Ctx;
4512 ImGuiInputTextState* obj = &g.InputTextState;
4513 IM_ASSERT(obj->ID != 0 && g.ActiveId == obj->ID);
4514
4515 // Grow internal buffer if needed
4516 const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4517 const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)ImStrlen(new_text);
4518 if (new_text_len + BufTextLen + 1 > obj->TextA.Size && (Flags & ImGuiInputTextFlags_ReadOnly) == 0)
4519 {
4520 if (!is_resizable)
4521 return;
4522
4523 IM_ASSERT(Buf == obj->TextA.Data);
4524 int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
4525 obj->TextA.resize(new_buf_size + 1);
4526 obj->TextSrc = obj->TextA.Data;
4527 Buf = obj->TextA.Data;
4528 BufSize = obj->BufCapacity = new_buf_size;
4529 }
4530
4531 if (BufTextLen != pos)
4532 memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
4533 memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
4534 Buf[BufTextLen + new_text_len] = '\0';
4535
4536 if (CursorPos >= pos)
4537 CursorPos += new_text_len;
4538 SelectionStart = SelectionEnd = CursorPos;
4539 BufDirty = true;
4540 BufTextLen += new_text_len;
4541 }
4542
4543 void ImGui::PushPasswordFont()
4544 {
4545 ImGuiContext& g = *GImGui;
4546 ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
4547 IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
4548 ImFontGlyph* glyph = g.FontBaked->FindGlyph('*');
4549 g.InputTextPasswordFontBackupFlags = g.Font->Flags;
4550 backup->FallbackGlyphIndex = g.FontBaked->FallbackGlyphIndex;
4551 backup->FallbackAdvanceX = g.FontBaked->FallbackAdvanceX;
4552 backup->IndexLookup.swap(g.FontBaked->IndexLookup);
4553 backup->IndexAdvanceX.swap(g.FontBaked->IndexAdvanceX);
4554 g.Font->Flags |= ImFontFlags_NoLoadGlyphs;
4555 g.FontBaked->FallbackGlyphIndex = g.FontBaked->Glyphs.index_from_ptr(glyph);
4556 g.FontBaked->FallbackAdvanceX = glyph->AdvanceX;
4557 }
4558
4559 void ImGui::PopPasswordFont()
4560 {
4561 ImGuiContext& g = *GImGui;
4562 ImFontBaked* backup = &g.InputTextPasswordFontBackupBaked;
4563 g.Font->Flags = g.InputTextPasswordFontBackupFlags;
4564 g.FontBaked->FallbackGlyphIndex = backup->FallbackGlyphIndex;
4565 g.FontBaked->FallbackAdvanceX = backup->FallbackAdvanceX;
4566 g.FontBaked->IndexLookup.swap(backup->IndexLookup);
4567 g.FontBaked->IndexAdvanceX.swap(backup->IndexAdvanceX);
4568 IM_ASSERT(backup->IndexAdvanceX.Size == 0 && backup->IndexLookup.Size == 0);
4569 }
4570
4571 // Return false to discard a character.
4572 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard)
4573 {
4574 unsigned int c = *p_char;
4575
4576 // Filter non-printable (NB: isprint is unreliable! see #2467)
4577 bool apply_named_filters = true;
4578 if (c < 0x20)
4579 {
4580 bool pass = false;
4581 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)
4582 if (c == '\n' && input_source_is_clipboard && (flags & ImGuiInputTextFlags_Multiline) == 0) // In single line mode, replace \n with a space
4583 {
4584 c = *p_char = ' ';
4585 pass = true;
4586 }
4587 pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0;
4588 pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0;
4589 if (!pass)
4590 return false;
4591 apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted.
4592 }
4593
4594 if (input_source_is_clipboard == false)
4595 {
4596 // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
4597 if (c == 127)
4598 return false;
4599
4600 // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
4601 if (c >= 0xE000 && c <= 0xF8FF)
4602 return false;
4603 }
4604
4605 // Filter Unicode ranges we are not handling in this build
4606 if (c > IM_UNICODE_CODEPOINT_MAX)
4607 return false;
4608
4609 // Generic named filters
4610 if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint)))
4611 {
4612 // 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 '.'.
4613 // The standard mandate that programs starts in the "C" locale where the decimal point is '.'.
4614 // 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.
4615 // Change the default decimal_point with:
4616 // ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point;
4617 // 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.
4618 ImGuiContext& g = *ctx;
4619 const unsigned c_decimal_point = (unsigned int)g.PlatformIO.Platform_LocaleDecimalPoint;
4620 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint))
4621 if (c == '.' || c == ',')
4622 c = c_decimal_point;
4623
4624 // Full-width -> half-width conversion for numeric fields (https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
4625 // While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may
4626 // scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font.
4627 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal))
4628 if (c >= 0xFF01 && c <= 0xFF5E)
4629 c = c - 0xFF01 + 0x21;
4630
4631 // Allow 0-9 . - + * /
4632 if (flags & ImGuiInputTextFlags_CharsDecimal)
4633 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
4634 return false;
4635
4636 // Allow 0-9 . - + * / e E
4637 if (flags & ImGuiInputTextFlags_CharsScientific)
4638 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
4639 return false;
4640
4641 // Allow 0-9 a-F A-F
4642 if (flags & ImGuiInputTextFlags_CharsHexadecimal)
4643 if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
4644 return false;
4645
4646 // Turn a-z into A-Z
4647 if (flags & ImGuiInputTextFlags_CharsUppercase)
4648 if (c >= 'a' && c <= 'z')
4649 c += (unsigned int)('A' - 'a');
4650
4651 if (flags & ImGuiInputTextFlags_CharsNoBlank)
4652 if (ImCharIsBlankW(c))
4653 return false;
4654
4655 *p_char = c;
4656 }
4657
4658 // Custom callback filter
4659 if (flags & ImGuiInputTextFlags_CallbackCharFilter)
4660 {
4661 ImGuiContext& g = *GImGui;
4662 ImGuiInputTextCallbackData callback_data;
4663 callback_data.Ctx = &g;
4664 callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
4665 callback_data.EventChar = (ImWchar)c;
4666 callback_data.Flags = flags;
4667 callback_data.UserData = user_data;
4668 if (callback(&callback_data) != 0)
4669 return false;
4670 *p_char = callback_data.EventChar;
4671 if (!callback_data.EventChar)
4672 return false;
4673 }
4674
4675 return true;
4676 }
4677
4678 // Find the shortest single replacement we can make to get from old_buf to new_buf
4679 // Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately.
4680 // 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.
4681 static void InputTextReconcileUndoState(ImGuiInputTextState* state, const char* old_buf, int old_length, const char* new_buf, int new_length)
4682 {
4683 const int shorter_length = ImMin(old_length, new_length);
4684 int first_diff;
4685 for (first_diff = 0; first_diff < shorter_length; first_diff++)
4686 if (old_buf[first_diff] != new_buf[first_diff])
4687 break;
4688 if (first_diff == old_length && first_diff == new_length)
4689 return;
4690
4691 int old_last_diff = old_length - 1;
4692 int new_last_diff = new_length - 1;
4693 for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
4694 if (old_buf[old_last_diff] != new_buf[new_last_diff])
4695 break;
4696
4697 const int insert_len = new_last_diff - first_diff + 1;
4698 const int delete_len = old_last_diff - first_diff + 1;
4699 if (insert_len > 0 || delete_len > 0)
4700 if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len))
4701 for (int i = 0; i < delete_len; i++)
4702 p[i] = old_buf[first_diff + i];
4703 }
4704
4705 // As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables)
4706 // we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714)
4707 // It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick,
4708 // but that more likely be attractive when we do have _NoLiveEdit flag available.
4709 void ImGui::InputTextDeactivateHook(ImGuiID id)
4710 {
4711 ImGuiContext& g = *GImGui;
4712 ImGuiInputTextState* state = &g.InputTextState;
4713 if (id == 0 || state->ID != id)
4714 return;
4715 g.InputTextDeactivatedState.ID = state->ID;
4716 if (state->Flags & ImGuiInputTextFlags_ReadOnly)
4717 {
4718 g.InputTextDeactivatedState.TextA.resize(0); // In theory this data won't be used, but clear to be neat.
4719 }
4720 else
4721 {
4722 IM_ASSERT(state->TextA.Data != 0);
4723 IM_ASSERT(state->TextA[state->TextLen] == 0);
4724 g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1);
4725 memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1);
4726 }
4727 }
4728
4729 // Edit a string of text
4730 // - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
4731 // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
4732 // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
4733 // - 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.
4734 // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
4735 // (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
4736 // 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)
4737 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)
4738 {
4739 ImGuiWindow* window = GetCurrentWindow();
4740 if (window->SkipItems)
4741 return false;
4742
4743 IM_ASSERT(buf != NULL && buf_size >= 0);
4744 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
4745 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
4746 IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline will not work with left-trimming
4747
4748 ImGuiContext& g = *GImGui;
4749 ImGuiIO& io = g.IO;
4750 const ImGuiStyle& style = g.Style;
4751
4752 const bool RENDER_SELECTION_WHEN_INACTIVE = false;
4753 const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
4754
4755 if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar)
4756 BeginGroup();
4757 const ImGuiID id = window->GetID(label);
4758 const ImVec2 label_size = CalcTextSize(label, NULL, true);
4759 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
4760 const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y);
4761
4762 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
4763 const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size);
4764
4765 ImGuiWindow* draw_window = window;
4766 ImVec2 inner_size = frame_size;
4767 ImGuiLastItemData item_data_backup;
4768 if (is_multiline)
4769 {
4770 ImVec2 backup_pos = window->DC.CursorPos;
4771 ItemSize(total_bb, style.FramePadding.y);
4772 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4773 {
4774 EndGroup();
4775 return false;
4776 }
4777 item_data_backup = g.LastItemData;
4778 window->DC.CursorPos = backup_pos;
4779
4780 // Prevent NavActivation from Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping.
4781 if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && (flags & ImGuiInputTextFlags_AllowTabInput))
4782 g.NavActivateId = 0;
4783
4784 // Prevent NavActivate reactivating in BeginChild() when we are already active.
4785 const ImGuiID backup_activate_id = g.NavActivateId;
4786 if (g.ActiveId == id) // Prevent reactivation
4787 g.NavActivateId = 0;
4788
4789 // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug.
4790 PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
4791 PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
4792 PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
4793 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges
4794 bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove);
4795 g.NavActivateId = backup_activate_id;
4796 PopStyleVar(3);
4797 PopStyleColor();
4798 if (!child_visible)
4799 {
4800 EndChild();
4801 EndGroup();
4802 return false;
4803 }
4804 draw_window = g.CurrentWindow; // Child window
4805 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.
4806 draw_window->DC.CursorPos += style.FramePadding;
4807 inner_size.x -= draw_window->ScrollbarSizes.x;
4808 }
4809 else
4810 {
4811 // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd)
4812 ItemSize(total_bb, style.FramePadding.y);
4813 if (!(flags & ImGuiInputTextFlags_MergedItem))
4814 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4815 return false;
4816 }
4817
4818 // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
4819 bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover);
4820 if (hovered)
4821 SetMouseCursor(ImGuiMouseCursor_TextInput);
4822 if (hovered && g.NavHighlightItemUnderNav)
4823 hovered = false;
4824
4825 // We are only allowed to access the state if we are already the active widget.
4826 ImGuiInputTextState* state = GetInputTextState(id);
4827
4828 if (g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly)
4829 flags |= ImGuiInputTextFlags_ReadOnly;
4830 const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
4831 const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
4832 const bool is_undoable = (flags & ImGuiInputTextFlags_UndoRedo) != 0;
4833 const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
4834 if (is_resizable)
4835 IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
4836
4837 const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard)));
4838
4839 const bool user_clicked = hovered && io.MouseClicked[0];
4840 const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4841 const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4842 bool clear_active_id = false;
4843 bool select_all = false;
4844
4845 float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;
4846
4847 const bool init_reload_from_user_buf = (state != NULL && state->WantReloadUserBuf);
4848 const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
4849 const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
4850 const bool init_state = (init_make_active || user_scroll_active);
4851 if (init_reload_from_user_buf)
4852 {
4853 int new_len = (int)ImStrlen(buf);
4854 IM_ASSERT(new_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?");
4855 state->WantReloadUserBuf = false;
4856 InputTextReconcileUndoState(state, state->TextA.Data, state->TextLen, buf, new_len);
4857 state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
4858 state->TextLen = new_len;
4859 memcpy(state->TextA.Data, buf, state->TextLen + 1);
4860 state->Stb->select_start = state->ReloadSelectionStart;
4861 state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
4862 state->CursorClamp();
4863 }
4864 else if ((init_state && g.ActiveId != id) || init_changed_specs)
4865 {
4866 // Access state even if we don't own it yet.
4867 state = &g.InputTextState;
4868 state->CursorAnimReset();
4869
4870 // 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)
4871 InputTextDeactivateHook(state->ID);
4872
4873 // Take a copy of the initial buffer value.
4874 // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
4875 const int buf_len = (int)ImStrlen(buf);
4876 IM_ASSERT(buf_len + 1 <= buf_size && "Is your input buffer properly zero-terminated?");
4877 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.
4878 memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
4879
4880 // Preserve cursor position and undo/redo stack if we come back to same widget
4881 // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
4882 bool recycle_state = (state->ID == id && !init_changed_specs);
4883 if (recycle_state && (state->TextLen != buf_len || (state->TextA.Data == NULL || strncmp(state->TextA.Data, buf, buf_len) != 0)))
4884 recycle_state = false;
4885
4886 // Start edition
4887 state->ID = id;
4888 state->TextLen = buf_len;
4889 if (!is_readonly)
4890 {
4891 state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
4892 memcpy(state->TextA.Data, buf, state->TextLen + 1);
4893 }
4894
4895 // Find initial scroll position for right alignment
4896 state->Scroll = ImVec2(0.0f, 0.0f);
4897 if (flags & ImGuiInputTextFlags_ElideLeft)
4898 state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
4899
4900 // Recycle existing cursor/selection/undo stack but clamp position
4901 // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
4902 if (recycle_state)
4903 state->CursorClamp();
4904 else
4905 stb_textedit_initialize_state(state->Stb, !is_multiline);
4906
4907 if (!is_multiline)
4908 {
4909 if (flags & ImGuiInputTextFlags_AutoSelectAll)
4910 select_all = true;
4911 if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState)))
4912 select_all = true;
4913 if (user_clicked && io.KeyCtrl)
4914 select_all = true;
4915 }
4916
4917 if (flags & ImGuiInputTextFlags_AlwaysOverwrite)
4918 state->Stb->insert_mode = 1; // stb field name is indeed incorrect (see #2863)
4919 }
4920
4921 const bool is_osx = io.ConfigMacOSXBehaviors;
4922 if (g.ActiveId != id && init_make_active)
4923 {
4924 IM_ASSERT(state && state->ID == id);
4925 SetActiveID(id, window);
4926 SetFocusID(id, window);
4927 FocusWindow(window);
4928 }
4929 if (g.ActiveId == id)
4930 {
4931 // Declare some inputs, the other are registered and polled via Shortcut() routing system.
4932 // 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.
4933 const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End };
4934 for (ImGuiKey key : always_owned_keys)
4935 SetKeyOwner(key, id);
4936 if (user_clicked)
4937 SetKeyOwner(ImGuiKey_MouseLeft, id);
4938 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
4939 if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
4940 {
4941 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
4942 SetKeyOwner(ImGuiKey_UpArrow, id);
4943 SetKeyOwner(ImGuiKey_DownArrow, id);
4944 }
4945 if (is_multiline)
4946 {
4947 SetKeyOwner(ImGuiKey_PageUp, id);
4948 SetKeyOwner(ImGuiKey_PageDown, id);
4949 }
4950 // FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu
4951 if (is_osx)
4952 SetKeyOwner(ImGuiMod_Alt, id);
4953
4954 // Expose scroll in a manner that is agnostic to us using a child window
4955 if (is_multiline && state != NULL)
4956 state->Scroll.y = draw_window->Scroll.y;
4957
4958 // Read-only mode always ever read from source buffer. Refresh TextLen when active.
4959 if (is_readonly && state != NULL)
4960 state->TextLen = (int)ImStrlen(buf);
4961 //if (is_readonly && state != NULL)
4962 // state->TextA.clear(); // Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation.
4963 }
4964 if (state != NULL)
4965 state->TextSrc = is_readonly ? buf : state->TextA.Data;
4966
4967 // 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)
4968 if (g.ActiveId == id && state == NULL)
4969 ClearActiveID();
4970
4971 // Release focus when we click outside
4972 if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
4973 clear_active_id = true;
4974
4975 // Lock the decision of whether we are going to take the path displaying the cursor or selection
4976 bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
4977 bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
4978 bool value_changed = false;
4979 bool validated = false;
4980
4981 // Select the buffer to render.
4982 const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state;
4983 bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
4984
4985 // Password pushes a temporary font with only a fallback glyph
4986 if (is_password && !is_displaying_hint)
4987 PushPasswordFont();
4988
4989 // Process mouse inputs and character inputs
4990 if (g.ActiveId == id)
4991 {
4992 IM_ASSERT(state != NULL);
4993 state->Edited = false;
4994 state->BufCapacity = buf_size;
4995 state->Flags = flags;
4996
4997 // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
4998 // Down the line we should have a cleaner library-wide concept of Selected vs Active.
4999 g.ActiveIdAllowOverlap = !io.MouseDown[0];
5000
5001 // Edit in progress
5002 const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->Scroll.x;
5003 const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f));
5004
5005 if (select_all)
5006 {
5007 state->SelectAll();
5008 state->SelectedAllMouseLock = true;
5009 }
5010 else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift)
5011 {
5012 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
5013 const int multiclick_count = (io.MouseClickedCount[0] - 2);
5014 if ((multiclick_count % 2) == 0)
5015 {
5016 // Double-click: Select word
5017 // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant:
5018 // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS)
5019 const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n';
5020 if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol)
5021 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
5022 //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
5023 if (!STB_TEXT_HAS_SELECTION(state->Stb))
5024 ImStb::stb_textedit_prep_selection_at_cursor(state->Stb);
5025 state->Stb->cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb->cursor);
5026 state->Stb->select_end = state->Stb->cursor;
5027 ImStb::stb_textedit_clamp(state, state->Stb);
5028 }
5029 else
5030 {
5031 // Triple-click: Select line
5032 const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n';
5033 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART);
5034 state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT);
5035 state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT);
5036 if (!is_eol && is_multiline)
5037 {
5038 ImSwap(state->Stb->select_start, state->Stb->select_end);
5039 state->Stb->cursor = state->Stb->select_end;
5040 }
5041 state->CursorFollow = false;
5042 }
5043 state->CursorAnimReset();
5044 }
5045 else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
5046 {
5047 if (hovered)
5048 {
5049 if (io.KeyShift)
5050 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
5051 else
5052 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
5053 state->CursorAnimReset();
5054 }
5055 }
5056 else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
5057 {
5058 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
5059 state->CursorAnimReset();
5060 state->CursorFollow = true;
5061 }
5062 if (state->SelectedAllMouseLock && !io.MouseDown[0])
5063 state->SelectedAllMouseLock = false;
5064
5065 // We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336)
5066 // (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)
5067 if ((flags & ImGuiInputTextFlags_AllowTabInput) && !is_readonly)
5068 {
5069 if (Shortcut(ImGuiKey_Tab, ImGuiInputFlags_Repeat, id))
5070 {
5071 unsigned int c = '\t'; // Insert TAB
5072 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
5073 state->OnCharPressed(c);
5074 }
5075 // FIXME: Implement Shift+Tab
5076 /*
5077 if (Shortcut(ImGuiKey_Tab | ImGuiMod_Shift, ImGuiInputFlags_Repeat, id))
5078 {
5079 }
5080 */
5081 }
5082
5083 // Process regular text input (before we check for Return because using some IME will effectively send a Return?)
5084 // 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.
5085 const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeyCtrl);
5086 if (io.InputQueueCharacters.Size > 0)
5087 {
5088 if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav)
5089 for (int n = 0; n < io.InputQueueCharacters.Size; n++)
5090 {
5091 // Insert character if they pass filtering
5092 unsigned int c = (unsigned int)io.InputQueueCharacters[n];
5093 if (c == '\t') // Skip Tab, see above.
5094 continue;
5095 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
5096 state->OnCharPressed(c);
5097 }
5098
5099 // Consume characters
5100 io.InputQueueCharacters.resize(0);
5101 }
5102 }
5103
5104 // Process other shortcuts/key-presses
5105 bool revert_edit = false;
5106 if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
5107 {
5108 IM_ASSERT(state != NULL);
5109
5110 const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1);
5111 state->Stb->row_count_per_page = row_count_per_page;
5112
5113 const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
5114 const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
5115 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
5116
5117 // 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)
5118 // Otherwise we could simply assume that we own the keys as we are active.
5119 const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat;
5120 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());
5121 const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection());
5122 const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly;
5123 const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
5124 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;
5125 const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id);
5126
5127 // 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.
5128 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
5129 const bool is_enter_pressed = IsKeyPressed(ImGuiKey_Enter, true) || IsKeyPressed(ImGuiKey_KeypadEnter, true);
5130 const bool is_gamepad_validate = nav_gamepad_active && (IsKeyPressed(ImGuiKey_NavGamepadActivate, false) || IsKeyPressed(ImGuiKey_NavGamepadInput, false));
5131 const bool is_cancel = Shortcut(ImGuiKey_Escape, f_repeat, id) || (nav_gamepad_active && Shortcut(ImGuiKey_NavGamepadCancel, f_repeat, id));
5132
5133 // FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of.
5134 // FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line.
5135 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); }
5136 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); }
5137 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); }
5138 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); }
5139 else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; }
5140 else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; }
5141 else if (IsKeyPressed(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
5142 else if (IsKeyPressed(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
5143 else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut)
5144 {
5145 if (!state->HasSelection())
5146 {
5147 // 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)
5148 if (is_wordmove_key_down)
5149 state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
5150 }
5151 state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask);
5152 }
5153 else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly)
5154 {
5155 if (!state->HasSelection())
5156 {
5157 if (is_wordmove_key_down)
5158 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT);
5159 else if (is_osx && io.KeyCtrl && !io.KeyAlt && !io.KeySuper)
5160 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT);
5161 }
5162 state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
5163 }
5164 else if (is_enter_pressed || is_gamepad_validate)
5165 {
5166 // Determine if we turn Enter into a \n character
5167 bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
5168 if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line != io.KeyCtrl))
5169 {
5170 validated = true;
5171 if (io.ConfigInputTextEnterKeepActive && !is_multiline)
5172 state->SelectAll(); // No need to scroll
5173 else
5174 clear_active_id = true;
5175 }
5176 else if (!is_readonly)
5177 {
5178 unsigned int c = '\n'; // Insert new line
5179 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
5180 state->OnCharPressed(c);
5181 }
5182 }
5183 else if (is_cancel)
5184 {
5185 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
5186 {
5187 if (buf[0] != 0)
5188 {
5189 revert_edit = true;
5190 }
5191 else
5192 {
5193 render_cursor = render_selection = false;
5194 clear_active_id = true;
5195 }
5196 }
5197 else
5198 {
5199 clear_active_id = revert_edit = true;
5200 render_cursor = render_selection = false;
5201 }
5202 }
5203 else if (is_undo || is_redo)
5204 {
5205 state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
5206 state->ClearSelection();
5207 }
5208 else if (is_select_all)
5209 {
5210 state->SelectAll();
5211 state->CursorFollow = true;
5212 }
5213 else if (is_cut || is_copy)
5214 {
5215 // Cut, Copy
5216 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
5217 {
5218 // SetClipboardText() only takes null terminated strings + state->TextSrc may point to read-only user buffer, so we need to make a copy.
5219 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
5220 const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
5221 g.TempBuffer.reserve(ie - ib + 1);
5222 memcpy(g.TempBuffer.Data, state->TextSrc + ib, ie - ib);
5223 g.TempBuffer.Data[ie - ib] = 0;
5224 SetClipboardText(g.TempBuffer.Data);
5225 }
5226 if (is_cut)
5227 {
5228 if (!state->HasSelection())
5229 state->SelectAll();
5230 state->CursorFollow = true;
5231 stb_textedit_cut(state, state->Stb);
5232 }
5233 }
5234 else if (is_paste)
5235 {
5236 if (const char* clipboard = GetClipboardText())
5237 {
5238 // Filter pasted buffer
5239 const int clipboard_len = (int)ImStrlen(clipboard);
5240 ImVector<char> clipboard_filtered;
5241 clipboard_filtered.reserve(clipboard_len + 1);
5242 for (const char* s = clipboard; *s != 0; )
5243 {
5244 unsigned int c;
5245 int in_len = ImTextCharFromUtf8(&c, s, NULL);
5246 s += in_len;
5247 if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
5248 continue;
5249 char c_utf8[5];
5250 ImTextCharToUtf8(c_utf8, c);
5251 int out_len = (int)ImStrlen(c_utf8);
5252 clipboard_filtered.resize(clipboard_filtered.Size + out_len);
5253 memcpy(clipboard_filtered.Data + clipboard_filtered.Size - out_len, c_utf8, out_len);
5254 }
5255 if (clipboard_filtered.Size > 0) // If everything was filtered, ignore the pasting operation
5256 {
5257 clipboard_filtered.push_back(0);
5258 stb_textedit_paste(state, state->Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1);
5259 state->CursorFollow = true;
5260 }
5261 }
5262 }
5263
5264 // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
5265 render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
5266 }
5267
5268 // Process callbacks and apply result back to user's buffer.
5269 const char* apply_new_text = NULL;
5270 int apply_new_text_length = 0;
5271 if (g.ActiveId == id)
5272 {
5273 IM_ASSERT(state != NULL);
5274 if (revert_edit && !is_readonly)
5275 {
5276 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
5277 {
5278 // Clear input
5279 IM_ASSERT(buf[0] != 0);
5280 apply_new_text = "";
5281 apply_new_text_length = 0;
5282 value_changed = true;
5283 IMSTB_TEXTEDIT_CHARTYPE empty_string;
5284 stb_textedit_replace(state, state->Stb, &empty_string, 0);
5285 }
5286 else if (strcmp(buf, state->TextToRevertTo.Data) != 0)
5287 {
5288 apply_new_text = state->TextToRevertTo.Data;
5289 apply_new_text_length = state->TextToRevertTo.Size - 1;
5290
5291 // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
5292 // Push records into the undo stack so we can CTRL+Z the revert operation itself
5293 value_changed = true;
5294 stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1);
5295 }
5296 }
5297
5298 // FIXME-OPT: We always reapply the live buffer back to the input buffer before clearing ActiveId,
5299 // even though strictly speaking it wasn't modified on this frame. Should mark dirty state from the stb_textedit callbacks.
5300 // If we do that, need to ensure that as special case, 'validated == true' also writes back.
5301 // This also allows the user to use InputText() without maintaining any user-side storage.
5302 // (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object
5303 // unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).
5304 const bool apply_edit_back_to_user_buffer = true;// !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
5305 if (apply_edit_back_to_user_buffer)
5306 {
5307 // Apply current edited text immediately.
5308 // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
5309
5310 // User callback
5311 if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0)
5312 {
5313 IM_ASSERT(callback != NULL);
5314
5315 // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
5316 ImGuiInputTextFlags event_flag = 0;
5317 ImGuiKey event_key = ImGuiKey_None;
5318 if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && Shortcut(ImGuiKey_Tab, 0, id))
5319 {
5320 event_flag = ImGuiInputTextFlags_CallbackCompletion;
5321 event_key = ImGuiKey_Tab;
5322 }
5323 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow))
5324 {
5325 event_flag = ImGuiInputTextFlags_CallbackHistory;
5326 event_key = ImGuiKey_UpArrow;
5327 }
5328 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow))
5329 {
5330 event_flag = ImGuiInputTextFlags_CallbackHistory;
5331 event_key = ImGuiKey_DownArrow;
5332 }
5333 else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited)
5334 {
5335 event_flag = ImGuiInputTextFlags_CallbackEdit;
5336 }
5337 else if (flags & ImGuiInputTextFlags_CallbackAlways)
5338 {
5339 event_flag = ImGuiInputTextFlags_CallbackAlways;
5340 }
5341
5342 if (event_flag)
5343 {
5344 ImGuiInputTextCallbackData callback_data;
5345 callback_data.Ctx = &g;
5346 callback_data.EventFlag = event_flag;
5347 callback_data.Flags = flags;
5348 callback_data.UserData = callback_user_data;
5349
5350 // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
5351 char* callback_buf = is_readonly ? buf : state->TextA.Data;
5352 IM_ASSERT(callback_buf == state->TextSrc);
5353 state->CallbackTextBackup.resize(state->TextLen + 1);
5354 memcpy(state->CallbackTextBackup.Data, callback_buf, state->TextLen + 1);
5355
5356 callback_data.EventKey = event_key;
5357 callback_data.Buf = callback_buf;
5358 callback_data.BufTextLen = state->TextLen;
5359 callback_data.BufSize = state->BufCapacity;
5360 callback_data.BufDirty = false;
5361
5362 const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
5363 const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start;
5364 const int utf8_selection_end = callback_data.SelectionEnd = state->Stb->select_end;
5365
5366 // Call user code
5367 callback(&callback_data);
5368
5369 // Read back what user may have modified
5370 callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback
5371 IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields
5372 IM_ASSERT(callback_data.BufSize == state->BufCapacity);
5373 IM_ASSERT(callback_data.Flags == flags);
5374 const bool buf_dirty = callback_data.BufDirty;
5375 if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
5376 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; }
5377 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; }
5378 if (buf_dirty)
5379 {
5380 // Callback may update buffer and thus set buf_dirty even in read-only mode.
5381 IM_ASSERT(callback_data.BufTextLen == (int)ImStrlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
5382 InputTextReconcileUndoState(state, state->CallbackTextBackup.Data, state->CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen);
5383 state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
5384 state->CursorAnimReset();
5385 }
5386 }
5387 }
5388
5389 // Will copy result string if modified
5390 if (!is_readonly && strcmp(state->TextSrc, buf) != 0)
5391 {
5392 apply_new_text = state->TextSrc;
5393 apply_new_text_length = state->TextLen;
5394 value_changed = true;
5395 }
5396 }
5397 }
5398
5399 // Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details)
5400 if (g.InputTextDeactivatedState.ID == id)
5401 {
5402 if (g.ActiveId != id && IsItemDeactivatedAfterEdit() && !is_readonly && strcmp(g.InputTextDeactivatedState.TextA.Data, buf) != 0)
5403 {
5404 apply_new_text = g.InputTextDeactivatedState.TextA.Data;
5405 apply_new_text_length = g.InputTextDeactivatedState.TextA.Size - 1;
5406 value_changed = true;
5407 //IMGUI_DEBUG_LOG("InputText(): apply Deactivated data for 0x%08X: \"%.*s\".\n", id, apply_new_text_length, apply_new_text);
5408 }
5409 g.InputTextDeactivatedState.ID = 0;
5410 }
5411
5412 // Copy result to user buffer. This can currently only happen when (g.ActiveId == id)
5413 if (apply_new_text != NULL)
5414 {
5415 //// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
5416 //// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
5417 //// without any storage on user's side.
5418 IM_ASSERT(apply_new_text_length >= 0);
5419 if (is_resizable)
5420 {
5421 ImGuiInputTextCallbackData callback_data;
5422 callback_data.Ctx = &g;
5423 callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
5424 callback_data.Flags = flags;
5425 callback_data.Buf = buf;
5426 callback_data.BufTextLen = apply_new_text_length;
5427 callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
5428 callback_data.UserData = callback_user_data;
5429 callback(&callback_data);
5430 buf = callback_data.Buf;
5431 buf_size = callback_data.BufSize;
5432 apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
5433 IM_ASSERT(apply_new_text_length <= buf_size);
5434 }
5435 //IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length);
5436
5437 // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
5438 ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
5439 }
5440
5441 // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
5442 // Otherwise request text input ahead for next frame.
5443 if (g.ActiveId == id && clear_active_id)
5444 ClearActiveID();
5445
5446 // Render frame
5447 if (!is_multiline)
5448 {
5449 RenderNavCursor(frame_bb, id);
5450 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
5451 }
5452
5453 const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size
5454 ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
5455 ImVec2 text_size(0.0f, 0.0f);
5456
5457 // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
5458 // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
5459 // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
5460 const int buf_display_max_length = 2 * 1024 * 1024;
5461 const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
5462 const char* buf_display_end = NULL; // We have specialized paths below for setting the length
5463
5464 // Display hint when contents is empty
5465 // At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368)
5466 const bool new_is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
5467 if (new_is_displaying_hint != is_displaying_hint)
5468 {
5469 if (is_password && !is_displaying_hint)
5470 PopPasswordFont();
5471 is_displaying_hint = new_is_displaying_hint;
5472 if (is_password && !is_displaying_hint)
5473 PushPasswordFont();
5474 }
5475 if (is_displaying_hint)
5476 {
5477 buf_display = hint;
5478 buf_display_end = hint + ImStrlen(hint);
5479 }
5480
5481 // Render text. We currently only render selection when the widget is active or while scrolling.
5482 // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
5483 if (render_cursor || render_selection)
5484 {
5485 IM_ASSERT(state != NULL);
5486 if (!is_displaying_hint)
5487 buf_display_end = buf_display + state->TextLen;
5488
5489 // Render text (with cursor and selection)
5490 // This is going to be messy. We need to:
5491 // - Display the text (this alone can be more easily clipped)
5492 // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
5493 // - Measure text height (for scrollbar)
5494 // 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)
5495 // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
5496 const char* text_begin = buf_display;
5497 const char* text_end = text_begin + state->TextLen;
5498 ImVec2 cursor_offset, select_start_offset;
5499
5500 {
5501 // Find lines numbers straddling cursor and selection min position
5502 int cursor_line_no = render_cursor ? -1 : -1000;
5503 int selmin_line_no = render_selection ? -1 : -1000;
5504 const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL;
5505 const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL;
5506
5507 // Count lines and find line number for cursor and selection ends
5508 int line_count = 1;
5509 if (is_multiline)
5510 {
5511 for (const char* s = text_begin; (s = (const char*)ImMemchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
5512 {
5513 if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; }
5514 if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; }
5515 line_count++;
5516 }
5517 }
5518 if (cursor_line_no == -1)
5519 cursor_line_no = line_count;
5520 if (selmin_line_no == -1)
5521 selmin_line_no = line_count;
5522
5523 // Calculate 2d position by finding the beginning of the line and measuring distance
5524 cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr).x;
5525 cursor_offset.y = cursor_line_no * g.FontSize;
5526 if (selmin_line_no >= 0)
5527 {
5528 select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr).x;
5529 select_start_offset.y = selmin_line_no * g.FontSize;
5530 }
5531
5532 // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
5533 if (is_multiline)
5534 text_size = ImVec2(inner_size.x, line_count * g.FontSize);
5535 }
5536
5537 // Scroll
5538 if (render_cursor && state->CursorFollow)
5539 {
5540 // Horizontal scroll in chunks of quarter width
5541 if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
5542 {
5543 const float scroll_increment_x = inner_size.x * 0.25f;
5544 const float visible_width = inner_size.x - style.FramePadding.x;
5545 if (cursor_offset.x < state->Scroll.x)
5546 state->Scroll.x = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x));
5547 else if (cursor_offset.x - visible_width >= state->Scroll.x)
5548 state->Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x);
5549 }
5550 else
5551 {
5552 state->Scroll.y = 0.0f;
5553 }
5554
5555 // Vertical scroll
5556 if (is_multiline)
5557 {
5558 // Test if cursor is vertically visible
5559 if (cursor_offset.y - g.FontSize < scroll_y)
5560 scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
5561 else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y)
5562 scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;
5563 const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);
5564 scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y);
5565 draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
5566 draw_window->Scroll.y = scroll_y;
5567 }
5568
5569 state->CursorFollow = false;
5570 }
5571
5572 // Draw selection
5573 const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f);
5574 if (render_selection)
5575 {
5576 const char* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
5577 const char* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end);
5578
5579 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.
5580 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.
5581 float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
5582 ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
5583 for (const char* p = text_selected_begin; p < text_selected_end; )
5584 {
5585 if (rect_pos.y > clip_rect.w + g.FontSize)
5586 break;
5587 if (rect_pos.y < clip_rect.y)
5588 {
5589 p = (const char*)ImMemchr((void*)p, '\n', text_selected_end - p);
5590 p = p ? p + 1 : text_selected_end;
5591 }
5592 else
5593 {
5594 ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true);
5595 if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.FontBaked->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
5596 ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));
5597 rect.ClipWith(clip_rect);
5598 if (rect.Overlaps(clip_rect))
5599 draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
5600 rect_pos.x = draw_pos.x - draw_scroll.x;
5601 }
5602 rect_pos.y += g.FontSize;
5603 }
5604 }
5605
5606 // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
5607 // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it.
5608 if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
5609 {
5610 ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
5611 draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
5612 }
5613
5614 // Draw blinking cursor
5615 if (render_cursor)
5616 {
5617 state->CursorAnim += io.DeltaTime;
5618 bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
5619 ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll);
5620 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);
5621 if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
5622 draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_InputTextCursor), 1.0f); // FIXME-DPI: Cursor thickness (#7031)
5623
5624 // 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.)
5625 // This is required for some backends (SDL3) to start emitting character/text inputs.
5626 // As per #6341, make sure we don't set that on the deactivating frame.
5627 if (!is_readonly && g.ActiveId == id)
5628 {
5629 ImGuiPlatformImeData* ime_data = &g.PlatformImeData; // (this is a public struct, passed to io.Platform_SetImeDataFn() handler)
5630 ime_data->WantVisible = true;
5631 ime_data->WantTextInput = true;
5632 ime_data->InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
5633 ime_data->InputLineHeight = g.FontSize;
5634 ime_data->ViewportId = window->Viewport->ID;
5635 }
5636 }
5637 }
5638 else
5639 {
5640 // Render text only (no selection, no cursor)
5641 if (is_multiline)
5642 text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
5643 else if (!is_displaying_hint && g.ActiveId == id)
5644 buf_display_end = buf_display + state->TextLen;
5645 else if (!is_displaying_hint)
5646 buf_display_end = buf_display + ImStrlen(buf_display);
5647
5648 if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
5649 {
5650 // Find render position for right alignment
5651 if (flags & ImGuiInputTextFlags_ElideLeft)
5652 draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x);
5653
5654 const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive?
5655 ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
5656 draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
5657 }
5658 }
5659
5660 if (is_password && !is_displaying_hint)
5661 PopPasswordFont();
5662
5663 if (is_multiline)
5664 {
5665 // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)...
5666 Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y));
5667 g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop;
5668 EndChild();
5669 item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow);
5670
5671 // ...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...
5672 // FIXME: This quite messy/tricky, should attempt to get rid of the child window.
5673 EndGroup();
5674 if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y))
5675 {
5676 g.LastItemData.ID = id;
5677 g.LastItemData.ItemFlags = item_data_backup.ItemFlags;
5678 g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
5679 }
5680 }
5681 if (state)
5682 state->TextSrc = NULL;
5683
5684 // Log as text
5685 if (g.LogEnabled && (!is_password || is_displaying_hint))
5686 {
5687 LogSetNextTextDecoration("{", "}");
5688 LogRenderedText(&draw_pos, buf_display, buf_display_end);
5689 }
5690
5691 if (label_size.x > 0)
5692 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
5693
5694 if (value_changed)
5695 MarkItemEdited(id);
5696
5697 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
5698 if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
5699 return validated;
5700 else
5701 return value_changed;
5702 }
5703
5704 void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
5705 {
5706 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5707 ImGuiContext& g = *GImGui;
5708 ImStb::STB_TexteditState* stb_state = state->Stb;
5709 ImStb::StbUndoState* undo_state = &stb_state->undostate;
5710 Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
5711 DebugLocateItemOnHover(state->ID);
5712 Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end);
5713 Text("BufCapacity: %d", state->BufCapacity);
5714 Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
5715 Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
5716 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);
5717 if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state
5718 {
5719 PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
5720 for (int n = 0; n < IMSTB_TEXTEDIT_UNDOSTATECOUNT; n++)
5721 {
5722 ImStb::StbUndoRecord* undo_rec = &undo_state->undo_rec[n];
5723 const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' ';
5724 if (undo_rec_type == ' ')
5725 BeginDisabled();
5726 const int buf_preview_len = (undo_rec_type != ' ' && undo_rec->char_storage != -1) ? undo_rec->insert_length : 0;
5727 const char* buf_preview_str = undo_state->undo_char + undo_rec->char_storage;
5728 Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"",
5729 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);
5730 if (undo_rec_type == ' ')
5731 EndDisabled();
5732 }
5733 PopStyleVar();
5734 }
5735 EndChild();
5736 #else
5737 IM_UNUSED(state);
5738 #endif
5739 }
5740
5741 //-------------------------------------------------------------------------
5742 // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
5743 //-------------------------------------------------------------------------
5744 // - ColorEdit3()
5745 // - ColorEdit4()
5746 // - ColorPicker3()
5747 // - RenderColorRectWithAlphaCheckerboard() [Internal]
5748 // - ColorPicker4()
5749 // - ColorButton()
5750 // - SetColorEditOptions()
5751 // - ColorTooltip() [Internal]
5752 // - ColorEditOptionsPopup() [Internal]
5753 // - ColorPickerOptionsPopup() [Internal]
5754 //-------------------------------------------------------------------------
5755
5756 bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
5757 {
5758 return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
5759 }
5760
5761 static void ColorEditRestoreH(const float* col, float* H)
5762 {
5763 ImGuiContext& g = *GImGui;
5764 IM_ASSERT(g.ColorEditCurrentID != 0);
5765 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5766 return;
5767 *H = g.ColorEditSavedHue;
5768 }
5769
5770 // ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation.
5771 // Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting.
5772 static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V)
5773 {
5774 ImGuiContext& g = *GImGui;
5775 IM_ASSERT(g.ColorEditCurrentID != 0);
5776 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5777 return;
5778
5779 // When S == 0, H is undefined.
5780 // When H == 1 it wraps around to 0.
5781 if (*S == 0.0f || (*H == 0.0f && g.ColorEditSavedHue == 1))
5782 *H = g.ColorEditSavedHue;
5783
5784 // When V == 0, S is undefined.
5785 if (*V == 0.0f)
5786 *S = g.ColorEditSavedSat;
5787 }
5788
5789 // Edit colors components (each component in 0.0f..1.0f range).
5790 // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
5791 // 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.
5792 bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
5793 {
5794 ImGuiWindow* window = GetCurrentWindow();
5795 if (window->SkipItems)
5796 return false;
5797
5798 ImGuiContext& g = *GImGui;
5799 const ImGuiStyle& style = g.Style;
5800 const float square_sz = GetFrameHeight();
5801 const char* label_display_end = FindRenderedTextEnd(label);
5802 float w_full = CalcItemWidth();
5803 g.NextItemData.ClearFlags();
5804
5805 BeginGroup();
5806 PushID(label);
5807 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
5808 if (set_current_color_edit_id)
5809 g.ColorEditCurrentID = window->IDStack.back();
5810
5811 // If we're not showing any slider there's no point in doing any HSV conversions
5812 const ImGuiColorEditFlags flags_untouched = flags;
5813 if (flags & ImGuiColorEditFlags_NoInputs)
5814 flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
5815
5816 // Context menu: display and modify options (before defaults are applied)
5817 if (!(flags & ImGuiColorEditFlags_NoOptions))
5818 ColorEditOptionsPopup(col, flags);
5819
5820 // Read stored options
5821 if (!(flags & ImGuiColorEditFlags_DisplayMask_))
5822 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_);
5823 if (!(flags & ImGuiColorEditFlags_DataTypeMask_))
5824 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_);
5825 if (!(flags & ImGuiColorEditFlags_PickerMask_))
5826 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_);
5827 if (!(flags & ImGuiColorEditFlags_InputMask_))
5828 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_);
5829 flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_));
5830 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected
5831 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
5832
5833 const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
5834 const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
5835 const int components = alpha ? 4 : 3;
5836 const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
5837 const float w_inputs = ImMax(w_full - w_button, 1.0f);
5838 w_full = w_inputs + w_button;
5839
5840 // Convert to the formats we need
5841 float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
5842 if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
5843 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5844 else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
5845 {
5846 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
5847 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5848 ColorEditRestoreHS(col, &f[0], &f[1], &f[2]);
5849 }
5850 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]) };
5851
5852 bool value_changed = false;
5853 bool value_changed_as_float = false;
5854
5855 const ImVec2 pos = window->DC.CursorPos;
5856 const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;
5857 window->DC.CursorPos.x = pos.x + inputs_offset_x;
5858
5859 if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5860 {
5861 // RGB/HSV 0..255 Sliders
5862 const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1);
5863
5864 const bool hide_prefix = (IM_TRUNC(w_items / components) <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
5865 static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
5866 static const char* fmt_table_int[3][4] =
5867 {
5868 { "%3d", "%3d", "%3d", "%3d" }, // Short display
5869 { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
5870 { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
5871 };
5872 static const char* fmt_table_float[3][4] =
5873 {
5874 { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
5875 { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
5876 { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
5877 };
5878 const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
5879
5880 float prev_split = 0.0f;
5881 for (int n = 0; n < components; n++)
5882 {
5883 if (n > 0)
5884 SameLine(0, style.ItemInnerSpacing.x);
5885 float next_split = IM_TRUNC(w_items * (n + 1) / components);
5886 SetNextItemWidth(ImMax(next_split - prev_split, 1.0f));
5887 prev_split = next_split;
5888
5889 // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0.
5890 if (flags & ImGuiColorEditFlags_Float)
5891 {
5892 value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
5893 value_changed_as_float |= value_changed;
5894 }
5895 else
5896 {
5897 value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
5898 }
5899 if (!(flags & ImGuiColorEditFlags_NoOptions))
5900 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5901 }
5902 }
5903 else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5904 {
5905 // RGB Hexadecimal Input
5906 char buf[64];
5907 if (alpha)
5908 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));
5909 else
5910 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255));
5911 SetNextItemWidth(w_inputs);
5912 if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsUppercase))
5913 {
5914 value_changed = true;
5915 char* p = buf;
5916 while (*p == '#' || ImCharIsBlankA(*p))
5917 p++;
5918 i[0] = i[1] = i[2] = 0;
5919 i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha)
5920 int r;
5921 if (alpha)
5922 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)
5923 else
5924 r = sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
5925 IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'.
5926 }
5927 if (!(flags & ImGuiColorEditFlags_NoOptions))
5928 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5929 }
5930
5931 ImGuiWindow* picker_active_window = NULL;
5932 if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
5933 {
5934 const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;
5935 window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);
5936
5937 const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
5938 if (ColorButton("##ColorButton", col_v4, flags))
5939 {
5940 if (!(flags & ImGuiColorEditFlags_NoPicker))
5941 {
5942 // Store current color and open a picker
5943 g.ColorPickerRef = col_v4;
5944 OpenPopup("picker");
5945 SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y));
5946 }
5947 }
5948 if (!(flags & ImGuiColorEditFlags_NoOptions))
5949 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5950
5951 if (BeginPopup("picker"))
5952 {
5953 if (g.CurrentWindow->BeginCount == 1)
5954 {
5955 picker_active_window = g.CurrentWindow;
5956 if (label != label_display_end)
5957 {
5958 TextEx(label, label_display_end);
5959 Spacing();
5960 }
5961 ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
5962 ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
5963 SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
5964 value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
5965 }
5966 EndPopup();
5967 }
5968 }
5969
5970 if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
5971 {
5972 // Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left),
5973 // but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this.
5974 SameLine(0.0f, style.ItemInnerSpacing.x);
5975 window->DC.CursorPos.x = pos.x + ((flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x);
5976 TextEx(label, label_display_end);
5977 }
5978
5979 // Convert back
5980 if (value_changed && picker_active_window == NULL)
5981 {
5982 if (!value_changed_as_float)
5983 for (int n = 0; n < 4; n++)
5984 f[n] = i[n] / 255.0f;
5985 if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
5986 {
5987 g.ColorEditSavedHue = f[0];
5988 g.ColorEditSavedSat = f[1];
5989 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5990 g.ColorEditSavedID = g.ColorEditCurrentID;
5991 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0));
5992 }
5993 if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
5994 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5995
5996 col[0] = f[0];
5997 col[1] = f[1];
5998 col[2] = f[2];
5999 if (alpha)
6000 col[3] = f[3];
6001 }
6002
6003 if (set_current_color_edit_id)
6004 g.ColorEditCurrentID = 0;
6005 PopID();
6006 EndGroup();
6007
6008 // Drag and Drop Target
6009 // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
6010 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
6011 {
6012 bool accepted_drag_drop = false;
6013 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
6014 {
6015 memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 //-V1086
6016 value_changed = accepted_drag_drop = true;
6017 }
6018 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
6019 {
6020 memcpy((float*)col, payload->Data, sizeof(float) * components);
6021 value_changed = accepted_drag_drop = true;
6022 }
6023
6024 // Drag-drop payloads are always RGB
6025 if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
6026 ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
6027 EndDragDropTarget();
6028 }
6029
6030 // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
6031 if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
6032 g.LastItemData.ID = g.ActiveId;
6033
6034 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
6035 MarkItemEdited(g.LastItemData.ID);
6036
6037 return value_changed;
6038 }
6039
6040 bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
6041 {
6042 float col4[4] = { col[0], col[1], col[2], 1.0f };
6043 if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
6044 return false;
6045 col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
6046 return true;
6047 }
6048
6049 // Helper for ColorPicker4()
6050 static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha)
6051 {
6052 ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha);
6053 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));
6054 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8));
6055 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));
6056 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8));
6057 }
6058
6059 // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
6060 // (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.)
6061 // 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..)
6062 // 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)
6063 bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
6064 {
6065 ImGuiContext& g = *GImGui;
6066 ImGuiWindow* window = GetCurrentWindow();
6067 if (window->SkipItems)
6068 return false;
6069
6070 ImDrawList* draw_list = window->DrawList;
6071 ImGuiStyle& style = g.Style;
6072 ImGuiIO& io = g.IO;
6073
6074 const float width = CalcItemWidth();
6075 const bool is_readonly = ((g.NextItemData.ItemFlags | g.CurrentItemFlags) & ImGuiItemFlags_ReadOnly) != 0;
6076 g.NextItemData.ClearFlags();
6077
6078 PushID(label);
6079 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
6080 if (set_current_color_edit_id)
6081 g.ColorEditCurrentID = window->IDStack.back();
6082 BeginGroup();
6083
6084 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
6085 flags |= ImGuiColorEditFlags_NoSmallPreview;
6086
6087 // Context menu: display and store options.
6088 if (!(flags & ImGuiColorEditFlags_NoOptions))
6089 ColorPickerOptionsPopup(col, flags);
6090
6091 // Read stored options
6092 if (!(flags & ImGuiColorEditFlags_PickerMask_))
6093 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_;
6094 if (!(flags & ImGuiColorEditFlags_InputMask_))
6095 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_;
6096 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected
6097 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
6098 if (!(flags & ImGuiColorEditFlags_NoOptions))
6099 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
6100
6101 // Setup
6102 int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
6103 bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
6104 ImVec2 picker_pos = window->DC.CursorPos;
6105 float square_sz = GetFrameHeight();
6106 float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
6107 float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
6108 float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
6109 float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
6110 float bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20f);
6111
6112 float backup_initial_col[4];
6113 memcpy(backup_initial_col, col, components * sizeof(float));
6114
6115 float wheel_thickness = sv_picker_size * 0.08f;
6116 float wheel_r_outer = sv_picker_size * 0.50f;
6117 float wheel_r_inner = wheel_r_outer - wheel_thickness;
6118 ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f);
6119
6120 // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
6121 float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
6122 ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
6123 ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
6124 ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
6125
6126 float H = col[0], S = col[1], V = col[2];
6127 float R = col[0], G = col[1], B = col[2];
6128 if (flags & ImGuiColorEditFlags_InputRGB)
6129 {
6130 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
6131 ColorConvertRGBtoHSV(R, G, B, H, S, V);
6132 ColorEditRestoreHS(col, &H, &S, &V);
6133 }
6134 else if (flags & ImGuiColorEditFlags_InputHSV)
6135 {
6136 ColorConvertHSVtoRGB(H, S, V, R, G, B);
6137 }
6138
6139 bool value_changed = false, value_changed_h = false, value_changed_sv = false;
6140
6141 PushItemFlag(ImGuiItemFlags_NoNav, true);
6142 if (flags & ImGuiColorEditFlags_PickerHueWheel)
6143 {
6144 // Hue wheel + SV triangle logic
6145 InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
6146 if (IsItemActive() && !is_readonly)
6147 {
6148 ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
6149 ImVec2 current_off = g.IO.MousePos - wheel_center;
6150 float initial_dist2 = ImLengthSqr(initial_off);
6151 if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1))
6152 {
6153 // Interactive with Hue wheel
6154 H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f;
6155 if (H < 0.0f)
6156 H += 1.0f;
6157 value_changed = value_changed_h = true;
6158 }
6159 float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
6160 float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
6161 if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
6162 {
6163 // Interacting with SV triangle
6164 ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
6165 if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
6166 current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
6167 float uu, vv, ww;
6168 ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
6169 V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
6170 S = ImClamp(uu / V, 0.0001f, 1.0f);
6171 value_changed = value_changed_sv = true;
6172 }
6173 }
6174 if (!(flags & ImGuiColorEditFlags_NoOptions))
6175 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
6176 }
6177 else if (flags & ImGuiColorEditFlags_PickerHueBar)
6178 {
6179 // SV rectangle logic
6180 InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
6181 if (IsItemActive() && !is_readonly)
6182 {
6183 S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1));
6184 V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6185 ColorEditRestoreH(col, &H); // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square.
6186 value_changed = value_changed_sv = true;
6187 }
6188 if (!(flags & ImGuiColorEditFlags_NoOptions))
6189 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
6190
6191 // Hue bar logic
6192 SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
6193 InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
6194 if (IsItemActive() && !is_readonly)
6195 {
6196 H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6197 value_changed = value_changed_h = true;
6198 }
6199 }
6200
6201 // Alpha bar logic
6202 if (alpha_bar)
6203 {
6204 SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
6205 InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
6206 if (IsItemActive())
6207 {
6208 col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
6209 value_changed = true;
6210 }
6211 }
6212 PopItemFlag(); // ImGuiItemFlags_NoNav
6213
6214 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
6215 {
6216 SameLine(0, style.ItemInnerSpacing.x);
6217 BeginGroup();
6218 }
6219
6220 if (!(flags & ImGuiColorEditFlags_NoLabel))
6221 {
6222 const char* label_display_end = FindRenderedTextEnd(label);
6223 if (label != label_display_end)
6224 {
6225 if ((flags & ImGuiColorEditFlags_NoSidePreview))
6226 SameLine(0, style.ItemInnerSpacing.x);
6227 TextEx(label, label_display_end);
6228 }
6229 }
6230
6231 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
6232 {
6233 PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
6234 ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6235 if ((flags & ImGuiColorEditFlags_NoLabel))
6236 Text("Current");
6237
6238 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoTooltip;
6239 ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
6240 if (ref_col != NULL)
6241 {
6242 Text("Original");
6243 ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
6244 if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
6245 {
6246 memcpy(col, ref_col, components * sizeof(float));
6247 value_changed = true;
6248 }
6249 }
6250 PopItemFlag();
6251 EndGroup();
6252 }
6253
6254 // Convert back color to RGB
6255 if (value_changed_h || value_changed_sv)
6256 {
6257 if (flags & ImGuiColorEditFlags_InputRGB)
6258 {
6259 ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]);
6260 g.ColorEditSavedHue = H;
6261 g.ColorEditSavedSat = S;
6262 g.ColorEditSavedID = g.ColorEditCurrentID;
6263 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0));
6264 }
6265 else if (flags & ImGuiColorEditFlags_InputHSV)
6266 {
6267 col[0] = H;
6268 col[1] = S;
6269 col[2] = V;
6270 }
6271 }
6272
6273 // R,G,B and H,S,V slider color editor
6274 bool value_changed_fix_hue_wrap = false;
6275 if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
6276 {
6277 PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
6278 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaMask_ | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview;
6279 ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
6280 if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6281 if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
6282 {
6283 // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
6284 // 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)
6285 value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
6286 value_changed = true;
6287 }
6288 if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6289 value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
6290 if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6291 value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
6292 PopItemWidth();
6293 }
6294
6295 // Try to cancel hue wrap (after ColorEdit4 call), if any
6296 if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
6297 {
6298 float new_H, new_S, new_V;
6299 ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
6300 if (new_H <= 0 && H > 0)
6301 {
6302 if (new_V <= 0 && V != new_V)
6303 ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
6304 else if (new_S <= 0)
6305 ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
6306 }
6307 }
6308
6309 if (value_changed)
6310 {
6311 if (flags & ImGuiColorEditFlags_InputRGB)
6312 {
6313 R = col[0];
6314 G = col[1];
6315 B = col[2];
6316 ColorConvertRGBtoHSV(R, G, B, H, S, V);
6317 ColorEditRestoreHS(col, &H, &S, &V); // Fix local Hue as display below will use it immediately.
6318 }
6319 else if (flags & ImGuiColorEditFlags_InputHSV)
6320 {
6321 H = col[0];
6322 S = col[1];
6323 V = col[2];
6324 ColorConvertHSVtoRGB(H, S, V, R, G, B);
6325 }
6326 }
6327
6328 const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha);
6329 const ImU32 col_black = IM_COL32(0,0,0,style_alpha8);
6330 const ImU32 col_white = IM_COL32(255,255,255,style_alpha8);
6331 const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8);
6332 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) };
6333
6334 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);
6335 ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
6336 ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!!
6337
6338 ImVec2 sv_cursor_pos;
6339
6340 if (flags & ImGuiColorEditFlags_PickerHueWheel)
6341 {
6342 // Render Hue Wheel
6343 const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
6344 const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
6345 for (int n = 0; n < 6; n++)
6346 {
6347 const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
6348 const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
6349 const int vert_start_idx = draw_list->VtxBuffer.Size;
6350 draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
6351 draw_list->PathStroke(col_white, 0, wheel_thickness);
6352 const int vert_end_idx = draw_list->VtxBuffer.Size;
6353
6354 // Paint colors over existing vertices
6355 ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
6356 ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
6357 ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]);
6358 }
6359
6360 // Render Cursor + preview on Hue Wheel
6361 float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
6362 float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
6363 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);
6364 float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
6365 int hue_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(hue_cursor_rad); // Lock segment count so the +1 one matches others.
6366 draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
6367 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments);
6368 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments);
6369
6370 // Render SV triangle (rotated according to hue)
6371 ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
6372 ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
6373 ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
6374 ImVec2 uv_white = GetFontTexUvWhitePixel();
6375 draw_list->PrimReserve(3, 3);
6376 draw_list->PrimVtx(tra, uv_white, hue_color32);
6377 draw_list->PrimVtx(trb, uv_white, col_black);
6378 draw_list->PrimVtx(trc, uv_white, col_white);
6379 draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f);
6380 sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
6381 }
6382 else if (flags & ImGuiColorEditFlags_PickerHueBar)
6383 {
6384 // Render SV Square
6385 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white);
6386 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black);
6387 RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);
6388 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
6389 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);
6390
6391 // Render Hue Bar
6392 for (int i = 0; i < 6; ++i)
6393 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]);
6394 float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size);
6395 RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
6396 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);
6397 }
6398
6399 // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
6400 float sv_cursor_rad = value_changed_sv ? wheel_thickness * 0.55f : wheel_thickness * 0.40f;
6401 int sv_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(sv_cursor_rad); // Lock segment count so the +1 one matches others.
6402 draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments);
6403 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments);
6404 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments);
6405
6406 // Render alpha bar
6407 if (alpha_bar)
6408 {
6409 float alpha = ImSaturate(col[3]);
6410 ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
6411 RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
6412 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);
6413 float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size);
6414 RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
6415 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);
6416 }
6417
6418 EndGroup();
6419
6420 if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
6421 value_changed = false;
6422 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
6423 MarkItemEdited(g.LastItemData.ID);
6424
6425 if (set_current_color_edit_id)
6426 g.ColorEditCurrentID = 0;
6427 PopID();
6428
6429 return value_changed;
6430 }
6431
6432 // A little color square. Return true when clicked.
6433 // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
6434 // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
6435 // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
6436 bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg)
6437 {
6438 ImGuiWindow* window = GetCurrentWindow();
6439 if (window->SkipItems)
6440 return false;
6441
6442 ImGuiContext& g = *GImGui;
6443 const ImGuiID id = window->GetID(desc_id);
6444 const float default_size = GetFrameHeight();
6445 const ImVec2 size(size_arg.x == 0.0f ? default_size : size_arg.x, size_arg.y == 0.0f ? default_size : size_arg.y);
6446 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
6447 ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
6448 if (!ItemAdd(bb, id))
6449 return false;
6450
6451 bool hovered, held;
6452 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
6453
6454 if (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaOpaque))
6455 flags &= ~(ImGuiColorEditFlags_AlphaNoBg | ImGuiColorEditFlags_AlphaPreviewHalf);
6456
6457 ImVec4 col_rgb = col;
6458 if (flags & ImGuiColorEditFlags_InputHSV)
6459 ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
6460
6461 ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
6462 float grid_step = ImMin(size.x, size.y) / 2.99f;
6463 float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
6464 ImRect bb_inner = bb;
6465 float off = 0.0f;
6466 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6467 {
6468 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.
6469 bb_inner.Expand(off);
6470 }
6471 if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
6472 {
6473 float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);
6474 if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
6475 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);
6476 else
6477 window->DrawList->AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight);
6478 window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft);
6479 }
6480 else
6481 {
6482 // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
6483 ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaOpaque) ? col_rgb_without_alpha : col_rgb;
6484 if (col_source.w < 1.0f && (flags & ImGuiColorEditFlags_AlphaNoBg) == 0)
6485 RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
6486 else
6487 window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);
6488 }
6489 RenderNavCursor(bb, id);
6490 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6491 {
6492 if (g.Style.FrameBorderSize > 0.0f)
6493 RenderFrameBorder(bb.Min, bb.Max, rounding);
6494 else
6495 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color buttons are often in need of some sort of border // FIXME-DPI
6496 }
6497
6498 // Drag and Drop Source
6499 // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
6500 if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
6501 {
6502 if (flags & ImGuiColorEditFlags_NoAlpha)
6503 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
6504 else
6505 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
6506 ColorButton(desc_id, col, flags);
6507 SameLine();
6508 TextEx("Color");
6509 EndDragDropSource();
6510 }
6511
6512 // Tooltip
6513 if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip))
6514 ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_));
6515
6516 return pressed;
6517 }
6518
6519 // Initialize/override default color options
6520 void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
6521 {
6522 ImGuiContext& g = *GImGui;
6523 if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6524 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_;
6525 if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0)
6526 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_;
6527 if ((flags & ImGuiColorEditFlags_PickerMask_) == 0)
6528 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_;
6529 if ((flags & ImGuiColorEditFlags_InputMask_) == 0)
6530 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_;
6531 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected
6532 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_)); // Check only 1 option is selected
6533 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check only 1 option is selected
6534 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check only 1 option is selected
6535 g.ColorEditOptions = flags;
6536 }
6537
6538 // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
6539 void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
6540 {
6541 ImGuiContext& g = *GImGui;
6542
6543 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
6544 return;
6545 const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
6546 if (text_end > text)
6547 {
6548 TextEx(text, text_end);
6549 Separator();
6550 }
6551
6552 ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
6553 ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6554 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]);
6555 ImGuiColorEditFlags flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_AlphaMask_;
6556 ColorButton("##preview", cf, (flags & flags_to_forward) | ImGuiColorEditFlags_NoTooltip, sz);
6557 SameLine();
6558 if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_))
6559 {
6560 if (flags & ImGuiColorEditFlags_NoAlpha)
6561 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]);
6562 else
6563 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]);
6564 }
6565 else if (flags & ImGuiColorEditFlags_InputHSV)
6566 {
6567 if (flags & ImGuiColorEditFlags_NoAlpha)
6568 Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
6569 else
6570 Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
6571 }
6572 EndTooltip();
6573 }
6574
6575 void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
6576 {
6577 bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_);
6578 bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_);
6579 if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
6580 return;
6581
6582 ImGuiContext& g = *GImGui;
6583 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6584 ImGuiColorEditFlags opts = g.ColorEditOptions;
6585 if (allow_opt_inputs)
6586 {
6587 if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB;
6588 if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV;
6589 if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex;
6590 }
6591 if (allow_opt_datatype)
6592 {
6593 if (allow_opt_inputs) Separator();
6594 if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8;
6595 if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float;
6596 }
6597
6598 if (allow_opt_inputs || allow_opt_datatype)
6599 Separator();
6600 if (Button("Copy as..", ImVec2(-1, 0)))
6601 OpenPopup("Copy");
6602 if (BeginPopup("Copy"))
6603 {
6604 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]);
6605 char buf[64];
6606 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6607 if (Selectable(buf))
6608 SetClipboardText(buf);
6609 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
6610 if (Selectable(buf))
6611 SetClipboardText(buf);
6612 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb);
6613 if (Selectable(buf))
6614 SetClipboardText(buf);
6615 if (!(flags & ImGuiColorEditFlags_NoAlpha))
6616 {
6617 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca);
6618 if (Selectable(buf))
6619 SetClipboardText(buf);
6620 }
6621 EndPopup();
6622 }
6623
6624 g.ColorEditOptions = opts;
6625 PopItemFlag();
6626 EndPopup();
6627 }
6628
6629 void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
6630 {
6631 bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_);
6632 bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
6633 if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
6634 return;
6635
6636 ImGuiContext& g = *GImGui;
6637 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6638 if (allow_opt_picker)
6639 {
6640 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
6641 PushItemWidth(picker_size.x);
6642 for (int picker_type = 0; picker_type < 2; picker_type++)
6643 {
6644 // Draw small/thumbnail version of each picker type (over an invisible button for selection)
6645 if (picker_type > 0) Separator();
6646 PushID(picker_type);
6647 ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha);
6648 if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
6649 if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
6650 ImVec2 backup_pos = GetCursorScreenPos();
6651 if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
6652 g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_);
6653 SetCursorScreenPos(backup_pos);
6654 ImVec4 previewing_ref_col;
6655 memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
6656 ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags);
6657 PopID();
6658 }
6659 PopItemWidth();
6660 }
6661 if (allow_opt_alpha_bar)
6662 {
6663 if (allow_opt_picker) Separator();
6664 CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
6665 }
6666 PopItemFlag();
6667 EndPopup();
6668 }
6669
6670 //-------------------------------------------------------------------------
6671 // [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
6672 //-------------------------------------------------------------------------
6673 // - TreeNode()
6674 // - TreeNodeV()
6675 // - TreeNodeEx()
6676 // - TreeNodeExV()
6677 // - TreeNodeStoreStackData() [Internal]
6678 // - TreeNodeBehavior() [Internal]
6679 // - TreePush()
6680 // - TreePop()
6681 // - GetTreeNodeToLabelSpacing()
6682 // - SetNextItemOpen()
6683 // - CollapsingHeader()
6684 //-------------------------------------------------------------------------
6685
6686 bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
6687 {
6688 va_list args;
6689 va_start(args, fmt);
6690 bool is_open = TreeNodeExV(str_id, 0, fmt, args);
6691 va_end(args);
6692 return is_open;
6693 }
6694
6695 bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
6696 {
6697 va_list args;
6698 va_start(args, fmt);
6699 bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
6700 va_end(args);
6701 return is_open;
6702 }
6703
6704 bool ImGui::TreeNode(const char* label)
6705 {
6706 ImGuiWindow* window = GetCurrentWindow();
6707 if (window->SkipItems)
6708 return false;
6709 ImGuiID id = window->GetID(label);
6710 return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL);
6711 }
6712
6713 bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
6714 {
6715 return TreeNodeExV(str_id, 0, fmt, args);
6716 }
6717
6718 bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
6719 {
6720 return TreeNodeExV(ptr_id, 0, fmt, args);
6721 }
6722
6723 bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
6724 {
6725 ImGuiWindow* window = GetCurrentWindow();
6726 if (window->SkipItems)
6727 return false;
6728 ImGuiID id = window->GetID(label);
6729 return TreeNodeBehavior(id, flags, label, NULL);
6730 }
6731
6732 bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6733 {
6734 va_list args;
6735 va_start(args, fmt);
6736 bool is_open = TreeNodeExV(str_id, flags, fmt, args);
6737 va_end(args);
6738 return is_open;
6739 }
6740
6741 bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6742 {
6743 va_list args;
6744 va_start(args, fmt);
6745 bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
6746 va_end(args);
6747 return is_open;
6748 }
6749
6750 bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6751 {
6752 ImGuiWindow* window = GetCurrentWindow();
6753 if (window->SkipItems)
6754 return false;
6755
6756 ImGuiID id = window->GetID(str_id);
6757 const char* label, *label_end;
6758 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6759 return TreeNodeBehavior(id, flags, label, label_end);
6760 }
6761
6762 bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6763 {
6764 ImGuiWindow* window = GetCurrentWindow();
6765 if (window->SkipItems)
6766 return false;
6767
6768 ImGuiID id = window->GetID(ptr_id);
6769 const char* label, *label_end;
6770 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6771 return TreeNodeBehavior(id, flags, label, label_end);
6772 }
6773
6774 bool ImGui::TreeNodeGetOpen(ImGuiID storage_id)
6775 {
6776 ImGuiContext& g = *GImGui;
6777 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6778 return storage->GetInt(storage_id, 0) != 0;
6779 }
6780
6781 void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open)
6782 {
6783 ImGuiContext& g = *GImGui;
6784 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6785 storage->SetInt(storage_id, open ? 1 : 0);
6786 }
6787
6788 bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags)
6789 {
6790 if (flags & ImGuiTreeNodeFlags_Leaf)
6791 return true;
6792
6793 // We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function
6794 ImGuiContext& g = *GImGui;
6795 ImGuiWindow* window = g.CurrentWindow;
6796 ImGuiStorage* storage = window->DC.StateStorage;
6797
6798 bool is_open;
6799 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasOpen)
6800 {
6801 if (g.NextItemData.OpenCond & ImGuiCond_Always)
6802 {
6803 is_open = g.NextItemData.OpenVal;
6804 TreeNodeSetOpen(storage_id, is_open);
6805 }
6806 else
6807 {
6808 // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
6809 const int stored_value = storage->GetInt(storage_id, -1);
6810 if (stored_value == -1)
6811 {
6812 is_open = g.NextItemData.OpenVal;
6813 TreeNodeSetOpen(storage_id, is_open);
6814 }
6815 else
6816 {
6817 is_open = stored_value != 0;
6818 }
6819 }
6820 }
6821 else
6822 {
6823 is_open = storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
6824 }
6825
6826 // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
6827 // NB- If we are above max depth we still allow manually opened nodes to be logged.
6828 if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
6829 is_open = true;
6830
6831 return is_open;
6832 }
6833
6834 // Store ImGuiTreeNodeStackData for just submitted node.
6835 // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase.
6836 static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags, float x1)
6837 {
6838 ImGuiContext& g = *GImGui;
6839 ImGuiWindow* window = g.CurrentWindow;
6840
6841 g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1);
6842 ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
6843 tree_node_data->ID = g.LastItemData.ID;
6844 tree_node_data->TreeFlags = flags;
6845 tree_node_data->ItemFlags = g.LastItemData.ItemFlags;
6846 tree_node_data->NavRect = g.LastItemData.NavRect;
6847
6848 // Initially I tried to latch value for GetColorU32(ImGuiCol_TreeLines) but it's not a good trade-off for very large trees.
6849 const bool draw_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) != 0;
6850 tree_node_data->DrawLinesX1 = draw_lines ? (x1 + g.FontSize * 0.5f + g.Style.FramePadding.x) : +FLT_MAX;
6851 tree_node_data->DrawLinesTableColumn = (draw_lines && g.CurrentTable) ? (ImGuiTableColumnIdx)g.CurrentTable->CurrentColumn : -1;
6852 tree_node_data->DrawLinesToNodesY2 = -FLT_MAX;
6853 window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
6854 if (flags & ImGuiTreeNodeFlags_DrawLinesToNodes)
6855 window->DC.TreeRecordsClippedNodesY2Mask |= (1 << window->DC.TreeDepth);
6856 }
6857
6858 // 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.
6859 bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
6860 {
6861 ImGuiWindow* window = GetCurrentWindow();
6862 if (window->SkipItems)
6863 return false;
6864
6865 ImGuiContext& g = *GImGui;
6866 const ImGuiStyle& style = g.Style;
6867 const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
6868 const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y));
6869
6870 if (!label_end)
6871 label_end = FindRenderedTextEnd(label);
6872 const ImVec2 label_size = CalcTextSize(label, label_end, false);
6873
6874 const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing
6875 const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
6876 const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow
6877
6878 // We vertically grow up to current line height up the typical widget height.
6879 const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
6880 const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL);
6881 const bool span_all_columns_label = (flags & ImGuiTreeNodeFlags_LabelSpanAllColumns) != 0 && (g.CurrentTable != NULL);
6882 ImRect frame_bb;
6883 frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;
6884 frame_bb.Min.y = window->DC.CursorPos.y;
6885 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;
6886 frame_bb.Max.y = window->DC.CursorPos.y + frame_height;
6887 if (display_frame)
6888 {
6889 const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits
6890 frame_bb.Min.x -= outer_extend;
6891 frame_bb.Max.x += outer_extend;
6892 }
6893
6894 ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y);
6895 ItemSize(ImVec2(text_width, frame_height), padding.y);
6896
6897 // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
6898 ImRect interact_bb = frame_bb;
6899 if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanLabelWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0)
6900 interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f);
6901
6902 // Compute open and multi-select states before ItemAdd() as it clear NextItem data.
6903 ImGuiID storage_id = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id;
6904 bool is_open = TreeNodeUpdateNextOpen(storage_id, flags);
6905
6906 bool is_visible;
6907 if (span_all_columns || span_all_columns_label)
6908 {
6909 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
6910 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
6911 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
6912 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
6913 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
6914 is_visible = ItemAdd(interact_bb, id);
6915 window->ClipRect.Min.x = backup_clip_rect_min_x;
6916 window->ClipRect.Max.x = backup_clip_rect_max_x;
6917 }
6918 else
6919 {
6920 is_visible = ItemAdd(interact_bb, id);
6921 }
6922 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
6923 g.LastItemData.DisplayRect = frame_bb;
6924
6925 // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsToParent enabled:
6926 // Store data for the current depth to allow returning to this node from any child item.
6927 // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
6928 // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsToParent by default or move it to ImGuiStyle.
6929 bool store_tree_node_stack_data = false;
6930 if ((flags & ImGuiTreeNodeFlags_DrawLinesMask_) == 0)
6931 flags |= g.Style.TreeLinesFlags;
6932 const bool draw_tree_lines = (flags & (ImGuiTreeNodeFlags_DrawLinesFull | ImGuiTreeNodeFlags_DrawLinesToNodes)) && (frame_bb.Min.y < window->ClipRect.Max.y) && (g.Style.TreeLinesSize > 0.0f);
6933 if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6934 {
6935 store_tree_node_stack_data = draw_tree_lines;
6936 if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsToParent) && !g.NavIdIsAlive)
6937 if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
6938 store_tree_node_stack_data = true;
6939 }
6940
6941 const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
6942 if (!is_visible)
6943 {
6944 if ((flags & ImGuiTreeNodeFlags_DrawLinesToNodes) && (window->DC.TreeRecordsClippedNodesY2Mask & (1 << (window->DC.TreeDepth - 1))))
6945 {
6946 ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
6947 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.
6948 if (frame_bb.Min.y >= window->ClipRect.Max.y)
6949 window->DC.TreeRecordsClippedNodesY2Mask &= ~(1 << (window->DC.TreeDepth - 1)); // Done
6950 }
6951 if (is_open && store_tree_node_stack_data)
6952 TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
6953 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6954 TreePushOverrideID(id);
6955 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
6956 return is_open;
6957 }
6958
6959 if (span_all_columns || span_all_columns_label)
6960 {
6961 TablePushBackgroundChannel();
6962 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
6963 g.LastItemData.ClipRect = window->ClipRect;
6964 }
6965
6966 ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;
6967 if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap))
6968 button_flags |= ImGuiButtonFlags_AllowOverlap;
6969 if (!is_leaf)
6970 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
6971
6972 // We allow clicking on the arrow section with keyboard modifiers held, in order to easily
6973 // allow browsing a tree while preserving selection with code implementing multi-selection patterns.
6974 // When clicking on the rest of the tree node we always disallow keyboard modifiers.
6975 const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x;
6976 const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;
6977 const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);
6978
6979 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
6980 if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default
6981 flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow;
6982
6983 // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags.
6984 // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support.
6985 // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0)
6986 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0)
6987 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1)
6988 // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1)
6989 // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0)
6990 // It is rather standard that arrow click react on Down rather than Up.
6991 // 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.
6992 if (is_mouse_x_over_arrow)
6993 button_flags |= ImGuiButtonFlags_PressedOnClick;
6994 else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
6995 button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
6996 else
6997 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
6998 if (flags & ImGuiTreeNodeFlags_NoNavFocus)
6999 button_flags |= ImGuiButtonFlags_NoNavFocus;
7000
7001 bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
7002 const bool was_selected = selected;
7003
7004 // Multi-selection support (header)
7005 if (is_multi_select)
7006 {
7007 // Handle multi-select + alter button flags for it
7008 MultiSelectItemHeader(id, &selected, &button_flags);
7009 if (is_mouse_x_over_arrow)
7010 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
7011 }
7012 else
7013 {
7014 if (window != g.HoveredWindow || !is_mouse_x_over_arrow)
7015 button_flags |= ImGuiButtonFlags_NoKeyModsAllowed;
7016 }
7017
7018 bool hovered, held;
7019 bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
7020 bool toggled = false;
7021 if (!is_leaf)
7022 {
7023 if (pressed && g.DragDropHoldJustPressedId != id)
7024 {
7025 if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select))
7026 toggled = true; // Single click
7027 if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
7028 toggled |= is_mouse_x_over_arrow && !g.NavHighlightItemUnderNav; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
7029 if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)
7030 toggled = true; // Double click
7031 }
7032 else if (pressed && g.DragDropHoldJustPressedId == id)
7033 {
7034 IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);
7035 if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
7036 toggled = true;
7037 else
7038 pressed = false; // Cancel press so it doesn't trigger selection.
7039 }
7040
7041 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)
7042 {
7043 toggled = true;
7044 NavClearPreferredPosForAxis(ImGuiAxis_X);
7045 NavMoveRequestCancel();
7046 }
7047 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?
7048 {
7049 toggled = true;
7050 NavClearPreferredPosForAxis(ImGuiAxis_X);
7051 NavMoveRequestCancel();
7052 }
7053
7054 if (toggled)
7055 {
7056 is_open = !is_open;
7057 window->DC.StateStorage->SetInt(storage_id, is_open);
7058 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;
7059 }
7060 }
7061
7062 // Multi-selection support (footer)
7063 if (is_multi_select)
7064 {
7065 bool pressed_copy = pressed && !toggled;
7066 MultiSelectItemFooter(id, &selected, &pressed_copy);
7067 if (pressed)
7068 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb);
7069 }
7070
7071 if (selected != was_selected)
7072 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
7073
7074 // Render
7075 {
7076 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
7077 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact;
7078 if (is_multi_select)
7079 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
7080 if (display_frame)
7081 {
7082 // Framed type
7083 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7084 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
7085 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
7086 if (span_all_columns && !span_all_columns_label)
7087 TablePopBackgroundChannel();
7088 if (flags & ImGuiTreeNodeFlags_Bullet)
7089 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
7090 else if (!is_leaf)
7091 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);
7092 else // Leaf without bullet, left-adjusted text
7093 text_pos.x -= text_offset_x - padding.x;
7094 if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)
7095 frame_bb.Max.x -= g.FontSize + style.FramePadding.x;
7096 if (g.LogEnabled)
7097 LogSetNextTextDecoration("###", "###");
7098 }
7099 else
7100 {
7101 // Unframed typed for tree nodes
7102 if (hovered || selected)
7103 {
7104 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7105 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
7106 }
7107 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
7108 if (span_all_columns && !span_all_columns_label)
7109 TablePopBackgroundChannel();
7110 if (flags & ImGuiTreeNodeFlags_Bullet)
7111 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);
7112 else if (!is_leaf)
7113 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);
7114 if (g.LogEnabled)
7115 LogSetNextTextDecoration(">", NULL);
7116 }
7117
7118 if (draw_tree_lines)
7119 TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5f));
7120
7121 // Label
7122 if (display_frame)
7123 RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
7124 else
7125 RenderText(text_pos, label, label_end, false);
7126
7127 if (span_all_columns_label)
7128 TablePopBackgroundChannel();
7129 }
7130
7131 if (is_open && store_tree_node_stack_data)
7132 TreeNodeStoreStackData(flags, text_pos.x - text_offset_x); // Call before TreePushOverrideID()
7133 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
7134 TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice
7135
7136 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
7137 return is_open;
7138 }
7139
7140 // Draw horizontal line from our parent node
7141 // This is only called for visible child nodes so we are not too fussy anymore about performances
7142 void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos)
7143 {
7144 ImGuiContext& g = *GImGui;
7145 ImGuiWindow* window = g.CurrentWindow;
7146 if (window->DC.TreeDepth == 0 || (window->DC.TreeHasStackDataDepthMask & (1 << (window->DC.TreeDepth - 1))) == 0)
7147 return;
7148
7149 ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
7150 float x1 = ImTrunc(parent_data->DrawLinesX1);
7151 float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x);
7152 float y = ImTrunc(target_pos.y);
7153 float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f;
7154 parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding);
7155 if (x1 >= x2)
7156 return;
7157 if (rounding > 0.0f)
7158 {
7159 x1 += 0.5f + rounding;
7160 window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3);
7161 if (x1 < x2)
7162 window->DrawList->PathLineTo(ImVec2(x2, y));
7163 window->DrawList->PathStroke(GetColorU32(ImGuiCol_TreeLines), ImDrawFlags_None, g.Style.TreeLinesSize);
7164 }
7165 else
7166 {
7167 window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
7168 }
7169 }
7170
7171 // Draw vertical line of the hierarchy
7172 void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data)
7173 {
7174 ImGuiContext& g = *GImGui;
7175 ImGuiWindow* window = g.CurrentWindow;
7176 float y1 = ImMax(data->NavRect.Max.y, window->ClipRect.Min.y);
7177 float y2 = data->DrawLinesToNodesY2;
7178 if (data->TreeFlags & ImGuiTreeNodeFlags_DrawLinesFull)
7179 {
7180 float y2_full = window->DC.CursorPos.y;
7181 if (g.CurrentTable)
7182 y2_full = ImMax(g.CurrentTable->RowPosY2, y2_full);
7183 y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5f);
7184 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
7185 y2 = y2_full;
7186 }
7187 y2 = ImMin(y2, window->ClipRect.Max.y);
7188 if (y2 <= y1)
7189 return;
7190 float x = ImTrunc(data->DrawLinesX1);
7191 if (data->DrawLinesTableColumn != -1)
7192 TablePushColumnChannel(data->DrawLinesTableColumn);
7193 window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize);
7194 if (data->DrawLinesTableColumn != -1)
7195 TablePopColumnChannel();
7196 }
7197
7198 void ImGui::TreePush(const char* str_id)
7199 {
7200 ImGuiWindow* window = GetCurrentWindow();
7201 Indent();
7202 window->DC.TreeDepth++;
7203 PushID(str_id);
7204 }
7205
7206 void ImGui::TreePush(const void* ptr_id)
7207 {
7208 ImGuiWindow* window = GetCurrentWindow();
7209 Indent();
7210 window->DC.TreeDepth++;
7211 PushID(ptr_id);
7212 }
7213
7214 void ImGui::TreePushOverrideID(ImGuiID id)
7215 {
7216 ImGuiContext& g = *GImGui;
7217 ImGuiWindow* window = g.CurrentWindow;
7218 Indent();
7219 window->DC.TreeDepth++;
7220 PushOverrideID(id);
7221 }
7222
7223 void ImGui::TreePop()
7224 {
7225 ImGuiContext& g = *GImGui;
7226 ImGuiWindow* window = g.CurrentWindow;
7227 Unindent();
7228
7229 window->DC.TreeDepth--;
7230 ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);
7231
7232 if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask)
7233 {
7234 const ImGuiTreeNodeStackData* data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1];
7235 IM_ASSERT(data->ID == window->IDStack.back());
7236
7237 // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsToParent is enabled)
7238 if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsToParent)
7239 if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
7240 NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data);
7241
7242 // Draw hierarchy lines
7243 if (data->DrawLinesX1 != +FLT_MAX && window->DC.CursorPos.y >= window->ClipRect.Min.y)
7244 TreeNodeDrawLineToTreePop(data);
7245
7246 g.TreeNodeStack.pop_back();
7247 window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask;
7248 window->DC.TreeRecordsClippedNodesY2Mask &= ~tree_depth_mask;
7249 }
7250
7251 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.
7252 PopID();
7253 }
7254
7255 // Horizontal distance preceding label when using TreeNode() or Bullet()
7256 float ImGui::GetTreeNodeToLabelSpacing()
7257 {
7258 ImGuiContext& g = *GImGui;
7259 return g.FontSize + (g.Style.FramePadding.x * 2.0f);
7260 }
7261
7262 // Set next TreeNode/CollapsingHeader open state.
7263 void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
7264 {
7265 ImGuiContext& g = *GImGui;
7266 if (g.CurrentWindow->SkipItems)
7267 return;
7268 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasOpen;
7269 g.NextItemData.OpenVal = is_open;
7270 g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always);
7271 }
7272
7273 // Set next TreeNode/CollapsingHeader storage id.
7274 void ImGui::SetNextItemStorageID(ImGuiID storage_id)
7275 {
7276 ImGuiContext& g = *GImGui;
7277 if (g.CurrentWindow->SkipItems)
7278 return;
7279 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasStorageID;
7280 g.NextItemData.StorageId = storage_id;
7281 }
7282
7283 // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
7284 // 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().
7285 bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
7286 {
7287 ImGuiWindow* window = GetCurrentWindow();
7288 if (window->SkipItems)
7289 return false;
7290 ImGuiID id = window->GetID(label);
7291 return TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
7292 }
7293
7294 // p_visible == NULL : regular collapsing header
7295 // 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
7296 // p_visible != NULL && *p_visible == false : do not show the header at all
7297 // Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen.
7298 bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags)
7299 {
7300 ImGuiWindow* window = GetCurrentWindow();
7301 if (window->SkipItems)
7302 return false;
7303
7304 if (p_visible && !*p_visible)
7305 return false;
7306
7307 ImGuiID id = window->GetID(label);
7308 flags |= ImGuiTreeNodeFlags_CollapsingHeader;
7309 if (p_visible)
7310 flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton;
7311 bool is_open = TreeNodeBehavior(id, flags, label);
7312 if (p_visible != NULL)
7313 {
7314 // Create a small overlapping close button
7315 // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
7316 // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.
7317 ImGuiContext& g = *GImGui;
7318 ImGuiLastItemData last_item_backup = g.LastItemData;
7319 float button_size = g.FontSize;
7320 float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x - button_size);
7321 float button_y = g.LastItemData.Rect.Min.y + g.Style.FramePadding.y;
7322 ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id);
7323 if (CloseButton(close_button_id, ImVec2(button_x, button_y)))
7324 *p_visible = false;
7325 g.LastItemData = last_item_backup;
7326 }
7327
7328 return is_open;
7329 }
7330
7331 //-------------------------------------------------------------------------
7332 // [SECTION] Widgets: Selectable
7333 //-------------------------------------------------------------------------
7334 // - Selectable()
7335 //-------------------------------------------------------------------------
7336
7337 // Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image.
7338 // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
7339 // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags.
7340 // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.
7341 bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
7342 {
7343 ImGuiWindow* window = GetCurrentWindow();
7344 if (window->SkipItems)
7345 return false;
7346
7347 ImGuiContext& g = *GImGui;
7348 const ImGuiStyle& style = g.Style;
7349
7350 // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.
7351 ImGuiID id = window->GetID(label);
7352 ImVec2 label_size;
7353
7354 if(flags & ImGuiSelectableFlags_NoHashTextHide)
7355 {
7356 label_size = CalcTextSize(label, NULL, false);
7357 }
7358 else
7359 {
7360 label_size = CalcTextSize(label, NULL, true);
7361 }
7362
7363 ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
7364 ImVec2 pos = window->DC.CursorPos;
7365 pos.y += window->DC.CurrLineTextBaseOffset;
7366 ItemSize(size, 0.0f);
7367
7368 // Fill horizontal space
7369 // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets.
7370 const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0;
7371 const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x;
7372 const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x;
7373 if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))
7374 size.x = ImMax(label_size.x, max_x - min_x);
7375
7376 // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
7377 // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
7378 ImRect bb(min_x, pos.y, min_x + size.x, pos.y + size.y);
7379 if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0)
7380 {
7381 const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x;
7382 const float spacing_y = style.ItemSpacing.y;
7383 const float spacing_L = IM_TRUNC(spacing_x * 0.50f);
7384 const float spacing_U = IM_TRUNC(spacing_y * 0.50f);
7385 bb.Min.x -= spacing_L;
7386 bb.Min.y -= spacing_U;
7387 bb.Max.x += (spacing_x - spacing_L);
7388 bb.Max.y += (spacing_y - spacing_U);
7389 }
7390 //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); }
7391
7392 const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0;
7393 const ImGuiItemFlags extra_item_flags = disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None;
7394 bool is_visible;
7395 if (span_all_columns)
7396 {
7397 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
7398 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
7399 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
7400 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
7401 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
7402 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
7403 window->ClipRect.Min.x = backup_clip_rect_min_x;
7404 window->ClipRect.Max.x = backup_clip_rect_max_x;
7405 }
7406 else
7407 {
7408 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
7409 }
7410
7411 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
7412 if (!is_visible)
7413 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)
7414 return false;
7415
7416 const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7417 if (disabled_item && !disabled_global) // Only testing this as an optimization
7418 BeginDisabled();
7419
7420 // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,
7421 // which would be advantageous since most selectable are not selected.
7422 if (span_all_columns)
7423 {
7424 if (g.CurrentTable)
7425 TablePushBackgroundChannel();
7426 else if (window->DC.CurrentColumns)
7427 PushColumnsBackground();
7428 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
7429 g.LastItemData.ClipRect = window->ClipRect;
7430 }
7431
7432 // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
7433 ImGuiButtonFlags button_flags = 0;
7434 if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }
7435 if (flags & ImGuiSelectableFlags_NoSetKeyOwner) { button_flags |= ImGuiButtonFlags_NoSetKeyOwner; }
7436 if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }
7437 if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }
7438 if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }
7439 if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; }
7440
7441 // Multi-selection support (header)
7442 const bool was_selected = selected;
7443 if (is_multi_select)
7444 {
7445 // Handle multi-select + alter button flags for it
7446 MultiSelectItemHeader(id, &selected, &button_flags);
7447 }
7448
7449 bool hovered, held;
7450 bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
7451
7452 // Multi-selection support (footer)
7453 if (is_multi_select)
7454 {
7455 MultiSelectItemFooter(id, &selected, &pressed);
7456 }
7457 else
7458 {
7459 // Auto-select when moved into
7460 // - This will be more fully fleshed in the range-select branch
7461 // - This is not exposed as it won't nicely work with some user side handling of shift/control
7462 // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons
7463 // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())
7464 // - (2) usage will fail with clipped items
7465 // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
7466 if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId)
7467 if (g.NavJustMovedToId == id)
7468 selected = pressed = true;
7469 }
7470
7471 // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
7472 if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
7473 {
7474 if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
7475 {
7476 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
7477 if (g.IO.ConfigNavCursorVisibleAuto)
7478 g.NavCursorVisible = false;
7479 }
7480 }
7481 if (pressed)
7482 MarkItemEdited(id);
7483
7484 if (selected != was_selected)
7485 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
7486
7487 // Render
7488 if (is_visible)
7489 {
7490 const bool highlighted = ((hovered && (held || !(g.IO.ConfigFlags&ImGuiConfigFlags_NoHoverColors))) || (flags & ImGuiSelectableFlags_Highlight));
7491 if ((highlighted || selected))
7492 {
7493 // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
7494 ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7495 RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
7496 }
7497 if (g.NavId == id)
7498 {
7499 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding;
7500 if (is_multi_select)
7501 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
7502 RenderNavCursor(bb, id, nav_render_cursor_flags);
7503 }
7504 }
7505
7506 if (span_all_columns)
7507 {
7508 if (g.CurrentTable)
7509 TablePopBackgroundChannel();
7510 else if (window->DC.CurrentColumns)
7511 PopColumnsBackground();
7512 }
7513
7514 // Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns.
7515 if (is_visible) {
7516 if(flags & ImGuiSelectableFlags_NoHashTextHide)
7517 {
7518 RenderTextClippedNoHashHide(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb);
7519 }
7520 else
7521 {
7522 RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window->WorkRect.Max.x), pos.y + size.y), label, NULL, &label_size, style.SelectableTextAlign, &bb);
7523 }
7524 }
7525
7526 // Automatically close popups
7527 if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
7528 CloseCurrentPopup();
7529
7530 if (disabled_item && !disabled_global)
7531 EndDisabled();
7532
7533 // Selectable() always returns a pressed state!
7534 // Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve
7535 // selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect().
7536 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
7537 return pressed; //-V1020
7538 }
7539
7540 bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
7541 {
7542 if (Selectable(label, *p_selected, flags, size_arg))
7543 {
7544 *p_selected = !*p_selected;
7545 return true;
7546 }
7547 return false;
7548 }
7549
7550
7551 //-------------------------------------------------------------------------
7552 // [SECTION] Widgets: Typing-Select support
7553 //-------------------------------------------------------------------------
7554
7555 // [Experimental] Currently not exposed in public API.
7556 // Consume character inputs and return search request, if any.
7557 // This would typically only be called on the focused window or location you want to grab inputs for, e.g.
7558 // if (ImGui::IsWindowFocused(...))
7559 // if (ImGuiTypingSelectRequest* req = ImGui::GetTypingSelectRequest())
7560 // focus_idx = ImGui::TypingSelectFindMatch(req, my_items.size(), [](void*, int n) { return my_items[n]->Name; }, &my_items, -1);
7561 // However the code is written in a way where calling it from multiple locations is safe (e.g. to obtain buffer).
7562 ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags flags)
7563 {
7564 ImGuiContext& g = *GImGui;
7565 ImGuiTypingSelectState* data = &g.TypingSelectState;
7566 ImGuiTypingSelectRequest* out_request = &data->Request;
7567
7568 // Clear buffer
7569 const float TYPING_SELECT_RESET_TIMER = 1.80f; // FIXME: Potentially move to IO config.
7570 const int TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK = 4; // Lock single char matching when repeating same char 4 times
7571 if (data->SearchBuffer[0] != 0)
7572 {
7573 bool clear_buffer = false;
7574 clear_buffer |= (g.NavFocusScopeId != data->FocusScope);
7575 clear_buffer |= (data->LastRequestTime + TYPING_SELECT_RESET_TIMER < g.Time);
7576 clear_buffer |= g.NavAnyRequest;
7577 clear_buffer |= g.ActiveId != 0 && g.NavActivateId == 0; // Allow temporary SPACE activation to not interfere
7578 clear_buffer |= IsKeyPressed(ImGuiKey_Escape) || IsKeyPressed(ImGuiKey_Enter);
7579 clear_buffer |= IsKeyPressed(ImGuiKey_Backspace) && (flags & ImGuiTypingSelectFlags_AllowBackspace) == 0;
7580 //if (clear_buffer) { IMGUI_DEBUG_LOG("GetTypingSelectRequest(): Clear SearchBuffer.\n"); }
7581 if (clear_buffer)
7582 data->Clear();
7583 }
7584
7585 // Append to buffer
7586 const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1;
7587 int buffer_len = (int)ImStrlen(data->SearchBuffer);
7588 bool select_request = false;
7589 for (ImWchar w : g.IO.InputQueueCharacters)
7590 {
7591 const int w_len = ImTextCountUtf8BytesFromStr(&w, &w + 1);
7592 if (w < 32 || (buffer_len == 0 && ImCharIsBlankW(w)) || (buffer_len + w_len > buffer_max_len)) // Ignore leading blanks
7593 continue;
7594 char w_buf[5];
7595 ImTextCharToUtf8(w_buf, (unsigned int)w);
7596 if (data->SingleCharModeLock && w_len == out_request->SingleCharSize && memcmp(w_buf, data->SearchBuffer, w_len) == 0)
7597 {
7598 select_request = true; // Same character: don't need to append to buffer.
7599 continue;
7600 }
7601 if (data->SingleCharModeLock)
7602 {
7603 data->Clear(); // Different character: clear
7604 buffer_len = 0;
7605 }
7606 memcpy(data->SearchBuffer + buffer_len, w_buf, w_len + 1); // Append
7607 buffer_len += w_len;
7608 select_request = true;
7609 }
7610 g.IO.InputQueueCharacters.resize(0);
7611
7612 // Handle backspace
7613 if ((flags & ImGuiTypingSelectFlags_AllowBackspace) && IsKeyPressed(ImGuiKey_Backspace, ImGuiInputFlags_Repeat))
7614 {
7615 char* p = (char*)(void*)ImTextFindPreviousUtf8Codepoint(data->SearchBuffer, data->SearchBuffer + buffer_len);
7616 *p = 0;
7617 buffer_len = (int)(p - data->SearchBuffer);
7618 }
7619
7620 // Return request if any
7621 if (buffer_len == 0)
7622 return NULL;
7623 if (select_request)
7624 {
7625 data->FocusScope = g.NavFocusScopeId;
7626 data->LastRequestFrame = g.FrameCount;
7627 data->LastRequestTime = (float)g.Time;
7628 }
7629 out_request->Flags = flags;
7630 out_request->SearchBufferLen = buffer_len;
7631 out_request->SearchBuffer = data->SearchBuffer;
7632 out_request->SelectRequest = (data->LastRequestFrame == g.FrameCount);
7633 out_request->SingleCharMode = false;
7634 out_request->SingleCharSize = 0;
7635
7636 // Calculate if buffer contains the same character repeated.
7637 // - This can be used to implement a special search mode on first character.
7638 // - Performed on UTF-8 codepoint for correctness.
7639 // - SingleCharMode is always set for first input character, because it usually leads to a "next".
7640 if (flags & ImGuiTypingSelectFlags_AllowSingleCharMode)
7641 {
7642 const char* buf_begin = out_request->SearchBuffer;
7643 const char* buf_end = out_request->SearchBuffer + out_request->SearchBufferLen;
7644 const int c0_len = ImTextCountUtf8BytesFromChar(buf_begin, buf_end);
7645 const char* p = buf_begin + c0_len;
7646 for (; p < buf_end; p += c0_len)
7647 if (memcmp(buf_begin, p, (size_t)c0_len) != 0)
7648 break;
7649 const int single_char_count = (p == buf_end) ? (out_request->SearchBufferLen / c0_len) : 0;
7650 out_request->SingleCharMode = (single_char_count > 0 || data->SingleCharModeLock);
7651 out_request->SingleCharSize = (ImS8)c0_len;
7652 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.
7653 }
7654
7655 return out_request;
7656 }
7657
7658 static int ImStrimatchlen(const char* s1, const char* s1_end, const char* s2)
7659 {
7660 int match_len = 0;
7661 while (s1 < s1_end && ImToUpper(*s1++) == ImToUpper(*s2++))
7662 match_len++;
7663 return match_len;
7664 }
7665
7666 // Default handler for finding a result for typing-select. You may implement your own.
7667 // You might want to display a tooltip to visualize the current request SearchBuffer
7668 // When SingleCharMode is set:
7669 // - it is better to NOT display a tooltip of other on-screen display indicator.
7670 // - the index of the currently focused item is required.
7671 // if your SetNextItemSelectionUserData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData.
7672 int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7673 {
7674 if (req == NULL || req->SelectRequest == false) // Support NULL parameter so both calls can be done from same spot.
7675 return -1;
7676 int idx = -1;
7677 if (req->SingleCharMode && (req->Flags & ImGuiTypingSelectFlags_AllowSingleCharMode))
7678 idx = TypingSelectFindNextSingleCharMatch(req, items_count, get_item_name_func, user_data, nav_item_idx);
7679 else
7680 idx = TypingSelectFindBestLeadingMatch(req, items_count, get_item_name_func, user_data);
7681 if (idx != -1)
7682 SetNavCursorVisibleAfterMove();
7683 return idx;
7684 }
7685
7686 // Special handling when a single character is repeated: perform search on a single letter and goes to next.
7687 int ImGui::TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7688 {
7689 // FIXME: Assume selection user data is index. Would be extremely practical.
7690 //if (nav_item_idx == -1)
7691 // nav_item_idx = (int)g.NavLastValidSelectionUserData;
7692
7693 int first_match_idx = -1;
7694 bool return_next_match = false;
7695 for (int idx = 0; idx < items_count; idx++)
7696 {
7697 const char* item_name = get_item_name_func(user_data, idx);
7698 if (ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SingleCharSize, item_name) < req->SingleCharSize)
7699 continue;
7700 if (return_next_match) // Return next matching item after current item.
7701 return idx;
7702 if (first_match_idx == -1 && nav_item_idx == -1) // Return first match immediately if we don't have a nav_item_idx value.
7703 return idx;
7704 if (first_match_idx == -1) // Record first match for wrapping.
7705 first_match_idx = idx;
7706 if (nav_item_idx == idx) // Record that we encountering nav_item so we can return next match.
7707 return_next_match = true;
7708 }
7709 return first_match_idx; // First result
7710 }
7711
7712 int ImGui::TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data)
7713 {
7714 int longest_match_idx = -1;
7715 int longest_match_len = 0;
7716 for (int idx = 0; idx < items_count; idx++)
7717 {
7718 const char* item_name = get_item_name_func(user_data, idx);
7719 const int match_len = ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SearchBufferLen, item_name);
7720 if (match_len <= longest_match_len)
7721 continue;
7722 longest_match_idx = idx;
7723 longest_match_len = match_len;
7724 if (match_len == req->SearchBufferLen)
7725 break;
7726 }
7727 return longest_match_idx;
7728 }
7729
7730 void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data)
7731 {
7732 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7733 Text("SearchBuffer = \"%s\"", data->SearchBuffer);
7734 Text("SingleCharMode = %d, Size = %d, Lock = %d", data->Request.SingleCharMode, data->Request.SingleCharSize, data->SingleCharModeLock);
7735 Text("LastRequest = time: %.2f, frame: %d", data->LastRequestTime, data->LastRequestFrame);
7736 #else
7737 IM_UNUSED(data);
7738 #endif
7739 }
7740
7741 //-------------------------------------------------------------------------
7742 // [SECTION] Widgets: Box-Select support
7743 // This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet.
7744 //-------------------------------------------------------------------------
7745 // Extra logic in MultiSelectItemFooter() and ImGuiListClipper::Step()
7746 //-------------------------------------------------------------------------
7747 // - BoxSelectPreStartDrag() [Internal]
7748 // - BoxSelectActivateDrag() [Internal]
7749 // - BoxSelectDeactivateDrag() [Internal]
7750 // - BoxSelectScrollWithMouseDrag() [Internal]
7751 // - BeginBoxSelect() [Internal]
7752 // - EndBoxSelect() [Internal]
7753 //-------------------------------------------------------------------------
7754
7755 // Call on the initial click.
7756 static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item)
7757 {
7758 ImGuiContext& g = *GImGui;
7759 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7760 bs->ID = id;
7761 bs->IsStarting = true; // Consider starting box-select.
7762 bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid);
7763 bs->IsStartedSetNavIdOnce = bs->IsStartedFromVoid;
7764 bs->KeyMods = g.IO.KeyMods;
7765 bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos);
7766 bs->ScrollAccum = ImVec2(0.0f, 0.0f);
7767 }
7768
7769 static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window)
7770 {
7771 ImGuiContext& g = *GImGui;
7772 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Activate\n", bs->ID);
7773 bs->IsActive = true;
7774 bs->Window = window;
7775 bs->IsStarting = false;
7776 ImGui::SetActiveID(bs->ID, window);
7777 ImGui::SetActiveIdUsingAllKeyboardKeys();
7778 if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0)
7779 bs->RequestClear = true;
7780 }
7781
7782 static void BoxSelectDeactivateDrag(ImGuiBoxSelectState* bs)
7783 {
7784 ImGuiContext& g = *GImGui;
7785 bs->IsActive = bs->IsStarting = false;
7786 if (g.ActiveId == bs->ID)
7787 {
7788 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Deactivate\n", bs->ID);
7789 ImGui::ClearActiveID();
7790 }
7791 bs->ID = 0;
7792 }
7793
7794 static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window, const ImRect& inner_r)
7795 {
7796 ImGuiContext& g = *GImGui;
7797 IM_ASSERT(bs->Window == window);
7798 for (int n = 0; n < 2; n++) // each axis
7799 {
7800 const float mouse_pos = g.IO.MousePos[n];
7801 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;
7802 const float scroll_curr = window->Scroll[n];
7803 if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n]))
7804 continue;
7805
7806 const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance
7807 const float scroll_step = g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime;
7808 bs->ScrollAccum[n] += scroll_step;
7809
7810 // Accumulate into a stored value so we can handle high-framerate
7811 const float scroll_step_i = ImFloor(bs->ScrollAccum[n]);
7812 if (scroll_step_i == 0.0f)
7813 continue;
7814 if (n == 0)
7815 ImGui::SetScrollX(window, scroll_curr + scroll_step_i);
7816 else
7817 ImGui::SetScrollY(window, scroll_curr + scroll_step_i);
7818 bs->ScrollAccum[n] -= scroll_step_i;
7819 }
7820 }
7821
7822 bool ImGui::BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags)
7823 {
7824 ImGuiContext& g = *GImGui;
7825 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7826 KeepAliveID(box_select_id);
7827 if (bs->ID != box_select_id)
7828 return false;
7829
7830 // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry.
7831 bs->UnclipMode = false;
7832 bs->RequestClear = false;
7833 if (bs->IsStarting && IsMouseDragPastThreshold(0))
7834 BoxSelectActivateDrag(bs, window);
7835 else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false)
7836 BoxSelectDeactivateDrag(bs);
7837 if (!bs->IsActive)
7838 return false;
7839
7840 // Current frame absolute prev/current rectangles are used to toggle selection.
7841 // They are derived from positions relative to scrolling space.
7842 ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel);
7843 ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already
7844 ImVec2 curr_end_pos_abs = g.IO.MousePos;
7845 if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow
7846 curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max);
7847 bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs);
7848 bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs);
7849 bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs);
7850 bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs);
7851
7852 // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper)
7853 // Storing an extra rect used by widgets supporting box-select.
7854 if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d)
7855 if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x)
7856 {
7857 bs->UnclipMode = true;
7858 bs->UnclipRect = bs->BoxSelectRectPrev; // FIXME-OPT: UnclipRect x coordinates could be intersection of Prev and Curr rect on X axis.
7859 bs->UnclipRect.Add(bs->BoxSelectRectCurr);
7860 }
7861
7862 //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7863 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectPrev.Min, bs->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7864 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectCurr.Min, bs->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f);
7865 return true;
7866 }
7867
7868 void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags)
7869 {
7870 ImGuiContext& g = *GImGui;
7871 ImGuiWindow* window = g.CurrentWindow;
7872 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7873 IM_ASSERT(bs->IsActive);
7874 bs->UnclipMode = false;
7875
7876 // Render selection rectangle
7877 bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view
7878 ImRect box_select_r = bs->BoxSelectRectCurr;
7879 box_select_r.ClipWith(scope_rect);
7880 window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling
7881 window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT FIXME-DPI: Styling
7882
7883 // Scroll
7884 const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0;
7885 if (enable_scroll)
7886 {
7887 ImRect scroll_r = scope_rect;
7888 scroll_r.Expand(-g.FontSize);
7889 //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255));
7890 if (!scroll_r.Contains(g.IO.MousePos))
7891 BoxSelectScrollWithMouseDrag(bs, window, scroll_r);
7892 }
7893 }
7894
7895 //-------------------------------------------------------------------------
7896 // [SECTION] Widgets: Multi-Select support
7897 //-------------------------------------------------------------------------
7898 // - DebugLogMultiSelectRequests() [Internal]
7899 // - CalcScopeRect() [Internal]
7900 // - BeginMultiSelect()
7901 // - EndMultiSelect()
7902 // - SetNextItemSelectionUserData()
7903 // - MultiSelectItemHeader() [Internal]
7904 // - MultiSelectItemFooter() [Internal]
7905 // - DebugNodeMultiSelectState() [Internal]
7906 //-------------------------------------------------------------------------
7907
7908 static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io)
7909 {
7910 ImGuiContext& g = *GImGui;
7911 IM_UNUSED(function);
7912 for (const ImGuiSelectionRequest& req : io->Requests)
7913 {
7914 if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear");
7915 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);
7916 }
7917 }
7918
7919 static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window)
7920 {
7921 ImGuiContext& g = *GImGui;
7922 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
7923 {
7924 // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only
7925 return ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin));
7926 }
7927 else
7928 {
7929 // When a table, pull HostClipRect, which allows us to predict ClipRect before first row/layout is performed. (#7970)
7930 ImRect scope_rect = window->InnerClipRect;
7931 if (g.CurrentTable != NULL)
7932 scope_rect = g.CurrentTable->HostClipRect;
7933
7934 // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect?
7935 scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max);
7936 return scope_rect;
7937 }
7938 }
7939
7940 // Return ImGuiMultiSelectIO structure.
7941 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
7942 // Passing 'selection_size' and 'items_count' parameters is currently optional.
7943 // - 'selection_size' is useful to disable some shortcut routing: e.g. ImGuiMultiSelectFlags_ClearOnEscape won't claim Escape key when selection_size 0,
7944 // allowing a first press to clear selection THEN the second press to leave child window and return to parent.
7945 // - '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).
7946 // - If they are costly for you to compute (e.g. external intrusive selection without maintaining size), you may avoid them and pass -1.
7947 // - 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.
7948 ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size, int items_count)
7949 {
7950 ImGuiContext& g = *GImGui;
7951 ImGuiWindow* window = g.CurrentWindow;
7952
7953 if (++g.MultiSelectTempDataStacked > g.MultiSelectTempData.Size)
7954 g.MultiSelectTempData.resize(g.MultiSelectTempDataStacked, ImGuiMultiSelectTempData());
7955 ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1];
7956 IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that.
7957 g.CurrentMultiSelect = ms;
7958 if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0)
7959 flags |= ImGuiMultiSelectFlags_ScopeWindow;
7960 if (flags & ImGuiMultiSelectFlags_SingleSelect)
7961 flags &= ~(ImGuiMultiSelectFlags_BoxSelect2d | ImGuiMultiSelectFlags_BoxSelect1d);
7962 if (flags & ImGuiMultiSelectFlags_BoxSelect2d)
7963 flags &= ~ImGuiMultiSelectFlags_BoxSelect1d;
7964
7965 // FIXME: Workaround to the fact we override CursorMaxPos, meaning size measurement are lost. (#8250)
7966 // They should perhaps be stacked properly?
7967 if (ImGuiTable* table = g.CurrentTable)
7968 if (table->CurrentColumn != -1)
7969 TableEndCell(table); // This is currently safe to call multiple time. If that properly is lost we can extract the "save measurement" part of it.
7970
7971 // FIXME: BeginFocusScope()
7972 const ImGuiID id = window->IDStack.back();
7973 ms->Clear();
7974 ms->FocusScopeId = id;
7975 ms->Flags = flags;
7976 ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId);
7977 ms->BackupCursorMaxPos = window->DC.CursorMaxPos;
7978 ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos;
7979 PushFocusScope(ms->FocusScopeId);
7980 if (flags & ImGuiMultiSelectFlags_ScopeWindow) // Mark parent child window as navigable into, with highlight. Assume user will always submit interactive items.
7981 window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main;
7982
7983 // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame.
7984 ms->KeyMods = g.NavJustMovedToId ? (g.NavJustMovedToIsTabbing ? 0 : g.NavJustMovedToKeyMods) : g.IO.KeyMods;
7985 if (flags & ImGuiMultiSelectFlags_NoRangeSelect)
7986 ms->KeyMods &= ~ImGuiMod_Shift;
7987
7988 // Bind storage
7989 ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id);
7990 storage->ID = id;
7991 storage->LastFrameActive = g.FrameCount;
7992 storage->LastSelectionSize = selection_size;
7993 storage->Window = window;
7994 ms->Storage = storage;
7995
7996 // Output to user
7997 ms->IO.Requests.resize(0);
7998 ms->IO.RangeSrcItem = storage->RangeSrcItem;
7999 ms->IO.NavIdItem = storage->NavIdItem;
8000 ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false;
8001 ms->IO.ItemsCount = items_count;
8002
8003 // Clear when using Navigation to move within the scope
8004 // (we compare FocusScopeId so it possible to use multiple selections inside a same window)
8005 bool request_clear = false;
8006 bool request_select_all = false;
8007 if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData)
8008 {
8009 if (ms->KeyMods & ImGuiMod_Shift)
8010 ms->IsKeyboardSetRange = true;
8011 if (ms->IsKeyboardSetRange)
8012 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear?
8013 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
8014 request_clear = true;
8015 }
8016 else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId)
8017 {
8018 // Also clear on leaving scope (may be optional?)
8019 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
8020 request_clear = true;
8021 }
8022
8023 // Box-select handling: update active state.
8024 ImGuiBoxSelectState* bs = &g.BoxSelectState;
8025 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
8026 {
8027 ms->BoxSelectId = GetID("##BoxSelect");
8028 if (BeginBoxSelect(CalcScopeRect(ms, window), window, ms->BoxSelectId, flags))
8029 request_clear |= bs->RequestClear;
8030 }
8031
8032 if (ms->IsFocused)
8033 {
8034 // Shortcut: Clear selection (Escape)
8035 // - Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window.
8036 // - Box select also handle Escape and needs to pass an id to bypass ActiveIdUsingAllKeyboardKeys lock.
8037 if (flags & ImGuiMultiSelectFlags_ClearOnEscape)
8038 {
8039 if (selection_size != 0 || bs->IsActive)
8040 if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_None, bs->IsActive ? bs->ID : 0))
8041 {
8042 request_clear = true;
8043 if (bs->IsActive)
8044 BoxSelectDeactivateDrag(bs);
8045 }
8046 }
8047
8048 // Shortcut: Select all (CTRL+A)
8049 if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll))
8050 if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A))
8051 request_select_all = true;
8052 }
8053
8054 if (request_clear || request_select_all)
8055 {
8056 MultiSelectAddSetAll(ms, request_select_all);
8057 if (!request_select_all)
8058 storage->LastSelectionSize = 0;
8059 }
8060 ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1;
8061 ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid;
8062
8063 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
8064 DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO);
8065
8066 return &ms->IO;
8067 }
8068
8069 // Return updated ImGuiMultiSelectIO structure.
8070 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
8071 ImGuiMultiSelectIO* ImGui::EndMultiSelect()
8072 {
8073 ImGuiContext& g = *GImGui;
8074 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
8075 ImGuiMultiSelectState* storage = ms->Storage;
8076 ImGuiWindow* window = g.CurrentWindow;
8077 IM_ASSERT_USER_ERROR(ms->FocusScopeId == g.CurrentFocusScopeId, "EndMultiSelect() FocusScope mismatch!");
8078 IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow);
8079 IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect);
8080
8081 ImRect scope_rect = CalcScopeRect(ms, window);
8082 if (ms->IsFocused)
8083 {
8084 // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here.
8085 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)
8086 {
8087 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId.
8088 storage->RangeSrcItem = ImGuiSelectionUserData_Invalid;
8089 }
8090 if (ms->NavIdPassedBy == false && storage->NavIdItem != ImGuiSelectionUserData_Invalid)
8091 {
8092 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n");
8093 storage->NavIdItem = ImGuiSelectionUserData_Invalid;
8094 storage->NavIdSelected = -1;
8095 }
8096
8097 if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId))
8098 EndBoxSelect(scope_rect, ms->Flags);
8099 }
8100
8101 if (ms->IsEndIO == false)
8102 ms->IO.Requests.resize(0);
8103
8104 // Clear selection when clicking void?
8105 // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection!
8106 // The InnerRect test is necessary for non-child/decorated windows.
8107 bool scope_hovered = IsWindowHovered() && window->InnerRect.Contains(g.IO.MousePos);
8108 if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect))
8109 scope_hovered &= scope_rect.Contains(g.IO.MousePos);
8110 if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0)
8111 {
8112 if (ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
8113 {
8114 if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1)
8115 {
8116 BoxSelectPreStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid);
8117 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
8118 SetHoveredID(ms->BoxSelectId);
8119 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
8120 SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from void to box-select.
8121 }
8122 }
8123
8124 if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid)
8125 if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None)
8126 MultiSelectAddSetAll(ms, false);
8127 }
8128
8129 // Courtesy nav wrapping helper flag
8130 if (ms->Flags & ImGuiMultiSelectFlags_NavWrapX)
8131 {
8132 IM_ASSERT(ms->Flags & ImGuiMultiSelectFlags_ScopeWindow); // Only supported at window scope
8133 ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX);
8134 }
8135
8136 // Unwind
8137 window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos);
8138 PopFocusScope();
8139
8140 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
8141 DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO);
8142
8143 ms->FocusScopeId = 0;
8144 ms->Flags = ImGuiMultiSelectFlags_None;
8145 g.CurrentMultiSelect = (--g.MultiSelectTempDataStacked > 0) ? &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] : NULL;
8146
8147 return &ms->IO;
8148 }
8149
8150 void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data)
8151 {
8152 // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code!
8153 // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api.
8154 ImGuiContext& g = *GImGui;
8155 g.NextItemData.SelectionUserData = selection_user_data;
8156 g.NextItemData.FocusScopeId = g.CurrentFocusScopeId;
8157
8158 if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect)
8159 {
8160 // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping)
8161 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect;
8162 if (ms->IO.RangeSrcItem == selection_user_data)
8163 ms->RangeSrcPassedBy = true;
8164 }
8165 else
8166 {
8167 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData;
8168 }
8169 }
8170
8171 // In charge of:
8172 // - Applying SetAll for submitted items.
8173 // - Applying SetRange for submitted items and record end points.
8174 // - Altering button behavior flags to facilitate use with drag and drop.
8175 void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags)
8176 {
8177 ImGuiContext& g = *GImGui;
8178 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
8179
8180 bool selected = *p_selected;
8181 if (ms->IsFocused)
8182 {
8183 ImGuiMultiSelectState* storage = ms->Storage;
8184 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
8185 IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope");
8186
8187 // Apply SetAll (Clear/SelectAll) requests requested by BeginMultiSelect().
8188 // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper.
8189 // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect()
8190 if (ms->LoopRequestSetAll != -1)
8191 selected = (ms->LoopRequestSetAll == 1);
8192
8193 // 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)
8194 // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function)
8195 if (ms->IsKeyboardSetRange)
8196 {
8197 IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0);
8198 const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped.
8199 if (is_range_dst)
8200 ms->RangeDstPassedBy = true;
8201 if (is_range_dst && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst
8202 {
8203 storage->RangeSrcItem = item_data;
8204 storage->RangeSelected = selected ? 1 : 0;
8205 }
8206 const bool is_range_src = storage->RangeSrcItem == item_data;
8207 if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy)
8208 {
8209 // Apply range-select value to visible items
8210 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1);
8211 selected = (storage->RangeSelected != 0);
8212 }
8213 else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0 && (ms->Flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
8214 {
8215 // Clear other items
8216 selected = false;
8217 }
8218 }
8219 *p_selected = selected;
8220 }
8221
8222 // Alter button behavior flags
8223 // To handle drag and drop of multiple items we need to avoid clearing selection on click.
8224 // 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.
8225 if (p_button_flags != NULL)
8226 {
8227 ImGuiButtonFlags button_flags = *p_button_flags;
8228 button_flags |= ImGuiButtonFlags_NoHoveredOnFocus;
8229 if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease))
8230 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
8231 else
8232 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
8233 *p_button_flags = button_flags;
8234 }
8235 }
8236
8237 // In charge of:
8238 // - Auto-select on navigation.
8239 // - Box-select toggle handling.
8240 // - Right-click handling.
8241 // - Altering selection based on Ctrl/Shift modifiers, both for keyboard and mouse.
8242 // - Record current selection state for RangeSrc
8243 // This is all rather complex, best to run and refer to "widgets_multiselect_xxx" tests in imgui_test_suite.
8244 void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed)
8245 {
8246 ImGuiContext& g = *GImGui;
8247 ImGuiWindow* window = g.CurrentWindow;
8248
8249 bool selected = *p_selected;
8250 bool pressed = *p_pressed;
8251 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
8252 ImGuiMultiSelectState* storage = ms->Storage;
8253 if (pressed)
8254 ms->IsFocused = true;
8255
8256 bool hovered = false;
8257 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)
8258 hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
8259 if (!ms->IsFocused && !hovered)
8260 return;
8261
8262 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
8263
8264 ImGuiMultiSelectFlags flags = ms->Flags;
8265 const bool is_singleselect = (flags & ImGuiMultiSelectFlags_SingleSelect) != 0;
8266 bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0;
8267 bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0;
8268
8269 bool apply_to_range_src = false;
8270
8271 if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
8272 apply_to_range_src = true;
8273 if (ms->IsEndIO == false)
8274 {
8275 ms->IO.Requests.resize(0);
8276 ms->IsEndIO = true;
8277 }
8278
8279 // Auto-select as you navigate a list
8280 if (g.NavJustMovedToId == id)
8281 {
8282 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8283 {
8284 if (is_ctrl && is_shift)
8285 pressed = true;
8286 else if (!is_ctrl)
8287 selected = pressed = true;
8288 }
8289 else
8290 {
8291 // With NoAutoSelect, using Shift+keyboard performs a write/copy
8292 if (is_shift)
8293 pressed = true;
8294 else if (!is_ctrl)
8295 apply_to_range_src = true; // Since if (pressed) {} main block is not running we update this
8296 }
8297 }
8298
8299 if (apply_to_range_src)
8300 {
8301 storage->RangeSrcItem = item_data;
8302 storage->RangeSelected = selected; // Will be updated at the end of this function anyway.
8303 }
8304
8305 // Box-select toggle handling
8306 if (ms->BoxSelectId != 0)
8307 if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId))
8308 {
8309 const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect);
8310 const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect);
8311 if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr))
8312 {
8313 if (storage->LastSelectionSize <= 0 && bs->IsStartedSetNavIdOnce)
8314 {
8315 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)
8316 bs->IsStartedSetNavIdOnce = false;
8317 }
8318 else
8319 {
8320 selected = !selected;
8321 MultiSelectAddSetRange(ms, selected, +1, item_data, item_data);
8322 }
8323 storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1);
8324 }
8325 }
8326
8327 // Right-click handling.
8328 // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816
8329 if (hovered && IsMouseClicked(1) && (flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8330 {
8331 if (g.ActiveId != 0 && g.ActiveId != id)
8332 ClearActiveID();
8333 SetFocusID(id, window);
8334 if (!pressed && !selected)
8335 {
8336 pressed = true;
8337 is_ctrl = is_shift = false;
8338 }
8339 }
8340
8341 // Unlike Space, Enter doesn't alter selection (but can still return a press) unless current item is not selected.
8342 // The later, "unless current item is not select", may become optional? It seems like a better default if Enter doesn't necessarily open something
8343 // (unlike e.g. Windows explorer). For use case where Enter always open something, we might decide to make this optional?
8344 const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput);
8345
8346 // Alter selection
8347 if (pressed && (!enter_pressed || !selected))
8348 {
8349 // Box-select
8350 ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
8351 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
8352 if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1)
8353 BoxSelectPreStartDrag(ms->BoxSelectId, item_data);
8354
8355 //----------------------------------------------------------------------------------------
8356 // ACTION | Begin | Pressed/Activated | End
8357 //----------------------------------------------------------------------------------------
8358 // Keys Navigated: | Clear | Src=item, Sel=1 SetRange 1
8359 // Keys Navigated: Ctrl | n/a | n/a
8360 // Keys Navigated: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
8361 // Keys Navigated: Ctrl+Shift | n/a | Dst=item, Sel=Src => Clear + SetRange Src-Dst
8362 // Keys Activated: | n/a | Src=item, Sel=1 => Clear + SetRange 1
8363 // Keys Activated: Ctrl | n/a | Src=item, Sel=!Sel => SetSange 1
8364 // Keys Activated: Shift | n/a | Dst=item, Sel=1 => Clear + SetSange 1
8365 //----------------------------------------------------------------------------------------
8366 // Mouse Pressed: | n/a | Src=item, Sel=1, => Clear + SetRange 1
8367 // Mouse Pressed: Ctrl | n/a | Src=item, Sel=!Sel => SetRange 1
8368 // Mouse Pressed: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
8369 // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst
8370 //----------------------------------------------------------------------------------------
8371
8372 if ((flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
8373 {
8374 bool request_clear = false;
8375 if (is_singleselect)
8376 request_clear = true;
8377 else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl)
8378 request_clear = (flags & ImGuiMultiSelectFlags_NoAutoClearOnReselect) ? !selected : true;
8379 else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl)
8380 request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again.
8381 if (request_clear)
8382 MultiSelectAddSetAll(ms, false);
8383 }
8384
8385 int range_direction;
8386 bool range_selected;
8387 if (is_shift && !is_singleselect)
8388 {
8389 //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue);
8390 if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
8391 storage->RangeSrcItem = item_data;
8392 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8393 {
8394 // Shift+Arrow always select
8395 // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected)
8396 range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
8397 }
8398 else
8399 {
8400 // Shift+Arrow copy source selection state
8401 // Shift+Click always copy from target selection state
8402 if (ms->IsKeyboardSetRange)
8403 range_selected = (storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
8404 else
8405 range_selected = !selected;
8406 }
8407 range_direction = ms->RangeSrcPassedBy ? +1 : -1;
8408 }
8409 else
8410 {
8411 // Ctrl inverts selection, otherwise always select
8412 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
8413 selected = is_ctrl ? !selected : true;
8414 else
8415 selected = !selected;
8416 storage->RangeSrcItem = item_data;
8417 range_selected = selected;
8418 range_direction = +1;
8419 }
8420 MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data);
8421 }
8422
8423 // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect)
8424 if (storage->RangeSrcItem == item_data)
8425 storage->RangeSelected = selected ? 1 : 0;
8426
8427 // Update/store the selection state of focused item
8428 if (g.NavId == id)
8429 {
8430 storage->NavIdItem = item_data;
8431 storage->NavIdSelected = selected ? 1 : 0;
8432 }
8433 if (storage->NavIdItem == item_data)
8434 ms->NavIdPassedBy = true;
8435 ms->LastSubmittedItem = item_data;
8436
8437 *p_selected = selected;
8438 *p_pressed = pressed;
8439 }
8440
8441 void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected)
8442 {
8443 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid };
8444 ms->IO.Requests.resize(0); // Can always clear previous requests
8445 ms->IO.Requests.push_back(req); // Add new request
8446 }
8447
8448 void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item)
8449 {
8450 // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges)
8451 if (ms->IO.Requests.Size > 0 && first_item == last_item && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0)
8452 {
8453 ImGuiSelectionRequest* prev = &ms->IO.Requests.Data[ms->IO.Requests.Size - 1];
8454 if (prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->LastSubmittedItem && prev->Selected == selected)
8455 {
8456 prev->RangeLastItem = last_item;
8457 return;
8458 }
8459 }
8460
8461 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item };
8462 ms->IO.Requests.push_back(req); // Add new request
8463 }
8464
8465 void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage)
8466 {
8467 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8468 const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
8469 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
8470 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*");
8471 if (!is_active) { PopStyleColor(); }
8472 if (!open)
8473 return;
8474 Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected);
8475 Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected);
8476 Text("LastSelectionSize = %d", storage->LastSelectionSize); // Provided by user
8477 TreePop();
8478 #else
8479 IM_UNUSED(storage);
8480 #endif
8481 }
8482
8483 //-------------------------------------------------------------------------
8484 // [SECTION] Widgets: Multi-Select helpers
8485 //-------------------------------------------------------------------------
8486 // - ImGuiSelectionBasicStorage
8487 // - ImGuiSelectionExternalStorage
8488 //-------------------------------------------------------------------------
8489
8490 ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage()
8491 {
8492 Size = 0;
8493 PreserveOrder = false;
8494 UserData = NULL;
8495 AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; };
8496 _SelectionOrder = 1; // Always >0
8497 }
8498
8499 void ImGuiSelectionBasicStorage::Clear()
8500 {
8501 Size = 0;
8502 _SelectionOrder = 1; // Always >0
8503 _Storage.Data.resize(0);
8504 }
8505
8506 void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r)
8507 {
8508 ImSwap(Size, r.Size);
8509 ImSwap(_SelectionOrder, r._SelectionOrder);
8510 _Storage.Data.swap(r._Storage.Data);
8511 }
8512
8513 bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const
8514 {
8515 return _Storage.GetInt(id, 0) != 0;
8516 }
8517
8518 static int IMGUI_CDECL PairComparerByValueInt(const void* lhs, const void* rhs)
8519 {
8520 int lhs_v = ((const ImGuiStoragePair*)lhs)->val_i;
8521 int rhs_v = ((const ImGuiStoragePair*)rhs)->val_i;
8522 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
8523 }
8524
8525 // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user.
8526 // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector<ImGuiID> instead of ImGuiStorage...)
8527 bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id)
8528 {
8529 ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it;
8530 ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size;
8531 if (PreserveOrder && it == NULL && it_end != NULL)
8532 ImQsort(_Storage.Data.Data, (size_t)_Storage.Data.Size, sizeof(ImGuiStoragePair), PairComparerByValueInt); // ~ImGuiStorage::BuildSortByValueInt()
8533 if (it == NULL)
8534 it = _Storage.Data.Data;
8535 IM_ASSERT(it >= _Storage.Data.Data && it <= it_end);
8536 if (it != it_end)
8537 while (it->val_i == 0 && it < it_end)
8538 it++;
8539 const bool has_more = (it != it_end);
8540 *opaque_it = has_more ? (void**)(it + 1) : (void**)(it);
8541 *out_id = has_more ? it->key : 0;
8542 if (PreserveOrder && !has_more)
8543 _Storage.BuildSortByKey();
8544 return has_more;
8545 }
8546
8547 void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected)
8548 {
8549 int* p_int = _Storage.GetIntRef(id, 0);
8550 if (selected && *p_int == 0) { *p_int = _SelectionOrder++; Size++; }
8551 else if (!selected && *p_int != 0) { *p_int = 0; Size--; }
8552 }
8553
8554 // Optimized for batch edits (with same value of 'selected')
8555 static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends, int selection_order)
8556 {
8557 ImGuiStorage* storage = &selection->_Storage;
8558 ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id);
8559 const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id);
8560 if (selected == (is_contained && it->val_i != 0))
8561 return;
8562 if (selected && !is_contained)
8563 storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish()
8564 else if (is_contained)
8565 it->val_i = selected ? selection_order : 0; // Modify in-place.
8566 selection->Size += selected ? +1 : -1;
8567 }
8568
8569 static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends)
8570 {
8571 ImGuiStorage* storage = &selection->_Storage;
8572 if (selected && selection->Size != size_before_amends)
8573 storage->BuildSortByKey(); // When done selecting: sort everything
8574 }
8575
8576 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8577 // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen.
8578 // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem.
8579 // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection.
8580 // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform
8581 // a lookup in order to have some way to iterate/interpolate between two items.
8582 // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices
8583 // and constructing a view index <> object id/ptr data structure anyway.
8584 // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ImGuiSelectionBasicStorage' INDIRECTION LOGIC.
8585 // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters.
8586 // The most simple implementation (using indices everywhere) would look like:
8587 // for (ImGuiSelectionRequest& req : ms_io->Requests)
8588 // {
8589 // if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { SetItemSelected(n, true); } }
8590 // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { SetItemSelected(n, ms_io->Selected); } }
8591 // }
8592 void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8593 {
8594 // For convenience we obtain ItemsCount as passed to BeginMultiSelect(), which is optional.
8595 // It makes sense when using ImGuiSelectionBasicStorage to simply pass your items count to BeginMultiSelect().
8596 // Other scheme may handle SetAll differently.
8597 IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!");
8598 IM_ASSERT(AdapterIndexToStorageId != NULL);
8599
8600 // This is optimized/specialized to cope with very large selections (e.g. 100k+ items)
8601 // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish().
8602 // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass.
8603 // - 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.
8604 // - 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
8605 // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.)
8606 // FIXME-OPT: For each block of consecutive SetRange request:
8607 // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage.
8608 // - rewrite sorted storage a single time.
8609 for (ImGuiSelectionRequest& req : ms_io->Requests)
8610 {
8611 if (req.Type == ImGuiSelectionRequestType_SetAll)
8612 {
8613 Clear();
8614 if (req.Selected)
8615 {
8616 _Storage.Data.reserve(ms_io->ItemsCount);
8617 const int size_before_amends = _Storage.Data.Size;
8618 for (int idx = 0; idx < ms_io->ItemsCount; idx++, _SelectionOrder++)
8619 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, _SelectionOrder);
8620 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8621 }
8622 }
8623 else if (req.Type == ImGuiSelectionRequestType_SetRange)
8624 {
8625 const int selection_changes = (int)req.RangeLastItem - (int)req.RangeFirstItem + 1;
8626 //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);
8627 if (selection_changes == 1 || (selection_changes < Size / 100))
8628 {
8629 // Multiple sorted insertion + copy likely to be faster.
8630 // Technically we could do a single copy with a little more work (sort sequential SetRange requests)
8631 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8632 SetItemSelected(GetStorageIdFromIndex(idx), req.Selected);
8633 }
8634 else
8635 {
8636 // Append insertion + single sort likely be faster.
8637 // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1
8638 const int size_before_amends = _Storage.Data.Size;
8639 int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0);
8640 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection)
8641 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order);
8642 if (req.Selected)
8643 _SelectionOrder += selection_changes;
8644 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8645 }
8646 }
8647 }
8648 }
8649
8650 //-------------------------------------------------------------------------
8651
8652 ImGuiSelectionExternalStorage::ImGuiSelectionExternalStorage()
8653 {
8654 UserData = NULL;
8655 AdapterSetItemSelected = NULL;
8656 }
8657
8658 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8659 // We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage
8660 // This makes no assumption about underlying storage.
8661 void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8662 {
8663 IM_ASSERT(AdapterSetItemSelected);
8664 for (ImGuiSelectionRequest& req : ms_io->Requests)
8665 {
8666 if (req.Type == ImGuiSelectionRequestType_SetAll)
8667 for (int idx = 0; idx < ms_io->ItemsCount; idx++)
8668 AdapterSetItemSelected(this, idx, req.Selected);
8669 if (req.Type == ImGuiSelectionRequestType_SetRange)
8670 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8671 AdapterSetItemSelected(this, idx, req.Selected);
8672 }
8673 }
8674
8675 //-------------------------------------------------------------------------
8676 // [SECTION] Widgets: ListBox
8677 //-------------------------------------------------------------------------
8678 // - BeginListBox()
8679 // - EndListBox()
8680 // - ListBox()
8681 //-------------------------------------------------------------------------
8682
8683 // This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
8684 // This handle some subtleties with capturing info from the label.
8685 // If you don't need a label you can pretty much directly use ImGui::BeginChild() with ImGuiChildFlags_FrameStyle.
8686 // Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty"
8687 // 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).
8688 bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)
8689 {
8690 ImGuiContext& g = *GImGui;
8691 ImGuiWindow* window = GetCurrentWindow();
8692 if (window->SkipItems)
8693 return false;
8694
8695 const ImGuiStyle& style = g.Style;
8696 const ImGuiID id = GetID(label);
8697 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8698
8699 // Size default to hold ~7.25 items.
8700 // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
8701 ImVec2 size = ImTrunc(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f));
8702 ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
8703 ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8704 ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
8705 g.NextItemData.ClearFlags();
8706
8707 if (!IsRectVisible(bb.Min, bb.Max))
8708 {
8709 ItemSize(bb.GetSize(), style.FramePadding.y);
8710 ItemAdd(bb, 0, &frame_bb);
8711 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8712 return false;
8713 }
8714
8715 // FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well.
8716 BeginGroup();
8717 if (label_size.x > 0.0f)
8718 {
8719 ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y);
8720 RenderText(label_pos, label);
8721 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size);
8722 AlignTextToFramePadding();
8723 }
8724
8725 BeginChild(id, frame_bb.GetSize(), ImGuiChildFlags_FrameStyle);
8726 return true;
8727 }
8728
8729 void ImGui::EndListBox()
8730 {
8731 ImGuiContext& g = *GImGui;
8732 ImGuiWindow* window = g.CurrentWindow;
8733 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?");
8734 IM_UNUSED(window);
8735
8736 EndChild();
8737 EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label
8738 }
8739
8740 bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
8741 {
8742 const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
8743 return value_changed;
8744 }
8745
8746 // This is merely a helper around BeginListBox(), EndListBox().
8747 // Considering using those directly to submit custom data or store selection differently.
8748 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)
8749 {
8750 ImGuiContext& g = *GImGui;
8751
8752 // Calculate size from "height_in_items"
8753 if (height_in_items < 0)
8754 height_in_items = ImMin(items_count, 7);
8755 float height_in_items_f = height_in_items + 0.25f;
8756 ImVec2 size(0.0f, ImTrunc(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f));
8757
8758 if (!BeginListBox(label, size))
8759 return false;
8760
8761 // Assume all items have even height (= 1 line of text). If you need items of different height,
8762 // you can create a custom version of ListBox() in your code without using the clipper.
8763 bool value_changed = false;
8764 ImGuiListClipper clipper;
8765 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.
8766 clipper.IncludeItemByIndex(*current_item);
8767 while (clipper.Step())
8768 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
8769 {
8770 const char* item_text = getter(user_data, i);
8771 if (item_text == NULL)
8772 item_text = "*Unknown item*";
8773
8774 PushID(i);
8775 const bool item_selected = (i == *current_item);
8776 if (Selectable(item_text, item_selected))
8777 {
8778 *current_item = i;
8779 value_changed = true;
8780 }
8781 if (item_selected)
8782 SetItemDefaultFocus();
8783 PopID();
8784 }
8785 EndListBox();
8786
8787 if (value_changed)
8788 MarkItemEdited(g.LastItemData.ID);
8789
8790 return value_changed;
8791 }
8792
8793 //-------------------------------------------------------------------------
8794 // [SECTION] Widgets: PlotLines, PlotHistogram
8795 //-------------------------------------------------------------------------
8796 // - PlotEx() [Internal]
8797 // - PlotLines()
8798 // - PlotHistogram()
8799 //-------------------------------------------------------------------------
8800 // Plot/Graph widgets are not very good.
8801 // Consider writing your own, or using a third-party one, see:
8802 // - ImPlot https://github.com/epezent/implot
8803 // - others https://github.com/ocornut/imgui/wiki/Useful-Extensions
8804 //-------------------------------------------------------------------------
8805
8806 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)
8807 {
8808 ImGuiContext& g = *GImGui;
8809 ImGuiWindow* window = GetCurrentWindow();
8810 if (window->SkipItems)
8811 return -1;
8812
8813 const ImGuiStyle& style = g.Style;
8814 const ImGuiID id = window->GetID(label);
8815
8816 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8817 const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f);
8818
8819 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8820 const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
8821 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));
8822 ItemSize(total_bb, style.FramePadding.y);
8823 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav))
8824 return -1;
8825 bool hovered;
8826 ButtonBehavior(frame_bb, id, &hovered, NULL);
8827
8828 // Determine scale from values if not specified
8829 if (scale_min == FLT_MAX || scale_max == FLT_MAX)
8830 {
8831 float v_min = FLT_MAX;
8832 float v_max = -FLT_MAX;
8833 for (int i = 0; i < values_count; i++)
8834 {
8835 const float v = values_getter(data, i);
8836 if (v != v) // Ignore NaN values
8837 continue;
8838 v_min = ImMin(v_min, v);
8839 v_max = ImMax(v_max, v);
8840 }
8841 if (scale_min == FLT_MAX)
8842 scale_min = v_min;
8843 if (scale_max == FLT_MAX)
8844 scale_max = v_max;
8845 }
8846
8847 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
8848
8849 const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
8850 int idx_hovered = -1;
8851 if (values_count >= values_count_min)
8852 {
8853 int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8854 int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8855
8856 // Tooltip on hover
8857 if (hovered && inner_bb.Contains(g.IO.MousePos))
8858 {
8859 const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
8860 const int v_idx = (int)(t * item_count);
8861 IM_ASSERT(v_idx >= 0 && v_idx < values_count);
8862
8863 const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
8864 const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
8865 if (plot_type == ImGuiPlotType_Lines)
8866 SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1);
8867 else if (plot_type == ImGuiPlotType_Histogram)
8868 SetTooltip("%d: %8.4g", v_idx, v0);
8869 idx_hovered = v_idx;
8870 }
8871
8872 const float t_step = 1.0f / (float)res_w;
8873 const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
8874
8875 float v0 = values_getter(data, (0 + values_offset) % values_count);
8876 float t0 = 0.0f;
8877 ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
8878 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
8879
8880 const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
8881 const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
8882
8883 for (int n = 0; n < res_w; n++)
8884 {
8885 const float t1 = t0 + t_step;
8886 const int v1_idx = (int)(t0 * item_count + 0.5f);
8887 IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
8888 const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
8889 const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
8890
8891 // 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.
8892 ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
8893 ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
8894 if (plot_type == ImGuiPlotType_Lines)
8895 {
8896 window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8897 }
8898 else if (plot_type == ImGuiPlotType_Histogram)
8899 {
8900 if (pos1.x >= pos0.x + 2.0f)
8901 pos1.x -= 1.0f;
8902 window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8903 }
8904
8905 t0 = t1;
8906 tp0 = tp1;
8907 }
8908 }
8909
8910 // Text overlay
8911 if (overlay_text)
8912 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));
8913
8914 if (label_size.x > 0.0f)
8915 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
8916
8917 // Return hovered index or -1 if none are hovered.
8918 // 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().
8919 return idx_hovered;
8920 }
8921
8922 struct ImGuiPlotArrayGetterData
8923 {
8924 const float* Values;
8925 int Stride;
8926
8927 ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
8928 };
8929
8930 static float Plot_ArrayGetter(void* data, int idx)
8931 {
8932 ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
8933 const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
8934 return v;
8935 }
8936
8937 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)
8938 {
8939 ImGuiPlotArrayGetterData data(values, stride);
8940 PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8941 }
8942
8943 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)
8944 {
8945 PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8946 }
8947
8948 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)
8949 {
8950 ImGuiPlotArrayGetterData data(values, stride);
8951 PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8952 }
8953
8954 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)
8955 {
8956 PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8957 }
8958
8959 //-------------------------------------------------------------------------
8960 // [SECTION] Widgets: Value helpers
8961 // Those is not very useful, legacy API.
8962 //-------------------------------------------------------------------------
8963 // - Value()
8964 //-------------------------------------------------------------------------
8965
8966 void ImGui::Value(const char* prefix, bool b)
8967 {
8968 Text("%s: %s", prefix, (b ? "true" : "false"));
8969 }
8970
8971 void ImGui::Value(const char* prefix, int v)
8972 {
8973 Text("%s: %d", prefix, v);
8974 }
8975
8976 void ImGui::Value(const char* prefix, unsigned int v)
8977 {
8978 Text("%s: %d", prefix, v);
8979 }
8980
8981 void ImGui::Value(const char* prefix, float v, const char* float_format)
8982 {
8983 if (float_format)
8984 {
8985 char fmt[64];
8986 ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
8987 Text(fmt, prefix, v);
8988 }
8989 else
8990 {
8991 Text("%s: %.3f", prefix, v);
8992 }
8993 }
8994
8995 //-------------------------------------------------------------------------
8996 // [SECTION] MenuItem, BeginMenu, EndMenu, etc.
8997 //-------------------------------------------------------------------------
8998 // - ImGuiMenuColumns [Internal]
8999 // - BeginMenuBar()
9000 // - EndMenuBar()
9001 // - BeginMainMenuBar()
9002 // - EndMainMenuBar()
9003 // - BeginMenu()
9004 // - EndMenu()
9005 // - MenuItemEx() [Internal]
9006 // - MenuItem()
9007 //-------------------------------------------------------------------------
9008
9009 // Helpers for internal use
9010 void ImGuiMenuColumns::Update(float spacing, bool window_reappearing)
9011 {
9012 if (window_reappearing)
9013 memset(Widths, 0, sizeof(Widths));
9014 Spacing = (ImU16)spacing;
9015 CalcNextTotalWidth(true);
9016 memset(Widths, 0, sizeof(Widths));
9017 TotalWidth = NextTotalWidth;
9018 NextTotalWidth = 0;
9019 }
9020
9021 void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets)
9022 {
9023 ImU16 offset = 0;
9024 bool want_spacing = false;
9025 for (int i = 0; i < IM_ARRAYSIZE(Widths); i++)
9026 {
9027 ImU16 width = Widths[i];
9028 if (want_spacing && width > 0)
9029 offset += Spacing;
9030 want_spacing |= (width > 0);
9031 if (update_offsets)
9032 {
9033 if (i == 1) { OffsetLabel = offset; }
9034 if (i == 2) { OffsetShortcut = offset; }
9035 if (i == 3) { OffsetMark = offset; }
9036 }
9037 offset += width;
9038 }
9039 NextTotalWidth = offset;
9040 }
9041
9042 float ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark)
9043 {
9044 Widths[0] = ImMax(Widths[0], (ImU16)w_icon);
9045 Widths[1] = ImMax(Widths[1], (ImU16)w_label);
9046 Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut);
9047 Widths[3] = ImMax(Widths[3], (ImU16)w_mark);
9048 CalcNextTotalWidth(false);
9049 return (float)ImMax(TotalWidth, NextTotalWidth);
9050 }
9051
9052 // FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
9053 // Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
9054 // 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.
9055 // Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
9056 bool ImGui::BeginMenuBar()
9057 {
9058 ImGuiWindow* window = GetCurrentWindow();
9059 if (window->SkipItems)
9060 return false;
9061 if (!(window->Flags & ImGuiWindowFlags_MenuBar))
9062 return false;
9063
9064 IM_ASSERT(!window->DC.MenuBarAppending);
9065 BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
9066 PushID("##MenuBar");
9067
9068 // 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.
9069 // 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.
9070 const float border_top = ImMax(IM_ROUND(window->WindowBorderSize * 0.5f - window->TitleBarHeight), 0.0f);
9071 const float border_half = IM_ROUND(window->WindowBorderSize * 0.5f);
9072 ImRect bar_rect = window->MenuBarRect();
9073 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));
9074 clip_rect.ClipWith(window->OuterRectClipped);
9075 PushClipRect(clip_rect.Min, clip_rect.Max, false);
9076
9077 // 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).
9078 window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
9079 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
9080 window->DC.IsSameLine = false;
9081 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
9082 window->DC.MenuBarAppending = true;
9083 AlignTextToFramePadding();
9084 return true;
9085 }
9086
9087 void ImGui::EndMenuBar()
9088 {
9089 ImGuiWindow* window = GetCurrentWindow();
9090 if (window->SkipItems)
9091 return;
9092 ImGuiContext& g = *GImGui;
9093
9094 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
9095 IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
9096 IM_ASSERT(window->DC.MenuBarAppending);
9097
9098 // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
9099 if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
9100 {
9101 // Try to find out if the request is for one of our child menu
9102 ImGuiWindow* nav_earliest_child = g.NavWindow;
9103 while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
9104 nav_earliest_child = nav_earliest_child->ParentWindow;
9105 if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
9106 {
9107 // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
9108 // 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)
9109 const ImGuiNavLayer layer = ImGuiNavLayer_Menu;
9110 IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary)
9111 FocusWindow(window);
9112 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
9113 // FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto?
9114 if (g.NavCursorVisible)
9115 {
9116 g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again
9117 g.NavCursorHideFrames = 2;
9118 }
9119 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
9120 NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
9121 }
9122 }
9123
9124 PopClipRect();
9125 PopID();
9126 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
9127 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.
9128
9129 // FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here.
9130 ImGuiGroupData& group_data = g.GroupStack.back();
9131 group_data.EmitItem = false;
9132 ImVec2 restore_cursor_max_pos = group_data.BackupCursorMaxPos;
9133 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, window->DC.CursorMaxPos.x - window->Scroll.x); // Convert ideal extents for scrolling layer equivalent.
9134 EndGroup(); // Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore
9135 window->DC.LayoutType = ImGuiLayoutType_Vertical;
9136 window->DC.IsSameLine = false;
9137 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
9138 window->DC.MenuBarAppending = false;
9139 window->DC.CursorMaxPos = restore_cursor_max_pos;
9140 }
9141
9142 // Important: calling order matters!
9143 // FIXME: Somehow overlapping with docking tech.
9144 // FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts)
9145 bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags)
9146 {
9147 IM_ASSERT(dir != ImGuiDir_None);
9148
9149 ImGuiWindow* bar_window = FindWindowByName(name);
9150 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport());
9151 if (bar_window == NULL || bar_window->BeginCount == 0)
9152 {
9153 // Calculate and set window size/position
9154 ImRect avail_rect = viewport->GetBuildWorkRect();
9155 ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
9156 ImVec2 pos = avail_rect.Min;
9157 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
9158 pos[axis] = avail_rect.Max[axis] - axis_size;
9159 ImVec2 size = avail_rect.GetSize();
9160 size[axis] = axis_size;
9161 SetNextWindowPos(pos);
9162 SetNextWindowSize(size);
9163
9164 // Report our size into work area (for next frame) using actual window size
9165 if (dir == ImGuiDir_Up || dir == ImGuiDir_Left)
9166 viewport->BuildWorkInsetMin[axis] += axis_size;
9167 else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right)
9168 viewport->BuildWorkInsetMax[axis] += axis_size;
9169 }
9170
9171 window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
9172 SetNextWindowViewport(viewport->ID); // Enforce viewport so we don't create our own viewport when ImGuiConfigFlags_ViewportsNoMerge is set.
9173 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
9174 PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint
9175 bool is_open = Begin(name, NULL, window_flags);
9176 PopStyleVar(2);
9177
9178 return is_open;
9179 }
9180
9181 bool ImGui::BeginMainMenuBar()
9182 {
9183 ImGuiContext& g = *GImGui;
9184 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
9185
9186 // Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change
9187 SetCurrentViewport(NULL, viewport);
9188
9189 // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
9190 // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea?
9191 // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings.
9192 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
9193 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
9194 float height = GetFrameHeight();
9195 bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags);
9196 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
9197 if (!is_open)
9198 {
9199 End();
9200 return false;
9201 }
9202
9203 // Temporarily disable _NoSavedSettings, in the off-chance that tables or child windows submitted within the menu-bar may want to use settings. (#8356)
9204 g.CurrentWindow->Flags &= ~ImGuiWindowFlags_NoSavedSettings;
9205 BeginMenuBar();
9206 return is_open;
9207 }
9208
9209 void ImGui::EndMainMenuBar()
9210 {
9211 ImGuiContext& g = *GImGui;
9212 if (!g.CurrentWindow->DC.MenuBarAppending)
9213 {
9214 IM_ASSERT_USER_ERROR(0, "Calling EndMainMenuBar() not from a menu-bar!"); // Not technically testing that it is the main menu bar
9215 return;
9216 }
9217
9218 EndMenuBar();
9219 g.CurrentWindow->Flags |= ImGuiWindowFlags_NoSavedSettings; // Restore _NoSavedSettings (#8356)
9220
9221 // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
9222 // FIXME: With this strategy we won't be able to restore a NULL focus.
9223 if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest && g.ActiveId == 0)
9224 FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild);
9225
9226 End();
9227 }
9228
9229 static bool IsRootOfOpenMenuSet()
9230 {
9231 ImGuiContext& g = *GImGui;
9232 ImGuiWindow* window = g.CurrentWindow;
9233 if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu))
9234 return false;
9235
9236 // Initially we used 'upper_popup->OpenParentId == window->IDStack.back()' to differentiate multiple menu sets from each others
9237 // (e.g. inside menu bar vs loose menu items) based on parent ID.
9238 // This would however prevent the use of e.g. PushID() user code submitting menus.
9239 // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag,
9240 // making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects.
9241 // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup
9242 // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu.
9243 // 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.
9244 // 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
9245 // 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
9246 // it likely won't be a problem anyone runs into.
9247 const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size];
9248 if (window->DC.NavLayerCurrent != upper_popup->ParentNavLayer)
9249 return false;
9250 return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true, false);
9251 }
9252
9253 bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
9254 {
9255 ImGuiWindow* window = GetCurrentWindow();
9256 if (window->SkipItems)
9257 return false;
9258
9259 ImGuiContext& g = *GImGui;
9260 const ImGuiStyle& style = g.Style;
9261 const ImGuiID id = window->GetID(label);
9262 bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None);
9263
9264 // 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)
9265 // 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.
9266 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
9267 if (window->Flags & ImGuiWindowFlags_ChildMenu)
9268 window_flags |= ImGuiWindowFlags_ChildWindow;
9269
9270 // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().
9271 // 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.
9272 // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used.
9273 if (g.MenusIdSubmittedThisFrame.contains(id))
9274 {
9275 if (menu_is_open)
9276 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)
9277 else
9278 g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values
9279 return menu_is_open;
9280 }
9281
9282 // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu
9283 g.MenusIdSubmittedThisFrame.push_back(id);
9284
9285 ImVec2 label_size = CalcTextSize(label, NULL, true);
9286
9287 // 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)
9288 // This is only done for items for the menu set and not the full parent window.
9289 const bool menuset_is_open = IsRootOfOpenMenuSet();
9290 if (menuset_is_open)
9291 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
9292
9293 // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
9294 // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().
9295 // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
9296 ImVec2 popup_pos, pos = window->DC.CursorPos;
9297 PushID(label);
9298 if (!enabled)
9299 BeginDisabled();
9300 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
9301 bool pressed;
9302
9303 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
9304 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups;
9305 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9306 {
9307 // Menu inside a horizontal menu bar
9308 // Selectable extend their highlight by half ItemSpacing in each direction.
9309 // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
9310 popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight);
9311 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
9312 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
9313 float w = label_size.x;
9314 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9315 pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y));
9316 LogSetNextTextDecoration("[", "]");
9317 RenderText(text_pos, label);
9318 PopStyleVar();
9319 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().
9320 }
9321 else
9322 {
9323 // Menu inside a regular/vertical menu
9324 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
9325 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
9326 popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
9327 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
9328 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
9329 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame
9330 float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
9331 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9332 pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
9333 LogSetNextTextDecoration("", ">");
9334 RenderText(text_pos, label);
9335 if (icon_w > 0.0f)
9336 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
9337 RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right);
9338 }
9339 if (!enabled)
9340 EndDisabled();
9341
9342 const bool hovered = (g.HoveredId == id) && enabled && !g.NavHighlightItemUnderNav;
9343 if (menuset_is_open)
9344 PopItemFlag();
9345
9346 bool want_open = false;
9347 bool want_open_nav_init = false;
9348 bool want_close = false;
9349 if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
9350 {
9351 // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
9352 // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
9353 bool moving_toward_child_menu = false;
9354 ImGuiPopupData* child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) ? &g.OpenPopupStack[g.BeginPopupStack.Size] : NULL; // Popup candidate (testing below)
9355 ImGuiWindow* child_menu_window = (child_popup && child_popup->Window && child_popup->Window->ParentWindow == window) ? child_popup->Window : NULL;
9356 if (g.HoveredWindow == window && child_menu_window != NULL)
9357 {
9358 const float ref_unit = g.FontSize; // FIXME-DPI
9359 const float child_dir = (window->Pos.x < child_menu_window->Pos.x) ? 1.0f : -1.0f;
9360 const ImRect next_window_rect = child_menu_window->Rect();
9361 ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta);
9362 ImVec2 tb = (child_dir > 0.0f) ? next_window_rect.GetTL() : next_window_rect.GetTR();
9363 ImVec2 tc = (child_dir > 0.0f) ? next_window_rect.GetBL() : next_window_rect.GetBR();
9364 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.
9365 ta.x += child_dir * -0.5f;
9366 tb.x += child_dir * ref_unit;
9367 tc.x += child_dir * ref_unit;
9368 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
9369 tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, +ref_unit * 8.0f);
9370 moving_toward_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
9371 //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
9372 }
9373
9374 // 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)
9375 // 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.
9376 // (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.)
9377 if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavHighlightItemUnderNav && g.ActiveId == 0)
9378 want_close = true;
9379
9380 // Open
9381 // (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test)
9382 if (!menu_is_open && pressed) // Click/activate to open
9383 want_open = true;
9384 else if (!menu_is_open && hovered && !moving_toward_child_menu) // Hover to open
9385 want_open = true;
9386 else if (!menu_is_open && hovered && g.HoveredIdTimer >= 0.30f && g.MouseStationaryTimer >= 0.30f) // Hover to open (timer fallback)
9387 want_open = true;
9388 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
9389 {
9390 want_open = want_open_nav_init = true;
9391 NavMoveRequestCancel();
9392 SetNavCursorVisibleAfterMove();
9393 }
9394 }
9395 else
9396 {
9397 // Menu bar
9398 if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
9399 {
9400 want_close = true;
9401 want_open = menu_is_open = false;
9402 }
9403 else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
9404 {
9405 want_open = true;
9406 }
9407 else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
9408 {
9409 want_open = true;
9410 NavMoveRequestCancel();
9411 }
9412 }
9413
9414 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.. }'
9415 want_close = true;
9416 if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))
9417 ClosePopupToLevel(g.BeginPopupStack.Size, true);
9418
9419 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
9420 PopID();
9421
9422 if (want_open && !menu_is_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
9423 {
9424 // 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.
9425 OpenPopup(label);
9426 }
9427 else if (want_open)
9428 {
9429 menu_is_open = true;
9430 OpenPopup(label, ImGuiPopupFlags_NoReopen);// | (want_open_nav_init ? ImGuiPopupFlags_NoReopenAlwaysNavInit : 0));
9431 }
9432
9433 if (menu_is_open)
9434 {
9435 ImGuiLastItemData last_item_in_parent = g.LastItemData;
9436 SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos.
9437 PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding
9438 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)
9439 PopStyleVar();
9440 if (menu_is_open)
9441 {
9442 // Implement what ImGuiPopupFlags_NoReopenAlwaysNavInit would do:
9443 // Perform an init request in the case the popup was already open (via a previous mouse hover)
9444 if (want_open && want_open_nav_init && !g.NavInitRequest)
9445 {
9446 FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags_UnlessBelowModal);
9447 NavInitWindow(g.CurrentWindow, false);
9448 }
9449
9450 // Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu()
9451 // (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags_NoWindowHoverableCheck)
9452 g.LastItemData = last_item_in_parent;
9453 if (g.HoveredWindow == window)
9454 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
9455 }
9456 }
9457 else
9458 {
9459 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
9460 }
9461
9462 return menu_is_open;
9463 }
9464
9465 bool ImGui::BeginMenu(const char* label, bool enabled)
9466 {
9467 return BeginMenuEx(label, NULL, enabled);
9468 }
9469
9470 void ImGui::EndMenu()
9471 {
9472 // Nav: When a left move request our menu failed, close ourselves.
9473 ImGuiContext& g = *GImGui;
9474 ImGuiWindow* window = g.CurrentWindow;
9475 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginMenu()/EndMenu() calls
9476 ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert.
9477 if (window->BeginCount == window->BeginCountPreviousFrame)
9478 if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet())
9479 if (g.NavWindow && (g.NavWindow->RootWindowForNav == window) && parent_window->DC.LayoutType == ImGuiLayoutType_Vertical)
9480 {
9481 ClosePopupToLevel(g.BeginPopupStack.Size - 1, true);
9482 NavMoveRequestCancel();
9483 }
9484
9485 EndPopup();
9486 }
9487
9488 bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled)
9489 {
9490 ImGuiWindow* window = GetCurrentWindow();
9491 if (window->SkipItems)
9492 return false;
9493
9494 ImGuiContext& g = *GImGui;
9495 ImGuiStyle& style = g.Style;
9496 ImVec2 pos = window->DC.CursorPos;
9497 ImVec2 label_size = CalcTextSize(label, NULL, true);
9498
9499 // See BeginMenuEx() for comments about this.
9500 const bool menuset_is_open = IsRootOfOpenMenuSet();
9501 if (menuset_is_open)
9502 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
9503
9504 // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
9505 // 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.
9506 bool pressed;
9507 PushID(label);
9508 if (!enabled)
9509 BeginDisabled();
9510
9511 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
9512 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SetNavIdOnHover;
9513 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
9514 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9515 {
9516 // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
9517 // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark.
9518 float w = label_size.x;
9519 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
9520 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9521 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
9522 pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f));
9523 PopStyleVar();
9524 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9525 RenderText(text_pos, label);
9526 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().
9527 }
9528 else
9529 {
9530 // Menu item inside a vertical menu
9531 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
9532 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
9533 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
9534 float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f;
9535 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
9536 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame
9537 float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
9538 pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
9539 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9540 {
9541 RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label);
9542 if (icon_w > 0.0f)
9543 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
9544 if (shortcut_w > 0.0f)
9545 {
9546 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
9547 LogSetNextTextDecoration("(", ")");
9548 RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);
9549 PopStyleColor();
9550 }
9551 if (selected)
9552 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);
9553 }
9554 }
9555 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
9556 if (!enabled)
9557 EndDisabled();
9558 PopID();
9559 if (menuset_is_open)
9560 PopItemFlag();
9561
9562 return pressed;
9563 }
9564
9565 bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
9566 {
9567 return MenuItemEx(label, NULL, shortcut, selected, enabled);
9568 }
9569
9570 bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
9571 {
9572 if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled))
9573 {
9574 if (p_selected)
9575 *p_selected = !*p_selected;
9576 return true;
9577 }
9578 return false;
9579 }
9580
9581 //-------------------------------------------------------------------------
9582 // [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
9583 //-------------------------------------------------------------------------
9584 // - BeginTabBar()
9585 // - BeginTabBarEx() [Internal]
9586 // - EndTabBar()
9587 // - TabBarLayout() [Internal]
9588 // - TabBarCalcTabID() [Internal]
9589 // - TabBarCalcMaxTabWidth() [Internal]
9590 // - TabBarFindTabById() [Internal]
9591 // - TabBarFindTabByOrder() [Internal]
9592 // - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal]
9593 // - TabBarGetCurrentTab() [Internal]
9594 // - TabBarGetTabName() [Internal]
9595 // - TabBarAddTab() [Internal]
9596 // - TabBarRemoveTab() [Internal]
9597 // - TabBarCloseTab() [Internal]
9598 // - TabBarScrollClamp() [Internal]
9599 // - TabBarScrollToTab() [Internal]
9600 // - TabBarQueueFocus() [Internal]
9601 // - TabBarQueueReorder() [Internal]
9602 // - TabBarProcessReorderFromMousePos() [Internal]
9603 // - TabBarProcessReorder() [Internal]
9604 // - TabBarScrollingButtons() [Internal]
9605 // - TabBarTabListPopupButton() [Internal]
9606 //-------------------------------------------------------------------------
9607
9608 struct ImGuiTabBarSection
9609 {
9610 int TabCount; // Number of tabs in this section.
9611 float Width; // Sum of width of tabs in this section (after shrinking down)
9612 float WidthAfterShrinkMinWidth;
9613 float Spacing; // Horizontal spacing at the end of the section.
9614
9615 ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); }
9616 };
9617
9618 namespace ImGui
9619 {
9620 static void TabBarLayout(ImGuiTabBar* tab_bar);
9621 static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window);
9622 static float TabBarCalcMaxTabWidth();
9623 static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
9624 static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections);
9625 static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
9626 static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
9627 }
9628
9629 ImGuiTabBar::ImGuiTabBar()
9630 {
9631 memset(this, 0, sizeof(*this));
9632 CurrFrameVisible = PrevFrameVisible = -1;
9633 LastTabItemIdx = -1;
9634 }
9635
9636 static inline int TabItemGetSectionIdx(const ImGuiTabItem* tab)
9637 {
9638 return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1;
9639 }
9640
9641 static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs)
9642 {
9643 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9644 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9645 const int a_section = TabItemGetSectionIdx(a);
9646 const int b_section = TabItemGetSectionIdx(b);
9647 if (a_section != b_section)
9648 return a_section - b_section;
9649 return (int)(a->IndexDuringLayout - b->IndexDuringLayout);
9650 }
9651
9652 static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs)
9653 {
9654 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9655 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9656 return (int)(a->BeginOrder - b->BeginOrder);
9657 }
9658
9659 static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)
9660 {
9661 ImGuiContext& g = *GImGui;
9662 return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);
9663 }
9664
9665 static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
9666 {
9667 ImGuiContext& g = *GImGui;
9668 if (g.TabBars.Contains(tab_bar))
9669 return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));
9670 return ImGuiPtrOrIndex(tab_bar);
9671 }
9672
9673 bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
9674 {
9675 ImGuiContext& g = *GImGui;
9676 ImGuiWindow* window = g.CurrentWindow;
9677 if (window->SkipItems)
9678 return false;
9679
9680 ImGuiID id = window->GetID(str_id);
9681 ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
9682 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);
9683 tab_bar->ID = id;
9684 tab_bar->SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f);
9685 tab_bar->SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f);
9686 //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false))
9687 flags |= ImGuiTabBarFlags_IsFocused;
9688 return BeginTabBarEx(tab_bar, tab_bar_bb, flags);
9689 }
9690
9691 bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
9692 {
9693 ImGuiContext& g = *GImGui;
9694 ImGuiWindow* window = g.CurrentWindow;
9695 if (window->SkipItems)
9696 return false;
9697
9698 IM_ASSERT(tab_bar->ID != 0);
9699 if ((flags & ImGuiTabBarFlags_DockNode) == 0)
9700 PushOverrideID(tab_bar->ID);
9701
9702 // Add to stack
9703 g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
9704 g.CurrentTabBar = tab_bar;
9705 tab_bar->Window = window;
9706
9707 // Append with multiple BeginTabBar()/EndTabBar() pairs.
9708 tab_bar->BackupCursorPos = window->DC.CursorPos;
9709 if (tab_bar->CurrFrameVisible == g.FrameCount)
9710 {
9711 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9712 tab_bar->BeginCount++;
9713 return true;
9714 }
9715
9716 // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable
9717 if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable)))
9718 if ((flags & ImGuiTabBarFlags_DockNode) == 0) // FIXME: TabBar with DockNode can now be hybrid
9719 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder);
9720 tab_bar->TabsAddedNew = false;
9721
9722 // Flags
9723 if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
9724 flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
9725
9726 tab_bar->Flags = flags;
9727 tab_bar->BarRect = tab_bar_bb;
9728 tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
9729 tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
9730 tab_bar->CurrFrameVisible = g.FrameCount;
9731 tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight;
9732 tab_bar->CurrTabsContentsHeight = 0.0f;
9733 tab_bar->ItemSpacingY = g.Style.ItemSpacing.y;
9734 tab_bar->FramePadding = g.Style.FramePadding;
9735 tab_bar->TabsActiveCount = 0;
9736 tab_bar->LastTabItemIdx = -1;
9737 tab_bar->BeginCount = 1;
9738
9739 // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap
9740 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9741
9742 // Draw separator
9743 // (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable)
9744 const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected);
9745 if (g.Style.TabBarBorderSize > 0.0f)
9746 {
9747 const float y = tab_bar->BarRect.Max.y;
9748 window->DrawList->AddRectFilled(ImVec2(tab_bar->SeparatorMinX, y - g.Style.TabBarBorderSize), ImVec2(tab_bar->SeparatorMaxX, y), col);
9749 }
9750 return true;
9751 }
9752
9753 void ImGui::EndTabBar()
9754 {
9755 ImGuiContext& g = *GImGui;
9756 ImGuiWindow* window = g.CurrentWindow;
9757 if (window->SkipItems)
9758 return;
9759
9760 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9761 if (tab_bar == NULL)
9762 {
9763 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!");
9764 return;
9765 }
9766
9767 // Fallback in case no TabItem have been submitted
9768 if (tab_bar->WantLayout)
9769 TabBarLayout(tab_bar);
9770
9771 // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
9772 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
9773 if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
9774 {
9775 tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight);
9776 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight;
9777 }
9778 else
9779 {
9780 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight;
9781 }
9782 if (tab_bar->BeginCount > 1)
9783 window->DC.CursorPos = tab_bar->BackupCursorPos;
9784
9785 tab_bar->LastTabItemIdx = -1;
9786 if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
9787 PopID();
9788
9789 g.CurrentTabBarStack.pop_back();
9790 g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
9791 }
9792
9793 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
9794 static float TabBarCalcScrollableWidth(ImGuiTabBar* tab_bar, ImGuiTabBarSection* sections)
9795 {
9796 return tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing;
9797 }
9798
9799 // This is called only once a frame before by the first call to ItemTab()
9800 // The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
9801 static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
9802 {
9803 ImGuiContext& g = *GImGui;
9804 tab_bar->WantLayout = false;
9805
9806 // Track selected tab when resizing our parent down
9807 const bool scroll_to_selected_tab = (tab_bar->BarRectPrevWidth > tab_bar->BarRect.GetWidth());
9808 tab_bar->BarRectPrevWidth = tab_bar->BarRect.GetWidth();
9809
9810 // Garbage collect by compacting list
9811 // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)
9812 int tab_dst_n = 0;
9813 bool need_sort_by_section = false;
9814 ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing
9815 for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
9816 {
9817 ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
9818 if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose)
9819 {
9820 // Remove tab
9821 if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; }
9822 if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; }
9823 if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; }
9824 continue;
9825 }
9826 if (tab_dst_n != tab_src_n)
9827 tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
9828
9829 tab = &tab_bar->Tabs[tab_dst_n];
9830 tab->IndexDuringLayout = (ImS16)tab_dst_n;
9831
9832 // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another)
9833 int curr_tab_section_n = TabItemGetSectionIdx(tab);
9834 if (tab_dst_n > 0)
9835 {
9836 ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1];
9837 int prev_tab_section_n = TabItemGetSectionIdx(prev_tab);
9838 if (curr_tab_section_n == 0 && prev_tab_section_n != 0)
9839 need_sort_by_section = true;
9840 if (prev_tab_section_n == 2 && curr_tab_section_n != 2)
9841 need_sort_by_section = true;
9842 }
9843
9844 sections[curr_tab_section_n].TabCount++;
9845 tab_dst_n++;
9846 }
9847 if (tab_bar->Tabs.Size != tab_dst_n)
9848 tab_bar->Tabs.resize(tab_dst_n);
9849
9850 if (need_sort_by_section)
9851 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection);
9852
9853 // Calculate spacing between sections
9854 sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9855 sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9856
9857 // Setup next selected tab
9858 ImGuiID scroll_to_tab_id = 0;
9859 if (tab_bar->NextSelectedTabId)
9860 {
9861 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
9862 tab_bar->NextSelectedTabId = 0;
9863 scroll_to_tab_id = tab_bar->SelectedTabId;
9864 }
9865
9866 // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
9867 if (tab_bar->ReorderRequestTabId != 0)
9868 {
9869 if (TabBarProcessReorder(tab_bar))
9870 if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId)
9871 scroll_to_tab_id = tab_bar->ReorderRequestTabId;
9872 tab_bar->ReorderRequestTabId = 0;
9873 }
9874
9875 // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
9876 const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
9877 if (tab_list_popup_button)
9878 if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x!
9879 scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
9880
9881 // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central
9882 // (whereas our tabs are stored as: leading, central, trailing)
9883 int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount };
9884 g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
9885
9886 // Minimum shrink width
9887 const float shrink_min_width = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed) ? g.Style.TabMinWidthShrink : 1.0f;
9888
9889 // Compute ideal tabs widths + store them into shrink buffer
9890 ImGuiTabItem* most_recently_selected_tab = NULL;
9891 int curr_section_n = -1;
9892 bool found_selected_tab_id = false;
9893 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
9894 {
9895 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
9896 IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
9897
9898 if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button))
9899 most_recently_selected_tab = tab;
9900 if (tab->ID == tab_bar->SelectedTabId)
9901 found_selected_tab_id = true;
9902 if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID)
9903 scroll_to_tab_id = tab->ID;
9904
9905 // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
9906 // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
9907 // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
9908 const char* tab_name = TabBarGetTabName(tab_bar, tab);
9909 const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
9910 tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x;
9911 if ((tab->Flags & ImGuiTabItemFlags_Button) == 0)
9912 tab->ContentWidth = ImMax(tab->ContentWidth, g.Style.TabMinWidthBase);
9913
9914 int section_n = TabItemGetSectionIdx(tab);
9915 ImGuiTabBarSection* section = &sections[section_n];
9916 section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
9917 section->WidthAfterShrinkMinWidth += ImMin(tab->ContentWidth, shrink_min_width) + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
9918 curr_section_n = section_n;
9919
9920 // Store data so we can build an array sorted by width if we need to shrink tabs down
9921 IM_MSVC_WARNING_SUPPRESS(6385);
9922 ImGuiShrinkWidthItem* shrink_width_item = &g.ShrinkWidthBuffer[shrink_buffer_indexes[section_n]++];
9923 shrink_width_item->Index = tab_n;
9924 shrink_width_item->Width = shrink_width_item->InitialWidth = tab->ContentWidth;
9925 tab->Width = ImMax(tab->ContentWidth, 1.0f);
9926 }
9927
9928 // Compute total ideal width (used for e.g. auto-resizing a window)
9929 float width_all_tabs_after_min_width_shrink = 0.0f;
9930 tab_bar->WidthAllTabsIdeal = 0.0f;
9931 for (int section_n = 0; section_n < 3; section_n++)
9932 {
9933 tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing;
9934 width_all_tabs_after_min_width_shrink += sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing;
9935 }
9936
9937 // Horizontal scrolling buttons
9938 // Important: note that TabBarScrollButtons() will alter BarRect.Max.x.
9939 const bool can_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
9940 const float width_all_tabs_to_use_for_scroll = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) ? tab_bar->WidthAllTabs : width_all_tabs_after_min_width_shrink;
9941 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);
9942 if (tab_bar->ScrollButtonEnabled)
9943 if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar))
9944 {
9945 scroll_to_tab_id = scroll_and_select_tab->ID;
9946 if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0)
9947 tab_bar->SelectedTabId = scroll_to_tab_id;
9948 }
9949 if (scroll_to_tab_id == 0 && scroll_to_selected_tab)
9950 scroll_to_tab_id = tab_bar->SelectedTabId;
9951
9952 // Shrink widths if full tabs don't fit in their allocated space
9953 float section_0_w = sections[0].Width + sections[0].Spacing;
9954 float section_1_w = sections[1].Width + sections[1].Spacing;
9955 float section_2_w = sections[2].Width + sections[2].Spacing;
9956 bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth();
9957 float width_excess;
9958 if (central_section_is_visible)
9959 width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section
9960 else
9961 width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section
9962
9963 // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore
9964 const bool can_shrink = (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyShrink) || (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyMixed);
9965 if (width_excess >= 1.0f && (can_shrink || !central_section_is_visible))
9966 {
9967 int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount);
9968 int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0);
9969 ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess, shrink_min_width);
9970
9971 // Apply shrunk values into tabs and sections
9972 for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++)
9973 {
9974 ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index];
9975 float shrinked_width = IM_TRUNC(g.ShrinkWidthBuffer[tab_n].Width);
9976 if (shrinked_width < 0.0f)
9977 continue;
9978
9979 shrinked_width = ImMax(1.0f, shrinked_width);
9980 int section_n = TabItemGetSectionIdx(tab);
9981 sections[section_n].Width -= (tab->Width - shrinked_width);
9982 tab->Width = shrinked_width;
9983 }
9984 }
9985
9986 // Layout all active tabs
9987 int section_tab_index = 0;
9988 float tab_offset = 0.0f;
9989 tab_bar->WidthAllTabs = 0.0f;
9990 for (int section_n = 0; section_n < 3; section_n++)
9991 {
9992 ImGuiTabBarSection* section = &sections[section_n];
9993 if (section_n == 2)
9994 tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset);
9995
9996 for (int tab_n = 0; tab_n < section->TabCount; tab_n++)
9997 {
9998 ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n];
9999 tab->Offset = tab_offset;
10000 tab->NameOffset = -1;
10001 tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f);
10002 }
10003 tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f);
10004 tab_offset += section->Spacing;
10005 section_tab_index += section->TabCount;
10006 }
10007
10008 // Clear name buffers
10009 tab_bar->TabsNames.Buf.resize(0);
10010
10011 // If we have lost the selected tab, select the next most recently active one
10012 if (found_selected_tab_id == false)
10013 tab_bar->SelectedTabId = 0;
10014 if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
10015 scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
10016
10017 // Lock in visible tab
10018 tab_bar->VisibleTabId = tab_bar->SelectedTabId;
10019 tab_bar->VisibleTabWasSubmitted = false;
10020
10021 // CTRL+TAB can override visible tab temporarily
10022 if (g.NavWindowingTarget != NULL && g.NavWindowingTarget->DockNode && g.NavWindowingTarget->DockNode->TabBar == tab_bar)
10023 tab_bar->VisibleTabId = scroll_to_tab_id = g.NavWindowingTarget->TabId;
10024
10025 // Apply request requests
10026 if (scroll_to_tab_id != 0)
10027 TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections);
10028 else if (tab_bar->ScrollButtonEnabled && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow))
10029 {
10030 const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH;
10031 const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX;
10032 if (TestKeyOwner(wheel_key, tab_bar->ID) && wheel != 0.0f)
10033 {
10034 const float scroll_step = wheel * TabBarCalcScrollableWidth(tab_bar, sections) / 3.0f;
10035 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
10036 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget - scroll_step);
10037 }
10038 SetKeyOwner(wheel_key, tab_bar->ID);
10039 }
10040
10041 // Update scrolling
10042 tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
10043 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
10044 if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
10045 {
10046 // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
10047 // Teleport if we are aiming far off the visible line
10048 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
10049 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
10050 const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
10051 tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
10052 }
10053 else
10054 {
10055 tab_bar->ScrollingSpeed = 0.0f;
10056 }
10057 tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing;
10058 tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing;
10059
10060 // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame)
10061 ImGuiWindow* window = g.CurrentWindow;
10062 window->DC.CursorPos = tab_bar->BarRect.Min;
10063 ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y);
10064 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal);
10065 }
10066
10067 // Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack.
10068 static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window)
10069 {
10070 if (docked_window != NULL)
10071 {
10072 IM_UNUSED(tab_bar);
10073 IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode);
10074 ImGuiID id = docked_window->TabId;
10075 KeepAliveID(id);
10076 return id;
10077 }
10078 else
10079 {
10080 ImGuiWindow* window = GImGui->CurrentWindow;
10081 return window->GetID(label);
10082 }
10083 }
10084
10085 static float ImGui::TabBarCalcMaxTabWidth()
10086 {
10087 ImGuiContext& g = *GImGui;
10088 return g.FontSize * 20.0f;
10089 }
10090
10091 ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
10092 {
10093 if (tab_id != 0)
10094 for (int n = 0; n < tab_bar->Tabs.Size; n++)
10095 if (tab_bar->Tabs[n].ID == tab_id)
10096 return &tab_bar->Tabs[n];
10097 return NULL;
10098 }
10099
10100 // Order = visible order, not submission order! (which is tab->BeginOrder)
10101 ImGuiTabItem* ImGui::TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order)
10102 {
10103 if (order < 0 || order >= tab_bar->Tabs.Size)
10104 return NULL;
10105 return &tab_bar->Tabs[order];
10106 }
10107
10108 // FIXME: See references to #2304 in TODO.txt
10109 ImGuiTabItem* ImGui::TabBarFindMostRecentlySelectedTabForActiveWindow(ImGuiTabBar* tab_bar)
10110 {
10111 ImGuiTabItem* most_recently_selected_tab = NULL;
10112 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
10113 {
10114 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
10115 if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected)
10116 if (tab->Window && tab->Window->WasActive)
10117 most_recently_selected_tab = tab;
10118 }
10119 return most_recently_selected_tab;
10120 }
10121
10122 ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar)
10123 {
10124 if (tab_bar->LastTabItemIdx < 0 || tab_bar->LastTabItemIdx >= tab_bar->Tabs.Size)
10125 return NULL;
10126 return &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10127 }
10128
10129 const char* ImGui::TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10130 {
10131 if (tab->Window)
10132 return (tab->Window->DisplayedName ? tab->Window->DisplayedName : tab->Window->Name);
10133 if (tab->NameOffset == -1)
10134 return "N/A";
10135 IM_ASSERT(tab->NameOffset < tab_bar->TabsNames.Buf.Size);
10136 return tab_bar->TabsNames.Buf.Data + tab->NameOffset;
10137 }
10138
10139 // The purpose of this call is to register tab in advance so we can control their order at the time they appear.
10140 // Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function.
10141 void ImGui::TabBarAddTab(ImGuiTabBar* tab_bar, ImGuiTabItemFlags tab_flags, ImGuiWindow* window)
10142 {
10143 ImGuiContext& g = *GImGui;
10144 IM_ASSERT(TabBarFindTabByID(tab_bar, window->TabId) == NULL);
10145 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)
10146
10147 if (!window->HasCloseButton)
10148 tab_flags |= ImGuiTabItemFlags_NoCloseButton; // Set _NoCloseButton immediately because it will be used for first-frame width calculation.
10149
10150 ImGuiTabItem new_tab;
10151 new_tab.ID = window->TabId;
10152 new_tab.Flags = tab_flags;
10153 new_tab.LastFrameVisible = tab_bar->CurrFrameVisible; // Required so BeginTabBar() doesn't ditch the tab
10154 if (new_tab.LastFrameVisible == -1)
10155 new_tab.LastFrameVisible = g.FrameCount - 1;
10156 new_tab.Window = window; // Required so tab bar layout can compute the tab width before tab submission
10157 tab_bar->Tabs.push_back(new_tab);
10158 }
10159
10160 // The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
10161 void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
10162 {
10163 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
10164 tab_bar->Tabs.erase(tab);
10165 if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
10166 if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
10167 if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
10168 }
10169
10170 // Called on manual closure attempt
10171 void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10172 {
10173 if (tab->Flags & ImGuiTabItemFlags_Button)
10174 return; // A button appended with TabItemButton().
10175
10176 if ((tab->Flags & (ImGuiTabItemFlags_UnsavedDocument | ImGuiTabItemFlags_NoAssumedClosure)) == 0)
10177 {
10178 // This will remove a frame of lag for selecting another tab on closure.
10179 // 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
10180 tab->WantClose = true;
10181 if (tab_bar->VisibleTabId == tab->ID)
10182 {
10183 tab->LastFrameVisible = -1;
10184 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
10185 }
10186 }
10187 else
10188 {
10189 // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup)
10190 if (tab_bar->VisibleTabId != tab->ID)
10191 TabBarQueueFocus(tab_bar, tab);
10192 }
10193 }
10194
10195 static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
10196 {
10197 scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth());
10198 return ImMax(scrolling, 0.0f);
10199 }
10200
10201 // Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys
10202 static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections)
10203 {
10204 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id);
10205 if (tab == NULL)
10206 return;
10207 if (tab->Flags & ImGuiTabItemFlags_SectionMask_)
10208 return;
10209
10210 ImGuiContext& g = *GImGui;
10211 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)
10212 int order = TabBarGetTabOrder(tab_bar, tab);
10213
10214 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
10215 float scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections);
10216
10217 // We make all tabs positions all relative Sections[0].Width to make code simpler
10218 float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f);
10219 float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f);
10220 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
10221 if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width))
10222 {
10223 // Scroll to the left
10224 tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
10225 tab_bar->ScrollingTarget = tab_x1;
10226 }
10227 else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width)
10228 {
10229 // Scroll to the right
10230 tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f);
10231 tab_bar->ScrollingTarget = tab_x2 - scrollable_width;
10232 }
10233 }
10234
10235 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
10236 {
10237 tab_bar->NextSelectedTabId = tab->ID;
10238 }
10239
10240 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name)
10241 {
10242 IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars
10243 ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name, NULL);
10244 tab_bar->NextSelectedTabId = tab_id;
10245 }
10246
10247 void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset)
10248 {
10249 IM_ASSERT(offset != 0);
10250 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
10251 tab_bar->ReorderRequestTabId = tab->ID;
10252 tab_bar->ReorderRequestOffset = (ImS16)offset;
10253 }
10254
10255 void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* src_tab, ImVec2 mouse_pos)
10256 {
10257 ImGuiContext& g = *GImGui;
10258 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
10259 if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0)
10260 return;
10261
10262 const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
10263 const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0);
10264
10265 // Count number of contiguous tabs we are crossing over
10266 const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1;
10267 const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab);
10268 int dst_idx = src_idx;
10269 for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir)
10270 {
10271 // Reordered tabs must share the same section
10272 const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i];
10273 if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder)
10274 break;
10275 if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_))
10276 break;
10277 dst_idx = i;
10278
10279 // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered.
10280 const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x;
10281 const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x;
10282 //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255));
10283 if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2))
10284 break;
10285 }
10286
10287 if (dst_idx != src_idx)
10288 TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx);
10289 }
10290
10291 bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar)
10292 {
10293 ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId);
10294 if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder))
10295 return false;
10296
10297 //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
10298 int tab2_order = TabBarGetTabOrder(tab_bar, tab1) + tab_bar->ReorderRequestOffset;
10299 if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size)
10300 return false;
10301
10302 // Reordered tabs must share the same section
10303 // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too)
10304 ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
10305 if (tab2->Flags & ImGuiTabItemFlags_NoReorder)
10306 return false;
10307 if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_))
10308 return false;
10309
10310 ImGuiTabItem item_tmp = *tab1;
10311 ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2;
10312 ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1;
10313 const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset;
10314 memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem));
10315 *tab2 = item_tmp;
10316
10317 if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
10318 MarkIniSettingsDirty();
10319 return true;
10320 }
10321
10322 static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
10323 {
10324 ImGuiContext& g = *GImGui;
10325 ImGuiWindow* window = g.CurrentWindow;
10326
10327 const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
10328 const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
10329
10330 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
10331 //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));
10332
10333 int select_dir = 0;
10334 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
10335 arrow_col.w *= 0.5f;
10336
10337 PushStyleColor(ImGuiCol_Text, arrow_col);
10338 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
10339 PushItemFlag(ImGuiItemFlags_ButtonRepeat | ImGuiItemFlags_NoNav, true);
10340 const float backup_repeat_delay = g.IO.KeyRepeatDelay;
10341 const float backup_repeat_rate = g.IO.KeyRepeatRate;
10342 g.IO.KeyRepeatDelay = 0.250f;
10343 g.IO.KeyRepeatRate = 0.200f;
10344 float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width);
10345 window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y);
10346 if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
10347 select_dir = -1;
10348 window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y);
10349 if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
10350 select_dir = +1;
10351 PopItemFlag();
10352 PopStyleColor(2);
10353 g.IO.KeyRepeatRate = backup_repeat_rate;
10354 g.IO.KeyRepeatDelay = backup_repeat_delay;
10355
10356 ImGuiTabItem* tab_to_scroll_to = NULL;
10357 if (select_dir != 0)
10358 if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
10359 {
10360 int selected_order = TabBarGetTabOrder(tab_bar, tab_item);
10361 int target_order = selected_order + select_dir;
10362
10363 // Skip tab item buttons until another tab item is found or end is reached
10364 while (tab_to_scroll_to == NULL)
10365 {
10366 // If we are at the end of the list, still scroll to make our tab visible
10367 tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order];
10368
10369 // Cross through buttons
10370 // (even if first/last item is a button, return it so we can update the scroll)
10371 if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button)
10372 {
10373 target_order += select_dir;
10374 selected_order += select_dir;
10375 tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL;
10376 }
10377 }
10378 }
10379 window->DC.CursorPos = backup_cursor_pos;
10380 tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
10381
10382 return tab_to_scroll_to;
10383 }
10384
10385 static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
10386 {
10387 ImGuiContext& g = *GImGui;
10388 ImGuiWindow* window = g.CurrentWindow;
10389
10390 // We use g.Style.FramePadding.y to match the square ArrowButton size
10391 const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
10392 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
10393 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
10394 tab_bar->BarRect.Min.x += tab_list_popup_button_width;
10395
10396 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
10397 arrow_col.w *= 0.5f;
10398 PushStyleColor(ImGuiCol_Text, arrow_col);
10399 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
10400 bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest);
10401 PopStyleColor(2);
10402
10403 ImGuiTabItem* tab_to_select = NULL;
10404 if (open)
10405 {
10406 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
10407 {
10408 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
10409 if (tab->Flags & ImGuiTabItemFlags_Button)
10410 continue;
10411
10412 const char* tab_name = TabBarGetTabName(tab_bar, tab);
10413 if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
10414 tab_to_select = tab;
10415 }
10416 EndCombo();
10417 }
10418
10419 window->DC.CursorPos = backup_cursor_pos;
10420 return tab_to_select;
10421 }
10422
10423 //-------------------------------------------------------------------------
10424 // [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
10425 //-------------------------------------------------------------------------
10426 // - BeginTabItem()
10427 // - EndTabItem()
10428 // - TabItemButton()
10429 // - TabItemEx() [Internal]
10430 // - SetTabItemClosed()
10431 // - TabItemCalcSize() [Internal]
10432 // - TabItemBackground() [Internal]
10433 // - TabItemLabelAndCloseButton() [Internal]
10434 //-------------------------------------------------------------------------
10435
10436 bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
10437 {
10438 ImGuiContext& g = *GImGui;
10439 ImGuiWindow* window = g.CurrentWindow;
10440 if (window->SkipItems)
10441 return false;
10442
10443 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10444 if (tab_bar == NULL)
10445 {
10446 IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!");
10447 return false;
10448 }
10449 IM_ASSERT((flags & ImGuiTabItemFlags_Button) == 0); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!
10450
10451 bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL);
10452 if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
10453 {
10454 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10455 PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
10456 }
10457 return ret;
10458 }
10459
10460 void ImGui::EndTabItem()
10461 {
10462 ImGuiContext& g = *GImGui;
10463 ImGuiWindow* window = g.CurrentWindow;
10464 if (window->SkipItems)
10465 return;
10466
10467 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10468 if (tab_bar == NULL)
10469 {
10470 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10471 return;
10472 }
10473 IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
10474 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
10475 if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
10476 PopID();
10477 }
10478
10479 bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags)
10480 {
10481 ImGuiContext& g = *GImGui;
10482 ImGuiWindow* window = g.CurrentWindow;
10483 if (window->SkipItems)
10484 return false;
10485
10486 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10487 if (tab_bar == NULL)
10488 {
10489 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10490 return false;
10491 }
10492 return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL);
10493 }
10494
10495 void ImGui::TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width)
10496 {
10497 ImGuiContext& g = *GImGui;
10498 ImGuiWindow* window = g.CurrentWindow;
10499 if (window->SkipItems)
10500 return;
10501
10502 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10503 if (tab_bar == NULL)
10504 {
10505 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
10506 return;
10507 }
10508 SetNextItemWidth(width);
10509 TabItemEx(tab_bar, str_id, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder | ImGuiTabItemFlags_Invisible, NULL);
10510 }
10511
10512 bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window)
10513 {
10514 // Layout whole tab bar if not already done
10515 ImGuiContext& g = *GImGui;
10516 if (tab_bar->WantLayout)
10517 {
10518 ImGuiNextItemData backup_next_item_data = g.NextItemData;
10519 TabBarLayout(tab_bar);
10520 g.NextItemData = backup_next_item_data;
10521 }
10522 ImGuiWindow* window = g.CurrentWindow;
10523 if (window->SkipItems)
10524 return false;
10525
10526 const ImGuiStyle& style = g.Style;
10527 const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window);
10528
10529 // If the user called us with *p_open == false, we early out and don't render.
10530 // 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.
10531 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
10532 if (p_open && !*p_open)
10533 {
10534 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
10535 return false;
10536 }
10537
10538 IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button));
10539 IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing
10540
10541 // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)
10542 if (flags & ImGuiTabItemFlags_NoCloseButton)
10543 p_open = NULL;
10544 else if (p_open == NULL)
10545 flags |= ImGuiTabItemFlags_NoCloseButton;
10546
10547 // Acquire tab data
10548 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
10549 bool tab_is_new = false;
10550 if (tab == NULL)
10551 {
10552 tab_bar->Tabs.push_back(ImGuiTabItem());
10553 tab = &tab_bar->Tabs.back();
10554 tab->ID = id;
10555 tab_bar->TabsAddedNew = tab_is_new = true;
10556 }
10557 tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab);
10558
10559 // Calculate tab contents size
10560 ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument));
10561 tab->RequestedWidth = -1.0f;
10562 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
10563 size.x = tab->RequestedWidth = g.NextItemData.Width;
10564 if (tab_is_new)
10565 tab->Width = ImMax(1.0f, size.x);
10566 tab->ContentWidth = size.x;
10567 tab->BeginOrder = tab_bar->TabsActiveCount++;
10568
10569 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
10570 const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
10571 const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
10572 const bool tab_just_unsaved = (flags & ImGuiTabItemFlags_UnsavedDocument) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
10573 const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0;
10574 tab->LastFrameVisible = g.FrameCount;
10575 tab->Flags = flags;
10576 tab->Window = docked_window;
10577
10578 // Append name _WITH_ the zero-terminator
10579 // (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar)
10580 if (docked_window != NULL)
10581 {
10582 IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_DockNode);
10583 tab->NameOffset = -1;
10584 }
10585 else
10586 {
10587 tab->NameOffset = (ImS32)tab_bar->TabsNames.size();
10588 tab_bar->TabsNames.append(label, label + ImStrlen(label) + 1);
10589 }
10590
10591 // Update selected tab
10592 if (!is_tab_button)
10593 {
10594 if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
10595 if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
10596 TabBarQueueFocus(tab_bar, tab); // New tabs gets activated
10597 if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // _SetSelected can only be passed on explicit tab bar
10598 TabBarQueueFocus(tab_bar, tab);
10599 }
10600
10601 // Lock visibility
10602 // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)
10603 bool tab_contents_visible = (tab_bar->VisibleTabId == id);
10604 if (tab_contents_visible)
10605 tab_bar->VisibleTabWasSubmitted = true;
10606
10607 // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
10608 if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing && docked_window == NULL)
10609 if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
10610 tab_contents_visible = true;
10611
10612 // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted
10613 // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'.
10614 if (tab_appearing && (!tab_bar_appearing || tab_is_new))
10615 {
10616 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
10617 if (is_tab_button)
10618 return false;
10619 return tab_contents_visible;
10620 }
10621
10622 if (tab_bar->SelectedTabId == id)
10623 tab->LastFrameSelected = g.FrameCount;
10624
10625 // Backup current layout position
10626 const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
10627
10628 // Layout
10629 const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
10630 size.x = tab->Width;
10631 if (is_central_section)
10632 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_TRUNC(tab->Offset - tab_bar->ScrollingAnim), 0.0f);
10633 else
10634 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f);
10635 ImVec2 pos = window->DC.CursorPos;
10636 ImRect bb(pos, pos + size);
10637
10638 // 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)
10639 const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX);
10640 if (want_clip_rect)
10641 PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true);
10642
10643 ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
10644 ItemSize(bb.GetSize(), style.FramePadding.y);
10645 window->DC.CursorMaxPos = backup_cursor_max_pos;
10646
10647 if (!ItemAdd(bb, id))
10648 {
10649 if (want_clip_rect)
10650 PopClipRect();
10651 window->DC.CursorPos = backup_main_cursor_pos;
10652 return tab_contents_visible;
10653 }
10654
10655 // Click to Select a tab
10656 ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap);
10657 if (g.DragDropActive && !g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW)) // FIXME: May be an opt-in property of the payload to disable this
10658 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
10659 bool hovered, held, pressed;
10660 if (flags & ImGuiTabItemFlags_Invisible)
10661 hovered = held = pressed = false;
10662 else
10663 pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
10664 if (pressed && !is_tab_button)
10665 TabBarQueueFocus(tab_bar, tab);
10666
10667 // Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow()
10668 // will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id.
10669 if (held && docked_window && g.ActiveId == id && g.ActiveIdIsJustActivated)
10670 g.ActiveIdWindow = docked_window;
10671
10672 // Drag and drop a single floating window node moves it
10673 ImGuiDockNode* node = docked_window ? docked_window->DockNode : NULL;
10674 const bool single_floating_window_node = node && node->IsFloatingNode() && (node->Windows.Size == 1);
10675 bool can_undock = true;
10676 if (node) {
10677 if (node->MergedFlags & ImGuiDockNodeFlags_NoMove) can_undock = false;
10678 }
10679 if (held && single_floating_window_node && IsMouseDragging(0, 0.0f))
10680 {
10681 // Move
10682 StartMouseMovingWindow(docked_window);
10683 }
10684 else if (held && !tab_appearing && IsMouseDragging(0) && can_undock)
10685 {
10686 // Drag and drop: re-order tabs
10687 int drag_dir = 0;
10688 float drag_distance_from_edge_x = 0.0f;
10689 if (!g.DragDropActive && ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (docked_window != NULL)))
10690 {
10691 // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
10692 if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
10693 {
10694 drag_dir = -1;
10695 drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x;
10696 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10697 }
10698 else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
10699 {
10700 drag_dir = +1;
10701 drag_distance_from_edge_x = g.IO.MousePos.x - bb.Max.x;
10702 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10703 }
10704 }
10705
10706 // Extract a Dockable window out of it's tab bar
10707 const bool can_undock = docked_window != NULL && !(docked_window->Flags & ImGuiWindowFlags_NoMove) && !(node->MergedFlags & ImGuiDockNodeFlags_NoUndocking);
10708 if (can_undock)
10709 {
10710 // We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar
10711 bool undocking_tab = (g.DragDropActive && g.DragDropPayload.SourceId == id);
10712 if (!undocking_tab) //&& (!g.IO.ConfigDockingWithShift || g.IO.KeyShift)
10713 {
10714 float threshold_base = g.FontSize;
10715 float threshold_x = (threshold_base * 2.2f);
10716 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);
10717 //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]
10718
10719 float distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y);
10720 if (distance_from_edge_y >= threshold_y)
10721 undocking_tab = true;
10722 if (drag_distance_from_edge_x > threshold_x)
10723 if ((drag_dir < 0 && TabBarGetTabOrder(tab_bar, tab) == 0) || (drag_dir > 0 && TabBarGetTabOrder(tab_bar, tab) == tab_bar->Tabs.Size - 1))
10724 undocking_tab = true;
10725 }
10726
10727 if (undocking_tab)
10728 {
10729 // Undock
10730 // FIXME: refactor to share more code with e.g. StartMouseMovingWindow
10731 DockContextQueueUndockWindow(&g, docked_window);
10732 g.MovingWindow = docked_window;
10733 SetActiveID(g.MovingWindow->MoveId, g.MovingWindow);
10734 g.ActiveIdClickOffset -= g.MovingWindow->Pos - bb.Min;
10735 g.ActiveIdNoClearOnFocusLoss = true;
10736 SetActiveIdUsingAllKeyboardKeys();
10737 }
10738 }
10739 }
10740
10741 #if 0
10742 if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth)
10743 {
10744 // Enlarge tab display when hovering
10745 bb.Max.x = bb.Min.x + IM_TRUNC(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)));
10746 display_draw_list = GetForegroundDrawList(window);
10747 TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
10748 }
10749 #endif
10750
10751 // Render tab shape
10752 const bool is_visible = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && !(flags & ImGuiTabItemFlags_Invisible);
10753 if (is_visible)
10754 {
10755 ImDrawList* display_draw_list = window->DrawList;
10756 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));
10757 TabItemBackground(display_draw_list, bb, flags, tab_col);
10758 if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f)
10759 {
10760 // Might be moved to TabItemBackground() ?
10761 ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale);
10762 ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale);
10763 ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline);
10764 if (style.TabRounding > 0.0f)
10765 {
10766 float rounding = style.TabRounding;
10767 display_draw_list->PathArcToFast(tl + ImVec2(+rounding, +rounding), rounding, 7, 9);
10768 display_draw_list->PathArcToFast(tr + ImVec2(-rounding, +rounding), rounding, 9, 11);
10769 display_draw_list->PathStroke(overline_col, 0, style.TabBarOverlineSize);
10770 }
10771 else
10772 {
10773 display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize);
10774 }
10775 }
10776 RenderNavCursor(bb, id);
10777
10778 // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
10779 const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
10780 if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button)
10781 TabBarQueueFocus(tab_bar, tab);
10782
10783 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
10784 flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
10785
10786 // Render tab label, process close button
10787 // tildearrow: `&& can_undock` for what?
10788 const ImGuiID close_button_id = (p_open && can_undock) ? GetIDWithSeed("#CLOSE", NULL, docked_window ? docked_window->ID : id) : 0;
10789 bool just_closed;
10790 bool text_clipped;
10791 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);
10792 if (just_closed && p_open != NULL)
10793 {
10794 *p_open = false;
10795 TabBarCloseTab(tab_bar, tab);
10796 }
10797
10798 // Forward Hovered state so IsItemHovered() after Begin() can work (even though we are technically hovering our parent)
10799 // That state is copied to window->DockTabItemStatusFlags by our caller.
10800 if (docked_window && (hovered || g.HoveredId == close_button_id))
10801 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10802
10803 // Tooltip
10804 // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)
10805 // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)
10806 // FIXME: This is a mess.
10807 // FIXME: We may want disabled tab to still display the tooltip?
10808 if (text_clipped && g.HoveredId == id && !held)
10809 if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))
10810 SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
10811 }
10812
10813 // Restore main window position so user can draw there
10814 if (want_clip_rect)
10815 PopClipRect();
10816 window->DC.CursorPos = backup_main_cursor_pos;
10817
10818 IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected
10819 if (is_tab_button)
10820 return pressed;
10821 return tab_contents_visible;
10822 }
10823
10824 // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
10825 // To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar().
10826 // Tabs closed by the close button will automatically be flagged to avoid this issue.
10827 void ImGui::SetTabItemClosed(const char* label)
10828 {
10829 ImGuiContext& g = *GImGui;
10830 bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
10831 if (is_within_manual_tab_bar)
10832 {
10833 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10834 ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL);
10835 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
10836 tab->WantClose = true; // Will be processed by next call to TabBarLayout()
10837 }
10838 else if (ImGuiWindow* window = FindWindowByName(label))
10839 {
10840 if (window->DockIsActive)
10841 if (ImGuiDockNode* node = window->DockNode)
10842 {
10843 ImGuiID tab_id = TabBarCalcTabID(node->TabBar, label, window);
10844 TabBarRemoveTab(node->TabBar, tab_id);
10845 window->DockTabWantClose = true;
10846 }
10847 }
10848 }
10849
10850 ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker)
10851 {
10852 ImGuiContext& g = *GImGui;
10853 ImVec2 label_size = CalcTextSize(label, NULL, true);
10854 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
10855 if (has_close_button_or_unsaved_marker)
10856 size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
10857 else
10858 size.x += g.Style.FramePadding.x + 1.0f;
10859 return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
10860 }
10861
10862 ImVec2 ImGui::TabItemCalcSize(ImGuiWindow* window)
10863 {
10864 return TabItemCalcSize((window->DisplayedName == NULL ? window->Name : window->DisplayedName), window->HasCloseButton || (window->Flags & ImGuiWindowFlags_UnsavedDocument));
10865 }
10866
10867 void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
10868 {
10869 // 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.
10870 ImGuiContext& g = *GImGui;
10871 const float width = bb.GetWidth();
10872 IM_UNUSED(flags);
10873 IM_ASSERT(width > 0.0f);
10874 const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f));
10875 const float y1 = bb.Min.y + 1.0f;
10876 const float y2 = bb.Max.y - g.Style.TabBarBorderSize;
10877 draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
10878 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
10879 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
10880 draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
10881 draw_list->PathFillConvex(col);
10882 if (g.Style.TabBorderSize > 0.0f)
10883 {
10884 draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
10885 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
10886 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
10887 draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
10888 draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize);
10889 }
10890 }
10891
10892 // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
10893 // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
10894 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)
10895 {
10896 ImGuiContext& g = *GImGui;
10897 ImVec2 label_size = CalcTextSize(label, NULL, true);
10898
10899 if (out_just_closed)
10900 *out_just_closed = false;
10901 if (out_text_clipped)
10902 *out_text_clipped = false;
10903
10904 if (bb.GetWidth() <= 1.0f)
10905 return;
10906
10907 // In Style V2 we'll have full override of all colors per state (e.g. focused, selected)
10908 // But right now if you want to alter text color of tabs this is what you need to do.
10909 #if 0
10910 const float backup_alpha = g.Style.Alpha;
10911 if (!is_contents_visible)
10912 g.Style.Alpha *= 0.7f;
10913 #endif
10914
10915 // Render text label (with clipping + alpha gradient) + unsaved marker
10916 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);
10917
10918 // Return clipped state ignoring the close button
10919 if (out_text_clipped)
10920 {
10921 *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_ellipsis_clip_bb.Max.x;
10922 //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));
10923 }
10924
10925 const float button_sz = g.FontSize;
10926 const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y);
10927
10928 // Close Button & Unsaved Marker
10929 // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
10930 // 'hovered' will be true when hovering the Tab but NOT when hovering the close button
10931 // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
10932 // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
10933 bool close_button_pressed = false;
10934 bool close_button_visible = false;
10935 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.
10936
10937 if (close_button_id != 0)
10938 {
10939 if (is_contents_visible)
10940 close_button_visible = (g.Style.TabCloseButtonMinWidthSelected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthSelected));
10941 else
10942 close_button_visible = (g.Style.TabCloseButtonMinWidthUnselected < 0.0f) ? true : (is_hovered && bb.GetWidth() >= ImMax(button_sz, g.Style.TabCloseButtonMinWidthUnselected));
10943 }
10944
10945 // When tabs/document is unsaved, the unsaved marker takes priority over the close button.
10946 const bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x) && (!close_button_visible || !is_hovered);
10947 if (unsaved_marker_visible)
10948 {
10949 const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz));
10950 RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));
10951 }
10952 else if (close_button_visible)
10953 {
10954 ImGuiLastItemData last_item_backup = g.LastItemData;
10955 if (CloseButton(close_button_id, button_pos))
10956 close_button_pressed = true;
10957 g.LastItemData = last_item_backup;
10958
10959 // Close with middle mouse button
10960 if (is_hovered && !(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
10961 close_button_pressed = true;
10962 }
10963
10964 // This is all rather complicated
10965 // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position)
10966 // 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..
10967 float ellipsis_max_x = text_ellipsis_clip_bb.Max.x;
10968 if (close_button_visible || unsaved_marker_visible)
10969 {
10970 const bool visible_without_hover = unsaved_marker_visible || (is_contents_visible ? g.Style.TabCloseButtonMinWidthSelected : g.Style.TabCloseButtonMinWidthUnselected) < 0.0f;
10971 if (visible_without_hover)
10972 {
10973 text_ellipsis_clip_bb.Max.x -= button_sz * 0.90f;
10974 ellipsis_max_x -= button_sz * 0.90f;
10975 }
10976 else
10977 {
10978 text_ellipsis_clip_bb.Max.x -= button_sz * 1.00f;
10979 }
10980 }
10981 LogSetNextTextDecoration("/", "\\");
10982 RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, ellipsis_max_x, label, NULL, &label_size);
10983
10984 #if 0
10985 if (!is_contents_visible)
10986 g.Style.Alpha = backup_alpha;
10987 #endif
10988
10989 if (out_just_closed)
10990 *out_just_closed = close_button_pressed;
10991 }
10992
10993
10994 #endif // #ifndef IMGUI_DISABLE