Debian Codegraph @

subprojects/imgui-1.91.6/imgui_demo.cpp

raw
1 // dear imgui, v1.91.6
2 // (demo code)
3
4 // Help:
5 // - Read FAQ at http://dearimgui.com/faq
6 // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7 // - Need help integrating Dear ImGui in your codebase?
8 // - Read Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started
9 // - Read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
10 // Read top of imgui.cpp and imgui.h for many details, documentation, comments, links.
11 // Get the latest version at https://github.com/ocornut/imgui
12
13 // How to easily locate code?
14 // - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools
15 // - Browse an online version the demo with code linked to hovered widgets: https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html
16 // - Find a visible string and search for it in the code!
17
18 //---------------------------------------------------
19 // PLEASE DO NOT REMOVE THIS FILE FROM YOUR PROJECT!
20 //---------------------------------------------------
21 // Message to the person tempted to delete this file when integrating Dear ImGui into their codebase:
22 // Think again! It is the most useful reference code that you and other coders will want to refer to and call.
23 // Have the ImGui::ShowDemoWindow() function wired in an always-available debug menu of your game/app!
24 // Also include Metrics! ItemPicker! DebugLog! and other debug features.
25 // Removing this file from your project is hindering access to documentation for everyone in your team,
26 // likely leading you to poorer usage of the library.
27 // Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().
28 // If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be
29 // linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty.
30 // In another situation, whenever you have Dear ImGui available you probably want this to be available for reference.
31 // Thank you,
32 // -Your beloved friend, imgui_demo.cpp (which you won't delete)
33
34 //--------------------------------------------
35 // ABOUT THE MEANING OF THE 'static' KEYWORD:
36 //--------------------------------------------
37 // In this demo code, we frequently use 'static' variables inside functions.
38 // A static variable persists across calls. It is essentially a global variable but declared inside the scope of the function.
39 // Think of "static int n = 0;" as "global int n = 0;" !
40 // We do this IN THE DEMO because we want:
41 // - to gather code and data in the same place.
42 // - to make the demo source code faster to read, faster to change, smaller in size.
43 // - it is also a convenient way of storing simple UI related information as long as your function
44 // doesn't need to be reentrant or used in multiple threads.
45 // This might be a pattern you will want to use in your code, but most of the data you would be working
46 // with in a complex codebase is likely going to be stored outside your functions.
47
48 //-----------------------------------------
49 // ABOUT THE CODING STYLE OF OUR DEMO CODE
50 //-----------------------------------------
51 // The Demo code in this file is designed to be easy to copy-and-paste into your application!
52 // Because of this:
53 // - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace.
54 // - We try to declare static variables in the local scope, as close as possible to the code using them.
55 // - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API.
56 // - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided
57 // by imgui.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional
58 // and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h.
59 // Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp.
60
61 // Navigating this file:
62 // - In Visual Studio: CTRL+comma ("Edit.GoToAll") can follow symbols inside comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
63 // - In Visual Studio w/ Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols inside comments.
64 // - In VS Code, CLion, etc.: CTRL+click can follow symbols inside comments.
65 // - You can search/grep for all sections listed in the index to find the section.
66
67 /*
68
69 Index of this file:
70
71 // [SECTION] Forward Declarations
72 // [SECTION] Helpers
73 // [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos)
74 // [SECTION] Demo Window / ShowDemoWindow()
75 // [SECTION] ShowDemoWindowMenuBar()
76 // [SECTION] ShowDemoWindowWidgets()
77 // [SECTION] ShowDemoWindowMultiSelect()
78 // [SECTION] ShowDemoWindowLayout()
79 // [SECTION] ShowDemoWindowPopups()
80 // [SECTION] ShowDemoWindowTables()
81 // [SECTION] ShowDemoWindowInputs()
82 // [SECTION] About Window / ShowAboutWindow()
83 // [SECTION] Style Editor / ShowStyleEditor()
84 // [SECTION] User Guide / ShowUserGuide()
85 // [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()
86 // [SECTION] Example App: Debug Console / ShowExampleAppConsole()
87 // [SECTION] Example App: Debug Log / ShowExampleAppLog()
88 // [SECTION] Example App: Simple Layout / ShowExampleAppLayout()
89 // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
90 // [SECTION] Example App: Long Text / ShowExampleAppLongText()
91 // [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()
92 // [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()
93 // [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay()
94 // [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen()
95 // [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles()
96 // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
97 // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
98 // [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser()
99
100 */
101
102 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
103 #define _CRT_SECURE_NO_WARNINGS
104 #endif
105
106 #include "imgui.h"
107 #ifndef IMGUI_DISABLE
108
109 // System includes
110 #include <ctype.h> // toupper
111 #include <limits.h> // INT_MIN, INT_MAX
112 #include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf
113 #include <stdio.h> // vsnprintf, sscanf, printf
114 #include <stdlib.h> // NULL, malloc, free, atoi
115 #include <stdint.h> // intptr_t
116 #if !defined(_MSC_VER) || _MSC_VER >= 1800
117 #include <inttypes.h> // PRId64/PRIu64, not avail in some MinGW headers.
118 #endif
119 #ifdef __EMSCRIPTEN__
120 #include <emscripten/version.h> // __EMSCRIPTEN_major__ etc.
121 #endif
122
123 // Visual Studio warnings
124 #ifdef _MSC_VER
125 #pragma warning (disable: 4127) // condition expression is constant
126 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
127 #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
128 #endif
129
130 // Clang/GCC warnings with -Weverything
131 #if defined(__clang__)
132 #if __has_warning("-Wunknown-warning-option")
133 #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!
134 #endif
135 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
136 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
137 #pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code)
138 #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type
139 #pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal
140 #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
141 #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.
142 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
143 #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.
144 #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
145 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
146 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
147 #elif defined(__GNUC__)
148 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
149 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
150 #pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure)
151 #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
152 #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
153 #pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
154 #endif
155
156 // Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)
157 #ifdef _WIN32
158 #define IM_NEWLINE "\r\n"
159 #else
160 #define IM_NEWLINE "\n"
161 #endif
162
163 // Helpers
164 #if defined(_MSC_VER) && !defined(snprintf)
165 #define snprintf _snprintf
166 #endif
167 #if defined(_MSC_VER) && !defined(vsnprintf)
168 #define vsnprintf _vsnprintf
169 #endif
170
171 // Format specifiers for 64-bit values (hasn't been decently standardized before VS2013)
172 #if !defined(PRId64) && defined(_MSC_VER)
173 #define PRId64 "I64d"
174 #define PRIu64 "I64u"
175 #elif !defined(PRId64)
176 #define PRId64 "lld"
177 #define PRIu64 "llu"
178 #endif
179
180 // Helpers macros
181 // We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste,
182 // but making an exception here as those are largely simplifying code...
183 // In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo.
184 #define IM_MIN(A, B) (((A) < (B)) ? (A) : (B))
185 #define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B))
186 #define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V))
187
188 // Enforce cdecl calling convention for functions called by the standard library,
189 // in case compilation settings changed the default to e.g. __vectorcall
190 #ifndef IMGUI_CDECL
191 #ifdef _MSC_VER
192 #define IMGUI_CDECL __cdecl
193 #else
194 #define IMGUI_CDECL
195 #endif
196 #endif
197
198 //-----------------------------------------------------------------------------
199 // [SECTION] Forward Declarations
200 //-----------------------------------------------------------------------------
201
202 #if !defined(IMGUI_DISABLE_DEMO_WINDOWS)
203
204 // Forward Declarations
205 struct ImGuiDemoWindowData;
206 static void ShowExampleAppMainMenuBar();
207 static void ShowExampleAppAssetsBrowser(bool* p_open);
208 static void ShowExampleAppConsole(bool* p_open);
209 static void ShowExampleAppCustomRendering(bool* p_open);
210 static void ShowExampleAppDocuments(bool* p_open);
211 static void ShowExampleAppLog(bool* p_open);
212 static void ShowExampleAppLayout(bool* p_open);
213 static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data);
214 static void ShowExampleAppSimpleOverlay(bool* p_open);
215 static void ShowExampleAppAutoResize(bool* p_open);
216 static void ShowExampleAppConstrainedResize(bool* p_open);
217 static void ShowExampleAppFullscreen(bool* p_open);
218 static void ShowExampleAppLongText(bool* p_open);
219 static void ShowExampleAppWindowTitles(bool* p_open);
220 static void ShowExampleMenuFile();
221
222 // We split the contents of the big ShowDemoWindow() function into smaller functions
223 // (because the link time of very large functions tends to grow non-linearly)
224 static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data);
225 static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data);
226 static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data);
227 static void ShowDemoWindowLayout();
228 static void ShowDemoWindowPopups();
229 static void ShowDemoWindowTables();
230 static void ShowDemoWindowColumns();
231 static void ShowDemoWindowInputs();
232
233 //-----------------------------------------------------------------------------
234 // [SECTION] Helpers
235 //-----------------------------------------------------------------------------
236
237 // Helper to display a little (?) mark which shows a tooltip when hovered.
238 // In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md)
239 static void HelpMarker(const char* desc)
240 {
241 ImGui::TextDisabled("(?)");
242 if (ImGui::BeginItemTooltip())
243 {
244 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
245 ImGui::TextUnformatted(desc);
246 ImGui::PopTextWrapPos();
247 ImGui::EndTooltip();
248 }
249 }
250
251 // Helper to wire demo markers located in code to an interactive browser
252 typedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data);
253 extern ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback;
254 extern void* GImGuiDemoMarkerCallbackUserData;
255 ImGuiDemoMarkerCallback GImGuiDemoMarkerCallback = NULL;
256 void* GImGuiDemoMarkerCallbackUserData = NULL;
257 #define IMGUI_DEMO_MARKER(section) do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0)
258
259 //-----------------------------------------------------------------------------
260 // [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor etc.)
261 //-----------------------------------------------------------------------------
262
263 // Simple representation for a tree
264 // (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.)
265 struct ExampleTreeNode
266 {
267 // Tree structure
268 char Name[28] = "";
269 int UID = 0;
270 ExampleTreeNode* Parent = NULL;
271 ImVector<ExampleTreeNode*> Childs;
272 unsigned short IndexInParent = 0; // Maintaining this allows us to implement linear traversal more easily
273
274 // Leaf Data
275 bool HasData = false; // All leaves have data
276 bool DataMyBool = true;
277 int DataMyInt = 128;
278 ImVec2 DataMyVec2 = ImVec2(0.0f, 3.141592f);
279 };
280
281 // Simple representation of struct metadata/serialization data.
282 // (this is a minimal version of what a typical advanced application may provide)
283 struct ExampleMemberInfo
284 {
285 const char* Name; // Member name
286 ImGuiDataType DataType; // Member type
287 int DataCount; // Member count (1 when scalar)
288 int Offset; // Offset inside parent structure
289 };
290
291 // Metadata description of ExampleTreeNode struct.
292 static const ExampleMemberInfo ExampleTreeNodeMemberInfos[]
293 {
294 { "MyBool", ImGuiDataType_Bool, 1, offsetof(ExampleTreeNode, DataMyBool) },
295 { "MyInt", ImGuiDataType_S32, 1, offsetof(ExampleTreeNode, DataMyInt) },
296 { "MyVec2", ImGuiDataType_Float, 2, offsetof(ExampleTreeNode, DataMyVec2) },
297 };
298
299 static ExampleTreeNode* ExampleTree_CreateNode(const char* name, int uid, ExampleTreeNode* parent)
300 {
301 ExampleTreeNode* node = IM_NEW(ExampleTreeNode);
302 snprintf(node->Name, IM_ARRAYSIZE(node->Name), "%s", name);
303 node->UID = uid;
304 node->Parent = parent;
305 node->IndexInParent = parent ? (unsigned short)parent->Childs.Size : 0;
306 if (parent)
307 parent->Childs.push_back(node);
308 return node;
309 }
310
311 static void ExampleTree_DestroyNode(ExampleTreeNode* node)
312 {
313 for (ExampleTreeNode* child_node : node->Childs)
314 ExampleTree_DestroyNode(child_node);
315 IM_DELETE(node);
316 }
317
318 // Create example tree data
319 // (this allocates _many_ more times than most other code in either Dear ImGui or others demo)
320 static ExampleTreeNode* ExampleTree_CreateDemoTree()
321 {
322 static const char* root_names[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" };
323 const size_t NAME_MAX_LEN = sizeof(ExampleTreeNode::Name);
324 char name_buf[NAME_MAX_LEN];
325 int uid = 0;
326 ExampleTreeNode* node_L0 = ExampleTree_CreateNode("<ROOT>", ++uid, NULL);
327 const int root_items_multiplier = 2;
328 for (int idx_L0 = 0; idx_L0 < IM_ARRAYSIZE(root_names) * root_items_multiplier; idx_L0++)
329 {
330 snprintf(name_buf, IM_ARRAYSIZE(name_buf), "%s %d", root_names[idx_L0 / root_items_multiplier], idx_L0 % root_items_multiplier);
331 ExampleTreeNode* node_L1 = ExampleTree_CreateNode(name_buf, ++uid, node_L0);
332 const int number_of_childs = (int)strlen(node_L1->Name);
333 for (int idx_L1 = 0; idx_L1 < number_of_childs; idx_L1++)
334 {
335 snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Child %d", idx_L1);
336 ExampleTreeNode* node_L2 = ExampleTree_CreateNode(name_buf, ++uid, node_L1);
337 node_L2->HasData = true;
338 if (idx_L1 == 0)
339 {
340 snprintf(name_buf, IM_ARRAYSIZE(name_buf), "Sub-child %d", 0);
341 ExampleTreeNode* node_L3 = ExampleTree_CreateNode(name_buf, ++uid, node_L2);
342 node_L3->HasData = true;
343 }
344 }
345 }
346 return node_L0;
347 }
348
349 //-----------------------------------------------------------------------------
350 // [SECTION] Demo Window / ShowDemoWindow()
351 //-----------------------------------------------------------------------------
352
353 // Data to be shared across different functions of the demo.
354 struct ImGuiDemoWindowData
355 {
356 // Examples Apps (accessible from the "Examples" menu)
357 bool ShowMainMenuBar = false;
358 bool ShowAppAssetsBrowser = false;
359 bool ShowAppConsole = false;
360 bool ShowAppCustomRendering = false;
361 bool ShowAppDocuments = false;
362 bool ShowAppLog = false;
363 bool ShowAppLayout = false;
364 bool ShowAppPropertyEditor = false;
365 bool ShowAppSimpleOverlay = false;
366 bool ShowAppAutoResize = false;
367 bool ShowAppConstrainedResize = false;
368 bool ShowAppFullscreen = false;
369 bool ShowAppLongText = false;
370 bool ShowAppWindowTitles = false;
371
372 // Dear ImGui Tools (accessible from the "Tools" menu)
373 bool ShowMetrics = false;
374 bool ShowDebugLog = false;
375 bool ShowIDStackTool = false;
376 bool ShowStyleEditor = false;
377 bool ShowAbout = false;
378
379 // Other data
380 ExampleTreeNode* DemoTree = NULL;
381
382 ~ImGuiDemoWindowData() { if (DemoTree) ExampleTree_DestroyNode(DemoTree); }
383 };
384
385 // Demonstrate most Dear ImGui features (this is big function!)
386 // You may execute this function to experiment with the UI and understand what it does.
387 // You may then search for keywords in the code when you are interested by a specific feature.
388 void ImGui::ShowDemoWindow(bool* p_open)
389 {
390 // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup
391 // Most functions would normally just assert/crash if the context is missing.
392 IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing Dear ImGui context. Refer to examples app!");
393
394 // Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
395 IMGUI_CHECKVERSION();
396
397 // Stored data
398 static ImGuiDemoWindowData demo_data;
399
400 // Examples Apps (accessible from the "Examples" menu)
401 if (demo_data.ShowMainMenuBar) { ShowExampleAppMainMenuBar(); }
402 if (demo_data.ShowAppDocuments) { ShowExampleAppDocuments(&demo_data.ShowAppDocuments); }
403 if (demo_data.ShowAppAssetsBrowser) { ShowExampleAppAssetsBrowser(&demo_data.ShowAppAssetsBrowser); }
404 if (demo_data.ShowAppConsole) { ShowExampleAppConsole(&demo_data.ShowAppConsole); }
405 if (demo_data.ShowAppCustomRendering) { ShowExampleAppCustomRendering(&demo_data.ShowAppCustomRendering); }
406 if (demo_data.ShowAppLog) { ShowExampleAppLog(&demo_data.ShowAppLog); }
407 if (demo_data.ShowAppLayout) { ShowExampleAppLayout(&demo_data.ShowAppLayout); }
408 if (demo_data.ShowAppPropertyEditor) { ShowExampleAppPropertyEditor(&demo_data.ShowAppPropertyEditor, &demo_data); }
409 if (demo_data.ShowAppSimpleOverlay) { ShowExampleAppSimpleOverlay(&demo_data.ShowAppSimpleOverlay); }
410 if (demo_data.ShowAppAutoResize) { ShowExampleAppAutoResize(&demo_data.ShowAppAutoResize); }
411 if (demo_data.ShowAppConstrainedResize) { ShowExampleAppConstrainedResize(&demo_data.ShowAppConstrainedResize); }
412 if (demo_data.ShowAppFullscreen) { ShowExampleAppFullscreen(&demo_data.ShowAppFullscreen); }
413 if (demo_data.ShowAppLongText) { ShowExampleAppLongText(&demo_data.ShowAppLongText); }
414 if (demo_data.ShowAppWindowTitles) { ShowExampleAppWindowTitles(&demo_data.ShowAppWindowTitles); }
415
416 // Dear ImGui Tools (accessible from the "Tools" menu)
417 if (demo_data.ShowMetrics) { ImGui::ShowMetricsWindow(&demo_data.ShowMetrics); }
418 if (demo_data.ShowDebugLog) { ImGui::ShowDebugLogWindow(&demo_data.ShowDebugLog); }
419 if (demo_data.ShowIDStackTool) { ImGui::ShowIDStackToolWindow(&demo_data.ShowIDStackTool); }
420 if (demo_data.ShowAbout) { ImGui::ShowAboutWindow(&demo_data.ShowAbout); }
421 if (demo_data.ShowStyleEditor)
422 {
423 ImGui::Begin("Dear ImGui Style Editor", &demo_data.ShowStyleEditor);
424 ImGui::ShowStyleEditor();
425 ImGui::End();
426 }
427
428 // Demonstrate the various window flags. Typically you would just use the default!
429 static bool no_titlebar = false;
430 static bool no_scrollbar = false;
431 static bool no_menu = false;
432 static bool no_move = false;
433 static bool no_resize = false;
434 static bool no_collapse = false;
435 static bool no_close = false;
436 static bool no_nav = false;
437 static bool no_background = false;
438 static bool no_bring_to_front = false;
439 static bool unsaved_document = false;
440
441 ImGuiWindowFlags window_flags = 0;
442 if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
443 if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar;
444 if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar;
445 if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
446 if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
447 if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
448 if (no_nav) window_flags |= ImGuiWindowFlags_NoNav;
449 if (no_background) window_flags |= ImGuiWindowFlags_NoBackground;
450 if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
451 if (unsaved_document) window_flags |= ImGuiWindowFlags_UnsavedDocument;
452 if (no_close) p_open = NULL; // Don't pass our bool* to Begin
453
454 // We specify a default position/size in case there's no data in the .ini file.
455 // We only do it to make the demo applications a little more welcoming, but typically this isn't required.
456 const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
457 ImGui::SetNextWindowPos(ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20), ImGuiCond_FirstUseEver);
458 ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);
459
460 // Main body of the Demo window starts here.
461 if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags))
462 {
463 // Early out if the window is collapsed, as an optimization.
464 ImGui::End();
465 return;
466 }
467
468 // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details.
469 ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets.
470 //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f); // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align)
471
472 // Menu Bar
473 ShowDemoWindowMenuBar(&demo_data);
474
475 ImGui::Text("dear imgui says hello! (%s) (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
476 ImGui::Spacing();
477
478 IMGUI_DEMO_MARKER("Help");
479 if (ImGui::CollapsingHeader("Help"))
480 {
481 ImGui::SeparatorText("ABOUT THIS DEMO:");
482 ImGui::BulletText("Sections below are demonstrating many aspects of the library.");
483 ImGui::BulletText("The \"Examples\" menu above leads to more demo contents.");
484 ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n"
485 "and Metrics/Debugger (general purpose Dear ImGui debugging tool).");
486
487 ImGui::SeparatorText("PROGRAMMER GUIDE:");
488 ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!");
489 ImGui::BulletText("See comments in imgui.cpp.");
490 ImGui::BulletText("See example applications in the examples/ folder.");
491 ImGui::BulletText("Read the FAQ at ");
492 ImGui::SameLine(0, 0);
493 ImGui::TextLinkOpenURL("https://www.dearimgui.com/faq/");
494 ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.");
495 ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.");
496
497 ImGui::SeparatorText("USER GUIDE:");
498 ImGui::ShowUserGuide();
499 }
500
501 IMGUI_DEMO_MARKER("Configuration");
502 if (ImGui::CollapsingHeader("Configuration"))
503 {
504 ImGuiIO& io = ImGui::GetIO();
505
506 if (ImGui::TreeNode("Configuration##2"))
507 {
508 ImGui::SeparatorText("General");
509 ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);
510 ImGui::SameLine(); HelpMarker("Enable keyboard controls.");
511 ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
512 ImGui::SameLine(); HelpMarker("Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
513 ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", &io.ConfigFlags, ImGuiConfigFlags_NoMouse);
514 ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable mouse inputs and interactions.");
515
516 // The "NoMouse" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it:
517 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
518 {
519 if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f)
520 {
521 ImGui::SameLine();
522 ImGui::Text("<<PRESS SPACE TO DISABLE>>");
523 }
524 // Prevent both being checked
525 if (ImGui::IsKeyPressed(ImGuiKey_Space) || (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard))
526 io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse;
527 }
528
529 ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);
530 ImGui::SameLine(); HelpMarker("Instruct backend to not alter mouse cursor shape and visibility.");
531 ImGui::CheckboxFlags("io.ConfigFlags: NoKeyboard", &io.ConfigFlags, ImGuiConfigFlags_NoKeyboard);
532 ImGui::SameLine(); HelpMarker("Instruct dear imgui to disable keyboard inputs and interactions.");
533
534 ImGui::Checkbox("io.ConfigInputTrickleEventQueue", &io.ConfigInputTrickleEventQueue);
535 ImGui::SameLine(); HelpMarker("Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.");
536 ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
537 ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
538
539 ImGui::SeparatorText("Keyboard/Gamepad Navigation");
540 ImGui::Checkbox("io.ConfigNavSwapGamepadButtons", &io.ConfigNavSwapGamepadButtons);
541 ImGui::Checkbox("io.ConfigNavMoveSetMousePos", &io.ConfigNavMoveSetMousePos);
542 ImGui::SameLine(); HelpMarker("Directional/tabbing navigation teleports the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is difficult");
543 ImGui::Checkbox("io.ConfigNavCaptureKeyboard", &io.ConfigNavCaptureKeyboard);
544 ImGui::Checkbox("io.ConfigNavEscapeClearFocusItem", &io.ConfigNavEscapeClearFocusItem);
545 ImGui::SameLine(); HelpMarker("Pressing Escape clears focused item.");
546 ImGui::Checkbox("io.ConfigNavEscapeClearFocusWindow", &io.ConfigNavEscapeClearFocusWindow);
547 ImGui::SameLine(); HelpMarker("Pressing Escape clears focused window.");
548 ImGui::Checkbox("io.ConfigNavCursorVisibleAuto", &io.ConfigNavCursorVisibleAuto);
549 ImGui::SameLine(); HelpMarker("Using directional navigation key makes the cursor visible. Mouse click hides the cursor.");
550 ImGui::Checkbox("io.ConfigNavCursorVisibleAlways", &io.ConfigNavCursorVisibleAlways);
551 ImGui::SameLine(); HelpMarker("Navigation cursor is always visible.");
552
553 ImGui::SeparatorText("Windows");
554 ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
555 ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.");
556 ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
557 ImGui::Checkbox("io.ConfigWindowsCopyContentsWithCtrlC", &io.ConfigWindowsCopyContentsWithCtrlC); // [EXPERIMENTAL]
558 ImGui::SameLine(); HelpMarker("*EXPERIMENTAL* CTRL+C copy the contents of focused window into the clipboard.\n\nExperimental because:\n- (1) has known issues with nested Begin/End pairs.\n- (2) text output quality varies.\n- (3) text output is in submission order rather than spatial order.");
559 ImGui::Checkbox("io.ConfigScrollbarScrollByPage", &io.ConfigScrollbarScrollByPage);
560 ImGui::SameLine(); HelpMarker("Enable scrolling page by page when clicking outside the scrollbar grab.\nWhen disabled, always scroll to clicked location.\nWhen enabled, Shift+Click scrolls to clicked location.");
561
562 ImGui::SeparatorText("Widgets");
563 ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
564 ImGui::SameLine(); HelpMarker("Enable blinking cursor (optional as some users consider it to be distracting).");
565 ImGui::Checkbox("io.ConfigInputTextEnterKeepActive", &io.ConfigInputTextEnterKeepActive);
566 ImGui::SameLine(); HelpMarker("Pressing Enter will keep item active and select contents (single-line only).");
567 ImGui::Checkbox("io.ConfigDragClickToInputText", &io.ConfigDragClickToInputText);
568 ImGui::SameLine(); HelpMarker("Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).");
569 ImGui::Checkbox("io.ConfigMacOSXBehaviors", &io.ConfigMacOSXBehaviors);
570 ImGui::SameLine(); HelpMarker("Swap Cmd<>Ctrl keys, enable various MacOS style behaviors.");
571 ImGui::Text("Also see Style->Rendering for rendering options.");
572
573 // Also read: https://github.com/ocornut/imgui/wiki/Error-Handling
574 ImGui::SeparatorText("Error Handling");
575
576 ImGui::Checkbox("io.ConfigErrorRecovery", &io.ConfigErrorRecovery);
577 ImGui::SameLine(); HelpMarker(
578 "Options to configure how we handle recoverable errors.\n"
579 "- Error recovery is not perfect nor guaranteed! It is a feature to ease development.\n"
580 "- You not are not supposed to rely on it in the course of a normal application run.\n"
581 "- Possible usage: facilitate recovery from errors triggered from a scripting language or after specific exceptions handlers.\n"
582 "- Always ensure that on programmers seat you have at minimum Asserts or Tooltips enabled when making direct imgui API call!"
583 "Otherwise it would severely hinder your ability to catch and correct mistakes!");
584 ImGui::Checkbox("io.ConfigErrorRecoveryEnableAssert", &io.ConfigErrorRecoveryEnableAssert);
585 ImGui::Checkbox("io.ConfigErrorRecoveryEnableDebugLog", &io.ConfigErrorRecoveryEnableDebugLog);
586 ImGui::Checkbox("io.ConfigErrorRecoveryEnableTooltip", &io.ConfigErrorRecoveryEnableTooltip);
587 if (!io.ConfigErrorRecoveryEnableAssert && !io.ConfigErrorRecoveryEnableDebugLog && !io.ConfigErrorRecoveryEnableTooltip)
588 io.ConfigErrorRecoveryEnableAssert = io.ConfigErrorRecoveryEnableDebugLog = io.ConfigErrorRecoveryEnableTooltip = true;
589
590 // Also read: https://github.com/ocornut/imgui/wiki/Debug-Tools
591 ImGui::SeparatorText("Debug");
592 ImGui::Checkbox("io.ConfigDebugIsDebuggerPresent", &io.ConfigDebugIsDebuggerPresent);
593 ImGui::SameLine(); HelpMarker("Enable various tools calling IM_DEBUG_BREAK().\n\nRequires a debugger being attached, otherwise IM_DEBUG_BREAK() options will appear to crash your application.");
594 ImGui::Checkbox("io.ConfigDebugHighlightIdConflicts", &io.ConfigDebugHighlightIdConflicts);
595 ImGui::SameLine(); HelpMarker("Highlight and show an error message when multiple items have conflicting identifiers.");
596 ImGui::BeginDisabled();
597 ImGui::Checkbox("io.ConfigDebugBeginReturnValueOnce", &io.ConfigDebugBeginReturnValueOnce);
598 ImGui::EndDisabled();
599 ImGui::SameLine(); HelpMarker("First calls to Begin()/BeginChild() will return false.\n\nTHIS OPTION IS DISABLED because it needs to be set at application boot-time to make sense. Showing the disabled option is a way to make this feature easier to discover.");
600 ImGui::Checkbox("io.ConfigDebugBeginReturnValueLoop", &io.ConfigDebugBeginReturnValueLoop);
601 ImGui::SameLine(); HelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
602 ImGui::Checkbox("io.ConfigDebugIgnoreFocusLoss", &io.ConfigDebugIgnoreFocusLoss);
603 ImGui::SameLine(); HelpMarker("Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data.");
604 ImGui::Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
605 ImGui::SameLine(); HelpMarker("Option to save .ini data with extra comments (particularly helpful for Docking, but makes saving slower).");
606
607 ImGui::TreePop();
608 ImGui::Spacing();
609 }
610
611 IMGUI_DEMO_MARKER("Configuration/Backend Flags");
612 if (ImGui::TreeNode("Backend Flags"))
613 {
614 HelpMarker(
615 "Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\n"
616 "Here we expose them as read-only fields to avoid breaking interactions with your backend.");
617
618 // FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright?
619 ImGui::BeginDisabled();
620 ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", &io.BackendFlags, ImGuiBackendFlags_HasGamepad);
621 ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors);
622 ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", &io.BackendFlags, ImGuiBackendFlags_HasSetMousePos);
623 ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", &io.BackendFlags, ImGuiBackendFlags_RendererHasVtxOffset);
624 ImGui::EndDisabled();
625
626 ImGui::TreePop();
627 ImGui::Spacing();
628 }
629
630 IMGUI_DEMO_MARKER("Configuration/Style");
631 if (ImGui::TreeNode("Style"))
632 {
633 ImGui::Checkbox("Style Editor", &demo_data.ShowStyleEditor);
634 ImGui::SameLine();
635 HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function.");
636 ImGui::TreePop();
637 ImGui::Spacing();
638 }
639
640 IMGUI_DEMO_MARKER("Configuration/Capture, Logging");
641 if (ImGui::TreeNode("Capture/Logging"))
642 {
643 HelpMarker(
644 "The logging API redirects all text output so you can easily capture the content of "
645 "a window or a block. Tree nodes can be automatically expanded.\n"
646 "Try opening any of the contents below in this window and then click one of the \"Log To\" button.");
647 ImGui::LogButtons();
648
649 HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output.");
650 if (ImGui::Button("Copy \"Hello, world!\" to clipboard"))
651 {
652 ImGui::LogToClipboard();
653 ImGui::LogText("Hello, world!");
654 ImGui::LogFinish();
655 }
656 ImGui::TreePop();
657 }
658 }
659
660 IMGUI_DEMO_MARKER("Window options");
661 if (ImGui::CollapsingHeader("Window options"))
662 {
663 if (ImGui::BeginTable("split", 3))
664 {
665 ImGui::TableNextColumn(); ImGui::Checkbox("No titlebar", &no_titlebar);
666 ImGui::TableNextColumn(); ImGui::Checkbox("No scrollbar", &no_scrollbar);
667 ImGui::TableNextColumn(); ImGui::Checkbox("No menu", &no_menu);
668 ImGui::TableNextColumn(); ImGui::Checkbox("No move", &no_move);
669 ImGui::TableNextColumn(); ImGui::Checkbox("No resize", &no_resize);
670 ImGui::TableNextColumn(); ImGui::Checkbox("No collapse", &no_collapse);
671 ImGui::TableNextColumn(); ImGui::Checkbox("No close", &no_close);
672 ImGui::TableNextColumn(); ImGui::Checkbox("No nav", &no_nav);
673 ImGui::TableNextColumn(); ImGui::Checkbox("No background", &no_background);
674 ImGui::TableNextColumn(); ImGui::Checkbox("No bring to front", &no_bring_to_front);
675 ImGui::TableNextColumn(); ImGui::Checkbox("Unsaved document", &unsaved_document);
676 ImGui::EndTable();
677 }
678 }
679
680 // All demo contents
681 ShowDemoWindowWidgets(&demo_data);
682 ShowDemoWindowLayout();
683 ShowDemoWindowPopups();
684 ShowDemoWindowTables();
685 ShowDemoWindowInputs();
686
687 // End of ShowDemoWindow()
688 ImGui::PopItemWidth();
689 ImGui::End();
690 }
691
692 //-----------------------------------------------------------------------------
693 // [SECTION] ShowDemoWindowMenuBar()
694 //-----------------------------------------------------------------------------
695
696 static void ShowDemoWindowMenuBar(ImGuiDemoWindowData* demo_data)
697 {
698 IMGUI_DEMO_MARKER("Menu");
699 if (ImGui::BeginMenuBar())
700 {
701 if (ImGui::BeginMenu("Menu"))
702 {
703 IMGUI_DEMO_MARKER("Menu/File");
704 ShowExampleMenuFile();
705 ImGui::EndMenu();
706 }
707 if (ImGui::BeginMenu("Examples"))
708 {
709 IMGUI_DEMO_MARKER("Menu/Examples");
710 ImGui::MenuItem("Main menu bar", NULL, &demo_data->ShowMainMenuBar);
711
712 ImGui::SeparatorText("Mini apps");
713 ImGui::MenuItem("Assets Browser", NULL, &demo_data->ShowAppAssetsBrowser);
714 ImGui::MenuItem("Console", NULL, &demo_data->ShowAppConsole);
715 ImGui::MenuItem("Custom rendering", NULL, &demo_data->ShowAppCustomRendering);
716 ImGui::MenuItem("Documents", NULL, &demo_data->ShowAppDocuments);
717 ImGui::MenuItem("Log", NULL, &demo_data->ShowAppLog);
718 ImGui::MenuItem("Property editor", NULL, &demo_data->ShowAppPropertyEditor);
719 ImGui::MenuItem("Simple layout", NULL, &demo_data->ShowAppLayout);
720 ImGui::MenuItem("Simple overlay", NULL, &demo_data->ShowAppSimpleOverlay);
721
722 ImGui::SeparatorText("Concepts");
723 ImGui::MenuItem("Auto-resizing window", NULL, &demo_data->ShowAppAutoResize);
724 ImGui::MenuItem("Constrained-resizing window", NULL, &demo_data->ShowAppConstrainedResize);
725 ImGui::MenuItem("Fullscreen window", NULL, &demo_data->ShowAppFullscreen);
726 ImGui::MenuItem("Long text display", NULL, &demo_data->ShowAppLongText);
727 ImGui::MenuItem("Manipulating window titles", NULL, &demo_data->ShowAppWindowTitles);
728
729 ImGui::EndMenu();
730 }
731 //if (ImGui::MenuItem("MenuItem")) {} // You can also use MenuItem() inside a menu bar!
732 if (ImGui::BeginMenu("Tools"))
733 {
734 IMGUI_DEMO_MARKER("Menu/Tools");
735 ImGuiIO& io = ImGui::GetIO();
736 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
737 const bool has_debug_tools = true;
738 #else
739 const bool has_debug_tools = false;
740 #endif
741 ImGui::MenuItem("Metrics/Debugger", NULL, &demo_data->ShowMetrics, has_debug_tools);
742 ImGui::MenuItem("Debug Log", NULL, &demo_data->ShowDebugLog, has_debug_tools);
743 ImGui::MenuItem("ID Stack Tool", NULL, &demo_data->ShowIDStackTool, has_debug_tools);
744 bool is_debugger_present = io.ConfigDebugIsDebuggerPresent;
745 if (ImGui::MenuItem("Item Picker", NULL, false, has_debug_tools && is_debugger_present))
746 ImGui::DebugStartItemPicker();
747 if (!is_debugger_present)
748 ImGui::SetItemTooltip("Requires io.ConfigDebugIsDebuggerPresent=true to be set.\n\nWe otherwise disable the menu option to avoid casual users crashing the application.\n\nYou can however always access the Item Picker in Metrics->Tools.");
749 ImGui::MenuItem("Style Editor", NULL, &demo_data->ShowStyleEditor);
750 ImGui::MenuItem("About Dear ImGui", NULL, &demo_data->ShowAbout);
751
752 ImGui::SeparatorText("Debug Options");
753 ImGui::MenuItem("Highlight ID Conflicts", NULL, &io.ConfigDebugHighlightIdConflicts, has_debug_tools);
754 ImGui::EndMenu();
755 }
756 ImGui::EndMenuBar();
757 }
758 }
759
760 //-----------------------------------------------------------------------------
761 // [SECTION] ShowDemoWindowWidgets()
762 //-----------------------------------------------------------------------------
763
764 static void ShowDemoWindowWidgets(ImGuiDemoWindowData* demo_data)
765 {
766 IMGUI_DEMO_MARKER("Widgets");
767 //ImGui::SetNextItemOpen(true, ImGuiCond_Once);
768 if (!ImGui::CollapsingHeader("Widgets"))
769 return;
770
771 static bool disable_all = false; // The Checkbox for that is inside the "Disabled" section at the bottom
772 if (disable_all)
773 ImGui::BeginDisabled();
774
775 IMGUI_DEMO_MARKER("Widgets/Basic");
776 if (ImGui::TreeNode("Basic"))
777 {
778 ImGui::SeparatorText("General");
779
780 IMGUI_DEMO_MARKER("Widgets/Basic/Button");
781 static int clicked = 0;
782 if (ImGui::Button("Button"))
783 clicked++;
784 if (clicked & 1)
785 {
786 ImGui::SameLine();
787 ImGui::Text("Thanks for clicking me!");
788 }
789
790 IMGUI_DEMO_MARKER("Widgets/Basic/Checkbox");
791 static bool check = true;
792 ImGui::Checkbox("checkbox", &check);
793
794 IMGUI_DEMO_MARKER("Widgets/Basic/RadioButton");
795 static int e = 0;
796 ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine();
797 ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine();
798 ImGui::RadioButton("radio c", &e, 2);
799
800 // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
801 IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Colored)");
802 for (int i = 0; i < 7; i++)
803 {
804 if (i > 0)
805 ImGui::SameLine();
806 ImGui::PushID(i);
807 ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f));
808 ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f));
809 ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f));
810 ImGui::Button("Click");
811 ImGui::PopStyleColor(3);
812 ImGui::PopID();
813 }
814
815 // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements
816 // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!)
817 // See 'Demo->Layout->Text Baseline Alignment' for details.
818 ImGui::AlignTextToFramePadding();
819 ImGui::Text("Hold to repeat:");
820 ImGui::SameLine();
821
822 // Arrow buttons with Repeater
823 IMGUI_DEMO_MARKER("Widgets/Basic/Buttons (Repeating)");
824 static int counter = 0;
825 float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
826 ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
827 if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; }
828 ImGui::SameLine(0.0f, spacing);
829 if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; }
830 ImGui::PopItemFlag();
831 ImGui::SameLine();
832 ImGui::Text("%d", counter);
833
834 ImGui::Button("Tooltip");
835 ImGui::SetItemTooltip("I am a tooltip");
836
837 ImGui::LabelText("label", "Value");
838
839 ImGui::SeparatorText("Inputs");
840
841 {
842 // To wire InputText() with std::string or any other custom string type,
843 // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
844 IMGUI_DEMO_MARKER("Widgets/Basic/InputText");
845 static char str0[128] = "Hello, world!";
846 ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
847 ImGui::SameLine(); HelpMarker(
848 "USER:\n"
849 "Hold SHIFT or use mouse to select text.\n"
850 "CTRL+Left/Right to word jump.\n"
851 "CTRL+A or Double-Click to select all.\n"
852 "CTRL+X,CTRL+C,CTRL+V clipboard.\n"
853 "CTRL+Z,CTRL+Y undo/redo.\n"
854 "ESCAPE to revert.\n\n"
855 "PROGRAMMER:\n"
856 "You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() "
857 "to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated "
858 "in imgui_demo.cpp).");
859
860 static char str1[128] = "";
861 ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1));
862
863 IMGUI_DEMO_MARKER("Widgets/Basic/InputInt, InputFloat");
864 static int i0 = 123;
865 ImGui::InputInt("input int", &i0);
866
867 static float f0 = 0.001f;
868 ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f");
869
870 static double d0 = 999999.00000001;
871 ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f");
872
873 static float f1 = 1.e10f;
874 ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e");
875 ImGui::SameLine(); HelpMarker(
876 "You can input value using the scientific notation,\n"
877 " e.g. \"1e+8\" becomes \"100000000\".");
878
879 static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
880 ImGui::InputFloat3("input float3", vec4a);
881 }
882
883 ImGui::SeparatorText("Drags");
884
885 {
886 IMGUI_DEMO_MARKER("Widgets/Basic/DragInt, DragFloat");
887 static int i1 = 50, i2 = 42, i3 = 128;
888 ImGui::DragInt("drag int", &i1, 1);
889 ImGui::SameLine(); HelpMarker(
890 "Click and drag to edit value.\n"
891 "Hold SHIFT/ALT for faster/slower edit.\n"
892 "Double-click or CTRL+click to input value.");
893 ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp);
894 ImGui::DragInt("drag int wrap 100..200", &i3, 1, 100, 200, "%d", ImGuiSliderFlags_WrapAround);
895
896 static float f1 = 1.00f, f2 = 0.0067f;
897 ImGui::DragFloat("drag float", &f1, 0.005f);
898 ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns");
899 //ImGui::DragFloat("drag wrap -1..1", &f3, 0.005f, -1.0f, 1.0f, NULL, ImGuiSliderFlags_WrapAround);
900 }
901
902 ImGui::SeparatorText("Sliders");
903
904 {
905 IMGUI_DEMO_MARKER("Widgets/Basic/SliderInt, SliderFloat");
906 static int i1 = 0;
907 ImGui::SliderInt("slider int", &i1, -1, 3);
908 ImGui::SameLine(); HelpMarker("CTRL+click to input value.");
909
910 static float f1 = 0.123f, f2 = 0.0f;
911 ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
912 ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic);
913
914 IMGUI_DEMO_MARKER("Widgets/Basic/SliderAngle");
915 static float angle = 0.0f;
916 ImGui::SliderAngle("slider angle", &angle);
917
918 // Using the format string to display a name instead of an integer.
919 // Here we completely omit '%d' from the format string, so it'll only display a name.
920 // This technique can also be used with DragInt().
921 IMGUI_DEMO_MARKER("Widgets/Basic/Slider (enum)");
922 enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT };
923 static int elem = Element_Fire;
924 const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" };
925 const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown";
926 ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name); // Use ImGuiSliderFlags_NoInput flag to disable CTRL+Click here.
927 ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.");
928 }
929
930 ImGui::SeparatorText("Selectors/Pickers");
931
932 {
933 IMGUI_DEMO_MARKER("Widgets/Basic/ColorEdit3, ColorEdit4");
934 static float col1[3] = { 1.0f, 0.0f, 0.2f };
935 static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
936 ImGui::ColorEdit3("color 1", col1);
937 ImGui::SameLine(); HelpMarker(
938 "Click on the color square to open a color picker.\n"
939 "Click and hold to use drag and drop.\n"
940 "Right-click on the color square to show options.\n"
941 "CTRL+click on individual component to input value.\n");
942
943 ImGui::ColorEdit4("color 2", col2);
944 }
945
946 {
947 // Using the _simplified_ one-liner Combo() api here
948 // See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api.
949 IMGUI_DEMO_MARKER("Widgets/Basic/Combo");
950 const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" };
951 static int item_current = 0;
952 ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items));
953 ImGui::SameLine(); HelpMarker(
954 "Using the simplified one-liner Combo API here.\n"
955 "Refer to the \"Combo\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API.");
956 }
957
958 {
959 // Using the _simplified_ one-liner ListBox() api here
960 // See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api.
961 IMGUI_DEMO_MARKER("Widgets/Basic/ListBox");
962 const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
963 static int item_current = 1;
964 ImGui::ListBox("listbox", &item_current, items, IM_ARRAYSIZE(items), 4);
965 ImGui::SameLine(); HelpMarker(
966 "Using the simplified one-liner ListBox API here.\n"
967 "Refer to the \"List boxes\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API.");
968 }
969
970 ImGui::TreePop();
971 }
972
973 IMGUI_DEMO_MARKER("Widgets/Tooltips");
974 if (ImGui::TreeNode("Tooltips"))
975 {
976 // Tooltips are windows following the mouse. They do not take focus away.
977 ImGui::SeparatorText("General");
978
979 // Typical use cases:
980 // - Short-form (text only): SetItemTooltip("Hello");
981 // - Short-form (any contents): if (BeginItemTooltip()) { Text("Hello"); EndTooltip(); }
982
983 // - Full-form (text only): if (IsItemHovered(...)) { SetTooltip("Hello"); }
984 // - Full-form (any contents): if (IsItemHovered(...) && BeginTooltip()) { Text("Hello"); EndTooltip(); }
985
986 HelpMarker(
987 "Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\n"
988 "We provide a helper SetItemTooltip() function to perform the two with standards flags.");
989
990 ImVec2 sz = ImVec2(-FLT_MIN, 0.0f);
991
992 ImGui::Button("Basic", sz);
993 ImGui::SetItemTooltip("I am a tooltip");
994
995 ImGui::Button("Fancy", sz);
996 if (ImGui::BeginItemTooltip())
997 {
998 ImGui::Text("I am a fancy tooltip");
999 static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
1000 ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
1001 ImGui::Text("Sin(time) = %f", sinf((float)ImGui::GetTime()));
1002 ImGui::EndTooltip();
1003 }
1004
1005 ImGui::SeparatorText("Always On");
1006
1007 // Showcase NOT relying on a IsItemHovered() to emit a tooltip.
1008 // Here the tooltip is always emitted when 'always_on == true'.
1009 static int always_on = 0;
1010 ImGui::RadioButton("Off", &always_on, 0);
1011 ImGui::SameLine();
1012 ImGui::RadioButton("Always On (Simple)", &always_on, 1);
1013 ImGui::SameLine();
1014 ImGui::RadioButton("Always On (Advanced)", &always_on, 2);
1015 if (always_on == 1)
1016 ImGui::SetTooltip("I am following you around.");
1017 else if (always_on == 2 && ImGui::BeginTooltip())
1018 {
1019 ImGui::ProgressBar(sinf((float)ImGui::GetTime()) * 0.5f + 0.5f, ImVec2(ImGui::GetFontSize() * 25, 0.0f));
1020 ImGui::EndTooltip();
1021 }
1022
1023 ImGui::SeparatorText("Custom");
1024
1025 HelpMarker(
1026 "Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize"
1027 "tooltip activation details across your application. You may however decide to use custom"
1028 "flags for a specific tooltip instance.");
1029
1030 // The following examples are passed for documentation purpose but may not be useful to most users.
1031 // Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from
1032 // 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used.
1033 // With default settings, ImGuiHoveredFlags_ForTooltip is equivalent to ImGuiHoveredFlags_DelayShort + ImGuiHoveredFlags_Stationary.
1034 ImGui::Button("Manual", sz);
1035 if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip))
1036 ImGui::SetTooltip("I am a manually emitted tooltip.");
1037
1038 ImGui::Button("DelayNone", sz);
1039 if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNone))
1040 ImGui::SetTooltip("I am a tooltip with no delay.");
1041
1042 ImGui::Button("DelayShort", sz);
1043 if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_NoSharedDelay))
1044 ImGui::SetTooltip("I am a tooltip with a short delay (%0.2f sec).", ImGui::GetStyle().HoverDelayShort);
1045
1046 ImGui::Button("DelayLong", sz);
1047 if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_NoSharedDelay))
1048 ImGui::SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui::GetStyle().HoverDelayNormal);
1049
1050 ImGui::Button("Stationary", sz);
1051 if (ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary))
1052 ImGui::SetTooltip("I am a tooltip requiring mouse to be stationary before activating.");
1053
1054 // Using ImGuiHoveredFlags_ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav',
1055 // which default value include the ImGuiHoveredFlags_AllowWhenDisabled flag.
1056 ImGui::BeginDisabled();
1057 ImGui::Button("Disabled item", sz);
1058 if (ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip))
1059 ImGui::SetTooltip("I am a a tooltip for a disabled item.");
1060 ImGui::EndDisabled();
1061
1062 ImGui::TreePop();
1063 }
1064
1065 // Testing ImGuiOnceUponAFrame helper.
1066 //static ImGuiOnceUponAFrame once;
1067 //for (int i = 0; i < 5; i++)
1068 // if (once)
1069 // ImGui::Text("This will be displayed only once.");
1070
1071 IMGUI_DEMO_MARKER("Widgets/Tree Nodes");
1072 if (ImGui::TreeNode("Tree Nodes"))
1073 {
1074 IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Basic trees");
1075 if (ImGui::TreeNode("Basic trees"))
1076 {
1077 for (int i = 0; i < 5; i++)
1078 {
1079 // Use SetNextItemOpen() so set the default state of a node to be open. We could
1080 // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing!
1081 if (i == 0)
1082 ImGui::SetNextItemOpen(true, ImGuiCond_Once);
1083
1084 // Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict.
1085 // An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode((void*)(intptr_t)i, ...)',
1086 // aka generate a dummy pointer-sized value to be hashed. The demo below uses that technique. Both are fine.
1087 ImGui::PushID(i);
1088 if (ImGui::TreeNode("", "Child %d", i))
1089 {
1090 ImGui::Text("blah blah");
1091 ImGui::SameLine();
1092 if (ImGui::SmallButton("button")) {}
1093 ImGui::TreePop();
1094 }
1095 ImGui::PopID();
1096 }
1097 ImGui::TreePop();
1098 }
1099
1100 IMGUI_DEMO_MARKER("Widgets/Tree Nodes/Advanced, with Selectable nodes");
1101 if (ImGui::TreeNode("Advanced, with Selectable nodes"))
1102 {
1103 HelpMarker(
1104 "This is a more typical looking tree with selectable nodes.\n"
1105 "Click to select, CTRL+Click to toggle, click on arrows or double-click to open.");
1106 static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth;
1107 static bool align_label_with_current_x_position = false;
1108 static bool test_drag_and_drop = false;
1109 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", &base_flags, ImGuiTreeNodeFlags_OpenOnArrow);
1110 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick);
1111 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node.");
1112 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &base_flags, ImGuiTreeNodeFlags_SpanFullWidth);
1113 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &base_flags, ImGuiTreeNodeFlags_SpanTextWidth); ImGui::SameLine(); HelpMarker("Reduce hit area to the text label and a bit of margin.");
1114 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &base_flags, ImGuiTreeNodeFlags_SpanAllColumns); ImGui::SameLine(); HelpMarker("For use in Tables only.");
1115 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_AllowOverlap", &base_flags, ImGuiTreeNodeFlags_AllowOverlap);
1116 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)");
1117 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsBackHere", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsBackHere);
1118 ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position);
1119 ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop);
1120 ImGui::Text("Hello!");
1121 if (align_label_with_current_x_position)
1122 ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
1123
1124 // 'selection_mask' is dumb representation of what may be user-side selection state.
1125 // You may retain selection state inside or outside your objects in whatever format you see fit.
1126 // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end
1127 /// of the loop. May be a pointer to your own node type, etc.
1128 static int selection_mask = (1 << 2);
1129 int node_clicked = -1;
1130 for (int i = 0; i < 6; i++)
1131 {
1132 // Disable the default "open on single-click behavior" + set Selected flag according to our selection.
1133 // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection.
1134 ImGuiTreeNodeFlags node_flags = base_flags;
1135 const bool is_selected = (selection_mask & (1 << i)) != 0;
1136 if (is_selected)
1137 node_flags |= ImGuiTreeNodeFlags_Selected;
1138 if (i < 3)
1139 {
1140 // Items 0..2 are Tree Node
1141 bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
1142 if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen())
1143 node_clicked = i;
1144 if (test_drag_and_drop && ImGui::BeginDragDropSource())
1145 {
1146 ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
1147 ImGui::Text("This is a drag and drop source");
1148 ImGui::EndDragDropSource();
1149 }
1150 if (i == 2 && (base_flags & ImGuiTreeNodeFlags_SpanTextWidth))
1151 {
1152 // Item 2 has an additional inline button to help demonstrate SpanTextWidth.
1153 ImGui::SameLine();
1154 if (ImGui::SmallButton("button")) {}
1155 }
1156 if (node_open)
1157 {
1158 ImGui::BulletText("Blah blah\nBlah Blah");
1159 ImGui::SameLine();
1160 ImGui::SmallButton("Button");
1161 ImGui::TreePop();
1162 }
1163 }
1164 else
1165 {
1166 // Items 3..5 are Tree Leaves
1167 // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can
1168 // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text().
1169 node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet
1170 ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i);
1171 if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen())
1172 node_clicked = i;
1173 if (test_drag_and_drop && ImGui::BeginDragDropSource())
1174 {
1175 ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
1176 ImGui::Text("This is a drag and drop source");
1177 ImGui::EndDragDropSource();
1178 }
1179 }
1180 }
1181 if (node_clicked != -1)
1182 {
1183 // Update selection state
1184 // (process outside of tree loop to avoid visual inconsistencies during the clicking frame)
1185 if (ImGui::GetIO().KeyCtrl)
1186 selection_mask ^= (1 << node_clicked); // CTRL+click to toggle
1187 else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection
1188 selection_mask = (1 << node_clicked); // Click to single-select
1189 }
1190 if (align_label_with_current_x_position)
1191 ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
1192 ImGui::TreePop();
1193 }
1194 ImGui::TreePop();
1195 }
1196
1197 IMGUI_DEMO_MARKER("Widgets/Collapsing Headers");
1198 if (ImGui::TreeNode("Collapsing Headers"))
1199 {
1200 static bool closable_group = true;
1201 ImGui::Checkbox("Show 2nd header", &closable_group);
1202 if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None))
1203 {
1204 ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
1205 for (int i = 0; i < 5; i++)
1206 ImGui::Text("Some content %d", i);
1207 }
1208 if (ImGui::CollapsingHeader("Header with a close button", &closable_group))
1209 {
1210 ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
1211 for (int i = 0; i < 5; i++)
1212 ImGui::Text("More content %d", i);
1213 }
1214 /*
1215 if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet))
1216 ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
1217 */
1218 ImGui::TreePop();
1219 }
1220
1221 IMGUI_DEMO_MARKER("Widgets/Bullets");
1222 if (ImGui::TreeNode("Bullets"))
1223 {
1224 ImGui::BulletText("Bullet point 1");
1225 ImGui::BulletText("Bullet point 2\nOn multiple lines");
1226 if (ImGui::TreeNode("Tree node"))
1227 {
1228 ImGui::BulletText("Another bullet point");
1229 ImGui::TreePop();
1230 }
1231 ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)");
1232 ImGui::Bullet(); ImGui::SmallButton("Button");
1233 ImGui::TreePop();
1234 }
1235
1236 IMGUI_DEMO_MARKER("Widgets/Text");
1237 if (ImGui::TreeNode("Text"))
1238 {
1239 IMGUI_DEMO_MARKER("Widgets/Text/Colored Text");
1240 if (ImGui::TreeNode("Colorful Text"))
1241 {
1242 // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.
1243 ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink");
1244 ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow");
1245 ImGui::TextDisabled("Disabled");
1246 ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle.");
1247 ImGui::TreePop();
1248 }
1249
1250 IMGUI_DEMO_MARKER("Widgets/Text/Word Wrapping");
1251 if (ImGui::TreeNode("Word Wrapping"))
1252 {
1253 // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
1254 ImGui::TextWrapped(
1255 "This text should automatically wrap on the edge of the window. The current implementation "
1256 "for text wrapping follows simple rules suitable for English and possibly other languages.");
1257 ImGui::Spacing();
1258
1259 static float wrap_width = 200.0f;
1260 ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
1261
1262 ImDrawList* draw_list = ImGui::GetWindowDrawList();
1263 for (int n = 0; n < 2; n++)
1264 {
1265 ImGui::Text("Test paragraph %d:", n);
1266 ImVec2 pos = ImGui::GetCursorScreenPos();
1267 ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y);
1268 ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight());
1269 ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
1270 if (n == 0)
1271 ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width);
1272 else
1273 ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh");
1274
1275 // Draw actual text bounding box, following by marker of our expected limit (should not overlap!)
1276 draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));
1277 draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255));
1278 ImGui::PopTextWrapPos();
1279 }
1280
1281 ImGui::TreePop();
1282 }
1283
1284 IMGUI_DEMO_MARKER("Widgets/Text/UTF-8 Text");
1285 if (ImGui::TreeNode("UTF-8 Text"))
1286 {
1287 // UTF-8 test with Japanese characters
1288 // (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.)
1289 // - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8
1290 // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you
1291 // can save your source files as 'UTF-8 without signature').
1292 // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8
1293 // CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants.
1294 // Don't do this in your application! Please use u8"text in any language" in your application!
1295 // Note that characters values are preserved even by InputText() if the font cannot be displayed,
1296 // so you can safely copy & paste garbled characters into another application.
1297 ImGui::TextWrapped(
1298 "CJK text will only appear if the font was loaded with the appropriate CJK character ranges. "
1299 "Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. "
1300 "Read docs/FONTS.md for details.");
1301 ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)");
1302 ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)");
1303 static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e";
1304 //static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis
1305 ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
1306 ImGui::TreePop();
1307 }
1308 ImGui::TreePop();
1309 }
1310
1311 IMGUI_DEMO_MARKER("Widgets/Images");
1312 if (ImGui::TreeNode("Images"))
1313 {
1314 ImGuiIO& io = ImGui::GetIO();
1315 ImGui::TextWrapped(
1316 "Below we are displaying the font texture (which is the only texture we have access to in this demo). "
1317 "Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. "
1318 "Hover the texture for a zoomed view!");
1319
1320 // Below we are displaying the font texture because it is the only texture we have access to inside the demo!
1321 // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that
1322 // will be passed to the rendering backend via the ImDrawCmd structure.
1323 // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top
1324 // of their respective source file to specify what they expect to be stored in ImTextureID, for example:
1325 // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer
1326 // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc.
1327 // More:
1328 // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers
1329 // to ImGui::Image(), and gather width/height through your own functions, etc.
1330 // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer,
1331 // it will help you debug issues if you are confused about it.
1332 // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().
1333 // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md
1334 // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
1335 ImTextureID my_tex_id = io.Fonts->TexID;
1336 float my_tex_w = (float)io.Fonts->TexWidth;
1337 float my_tex_h = (float)io.Fonts->TexHeight;
1338 {
1339 static bool use_text_color_for_tint = false;
1340 ImGui::Checkbox("Use Text Color for Tint", &use_text_color_for_tint);
1341 ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h);
1342 ImVec2 pos = ImGui::GetCursorScreenPos();
1343 ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left
1344 ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right
1345 ImVec4 tint_col = use_text_color_for_tint ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
1346 ImVec4 border_col = ImGui::GetStyleColorVec4(ImGuiCol_Border);
1347 ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col);
1348 if (ImGui::BeginItemTooltip())
1349 {
1350 float region_sz = 32.0f;
1351 float region_x = io.MousePos.x - pos.x - region_sz * 0.5f;
1352 float region_y = io.MousePos.y - pos.y - region_sz * 0.5f;
1353 float zoom = 4.0f;
1354 if (region_x < 0.0f) { region_x = 0.0f; }
1355 else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; }
1356 if (region_y < 0.0f) { region_y = 0.0f; }
1357 else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; }
1358 ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y);
1359 ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz);
1360 ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h);
1361 ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h);
1362 ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col);
1363 ImGui::EndTooltip();
1364 }
1365 }
1366
1367 IMGUI_DEMO_MARKER("Widgets/Images/Textured buttons");
1368 ImGui::TextWrapped("And now some textured buttons..");
1369 static int pressed_count = 0;
1370 for (int i = 0; i < 8; i++)
1371 {
1372 // UV coordinates are often (0.0f, 0.0f) and (1.0f, 1.0f) to display an entire textures.
1373 // Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation.
1374 // Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
1375 ImGui::PushID(i);
1376 if (i > 0)
1377 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(i - 1.0f, i - 1.0f));
1378 ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible
1379 ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left
1380 ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h); // UV coordinates for (32,32) in our texture
1381 ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background
1382 ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
1383 if (ImGui::ImageButton("", my_tex_id, size, uv0, uv1, bg_col, tint_col))
1384 pressed_count += 1;
1385 if (i > 0)
1386 ImGui::PopStyleVar();
1387 ImGui::PopID();
1388 ImGui::SameLine();
1389 }
1390 ImGui::NewLine();
1391 ImGui::Text("Pressed %d times.", pressed_count);
1392 ImGui::TreePop();
1393 }
1394
1395 IMGUI_DEMO_MARKER("Widgets/Combo");
1396 if (ImGui::TreeNode("Combo"))
1397 {
1398 // Combo Boxes are also called "Dropdown" in other systems
1399 // Expose flags as checkbox for the demo
1400 static ImGuiComboFlags flags = 0;
1401 ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", &flags, ImGuiComboFlags_PopupAlignLeft);
1402 ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo");
1403 if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", &flags, ImGuiComboFlags_NoArrowButton))
1404 flags &= ~ImGuiComboFlags_NoPreview; // Clear incompatible flags
1405 if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", &flags, ImGuiComboFlags_NoPreview))
1406 flags &= ~(ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_WidthFitPreview); // Clear incompatible flags
1407 if (ImGui::CheckboxFlags("ImGuiComboFlags_WidthFitPreview", &flags, ImGuiComboFlags_WidthFitPreview))
1408 flags &= ~ImGuiComboFlags_NoPreview;
1409
1410 // Override default popup height
1411 if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightSmall", &flags, ImGuiComboFlags_HeightSmall))
1412 flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightSmall);
1413 if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightRegular", &flags, ImGuiComboFlags_HeightRegular))
1414 flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightRegular);
1415 if (ImGui::CheckboxFlags("ImGuiComboFlags_HeightLargest", &flags, ImGuiComboFlags_HeightLargest))
1416 flags &= ~(ImGuiComboFlags_HeightMask_ & ~ImGuiComboFlags_HeightLargest);
1417
1418 // Using the generic BeginCombo() API, you have full control over how to display the combo contents.
1419 // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
1420 // stored in the object itself, etc.)
1421 const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
1422 static int item_selected_idx = 0; // Here we store our selection data as an index.
1423
1424 // Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[])
1425 const char* combo_preview_value = items[item_selected_idx];
1426
1427 if (ImGui::BeginCombo("combo 1", combo_preview_value, flags))
1428 {
1429 for (int n = 0; n < IM_ARRAYSIZE(items); n++)
1430 {
1431 const bool is_selected = (item_selected_idx == n);
1432 if (ImGui::Selectable(items[n], is_selected))
1433 item_selected_idx = n;
1434
1435 // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
1436 if (is_selected)
1437 ImGui::SetItemDefaultFocus();
1438 }
1439 ImGui::EndCombo();
1440 }
1441
1442 ImGui::Spacing();
1443 ImGui::SeparatorText("One-liner variants");
1444 HelpMarker("Flags above don't apply to this section.");
1445
1446 // Simplified one-liner Combo() API, using values packed in a single constant string
1447 // This is a convenience for when the selection set is small and known at compile-time.
1448 static int item_current_2 = 0;
1449 ImGui::Combo("combo 2 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
1450
1451 // Simplified one-liner Combo() using an array of const char*
1452 // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control.
1453 static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview
1454 ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items));
1455
1456 // Simplified one-liner Combo() using an accessor function
1457 static int item_current_4 = 0;
1458 ImGui::Combo("combo 4 (function)", &item_current_4, [](void* data, int n) { return ((const char**)data)[n]; }, items, IM_ARRAYSIZE(items));
1459
1460 ImGui::TreePop();
1461 }
1462
1463 IMGUI_DEMO_MARKER("Widgets/List Boxes");
1464 if (ImGui::TreeNode("List boxes"))
1465 {
1466 // BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild()
1467 // using the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
1468 // You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild()
1469 // to always be called (inconsistent with BeginListBox()/EndListBox()).
1470
1471 // Using the generic BeginListBox() API, you have full control over how to display the combo contents.
1472 // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
1473 // stored in the object itself, etc.)
1474 const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
1475 static int item_selected_idx = 0; // Here we store our selected data as an index.
1476
1477 static bool item_highlight = false;
1478 int item_highlighted_idx = -1; // Here we store our highlighted data as an index.
1479 ImGui::Checkbox("Highlight hovered item in second listbox", &item_highlight);
1480
1481 if (ImGui::BeginListBox("listbox 1"))
1482 {
1483 for (int n = 0; n < IM_ARRAYSIZE(items); n++)
1484 {
1485 const bool is_selected = (item_selected_idx == n);
1486 if (ImGui::Selectable(items[n], is_selected))
1487 item_selected_idx = n;
1488
1489 if (item_highlight && ImGui::IsItemHovered())
1490 item_highlighted_idx = n;
1491
1492 // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
1493 if (is_selected)
1494 ImGui::SetItemDefaultFocus();
1495 }
1496 ImGui::EndListBox();
1497 }
1498 ImGui::SameLine(); HelpMarker("Here we are sharing selection state between both boxes.");
1499
1500 // Custom size: use all width, 5 items tall
1501 ImGui::Text("Full-width:");
1502 if (ImGui::BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing())))
1503 {
1504 for (int n = 0; n < IM_ARRAYSIZE(items); n++)
1505 {
1506 bool is_selected = (item_selected_idx == n);
1507 ImGuiSelectableFlags flags = (item_highlighted_idx == n) ? ImGuiSelectableFlags_Highlight : 0;
1508 if (ImGui::Selectable(items[n], is_selected, flags))
1509 item_selected_idx = n;
1510
1511 // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
1512 if (is_selected)
1513 ImGui::SetItemDefaultFocus();
1514 }
1515 ImGui::EndListBox();
1516 }
1517
1518 ImGui::TreePop();
1519 }
1520
1521 IMGUI_DEMO_MARKER("Widgets/Selectables");
1522 //ImGui::SetNextItemOpen(true, ImGuiCond_Once);
1523 if (ImGui::TreeNode("Selectables"))
1524 {
1525 // Selectable() has 2 overloads:
1526 // - The one taking "bool selected" as a read-only selection information.
1527 // When Selectable() has been clicked it returns true and you can alter selection state accordingly.
1528 // - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases)
1529 // The earlier is more flexible, as in real application your selection may be stored in many different ways
1530 // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc).
1531 IMGUI_DEMO_MARKER("Widgets/Selectables/Basic");
1532 if (ImGui::TreeNode("Basic"))
1533 {
1534 static bool selection[5] = { false, true, false, false };
1535 ImGui::Selectable("1. I am selectable", &selection[0]);
1536 ImGui::Selectable("2. I am selectable", &selection[1]);
1537 ImGui::Selectable("3. I am selectable", &selection[2]);
1538 if (ImGui::Selectable("4. I am double clickable", selection[3], ImGuiSelectableFlags_AllowDoubleClick))
1539 if (ImGui::IsMouseDoubleClicked(0))
1540 selection[3] = !selection[3];
1541 ImGui::TreePop();
1542 }
1543
1544 IMGUI_DEMO_MARKER("Widgets/Selectables/Rendering more items on the same line");
1545 if (ImGui::TreeNode("Rendering more items on the same line"))
1546 {
1547 // (1) Using SetNextItemAllowOverlap()
1548 // (2) Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically.
1549 static bool selected[3] = { false, false, false };
1550 ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(); ImGui::SmallButton("Link 1");
1551 ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(); ImGui::SmallButton("Link 2");
1552 ImGui::SetNextItemAllowOverlap(); ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(); ImGui::SmallButton("Link 3");
1553 ImGui::TreePop();
1554 }
1555
1556 IMGUI_DEMO_MARKER("Widgets/Selectables/In Tables");
1557 if (ImGui::TreeNode("In Tables"))
1558 {
1559 static bool selected[10] = {};
1560
1561 if (ImGui::BeginTable("split1", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))
1562 {
1563 for (int i = 0; i < 10; i++)
1564 {
1565 char label[32];
1566 sprintf(label, "Item %d", i);
1567 ImGui::TableNextColumn();
1568 ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap
1569 }
1570 ImGui::EndTable();
1571 }
1572 ImGui::Spacing();
1573 if (ImGui::BeginTable("split2", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))
1574 {
1575 for (int i = 0; i < 10; i++)
1576 {
1577 char label[32];
1578 sprintf(label, "Item %d", i);
1579 ImGui::TableNextRow();
1580 ImGui::TableNextColumn();
1581 ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns);
1582 ImGui::TableNextColumn();
1583 ImGui::Text("Some other contents");
1584 ImGui::TableNextColumn();
1585 ImGui::Text("123456");
1586 }
1587 ImGui::EndTable();
1588 }
1589 ImGui::TreePop();
1590 }
1591
1592 IMGUI_DEMO_MARKER("Widgets/Selectables/Grid");
1593 if (ImGui::TreeNode("Grid"))
1594 {
1595 static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
1596
1597 // Add in a bit of silly fun...
1598 const float time = (float)ImGui::GetTime();
1599 const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected...
1600 if (winning_state)
1601 ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f)));
1602
1603 for (int y = 0; y < 4; y++)
1604 for (int x = 0; x < 4; x++)
1605 {
1606 if (x > 0)
1607 ImGui::SameLine();
1608 ImGui::PushID(y * 4 + x);
1609 if (ImGui::Selectable("Sailor", selected[y][x] != 0, 0, ImVec2(50, 50)))
1610 {
1611 // Toggle clicked cell + toggle neighbors
1612 selected[y][x] ^= 1;
1613 if (x > 0) { selected[y][x - 1] ^= 1; }
1614 if (x < 3) { selected[y][x + 1] ^= 1; }
1615 if (y > 0) { selected[y - 1][x] ^= 1; }
1616 if (y < 3) { selected[y + 1][x] ^= 1; }
1617 }
1618 ImGui::PopID();
1619 }
1620
1621 if (winning_state)
1622 ImGui::PopStyleVar();
1623 ImGui::TreePop();
1624 }
1625 IMGUI_DEMO_MARKER("Widgets/Selectables/Alignment");
1626 if (ImGui::TreeNode("Alignment"))
1627 {
1628 HelpMarker(
1629 "By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item "
1630 "basis using PushStyleVar(). You'll probably want to always keep your default situation to "
1631 "left-align otherwise it becomes difficult to layout multiple items on a same line");
1632 static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true };
1633 for (int y = 0; y < 3; y++)
1634 {
1635 for (int x = 0; x < 3; x++)
1636 {
1637 ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f);
1638 char name[32];
1639 sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y);
1640 if (x > 0) ImGui::SameLine();
1641 ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment);
1642 ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80));
1643 ImGui::PopStyleVar();
1644 }
1645 }
1646 ImGui::TreePop();
1647 }
1648 ImGui::TreePop();
1649 }
1650
1651 ShowDemoWindowMultiSelect(demo_data);
1652
1653 // To wire InputText() with std::string or any other custom string type,
1654 // see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
1655 IMGUI_DEMO_MARKER("Widgets/Text Input");
1656 if (ImGui::TreeNode("Text Input"))
1657 {
1658 IMGUI_DEMO_MARKER("Widgets/Text Input/Multi-line Text Input");
1659 if (ImGui::TreeNode("Multi-line Text Input"))
1660 {
1661 // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize
1662 // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings.
1663 static char text[1024 * 16] =
1664 "/*\n"
1665 " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n"
1666 " the hexadecimal encoding of one offending instruction,\n"
1667 " more formally, the invalid operand with locked CMPXCHG8B\n"
1668 " instruction bug, is a design flaw in the majority of\n"
1669 " Intel Pentium, Pentium MMX, and Pentium OverDrive\n"
1670 " processors (all in the P5 microarchitecture).\n"
1671 "*/\n\n"
1672 "label:\n"
1673 "\tlock cmpxchg8b eax\n";
1674
1675 static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;
1676 HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include <string> in here)");
1677 ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly);
1678 ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput);
1679 ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets.");
1680 ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine);
1681 ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags);
1682 ImGui::TreePop();
1683 }
1684
1685 IMGUI_DEMO_MARKER("Widgets/Text Input/Filtered Text Input");
1686 if (ImGui::TreeNode("Filtered Text Input"))
1687 {
1688 struct TextFilters
1689 {
1690 // Modify character input by altering 'data->Eventchar' (ImGuiInputTextFlags_CallbackCharFilter callback)
1691 static int FilterCasingSwap(ImGuiInputTextCallbackData* data)
1692 {
1693 if (data->EventChar >= 'a' && data->EventChar <= 'z') { data->EventChar -= 'a' - 'A'; } // Lowercase becomes uppercase
1694 else if (data->EventChar >= 'A' && data->EventChar <= 'Z') { data->EventChar += 'a' - 'A'; } // Uppercase becomes lowercase
1695 return 0;
1696 }
1697
1698 // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out)
1699 static int FilterImGuiLetters(ImGuiInputTextCallbackData* data)
1700 {
1701 if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar))
1702 return 0;
1703 return 1;
1704 }
1705 };
1706
1707 static char buf1[32] = ""; ImGui::InputText("default", buf1, 32);
1708 static char buf2[32] = ""; ImGui::InputText("decimal", buf2, 32, ImGuiInputTextFlags_CharsDecimal);
1709 static char buf3[32] = ""; ImGui::InputText("hexadecimal", buf3, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
1710 static char buf4[32] = ""; ImGui::InputText("uppercase", buf4, 32, ImGuiInputTextFlags_CharsUppercase);
1711 static char buf5[32] = ""; ImGui::InputText("no blank", buf5, 32, ImGuiInputTextFlags_CharsNoBlank);
1712 static char buf6[32] = ""; ImGui::InputText("casing swap", buf6, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterCasingSwap); // Use CharFilter callback to replace characters.
1713 static char buf7[32] = ""; ImGui::InputText("\"imgui\"", buf7, 32, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); // Use CharFilter callback to disable some characters.
1714 ImGui::TreePop();
1715 }
1716
1717 IMGUI_DEMO_MARKER("Widgets/Text Input/Password input");
1718 if (ImGui::TreeNode("Password Input"))
1719 {
1720 static char password[64] = "password123";
1721 ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
1722 ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
1723 ImGui::InputTextWithHint("password (w/ hint)", "<password>", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
1724 ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password));
1725 ImGui::TreePop();
1726 }
1727
1728 IMGUI_DEMO_MARKER("Widgets/Text Input/Completion, History, Edit Callbacks");
1729 if (ImGui::TreeNode("Completion, History, Edit Callbacks"))
1730 {
1731 struct Funcs
1732 {
1733 static int MyCallback(ImGuiInputTextCallbackData* data)
1734 {
1735 if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion)
1736 {
1737 data->InsertChars(data->CursorPos, "..");
1738 }
1739 else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory)
1740 {
1741 if (data->EventKey == ImGuiKey_UpArrow)
1742 {
1743 data->DeleteChars(0, data->BufTextLen);
1744 data->InsertChars(0, "Pressed Up!");
1745 data->SelectAll();
1746 }
1747 else if (data->EventKey == ImGuiKey_DownArrow)
1748 {
1749 data->DeleteChars(0, data->BufTextLen);
1750 data->InsertChars(0, "Pressed Down!");
1751 data->SelectAll();
1752 }
1753 }
1754 else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)
1755 {
1756 // Toggle casing of first character
1757 char c = data->Buf[0];
1758 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32;
1759 data->BufDirty = true;
1760
1761 // Increment a counter
1762 int* p_int = (int*)data->UserData;
1763 *p_int = *p_int + 1;
1764 }
1765 return 0;
1766 }
1767 };
1768 static char buf1[64];
1769 ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback);
1770 ImGui::SameLine(); HelpMarker(
1771 "Here we append \"..\" each time Tab is pressed. "
1772 "See 'Examples>Console' for a more meaningful demonstration of using this callback.");
1773
1774 static char buf2[64];
1775 ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback);
1776 ImGui::SameLine(); HelpMarker(
1777 "Here we replace and select text each time Up/Down are pressed. "
1778 "See 'Examples>Console' for a more meaningful demonstration of using this callback.");
1779
1780 static char buf3[64];
1781 static int edit_count = 0;
1782 ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count);
1783 ImGui::SameLine(); HelpMarker(
1784 "Here we toggle the casing of the first character on every edit + count edits.");
1785 ImGui::SameLine(); ImGui::Text("(%d)", edit_count);
1786
1787 ImGui::TreePop();
1788 }
1789
1790 IMGUI_DEMO_MARKER("Widgets/Text Input/Resize Callback");
1791 if (ImGui::TreeNode("Resize Callback"))
1792 {
1793 // To wire InputText() with std::string or any other custom string type,
1794 // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper
1795 // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string.
1796 HelpMarker(
1797 "Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n"
1798 "See misc/cpp/imgui_stdlib.h for an implementation of this for std::string.");
1799 struct Funcs
1800 {
1801 static int MyResizeCallback(ImGuiInputTextCallbackData* data)
1802 {
1803 if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)
1804 {
1805 ImVector<char>* my_str = (ImVector<char>*)data->UserData;
1806 IM_ASSERT(my_str->begin() == data->Buf);
1807 my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1
1808 data->Buf = my_str->begin();
1809 }
1810 return 0;
1811 }
1812
1813 // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace.
1814 // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)'
1815 static bool MyInputTextMultiline(const char* label, ImVector<char>* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0)
1816 {
1817 IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0);
1818 return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str);
1819 }
1820 };
1821
1822 // For this demo we are using ImVector as a string container.
1823 // Note that because we need to store a terminating zero character, our size/capacity are 1 more
1824 // than usually reported by a typical string class.
1825 static ImVector<char> my_str;
1826 if (my_str.empty())
1827 my_str.push_back(0);
1828 Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16));
1829 ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity());
1830 ImGui::TreePop();
1831 }
1832
1833 IMGUI_DEMO_MARKER("Widgets/Text Input/Eliding, Alignment");
1834 if (ImGui::TreeNode("Eliding, Alignment"))
1835 {
1836 static char buf1[128] = "/path/to/some/folder/with/long/filename.cpp";
1837 static ImGuiInputTextFlags flags = ImGuiInputTextFlags_ElideLeft;
1838 ImGui::CheckboxFlags("ImGuiInputTextFlags_ElideLeft", &flags, ImGuiInputTextFlags_ElideLeft);
1839 ImGui::InputText("Path", buf1, IM_ARRAYSIZE(buf1), flags);
1840 ImGui::TreePop();
1841 }
1842
1843 IMGUI_DEMO_MARKER("Widgets/Text Input/Miscellaneous");
1844 if (ImGui::TreeNode("Miscellaneous"))
1845 {
1846 static char buf1[16];
1847 static ImGuiInputTextFlags flags = ImGuiInputTextFlags_EscapeClearsAll;
1848 ImGui::CheckboxFlags("ImGuiInputTextFlags_EscapeClearsAll", &flags, ImGuiInputTextFlags_EscapeClearsAll);
1849 ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly);
1850 ImGui::CheckboxFlags("ImGuiInputTextFlags_NoUndoRedo", &flags, ImGuiInputTextFlags_NoUndoRedo);
1851 ImGui::InputText("Hello", buf1, IM_ARRAYSIZE(buf1), flags);
1852 ImGui::TreePop();
1853 }
1854
1855 ImGui::TreePop();
1856 }
1857
1858 // Tabs
1859 IMGUI_DEMO_MARKER("Widgets/Tabs");
1860 if (ImGui::TreeNode("Tabs"))
1861 {
1862 IMGUI_DEMO_MARKER("Widgets/Tabs/Basic");
1863 if (ImGui::TreeNode("Basic"))
1864 {
1865 ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
1866 if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
1867 {
1868 if (ImGui::BeginTabItem("Avocado"))
1869 {
1870 ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah");
1871 ImGui::EndTabItem();
1872 }
1873 if (ImGui::BeginTabItem("Broccoli"))
1874 {
1875 ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah");
1876 ImGui::EndTabItem();
1877 }
1878 if (ImGui::BeginTabItem("Cucumber"))
1879 {
1880 ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah");
1881 ImGui::EndTabItem();
1882 }
1883 ImGui::EndTabBar();
1884 }
1885 ImGui::Separator();
1886 ImGui::TreePop();
1887 }
1888
1889 IMGUI_DEMO_MARKER("Widgets/Tabs/Advanced & Close Button");
1890 if (ImGui::TreeNode("Advanced & Close Button"))
1891 {
1892 // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
1893 static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;
1894 ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", &tab_bar_flags, ImGuiTabBarFlags_Reorderable);
1895 ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);
1896 ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
1897 ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
1898 ImGui::CheckboxFlags("ImGuiTabBarFlags_DrawSelectedOverline", &tab_bar_flags, ImGuiTabBarFlags_DrawSelectedOverline);
1899 if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
1900 tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
1901 if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
1902 tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
1903 if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
1904 tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
1905
1906 // Tab Bar
1907 ImGui::AlignTextToFramePadding();
1908 ImGui::Text("Opened:");
1909 const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" };
1910 static bool opened[4] = { true, true, true, true }; // Persistent user state
1911 for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
1912 {
1913 ImGui::SameLine();
1914 ImGui::Checkbox(names[n], &opened[n]);
1915 }
1916
1917 // Passing a bool* to BeginTabItem() is similar to passing one to Begin():
1918 // the underlying bool will be set to false when the tab is closed.
1919 if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
1920 {
1921 for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
1922 if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None))
1923 {
1924 ImGui::Text("This is the %s tab!", names[n]);
1925 if (n & 1)
1926 ImGui::Text("I am an odd tab.");
1927 ImGui::EndTabItem();
1928 }
1929 ImGui::EndTabBar();
1930 }
1931 ImGui::Separator();
1932 ImGui::TreePop();
1933 }
1934
1935 IMGUI_DEMO_MARKER("Widgets/Tabs/TabItemButton & Leading-Trailing flags");
1936 if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags"))
1937 {
1938 static ImVector<int> active_tabs;
1939 static int next_tab_id = 0;
1940 if (next_tab_id == 0) // Initialize with some default tabs
1941 for (int i = 0; i < 3; i++)
1942 active_tabs.push_back(next_tab_id++);
1943
1944 // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together.
1945 // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags...
1946 // but they tend to make more sense together)
1947 static bool show_leading_button = true;
1948 static bool show_trailing_button = true;
1949 ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button);
1950 ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button);
1951
1952 // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs
1953 static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown;
1954 ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
1955 if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
1956 tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
1957 if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
1958 tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
1959
1960 if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
1961 {
1962 // Demo a Leading TabItemButton(): click the "?" button to open a menu
1963 if (show_leading_button)
1964 if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip))
1965 ImGui::OpenPopup("MyHelpMenu");
1966 if (ImGui::BeginPopup("MyHelpMenu"))
1967 {
1968 ImGui::Selectable("Hello!");
1969 ImGui::EndPopup();
1970 }
1971
1972 // Demo Trailing Tabs: click the "+" button to add a new tab.
1973 // (In your app you may want to use a font icon instead of the "+")
1974 // We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags_Trailing flag it will always appear at the end.
1975 if (show_trailing_button)
1976 if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip))
1977 active_tabs.push_back(next_tab_id++); // Add new tab
1978
1979 // Submit our regular tabs
1980 for (int n = 0; n < active_tabs.Size; )
1981 {
1982 bool open = true;
1983 char name[16];
1984 snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]);
1985 if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None))
1986 {
1987 ImGui::Text("This is the %s tab!", name);
1988 ImGui::EndTabItem();
1989 }
1990
1991 if (!open)
1992 active_tabs.erase(active_tabs.Data + n);
1993 else
1994 n++;
1995 }
1996
1997 ImGui::EndTabBar();
1998 }
1999 ImGui::Separator();
2000 ImGui::TreePop();
2001 }
2002 ImGui::TreePop();
2003 }
2004
2005 // Plot/Graph widgets are not very good.
2006 // Consider using a third-party library such as ImPlot: https://github.com/epezent/implot
2007 // (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions)
2008 IMGUI_DEMO_MARKER("Widgets/Plotting");
2009 if (ImGui::TreeNode("Plotting"))
2010 {
2011 static bool animate = true;
2012 ImGui::Checkbox("Animate", &animate);
2013
2014 // Plot as lines and plot as histogram
2015 static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
2016 ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
2017 ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f));
2018 //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!");
2019
2020 // Fill an array of contiguous float values to plot
2021 // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float
2022 // and the sizeof() of your structure in the "stride" parameter.
2023 static float values[90] = {};
2024 static int values_offset = 0;
2025 static double refresh_time = 0.0;
2026 if (!animate || refresh_time == 0.0)
2027 refresh_time = ImGui::GetTime();
2028 while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo
2029 {
2030 static float phase = 0.0f;
2031 values[values_offset] = cosf(phase);
2032 values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);
2033 phase += 0.10f * values_offset;
2034 refresh_time += 1.0f / 60.0f;
2035 }
2036
2037 // Plots can display overlay texts
2038 // (in this example, we will display an average value)
2039 {
2040 float average = 0.0f;
2041 for (int n = 0; n < IM_ARRAYSIZE(values); n++)
2042 average += values[n];
2043 average /= (float)IM_ARRAYSIZE(values);
2044 char overlay[32];
2045 sprintf(overlay, "avg %f", average);
2046 ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f));
2047 }
2048
2049 // Use functions to generate output
2050 // FIXME: This is actually VERY awkward because current plot API only pass in indices.
2051 // We probably want an API passing floats and user provide sample rate/count.
2052 struct Funcs
2053 {
2054 static float Sin(void*, int i) { return sinf(i * 0.1f); }
2055 static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; }
2056 };
2057 static int func_type = 0, display_count = 70;
2058 ImGui::SeparatorText("Functions");
2059 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
2060 ImGui::Combo("func", &func_type, "Sin\0Saw\0");
2061 ImGui::SameLine();
2062 ImGui::SliderInt("Sample count", &display_count, 1, 400);
2063 float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;
2064 ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
2065 ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
2066 ImGui::Separator();
2067
2068 ImGui::Text("Need better plotting and graphing? Consider using ImPlot:");
2069 ImGui::TextLinkOpenURL("https://github.com/epezent/implot");
2070 ImGui::Separator();
2071
2072 ImGui::TreePop();
2073 }
2074
2075 IMGUI_DEMO_MARKER("Widgets/Progress Bars");
2076 if (ImGui::TreeNode("Progress Bars"))
2077 {
2078 // Animate a simple progress bar
2079 static float progress = 0.0f, progress_dir = 1.0f;
2080 progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
2081 if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }
2082 if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }
2083
2084 // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width,
2085 // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.
2086 ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f));
2087 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
2088 ImGui::Text("Progress Bar");
2089
2090 float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f);
2091 char buf[32];
2092 sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753);
2093 ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf);
2094
2095 // Pass an animated negative value, e.g. -1.0f * (float)ImGui::GetTime() is the recommended value.
2096 // Adjust the factor if you want to adjust the animation speed.
2097 ImGui::ProgressBar(-1.0f * (float)ImGui::GetTime(), ImVec2(0.0f, 0.0f), "Searching..");
2098 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
2099 ImGui::Text("Indeterminate");
2100
2101 ImGui::TreePop();
2102 }
2103
2104 IMGUI_DEMO_MARKER("Widgets/Color");
2105 if (ImGui::TreeNode("Color/Picker Widgets"))
2106 {
2107 static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f);
2108
2109 static bool alpha_preview = true;
2110 static bool alpha_half_preview = false;
2111 static bool drag_and_drop = true;
2112 static bool options_menu = true;
2113 static bool hdr = false;
2114 ImGui::SeparatorText("Options");
2115 ImGui::Checkbox("With Alpha Preview", &alpha_preview);
2116 ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
2117 ImGui::Checkbox("With Drag and Drop", &drag_and_drop);
2118 ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options.");
2119 ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
2120 ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
2121
2122 IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit");
2123 ImGui::SeparatorText("Inline color editor");
2124 ImGui::Text("Color widget:");
2125 ImGui::SameLine(); HelpMarker(
2126 "Click on the color square to open a color picker.\n"
2127 "CTRL+click on individual component to input value.\n");
2128 ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
2129
2130 IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (HSV, with Alpha)");
2131 ImGui::Text("Color widget HSV with Alpha:");
2132 ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags);
2133
2134 IMGUI_DEMO_MARKER("Widgets/Color/ColorEdit (float display)");
2135 ImGui::Text("Color widget with Float Display:");
2136 ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
2137
2138 IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with Picker)");
2139 ImGui::Text("Color button with Picker:");
2140 ImGui::SameLine(); HelpMarker(
2141 "With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n"
2142 "With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only "
2143 "be used for the tooltip and picker popup.");
2144 ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
2145
2146 IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (with custom Picker popup)");
2147 ImGui::Text("Color button with Custom Picker Popup:");
2148
2149 // Generate a default palette. The palette will persist and can be edited.
2150 static bool saved_palette_init = true;
2151 static ImVec4 saved_palette[32] = {};
2152 if (saved_palette_init)
2153 {
2154 for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
2155 {
2156 ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f,
2157 saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
2158 saved_palette[n].w = 1.0f; // Alpha
2159 }
2160 saved_palette_init = false;
2161 }
2162
2163 static ImVec4 backup_color;
2164 bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags);
2165 ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
2166 open_popup |= ImGui::Button("Palette");
2167 if (open_popup)
2168 {
2169 ImGui::OpenPopup("mypicker");
2170 backup_color = color;
2171 }
2172 if (ImGui::BeginPopup("mypicker"))
2173 {
2174 ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!");
2175 ImGui::Separator();
2176 ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
2177 ImGui::SameLine();
2178
2179 ImGui::BeginGroup(); // Lock X position
2180 ImGui::Text("Current");
2181 ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
2182 ImGui::Text("Previous");
2183 if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
2184 color = backup_color;
2185 ImGui::Separator();
2186 ImGui::Text("Palette");
2187 for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
2188 {
2189 ImGui::PushID(n);
2190 if ((n % 8) != 0)
2191 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);
2192
2193 ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;
2194 if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20)))
2195 color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
2196
2197 // Allow user to drop colors into each palette entry. Note that ColorButton() is already a
2198 // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.
2199 if (ImGui::BeginDragDropTarget())
2200 {
2201 if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
2202 memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
2203 if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
2204 memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
2205 ImGui::EndDragDropTarget();
2206 }
2207
2208 ImGui::PopID();
2209 }
2210 ImGui::EndGroup();
2211 ImGui::EndPopup();
2212 }
2213
2214 IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)");
2215 ImGui::Text("Color button only:");
2216 static bool no_border = false;
2217 ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border);
2218 ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80));
2219
2220 IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker");
2221 ImGui::SeparatorText("Color picker");
2222 static bool alpha = true;
2223 static bool alpha_bar = true;
2224 static bool side_preview = true;
2225 static bool ref_color = false;
2226 static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f);
2227 static int display_mode = 0;
2228 static int picker_mode = 0;
2229 ImGui::Checkbox("With Alpha", &alpha);
2230 ImGui::Checkbox("With Alpha Bar", &alpha_bar);
2231 ImGui::Checkbox("With Side Preview", &side_preview);
2232 if (side_preview)
2233 {
2234 ImGui::SameLine();
2235 ImGui::Checkbox("With Ref Color", &ref_color);
2236 if (ref_color)
2237 {
2238 ImGui::SameLine();
2239 ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);
2240 }
2241 }
2242 ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0");
2243 ImGui::SameLine(); HelpMarker(
2244 "ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, "
2245 "but the user can change it with a right-click on those inputs.\n\nColorPicker defaults to displaying RGB+HSV+Hex "
2246 "if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions().");
2247 ImGui::SameLine(); HelpMarker("When not specified explicitly (Auto/Current mode), user can right-click the picker to change mode.");
2248 ImGuiColorEditFlags flags = misc_flags;
2249 if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4()
2250 if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar;
2251 if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview;
2252 if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar;
2253 if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel;
2254 if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays
2255 if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode
2256 if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV;
2257 if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex;
2258 ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
2259
2260 ImGui::Text("Set defaults in code:");
2261 ImGui::SameLine(); HelpMarker(
2262 "SetColorEditOptions() is designed to allow you to set boot-time default.\n"
2263 "We don't have Push/Pop functions because you can force options on a per-widget basis if needed,"
2264 "and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid"
2265 "encouraging you to persistently save values that aren't forward-compatible.");
2266 if (ImGui::Button("Default: Uint8 + HSV + Hue Bar"))
2267 ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar);
2268 if (ImGui::Button("Default: Float + HDR + Hue Wheel"))
2269 ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel);
2270
2271 // Always display a small version of both types of pickers
2272 // (that's in order to make it more visible in the demo to people who are skimming quickly through it)
2273 ImGui::Text("Both types:");
2274 float w = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.y) * 0.40f;
2275 ImGui::SetNextItemWidth(w);
2276 ImGui::ColorPicker3("##MyColor##5", (float*)&color, ImGuiColorEditFlags_PickerHueBar | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha);
2277 ImGui::SameLine();
2278 ImGui::SetNextItemWidth(w);
2279 ImGui::ColorPicker3("##MyColor##6", (float*)&color, ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoAlpha);
2280
2281 // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0)
2282 static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV!
2283 ImGui::Spacing();
2284 ImGui::Text("HSV encoded colors");
2285 ImGui::SameLine(); HelpMarker(
2286 "By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV"
2287 "allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the"
2288 "added benefit that you can manipulate hue values with the picker even when saturation or value are zero.");
2289 ImGui::Text("Color widget with InputHSV:");
2290 ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
2291 ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
2292 ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f);
2293
2294 ImGui::TreePop();
2295 }
2296
2297 IMGUI_DEMO_MARKER("Widgets/Drag and Slider Flags");
2298 if (ImGui::TreeNode("Drag/Slider Flags"))
2299 {
2300 // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same!
2301 static ImGuiSliderFlags flags = ImGuiSliderFlags_None;
2302 ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", &flags, ImGuiSliderFlags_AlwaysClamp);
2303 ImGui::CheckboxFlags("ImGuiSliderFlags_ClampOnInput", &flags, ImGuiSliderFlags_ClampOnInput);
2304 ImGui::SameLine(); HelpMarker("Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.");
2305 ImGui::CheckboxFlags("ImGuiSliderFlags_ClampZeroRange", &flags, ImGuiSliderFlags_ClampZeroRange);
2306 ImGui::SameLine(); HelpMarker("Clamp even if min==max==0.0f. Otherwise DragXXX functions don't clamp.");
2307 ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", &flags, ImGuiSliderFlags_Logarithmic);
2308 ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
2309 ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", &flags, ImGuiSliderFlags_NoRoundToFormat);
2310 ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).");
2311 ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", &flags, ImGuiSliderFlags_NoInput);
2312 ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget.");
2313 ImGui::CheckboxFlags("ImGuiSliderFlags_WrapAround", &flags, ImGuiSliderFlags_WrapAround);
2314 ImGui::SameLine(); HelpMarker("Enable wrapping around from max to min and from min to max (only supported by DragXXX() functions)");
2315
2316 // Drags
2317 static float drag_f = 0.5f;
2318 static int drag_i = 50;
2319 ImGui::Text("Underlying float value: %f", drag_f);
2320 ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags);
2321 ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags);
2322 ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags);
2323 ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags);
2324 //ImGui::DragFloat("DragFloat (0 -> 0)", &drag_f, 0.005f, 0.0f, 0.0f, "%.3f", flags); // To test ClampZeroRange
2325 //ImGui::DragFloat("DragFloat (100 -> 100)", &drag_f, 0.005f, 100.0f, 100.0f, "%.3f", flags);
2326 ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags);
2327
2328 // Sliders
2329 static float slider_f = 0.5f;
2330 static int slider_i = 50;
2331 const ImGuiSliderFlags flags_for_sliders = flags & ~ImGuiSliderFlags_WrapAround;
2332 ImGui::Text("Underlying float value: %f", slider_f);
2333 ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags_for_sliders);
2334 ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags_for_sliders);
2335
2336 ImGui::TreePop();
2337 }
2338
2339 IMGUI_DEMO_MARKER("Widgets/Range Widgets");
2340 if (ImGui::TreeNode("Range Widgets"))
2341 {
2342 static float begin = 10, end = 90;
2343 static int begin_i = 100, end_i = 1000;
2344 ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp);
2345 ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units");
2346 ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units");
2347 ImGui::TreePop();
2348 }
2349
2350 IMGUI_DEMO_MARKER("Widgets/Data Types");
2351 if (ImGui::TreeNode("Data Types"))
2352 {
2353 // DragScalar/InputScalar/SliderScalar functions allow various data types
2354 // - signed/unsigned
2355 // - 8/16/32/64-bits
2356 // - integer/float/double
2357 // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum
2358 // to pass the type, and passing all arguments by pointer.
2359 // This is the reason the test code below creates local variables to hold "zero" "one" etc. for each type.
2360 // In practice, if you frequently use a given type that is not covered by the normal API entry points,
2361 // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*,
2362 // and then pass their address to the generic function. For example:
2363 // bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld")
2364 // {
2365 // return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format);
2366 // }
2367
2368 // Setup limits (as helper variables so we can take their address, as explained above)
2369 // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2.
2370 #ifndef LLONG_MIN
2371 ImS64 LLONG_MIN = -9223372036854775807LL - 1;
2372 ImS64 LLONG_MAX = 9223372036854775807LL;
2373 ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1);
2374 #endif
2375 const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127;
2376 const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255;
2377 const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767;
2378 const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535;
2379 const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN/2, s32_max = INT_MAX/2, s32_hi_a = INT_MAX/2 - 100, s32_hi_b = INT_MAX/2;
2380 const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX/2, u32_hi_a = UINT_MAX/2 - 100, u32_hi_b = UINT_MAX/2;
2381 const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2, s64_hi_a = LLONG_MAX/2 - 100, s64_hi_b = LLONG_MAX/2;
2382 const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2;
2383 const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f;
2384 const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0;
2385
2386 // State
2387 static char s8_v = 127;
2388 static ImU8 u8_v = 255;
2389 static short s16_v = 32767;
2390 static ImU16 u16_v = 65535;
2391 static ImS32 s32_v = -1;
2392 static ImU32 u32_v = (ImU32)-1;
2393 static ImS64 s64_v = -1;
2394 static ImU64 u64_v = (ImU64)-1;
2395 static float f32_v = 0.123f;
2396 static double f64_v = 90000.01234567890123456789;
2397
2398 const float drag_speed = 0.2f;
2399 static bool drag_clamp = false;
2400 IMGUI_DEMO_MARKER("Widgets/Data Types/Drags");
2401 ImGui::SeparatorText("Drags");
2402 ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp);
2403 ImGui::SameLine(); HelpMarker(
2404 "As with every widget in dear imgui, we never modify values unless there is a user interaction.\n"
2405 "You can override the clamping limits by using CTRL+Click to input a value.");
2406 ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL);
2407 ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms");
2408 ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL);
2409 ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms");
2410 ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL);
2411 ImGui::DragScalar("drag s32 hex", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL, "0x%08X");
2412 ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms");
2413 ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL);
2414 ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL);
2415 ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f");
2416 ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic);
2417 ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams");
2418 ImGui::DragScalar("drag double log",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic);
2419
2420 IMGUI_DEMO_MARKER("Widgets/Data Types/Sliders");
2421 ImGui::SeparatorText("Sliders");
2422 ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d");
2423 ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u");
2424 ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d");
2425 ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u");
2426 ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty,"%d");
2427 ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d");
2428 ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d");
2429 ImGui::SliderScalar("slider s32 hex", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "0x%04X");
2430 ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty,"%u");
2431 ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u");
2432 ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u");
2433 ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty,"%" PRId64);
2434 ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%" PRId64);
2435 ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%" PRId64);
2436 ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty,"%" PRIu64 " ms");
2437 ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%" PRIu64 " ms");
2438 ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%" PRIu64 " ms");
2439 ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one);
2440 ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic);
2441 ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e");
2442 ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams");
2443 ImGui::SliderScalar("slider double low log",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic);
2444 ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams");
2445
2446 ImGui::SeparatorText("Sliders (reverse)");
2447 ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d");
2448 ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u");
2449 ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d");
2450 ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u");
2451 ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%" PRId64);
2452 ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%" PRIu64 " ms");
2453
2454 IMGUI_DEMO_MARKER("Widgets/Data Types/Inputs");
2455 static bool inputs_step = true;
2456 static ImGuiInputTextFlags flags = ImGuiInputTextFlags_None;
2457 ImGui::SeparatorText("Inputs");
2458 ImGui::Checkbox("Show step buttons", &inputs_step);
2459 ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly);
2460 ImGui::CheckboxFlags("ImGuiInputTextFlags_ParseEmptyRefVal", &flags, ImGuiInputTextFlags_ParseEmptyRefVal);
2461 ImGui::CheckboxFlags("ImGuiInputTextFlags_DisplayEmptyRefVal", &flags, ImGuiInputTextFlags_DisplayEmptyRefVal);
2462 ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d", flags);
2463 ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u", flags);
2464 ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d", flags);
2465 ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u", flags);
2466 ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d", flags);
2467 ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%04X", flags);
2468 ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u", flags);
2469 ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", flags);
2470 ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL, NULL, NULL, flags);
2471 ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL, NULL, NULL, flags);
2472 ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL, NULL, NULL, flags);
2473 ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL, NULL, NULL, flags);
2474
2475 ImGui::TreePop();
2476 }
2477
2478 IMGUI_DEMO_MARKER("Widgets/Multi-component Widgets");
2479 if (ImGui::TreeNode("Multi-component Widgets"))
2480 {
2481 static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
2482 static int vec4i[4] = { 1, 5, 100, 255 };
2483
2484 ImGui::SeparatorText("2-wide");
2485 ImGui::InputFloat2("input float2", vec4f);
2486 ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f);
2487 ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f);
2488 ImGui::InputInt2("input int2", vec4i);
2489 ImGui::DragInt2("drag int2", vec4i, 1, 0, 255);
2490 ImGui::SliderInt2("slider int2", vec4i, 0, 255);
2491
2492 ImGui::SeparatorText("3-wide");
2493 ImGui::InputFloat3("input float3", vec4f);
2494 ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f);
2495 ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f);
2496 ImGui::InputInt3("input int3", vec4i);
2497 ImGui::DragInt3("drag int3", vec4i, 1, 0, 255);
2498 ImGui::SliderInt3("slider int3", vec4i, 0, 255);
2499
2500 ImGui::SeparatorText("4-wide");
2501 ImGui::InputFloat4("input float4", vec4f);
2502 ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f);
2503 ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f);
2504 ImGui::InputInt4("input int4", vec4i);
2505 ImGui::DragInt4("drag int4", vec4i, 1, 0, 255);
2506 ImGui::SliderInt4("slider int4", vec4i, 0, 255);
2507
2508 ImGui::TreePop();
2509 }
2510
2511 IMGUI_DEMO_MARKER("Widgets/Vertical Sliders");
2512 if (ImGui::TreeNode("Vertical Sliders"))
2513 {
2514 const float spacing = 4;
2515 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
2516
2517 static int int_value = 0;
2518 ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5);
2519 ImGui::SameLine();
2520
2521 static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f };
2522 ImGui::PushID("set1");
2523 for (int i = 0; i < 7; i++)
2524 {
2525 if (i > 0) ImGui::SameLine();
2526 ImGui::PushID(i);
2527 ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f));
2528 ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f));
2529 ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f));
2530 ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f));
2531 ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, "");
2532 if (ImGui::IsItemActive() || ImGui::IsItemHovered())
2533 ImGui::SetTooltip("%.3f", values[i]);
2534 ImGui::PopStyleColor(4);
2535 ImGui::PopID();
2536 }
2537 ImGui::PopID();
2538
2539 ImGui::SameLine();
2540 ImGui::PushID("set2");
2541 static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f };
2542 const int rows = 3;
2543 const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows));
2544 for (int nx = 0; nx < 4; nx++)
2545 {
2546 if (nx > 0) ImGui::SameLine();
2547 ImGui::BeginGroup();
2548 for (int ny = 0; ny < rows; ny++)
2549 {
2550 ImGui::PushID(nx * rows + ny);
2551 ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, "");
2552 if (ImGui::IsItemActive() || ImGui::IsItemHovered())
2553 ImGui::SetTooltip("%.3f", values2[nx]);
2554 ImGui::PopID();
2555 }
2556 ImGui::EndGroup();
2557 }
2558 ImGui::PopID();
2559
2560 ImGui::SameLine();
2561 ImGui::PushID("set3");
2562 for (int i = 0; i < 4; i++)
2563 {
2564 if (i > 0) ImGui::SameLine();
2565 ImGui::PushID(i);
2566 ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
2567 ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
2568 ImGui::PopStyleVar();
2569 ImGui::PopID();
2570 }
2571 ImGui::PopID();
2572 ImGui::PopStyleVar();
2573 ImGui::TreePop();
2574 }
2575
2576 IMGUI_DEMO_MARKER("Widgets/Drag and drop");
2577 if (ImGui::TreeNode("Drag and Drop"))
2578 {
2579 IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets");
2580 if (ImGui::TreeNode("Drag and drop in standard widgets"))
2581 {
2582 // ColorEdit widgets automatically act as drag source and drag target.
2583 // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F
2584 // to allow your own widgets to use colors in their drag and drop interaction.
2585 // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo.
2586 HelpMarker("You can drag from the color squares.");
2587 static float col1[3] = { 1.0f, 0.0f, 0.2f };
2588 static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
2589 ImGui::ColorEdit3("color 1", col1);
2590 ImGui::ColorEdit4("color 2", col2);
2591 ImGui::TreePop();
2592 }
2593
2594 IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items");
2595 if (ImGui::TreeNode("Drag and drop to copy/swap items"))
2596 {
2597 enum Mode
2598 {
2599 Mode_Copy,
2600 Mode_Move,
2601 Mode_Swap
2602 };
2603 static int mode = 0;
2604 if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine();
2605 if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine();
2606 if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; }
2607 static const char* names[9] =
2608 {
2609 "Bobby", "Beatrice", "Betty",
2610 "Brianna", "Barry", "Bernard",
2611 "Bibi", "Blaine", "Bryn"
2612 };
2613 for (int n = 0; n < IM_ARRAYSIZE(names); n++)
2614 {
2615 ImGui::PushID(n);
2616 if ((n % 3) != 0)
2617 ImGui::SameLine();
2618 ImGui::Button(names[n], ImVec2(60, 60));
2619
2620 // Our buttons are both drag sources and drag targets here!
2621 if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
2622 {
2623 // Set payload to carry the index of our item (could be anything)
2624 ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int));
2625
2626 // Display preview (could be anything, e.g. when dragging an image we could decide to display
2627 // the filename and a small preview of the image, etc.)
2628 if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); }
2629 if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); }
2630 if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); }
2631 ImGui::EndDragDropSource();
2632 }
2633 if (ImGui::BeginDragDropTarget())
2634 {
2635 if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL"))
2636 {
2637 IM_ASSERT(payload->DataSize == sizeof(int));
2638 int payload_n = *(const int*)payload->Data;
2639 if (mode == Mode_Copy)
2640 {
2641 names[n] = names[payload_n];
2642 }
2643 if (mode == Mode_Move)
2644 {
2645 names[n] = names[payload_n];
2646 names[payload_n] = "";
2647 }
2648 if (mode == Mode_Swap)
2649 {
2650 const char* tmp = names[n];
2651 names[n] = names[payload_n];
2652 names[payload_n] = tmp;
2653 }
2654 }
2655 ImGui::EndDragDropTarget();
2656 }
2657 ImGui::PopID();
2658 }
2659 ImGui::TreePop();
2660 }
2661
2662 IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Drag to reorder items (simple)");
2663 if (ImGui::TreeNode("Drag to reorder items (simple)"))
2664 {
2665 // FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice.
2666 // This code was always slightly faulty but in a way which was not easily noticeable.
2667 // Until we fix this, enable ImGuiItemFlags_AllowDuplicateId to disable detecting the issue.
2668 ImGui::PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true);
2669
2670 // Simple reordering
2671 HelpMarker(
2672 "We don't use the drag and drop api at all here! "
2673 "Instead we query when the item is held but not hovered, and order items accordingly.");
2674 static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" };
2675 for (int n = 0; n < IM_ARRAYSIZE(item_names); n++)
2676 {
2677 const char* item = item_names[n];
2678 ImGui::Selectable(item);
2679
2680 if (ImGui::IsItemActive() && !ImGui::IsItemHovered())
2681 {
2682 int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1);
2683 if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names))
2684 {
2685 item_names[n] = item_names[n_next];
2686 item_names[n_next] = item;
2687 ImGui::ResetMouseDragDelta();
2688 }
2689 }
2690 }
2691
2692 ImGui::PopItemFlag();
2693 ImGui::TreePop();
2694 }
2695
2696 IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Tooltip at target location");
2697 if (ImGui::TreeNode("Tooltip at target location"))
2698 {
2699 for (int n = 0; n < 2; n++)
2700 {
2701 // Drop targets
2702 ImGui::Button(n ? "drop here##1" : "drop here##0");
2703 if (ImGui::BeginDragDropTarget())
2704 {
2705 ImGuiDragDropFlags drop_target_flags = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoPreviewTooltip;
2706 if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, drop_target_flags))
2707 {
2708 IM_UNUSED(payload);
2709 ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed);
2710 ImGui::SetTooltip("Cannot drop here!");
2711 }
2712 ImGui::EndDragDropTarget();
2713 }
2714
2715 // Drop source
2716 static ImVec4 col4 = { 1.0f, 0.0f, 0.2f, 1.0f };
2717 if (n == 0)
2718 ImGui::ColorButton("drag me", col4);
2719
2720 }
2721 ImGui::TreePop();
2722 }
2723
2724 ImGui::TreePop();
2725 }
2726
2727 IMGUI_DEMO_MARKER("Widgets/Querying Item Status (Edited,Active,Hovered etc.)");
2728 if (ImGui::TreeNode("Querying Item Status (Edited/Active/Hovered etc.)"))
2729 {
2730 // Select an item type
2731 const char* item_names[] =
2732 {
2733 "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat",
2734 "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox"
2735 };
2736 static int item_type = 4;
2737 static bool item_disabled = false;
2738 ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names));
2739 ImGui::SameLine();
2740 HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered().");
2741 ImGui::Checkbox("Item Disabled", &item_disabled);
2742
2743 // Submit selected items so we can query their status in the code following it.
2744 bool ret = false;
2745 static bool b = false;
2746 static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f };
2747 static char str[16] = {};
2748 if (item_disabled)
2749 ImGui::BeginDisabled(true);
2750 if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction
2751 if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button
2752 if (item_type == 2) { ImGui::PushItemFlag(ImGuiItemFlags_ButtonRepeat, true); ret = ImGui::Button("ITEM: Button"); ImGui::PopItemFlag(); } // Testing button (with repeater)
2753 if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox
2754 if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item
2755 if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing)
2756 if (item_type == 6) { ret = ImGui::InputTextMultiline("ITEM: InputTextMultiline", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window)
2757 if (item_type == 7) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input
2758 if (item_type == 8) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
2759 if (item_type == 9) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
2760 if (item_type == 10){ ret = ImGui::Selectable("ITEM: Selectable"); } // Testing selectable item
2761 if (item_type == 11){ ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy)
2762 if (item_type == 12){ ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node
2763 if (item_type == 13){ ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.
2764 if (item_type == 14){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::Combo("ITEM: Combo", &current, items, IM_ARRAYSIZE(items)); }
2765 if (item_type == 15){ const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", &current, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); }
2766
2767 bool hovered_delay_none = ImGui::IsItemHovered();
2768 bool hovered_delay_stationary = ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary);
2769 bool hovered_delay_short = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort);
2770 bool hovered_delay_normal = ImGui::IsItemHovered(ImGuiHoveredFlags_DelayNormal);
2771 bool hovered_delay_tooltip = ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip); // = Normal + Stationary
2772
2773 // Display the values of IsItemHovered() and other common item state functions.
2774 // Note that the ImGuiHoveredFlags_XXX flags can be combined.
2775 // Because BulletText is an item itself and that would affect the output of IsItemXXX functions,
2776 // we query every state in a single call to avoid storing them and to simplify the code.
2777 ImGui::BulletText(
2778 "Return value = %d\n"
2779 "IsItemFocused() = %d\n"
2780 "IsItemHovered() = %d\n"
2781 "IsItemHovered(_AllowWhenBlockedByPopup) = %d\n"
2782 "IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n"
2783 "IsItemHovered(_AllowWhenOverlappedByItem) = %d\n"
2784 "IsItemHovered(_AllowWhenOverlappedByWindow) = %d\n"
2785 "IsItemHovered(_AllowWhenDisabled) = %d\n"
2786 "IsItemHovered(_RectOnly) = %d\n"
2787 "IsItemActive() = %d\n"
2788 "IsItemEdited() = %d\n"
2789 "IsItemActivated() = %d\n"
2790 "IsItemDeactivated() = %d\n"
2791 "IsItemDeactivatedAfterEdit() = %d\n"
2792 "IsItemVisible() = %d\n"
2793 "IsItemClicked() = %d\n"
2794 "IsItemToggledOpen() = %d\n"
2795 "GetItemRectMin() = (%.1f, %.1f)\n"
2796 "GetItemRectMax() = (%.1f, %.1f)\n"
2797 "GetItemRectSize() = (%.1f, %.1f)",
2798 ret,
2799 ImGui::IsItemFocused(),
2800 ImGui::IsItemHovered(),
2801 ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
2802 ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
2803 ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByItem),
2804 ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow),
2805 ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled),
2806 ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly),
2807 ImGui::IsItemActive(),
2808 ImGui::IsItemEdited(),
2809 ImGui::IsItemActivated(),
2810 ImGui::IsItemDeactivated(),
2811 ImGui::IsItemDeactivatedAfterEdit(),
2812 ImGui::IsItemVisible(),
2813 ImGui::IsItemClicked(),
2814 ImGui::IsItemToggledOpen(),
2815 ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y,
2816 ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y,
2817 ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y
2818 );
2819 ImGui::BulletText(
2820 "with Hovering Delay or Stationary test:\n"
2821 "IsItemHovered() = = %d\n"
2822 "IsItemHovered(_Stationary) = %d\n"
2823 "IsItemHovered(_DelayShort) = %d\n"
2824 "IsItemHovered(_DelayNormal) = %d\n"
2825 "IsItemHovered(_Tooltip) = %d",
2826 hovered_delay_none, hovered_delay_stationary, hovered_delay_short, hovered_delay_normal, hovered_delay_tooltip);
2827
2828 if (item_disabled)
2829 ImGui::EndDisabled();
2830
2831 char buf[1] = "";
2832 ImGui::InputText("unused", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly);
2833 ImGui::SameLine();
2834 HelpMarker("This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status.");
2835
2836 ImGui::TreePop();
2837 }
2838
2839 IMGUI_DEMO_MARKER("Widgets/Querying Window Status (Focused,Hovered etc.)");
2840 if (ImGui::TreeNode("Querying Window Status (Focused/Hovered etc.)"))
2841 {
2842 static bool embed_all_inside_a_child_window = false;
2843 ImGui::Checkbox("Embed everything inside a child window for testing _RootWindow flag.", &embed_all_inside_a_child_window);
2844 if (embed_all_inside_a_child_window)
2845 ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), ImGuiChildFlags_Borders);
2846
2847 // Testing IsWindowFocused() function with its various flags.
2848 ImGui::BulletText(
2849 "IsWindowFocused() = %d\n"
2850 "IsWindowFocused(_ChildWindows) = %d\n"
2851 "IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n"
2852 "IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
2853 "IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n"
2854 "IsWindowFocused(_RootWindow) = %d\n"
2855 "IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\n"
2856 "IsWindowFocused(_AnyWindow) = %d\n",
2857 ImGui::IsWindowFocused(),
2858 ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
2859 ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy),
2860 ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
2861 ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy),
2862 ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),
2863 ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy),
2864 ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
2865
2866 // Testing IsWindowHovered() function with its various flags.
2867 ImGui::BulletText(
2868 "IsWindowHovered() = %d\n"
2869 "IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n"
2870 "IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
2871 "IsWindowHovered(_ChildWindows) = %d\n"
2872 "IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\n"
2873 "IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
2874 "IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\n"
2875 "IsWindowHovered(_RootWindow) = %d\n"
2876 "IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\n"
2877 "IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n"
2878 "IsWindowHovered(_AnyWindow) = %d\n"
2879 "IsWindowHovered(_Stationary) = %d\n",
2880 ImGui::IsWindowHovered(),
2881 ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
2882 ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
2883 ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
2884 ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy),
2885 ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
2886 ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy),
2887 ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),
2888 ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy),
2889 ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup),
2890 ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow),
2891 ImGui::IsWindowHovered(ImGuiHoveredFlags_Stationary));
2892
2893 ImGui::BeginChild("child", ImVec2(0, 50), ImGuiChildFlags_Borders);
2894 ImGui::Text("This is another child window for testing the _ChildWindows flag.");
2895 ImGui::EndChild();
2896 if (embed_all_inside_a_child_window)
2897 ImGui::EndChild();
2898
2899 // Calling IsItemHovered() after begin returns the hovered status of the title bar.
2900 // This is useful in particular if you want to create a context menu associated to the title bar of a window.
2901 static bool test_window = false;
2902 ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window);
2903 if (test_window)
2904 {
2905 ImGui::Begin("Title bar Hovered/Active tests", &test_window);
2906 if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()
2907 {
2908 if (ImGui::MenuItem("Close")) { test_window = false; }
2909 ImGui::EndPopup();
2910 }
2911 ImGui::Text(
2912 "IsItemHovered() after begin = %d (== is title bar hovered)\n"
2913 "IsItemActive() after begin = %d (== is window being clicked/moved)\n",
2914 ImGui::IsItemHovered(), ImGui::IsItemActive());
2915 ImGui::End();
2916 }
2917
2918 ImGui::TreePop();
2919 }
2920
2921 // Demonstrate BeginDisabled/EndDisabled using a checkbox located at the bottom of the section (which is a bit odd:
2922 // logically we'd have this checkbox at the top of the section, but we don't want this feature to steal that space)
2923 if (disable_all)
2924 ImGui::EndDisabled();
2925
2926 IMGUI_DEMO_MARKER("Widgets/Disable Block");
2927 if (ImGui::TreeNode("Disable block"))
2928 {
2929 ImGui::Checkbox("Disable entire section above", &disable_all);
2930 ImGui::SameLine(); HelpMarker("Demonstrate using BeginDisabled()/EndDisabled() across this section.");
2931 ImGui::TreePop();
2932 }
2933
2934 IMGUI_DEMO_MARKER("Widgets/Text Filter");
2935 if (ImGui::TreeNode("Text Filter"))
2936 {
2937 // Helper class to easy setup a text filter.
2938 // You may want to implement a more feature-full filtering scheme in your own application.
2939 HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings.");
2940 static ImGuiTextFilter filter;
2941 ImGui::Text("Filter usage:\n"
2942 " \"\" display all lines\n"
2943 " \"xxx\" display lines containing \"xxx\"\n"
2944 " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n"
2945 " \"-xxx\" hide lines containing \"xxx\"");
2946 filter.Draw();
2947 const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" };
2948 for (int i = 0; i < IM_ARRAYSIZE(lines); i++)
2949 if (filter.PassFilter(lines[i]))
2950 ImGui::BulletText("%s", lines[i]);
2951 ImGui::TreePop();
2952 }
2953 }
2954
2955 static const char* ExampleNames[] =
2956 {
2957 "Artichoke", "Arugula", "Asparagus", "Avocado", "Bamboo Shoots", "Bean Sprouts", "Beans", "Beet", "Belgian Endive", "Bell Pepper",
2958 "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava",
2959 "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber"
2960 };
2961
2962 // Extra functions to add deletion support to ImGuiSelectionBasicStorage
2963 struct ExampleSelectionWithDeletion : ImGuiSelectionBasicStorage
2964 {
2965 // Find which item should be Focused after deletion.
2966 // Call _before_ item submission. Retunr an index in the before-deletion item list, your item loop should call SetKeyboardFocusHere() on it.
2967 // The subsequent ApplyDeletionPostLoop() code will use it to apply Selection.
2968 // - We cannot provide this logic in core Dear ImGui because we don't have access to selection data.
2969 // - We don't actually manipulate the ImVector<> here, only in ApplyDeletionPostLoop(), but using similar API for consistency and flexibility.
2970 // - Important: Deletion only works if the underlying ImGuiID for your items are stable: aka not depend on their index, but on e.g. item id/ptr.
2971 // FIXME-MULTISELECT: Doesn't take account of the possibility focus target will be moved during deletion. Need refocus or scroll offset.
2972 int ApplyDeletionPreLoop(ImGuiMultiSelectIO* ms_io, int items_count)
2973 {
2974 if (Size == 0)
2975 return -1;
2976
2977 // If focused item is not selected...
2978 const int focused_idx = (int)ms_io->NavIdItem; // Index of currently focused item
2979 if (ms_io->NavIdSelected == false) // This is merely a shortcut, == Contains(adapter->IndexToStorage(items, focused_idx))
2980 {
2981 ms_io->RangeSrcReset = true; // Request to recover RangeSrc from NavId next frame. Would be ok to reset even when NavIdSelected==true, but it would take an extra frame to recover RangeSrc when deleting a selected item.
2982 return focused_idx; // Request to focus same item after deletion.
2983 }
2984
2985 // If focused item is selected: land on first unselected item after focused item.
2986 for (int idx = focused_idx + 1; idx < items_count; idx++)
2987 if (!Contains(GetStorageIdFromIndex(idx)))
2988 return idx;
2989
2990 // If focused item is selected: otherwise return last unselected item before focused item.
2991 for (int idx = IM_MIN(focused_idx, items_count) - 1; idx >= 0; idx--)
2992 if (!Contains(GetStorageIdFromIndex(idx)))
2993 return idx;
2994
2995 return -1;
2996 }
2997
2998 // Rewrite item list (delete items) + update selection.
2999 // - Call after EndMultiSelect()
3000 // - We cannot provide this logic in core Dear ImGui because we don't have access to your items, nor to selection data.
3001 template<typename ITEM_TYPE>
3002 void ApplyDeletionPostLoop(ImGuiMultiSelectIO* ms_io, ImVector<ITEM_TYPE>& items, int item_curr_idx_to_select)
3003 {
3004 // Rewrite item list (delete items) + convert old selection index (before deletion) to new selection index (after selection).
3005 // If NavId was not part of selection, we will stay on same item.
3006 ImVector<ITEM_TYPE> new_items;
3007 new_items.reserve(items.Size - Size);
3008 int item_next_idx_to_select = -1;
3009 for (int idx = 0; idx < items.Size; idx++)
3010 {
3011 if (!Contains(GetStorageIdFromIndex(idx)))
3012 new_items.push_back(items[idx]);
3013 if (item_curr_idx_to_select == idx)
3014 item_next_idx_to_select = new_items.Size - 1;
3015 }
3016 items.swap(new_items);
3017
3018 // Update selection
3019 Clear();
3020 if (item_next_idx_to_select != -1 && ms_io->NavIdSelected)
3021 SetItemSelected(GetStorageIdFromIndex(item_next_idx_to_select), true);
3022 }
3023 };
3024
3025 // Example: Implement dual list box storage and interface
3026 struct ExampleDualListBox
3027 {
3028 ImVector<ImGuiID> Items[2]; // ID is index into ExampleName[]
3029 ImGuiSelectionBasicStorage Selections[2]; // Store ExampleItemId into selection
3030 bool OptKeepSorted = true;
3031
3032 void MoveAll(int src, int dst)
3033 {
3034 IM_ASSERT((src == 0 && dst == 1) || (src == 1 && dst == 0));
3035 for (ImGuiID item_id : Items[src])
3036 Items[dst].push_back(item_id);
3037 Items[src].clear();
3038 SortItems(dst);
3039 Selections[src].Swap(Selections[dst]);
3040 Selections[src].Clear();
3041 }
3042 void MoveSelected(int src, int dst)
3043 {
3044 for (int src_n = 0; src_n < Items[src].Size; src_n++)
3045 {
3046 ImGuiID item_id = Items[src][src_n];
3047 if (!Selections[src].Contains(item_id))
3048 continue;
3049 Items[src].erase(&Items[src][src_n]); // FIXME-OPT: Could be implemented more optimally (rebuild src items and swap)
3050 Items[dst].push_back(item_id);
3051 src_n--;
3052 }
3053 if (OptKeepSorted)
3054 SortItems(dst);
3055 Selections[src].Swap(Selections[dst]);
3056 Selections[src].Clear();
3057 }
3058 void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, int side)
3059 {
3060 // In this example we store item id in selection (instead of item index)
3061 Selections[side].UserData = Items[side].Data;
3062 Selections[side].AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImGuiID* items = (ImGuiID*)self->UserData; return items[idx]; };
3063 Selections[side].ApplyRequests(ms_io);
3064 }
3065 static int IMGUI_CDECL CompareItemsByValue(const void* lhs, const void* rhs)
3066 {
3067 const int* a = (const int*)lhs;
3068 const int* b = (const int*)rhs;
3069 return (*a - *b) > 0 ? +1 : -1;
3070 }
3071 void SortItems(int n)
3072 {
3073 qsort(Items[n].Data, (size_t)Items[n].Size, sizeof(Items[n][0]), CompareItemsByValue);
3074 }
3075 void Show()
3076 {
3077 //ImGui::Checkbox("Sorted", &OptKeepSorted);
3078 if (ImGui::BeginTable("split", 3, ImGuiTableFlags_None))
3079 {
3080 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Left side
3081 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); // Buttons
3082 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch); // Right side
3083 ImGui::TableNextRow();
3084
3085 int request_move_selected = -1;
3086 int request_move_all = -1;
3087 float child_height_0 = 0.0f;
3088 for (int side = 0; side < 2; side++)
3089 {
3090 // FIXME-MULTISELECT: Dual List Box: Add context menus
3091 // FIXME-NAV: Using ImGuiWindowFlags_NavFlattened exhibit many issues.
3092 ImVector<ImGuiID>& items = Items[side];
3093 ImGuiSelectionBasicStorage& selection = Selections[side];
3094
3095 ImGui::TableSetColumnIndex((side == 0) ? 0 : 2);
3096 ImGui::Text("%s (%d)", (side == 0) ? "Available" : "Basket", items.Size);
3097
3098 // Submit scrolling range to avoid glitches on moving/deletion
3099 const float items_height = ImGui::GetTextLineHeightWithSpacing();
3100 ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height));
3101
3102 bool child_visible;
3103 if (side == 0)
3104 {
3105 // Left child is resizable
3106 ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetFrameHeightWithSpacing() * 4), ImVec2(FLT_MAX, FLT_MAX));
3107 child_visible = ImGui::BeginChild("0", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY);
3108 child_height_0 = ImGui::GetWindowSize().y;
3109 }
3110 else
3111 {
3112 // Right child use same height as left one
3113 child_visible = ImGui::BeginChild("1", ImVec2(-FLT_MIN, child_height_0), ImGuiChildFlags_FrameStyle);
3114 }
3115 if (child_visible)
3116 {
3117 ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_None;
3118 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size);
3119 ApplySelectionRequests(ms_io, side);
3120
3121 for (int item_n = 0; item_n < items.Size; item_n++)
3122 {
3123 ImGuiID item_id = items[item_n];
3124 bool item_is_selected = selection.Contains(item_id);
3125 ImGui::SetNextItemSelectionUserData(item_n);
3126 ImGui::Selectable(ExampleNames[item_id], item_is_selected, ImGuiSelectableFlags_AllowDoubleClick);
3127 if (ImGui::IsItemFocused())
3128 {
3129 // FIXME-MULTISELECT: Dual List Box: Transfer focus
3130 if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))
3131 request_move_selected = side;
3132 if (ImGui::IsMouseDoubleClicked(0)) // FIXME-MULTISELECT: Double-click on multi-selection?
3133 request_move_selected = side;
3134 }
3135 }
3136
3137 ms_io = ImGui::EndMultiSelect();
3138 ApplySelectionRequests(ms_io, side);
3139 }
3140 ImGui::EndChild();
3141 }
3142
3143 // Buttons columns
3144 ImGui::TableSetColumnIndex(1);
3145 ImGui::NewLine();
3146 //ImVec2 button_sz = { ImGui::CalcTextSize(">>").x + ImGui::GetStyle().FramePadding.x * 2.0f, ImGui::GetFrameHeight() + padding.y * 2.0f };
3147 ImVec2 button_sz = { ImGui::GetFrameHeight(), ImGui::GetFrameHeight() };
3148
3149 // (Using BeginDisabled()/EndDisabled() works but feels distracting given how it is currently visualized)
3150 if (ImGui::Button(">>", button_sz))
3151 request_move_all = 0;
3152 if (ImGui::Button(">", button_sz))
3153 request_move_selected = 0;
3154 if (ImGui::Button("<", button_sz))
3155 request_move_selected = 1;
3156 if (ImGui::Button("<<", button_sz))
3157 request_move_all = 1;
3158
3159 // Process requests
3160 if (request_move_all != -1)
3161 MoveAll(request_move_all, request_move_all ^ 1);
3162 if (request_move_selected != -1)
3163 MoveSelected(request_move_selected, request_move_selected ^ 1);
3164
3165 // FIXME-MULTISELECT: Support action from outside
3166 /*
3167 if (OptKeepSorted == false)
3168 {
3169 ImGui::NewLine();
3170 if (ImGui::ArrowButton("MoveUp", ImGuiDir_Up)) {}
3171 if (ImGui::ArrowButton("MoveDown", ImGuiDir_Down)) {}
3172 }
3173 */
3174
3175 ImGui::EndTable();
3176 }
3177 }
3178 };
3179
3180 //-----------------------------------------------------------------------------
3181 // [SECTION] ShowDemoWindowMultiSelect()
3182 //-----------------------------------------------------------------------------
3183 // Multi-selection demos
3184 // Also read: https://github.com/ocornut/imgui/wiki/Multi-Select
3185 //-----------------------------------------------------------------------------
3186
3187 static void ShowDemoWindowMultiSelect(ImGuiDemoWindowData* demo_data)
3188 {
3189 IMGUI_DEMO_MARKER("Widgets/Selection State & Multi-Select");
3190 if (ImGui::TreeNode("Selection State & Multi-Select"))
3191 {
3192 HelpMarker("Selections can be built using Selectable(), TreeNode() or other widgets. Selection state is owned by application code/data.");
3193
3194 // Without any fancy API: manage single-selection yourself.
3195 IMGUI_DEMO_MARKER("Widgets/Selection State/Single-Select");
3196 if (ImGui::TreeNode("Single-Select"))
3197 {
3198 static int selected = -1;
3199 for (int n = 0; n < 5; n++)
3200 {
3201 char buf[32];
3202 sprintf(buf, "Object %d", n);
3203 if (ImGui::Selectable(buf, selected == n))
3204 selected = n;
3205 }
3206 ImGui::TreePop();
3207 }
3208
3209 // Demonstrate implementation a most-basic form of multi-selection manually
3210 // This doesn't support the SHIFT modifier which requires BeginMultiSelect()!
3211 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (manual/simplified, without BeginMultiSelect)");
3212 if (ImGui::TreeNode("Multi-Select (manual/simplified, without BeginMultiSelect)"))
3213 {
3214 HelpMarker("Hold CTRL and click to select multiple items.");
3215 static bool selection[5] = { false, false, false, false, false };
3216 for (int n = 0; n < 5; n++)
3217 {
3218 char buf[32];
3219 sprintf(buf, "Object %d", n);
3220 if (ImGui::Selectable(buf, selection[n]))
3221 {
3222 if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held
3223 memset(selection, 0, sizeof(selection));
3224 selection[n] ^= 1; // Toggle current item
3225 }
3226 }
3227 ImGui::TreePop();
3228 }
3229
3230 // Demonstrate handling proper multi-selection using the BeginMultiSelect/EndMultiSelect API.
3231 // SHIFT+Click w/ CTRL and other standard features are supported.
3232 // We use the ImGuiSelectionBasicStorage helper which you may freely reimplement.
3233 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select");
3234 if (ImGui::TreeNode("Multi-Select"))
3235 {
3236 ImGui::Text("Supported features:");
3237 ImGui::BulletText("Keyboard navigation (arrows, page up/down, home/end, space).");
3238 ImGui::BulletText("Ctrl modifier to preserve and toggle selection.");
3239 ImGui::BulletText("Shift modifier for range selection.");
3240 ImGui::BulletText("CTRL+A to select all.");
3241 ImGui::BulletText("Escape to clear selection.");
3242 ImGui::BulletText("Click and drag to box-select.");
3243 ImGui::Text("Tip: Use 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen.");
3244
3245 // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection
3246 const int ITEMS_COUNT = 50;
3247 static ImGuiSelectionBasicStorage selection;
3248 ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT);
3249
3250 // The BeginChild() has no purpose for selection logic, other that offering a scrolling region.
3251 if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY))
3252 {
3253 ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d;
3254 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT);
3255 selection.ApplyRequests(ms_io);
3256
3257 for (int n = 0; n < ITEMS_COUNT; n++)
3258 {
3259 char label[64];
3260 sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]);
3261 bool item_is_selected = selection.Contains((ImGuiID)n);
3262 ImGui::SetNextItemSelectionUserData(n);
3263 ImGui::Selectable(label, item_is_selected);
3264 }
3265
3266 ms_io = ImGui::EndMultiSelect();
3267 selection.ApplyRequests(ms_io);
3268 }
3269 ImGui::EndChild();
3270 ImGui::TreePop();
3271 }
3272
3273 // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect()
3274 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with clipper)");
3275 if (ImGui::TreeNode("Multi-Select (with clipper)"))
3276 {
3277 // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection
3278 static ImGuiSelectionBasicStorage selection;
3279
3280 ImGui::Text("Added features:");
3281 ImGui::BulletText("Using ImGuiListClipper.");
3282
3283 const int ITEMS_COUNT = 10000;
3284 ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT);
3285 if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY))
3286 {
3287 ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d;
3288 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT);
3289 selection.ApplyRequests(ms_io);
3290
3291 ImGuiListClipper clipper;
3292 clipper.Begin(ITEMS_COUNT);
3293 if (ms_io->RangeSrcItem != -1)
3294 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped.
3295 while (clipper.Step())
3296 {
3297 for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++)
3298 {
3299 char label[64];
3300 sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]);
3301 bool item_is_selected = selection.Contains((ImGuiID)n);
3302 ImGui::SetNextItemSelectionUserData(n);
3303 ImGui::Selectable(label, item_is_selected);
3304 }
3305 }
3306
3307 ms_io = ImGui::EndMultiSelect();
3308 selection.ApplyRequests(ms_io);
3309 }
3310 ImGui::EndChild();
3311 ImGui::TreePop();
3312 }
3313
3314 // Demonstrate dynamic item list + deletion support using the BeginMultiSelect/EndMultiSelect API.
3315 // In order to support Deletion without any glitches you need to:
3316 // - (1) If items are submitted in their own scrolling area, submit contents size SetNextWindowContentSize() ahead of time to prevent one-frame readjustment of scrolling.
3317 // - (2) Items needs to have persistent ID Stack identifier = ID needs to not depends on their index. PushID(index) = KO. PushID(item_id) = OK. This is in order to focus items reliably after a selection.
3318 // - (3) BeginXXXX process
3319 // - (4) Focus process
3320 // - (5) EndXXXX process
3321 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (with deletion)");
3322 if (ImGui::TreeNode("Multi-Select (with deletion)"))
3323 {
3324 // Storing items data separately from selection data.
3325 // (you may decide to store selection data inside your item (aka intrusive storage) if you don't need multiple views over same items)
3326 // Use a custom selection.Adapter: store item identifier in Selection (instead of index)
3327 static ImVector<ImGuiID> items;
3328 static ExampleSelectionWithDeletion selection;
3329 selection.UserData = (void*)&items;
3330 selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self, int idx) { ImVector<ImGuiID>* p_items = (ImVector<ImGuiID>*)self->UserData; return (*p_items)[idx]; }; // Index -> ID
3331
3332 ImGui::Text("Added features:");
3333 ImGui::BulletText("Dynamic list with Delete key support.");
3334 ImGui::Text("Selection size: %d/%d", selection.Size, items.Size);
3335
3336 // Initialize default list with 50 items + button to add/remove items.
3337 static ImGuiID items_next_id = 0;
3338 if (items_next_id == 0)
3339 for (ImGuiID n = 0; n < 50; n++)
3340 items.push_back(items_next_id++);
3341 if (ImGui::SmallButton("Add 20 items")) { for (int n = 0; n < 20; n++) { items.push_back(items_next_id++); } }
3342 ImGui::SameLine();
3343 if (ImGui::SmallButton("Remove 20 items")) { for (int n = IM_MIN(20, items.Size); n > 0; n--) { selection.SetItemSelected(items.back(), false); items.pop_back(); } }
3344
3345 // (1) Extra to support deletion: Submit scrolling range to avoid glitches on deletion
3346 const float items_height = ImGui::GetTextLineHeightWithSpacing();
3347 ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height));
3348
3349 if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY))
3350 {
3351 ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d;
3352 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size);
3353 selection.ApplyRequests(ms_io);
3354
3355 const bool want_delete = ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0);
3356 const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1;
3357
3358 for (int n = 0; n < items.Size; n++)
3359 {
3360 const ImGuiID item_id = items[n];
3361 char label[64];
3362 sprintf(label, "Object %05u: %s", item_id, ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)]);
3363
3364 bool item_is_selected = selection.Contains(item_id);
3365 ImGui::SetNextItemSelectionUserData(n);
3366 ImGui::Selectable(label, item_is_selected);
3367 if (item_curr_idx_to_focus == n)
3368 ImGui::SetKeyboardFocusHere(-1);
3369 }
3370
3371 // Apply multi-select requests
3372 ms_io = ImGui::EndMultiSelect();
3373 selection.ApplyRequests(ms_io);
3374 if (want_delete)
3375 selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus);
3376 }
3377 ImGui::EndChild();
3378 ImGui::TreePop();
3379 }
3380
3381 // Implement a Dual List Box (#6648)
3382 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (dual list box)");
3383 if (ImGui::TreeNode("Multi-Select (dual list box)"))
3384 {
3385 // Init default state
3386 static ExampleDualListBox dlb;
3387 if (dlb.Items[0].Size == 0 && dlb.Items[1].Size == 0)
3388 for (int item_id = 0; item_id < IM_ARRAYSIZE(ExampleNames); item_id++)
3389 dlb.Items[0].push_back((ImGuiID)item_id);
3390
3391 // Show
3392 dlb.Show();
3393
3394 ImGui::TreePop();
3395 }
3396
3397 // Demonstrate using the clipper with BeginMultiSelect()/EndMultiSelect()
3398 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (in a table)");
3399 if (ImGui::TreeNode("Multi-Select (in a table)"))
3400 {
3401 static ImGuiSelectionBasicStorage selection;
3402
3403 const int ITEMS_COUNT = 10000;
3404 ImGui::Text("Selection: %d/%d", selection.Size, ITEMS_COUNT);
3405 if (ImGui::BeginTable("##Basket", 2, ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter))
3406 {
3407 ImGui::TableSetupColumn("Object");
3408 ImGui::TableSetupColumn("Action");
3409 ImGui::TableSetupScrollFreeze(0, 1);
3410 ImGui::TableHeadersRow();
3411
3412 ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d;
3413 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, ITEMS_COUNT);
3414 selection.ApplyRequests(ms_io);
3415
3416 ImGuiListClipper clipper;
3417 clipper.Begin(ITEMS_COUNT);
3418 if (ms_io->RangeSrcItem != -1)
3419 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped.
3420 while (clipper.Step())
3421 {
3422 for (int n = clipper.DisplayStart; n < clipper.DisplayEnd; n++)
3423 {
3424 ImGui::TableNextRow();
3425 ImGui::TableNextColumn();
3426 char label[64];
3427 sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]);
3428 bool item_is_selected = selection.Contains((ImGuiID)n);
3429 ImGui::SetNextItemSelectionUserData(n);
3430 ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap);
3431 ImGui::TableNextColumn();
3432 ImGui::SmallButton("hello");
3433 }
3434 }
3435
3436 ms_io = ImGui::EndMultiSelect();
3437 selection.ApplyRequests(ms_io);
3438 ImGui::EndTable();
3439 }
3440 ImGui::TreePop();
3441 }
3442
3443 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (checkboxes)");
3444 if (ImGui::TreeNode("Multi-Select (checkboxes)"))
3445 {
3446 ImGui::Text("In a list of checkboxes (not selectable):");
3447 ImGui::BulletText("Using _NoAutoSelect + _NoAutoClear flags.");
3448 ImGui::BulletText("Shift+Click to check multiple boxes.");
3449 ImGui::BulletText("Shift+Keyboard to copy current value to other boxes.");
3450
3451 // If you have an array of checkboxes, you may want to use NoAutoSelect + NoAutoClear and the ImGuiSelectionExternalStorage helper.
3452 static bool items[20] = {};
3453 static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_NoAutoSelect | ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_ClearOnEscape;
3454 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect);
3455 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear);
3456 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d); // Cannot use ImGuiMultiSelectFlags_BoxSelect1d as checkboxes are varying width.
3457
3458 if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY))
3459 {
3460 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, -1, IM_ARRAYSIZE(items));
3461 ImGuiSelectionExternalStorage storage_wrapper;
3462 storage_wrapper.UserData = (void*)items;
3463 storage_wrapper.AdapterSetItemSelected = [](ImGuiSelectionExternalStorage* self, int n, bool selected) { bool* array = (bool*)self->UserData; array[n] = selected; };
3464 storage_wrapper.ApplyRequests(ms_io);
3465 for (int n = 0; n < 20; n++)
3466 {
3467 char label[32];
3468 sprintf(label, "Item %d", n);
3469 ImGui::SetNextItemSelectionUserData(n);
3470 ImGui::Checkbox(label, &items[n]);
3471 }
3472 ms_io = ImGui::EndMultiSelect();
3473 storage_wrapper.ApplyRequests(ms_io);
3474 }
3475 ImGui::EndChild();
3476
3477 ImGui::TreePop();
3478 }
3479
3480 // Demonstrate individual selection scopes in same window
3481 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (multiple scopes)");
3482 if (ImGui::TreeNode("Multi-Select (multiple scopes)"))
3483 {
3484 // Use default select: Pass index to SetNextItemSelectionUserData(), store index in Selection
3485 const int SCOPES_COUNT = 3;
3486 const int ITEMS_COUNT = 8; // Per scope
3487 static ImGuiSelectionBasicStorage selections_data[SCOPES_COUNT];
3488
3489 // Use ImGuiMultiSelectFlags_ScopeRect to not affect other selections in same window.
3490 static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ScopeRect | ImGuiMultiSelectFlags_ClearOnEscape;// | ImGuiMultiSelectFlags_ClearOnClickVoid;
3491 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow))
3492 flags &= ~ImGuiMultiSelectFlags_ScopeRect;
3493 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect))
3494 flags &= ~ImGuiMultiSelectFlags_ScopeWindow;
3495 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid);
3496 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d);
3497
3498 for (int selection_scope_n = 0; selection_scope_n < SCOPES_COUNT; selection_scope_n++)
3499 {
3500 ImGui::PushID(selection_scope_n);
3501 ImGuiSelectionBasicStorage* selection = &selections_data[selection_scope_n];
3502 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection->Size, ITEMS_COUNT);
3503 selection->ApplyRequests(ms_io);
3504
3505 ImGui::SeparatorText("Selection scope");
3506 ImGui::Text("Selection size: %d/%d", selection->Size, ITEMS_COUNT);
3507
3508 for (int n = 0; n < ITEMS_COUNT; n++)
3509 {
3510 char label[64];
3511 sprintf(label, "Object %05d: %s", n, ExampleNames[n % IM_ARRAYSIZE(ExampleNames)]);
3512 bool item_is_selected = selection->Contains((ImGuiID)n);
3513 ImGui::SetNextItemSelectionUserData(n);
3514 ImGui::Selectable(label, item_is_selected);
3515 }
3516
3517 // Apply multi-select requests
3518 ms_io = ImGui::EndMultiSelect();
3519 selection->ApplyRequests(ms_io);
3520 ImGui::PopID();
3521 }
3522 ImGui::TreePop();
3523 }
3524
3525 // See ShowExampleAppAssetsBrowser()
3526 if (ImGui::TreeNode("Multi-Select (tiled assets browser)"))
3527 {
3528 ImGui::Checkbox("Assets Browser", &demo_data->ShowAppAssetsBrowser);
3529 ImGui::Text("(also access from 'Examples->Assets Browser' in menu)");
3530 ImGui::TreePop();
3531 }
3532
3533 // Demonstrate supporting multiple-selection in a tree.
3534 // - We don't use linear indices for selection user data, but our ExampleTreeNode* pointer directly!
3535 // This showcase how SetNextItemSelectionUserData() never assume indices!
3536 // - The difficulty here is to "interpolate" from RangeSrcItem to RangeDstItem in the SetAll/SetRange request.
3537 // We want this interpolation to match what the user sees: in visible order, skipping closed nodes.
3538 // This is implemented by our TreeGetNextNodeInVisibleOrder() user-space helper.
3539 // - Important: In a real codebase aiming to implement full-featured selectable tree with custom filtering, you
3540 // are more likely to build an array mapping sequential indices to visible tree nodes, since your
3541 // filtering/search + clipping process will benefit from it. Having this will make this interpolation much easier.
3542 // - Consider this a prototype: we are working toward simplifying some of it.
3543 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (trees)");
3544 if (ImGui::TreeNode("Multi-Select (trees)"))
3545 {
3546 HelpMarker(
3547 "This is rather advanced and experimental. If you are getting started with multi-select,"
3548 "please don't start by looking at how to use it for a tree!\n\n"
3549 "Future versions will try to simplify and formalize some of this.");
3550
3551 struct ExampleTreeFuncs
3552 {
3553 static void DrawNode(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection)
3554 {
3555 ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
3556 tree_node_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Enable pressing left to jump to parent
3557 if (node->Childs.Size == 0)
3558 tree_node_flags |= ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_Leaf;
3559 if (selection->Contains((ImGuiID)node->UID))
3560 tree_node_flags |= ImGuiTreeNodeFlags_Selected;
3561
3562 // Using SetNextItemStorageID() to specify storage id, so we can easily peek into
3563 // the storage holding open/close stage, using our TreeNodeGetOpen/TreeNodeSetOpen() functions.
3564 ImGui::SetNextItemSelectionUserData((ImGuiSelectionUserData)(intptr_t)node);
3565 ImGui::SetNextItemStorageID((ImGuiID)node->UID);
3566 if (ImGui::TreeNodeEx(node->Name, tree_node_flags))
3567 {
3568 for (ExampleTreeNode* child : node->Childs)
3569 DrawNode(child, selection);
3570 ImGui::TreePop();
3571 }
3572 else if (ImGui::IsItemToggledOpen())
3573 {
3574 TreeCloseAndUnselectChildNodes(node, selection);
3575 }
3576 }
3577
3578 static bool TreeNodeGetOpen(ExampleTreeNode* node)
3579 {
3580 return ImGui::GetStateStorage()->GetBool((ImGuiID)node->UID);
3581 }
3582
3583 static void TreeNodeSetOpen(ExampleTreeNode* node, bool open)
3584 {
3585 ImGui::GetStateStorage()->SetBool((ImGuiID)node->UID, open);
3586 }
3587
3588 // When closing a node: 1) close and unselect all child nodes, 2) select parent if any child was selected.
3589 // FIXME: This is currently handled by user logic but I'm hoping to eventually provide tree node
3590 // features to do this automatically, e.g. a ImGuiTreeNodeFlags_AutoCloseChildNodes etc.
3591 static int TreeCloseAndUnselectChildNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, int depth = 0)
3592 {
3593 // Recursive close (the test for depth == 0 is because we call this on a node that was just closed!)
3594 int unselected_count = selection->Contains((ImGuiID)node->UID) ? 1 : 0;
3595 if (depth == 0 || TreeNodeGetOpen(node))
3596 {
3597 for (ExampleTreeNode* child : node->Childs)
3598 unselected_count += TreeCloseAndUnselectChildNodes(child, selection, depth + 1);
3599 TreeNodeSetOpen(node, false);
3600 }
3601
3602 // Select root node if any of its child was selected, otherwise unselect
3603 selection->SetItemSelected((ImGuiID)node->UID, (depth == 0 && unselected_count > 0));
3604 return unselected_count;
3605 }
3606
3607 // Apply multi-selection requests
3608 static void ApplySelectionRequests(ImGuiMultiSelectIO* ms_io, ExampleTreeNode* tree, ImGuiSelectionBasicStorage* selection)
3609 {
3610 for (ImGuiSelectionRequest& req : ms_io->Requests)
3611 {
3612 if (req.Type == ImGuiSelectionRequestType_SetAll)
3613 {
3614 if (req.Selected)
3615 TreeSetAllInOpenNodes(tree, selection, req.Selected);
3616 else
3617 selection->Clear();
3618 }
3619 else if (req.Type == ImGuiSelectionRequestType_SetRange)
3620 {
3621 ExampleTreeNode* first_node = (ExampleTreeNode*)(intptr_t)req.RangeFirstItem;
3622 ExampleTreeNode* last_node = (ExampleTreeNode*)(intptr_t)req.RangeLastItem;
3623 for (ExampleTreeNode* node = first_node; node != NULL; node = TreeGetNextNodeInVisibleOrder(node, last_node))
3624 selection->SetItemSelected((ImGuiID)node->UID, req.Selected);
3625 }
3626 }
3627 }
3628
3629 static void TreeSetAllInOpenNodes(ExampleTreeNode* node, ImGuiSelectionBasicStorage* selection, bool selected)
3630 {
3631 if (node->Parent != NULL) // Root node isn't visible nor selectable in our scheme
3632 selection->SetItemSelected((ImGuiID)node->UID, selected);
3633 if (node->Parent == NULL || TreeNodeGetOpen(node))
3634 for (ExampleTreeNode* child : node->Childs)
3635 TreeSetAllInOpenNodes(child, selection, selected);
3636 }
3637
3638 // Interpolate in *user-visible order* AND only *over opened nodes*.
3639 // If you have a sequential mapping tables (e.g. generated after a filter/search pass) this would be simpler.
3640 // Here the tricks are that:
3641 // - we store/maintain ExampleTreeNode::IndexInParent which allows implementing a linear iterator easily, without searches, without recursion.
3642 // this could be replaced by a search in parent, aka 'int index_in_parent = curr_node->Parent->Childs.find_index(curr_node)'
3643 // which would only be called when crossing from child to a parent, aka not too much.
3644 // - we call SetNextItemStorageID() before our TreeNode() calls with an ID which doesn't relate to UI stack,
3645 // making it easier to call TreeNodeGetOpen()/TreeNodeSetOpen() from any location.
3646 static ExampleTreeNode* TreeGetNextNodeInVisibleOrder(ExampleTreeNode* curr_node, ExampleTreeNode* last_node)
3647 {
3648 // Reached last node
3649 if (curr_node == last_node)
3650 return NULL;
3651
3652 // Recurse into childs. Query storage to tell if the node is open.
3653 if (curr_node->Childs.Size > 0 && TreeNodeGetOpen(curr_node))
3654 return curr_node->Childs[0];
3655
3656 // Next sibling, then into our own parent
3657 while (curr_node->Parent != NULL)
3658 {
3659 if (curr_node->IndexInParent + 1 < curr_node->Parent->Childs.Size)
3660 return curr_node->Parent->Childs[curr_node->IndexInParent + 1];
3661 curr_node = curr_node->Parent;
3662 }
3663 return NULL;
3664 }
3665
3666 }; // ExampleTreeFuncs
3667
3668 static ImGuiSelectionBasicStorage selection;
3669 if (demo_data->DemoTree == NULL)
3670 demo_data->DemoTree = ExampleTree_CreateDemoTree(); // Create tree once
3671 ImGui::Text("Selection size: %d", selection.Size);
3672
3673 if (ImGui::BeginChild("##Tree", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY))
3674 {
3675 ExampleTreeNode* tree = demo_data->DemoTree;
3676 ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect2d;
3677 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, selection.Size, -1);
3678 ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection);
3679 for (ExampleTreeNode* node : tree->Childs)
3680 ExampleTreeFuncs::DrawNode(node, &selection);
3681 ms_io = ImGui::EndMultiSelect();
3682 ExampleTreeFuncs::ApplySelectionRequests(ms_io, tree, &selection);
3683 }
3684 ImGui::EndChild();
3685
3686 ImGui::TreePop();
3687 }
3688
3689 // Advanced demonstration of BeginMultiSelect()
3690 // - Showcase clipping.
3691 // - Showcase deletion.
3692 // - Showcase basic drag and drop.
3693 // - Showcase TreeNode variant (note that tree node don't expand in the demo: supporting expanding tree nodes + clipping a separate thing).
3694 // - Showcase using inside a table.
3695 IMGUI_DEMO_MARKER("Widgets/Selection State/Multi-Select (advanced)");
3696 //ImGui::SetNextItemOpen(true, ImGuiCond_Once);
3697 if (ImGui::TreeNode("Multi-Select (advanced)"))
3698 {
3699 // Options
3700 enum WidgetType { WidgetType_Selectable, WidgetType_TreeNode };
3701 static bool use_clipper = true;
3702 static bool use_deletion = true;
3703 static bool use_drag_drop = true;
3704 static bool show_in_table = false;
3705 static bool show_color_button = true;
3706 static ImGuiMultiSelectFlags flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_BoxSelect1d;
3707 static WidgetType widget_type = WidgetType_Selectable;
3708
3709 if (ImGui::TreeNode("Options"))
3710 {
3711 if (ImGui::RadioButton("Selectables", widget_type == WidgetType_Selectable)) { widget_type = WidgetType_Selectable; }
3712 ImGui::SameLine();
3713 if (ImGui::RadioButton("Tree nodes", widget_type == WidgetType_TreeNode)) { widget_type = WidgetType_TreeNode; }
3714 ImGui::SameLine();
3715 HelpMarker("TreeNode() is technically supported but... using this correctly is more complicated (you need some sort of linear/random access to your tree, which is suited to advanced trees setups already implementing filters and clipper. We will work toward simplifying and demoing this.\n\nFor now the tree demo is actually a little bit meaningless because it is an empty tree with only root nodes.");
3716 ImGui::Checkbox("Enable clipper", &use_clipper);
3717 ImGui::Checkbox("Enable deletion", &use_deletion);
3718 ImGui::Checkbox("Enable drag & drop", &use_drag_drop);
3719 ImGui::Checkbox("Show in a table", &show_in_table);
3720 ImGui::Checkbox("Show color button", &show_color_button);
3721 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SingleSelect", &flags, ImGuiMultiSelectFlags_SingleSelect);
3722 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoSelectAll", &flags, ImGuiMultiSelectFlags_NoSelectAll);
3723 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoRangeSelect", &flags, ImGuiMultiSelectFlags_NoRangeSelect);
3724 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoSelect", &flags, ImGuiMultiSelectFlags_NoAutoSelect);
3725 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClear", &flags, ImGuiMultiSelectFlags_NoAutoClear);
3726 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_NoAutoClearOnReselect", &flags, ImGuiMultiSelectFlags_NoAutoClearOnReselect);
3727 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect1d", &flags, ImGuiMultiSelectFlags_BoxSelect1d);
3728 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelect2d", &flags, ImGuiMultiSelectFlags_BoxSelect2d);
3729 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_BoxSelectNoScroll", &flags, ImGuiMultiSelectFlags_BoxSelectNoScroll);
3730 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnEscape", &flags, ImGuiMultiSelectFlags_ClearOnEscape);
3731 ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ClearOnClickVoid", &flags, ImGuiMultiSelectFlags_ClearOnClickVoid);
3732 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeWindow", &flags, ImGuiMultiSelectFlags_ScopeWindow) && (flags & ImGuiMultiSelectFlags_ScopeWindow))
3733 flags &= ~ImGuiMultiSelectFlags_ScopeRect;
3734 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_ScopeRect", &flags, ImGuiMultiSelectFlags_ScopeRect) && (flags & ImGuiMultiSelectFlags_ScopeRect))
3735 flags &= ~ImGuiMultiSelectFlags_ScopeWindow;
3736 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClick", &flags, ImGuiMultiSelectFlags_SelectOnClick) && (flags & ImGuiMultiSelectFlags_SelectOnClick))
3737 flags &= ~ImGuiMultiSelectFlags_SelectOnClickRelease;
3738 if (ImGui::CheckboxFlags("ImGuiMultiSelectFlags_SelectOnClickRelease", &flags, ImGuiMultiSelectFlags_SelectOnClickRelease) && (flags & ImGuiMultiSelectFlags_SelectOnClickRelease))
3739 flags &= ~ImGuiMultiSelectFlags_SelectOnClick;
3740 ImGui::SameLine(); HelpMarker("Allow dragging an unselected item without altering selection.");
3741 ImGui::TreePop();
3742 }
3743
3744 // Initialize default list with 1000 items.
3745 // Use default selection.Adapter: Pass index to SetNextItemSelectionUserData(), store index in Selection
3746 static ImVector<int> items;
3747 static int items_next_id = 0;
3748 if (items_next_id == 0) { for (int n = 0; n < 1000; n++) { items.push_back(items_next_id++); } }
3749 static ExampleSelectionWithDeletion selection;
3750 static bool request_deletion_from_menu = false; // Queue deletion triggered from context menu
3751
3752 ImGui::Text("Selection size: %d/%d", selection.Size, items.Size);
3753
3754 const float items_height = (widget_type == WidgetType_TreeNode) ? ImGui::GetTextLineHeight() : ImGui::GetTextLineHeightWithSpacing();
3755 ImGui::SetNextWindowContentSize(ImVec2(0.0f, items.Size * items_height));
3756 if (ImGui::BeginChild("##Basket", ImVec2(-FLT_MIN, ImGui::GetFontSize() * 20), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY))
3757 {
3758 ImVec2 color_button_sz(ImGui::GetFontSize(), ImGui::GetFontSize());
3759 if (widget_type == WidgetType_TreeNode)
3760 ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, 0.0f);
3761
3762 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(flags, selection.Size, items.Size);
3763 selection.ApplyRequests(ms_io);
3764
3765 const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (selection.Size > 0)) || request_deletion_from_menu;
3766 const int item_curr_idx_to_focus = want_delete ? selection.ApplyDeletionPreLoop(ms_io, items.Size) : -1;
3767 request_deletion_from_menu = false;
3768
3769 if (show_in_table)
3770 {
3771 if (widget_type == WidgetType_TreeNode)
3772 ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2(0.0f, 0.0f));
3773 ImGui::BeginTable("##Split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_NoPadOuterX);
3774 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.70f);
3775 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 0.30f);
3776 //ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacingY, 0.0f);
3777 }
3778
3779 ImGuiListClipper clipper;
3780 if (use_clipper)
3781 {
3782 clipper.Begin(items.Size);
3783 if (item_curr_idx_to_focus != -1)
3784 clipper.IncludeItemByIndex(item_curr_idx_to_focus); // Ensure focused item is not clipped.
3785 if (ms_io->RangeSrcItem != -1)
3786 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem); // Ensure RangeSrc item is not clipped.
3787 }
3788
3789 while (!use_clipper || clipper.Step())
3790 {
3791 const int item_begin = use_clipper ? clipper.DisplayStart : 0;
3792 const int item_end = use_clipper ? clipper.DisplayEnd : items.Size;
3793 for (int n = item_begin; n < item_end; n++)
3794 {
3795 if (show_in_table)
3796 ImGui::TableNextColumn();
3797
3798 const int item_id = items[n];
3799 const char* item_category = ExampleNames[item_id % IM_ARRAYSIZE(ExampleNames)];
3800 char label[64];
3801 sprintf(label, "Object %05d: %s", item_id, item_category);
3802
3803 // IMPORTANT: for deletion refocus to work we need object ID to be stable,
3804 // aka not depend on their index in the list. Here we use our persistent item_id
3805 // instead of index to build a unique ID that will persist.
3806 // (If we used PushID(index) instead, focus wouldn't be restored correctly after deletion).
3807 ImGui::PushID(item_id);
3808
3809 // Emit a color button, to test that Shift+LeftArrow landing on an item that is not part
3810 // of the selection scope doesn't erroneously alter our selection.
3811 if (show_color_button)
3812 {
3813 ImU32 dummy_col = (ImU32)((unsigned int)n * 0xC250B74B) | IM_COL32_A_MASK;
3814 ImGui::ColorButton("##", ImColor(dummy_col), ImGuiColorEditFlags_NoTooltip, color_button_sz);
3815 ImGui::SameLine();
3816 }
3817
3818 // Submit item
3819 bool item_is_selected = selection.Contains((ImGuiID)n);
3820 bool item_is_open = false;
3821 ImGui::SetNextItemSelectionUserData(n);
3822 if (widget_type == WidgetType_Selectable)
3823 {
3824 ImGui::Selectable(label, item_is_selected, ImGuiSelectableFlags_None);
3825 }
3826 else if (widget_type == WidgetType_TreeNode)
3827 {
3828 ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
3829 if (item_is_selected)
3830 tree_node_flags |= ImGuiTreeNodeFlags_Selected;
3831 item_is_open = ImGui::TreeNodeEx(label, tree_node_flags);
3832 }
3833
3834 // Focus (for after deletion)
3835 if (item_curr_idx_to_focus == n)
3836 ImGui::SetKeyboardFocusHere(-1);
3837
3838 // Drag and Drop
3839 if (use_drag_drop && ImGui::BeginDragDropSource())
3840 {
3841 // Create payload with full selection OR single unselected item.
3842 // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease)
3843 if (ImGui::GetDragDropPayload() == NULL)
3844 {
3845 ImVector<int> payload_items;
3846 void* it = NULL;
3847 ImGuiID id = 0;
3848 if (!item_is_selected)
3849 payload_items.push_back(item_id);
3850 else
3851 while (selection.GetNextSelectedItem(&it, &id))
3852 payload_items.push_back((int)id);
3853 ImGui::SetDragDropPayload("MULTISELECT_DEMO_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes());
3854 }
3855
3856 // Display payload content in tooltip
3857 const ImGuiPayload* payload = ImGui::GetDragDropPayload();
3858 const int* payload_items = (int*)payload->Data;
3859 const int payload_count = (int)payload->DataSize / (int)sizeof(int);
3860 if (payload_count == 1)
3861 ImGui::Text("Object %05d: %s", payload_items[0], ExampleNames[payload_items[0] % IM_ARRAYSIZE(ExampleNames)]);
3862 else
3863 ImGui::Text("Dragging %d objects", payload_count);
3864
3865 ImGui::EndDragDropSource();
3866 }
3867
3868 if (widget_type == WidgetType_TreeNode && item_is_open)
3869 ImGui::TreePop();
3870
3871 // Right-click: context menu
3872 if (ImGui::BeginPopupContextItem())
3873 {
3874 ImGui::BeginDisabled(!use_deletion || selection.Size == 0);
3875 sprintf(label, "Delete %d item(s)###DeleteSelected", selection.Size);
3876 if (ImGui::Selectable(label))
3877 request_deletion_from_menu = true;
3878 ImGui::EndDisabled();
3879 ImGui::Selectable("Close");
3880 ImGui::EndPopup();
3881 }
3882
3883 // Demo content within a table
3884 if (show_in_table)
3885 {
3886 ImGui::TableNextColumn();
3887 ImGui::SetNextItemWidth(-FLT_MIN);
3888 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
3889 ImGui::InputText("###NoLabel", (char*)(void*)item_category, strlen(item_category), ImGuiInputTextFlags_ReadOnly);
3890 ImGui::PopStyleVar();
3891 }
3892
3893 ImGui::PopID();
3894 }
3895 if (!use_clipper)
3896 break;
3897 }
3898
3899 if (show_in_table)
3900 {
3901 ImGui::EndTable();
3902 if (widget_type == WidgetType_TreeNode)
3903 ImGui::PopStyleVar();
3904 }
3905
3906 // Apply multi-select requests
3907 ms_io = ImGui::EndMultiSelect();
3908 selection.ApplyRequests(ms_io);
3909 if (want_delete)
3910 selection.ApplyDeletionPostLoop(ms_io, items, item_curr_idx_to_focus);
3911
3912 if (widget_type == WidgetType_TreeNode)
3913 ImGui::PopStyleVar();
3914 }
3915 ImGui::EndChild();
3916 ImGui::TreePop();
3917 }
3918 ImGui::TreePop();
3919 }
3920 }
3921
3922 //-----------------------------------------------------------------------------
3923 // [SECTION] ShowDemoWindowLayout()
3924 //-----------------------------------------------------------------------------
3925
3926 static void ShowDemoWindowLayout()
3927 {
3928 IMGUI_DEMO_MARKER("Layout");
3929 if (!ImGui::CollapsingHeader("Layout & Scrolling"))
3930 return;
3931
3932 IMGUI_DEMO_MARKER("Layout/Child windows");
3933 if (ImGui::TreeNode("Child windows"))
3934 {
3935 ImGui::SeparatorText("Child windows");
3936
3937 HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.");
3938 static bool disable_mouse_wheel = false;
3939 static bool disable_menu = false;
3940 ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
3941 ImGui::Checkbox("Disable Menu", &disable_menu);
3942
3943 // Child 1: no border, enable horizontal scrollbar
3944 {
3945 ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar;
3946 if (disable_mouse_wheel)
3947 window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
3948 ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), ImGuiChildFlags_None, window_flags);
3949 for (int i = 0; i < 100; i++)
3950 ImGui::Text("%04d: scrollable region", i);
3951 ImGui::EndChild();
3952 }
3953
3954 ImGui::SameLine();
3955
3956 // Child 2: rounded border
3957 {
3958 ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;
3959 if (disable_mouse_wheel)
3960 window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
3961 if (!disable_menu)
3962 window_flags |= ImGuiWindowFlags_MenuBar;
3963 ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
3964 ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags);
3965 if (!disable_menu && ImGui::BeginMenuBar())
3966 {
3967 if (ImGui::BeginMenu("Menu"))
3968 {
3969 ShowExampleMenuFile();
3970 ImGui::EndMenu();
3971 }
3972 ImGui::EndMenuBar();
3973 }
3974 if (ImGui::BeginTable("split", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))
3975 {
3976 for (int i = 0; i < 100; i++)
3977 {
3978 char buf[32];
3979 sprintf(buf, "%03d", i);
3980 ImGui::TableNextColumn();
3981 ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
3982 }
3983 ImGui::EndTable();
3984 }
3985 ImGui::EndChild();
3986 ImGui::PopStyleVar();
3987 }
3988
3989 // Child 3: manual-resize
3990 ImGui::SeparatorText("Manual-resize");
3991 {
3992 HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents.");
3993 //if (ImGui::Button("Set Height to 200"))
3994 // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f));
3995
3996 ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
3997 if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY))
3998 for (int n = 0; n < 10; n++)
3999 ImGui::Text("Line %04d", n);
4000 ImGui::PopStyleColor();
4001 ImGui::EndChild();
4002 }
4003
4004 // Child 4: auto-resizing height with a limit
4005 ImGui::SeparatorText("Auto-resize with constraints");
4006 {
4007 static int draw_lines = 3;
4008 static int max_height_in_lines = 10;
4009 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
4010 ImGui::DragInt("Lines Count", &draw_lines, 0.2f);
4011 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
4012 ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f);
4013
4014 ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 1), ImVec2(FLT_MAX, ImGui::GetTextLineHeightWithSpacing() * max_height_in_lines));
4015 if (ImGui::BeginChild("ConstrainedChild", ImVec2(-FLT_MIN, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY))
4016 for (int n = 0; n < draw_lines; n++)
4017 ImGui::Text("Line %04d", n);
4018 ImGui::EndChild();
4019 }
4020
4021 ImGui::SeparatorText("Misc/Advanced");
4022
4023 // Demonstrate a few extra things
4024 // - Changing ImGuiCol_ChildBg (which is transparent black in default styles)
4025 // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)
4026 // You can also call SetNextWindowPos() to position the child window. The parent window will effectively
4027 // layout from this position.
4028 // - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from
4029 // the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details.
4030 {
4031 static int offset_x = 0;
4032 static bool override_bg_color = true;
4033 static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY;
4034 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
4035 ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000);
4036 ImGui::Checkbox("Override ChildBg color", &override_bg_color);
4037 ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders);
4038 ImGui::CheckboxFlags("ImGuiChildFlags_AlwaysUseWindowPadding", &child_flags, ImGuiChildFlags_AlwaysUseWindowPadding);
4039 ImGui::CheckboxFlags("ImGuiChildFlags_ResizeX", &child_flags, ImGuiChildFlags_ResizeX);
4040 ImGui::CheckboxFlags("ImGuiChildFlags_ResizeY", &child_flags, ImGuiChildFlags_ResizeY);
4041 ImGui::CheckboxFlags("ImGuiChildFlags_FrameStyle", &child_flags, ImGuiChildFlags_FrameStyle);
4042 ImGui::SameLine(); HelpMarker("Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding.");
4043 if (child_flags & ImGuiChildFlags_FrameStyle)
4044 override_bg_color = false;
4045
4046 ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x);
4047 if (override_bg_color)
4048 ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100));
4049 ImGui::BeginChild("Red", ImVec2(200, 100), child_flags, ImGuiWindowFlags_None);
4050 if (override_bg_color)
4051 ImGui::PopStyleColor();
4052
4053 for (int n = 0; n < 50; n++)
4054 ImGui::Text("Some test %d", n);
4055 ImGui::EndChild();
4056 bool child_is_hovered = ImGui::IsItemHovered();
4057 ImVec2 child_rect_min = ImGui::GetItemRectMin();
4058 ImVec2 child_rect_max = ImGui::GetItemRectMax();
4059 ImGui::Text("Hovered: %d", child_is_hovered);
4060 ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y);
4061 }
4062
4063 ImGui::TreePop();
4064 }
4065
4066 IMGUI_DEMO_MARKER("Layout/Widgets Width");
4067 if (ImGui::TreeNode("Widgets Width"))
4068 {
4069 static float f = 0.0f;
4070 static bool show_indented_items = true;
4071 ImGui::Checkbox("Show indented items", &show_indented_items);
4072
4073 // Use SetNextItemWidth() to set the width of a single upcoming item.
4074 // Use PushItemWidth()/PopItemWidth() to set the width of a group of items.
4075 // In real code use you'll probably want to choose width values that are proportional to your font size
4076 // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc.
4077
4078 ImGui::Text("SetNextItemWidth/PushItemWidth(100)");
4079 ImGui::SameLine(); HelpMarker("Fixed width.");
4080 ImGui::PushItemWidth(100);
4081 ImGui::DragFloat("float##1b", &f);
4082 if (show_indented_items)
4083 {
4084 ImGui::Indent();
4085 ImGui::DragFloat("float (indented)##1b", &f);
4086 ImGui::Unindent();
4087 }
4088 ImGui::PopItemWidth();
4089
4090 ImGui::Text("SetNextItemWidth/PushItemWidth(-100)");
4091 ImGui::SameLine(); HelpMarker("Align to right edge minus 100");
4092 ImGui::PushItemWidth(-100);
4093 ImGui::DragFloat("float##2a", &f);
4094 if (show_indented_items)
4095 {
4096 ImGui::Indent();
4097 ImGui::DragFloat("float (indented)##2b", &f);
4098 ImGui::Unindent();
4099 }
4100 ImGui::PopItemWidth();
4101
4102 ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)");
4103 ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
4104 ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
4105 ImGui::DragFloat("float##3a", &f);
4106 if (show_indented_items)
4107 {
4108 ImGui::Indent();
4109 ImGui::DragFloat("float (indented)##3b", &f);
4110 ImGui::Unindent();
4111 }
4112 ImGui::PopItemWidth();
4113
4114 ImGui::Text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)");
4115 ImGui::SameLine(); HelpMarker("Align to right edge minus half");
4116 ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);
4117 ImGui::DragFloat("float##4a", &f);
4118 if (show_indented_items)
4119 {
4120 ImGui::Indent();
4121 ImGui::DragFloat("float (indented)##4b", &f);
4122 ImGui::Unindent();
4123 }
4124 ImGui::PopItemWidth();
4125
4126 // Demonstrate using PushItemWidth to surround three items.
4127 // Calling SetNextItemWidth() before each of them would have the same effect.
4128 ImGui::Text("SetNextItemWidth/PushItemWidth(-FLT_MIN)");
4129 ImGui::SameLine(); HelpMarker("Align to right edge");
4130 ImGui::PushItemWidth(-FLT_MIN);
4131 ImGui::DragFloat("##float5a", &f);
4132 if (show_indented_items)
4133 {
4134 ImGui::Indent();
4135 ImGui::DragFloat("float (indented)##5b", &f);
4136 ImGui::Unindent();
4137 }
4138 ImGui::PopItemWidth();
4139
4140 ImGui::TreePop();
4141 }
4142
4143 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout");
4144 if (ImGui::TreeNode("Basic Horizontal Layout"))
4145 {
4146 ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)");
4147
4148 // Text
4149 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine");
4150 ImGui::Text("Two items: Hello"); ImGui::SameLine();
4151 ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
4152
4153 // Adjust spacing
4154 ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20);
4155 ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
4156
4157 // Button
4158 ImGui::AlignTextToFramePadding();
4159 ImGui::Text("Normal buttons"); ImGui::SameLine();
4160 ImGui::Button("Banana"); ImGui::SameLine();
4161 ImGui::Button("Apple"); ImGui::SameLine();
4162 ImGui::Button("Corniflower");
4163
4164 // Button
4165 ImGui::Text("Small buttons"); ImGui::SameLine();
4166 ImGui::SmallButton("Like this one"); ImGui::SameLine();
4167 ImGui::Text("can fit within a text block.");
4168
4169 // Aligned to arbitrary position. Easy/cheap column.
4170 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (with offset)");
4171 ImGui::Text("Aligned");
4172 ImGui::SameLine(150); ImGui::Text("x=150");
4173 ImGui::SameLine(300); ImGui::Text("x=300");
4174 ImGui::Text("Aligned");
4175 ImGui::SameLine(150); ImGui::SmallButton("x=150");
4176 ImGui::SameLine(300); ImGui::SmallButton("x=300");
4177
4178 // Checkbox
4179 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/SameLine (more)");
4180 static bool c1 = false, c2 = false, c3 = false, c4 = false;
4181 ImGui::Checkbox("My", &c1); ImGui::SameLine();
4182 ImGui::Checkbox("Tailor", &c2); ImGui::SameLine();
4183 ImGui::Checkbox("Is", &c3); ImGui::SameLine();
4184 ImGui::Checkbox("Rich", &c4);
4185
4186 // Various
4187 static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f;
4188 ImGui::PushItemWidth(80);
4189 const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" };
4190 static int item = -1;
4191 ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine();
4192 ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine();
4193 ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine();
4194 ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f);
4195 ImGui::PopItemWidth();
4196
4197 ImGui::PushItemWidth(80);
4198 ImGui::Text("Lists:");
4199 static int selection[4] = { 0, 1, 2, 3 };
4200 for (int i = 0; i < 4; i++)
4201 {
4202 if (i > 0) ImGui::SameLine();
4203 ImGui::PushID(i);
4204 ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items));
4205 ImGui::PopID();
4206 //ImGui::SetItemTooltip("ListBox %d hovered", i);
4207 }
4208 ImGui::PopItemWidth();
4209
4210 // Dummy
4211 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy");
4212 ImVec2 button_sz(40, 40);
4213 ImGui::Button("A", button_sz); ImGui::SameLine();
4214 ImGui::Dummy(button_sz); ImGui::SameLine();
4215 ImGui::Button("B", button_sz);
4216
4217 // Manually wrapping
4218 // (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
4219 IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping");
4220 ImGui::Text("Manual wrapping:");
4221 ImGuiStyle& style = ImGui::GetStyle();
4222 int buttons_count = 20;
4223 float window_visible_x2 = ImGui::GetCursorScreenPos().x + ImGui::GetContentRegionAvail().x;
4224 for (int n = 0; n < buttons_count; n++)
4225 {
4226 ImGui::PushID(n);
4227 ImGui::Button("Box", button_sz);
4228 float last_button_x2 = ImGui::GetItemRectMax().x;
4229 float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line
4230 if (n + 1 < buttons_count && next_button_x2 < window_visible_x2)
4231 ImGui::SameLine();
4232 ImGui::PopID();
4233 }
4234
4235 ImGui::TreePop();
4236 }
4237
4238 IMGUI_DEMO_MARKER("Layout/Groups");
4239 if (ImGui::TreeNode("Groups"))
4240 {
4241 HelpMarker(
4242 "BeginGroup() basically locks the horizontal position for new line. "
4243 "EndGroup() bundles the whole group so that you can use \"item\" functions such as "
4244 "IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.");
4245 ImGui::BeginGroup();
4246 {
4247 ImGui::BeginGroup();
4248 ImGui::Button("AAA");
4249 ImGui::SameLine();
4250 ImGui::Button("BBB");
4251 ImGui::SameLine();
4252 ImGui::BeginGroup();
4253 ImGui::Button("CCC");
4254 ImGui::Button("DDD");
4255 ImGui::EndGroup();
4256 ImGui::SameLine();
4257 ImGui::Button("EEE");
4258 ImGui::EndGroup();
4259 ImGui::SetItemTooltip("First group hovered");
4260 }
4261 // Capture the group size and create widgets using the same size
4262 ImVec2 size = ImGui::GetItemRectSize();
4263 const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f };
4264 ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);
4265
4266 ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
4267 ImGui::SameLine();
4268 ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
4269 ImGui::EndGroup();
4270 ImGui::SameLine();
4271
4272 ImGui::Button("LEVERAGE\nBUZZWORD", size);
4273 ImGui::SameLine();
4274
4275 if (ImGui::BeginListBox("List", size))
4276 {
4277 ImGui::Selectable("Selected", true);
4278 ImGui::Selectable("Not Selected", false);
4279 ImGui::EndListBox();
4280 }
4281
4282 ImGui::TreePop();
4283 }
4284
4285 IMGUI_DEMO_MARKER("Layout/Text Baseline Alignment");
4286 if (ImGui::TreeNode("Text Baseline Alignment"))
4287 {
4288 {
4289 ImGui::BulletText("Text baseline:");
4290 ImGui::SameLine(); HelpMarker(
4291 "This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. "
4292 "Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.");
4293 ImGui::Indent();
4294
4295 ImGui::Text("KO Blahblah"); ImGui::SameLine();
4296 ImGui::Button("Some framed item"); ImGui::SameLine();
4297 HelpMarker("Baseline of button will look misaligned with text..");
4298
4299 // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
4300 // (because we don't know what's coming after the Text() statement, we need to move the text baseline
4301 // down by FramePadding.y ahead of time)
4302 ImGui::AlignTextToFramePadding();
4303 ImGui::Text("OK Blahblah"); ImGui::SameLine();
4304 ImGui::Button("Some framed item##2"); ImGui::SameLine();
4305 HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y");
4306
4307 // SmallButton() uses the same vertical padding as Text
4308 ImGui::Button("TEST##1"); ImGui::SameLine();
4309 ImGui::Text("TEST"); ImGui::SameLine();
4310 ImGui::SmallButton("TEST##2");
4311
4312 // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
4313 ImGui::AlignTextToFramePadding();
4314 ImGui::Text("Text aligned to framed item"); ImGui::SameLine();
4315 ImGui::Button("Item##1"); ImGui::SameLine();
4316 ImGui::Text("Item"); ImGui::SameLine();
4317 ImGui::SmallButton("Item##2"); ImGui::SameLine();
4318 ImGui::Button("Item##3");
4319
4320 ImGui::Unindent();
4321 }
4322
4323 ImGui::Spacing();
4324
4325 {
4326 ImGui::BulletText("Multi-line text:");
4327 ImGui::Indent();
4328 ImGui::Text("One\nTwo\nThree"); ImGui::SameLine();
4329 ImGui::Text("Hello\nWorld"); ImGui::SameLine();
4330 ImGui::Text("Banana");
4331
4332 ImGui::Text("Banana"); ImGui::SameLine();
4333 ImGui::Text("Hello\nWorld"); ImGui::SameLine();
4334 ImGui::Text("One\nTwo\nThree");
4335
4336 ImGui::Button("HOP##1"); ImGui::SameLine();
4337 ImGui::Text("Banana"); ImGui::SameLine();
4338 ImGui::Text("Hello\nWorld"); ImGui::SameLine();
4339 ImGui::Text("Banana");
4340
4341 ImGui::Button("HOP##2"); ImGui::SameLine();
4342 ImGui::Text("Hello\nWorld"); ImGui::SameLine();
4343 ImGui::Text("Banana");
4344 ImGui::Unindent();
4345 }
4346
4347 ImGui::Spacing();
4348
4349 {
4350 ImGui::BulletText("Misc items:");
4351 ImGui::Indent();
4352
4353 // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.
4354 ImGui::Button("80x80", ImVec2(80, 80));
4355 ImGui::SameLine();
4356 ImGui::Button("50x50", ImVec2(50, 50));
4357 ImGui::SameLine();
4358 ImGui::Button("Button()");
4359 ImGui::SameLine();
4360 ImGui::SmallButton("SmallButton()");
4361
4362 // Tree
4363 const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
4364 ImGui::Button("Button##1");
4365 ImGui::SameLine(0.0f, spacing);
4366 if (ImGui::TreeNode("Node##1"))
4367 {
4368 // Placeholder tree data
4369 for (int i = 0; i < 6; i++)
4370 ImGui::BulletText("Item %d..", i);
4371 ImGui::TreePop();
4372 }
4373
4374 // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.
4375 // Otherwise you can use SmallButton() (smaller fit).
4376 ImGui::AlignTextToFramePadding();
4377
4378 // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add
4379 // other contents below the node.
4380 bool node_open = ImGui::TreeNode("Node##2");
4381 ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2");
4382 if (node_open)
4383 {
4384 // Placeholder tree data
4385 for (int i = 0; i < 6; i++)
4386 ImGui::BulletText("Item %d..", i);
4387 ImGui::TreePop();
4388 }
4389
4390 // Bullet
4391 ImGui::Button("Button##3");
4392 ImGui::SameLine(0.0f, spacing);
4393 ImGui::BulletText("Bullet text");
4394
4395 ImGui::AlignTextToFramePadding();
4396 ImGui::BulletText("Node");
4397 ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4");
4398 ImGui::Unindent();
4399 }
4400
4401 ImGui::TreePop();
4402 }
4403
4404 IMGUI_DEMO_MARKER("Layout/Scrolling");
4405 if (ImGui::TreeNode("Scrolling"))
4406 {
4407 // Vertical scroll functions
4408 IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical");
4409 HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.");
4410
4411 static int track_item = 50;
4412 static bool enable_track = true;
4413 static bool enable_extra_decorations = false;
4414 static float scroll_to_off_px = 0.0f;
4415 static float scroll_to_pos_px = 200.0f;
4416
4417 ImGui::Checkbox("Decoration", &enable_extra_decorations);
4418
4419 ImGui::Checkbox("Track", &enable_track);
4420 ImGui::PushItemWidth(100);
4421 ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d");
4422
4423 bool scroll_to_off = ImGui::Button("Scroll Offset");
4424 ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px");
4425
4426 bool scroll_to_pos = ImGui::Button("Scroll To Pos");
4427 ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px");
4428 ImGui::PopItemWidth();
4429
4430 if (scroll_to_off || scroll_to_pos)
4431 enable_track = false;
4432
4433 ImGuiStyle& style = ImGui::GetStyle();
4434 float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5;
4435 if (child_w < 1.0f)
4436 child_w = 1.0f;
4437 ImGui::PushID("##VerticalScrolling");
4438 for (int i = 0; i < 5; i++)
4439 {
4440 if (i > 0) ImGui::SameLine();
4441 ImGui::BeginGroup();
4442 const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" };
4443 ImGui::TextUnformatted(names[i]);
4444
4445 const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;
4446 const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
4447 const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), ImGuiChildFlags_Borders, child_flags);
4448 if (ImGui::BeginMenuBar())
4449 {
4450 ImGui::TextUnformatted("abc");
4451 ImGui::EndMenuBar();
4452 }
4453 if (scroll_to_off)
4454 ImGui::SetScrollY(scroll_to_off_px);
4455 if (scroll_to_pos)
4456 ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f);
4457 if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
4458 {
4459 for (int item = 0; item < 100; item++)
4460 {
4461 if (enable_track && item == track_item)
4462 {
4463 ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
4464 ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
4465 }
4466 else
4467 {
4468 ImGui::Text("Item %d", item);
4469 }
4470 }
4471 }
4472 float scroll_y = ImGui::GetScrollY();
4473 float scroll_max_y = ImGui::GetScrollMaxY();
4474 ImGui::EndChild();
4475 ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y);
4476 ImGui::EndGroup();
4477 }
4478 ImGui::PopID();
4479
4480 // Horizontal scroll functions
4481 IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal");
4482 ImGui::Spacing();
4483 HelpMarker(
4484 "Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n"
4485 "Because the clipping rectangle of most window hides half worth of WindowPadding on the "
4486 "left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the "
4487 "equivalent SetScrollFromPosY(+1) wouldn't.");
4488 ImGui::PushID("##HorizontalScrolling");
4489 for (int i = 0; i < 5; i++)
4490 {
4491 float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f;
4492 ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0);
4493 ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
4494 bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), ImGuiChildFlags_Borders, child_flags);
4495 if (scroll_to_off)
4496 ImGui::SetScrollX(scroll_to_off_px);
4497 if (scroll_to_pos)
4498 ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f);
4499 if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
4500 {
4501 for (int item = 0; item < 100; item++)
4502 {
4503 if (item > 0)
4504 ImGui::SameLine();
4505 if (enable_track && item == track_item)
4506 {
4507 ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
4508 ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right
4509 }
4510 else
4511 {
4512 ImGui::Text("Item %d", item);
4513 }
4514 }
4515 }
4516 float scroll_x = ImGui::GetScrollX();
4517 float scroll_max_x = ImGui::GetScrollMaxX();
4518 ImGui::EndChild();
4519 ImGui::SameLine();
4520 const char* names[] = { "Left", "25%", "Center", "75%", "Right" };
4521 ImGui::Text("%s\n%.0f/%.0f", names[i], scroll_x, scroll_max_x);
4522 ImGui::Spacing();
4523 }
4524 ImGui::PopID();
4525
4526 // Miscellaneous Horizontal Scrolling Demo
4527 IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal (more)");
4528 HelpMarker(
4529 "Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n"
4530 "You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().");
4531 static int lines = 7;
4532 ImGui::SliderInt("Lines", &lines, 1, 15);
4533 ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
4534 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));
4535 ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30);
4536 ImGui::BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar);
4537 for (int line = 0; line < lines; line++)
4538 {
4539 // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()
4540 // If you want to create your own time line for a real application you may be better off manipulating
4541 // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets
4542 // yourself. You may also want to use the lower-level ImDrawList API.
4543 int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
4544 for (int n = 0; n < num_buttons; n++)
4545 {
4546 if (n > 0) ImGui::SameLine();
4547 ImGui::PushID(n + line * 1000);
4548 char num_buf[16];
4549 sprintf(num_buf, "%d", n);
4550 const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf;
4551 float hue = n * 0.05f;
4552 ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
4553 ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
4554 ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
4555 ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));
4556 ImGui::PopStyleColor(3);
4557 ImGui::PopID();
4558 }
4559 }
4560 float scroll_x = ImGui::GetScrollX();
4561 float scroll_max_x = ImGui::GetScrollMaxX();
4562 ImGui::EndChild();
4563 ImGui::PopStyleVar(2);
4564 float scroll_x_delta = 0.0f;
4565 ImGui::SmallButton("<<");
4566 if (ImGui::IsItemActive())
4567 scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;
4568 ImGui::SameLine();
4569 ImGui::Text("Scroll from code"); ImGui::SameLine();
4570 ImGui::SmallButton(">>");
4571 if (ImGui::IsItemActive())
4572 scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
4573 ImGui::SameLine();
4574 ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x);
4575 if (scroll_x_delta != 0.0f)
4576 {
4577 // Demonstrate a trick: you can use Begin to set yourself in the context of another window
4578 // (here we are already out of your child window)
4579 ImGui::BeginChild("scrolling");
4580 ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);
4581 ImGui::EndChild();
4582 }
4583 ImGui::Spacing();
4584
4585 static bool show_horizontal_contents_size_demo_window = false;
4586 ImGui::Checkbox("Show Horizontal contents size demo window", &show_horizontal_contents_size_demo_window);
4587
4588 if (show_horizontal_contents_size_demo_window)
4589 {
4590 static bool show_h_scrollbar = true;
4591 static bool show_button = true;
4592 static bool show_tree_nodes = true;
4593 static bool show_text_wrapped = false;
4594 static bool show_columns = true;
4595 static bool show_tab_bar = true;
4596 static bool show_child = false;
4597 static bool explicit_content_size = false;
4598 static float contents_size_x = 300.0f;
4599 if (explicit_content_size)
4600 ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f));
4601 ImGui::Begin("Horizontal contents size demo window", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0);
4602 IMGUI_DEMO_MARKER("Layout/Scrolling/Horizontal contents size demo window");
4603 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));
4604 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0));
4605 HelpMarker(
4606 "Test how different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\n"
4607 "Use 'Metrics->Tools->Show windows rectangles' to visualize rectangles.");
4608 ImGui::Checkbox("H-scrollbar", &show_h_scrollbar);
4609 ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten)
4610 ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width
4611 ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size
4612 ImGui::Checkbox("Columns", &show_columns); // Will use contents size
4613 ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size
4614 ImGui::Checkbox("Child", &show_child); // Will grow and use contents size
4615 ImGui::Checkbox("Explicit content size", &explicit_content_size);
4616 ImGui::Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY());
4617 if (explicit_content_size)
4618 {
4619 ImGui::SameLine();
4620 ImGui::SetNextItemWidth(100);
4621 ImGui::DragFloat("##csx", &contents_size_x);
4622 ImVec2 p = ImGui::GetCursorScreenPos();
4623 ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE);
4624 ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE);
4625 ImGui::Dummy(ImVec2(0, 10));
4626 }
4627 ImGui::PopStyleVar(2);
4628 ImGui::Separator();
4629 if (show_button)
4630 {
4631 ImGui::Button("this is a 300-wide button", ImVec2(300, 0));
4632 }
4633 if (show_tree_nodes)
4634 {
4635 bool open = true;
4636 if (ImGui::TreeNode("this is a tree node"))
4637 {
4638 if (ImGui::TreeNode("another one of those tree node..."))
4639 {
4640 ImGui::Text("Some tree contents");
4641 ImGui::TreePop();
4642 }
4643 ImGui::TreePop();
4644 }
4645 ImGui::CollapsingHeader("CollapsingHeader", &open);
4646 }
4647 if (show_text_wrapped)
4648 {
4649 ImGui::TextWrapped("This text should automatically wrap on the edge of the work rectangle.");
4650 }
4651 if (show_columns)
4652 {
4653 ImGui::Text("Tables:");
4654 if (ImGui::BeginTable("table", 4, ImGuiTableFlags_Borders))
4655 {
4656 for (int n = 0; n < 4; n++)
4657 {
4658 ImGui::TableNextColumn();
4659 ImGui::Text("Width %.2f", ImGui::GetContentRegionAvail().x);
4660 }
4661 ImGui::EndTable();
4662 }
4663 ImGui::Text("Columns:");
4664 ImGui::Columns(4);
4665 for (int n = 0; n < 4; n++)
4666 {
4667 ImGui::Text("Width %.2f", ImGui::GetColumnWidth());
4668 ImGui::NextColumn();
4669 }
4670 ImGui::Columns(1);
4671 }
4672 if (show_tab_bar && ImGui::BeginTabBar("Hello"))
4673 {
4674 if (ImGui::BeginTabItem("OneOneOne")) { ImGui::EndTabItem(); }
4675 if (ImGui::BeginTabItem("TwoTwoTwo")) { ImGui::EndTabItem(); }
4676 if (ImGui::BeginTabItem("ThreeThreeThree")) { ImGui::EndTabItem(); }
4677 if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); }
4678 ImGui::EndTabBar();
4679 }
4680 if (show_child)
4681 {
4682 ImGui::BeginChild("child", ImVec2(0, 0), ImGuiChildFlags_Borders);
4683 ImGui::EndChild();
4684 }
4685 ImGui::End();
4686 }
4687
4688 ImGui::TreePop();
4689 }
4690
4691 IMGUI_DEMO_MARKER("Layout/Text Clipping");
4692 if (ImGui::TreeNode("Text Clipping"))
4693 {
4694 static ImVec2 size(100.0f, 100.0f);
4695 static ImVec2 offset(30.0f, 30.0f);
4696 ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f");
4697 ImGui::TextWrapped("(Click and drag to scroll)");
4698
4699 HelpMarker(
4700 "(Left) Using ImGui::PushClipRect():\n"
4701 "Will alter ImGui hit-testing logic + ImDrawList rendering.\n"
4702 "(use this if you want your clipping rectangle to affect interactions)\n\n"
4703 "(Center) Using ImDrawList::PushClipRect():\n"
4704 "Will alter ImDrawList rendering only.\n"
4705 "(use this as a shortcut if you are only using ImDrawList calls)\n\n"
4706 "(Right) Using ImDrawList::AddText() with a fine ClipRect:\n"
4707 "Will alter only this specific ImDrawList::AddText() rendering.\n"
4708 "This is often used internally to avoid altering the clipping rectangle and minimize draw calls.");
4709
4710 for (int n = 0; n < 3; n++)
4711 {
4712 if (n > 0)
4713 ImGui::SameLine();
4714
4715 ImGui::PushID(n);
4716 ImGui::InvisibleButton("##canvas", size);
4717 if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left))
4718 {
4719 offset.x += ImGui::GetIO().MouseDelta.x;
4720 offset.y += ImGui::GetIO().MouseDelta.y;
4721 }
4722 ImGui::PopID();
4723 if (!ImGui::IsItemVisible()) // Skip rendering as ImDrawList elements are not clipped.
4724 continue;
4725
4726 const ImVec2 p0 = ImGui::GetItemRectMin();
4727 const ImVec2 p1 = ImGui::GetItemRectMax();
4728 const char* text_str = "Line 1 hello\nLine 2 clip me!";
4729 const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y);
4730 ImDrawList* draw_list = ImGui::GetWindowDrawList();
4731 switch (n)
4732 {
4733 case 0:
4734 ImGui::PushClipRect(p0, p1, true);
4735 draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
4736 draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
4737 ImGui::PopClipRect();
4738 break;
4739 case 1:
4740 draw_list->PushClipRect(p0, p1, true);
4741 draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
4742 draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
4743 draw_list->PopClipRect();
4744 break;
4745 case 2:
4746 ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert.
4747 draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
4748 draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect);
4749 break;
4750 }
4751 }
4752
4753 ImGui::TreePop();
4754 }
4755
4756 IMGUI_DEMO_MARKER("Layout/Overlap Mode");
4757 if (ImGui::TreeNode("Overlap Mode"))
4758 {
4759 static bool enable_allow_overlap = true;
4760
4761 HelpMarker(
4762 "Hit-testing is by default performed in item submission order, which generally is perceived as 'back-to-front'.\n\n"
4763 "By using SetNextItemAllowOverlap() you can notify that an item may be overlapped by another. "
4764 "Doing so alters the hovering logic: items using AllowOverlap mode requires an extra frame to accept hovered state.");
4765 ImGui::Checkbox("Enable AllowOverlap", &enable_allow_overlap);
4766
4767 ImVec2 button1_pos = ImGui::GetCursorScreenPos();
4768 ImVec2 button2_pos = ImVec2(button1_pos.x + 50.0f, button1_pos.y + 50.0f);
4769 if (enable_allow_overlap)
4770 ImGui::SetNextItemAllowOverlap();
4771 ImGui::Button("Button 1", ImVec2(80, 80));
4772 ImGui::SetCursorScreenPos(button2_pos);
4773 ImGui::Button("Button 2", ImVec2(80, 80));
4774
4775 // This is typically used with width-spanning items.
4776 // (note that Selectable() has a dedicated flag ImGuiSelectableFlags_AllowOverlap, which is a shortcut
4777 // for using SetNextItemAllowOverlap(). For demo purpose we use SetNextItemAllowOverlap() here.)
4778 if (enable_allow_overlap)
4779 ImGui::SetNextItemAllowOverlap();
4780 ImGui::Selectable("Some Selectable", false);
4781 ImGui::SameLine();
4782 ImGui::SmallButton("++");
4783
4784 ImGui::TreePop();
4785 }
4786 }
4787
4788 //-----------------------------------------------------------------------------
4789 // [SECTION] ShowDemoWindowPopups()
4790 //-----------------------------------------------------------------------------
4791
4792 static void ShowDemoWindowPopups()
4793 {
4794 IMGUI_DEMO_MARKER("Popups");
4795 if (!ImGui::CollapsingHeader("Popups & Modal windows"))
4796 return;
4797
4798 // The properties of popups windows are:
4799 // - They block normal mouse hovering detection outside them. (*)
4800 // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
4801 // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as
4802 // we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup().
4803 // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even
4804 // when normally blocked by a popup.
4805 // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close
4806 // popups at any time.
4807
4808 // Typical use for regular windows:
4809 // bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End();
4810 // Typical use for popups:
4811 // if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup") { [...] EndPopup(); }
4812
4813 // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state.
4814 // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below.
4815
4816 IMGUI_DEMO_MARKER("Popups/Popups");
4817 if (ImGui::TreeNode("Popups"))
4818 {
4819 ImGui::TextWrapped(
4820 "When a popup is active, it inhibits interacting with windows that are behind the popup. "
4821 "Clicking outside the popup closes it.");
4822
4823 static int selected_fish = -1;
4824 const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" };
4825 static bool toggles[] = { true, false, false, false, false };
4826
4827 // Simple selection popup (if you want to show the current selection inside the Button itself,
4828 // you may want to build a string using the "###" operator to preserve a constant ID with a variable label)
4829 if (ImGui::Button("Select.."))
4830 ImGui::OpenPopup("my_select_popup");
4831 ImGui::SameLine();
4832 ImGui::TextUnformatted(selected_fish == -1 ? "<None>" : names[selected_fish]);
4833 if (ImGui::BeginPopup("my_select_popup"))
4834 {
4835 ImGui::SeparatorText("Aquarium");
4836 for (int i = 0; i < IM_ARRAYSIZE(names); i++)
4837 if (ImGui::Selectable(names[i]))
4838 selected_fish = i;
4839 ImGui::EndPopup();
4840 }
4841
4842 // Showing a menu with toggles
4843 if (ImGui::Button("Toggle.."))
4844 ImGui::OpenPopup("my_toggle_popup");
4845 if (ImGui::BeginPopup("my_toggle_popup"))
4846 {
4847 for (int i = 0; i < IM_ARRAYSIZE(names); i++)
4848 ImGui::MenuItem(names[i], "", &toggles[i]);
4849 if (ImGui::BeginMenu("Sub-menu"))
4850 {
4851 ImGui::MenuItem("Click me");
4852 ImGui::EndMenu();
4853 }
4854
4855 ImGui::Separator();
4856 ImGui::Text("Tooltip here");
4857 ImGui::SetItemTooltip("I am a tooltip over a popup");
4858
4859 if (ImGui::Button("Stacked Popup"))
4860 ImGui::OpenPopup("another popup");
4861 if (ImGui::BeginPopup("another popup"))
4862 {
4863 for (int i = 0; i < IM_ARRAYSIZE(names); i++)
4864 ImGui::MenuItem(names[i], "", &toggles[i]);
4865 if (ImGui::BeginMenu("Sub-menu"))
4866 {
4867 ImGui::MenuItem("Click me");
4868 if (ImGui::Button("Stacked Popup"))
4869 ImGui::OpenPopup("another popup");
4870 if (ImGui::BeginPopup("another popup"))
4871 {
4872 ImGui::Text("I am the last one here.");
4873 ImGui::EndPopup();
4874 }
4875 ImGui::EndMenu();
4876 }
4877 ImGui::EndPopup();
4878 }
4879 ImGui::EndPopup();
4880 }
4881
4882 // Call the more complete ShowExampleMenuFile which we use in various places of this demo
4883 if (ImGui::Button("With a menu.."))
4884 ImGui::OpenPopup("my_file_popup");
4885 if (ImGui::BeginPopup("my_file_popup", ImGuiWindowFlags_MenuBar))
4886 {
4887 if (ImGui::BeginMenuBar())
4888 {
4889 if (ImGui::BeginMenu("File"))
4890 {
4891 ShowExampleMenuFile();
4892 ImGui::EndMenu();
4893 }
4894 if (ImGui::BeginMenu("Edit"))
4895 {
4896 ImGui::MenuItem("Dummy");
4897 ImGui::EndMenu();
4898 }
4899 ImGui::EndMenuBar();
4900 }
4901 ImGui::Text("Hello from popup!");
4902 ImGui::Button("This is a dummy button..");
4903 ImGui::EndPopup();
4904 }
4905
4906 ImGui::TreePop();
4907 }
4908
4909 IMGUI_DEMO_MARKER("Popups/Context menus");
4910 if (ImGui::TreeNode("Context menus"))
4911 {
4912 HelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier.");
4913
4914 // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:
4915 // if (id == 0)
4916 // id = GetItemID(); // Use last item id
4917 // if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
4918 // OpenPopup(id);
4919 // return BeginPopup(id);
4920 // For advanced uses you may want to replicate and customize this code.
4921 // See more details in BeginPopupContextItem().
4922
4923 // Example 1
4924 // When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(),
4925 // and BeginPopupContextItem() will use the last item ID as the popup ID.
4926 {
4927 const char* names[5] = { "Label1", "Label2", "Label3", "Label4", "Label5" };
4928 static int selected = -1;
4929 for (int n = 0; n < 5; n++)
4930 {
4931 if (ImGui::Selectable(names[n], selected == n))
4932 selected = n;
4933 if (ImGui::BeginPopupContextItem()) // <-- use last item id as popup id
4934 {
4935 selected = n;
4936 ImGui::Text("This a popup for \"%s\"!", names[n]);
4937 if (ImGui::Button("Close"))
4938 ImGui::CloseCurrentPopup();
4939 ImGui::EndPopup();
4940 }
4941 ImGui::SetItemTooltip("Right-click to open popup");
4942 }
4943 }
4944
4945 // Example 2
4946 // Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem().
4947 // Using an explicit identifier is also convenient if you want to activate the popups from different locations.
4948 {
4949 HelpMarker("Text() elements don't have stable identifiers so we need to provide one.");
4950 static float value = 0.5f;
4951 ImGui::Text("Value = %.3f <-- (1) right-click this text", value);
4952 if (ImGui::BeginPopupContextItem("my popup"))
4953 {
4954 if (ImGui::Selectable("Set to zero")) value = 0.0f;
4955 if (ImGui::Selectable("Set to PI")) value = 3.1415f;
4956 ImGui::SetNextItemWidth(-FLT_MIN);
4957 ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f);
4958 ImGui::EndPopup();
4959 }
4960
4961 // We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup.
4962 // Here we make it that right-clicking this other text element opens the same popup as above.
4963 // The popup itself will be submitted by the code above.
4964 ImGui::Text("(2) Or right-click this text");
4965 ImGui::OpenPopupOnItemClick("my popup", ImGuiPopupFlags_MouseButtonRight);
4966
4967 // Back to square one: manually open the same popup.
4968 if (ImGui::Button("(3) Or click this button"))
4969 ImGui::OpenPopup("my popup");
4970 }
4971
4972 // Example 3
4973 // When using BeginPopupContextItem() with an implicit identifier (NULL == use last item ID),
4974 // we need to make sure your item identifier is stable.
4975 // In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ).
4976 {
4977 HelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator.");
4978 static char name[32] = "Label1";
4979 char buf[64];
4980 sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
4981 ImGui::Button(buf);
4982 if (ImGui::BeginPopupContextItem())
4983 {
4984 ImGui::Text("Edit name:");
4985 ImGui::InputText("##edit", name, IM_ARRAYSIZE(name));
4986 if (ImGui::Button("Close"))
4987 ImGui::CloseCurrentPopup();
4988 ImGui::EndPopup();
4989 }
4990 ImGui::SameLine(); ImGui::Text("(<-- right-click here)");
4991 }
4992
4993 ImGui::TreePop();
4994 }
4995
4996 IMGUI_DEMO_MARKER("Popups/Modals");
4997 if (ImGui::TreeNode("Modals"))
4998 {
4999 ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside.");
5000
5001 if (ImGui::Button("Delete.."))
5002 ImGui::OpenPopup("Delete?");
5003
5004 // Always center this window when appearing
5005 ImVec2 center = ImGui::GetMainViewport()->GetCenter();
5006 ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
5007
5008 if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
5009 {
5010 ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!");
5011 ImGui::Separator();
5012
5013 //static int unused_i = 0;
5014 //ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0");
5015
5016 static bool dont_ask_me_next_time = false;
5017 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
5018 ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time);
5019 ImGui::PopStyleVar();
5020
5021 if (ImGui::Button("OK", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }
5022 ImGui::SetItemDefaultFocus();
5023 ImGui::SameLine();
5024 if (ImGui::Button("Cancel", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }
5025 ImGui::EndPopup();
5026 }
5027
5028 if (ImGui::Button("Stacked modals.."))
5029 ImGui::OpenPopup("Stacked 1");
5030 if (ImGui::BeginPopupModal("Stacked 1", NULL, ImGuiWindowFlags_MenuBar))
5031 {
5032 if (ImGui::BeginMenuBar())
5033 {
5034 if (ImGui::BeginMenu("File"))
5035 {
5036 if (ImGui::MenuItem("Some menu item")) {}
5037 ImGui::EndMenu();
5038 }
5039 ImGui::EndMenuBar();
5040 }
5041 ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDimBg] behind it.");
5042
5043 // Testing behavior of widgets stacking their own regular popups over the modal.
5044 static int item = 1;
5045 static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
5046 ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
5047 ImGui::ColorEdit4("Color", color);
5048
5049 if (ImGui::Button("Add another modal.."))
5050 ImGui::OpenPopup("Stacked 2");
5051
5052 // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which
5053 // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value
5054 // of the bool actually doesn't matter here.
5055 bool unused_open = true;
5056 if (ImGui::BeginPopupModal("Stacked 2", &unused_open))
5057 {
5058 ImGui::Text("Hello from Stacked The Second!");
5059 ImGui::ColorEdit4("Color", color); // Allow opening another nested popup
5060 if (ImGui::Button("Close"))
5061 ImGui::CloseCurrentPopup();
5062 ImGui::EndPopup();
5063 }
5064
5065 if (ImGui::Button("Close"))
5066 ImGui::CloseCurrentPopup();
5067 ImGui::EndPopup();
5068 }
5069
5070 ImGui::TreePop();
5071 }
5072
5073 IMGUI_DEMO_MARKER("Popups/Menus inside a regular window");
5074 if (ImGui::TreeNode("Menus inside a regular window"))
5075 {
5076 ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!");
5077 ImGui::Separator();
5078
5079 ImGui::MenuItem("Menu item", "CTRL+M");
5080 if (ImGui::BeginMenu("Menu inside a regular window"))
5081 {
5082 ShowExampleMenuFile();
5083 ImGui::EndMenu();
5084 }
5085 ImGui::Separator();
5086 ImGui::TreePop();
5087 }
5088 }
5089
5090 // Dummy data structure that we use for the Table demo.
5091 // (pre-C++11 doesn't allow us to instantiate ImVector<MyItem> template if this structure is defined inside the demo function)
5092 namespace
5093 {
5094 // We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code.
5095 // This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID.
5096 // But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex)
5097 // If you don't use sorting, you will generally never care about giving column an ID!
5098 enum MyItemColumnID
5099 {
5100 MyItemColumnID_ID,
5101 MyItemColumnID_Name,
5102 MyItemColumnID_Action,
5103 MyItemColumnID_Quantity,
5104 MyItemColumnID_Description
5105 };
5106
5107 struct MyItem
5108 {
5109 int ID;
5110 const char* Name;
5111 int Quantity;
5112
5113 // We have a problem which is affecting _only this demo_ and should not affect your code:
5114 // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(),
5115 // however qsort doesn't allow passing user data to comparing function.
5116 // As a workaround, we are storing the sort specs in a static/global for the comparing function to access.
5117 // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global.
5118 // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called
5119 // very often by the sorting algorithm it would be a little wasteful.
5120 static const ImGuiTableSortSpecs* s_current_sort_specs;
5121
5122 static void SortWithSortSpecs(ImGuiTableSortSpecs* sort_specs, MyItem* items, int items_count)
5123 {
5124 s_current_sort_specs = sort_specs; // Store in variable accessible by the sort function.
5125 if (items_count > 1)
5126 qsort(items, (size_t)items_count, sizeof(items[0]), MyItem::CompareWithSortSpecs);
5127 s_current_sort_specs = NULL;
5128 }
5129
5130 // Compare function to be used by qsort()
5131 static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs)
5132 {
5133 const MyItem* a = (const MyItem*)lhs;
5134 const MyItem* b = (const MyItem*)rhs;
5135 for (int n = 0; n < s_current_sort_specs->SpecsCount; n++)
5136 {
5137 // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn()
5138 // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler!
5139 const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n];
5140 int delta = 0;
5141 switch (sort_spec->ColumnUserID)
5142 {
5143 case MyItemColumnID_ID: delta = (a->ID - b->ID); break;
5144 case MyItemColumnID_Name: delta = (strcmp(a->Name, b->Name)); break;
5145 case MyItemColumnID_Quantity: delta = (a->Quantity - b->Quantity); break;
5146 case MyItemColumnID_Description: delta = (strcmp(a->Name, b->Name)); break;
5147 default: IM_ASSERT(0); break;
5148 }
5149 if (delta > 0)
5150 return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;
5151 if (delta < 0)
5152 return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1;
5153 }
5154
5155 // qsort() is instable so always return a way to differenciate items.
5156 // Your own compare function may want to avoid fallback on implicit sort specs.
5157 // e.g. a Name compare if it wasn't already part of the sort specs.
5158 return (a->ID - b->ID);
5159 }
5160 };
5161 const ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL;
5162 }
5163
5164 // Make the UI compact because there are so many fields
5165 static void PushStyleCompact()
5166 {
5167 ImGuiStyle& style = ImGui::GetStyle();
5168 ImGui::PushStyleVarY(ImGuiStyleVar_FramePadding, (float)(int)(style.FramePadding.y * 0.60f));
5169 ImGui::PushStyleVarY(ImGuiStyleVar_ItemSpacing, (float)(int)(style.ItemSpacing.y * 0.60f));
5170 }
5171
5172 static void PopStyleCompact()
5173 {
5174 ImGui::PopStyleVar(2);
5175 }
5176
5177 // Show a combo box with a choice of sizing policies
5178 static void EditTableSizingFlags(ImGuiTableFlags* p_flags)
5179 {
5180 struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; };
5181 static const EnumDesc policies[] =
5182 {
5183 { ImGuiTableFlags_None, "Default", "Use default sizing policy:\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\n- ImGuiTableFlags_SizingStretchSame otherwise." },
5184 { ImGuiTableFlags_SizingFixedFit, "ImGuiTableFlags_SizingFixedFit", "Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width." },
5185 { ImGuiTableFlags_SizingFixedSame, "ImGuiTableFlags_SizingFixedSame", "Columns are all the same width, matching the maximum contents width.\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible." },
5186 { ImGuiTableFlags_SizingStretchProp, "ImGuiTableFlags_SizingStretchProp", "Columns default to _WidthStretch with weights proportional to their widths." },
5187 { ImGuiTableFlags_SizingStretchSame, "ImGuiTableFlags_SizingStretchSame", "Columns default to _WidthStretch with same weights." }
5188 };
5189 int idx;
5190 for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++)
5191 if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_))
5192 break;
5193 const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen("ImGuiTableFlags") : 0) : "";
5194 if (ImGui::BeginCombo("Sizing Policy", preview_text))
5195 {
5196 for (int n = 0; n < IM_ARRAYSIZE(policies); n++)
5197 if (ImGui::Selectable(policies[n].Name, idx == n))
5198 *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value;
5199 ImGui::EndCombo();
5200 }
5201 ImGui::SameLine();
5202 ImGui::TextDisabled("(?)");
5203 if (ImGui::BeginItemTooltip())
5204 {
5205 ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f);
5206 for (int m = 0; m < IM_ARRAYSIZE(policies); m++)
5207 {
5208 ImGui::Separator();
5209 ImGui::Text("%s:", policies[m].Name);
5210 ImGui::Separator();
5211 ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetStyle().IndentSpacing * 0.5f);
5212 ImGui::TextUnformatted(policies[m].Tooltip);
5213 }
5214 ImGui::PopTextWrapPos();
5215 ImGui::EndTooltip();
5216 }
5217 }
5218
5219 static void EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags)
5220 {
5221 ImGui::CheckboxFlags("_Disabled", p_flags, ImGuiTableColumnFlags_Disabled); ImGui::SameLine(); HelpMarker("Master disable flag (also hide from context menu)");
5222 ImGui::CheckboxFlags("_DefaultHide", p_flags, ImGuiTableColumnFlags_DefaultHide);
5223 ImGui::CheckboxFlags("_DefaultSort", p_flags, ImGuiTableColumnFlags_DefaultSort);
5224 if (ImGui::CheckboxFlags("_WidthStretch", p_flags, ImGuiTableColumnFlags_WidthStretch))
5225 *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch);
5226 if (ImGui::CheckboxFlags("_WidthFixed", p_flags, ImGuiTableColumnFlags_WidthFixed))
5227 *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed);
5228 ImGui::CheckboxFlags("_NoResize", p_flags, ImGuiTableColumnFlags_NoResize);
5229 ImGui::CheckboxFlags("_NoReorder", p_flags, ImGuiTableColumnFlags_NoReorder);
5230 ImGui::CheckboxFlags("_NoHide", p_flags, ImGuiTableColumnFlags_NoHide);
5231 ImGui::CheckboxFlags("_NoClip", p_flags, ImGuiTableColumnFlags_NoClip);
5232 ImGui::CheckboxFlags("_NoSort", p_flags, ImGuiTableColumnFlags_NoSort);
5233 ImGui::CheckboxFlags("_NoSortAscending", p_flags, ImGuiTableColumnFlags_NoSortAscending);
5234 ImGui::CheckboxFlags("_NoSortDescending", p_flags, ImGuiTableColumnFlags_NoSortDescending);
5235 ImGui::CheckboxFlags("_NoHeaderLabel", p_flags, ImGuiTableColumnFlags_NoHeaderLabel);
5236 ImGui::CheckboxFlags("_NoHeaderWidth", p_flags, ImGuiTableColumnFlags_NoHeaderWidth);
5237 ImGui::CheckboxFlags("_PreferSortAscending", p_flags, ImGuiTableColumnFlags_PreferSortAscending);
5238 ImGui::CheckboxFlags("_PreferSortDescending", p_flags, ImGuiTableColumnFlags_PreferSortDescending);
5239 ImGui::CheckboxFlags("_IndentEnable", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker("Default for column 0");
5240 ImGui::CheckboxFlags("_IndentDisable", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker("Default for column >0");
5241 ImGui::CheckboxFlags("_AngledHeader", p_flags, ImGuiTableColumnFlags_AngledHeader);
5242 }
5243
5244 static void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags)
5245 {
5246 ImGui::CheckboxFlags("_IsEnabled", &flags, ImGuiTableColumnFlags_IsEnabled);
5247 ImGui::CheckboxFlags("_IsVisible", &flags, ImGuiTableColumnFlags_IsVisible);
5248 ImGui::CheckboxFlags("_IsSorted", &flags, ImGuiTableColumnFlags_IsSorted);
5249 ImGui::CheckboxFlags("_IsHovered", &flags, ImGuiTableColumnFlags_IsHovered);
5250 }
5251
5252 //-----------------------------------------------------------------------------
5253 // [SECTION] ShowDemoWindowTables()
5254 //-----------------------------------------------------------------------------
5255
5256 static void ShowDemoWindowTables()
5257 {
5258 //ImGui::SetNextItemOpen(true, ImGuiCond_Once);
5259 IMGUI_DEMO_MARKER("Tables");
5260 if (!ImGui::CollapsingHeader("Tables & Columns"))
5261 return;
5262
5263 // Using those as a base value to create width/height that are factor of the size of our font
5264 const float TEXT_BASE_WIDTH = ImGui::CalcTextSize("A").x;
5265 const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing();
5266
5267 ImGui::PushID("Tables");
5268
5269 int open_action = -1;
5270 if (ImGui::Button("Expand all"))
5271 open_action = 1;
5272 ImGui::SameLine();
5273 if (ImGui::Button("Collapse all"))
5274 open_action = 0;
5275 ImGui::SameLine();
5276
5277 // Options
5278 static bool disable_indent = false;
5279 ImGui::Checkbox("Disable tree indentation", &disable_indent);
5280 ImGui::SameLine();
5281 HelpMarker("Disable the indenting of tree nodes so demo tables can use the full window width.");
5282 ImGui::Separator();
5283 if (disable_indent)
5284 ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f);
5285
5286 // About Styling of tables
5287 // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs.
5288 // There are however a few settings that a shared and part of the ImGuiStyle structure:
5289 // style.CellPadding // Padding within each cell
5290 // style.Colors[ImGuiCol_TableHeaderBg] // Table header background
5291 // style.Colors[ImGuiCol_TableBorderStrong] // Table outer and header borders
5292 // style.Colors[ImGuiCol_TableBorderLight] // Table inner borders
5293 // style.Colors[ImGuiCol_TableRowBg] // Table row background when ImGuiTableFlags_RowBg is enabled (even rows)
5294 // style.Colors[ImGuiCol_TableRowBgAlt] // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows)
5295
5296 // Demos
5297 if (open_action != -1)
5298 ImGui::SetNextItemOpen(open_action != 0);
5299 IMGUI_DEMO_MARKER("Tables/Basic");
5300 if (ImGui::TreeNode("Basic"))
5301 {
5302 // Here we will showcase three different ways to output a table.
5303 // They are very simple variations of a same thing!
5304
5305 // [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column.
5306 // In many situations, this is the most flexible and easy to use pattern.
5307 HelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.");
5308 if (ImGui::BeginTable("table1", 3))
5309 {
5310 for (int row = 0; row < 4; row++)
5311 {
5312 ImGui::TableNextRow();
5313 for (int column = 0; column < 3; column++)
5314 {
5315 ImGui::TableSetColumnIndex(column);
5316 ImGui::Text("Row %d Column %d", row, column);
5317 }
5318 }
5319 ImGui::EndTable();
5320 }
5321
5322 // [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex().
5323 // This is generally more convenient when you have code manually submitting the contents of each column.
5324 HelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.");
5325 if (ImGui::BeginTable("table2", 3))
5326 {
5327 for (int row = 0; row < 4; row++)
5328 {
5329 ImGui::TableNextRow();
5330 ImGui::TableNextColumn();
5331 ImGui::Text("Row %d", row);
5332 ImGui::TableNextColumn();
5333 ImGui::Text("Some contents");
5334 ImGui::TableNextColumn();
5335 ImGui::Text("123.456");
5336 }
5337 ImGui::EndTable();
5338 }
5339
5340 // [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(),
5341 // as TableNextColumn() will automatically wrap around and create new rows as needed.
5342 // This is generally more convenient when your cells all contains the same type of data.
5343 HelpMarker(
5344 "Only using TableNextColumn(), which tends to be convenient for tables where every cell contains "
5345 "the same type of contents.\n This is also more similar to the old NextColumn() function of the "
5346 "Columns API, and provided to facilitate the Columns->Tables API transition.");
5347 if (ImGui::BeginTable("table3", 3))
5348 {
5349 for (int item = 0; item < 14; item++)
5350 {
5351 ImGui::TableNextColumn();
5352 ImGui::Text("Item %d", item);
5353 }
5354 ImGui::EndTable();
5355 }
5356
5357 ImGui::TreePop();
5358 }
5359
5360 if (open_action != -1)
5361 ImGui::SetNextItemOpen(open_action != 0);
5362 IMGUI_DEMO_MARKER("Tables/Borders, background");
5363 if (ImGui::TreeNode("Borders, background"))
5364 {
5365 // Expose a few Borders related flags interactively
5366 enum ContentsType { CT_Text, CT_FillButton };
5367 static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
5368 static bool display_headers = false;
5369 static int contents_type = CT_Text;
5370
5371 PushStyleCompact();
5372 ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
5373 ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders);
5374 ImGui::SameLine(); HelpMarker("ImGuiTableFlags_Borders\n = ImGuiTableFlags_BordersInnerV\n | ImGuiTableFlags_BordersOuterV\n | ImGuiTableFlags_BordersInnerH\n | ImGuiTableFlags_BordersOuterH");
5375 ImGui::Indent();
5376
5377 ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH);
5378 ImGui::Indent();
5379 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH);
5380 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH);
5381 ImGui::Unindent();
5382
5383 ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
5384 ImGui::Indent();
5385 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV);
5386 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV);
5387 ImGui::Unindent();
5388
5389 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter);
5390 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner);
5391 ImGui::Unindent();
5392
5393 ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:");
5394 ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text);
5395 ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton);
5396 ImGui::Checkbox("Display headers", &display_headers);
5397 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers");
5398 PopStyleCompact();
5399
5400 if (ImGui::BeginTable("table1", 3, flags))
5401 {
5402 // Display headers so we can inspect their interaction with borders
5403 // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them now. See other sections for details)
5404 if (display_headers)
5405 {
5406 ImGui::TableSetupColumn("One");
5407 ImGui::TableSetupColumn("Two");
5408 ImGui::TableSetupColumn("Three");
5409 ImGui::TableHeadersRow();
5410 }
5411
5412 for (int row = 0; row < 5; row++)
5413 {
5414 ImGui::TableNextRow();
5415 for (int column = 0; column < 3; column++)
5416 {
5417 ImGui::TableSetColumnIndex(column);
5418 char buf[32];
5419 sprintf(buf, "Hello %d,%d", column, row);
5420 if (contents_type == CT_Text)
5421 ImGui::TextUnformatted(buf);
5422 else if (contents_type == CT_FillButton)
5423 ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
5424 }
5425 }
5426 ImGui::EndTable();
5427 }
5428 ImGui::TreePop();
5429 }
5430
5431 if (open_action != -1)
5432 ImGui::SetNextItemOpen(open_action != 0);
5433 IMGUI_DEMO_MARKER("Tables/Resizable, stretch");
5434 if (ImGui::TreeNode("Resizable, stretch"))
5435 {
5436 // By default, if we don't enable ScrollX the sizing policy for each column is "Stretch"
5437 // All columns maintain a sizing weight, and they will occupy all available width.
5438 static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
5439 PushStyleCompact();
5440 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
5441 ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
5442 ImGui::SameLine(); HelpMarker(
5443 "Using the _Resizable flag automatically enables the _BordersInnerV flag as well, "
5444 "this is why the resize borders are still showing when unchecking this.");
5445 PopStyleCompact();
5446
5447 if (ImGui::BeginTable("table1", 3, flags))
5448 {
5449 for (int row = 0; row < 5; row++)
5450 {
5451 ImGui::TableNextRow();
5452 for (int column = 0; column < 3; column++)
5453 {
5454 ImGui::TableSetColumnIndex(column);
5455 ImGui::Text("Hello %d,%d", column, row);
5456 }
5457 }
5458 ImGui::EndTable();
5459 }
5460 ImGui::TreePop();
5461 }
5462
5463 if (open_action != -1)
5464 ImGui::SetNextItemOpen(open_action != 0);
5465 IMGUI_DEMO_MARKER("Tables/Resizable, fixed");
5466 if (ImGui::TreeNode("Resizable, fixed"))
5467 {
5468 // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set)
5469 // So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small)
5470 // If there is not enough available width to fit all columns, they will however be resized down.
5471 // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings
5472 HelpMarker(
5473 "Using _Resizable + _SizingFixedFit flags.\n"
5474 "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n"
5475 "Double-click a column border to auto-fit the column to its contents.");
5476 PushStyleCompact();
5477 static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;
5478 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
5479 PopStyleCompact();
5480
5481 if (ImGui::BeginTable("table1", 3, flags))
5482 {
5483 for (int row = 0; row < 5; row++)
5484 {
5485 ImGui::TableNextRow();
5486 for (int column = 0; column < 3; column++)
5487 {
5488 ImGui::TableSetColumnIndex(column);
5489 ImGui::Text("Hello %d,%d", column, row);
5490 }
5491 }
5492 ImGui::EndTable();
5493 }
5494 ImGui::TreePop();
5495 }
5496
5497 if (open_action != -1)
5498 ImGui::SetNextItemOpen(open_action != 0);
5499 IMGUI_DEMO_MARKER("Tables/Resizable, mixed");
5500 if (ImGui::TreeNode("Resizable, mixed"))
5501 {
5502 HelpMarker(
5503 "Using TableSetupColumn() to alter resizing policy on a per-column basis.\n\n"
5504 "When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch.");
5505 static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
5506
5507 if (ImGui::BeginTable("table1", 3, flags))
5508 {
5509 ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
5510 ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
5511 ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthStretch);
5512 ImGui::TableHeadersRow();
5513 for (int row = 0; row < 5; row++)
5514 {
5515 ImGui::TableNextRow();
5516 for (int column = 0; column < 3; column++)
5517 {
5518 ImGui::TableSetColumnIndex(column);
5519 ImGui::Text("%s %d,%d", (column == 2) ? "Stretch" : "Fixed", column, row);
5520 }
5521 }
5522 ImGui::EndTable();
5523 }
5524 if (ImGui::BeginTable("table2", 6, flags))
5525 {
5526 ImGui::TableSetupColumn("AAA", ImGuiTableColumnFlags_WidthFixed);
5527 ImGui::TableSetupColumn("BBB", ImGuiTableColumnFlags_WidthFixed);
5528 ImGui::TableSetupColumn("CCC", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide);
5529 ImGui::TableSetupColumn("DDD", ImGuiTableColumnFlags_WidthStretch);
5530 ImGui::TableSetupColumn("EEE", ImGuiTableColumnFlags_WidthStretch);
5531 ImGui::TableSetupColumn("FFF", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide);
5532 ImGui::TableHeadersRow();
5533 for (int row = 0; row < 5; row++)
5534 {
5535 ImGui::TableNextRow();
5536 for (int column = 0; column < 6; column++)
5537 {
5538 ImGui::TableSetColumnIndex(column);
5539 ImGui::Text("%s %d,%d", (column >= 3) ? "Stretch" : "Fixed", column, row);
5540 }
5541 }
5542 ImGui::EndTable();
5543 }
5544 ImGui::TreePop();
5545 }
5546
5547 if (open_action != -1)
5548 ImGui::SetNextItemOpen(open_action != 0);
5549 IMGUI_DEMO_MARKER("Tables/Reorderable, hideable, with headers");
5550 if (ImGui::TreeNode("Reorderable, hideable, with headers"))
5551 {
5552 HelpMarker(
5553 "Click and drag column headers to reorder columns.\n\n"
5554 "Right-click on a header to open a context menu.");
5555 static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV;
5556 PushStyleCompact();
5557 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
5558 ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable);
5559 ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable);
5560 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody);
5561 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers)");
5562 ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn);
5563 PopStyleCompact();
5564
5565 if (ImGui::BeginTable("table1", 3, flags))
5566 {
5567 // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column.
5568 // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.)
5569 ImGui::TableSetupColumn("One");
5570 ImGui::TableSetupColumn("Two");
5571 ImGui::TableSetupColumn("Three");
5572 ImGui::TableHeadersRow();
5573 for (int row = 0; row < 6; row++)
5574 {
5575 ImGui::TableNextRow();
5576 for (int column = 0; column < 3; column++)
5577 {
5578 ImGui::TableSetColumnIndex(column);
5579 ImGui::Text("Hello %d,%d", column, row);
5580 }
5581 }
5582 ImGui::EndTable();
5583 }
5584
5585 // Use outer_size.x == 0.0f instead of default to make the table as tight as possible
5586 // (only valid when no scrolling and no stretch column)
5587 if (ImGui::BeginTable("table2", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0f, 0.0f)))
5588 {
5589 ImGui::TableSetupColumn("One");
5590 ImGui::TableSetupColumn("Two");
5591 ImGui::TableSetupColumn("Three");
5592 ImGui::TableHeadersRow();
5593 for (int row = 0; row < 6; row++)
5594 {
5595 ImGui::TableNextRow();
5596 for (int column = 0; column < 3; column++)
5597 {
5598 ImGui::TableSetColumnIndex(column);
5599 ImGui::Text("Fixed %d,%d", column, row);
5600 }
5601 }
5602 ImGui::EndTable();
5603 }
5604 ImGui::TreePop();
5605 }
5606
5607 if (open_action != -1)
5608 ImGui::SetNextItemOpen(open_action != 0);
5609 IMGUI_DEMO_MARKER("Tables/Padding");
5610 if (ImGui::TreeNode("Padding"))
5611 {
5612 // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding.
5613 // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding.
5614 HelpMarker(
5615 "We often want outer padding activated when any using features which makes the edges of a column visible:\n"
5616 "e.g.:\n"
5617 "- BorderOuterV\n"
5618 "- any form of row selection\n"
5619 "Because of this, activating BorderOuterV sets the default to PadOuterX. "
5620 "Using PadOuterX or NoPadOuterX you can override the default.\n\n"
5621 "Actual padding values are using style.CellPadding.\n\n"
5622 "In this demo we don't show horizontal borders to emphasize how they don't affect default horizontal padding.");
5623
5624 static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV;
5625 PushStyleCompact();
5626 ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX);
5627 ImGui::SameLine(); HelpMarker("Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)");
5628 ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags1, ImGuiTableFlags_NoPadOuterX);
5629 ImGui::SameLine(); HelpMarker("Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)");
5630 ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags1, ImGuiTableFlags_NoPadInnerX);
5631 ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)");
5632 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV);
5633 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV);
5634 static bool show_headers = false;
5635 ImGui::Checkbox("show_headers", &show_headers);
5636 PopStyleCompact();
5637
5638 if (ImGui::BeginTable("table_padding", 3, flags1))
5639 {
5640 if (show_headers)
5641 {
5642 ImGui::TableSetupColumn("One");
5643 ImGui::TableSetupColumn("Two");
5644 ImGui::TableSetupColumn("Three");
5645 ImGui::TableHeadersRow();
5646 }
5647
5648 for (int row = 0; row < 5; row++)
5649 {
5650 ImGui::TableNextRow();
5651 for (int column = 0; column < 3; column++)
5652 {
5653 ImGui::TableSetColumnIndex(column);
5654 if (row == 0)
5655 {
5656 ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x);
5657 }
5658 else
5659 {
5660 char buf[32];
5661 sprintf(buf, "Hello %d,%d", column, row);
5662 ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
5663 }
5664 //if (ImGui::TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered)
5665 // ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255));
5666 }
5667 }
5668 ImGui::EndTable();
5669 }
5670
5671 // Second example: set style.CellPadding to (0.0) or a custom value.
5672 // FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one...
5673 HelpMarker("Setting style.CellPadding to (0,0) or a custom value.");
5674 static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;
5675 static ImVec2 cell_padding(0.0f, 0.0f);
5676 static bool show_widget_frame_bg = true;
5677
5678 PushStyleCompact();
5679 ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders);
5680 ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags2, ImGuiTableFlags_BordersH);
5681 ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags2, ImGuiTableFlags_BordersV);
5682 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags2, ImGuiTableFlags_BordersInner);
5683 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags2, ImGuiTableFlags_BordersOuter);
5684 ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags2, ImGuiTableFlags_RowBg);
5685 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags2, ImGuiTableFlags_Resizable);
5686 ImGui::Checkbox("show_widget_frame_bg", &show_widget_frame_bg);
5687 ImGui::SliderFloat2("CellPadding", &cell_padding.x, 0.0f, 10.0f, "%.0f");
5688 PopStyleCompact();
5689
5690 ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding);
5691 if (ImGui::BeginTable("table_padding_2", 3, flags2))
5692 {
5693 static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells
5694 static bool init = true;
5695 if (!show_widget_frame_bg)
5696 ImGui::PushStyleColor(ImGuiCol_FrameBg, 0);
5697 for (int cell = 0; cell < 3 * 5; cell++)
5698 {
5699 ImGui::TableNextColumn();
5700 if (init)
5701 strcpy(text_bufs[cell], "edit me");
5702 ImGui::SetNextItemWidth(-FLT_MIN);
5703 ImGui::PushID(cell);
5704 ImGui::InputText("##cell", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell]));
5705 ImGui::PopID();
5706 }
5707 if (!show_widget_frame_bg)
5708 ImGui::PopStyleColor();
5709 init = false;
5710 ImGui::EndTable();
5711 }
5712 ImGui::PopStyleVar();
5713
5714 ImGui::TreePop();
5715 }
5716
5717 if (open_action != -1)
5718 ImGui::SetNextItemOpen(open_action != 0);
5719 IMGUI_DEMO_MARKER("Tables/Explicit widths");
5720 if (ImGui::TreeNode("Sizing policies"))
5721 {
5722 static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
5723 PushStyleCompact();
5724 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable);
5725 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags1, ImGuiTableFlags_NoHostExtendX);
5726 PopStyleCompact();
5727
5728 static ImGuiTableFlags sizing_policy_flags[4] = { ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame };
5729 for (int table_n = 0; table_n < 4; table_n++)
5730 {
5731 ImGui::PushID(table_n);
5732 ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 30);
5733 EditTableSizingFlags(&sizing_policy_flags[table_n]);
5734
5735 // To make it easier to understand the different sizing policy,
5736 // For each policy: we display one table where the columns have equal contents width,
5737 // and one where the columns have different contents width.
5738 if (ImGui::BeginTable("table1", 3, sizing_policy_flags[table_n] | flags1))
5739 {
5740 for (int row = 0; row < 3; row++)
5741 {
5742 ImGui::TableNextRow();
5743 ImGui::TableNextColumn(); ImGui::Text("Oh dear");
5744 ImGui::TableNextColumn(); ImGui::Text("Oh dear");
5745 ImGui::TableNextColumn(); ImGui::Text("Oh dear");
5746 }
5747 ImGui::EndTable();
5748 }
5749 if (ImGui::BeginTable("table2", 3, sizing_policy_flags[table_n] | flags1))
5750 {
5751 for (int row = 0; row < 3; row++)
5752 {
5753 ImGui::TableNextRow();
5754 ImGui::TableNextColumn(); ImGui::Text("AAAA");
5755 ImGui::TableNextColumn(); ImGui::Text("BBBBBBBB");
5756 ImGui::TableNextColumn(); ImGui::Text("CCCCCCCCCCCC");
5757 }
5758 ImGui::EndTable();
5759 }
5760 ImGui::PopID();
5761 }
5762
5763 ImGui::Spacing();
5764 ImGui::TextUnformatted("Advanced");
5765 ImGui::SameLine();
5766 HelpMarker(
5767 "This section allows you to interact and see the effect of various sizing policies "
5768 "depending on whether Scroll is enabled and the contents of your columns.");
5769
5770 enum ContentsType { CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText };
5771 static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable;
5772 static int contents_type = CT_ShowWidth;
5773 static int column_count = 3;
5774
5775 PushStyleCompact();
5776 ImGui::PushID("Advanced");
5777 ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);
5778 EditTableSizingFlags(&flags);
5779 ImGui::Combo("Contents", &contents_type, "Show width\0Short Text\0Long Text\0Button\0Fill Button\0InputText\0");
5780 if (contents_type == CT_FillButton)
5781 {
5782 ImGui::SameLine();
5783 HelpMarker(
5784 "Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop "
5785 "where contents width can feed into auto-column width can feed into contents width.");
5786 }
5787 ImGui::DragInt("Columns", &column_count, 0.1f, 1, 64, "%d", ImGuiSliderFlags_AlwaysClamp);
5788 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
5789 ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths);
5790 ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
5791 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
5792 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
5793 ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip);
5794 ImGui::PopItemWidth();
5795 ImGui::PopID();
5796 PopStyleCompact();
5797
5798 if (ImGui::BeginTable("table2", column_count, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 7)))
5799 {
5800 for (int cell = 0; cell < 10 * column_count; cell++)
5801 {
5802 ImGui::TableNextColumn();
5803 int column = ImGui::TableGetColumnIndex();
5804 int row = ImGui::TableGetRowIndex();
5805
5806 ImGui::PushID(cell);
5807 char label[32];
5808 static char text_buf[32] = "";
5809 sprintf(label, "Hello %d,%d", column, row);
5810 switch (contents_type)
5811 {
5812 case CT_ShortText: ImGui::TextUnformatted(label); break;
5813 case CT_LongText: ImGui::Text("Some %s text %d,%d\nOver two lines..", column == 0 ? "long" : "longeeer", column, row); break;
5814 case CT_ShowWidth: ImGui::Text("W: %.1f", ImGui::GetContentRegionAvail().x); break;
5815 case CT_Button: ImGui::Button(label); break;
5816 case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break;
5817 case CT_InputText: ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText("##", text_buf, IM_ARRAYSIZE(text_buf)); break;
5818 }
5819 ImGui::PopID();
5820 }
5821 ImGui::EndTable();
5822 }
5823 ImGui::TreePop();
5824 }
5825
5826 if (open_action != -1)
5827 ImGui::SetNextItemOpen(open_action != 0);
5828 IMGUI_DEMO_MARKER("Tables/Vertical scrolling, with clipping");
5829 if (ImGui::TreeNode("Vertical scrolling, with clipping"))
5830 {
5831 HelpMarker(
5832 "Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\n\n"
5833 "We also demonstrate using ImGuiListClipper to virtualize the submission of many items.");
5834 static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
5835
5836 PushStyleCompact();
5837 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
5838 PopStyleCompact();
5839
5840 // When using ScrollX or ScrollY we need to specify a size for our table container!
5841 // Otherwise by default the table will fit all available space, like a BeginChild() call.
5842 ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);
5843 if (ImGui::BeginTable("table_scrolly", 3, flags, outer_size))
5844 {
5845 ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible
5846 ImGui::TableSetupColumn("One", ImGuiTableColumnFlags_None);
5847 ImGui::TableSetupColumn("Two", ImGuiTableColumnFlags_None);
5848 ImGui::TableSetupColumn("Three", ImGuiTableColumnFlags_None);
5849 ImGui::TableHeadersRow();
5850
5851 // Demonstrate using clipper for large vertical lists
5852 ImGuiListClipper clipper;
5853 clipper.Begin(1000);
5854 while (clipper.Step())
5855 {
5856 for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++)
5857 {
5858 ImGui::TableNextRow();
5859 for (int column = 0; column < 3; column++)
5860 {
5861 ImGui::TableSetColumnIndex(column);
5862 ImGui::Text("Hello %d,%d", column, row);
5863 }
5864 }
5865 }
5866 ImGui::EndTable();
5867 }
5868 ImGui::TreePop();
5869 }
5870
5871 if (open_action != -1)
5872 ImGui::SetNextItemOpen(open_action != 0);
5873 IMGUI_DEMO_MARKER("Tables/Horizontal scrolling");
5874 if (ImGui::TreeNode("Horizontal scrolling"))
5875 {
5876 HelpMarker(
5877 "When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, "
5878 "as automatically stretching columns doesn't make much sense with horizontal scrolling.\n\n"
5879 "Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX, "
5880 "because the container window won't automatically extend vertically to fix contents "
5881 "(this may be improved in future versions).");
5882 static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;
5883 static int freeze_cols = 1;
5884 static int freeze_rows = 1;
5885
5886 PushStyleCompact();
5887 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
5888 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
5889 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
5890 ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
5891 ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
5892 ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
5893 ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
5894 PopStyleCompact();
5895
5896 // When using ScrollX or ScrollY we need to specify a size for our table container!
5897 // Otherwise by default the table will fit all available space, like a BeginChild() call.
5898 ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);
5899 if (ImGui::BeginTable("table_scrollx", 7, flags, outer_size))
5900 {
5901 ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);
5902 ImGui::TableSetupColumn("Line #", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze()
5903 ImGui::TableSetupColumn("One");
5904 ImGui::TableSetupColumn("Two");
5905 ImGui::TableSetupColumn("Three");
5906 ImGui::TableSetupColumn("Four");
5907 ImGui::TableSetupColumn("Five");
5908 ImGui::TableSetupColumn("Six");
5909 ImGui::TableHeadersRow();
5910 for (int row = 0; row < 20; row++)
5911 {
5912 ImGui::TableNextRow();
5913 for (int column = 0; column < 7; column++)
5914 {
5915 // Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement.
5916 // Because here we know that:
5917 // - A) all our columns are contributing the same to row height
5918 // - B) column 0 is always visible,
5919 // We only always submit this one column and can skip others.
5920 // More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags().
5921 if (!ImGui::TableSetColumnIndex(column) && column > 0)
5922 continue;
5923 if (column == 0)
5924 ImGui::Text("Line %d", row);
5925 else
5926 ImGui::Text("Hello world %d,%d", column, row);
5927 }
5928 }
5929 ImGui::EndTable();
5930 }
5931
5932 ImGui::Spacing();
5933 ImGui::TextUnformatted("Stretch + ScrollX");
5934 ImGui::SameLine();
5935 HelpMarker(
5936 "Showcase using Stretch columns + ScrollX together: "
5937 "this is rather unusual and only makes sense when specifying an 'inner_width' for the table!\n"
5938 "Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns "
5939 "along with ScrollX doesn't make sense.");
5940 static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;
5941 static float inner_width = 1000.0f;
5942 PushStyleCompact();
5943 ImGui::PushID("flags3");
5944 ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);
5945 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags2, ImGuiTableFlags_ScrollX);
5946 ImGui::DragFloat("inner_width", &inner_width, 1.0f, 0.0f, FLT_MAX, "%.1f");
5947 ImGui::PopItemWidth();
5948 ImGui::PopID();
5949 PopStyleCompact();
5950 if (ImGui::BeginTable("table2", 7, flags2, outer_size, inner_width))
5951 {
5952 for (int cell = 0; cell < 20 * 7; cell++)
5953 {
5954 ImGui::TableNextColumn();
5955 ImGui::Text("Hello world %d,%d", ImGui::TableGetColumnIndex(), ImGui::TableGetRowIndex());
5956 }
5957 ImGui::EndTable();
5958 }
5959 ImGui::TreePop();
5960 }
5961
5962 if (open_action != -1)
5963 ImGui::SetNextItemOpen(open_action != 0);
5964 IMGUI_DEMO_MARKER("Tables/Columns flags");
5965 if (ImGui::TreeNode("Columns flags"))
5966 {
5967 // Create a first table just to show all the options/flags we want to make visible in our example!
5968 const int column_count = 3;
5969 const char* column_names[column_count] = { "One", "Two", "Three" };
5970 static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide };
5971 static ImGuiTableColumnFlags column_flags_out[column_count] = { 0, 0, 0 }; // Output from TableGetColumnFlags()
5972
5973 if (ImGui::BeginTable("table_columns_flags_checkboxes", column_count, ImGuiTableFlags_None))
5974 {
5975 PushStyleCompact();
5976 for (int column = 0; column < column_count; column++)
5977 {
5978 ImGui::TableNextColumn();
5979 ImGui::PushID(column);
5980 ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation across columns
5981 ImGui::Text("'%s'", column_names[column]);
5982 ImGui::Spacing();
5983 ImGui::Text("Input flags:");
5984 EditTableColumnsFlags(&column_flags[column]);
5985 ImGui::Spacing();
5986 ImGui::Text("Output flags:");
5987 ImGui::BeginDisabled();
5988 ShowTableColumnsStatusFlags(column_flags_out[column]);
5989 ImGui::EndDisabled();
5990 ImGui::PopID();
5991 }
5992 PopStyleCompact();
5993 ImGui::EndTable();
5994 }
5995
5996 // Create the real table we care about for the example!
5997 // We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above,
5998 // otherwise in a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible
5999 // + resizing the parent window down).
6000 const ImGuiTableFlags flags
6001 = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
6002 | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV
6003 | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable;
6004 ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 9);
6005 if (ImGui::BeginTable("table_columns_flags", column_count, flags, outer_size))
6006 {
6007 bool has_angled_header = false;
6008 for (int column = 0; column < column_count; column++)
6009 {
6010 has_angled_header |= (column_flags[column] & ImGuiTableColumnFlags_AngledHeader) != 0;
6011 ImGui::TableSetupColumn(column_names[column], column_flags[column]);
6012 }
6013 if (has_angled_header)
6014 ImGui::TableAngledHeadersRow();
6015 ImGui::TableHeadersRow();
6016 for (int column = 0; column < column_count; column++)
6017 column_flags_out[column] = ImGui::TableGetColumnFlags(column);
6018 float indent_step = (float)((int)TEXT_BASE_WIDTH / 2);
6019 for (int row = 0; row < 8; row++)
6020 {
6021 // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags.
6022 ImGui::Indent(indent_step);
6023 ImGui::TableNextRow();
6024 for (int column = 0; column < column_count; column++)
6025 {
6026 ImGui::TableSetColumnIndex(column);
6027 ImGui::Text("%s %s", (column == 0) ? "Indented" : "Hello", ImGui::TableGetColumnName(column));
6028 }
6029 }
6030 ImGui::Unindent(indent_step * 8.0f);
6031
6032 ImGui::EndTable();
6033 }
6034 ImGui::TreePop();
6035 }
6036
6037 if (open_action != -1)
6038 ImGui::SetNextItemOpen(open_action != 0);
6039 IMGUI_DEMO_MARKER("Tables/Columns widths");
6040 if (ImGui::TreeNode("Columns widths"))
6041 {
6042 HelpMarker("Using TableSetupColumn() to setup default width.");
6043
6044 static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize;
6045 PushStyleCompact();
6046 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable);
6047 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize);
6048 PopStyleCompact();
6049 if (ImGui::BeginTable("table1", 3, flags1))
6050 {
6051 // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.
6052 ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f
6053 ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f
6054 ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto
6055 ImGui::TableHeadersRow();
6056 for (int row = 0; row < 4; row++)
6057 {
6058 ImGui::TableNextRow();
6059 for (int column = 0; column < 3; column++)
6060 {
6061 ImGui::TableSetColumnIndex(column);
6062 if (row == 0)
6063 ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x);
6064 else
6065 ImGui::Text("Hello %d,%d", column, row);
6066 }
6067 }
6068 ImGui::EndTable();
6069 }
6070
6071 HelpMarker(
6072 "Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, "
6073 "fixed columns with set width may still be shrunk down if there's not enough space in the host.");
6074
6075 static ImGuiTableFlags flags2 = ImGuiTableFlags_None;
6076 PushStyleCompact();
6077 ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible);
6078 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV);
6079 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV);
6080 PopStyleCompact();
6081 if (ImGui::BeginTable("table2", 4, flags2))
6082 {
6083 // We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns
6084 // will default to ImGuiTableColumnFlags_WidthFixed.
6085 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 100.0f);
6086 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);
6087 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f);
6088 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);
6089 for (int row = 0; row < 5; row++)
6090 {
6091 ImGui::TableNextRow();
6092 for (int column = 0; column < 4; column++)
6093 {
6094 ImGui::TableSetColumnIndex(column);
6095 if (row == 0)
6096 ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x);
6097 else
6098 ImGui::Text("Hello %d,%d", column, row);
6099 }
6100 }
6101 ImGui::EndTable();
6102 }
6103 ImGui::TreePop();
6104 }
6105
6106 if (open_action != -1)
6107 ImGui::SetNextItemOpen(open_action != 0);
6108 IMGUI_DEMO_MARKER("Tables/Nested tables");
6109 if (ImGui::TreeNode("Nested tables"))
6110 {
6111 HelpMarker("This demonstrates embedding a table into another table cell.");
6112
6113 if (ImGui::BeginTable("table_nested1", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
6114 {
6115 ImGui::TableSetupColumn("A0");
6116 ImGui::TableSetupColumn("A1");
6117 ImGui::TableHeadersRow();
6118
6119 ImGui::TableNextColumn();
6120 ImGui::Text("A0 Row 0");
6121 {
6122 float rows_height = TEXT_BASE_HEIGHT * 2;
6123 if (ImGui::BeginTable("table_nested2", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
6124 {
6125 ImGui::TableSetupColumn("B0");
6126 ImGui::TableSetupColumn("B1");
6127 ImGui::TableHeadersRow();
6128
6129 ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);
6130 ImGui::TableNextColumn();
6131 ImGui::Text("B0 Row 0");
6132 ImGui::TableNextColumn();
6133 ImGui::Text("B1 Row 0");
6134 ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);
6135 ImGui::TableNextColumn();
6136 ImGui::Text("B0 Row 1");
6137 ImGui::TableNextColumn();
6138 ImGui::Text("B1 Row 1");
6139
6140 ImGui::EndTable();
6141 }
6142 }
6143 ImGui::TableNextColumn(); ImGui::Text("A1 Row 0");
6144 ImGui::TableNextColumn(); ImGui::Text("A0 Row 1");
6145 ImGui::TableNextColumn(); ImGui::Text("A1 Row 1");
6146 ImGui::EndTable();
6147 }
6148 ImGui::TreePop();
6149 }
6150
6151 if (open_action != -1)
6152 ImGui::SetNextItemOpen(open_action != 0);
6153 IMGUI_DEMO_MARKER("Tables/Row height");
6154 if (ImGui::TreeNode("Row height"))
6155 {
6156 HelpMarker(
6157 "You can pass a 'min_row_height' to TableNextRow().\n\nRows are padded with 'style.CellPadding.y' on top and bottom, "
6158 "so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\n\n"
6159 "We cannot honor a _maximum_ row height as that would require a unique clipping rectangle per row.");
6160 if (ImGui::BeginTable("table_row_height", 1, ImGuiTableFlags_Borders))
6161 {
6162 for (int row = 0; row < 8; row++)
6163 {
6164 float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row);
6165 ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height);
6166 ImGui::TableNextColumn();
6167 ImGui::Text("min_row_height = %.2f", min_row_height);
6168 }
6169 ImGui::EndTable();
6170 }
6171
6172 HelpMarker(
6173 "Showcase using SameLine(0,0) to share Current Line Height between cells.\n\n"
6174 "Please note that Tables Row Height is not the same thing as Current Line Height, "
6175 "as a table cell may contains multiple lines.");
6176 if (ImGui::BeginTable("table_share_lineheight", 2, ImGuiTableFlags_Borders))
6177 {
6178 ImGui::TableNextRow();
6179 ImGui::TableNextColumn();
6180 ImGui::ColorButton("##1", ImVec4(0.13f, 0.26f, 0.40f, 1.0f), ImGuiColorEditFlags_None, ImVec2(40, 40));
6181 ImGui::TableNextColumn();
6182 ImGui::Text("Line 1");
6183 ImGui::Text("Line 2");
6184
6185 ImGui::TableNextRow();
6186 ImGui::TableNextColumn();
6187 ImGui::ColorButton("##2", ImVec4(0.13f, 0.26f, 0.40f, 1.0f), ImGuiColorEditFlags_None, ImVec2(40, 40));
6188 ImGui::TableNextColumn();
6189 ImGui::SameLine(0.0f, 0.0f); // Reuse line height from previous column
6190 ImGui::Text("Line 1, with SameLine(0,0)");
6191 ImGui::Text("Line 2");
6192
6193 ImGui::EndTable();
6194 }
6195
6196 HelpMarker("Showcase altering CellPadding.y between rows. Note that CellPadding.x is locked for the entire table.");
6197 if (ImGui::BeginTable("table_changing_cellpadding_y", 1, ImGuiTableFlags_Borders))
6198 {
6199 ImGuiStyle& style = ImGui::GetStyle();
6200 for (int row = 0; row < 8; row++)
6201 {
6202 if ((row % 3) == 2)
6203 ImGui::PushStyleVarY(ImGuiStyleVar_CellPadding, 20.0f);
6204 ImGui::TableNextRow(ImGuiTableRowFlags_None);
6205 ImGui::TableNextColumn();
6206 ImGui::Text("CellPadding.y = %.2f", style.CellPadding.y);
6207 if ((row % 3) == 2)
6208 ImGui::PopStyleVar();
6209 }
6210 ImGui::EndTable();
6211 }
6212
6213 ImGui::TreePop();
6214 }
6215
6216 if (open_action != -1)
6217 ImGui::SetNextItemOpen(open_action != 0);
6218 IMGUI_DEMO_MARKER("Tables/Outer size");
6219 if (ImGui::TreeNode("Outer size"))
6220 {
6221 // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY
6222 // Important to that note how the two flags have slightly different behaviors!
6223 ImGui::Text("Using NoHostExtendX and NoHostExtendY:");
6224 PushStyleCompact();
6225 static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX;
6226 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
6227 ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
6228 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY);
6229 ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
6230 PopStyleCompact();
6231
6232 ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 5.5f);
6233 if (ImGui::BeginTable("table1", 3, flags, outer_size))
6234 {
6235 for (int row = 0; row < 10; row++)
6236 {
6237 ImGui::TableNextRow();
6238 for (int column = 0; column < 3; column++)
6239 {
6240 ImGui::TableNextColumn();
6241 ImGui::Text("Cell %d,%d", column, row);
6242 }
6243 }
6244 ImGui::EndTable();
6245 }
6246 ImGui::SameLine();
6247 ImGui::Text("Hello!");
6248
6249 ImGui::Spacing();
6250
6251 ImGui::Text("Using explicit size:");
6252 if (ImGui::BeginTable("table2", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))
6253 {
6254 for (int row = 0; row < 5; row++)
6255 {
6256 ImGui::TableNextRow();
6257 for (int column = 0; column < 3; column++)
6258 {
6259 ImGui::TableNextColumn();
6260 ImGui::Text("Cell %d,%d", column, row);
6261 }
6262 }
6263 ImGui::EndTable();
6264 }
6265 ImGui::SameLine();
6266 if (ImGui::BeginTable("table3", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))
6267 {
6268 for (int row = 0; row < 3; row++)
6269 {
6270 ImGui::TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f);
6271 for (int column = 0; column < 3; column++)
6272 {
6273 ImGui::TableNextColumn();
6274 ImGui::Text("Cell %d,%d", column, row);
6275 }
6276 }
6277 ImGui::EndTable();
6278 }
6279
6280 ImGui::TreePop();
6281 }
6282
6283 if (open_action != -1)
6284 ImGui::SetNextItemOpen(open_action != 0);
6285 IMGUI_DEMO_MARKER("Tables/Background color");
6286 if (ImGui::TreeNode("Background color"))
6287 {
6288 static ImGuiTableFlags flags = ImGuiTableFlags_RowBg;
6289 static int row_bg_type = 1;
6290 static int row_bg_target = 1;
6291 static int cell_bg_type = 1;
6292
6293 PushStyleCompact();
6294 ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags, ImGuiTableFlags_Borders);
6295 ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
6296 ImGui::SameLine(); HelpMarker("ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style.");
6297 ImGui::Combo("row bg type", (int*)&row_bg_type, "None\0Red\0Gradient\0");
6298 ImGui::Combo("row bg target", (int*)&row_bg_target, "RowBg0\0RowBg1\0"); ImGui::SameLine(); HelpMarker("Target RowBg0 to override the alternating odd/even colors,\nTarget RowBg1 to blend with them.");
6299 ImGui::Combo("cell bg type", (int*)&cell_bg_type, "None\0Blue\0"); ImGui::SameLine(); HelpMarker("We are colorizing cells to B1->C2 here.");
6300 IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2);
6301 IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1);
6302 IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1);
6303 PopStyleCompact();
6304
6305 if (ImGui::BeginTable("table1", 5, flags))
6306 {
6307 for (int row = 0; row < 6; row++)
6308 {
6309 ImGui::TableNextRow();
6310
6311 // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)'
6312 // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag.
6313 if (row_bg_type != 0)
6314 {
6315 ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient?
6316 ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color);
6317 }
6318
6319 // Fill cells
6320 for (int column = 0; column < 5; column++)
6321 {
6322 ImGui::TableSetColumnIndex(column);
6323 ImGui::Text("%c%c", 'A' + row, '0' + column);
6324
6325 // Change background of Cells B1->C2
6326 // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)'
6327 // (the CellBg color will be blended over the RowBg and ColumnBg colors)
6328 // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop.
6329 if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1)
6330 {
6331 ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f));
6332 ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
6333 }
6334 }
6335 }
6336 ImGui::EndTable();
6337 }
6338 ImGui::TreePop();
6339 }
6340
6341 if (open_action != -1)
6342 ImGui::SetNextItemOpen(open_action != 0);
6343 IMGUI_DEMO_MARKER("Tables/Tree view");
6344 if (ImGui::TreeNode("Tree view"))
6345 {
6346 static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody;
6347
6348 static ImGuiTreeNodeFlags tree_node_flags = ImGuiTreeNodeFlags_SpanAllColumns;
6349 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanFullWidth);
6350 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanTextWidth", &tree_node_flags, ImGuiTreeNodeFlags_SpanTextWidth);
6351 ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAllColumns", &tree_node_flags, ImGuiTreeNodeFlags_SpanAllColumns);
6352
6353 HelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns.");
6354 if (ImGui::BeginTable("3ways", 3, flags))
6355 {
6356 // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On
6357 ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_NoHide);
6358 ImGui::TableSetupColumn("Size", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);
6359 ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f);
6360 ImGui::TableHeadersRow();
6361
6362 // Simple storage to output a dummy file-system.
6363 struct MyTreeNode
6364 {
6365 const char* Name;
6366 const char* Type;
6367 int Size;
6368 int ChildIdx;
6369 int ChildCount;
6370 static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes)
6371 {
6372 ImGui::TableNextRow();
6373 ImGui::TableNextColumn();
6374 const bool is_folder = (node->ChildCount > 0);
6375 if (is_folder)
6376 {
6377 bool open = ImGui::TreeNodeEx(node->Name, tree_node_flags);
6378 ImGui::TableNextColumn();
6379 ImGui::TextDisabled("--");
6380 ImGui::TableNextColumn();
6381 ImGui::TextUnformatted(node->Type);
6382 if (open)
6383 {
6384 for (int child_n = 0; child_n < node->ChildCount; child_n++)
6385 DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes);
6386 ImGui::TreePop();
6387 }
6388 }
6389 else
6390 {
6391 ImGui::TreeNodeEx(node->Name, tree_node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen);
6392 ImGui::TableNextColumn();
6393 ImGui::Text("%d", node->Size);
6394 ImGui::TableNextColumn();
6395 ImGui::TextUnformatted(node->Type);
6396 }
6397 }
6398 };
6399 static const MyTreeNode nodes[] =
6400 {
6401 { "Root", "Folder", -1, 1, 3 }, // 0
6402 { "Music", "Folder", -1, 4, 2 }, // 1
6403 { "Textures", "Folder", -1, 6, 3 }, // 2
6404 { "desktop.ini", "System file", 1024, -1,-1 }, // 3
6405 { "File1_a.wav", "Audio file", 123000, -1,-1 }, // 4
6406 { "File1_b.wav", "Audio file", 456000, -1,-1 }, // 5
6407 { "Image001.png", "Image file", 203128, -1,-1 }, // 6
6408 { "Copy of Image001.png", "Image file", 203256, -1,-1 }, // 7
6409 { "Copy of Image001 (Final2).png","Image file", 203512, -1,-1 }, // 8
6410 };
6411
6412 MyTreeNode::DisplayNode(&nodes[0], nodes);
6413
6414 ImGui::EndTable();
6415 }
6416 ImGui::TreePop();
6417 }
6418
6419 if (open_action != -1)
6420 ImGui::SetNextItemOpen(open_action != 0);
6421 IMGUI_DEMO_MARKER("Tables/Item width");
6422 if (ImGui::TreeNode("Item width"))
6423 {
6424 HelpMarker(
6425 "Showcase using PushItemWidth() and how it is preserved on a per-column basis.\n\n"
6426 "Note that on auto-resizing non-resizable fixed columns, querying the content width for "
6427 "e.g. right-alignment doesn't make sense.");
6428 if (ImGui::BeginTable("table_item_width", 3, ImGuiTableFlags_Borders))
6429 {
6430 ImGui::TableSetupColumn("small");
6431 ImGui::TableSetupColumn("half");
6432 ImGui::TableSetupColumn("right-align");
6433 ImGui::TableHeadersRow();
6434
6435 for (int row = 0; row < 3; row++)
6436 {
6437 ImGui::TableNextRow();
6438 if (row == 0)
6439 {
6440 // Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient)
6441 ImGui::TableSetColumnIndex(0);
6442 ImGui::PushItemWidth(TEXT_BASE_WIDTH * 3.0f); // Small
6443 ImGui::TableSetColumnIndex(1);
6444 ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);
6445 ImGui::TableSetColumnIndex(2);
6446 ImGui::PushItemWidth(-FLT_MIN); // Right-aligned
6447 }
6448
6449 // Draw our contents
6450 static float dummy_f = 0.0f;
6451 ImGui::PushID(row);
6452 ImGui::TableSetColumnIndex(0);
6453 ImGui::SliderFloat("float0", &dummy_f, 0.0f, 1.0f);
6454 ImGui::TableSetColumnIndex(1);
6455 ImGui::SliderFloat("float1", &dummy_f, 0.0f, 1.0f);
6456 ImGui::TableSetColumnIndex(2);
6457 ImGui::SliderFloat("##float2", &dummy_f, 0.0f, 1.0f); // No visible label since right-aligned
6458 ImGui::PopID();
6459 }
6460 ImGui::EndTable();
6461 }
6462 ImGui::TreePop();
6463 }
6464
6465 // Demonstrate using TableHeader() calls instead of TableHeadersRow()
6466 if (open_action != -1)
6467 ImGui::SetNextItemOpen(open_action != 0);
6468 IMGUI_DEMO_MARKER("Tables/Custom headers");
6469 if (ImGui::TreeNode("Custom headers"))
6470 {
6471 const int COLUMNS_COUNT = 3;
6472 if (ImGui::BeginTable("table_custom_headers", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
6473 {
6474 ImGui::TableSetupColumn("Apricot");
6475 ImGui::TableSetupColumn("Banana");
6476 ImGui::TableSetupColumn("Cherry");
6477
6478 // Dummy entire-column selection storage
6479 // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox.
6480 static bool column_selected[3] = {};
6481
6482 // Instead of calling TableHeadersRow() we'll submit custom headers ourselves.
6483 // (A different approach is also possible:
6484 // - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call.
6485 // - Call TableHeadersRow() normally. This will submit TableHeader() with no name.
6486 // - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().)
6487 ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
6488 for (int column = 0; column < COLUMNS_COUNT; column++)
6489 {
6490 ImGui::TableSetColumnIndex(column);
6491 const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn()
6492 ImGui::PushID(column);
6493 ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
6494 ImGui::Checkbox("##checkall", &column_selected[column]);
6495 ImGui::PopStyleVar();
6496 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
6497 ImGui::TableHeader(column_name);
6498 ImGui::PopID();
6499 }
6500
6501 // Submit table contents
6502 for (int row = 0; row < 5; row++)
6503 {
6504 ImGui::TableNextRow();
6505 for (int column = 0; column < 3; column++)
6506 {
6507 char buf[32];
6508 sprintf(buf, "Cell %d,%d", column, row);
6509 ImGui::TableSetColumnIndex(column);
6510 ImGui::Selectable(buf, column_selected[column]);
6511 }
6512 }
6513 ImGui::EndTable();
6514 }
6515 ImGui::TreePop();
6516 }
6517
6518 // Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers
6519 if (open_action != -1)
6520 ImGui::SetNextItemOpen(open_action != 0);
6521 IMGUI_DEMO_MARKER("Tables/Angled headers");
6522 if (ImGui::TreeNode("Angled headers"))
6523 {
6524 const char* column_names[] = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" };
6525 const int columns_count = IM_ARRAYSIZE(column_names);
6526 const int rows_count = 12;
6527
6528 static ImGuiTableFlags table_flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_HighlightHoveredColumn;
6529 static ImGuiTableColumnFlags column_flags = ImGuiTableColumnFlags_AngledHeader | ImGuiTableColumnFlags_WidthFixed;
6530 static bool bools[columns_count * rows_count] = {}; // Dummy storage selection storage
6531 static int frozen_cols = 1;
6532 static int frozen_rows = 2;
6533 ImGui::CheckboxFlags("_ScrollX", &table_flags, ImGuiTableFlags_ScrollX);
6534 ImGui::CheckboxFlags("_ScrollY", &table_flags, ImGuiTableFlags_ScrollY);
6535 ImGui::CheckboxFlags("_Resizable", &table_flags, ImGuiTableFlags_Resizable);
6536 ImGui::CheckboxFlags("_Sortable", &table_flags, ImGuiTableFlags_Sortable);
6537 ImGui::CheckboxFlags("_NoBordersInBody", &table_flags, ImGuiTableFlags_NoBordersInBody);
6538 ImGui::CheckboxFlags("_HighlightHoveredColumn", &table_flags, ImGuiTableFlags_HighlightHoveredColumn);
6539 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
6540 ImGui::SliderInt("Frozen columns", &frozen_cols, 0, 2);
6541 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
6542 ImGui::SliderInt("Frozen rows", &frozen_rows, 0, 2);
6543 ImGui::CheckboxFlags("Disable header contributing to column width", &column_flags, ImGuiTableColumnFlags_NoHeaderWidth);
6544
6545 if (ImGui::TreeNode("Style settings"))
6546 {
6547 ImGui::SameLine();
6548 HelpMarker("Giving access to some ImGuiStyle value in this demo for convenience.");
6549 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
6550 ImGui::SliderAngle("style.TableAngledHeadersAngle", &ImGui::GetStyle().TableAngledHeadersAngle, -50.0f, +50.0f);
6551 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
6552 ImGui::SliderFloat2("style.TableAngledHeadersTextAlign", (float*)&ImGui::GetStyle().TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f");
6553 ImGui::TreePop();
6554 }
6555
6556 if (ImGui::BeginTable("table_angled_headers", columns_count, table_flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 12)))
6557 {
6558 ImGui::TableSetupColumn(column_names[0], ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_NoReorder);
6559 for (int n = 1; n < columns_count; n++)
6560 ImGui::TableSetupColumn(column_names[n], column_flags);
6561 ImGui::TableSetupScrollFreeze(frozen_cols, frozen_rows);
6562
6563 ImGui::TableAngledHeadersRow(); // Draw angled headers for all columns with the ImGuiTableColumnFlags_AngledHeader flag.
6564 ImGui::TableHeadersRow(); // Draw remaining headers and allow access to context-menu and other functions.
6565 for (int row = 0; row < rows_count; row++)
6566 {
6567 ImGui::PushID(row);
6568 ImGui::TableNextRow();
6569 ImGui::TableSetColumnIndex(0);
6570 ImGui::AlignTextToFramePadding();
6571 ImGui::Text("Track %d", row);
6572 for (int column = 1; column < columns_count; column++)
6573 if (ImGui::TableSetColumnIndex(column))
6574 {
6575 ImGui::PushID(column);
6576 ImGui::Checkbox("", &bools[row * columns_count + column]);
6577 ImGui::PopID();
6578 }
6579 ImGui::PopID();
6580 }
6581 ImGui::EndTable();
6582 }
6583 ImGui::TreePop();
6584 }
6585
6586 // Demonstrate creating custom context menus inside columns,
6587 // while playing it nice with context menus provided by TableHeadersRow()/TableHeader()
6588 if (open_action != -1)
6589 ImGui::SetNextItemOpen(open_action != 0);
6590 IMGUI_DEMO_MARKER("Tables/Context menus");
6591 if (ImGui::TreeNode("Context menus"))
6592 {
6593 HelpMarker(
6594 "By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\n"
6595 "Using ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body.");
6596 static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody;
6597
6598 PushStyleCompact();
6599 ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags1, ImGuiTableFlags_ContextMenuInBody);
6600 PopStyleCompact();
6601
6602 // Context Menus: first example
6603 // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu.
6604 // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set)
6605 const int COLUMNS_COUNT = 3;
6606 if (ImGui::BeginTable("table_context_menu", COLUMNS_COUNT, flags1))
6607 {
6608 ImGui::TableSetupColumn("One");
6609 ImGui::TableSetupColumn("Two");
6610 ImGui::TableSetupColumn("Three");
6611
6612 // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu.
6613 ImGui::TableHeadersRow();
6614
6615 // Submit dummy contents
6616 for (int row = 0; row < 4; row++)
6617 {
6618 ImGui::TableNextRow();
6619 for (int column = 0; column < COLUMNS_COUNT; column++)
6620 {
6621 ImGui::TableSetColumnIndex(column);
6622 ImGui::Text("Cell %d,%d", column, row);
6623 }
6624 }
6625 ImGui::EndTable();
6626 }
6627
6628 // Context Menus: second example
6629 // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
6630 // [2.2] Right-click on the ".." to open a custom popup
6631 // [2.3] Right-click in columns to open another custom popup
6632 HelpMarker(
6633 "Demonstrate mixing table context menu (over header), item context button (over button) "
6634 "and custom per-colunm context menu (over column body).");
6635 ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders;
6636 if (ImGui::BeginTable("table_context_menu_2", COLUMNS_COUNT, flags2))
6637 {
6638 ImGui::TableSetupColumn("One");
6639 ImGui::TableSetupColumn("Two");
6640 ImGui::TableSetupColumn("Three");
6641
6642 // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.
6643 ImGui::TableHeadersRow();
6644 for (int row = 0; row < 4; row++)
6645 {
6646 ImGui::TableNextRow();
6647 for (int column = 0; column < COLUMNS_COUNT; column++)
6648 {
6649 // Submit dummy contents
6650 ImGui::TableSetColumnIndex(column);
6651 ImGui::Text("Cell %d,%d", column, row);
6652 ImGui::SameLine();
6653
6654 // [2.2] Right-click on the ".." to open a custom popup
6655 ImGui::PushID(row * COLUMNS_COUNT + column);
6656 ImGui::SmallButton("..");
6657 if (ImGui::BeginPopupContextItem())
6658 {
6659 ImGui::Text("This is the popup for Button(\"..\") in Cell %d,%d", column, row);
6660 if (ImGui::Button("Close"))
6661 ImGui::CloseCurrentPopup();
6662 ImGui::EndPopup();
6663 }
6664 ImGui::PopID();
6665 }
6666 }
6667
6668 // [2.3] Right-click anywhere in columns to open another custom popup
6669 // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup
6670 // to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping)
6671 int hovered_column = -1;
6672 for (int column = 0; column < COLUMNS_COUNT + 1; column++)
6673 {
6674 ImGui::PushID(column);
6675 if (ImGui::TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered)
6676 hovered_column = column;
6677 if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1))
6678 ImGui::OpenPopup("MyPopup");
6679 if (ImGui::BeginPopup("MyPopup"))
6680 {
6681 if (column == COLUMNS_COUNT)
6682 ImGui::Text("This is a custom popup for unused space after the last column.");
6683 else
6684 ImGui::Text("This is a custom popup for Column %d", column);
6685 if (ImGui::Button("Close"))
6686 ImGui::CloseCurrentPopup();
6687 ImGui::EndPopup();
6688 }
6689 ImGui::PopID();
6690 }
6691
6692 ImGui::EndTable();
6693 ImGui::Text("Hovered column: %d", hovered_column);
6694 }
6695 ImGui::TreePop();
6696 }
6697
6698 // Demonstrate creating multiple tables with the same ID
6699 if (open_action != -1)
6700 ImGui::SetNextItemOpen(open_action != 0);
6701 IMGUI_DEMO_MARKER("Tables/Synced instances");
6702 if (ImGui::TreeNode("Synced instances"))
6703 {
6704 HelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.");
6705
6706 static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings;
6707 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
6708 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
6709 ImGui::CheckboxFlags("ImGuiTableFlags_SizingFixedFit", &flags, ImGuiTableFlags_SizingFixedFit);
6710 ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn);
6711 for (int n = 0; n < 3; n++)
6712 {
6713 char buf[32];
6714 sprintf(buf, "Synced Table %d", n);
6715 bool open = ImGui::CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen);
6716 if (open && ImGui::BeginTable("Table", 3, flags, ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 5)))
6717 {
6718 ImGui::TableSetupColumn("One");
6719 ImGui::TableSetupColumn("Two");
6720 ImGui::TableSetupColumn("Three");
6721 ImGui::TableHeadersRow();
6722 const int cell_count = (n == 1) ? 27 : 9; // Make second table have a scrollbar to verify that additional decoration is not affecting column positions.
6723 for (int cell = 0; cell < cell_count; cell++)
6724 {
6725 ImGui::TableNextColumn();
6726 ImGui::Text("this cell %d", cell);
6727 }
6728 ImGui::EndTable();
6729 }
6730 }
6731 ImGui::TreePop();
6732 }
6733
6734 // Demonstrate using Sorting facilities
6735 // This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting.
6736 // Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified)
6737 static const char* template_items_names[] =
6738 {
6739 "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango",
6740 "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot"
6741 };
6742 if (open_action != -1)
6743 ImGui::SetNextItemOpen(open_action != 0);
6744 IMGUI_DEMO_MARKER("Tables/Sorting");
6745 if (ImGui::TreeNode("Sorting"))
6746 {
6747 // Create item list
6748 static ImVector<MyItem> items;
6749 if (items.Size == 0)
6750 {
6751 items.resize(50, MyItem());
6752 for (int n = 0; n < items.Size; n++)
6753 {
6754 const int template_n = n % IM_ARRAYSIZE(template_items_names);
6755 MyItem& item = items[n];
6756 item.ID = n;
6757 item.Name = template_items_names[template_n];
6758 item.Quantity = (n * n - n) % 20; // Assign default quantities
6759 }
6760 }
6761
6762 // Options
6763 static ImGuiTableFlags flags =
6764 ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
6765 | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody
6766 | ImGuiTableFlags_ScrollY;
6767 PushStyleCompact();
6768 ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti);
6769 ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
6770 ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate);
6771 ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
6772 PopStyleCompact();
6773
6774 if (ImGui::BeginTable("table_sorting", 4, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 15), 0.0f))
6775 {
6776 // Declare columns
6777 // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
6778 // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!
6779 // Demonstrate using a mixture of flags among available sort-related flags:
6780 // - ImGuiTableColumnFlags_DefaultSort
6781 // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending
6782 // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending
6783 ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_ID);
6784 ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name);
6785 ImGui::TableSetupColumn("Action", ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action);
6786 ImGui::TableSetupColumn("Quantity", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Quantity);
6787 ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible
6788 ImGui::TableHeadersRow();
6789
6790 // Sort our data if sort specs have been changed!
6791 if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs())
6792 if (sort_specs->SpecsDirty)
6793 {
6794 MyItem::SortWithSortSpecs(sort_specs, items.Data, items.Size);
6795 sort_specs->SpecsDirty = false;
6796 }
6797
6798 // Demonstrate using clipper for large vertical lists
6799 ImGuiListClipper clipper;
6800 clipper.Begin(items.Size);
6801 while (clipper.Step())
6802 for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)
6803 {
6804 // Display a data item
6805 MyItem* item = &items[row_n];
6806 ImGui::PushID(item->ID);
6807 ImGui::TableNextRow();
6808 ImGui::TableNextColumn();
6809 ImGui::Text("%04d", item->ID);
6810 ImGui::TableNextColumn();
6811 ImGui::TextUnformatted(item->Name);
6812 ImGui::TableNextColumn();
6813 ImGui::SmallButton("None");
6814 ImGui::TableNextColumn();
6815 ImGui::Text("%d", item->Quantity);
6816 ImGui::PopID();
6817 }
6818 ImGui::EndTable();
6819 }
6820 ImGui::TreePop();
6821 }
6822
6823 // In this example we'll expose most table flags and settings.
6824 // For specific flags and settings refer to the corresponding section for more detailed explanation.
6825 // This section is mostly useful to experiment with combining certain flags or settings with each others.
6826 //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG]
6827 if (open_action != -1)
6828 ImGui::SetNextItemOpen(open_action != 0);
6829 IMGUI_DEMO_MARKER("Tables/Advanced");
6830 if (ImGui::TreeNode("Advanced"))
6831 {
6832 static ImGuiTableFlags flags =
6833 ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable
6834 | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti
6835 | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody
6836 | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY
6837 | ImGuiTableFlags_SizingFixedFit;
6838 static ImGuiTableColumnFlags columns_base_flags = ImGuiTableColumnFlags_None;
6839
6840 enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow };
6841 static int contents_type = CT_SelectableSpanRow;
6842 const char* contents_type_names[] = { "Text", "Button", "SmallButton", "FillButton", "Selectable", "Selectable (span row)" };
6843 static int freeze_cols = 1;
6844 static int freeze_rows = 1;
6845 static int items_count = IM_ARRAYSIZE(template_items_names) * 2;
6846 static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12);
6847 static float row_min_height = 0.0f; // Auto
6848 static float inner_width_with_scroll = 0.0f; // Auto-extend
6849 static bool outer_size_enabled = true;
6850 static bool show_headers = true;
6851 static bool show_wrapped_text = false;
6852 //static ImGuiTextFilter filter;
6853 //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affect column sizing
6854 if (ImGui::TreeNode("Options"))
6855 {
6856 // Make the UI compact because there are so many fields
6857 PushStyleCompact();
6858 ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f);
6859
6860 if (ImGui::TreeNodeEx("Features:", ImGuiTreeNodeFlags_DefaultOpen))
6861 {
6862 ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags, ImGuiTableFlags_Resizable);
6863 ImGui::CheckboxFlags("ImGuiTableFlags_Reorderable", &flags, ImGuiTableFlags_Reorderable);
6864 ImGui::CheckboxFlags("ImGuiTableFlags_Hideable", &flags, ImGuiTableFlags_Hideable);
6865 ImGui::CheckboxFlags("ImGuiTableFlags_Sortable", &flags, ImGuiTableFlags_Sortable);
6866 ImGui::CheckboxFlags("ImGuiTableFlags_NoSavedSettings", &flags, ImGuiTableFlags_NoSavedSettings);
6867 ImGui::CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", &flags, ImGuiTableFlags_ContextMenuInBody);
6868 ImGui::TreePop();
6869 }
6870
6871 if (ImGui::TreeNodeEx("Decorations:", ImGuiTreeNodeFlags_DefaultOpen))
6872 {
6873 ImGui::CheckboxFlags("ImGuiTableFlags_RowBg", &flags, ImGuiTableFlags_RowBg);
6874 ImGui::CheckboxFlags("ImGuiTableFlags_BordersV", &flags, ImGuiTableFlags_BordersV);
6875 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags, ImGuiTableFlags_BordersOuterV);
6876 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags, ImGuiTableFlags_BordersInnerV);
6877 ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags, ImGuiTableFlags_BordersH);
6878 ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterH", &flags, ImGuiTableFlags_BordersOuterH);
6879 ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerH", &flags, ImGuiTableFlags_BordersInnerH);
6880 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers");
6881 ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers)");
6882 ImGui::TreePop();
6883 }
6884
6885 if (ImGui::TreeNodeEx("Sizing:", ImGuiTreeNodeFlags_DefaultOpen))
6886 {
6887 EditTableSizingFlags(&flags);
6888 ImGui::SameLine(); HelpMarker("In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical.");
6889 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendX", &flags, ImGuiTableFlags_NoHostExtendX);
6890 ImGui::SameLine(); HelpMarker("Make outer width auto-fit to columns, overriding outer_size.x value.\n\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.");
6891 ImGui::CheckboxFlags("ImGuiTableFlags_NoHostExtendY", &flags, ImGuiTableFlags_NoHostExtendY);
6892 ImGui::SameLine(); HelpMarker("Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\n\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.");
6893 ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags, ImGuiTableFlags_NoKeepColumnsVisible);
6894 ImGui::SameLine(); HelpMarker("Only available if ScrollX is disabled.");
6895 ImGui::CheckboxFlags("ImGuiTableFlags_PreciseWidths", &flags, ImGuiTableFlags_PreciseWidths);
6896 ImGui::SameLine(); HelpMarker("Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.");
6897 ImGui::CheckboxFlags("ImGuiTableFlags_NoClip", &flags, ImGuiTableFlags_NoClip);
6898 ImGui::SameLine(); HelpMarker("Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options.");
6899 ImGui::TreePop();
6900 }
6901
6902 if (ImGui::TreeNodeEx("Padding:", ImGuiTreeNodeFlags_DefaultOpen))
6903 {
6904 ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX);
6905 ImGui::CheckboxFlags("ImGuiTableFlags_NoPadOuterX", &flags, ImGuiTableFlags_NoPadOuterX);
6906 ImGui::CheckboxFlags("ImGuiTableFlags_NoPadInnerX", &flags, ImGuiTableFlags_NoPadInnerX);
6907 ImGui::TreePop();
6908 }
6909
6910 if (ImGui::TreeNodeEx("Scrolling:", ImGuiTreeNodeFlags_DefaultOpen))
6911 {
6912 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollX", &flags, ImGuiTableFlags_ScrollX);
6913 ImGui::SameLine();
6914 ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
6915 ImGui::DragInt("freeze_cols", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
6916 ImGui::CheckboxFlags("ImGuiTableFlags_ScrollY", &flags, ImGuiTableFlags_ScrollY);
6917 ImGui::SameLine();
6918 ImGui::SetNextItemWidth(ImGui::GetFrameHeight());
6919 ImGui::DragInt("freeze_rows", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);
6920 ImGui::TreePop();
6921 }
6922
6923 if (ImGui::TreeNodeEx("Sorting:", ImGuiTreeNodeFlags_DefaultOpen))
6924 {
6925 ImGui::CheckboxFlags("ImGuiTableFlags_SortMulti", &flags, ImGuiTableFlags_SortMulti);
6926 ImGui::SameLine(); HelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).");
6927 ImGui::CheckboxFlags("ImGuiTableFlags_SortTristate", &flags, ImGuiTableFlags_SortTristate);
6928 ImGui::SameLine(); HelpMarker("When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).");
6929 ImGui::TreePop();
6930 }
6931
6932 if (ImGui::TreeNodeEx("Headers:", ImGuiTreeNodeFlags_DefaultOpen))
6933 {
6934 ImGui::Checkbox("show_headers", &show_headers);
6935 ImGui::CheckboxFlags("ImGuiTableFlags_HighlightHoveredColumn", &flags, ImGuiTableFlags_HighlightHoveredColumn);
6936 ImGui::CheckboxFlags("ImGuiTableColumnFlags_AngledHeader", &columns_base_flags, ImGuiTableColumnFlags_AngledHeader);
6937 ImGui::SameLine(); HelpMarker("Enable AngledHeader on all columns. Best enabled on selected narrow columns (see \"Angled headers\" section of the demo).");
6938 ImGui::TreePop();
6939 }
6940
6941 if (ImGui::TreeNodeEx("Other:", ImGuiTreeNodeFlags_DefaultOpen))
6942 {
6943 ImGui::Checkbox("show_wrapped_text", &show_wrapped_text);
6944
6945 ImGui::DragFloat2("##OuterSize", &outer_size_value.x);
6946 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
6947 ImGui::Checkbox("outer_size", &outer_size_enabled);
6948 ImGui::SameLine();
6949 HelpMarker("If scrolling is disabled (ScrollX and ScrollY not set):\n"
6950 "- The table is output directly in the parent window.\n"
6951 "- OuterSize.x < 0.0f will right-align the table.\n"
6952 "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch columns.\n"
6953 "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).");
6954
6955 // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling.
6956 // To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled.
6957 ImGui::DragFloat("inner_width (when ScrollX active)", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX);
6958
6959 ImGui::DragFloat("row_min_height", &row_min_height, 1.0f, 0.0f, FLT_MAX);
6960 ImGui::SameLine(); HelpMarker("Specify height of the Selectable item.");
6961
6962 ImGui::DragInt("items_count", &items_count, 0.1f, 0, 9999);
6963 ImGui::Combo("items_type (first column)", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names));
6964 //filter.Draw("filter");
6965 ImGui::TreePop();
6966 }
6967
6968 ImGui::PopItemWidth();
6969 PopStyleCompact();
6970 ImGui::Spacing();
6971 ImGui::TreePop();
6972 }
6973
6974 // Update item list if we changed the number of items
6975 static ImVector<MyItem> items;
6976 static ImVector<int> selection;
6977 static bool items_need_sort = false;
6978 if (items.Size != items_count)
6979 {
6980 items.resize(items_count, MyItem());
6981 for (int n = 0; n < items_count; n++)
6982 {
6983 const int template_n = n % IM_ARRAYSIZE(template_items_names);
6984 MyItem& item = items[n];
6985 item.ID = n;
6986 item.Name = template_items_names[template_n];
6987 item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities
6988 }
6989 }
6990
6991 const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList();
6992 const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size;
6993 ImVec2 table_scroll_cur, table_scroll_max; // For debug display
6994 const ImDrawList* table_draw_list = NULL; // "
6995
6996 // Submit table
6997 const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f;
6998 if (ImGui::BeginTable("table_advanced", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use))
6999 {
7000 // Declare columns
7001 // We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.
7002 // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!
7003 ImGui::TableSetupColumn("ID", columns_base_flags | ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0f, MyItemColumnID_ID);
7004 ImGui::TableSetupColumn("Name", columns_base_flags | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name);
7005 ImGui::TableSetupColumn("Action", columns_base_flags | ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action);
7006 ImGui::TableSetupColumn("Quantity", columns_base_flags | ImGuiTableColumnFlags_PreferSortDescending, 0.0f, MyItemColumnID_Quantity);
7007 ImGui::TableSetupColumn("Description", columns_base_flags | ((flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch), 0.0f, MyItemColumnID_Description);
7008 ImGui::TableSetupColumn("Hidden", columns_base_flags | ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort);
7009 ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);
7010
7011 // Sort our data if sort specs have been changed!
7012 ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs();
7013 if (sort_specs && sort_specs->SpecsDirty)
7014 items_need_sort = true;
7015 if (sort_specs && items_need_sort && items.Size > 1)
7016 {
7017 MyItem::SortWithSortSpecs(sort_specs, items.Data, items.Size);
7018 sort_specs->SpecsDirty = false;
7019 }
7020 items_need_sort = false;
7021
7022 // Take note of whether we are currently sorting based on the Quantity field,
7023 // we will use this to trigger sorting when we know the data of this column has been modified.
7024 const bool sorts_specs_using_quantity = (ImGui::TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) != 0;
7025
7026 // Show headers
7027 if (show_headers && (columns_base_flags & ImGuiTableColumnFlags_AngledHeader) != 0)
7028 ImGui::TableAngledHeadersRow();
7029 if (show_headers)
7030 ImGui::TableHeadersRow();
7031
7032 // Show data
7033 // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here?
7034 #if 1
7035 // Demonstrate using clipper for large vertical lists
7036 ImGuiListClipper clipper;
7037 clipper.Begin(items.Size);
7038 while (clipper.Step())
7039 {
7040 for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)
7041 #else
7042 // Without clipper
7043 {
7044 for (int row_n = 0; row_n < items.Size; row_n++)
7045 #endif
7046 {
7047 MyItem* item = &items[row_n];
7048 //if (!filter.PassFilter(item->Name))
7049 // continue;
7050
7051 const bool item_is_selected = selection.contains(item->ID);
7052 ImGui::PushID(item->ID);
7053 ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height);
7054
7055 // For the demo purpose we can select among different type of items submitted in the first column
7056 ImGui::TableSetColumnIndex(0);
7057 char label[32];
7058 sprintf(label, "%04d", item->ID);
7059 if (contents_type == CT_Text)
7060 ImGui::TextUnformatted(label);
7061 else if (contents_type == CT_Button)
7062 ImGui::Button(label);
7063 else if (contents_type == CT_SmallButton)
7064 ImGui::SmallButton(label);
7065 else if (contents_type == CT_FillButton)
7066 ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f));
7067 else if (contents_type == CT_Selectable || contents_type == CT_SelectableSpanRow)
7068 {
7069 ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowOverlap : ImGuiSelectableFlags_None;
7070 if (ImGui::Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height)))
7071 {
7072 if (ImGui::GetIO().KeyCtrl)
7073 {
7074 if (item_is_selected)
7075 selection.find_erase_unsorted(item->ID);
7076 else
7077 selection.push_back(item->ID);
7078 }
7079 else
7080 {
7081 selection.clear();
7082 selection.push_back(item->ID);
7083 }
7084 }
7085 }
7086
7087 if (ImGui::TableSetColumnIndex(1))
7088 ImGui::TextUnformatted(item->Name);
7089
7090 // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity,
7091 // and we are currently sorting on the column showing the Quantity.
7092 // To avoid triggering a sort while holding the button, we only trigger it when the button has been released.
7093 // You will probably need some extra logic if you want to automatically sort when a specific entry changes.
7094 if (ImGui::TableSetColumnIndex(2))
7095 {
7096 if (ImGui::SmallButton("Chop")) { item->Quantity += 1; }
7097 if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }
7098 ImGui::SameLine();
7099 if (ImGui::SmallButton("Eat")) { item->Quantity -= 1; }
7100 if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }
7101 }
7102
7103 if (ImGui::TableSetColumnIndex(3))
7104 ImGui::Text("%d", item->Quantity);
7105
7106 ImGui::TableSetColumnIndex(4);
7107 if (show_wrapped_text)
7108 ImGui::TextWrapped("Lorem ipsum dolor sit amet");
7109 else
7110 ImGui::Text("Lorem ipsum dolor sit amet");
7111
7112 if (ImGui::TableSetColumnIndex(5))
7113 ImGui::Text("1234");
7114
7115 ImGui::PopID();
7116 }
7117 }
7118
7119 // Store some info to display debug details below
7120 table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY());
7121 table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY());
7122 table_draw_list = ImGui::GetWindowDrawList();
7123 ImGui::EndTable();
7124 }
7125 static bool show_debug_details = false;
7126 ImGui::Checkbox("Debug details", &show_debug_details);
7127 if (show_debug_details && table_draw_list)
7128 {
7129 ImGui::SameLine(0.0f, 0.0f);
7130 const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size;
7131 if (table_draw_list == parent_draw_list)
7132 ImGui::Text(": DrawCmd: +%d (in same window)",
7133 table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count);
7134 else
7135 ImGui::Text(": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)",
7136 table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y);
7137 }
7138 ImGui::TreePop();
7139 }
7140
7141 ImGui::PopID();
7142
7143 ShowDemoWindowColumns();
7144
7145 if (disable_indent)
7146 ImGui::PopStyleVar();
7147 }
7148
7149 // Demonstrate old/legacy Columns API!
7150 // [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!]
7151 static void ShowDemoWindowColumns()
7152 {
7153 IMGUI_DEMO_MARKER("Columns (legacy API)");
7154 bool open = ImGui::TreeNode("Legacy Columns API");
7155 ImGui::SameLine();
7156 HelpMarker("Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!");
7157 if (!open)
7158 return;
7159
7160 // Basic columns
7161 IMGUI_DEMO_MARKER("Columns (legacy API)/Basic");
7162 if (ImGui::TreeNode("Basic"))
7163 {
7164 ImGui::Text("Without border:");
7165 ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border
7166 ImGui::Separator();
7167 for (int n = 0; n < 14; n++)
7168 {
7169 char label[32];
7170 sprintf(label, "Item %d", n);
7171 if (ImGui::Selectable(label)) {}
7172 //if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {}
7173 ImGui::NextColumn();
7174 }
7175 ImGui::Columns(1);
7176 ImGui::Separator();
7177
7178 ImGui::Text("With border:");
7179 ImGui::Columns(4, "mycolumns"); // 4-ways, with border
7180 ImGui::Separator();
7181 ImGui::Text("ID"); ImGui::NextColumn();
7182 ImGui::Text("Name"); ImGui::NextColumn();
7183 ImGui::Text("Path"); ImGui::NextColumn();
7184 ImGui::Text("Hovered"); ImGui::NextColumn();
7185 ImGui::Separator();
7186 const char* names[3] = { "One", "Two", "Three" };
7187 const char* paths[3] = { "/path/one", "/path/two", "/path/three" };
7188 static int selected = -1;
7189 for (int i = 0; i < 3; i++)
7190 {
7191 char label[32];
7192 sprintf(label, "%04d", i);
7193 if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
7194 selected = i;
7195 bool hovered = ImGui::IsItemHovered();
7196 ImGui::NextColumn();
7197 ImGui::Text(names[i]); ImGui::NextColumn();
7198 ImGui::Text(paths[i]); ImGui::NextColumn();
7199 ImGui::Text("%d", hovered); ImGui::NextColumn();
7200 }
7201 ImGui::Columns(1);
7202 ImGui::Separator();
7203 ImGui::TreePop();
7204 }
7205
7206 IMGUI_DEMO_MARKER("Columns (legacy API)/Borders");
7207 if (ImGui::TreeNode("Borders"))
7208 {
7209 // NB: Future columns API should allow automatic horizontal borders.
7210 static bool h_borders = true;
7211 static bool v_borders = true;
7212 static int columns_count = 4;
7213 const int lines_count = 3;
7214 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
7215 ImGui::DragInt("##columns_count", &columns_count, 0.1f, 2, 10, "%d columns");
7216 if (columns_count < 2)
7217 columns_count = 2;
7218 ImGui::SameLine();
7219 ImGui::Checkbox("horizontal", &h_borders);
7220 ImGui::SameLine();
7221 ImGui::Checkbox("vertical", &v_borders);
7222 ImGui::Columns(columns_count, NULL, v_borders);
7223 for (int i = 0; i < columns_count * lines_count; i++)
7224 {
7225 if (h_borders && ImGui::GetColumnIndex() == 0)
7226 ImGui::Separator();
7227 ImGui::PushID(i);
7228 ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i);
7229 ImGui::Text("Width %.2f", ImGui::GetColumnWidth());
7230 ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x);
7231 ImGui::Text("Offset %.2f", ImGui::GetColumnOffset());
7232 ImGui::Text("Long text that is likely to clip");
7233 ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f));
7234 ImGui::PopID();
7235 ImGui::NextColumn();
7236 }
7237 ImGui::Columns(1);
7238 if (h_borders)
7239 ImGui::Separator();
7240 ImGui::TreePop();
7241 }
7242
7243 // Create multiple items in a same cell before switching to next column
7244 IMGUI_DEMO_MARKER("Columns (legacy API)/Mixed items");
7245 if (ImGui::TreeNode("Mixed items"))
7246 {
7247 ImGui::Columns(3, "mixed");
7248 ImGui::Separator();
7249
7250 ImGui::Text("Hello");
7251 ImGui::Button("Banana");
7252 ImGui::NextColumn();
7253
7254 ImGui::Text("ImGui");
7255 ImGui::Button("Apple");
7256 static float foo = 1.0f;
7257 ImGui::InputFloat("red", &foo, 0.05f, 0, "%.3f");
7258 ImGui::Text("An extra line here.");
7259 ImGui::NextColumn();
7260
7261 ImGui::Text("Sailor");
7262 ImGui::Button("Corniflower");
7263 static float bar = 1.0f;
7264 ImGui::InputFloat("blue", &bar, 0.05f, 0, "%.3f");
7265 ImGui::NextColumn();
7266
7267 if (ImGui::CollapsingHeader("Category A")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
7268 if (ImGui::CollapsingHeader("Category B")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
7269 if (ImGui::CollapsingHeader("Category C")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
7270 ImGui::Columns(1);
7271 ImGui::Separator();
7272 ImGui::TreePop();
7273 }
7274
7275 // Word wrapping
7276 IMGUI_DEMO_MARKER("Columns (legacy API)/Word-wrapping");
7277 if (ImGui::TreeNode("Word-wrapping"))
7278 {
7279 ImGui::Columns(2, "word-wrapping");
7280 ImGui::Separator();
7281 ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
7282 ImGui::TextWrapped("Hello Left");
7283 ImGui::NextColumn();
7284 ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
7285 ImGui::TextWrapped("Hello Right");
7286 ImGui::Columns(1);
7287 ImGui::Separator();
7288 ImGui::TreePop();
7289 }
7290
7291 IMGUI_DEMO_MARKER("Columns (legacy API)/Horizontal Scrolling");
7292 if (ImGui::TreeNode("Horizontal Scrolling"))
7293 {
7294 ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));
7295 ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f);
7296 ImGui::BeginChild("##ScrollingRegion", child_size, ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar);
7297 ImGui::Columns(10);
7298
7299 // Also demonstrate using clipper for large vertical lists
7300 int ITEMS_COUNT = 2000;
7301 ImGuiListClipper clipper;
7302 clipper.Begin(ITEMS_COUNT);
7303 while (clipper.Step())
7304 {
7305 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
7306 for (int j = 0; j < 10; j++)
7307 {
7308 ImGui::Text("Line %d Column %d...", i, j);
7309 ImGui::NextColumn();
7310 }
7311 }
7312 ImGui::Columns(1);
7313 ImGui::EndChild();
7314 ImGui::TreePop();
7315 }
7316
7317 IMGUI_DEMO_MARKER("Columns (legacy API)/Tree");
7318 if (ImGui::TreeNode("Tree"))
7319 {
7320 ImGui::Columns(2, "tree", true);
7321 for (int x = 0; x < 3; x++)
7322 {
7323 bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x);
7324 ImGui::NextColumn();
7325 ImGui::Text("Node contents");
7326 ImGui::NextColumn();
7327 if (open1)
7328 {
7329 for (int y = 0; y < 3; y++)
7330 {
7331 bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y);
7332 ImGui::NextColumn();
7333 ImGui::Text("Node contents");
7334 if (open2)
7335 {
7336 ImGui::Text("Even more contents");
7337 if (ImGui::TreeNode("Tree in column"))
7338 {
7339 ImGui::Text("The quick brown fox jumps over the lazy dog");
7340 ImGui::TreePop();
7341 }
7342 }
7343 ImGui::NextColumn();
7344 if (open2)
7345 ImGui::TreePop();
7346 }
7347 ImGui::TreePop();
7348 }
7349 }
7350 ImGui::Columns(1);
7351 ImGui::TreePop();
7352 }
7353
7354 ImGui::TreePop();
7355 }
7356
7357 //-----------------------------------------------------------------------------
7358 // [SECTION] ShowDemoWindowInputs()
7359 //-----------------------------------------------------------------------------
7360
7361 static void ShowDemoWindowInputs()
7362 {
7363 IMGUI_DEMO_MARKER("Inputs & Focus");
7364 if (ImGui::CollapsingHeader("Inputs & Focus"))
7365 {
7366 ImGuiIO& io = ImGui::GetIO();
7367
7368 // Display inputs submitted to ImGuiIO
7369 IMGUI_DEMO_MARKER("Inputs & Focus/Inputs");
7370 ImGui::SetNextItemOpen(true, ImGuiCond_Once);
7371 bool inputs_opened = ImGui::TreeNode("Inputs");
7372 ImGui::SameLine();
7373 HelpMarker(
7374 "This is a simplified view. See more detailed input state:\n"
7375 "- in 'Tools->Metrics/Debugger->Inputs'.\n"
7376 "- in 'Tools->Debug Log->IO'.");
7377 if (inputs_opened)
7378 {
7379 if (ImGui::IsMousePosValid())
7380 ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
7381 else
7382 ImGui::Text("Mouse pos: <INVALID>");
7383 ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
7384 ImGui::Text("Mouse down:");
7385 for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDown(i)) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
7386 ImGui::Text("Mouse wheel: %.1f", io.MouseWheel);
7387
7388 // We iterate both legacy native range and named ImGuiKey ranges. This is a little unusual/odd but this allows
7389 // displaying the data for old/new backends.
7390 // User code should never have to go through such hoops!
7391 // You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
7392 struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
7393 ImGuiKey start_key = ImGuiKey_NamedKey_BEGIN;
7394 ImGui::Text("Keys down:"); for (ImGuiKey key = start_key; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !ImGui::IsKeyDown(key)) continue; ImGui::SameLine(); ImGui::Text((key < ImGuiKey_NamedKey_BEGIN) ? "\"%s\"" : "\"%s\" %d", ImGui::GetKeyName(key), key); }
7395 ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
7396 ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
7397
7398 ImGui::TreePop();
7399 }
7400
7401 // Display ImGuiIO output flags
7402 IMGUI_DEMO_MARKER("Inputs & Focus/Outputs");
7403 ImGui::SetNextItemOpen(true, ImGuiCond_Once);
7404 bool outputs_opened = ImGui::TreeNode("Outputs");
7405 ImGui::SameLine();
7406 HelpMarker(
7407 "The value of io.WantCaptureMouse and io.WantCaptureKeyboard are normally set by Dear ImGui "
7408 "to instruct your application of how to route inputs. Typically, when a value is true, it means "
7409 "Dear ImGui wants the corresponding inputs and we expect the underlying application to ignore them.\n\n"
7410 "The most typical case is: when hovering a window, Dear ImGui set io.WantCaptureMouse to true, "
7411 "and underlying application should ignore mouse inputs (in practice there are many and more subtle "
7412 "rules leading to how those flags are set).");
7413 if (outputs_opened)
7414 {
7415 ImGui::Text("io.WantCaptureMouse: %d", io.WantCaptureMouse);
7416 ImGui::Text("io.WantCaptureMouseUnlessPopupClose: %d", io.WantCaptureMouseUnlessPopupClose);
7417 ImGui::Text("io.WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
7418 ImGui::Text("io.WantTextInput: %d", io.WantTextInput);
7419 ImGui::Text("io.WantSetMousePos: %d", io.WantSetMousePos);
7420 ImGui::Text("io.NavActive: %d, io.NavVisible: %d", io.NavActive, io.NavVisible);
7421
7422 IMGUI_DEMO_MARKER("Inputs & Focus/Outputs/WantCapture override");
7423 if (ImGui::TreeNode("WantCapture override"))
7424 {
7425 HelpMarker(
7426 "Hovering the colored canvas will override io.WantCaptureXXX fields.\n"
7427 "Notice how normally (when set to none), the value of io.WantCaptureKeyboard would be false when hovering "
7428 "and true when clicking.");
7429 static int capture_override_mouse = -1;
7430 static int capture_override_keyboard = -1;
7431 const char* capture_override_desc[] = { "None", "Set to false", "Set to true" };
7432 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15);
7433 ImGui::SliderInt("SetNextFrameWantCaptureMouse() on hover", &capture_override_mouse, -1, +1, capture_override_desc[capture_override_mouse + 1], ImGuiSliderFlags_AlwaysClamp);
7434 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15);
7435 ImGui::SliderInt("SetNextFrameWantCaptureKeyboard() on hover", &capture_override_keyboard, -1, +1, capture_override_desc[capture_override_keyboard + 1], ImGuiSliderFlags_AlwaysClamp);
7436
7437 ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(128.0f, 96.0f)); // Dummy item
7438 if (ImGui::IsItemHovered() && capture_override_mouse != -1)
7439 ImGui::SetNextFrameWantCaptureMouse(capture_override_mouse == 1);
7440 if (ImGui::IsItemHovered() && capture_override_keyboard != -1)
7441 ImGui::SetNextFrameWantCaptureKeyboard(capture_override_keyboard == 1);
7442
7443 ImGui::TreePop();
7444 }
7445 ImGui::TreePop();
7446 }
7447
7448 // Demonstrate using Shortcut() and Routing Policies.
7449 // The general flow is:
7450 // - Code interested in a chord (e.g. "Ctrl+A") declares their intent.
7451 // - Multiple locations may be interested in same chord! Routing helps find a winner.
7452 // - Every frame, we resolve all claims and assign one owner if the modifiers are matching.
7453 // - The lower-level function is 'bool SetShortcutRouting()', returns true when caller got the route.
7454 // - Most of the times, SetShortcutRouting() is not called directly. User mostly calls Shortcut() with routing flags.
7455 // - If you call Shortcut() WITHOUT any routing option, it uses ImGuiInputFlags_RouteFocused.
7456 // TL;DR: Most uses will simply be:
7457 // - Shortcut(ImGuiMod_Ctrl | ImGuiKey_A); // Use ImGuiInputFlags_RouteFocused policy.
7458 IMGUI_DEMO_MARKER("Inputs & Focus/Shortcuts");
7459 if (ImGui::TreeNode("Shortcuts"))
7460 {
7461 static ImGuiInputFlags route_options = ImGuiInputFlags_Repeat;
7462 static ImGuiInputFlags route_type = ImGuiInputFlags_RouteFocused;
7463 ImGui::CheckboxFlags("ImGuiInputFlags_Repeat", &route_options, ImGuiInputFlags_Repeat);
7464 ImGui::RadioButton("ImGuiInputFlags_RouteActive", &route_type, ImGuiInputFlags_RouteActive);
7465 ImGui::RadioButton("ImGuiInputFlags_RouteFocused (default)", &route_type, ImGuiInputFlags_RouteFocused);
7466 ImGui::RadioButton("ImGuiInputFlags_RouteGlobal", &route_type, ImGuiInputFlags_RouteGlobal);
7467 ImGui::Indent();
7468 ImGui::BeginDisabled(route_type != ImGuiInputFlags_RouteGlobal);
7469 ImGui::CheckboxFlags("ImGuiInputFlags_RouteOverFocused", &route_options, ImGuiInputFlags_RouteOverFocused);
7470 ImGui::CheckboxFlags("ImGuiInputFlags_RouteOverActive", &route_options, ImGuiInputFlags_RouteOverActive);
7471 ImGui::CheckboxFlags("ImGuiInputFlags_RouteUnlessBgFocused", &route_options, ImGuiInputFlags_RouteUnlessBgFocused);
7472 ImGui::EndDisabled();
7473 ImGui::Unindent();
7474 ImGui::RadioButton("ImGuiInputFlags_RouteAlways", &route_type, ImGuiInputFlags_RouteAlways);
7475 ImGuiInputFlags flags = route_type | route_options; // Merged flags
7476 if (route_type != ImGuiInputFlags_RouteGlobal)
7477 flags &= ~(ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused);
7478
7479 ImGui::SeparatorText("Using SetNextItemShortcut()");
7480 ImGui::Text("Ctrl+S");
7481 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_S, flags | ImGuiInputFlags_Tooltip);
7482 ImGui::Button("Save");
7483 ImGui::Text("Alt+F");
7484 ImGui::SetNextItemShortcut(ImGuiMod_Alt | ImGuiKey_F, flags | ImGuiInputFlags_Tooltip);
7485 static float f = 0.5f;
7486 ImGui::SliderFloat("Factor", &f, 0.0f, 1.0f);
7487
7488 ImGui::SeparatorText("Using Shortcut()");
7489 const float line_height = ImGui::GetTextLineHeightWithSpacing();
7490 const ImGuiKeyChord key_chord = ImGuiMod_Ctrl | ImGuiKey_A;
7491
7492 ImGui::Text("Ctrl+A");
7493 ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "...");
7494
7495 ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(1.0f, 0.0f, 1.0f, 0.1f));
7496
7497 ImGui::BeginChild("WindowA", ImVec2(-FLT_MIN, line_height * 14), true);
7498 ImGui::Text("Press CTRL+A and see who receives it!");
7499 ImGui::Separator();
7500
7501 // 1: Window polling for CTRL+A
7502 ImGui::Text("(in WindowA)");
7503 ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "...");
7504
7505 // 2: InputText also polling for CTRL+A: it always uses _RouteFocused internally (gets priority when active)
7506 // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h)
7507 //char str[16] = "Press CTRL+A";
7508 //ImGui::Spacing();
7509 //ImGui::InputText("InputTextB", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly);
7510 //ImGuiID item_id = ImGui::GetItemID();
7511 //ImGui::SameLine(); HelpMarker("Internal widgets always use _RouteFocused");
7512 //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, item_id) ? "PRESSED" : "...");
7513
7514 // 3: Dummy child is not claiming the route: focusing them shouldn't steal route away from WindowA
7515 ImGui::BeginChild("ChildD", ImVec2(-FLT_MIN, line_height * 4), true);
7516 ImGui::Text("(in ChildD: not using same Shortcut)");
7517 ImGui::Text("IsWindowFocused: %d", ImGui::IsWindowFocused());
7518 ImGui::EndChild();
7519
7520 // 4: Child window polling for CTRL+A. It is deeper than WindowA and gets priority when focused.
7521 ImGui::BeginChild("ChildE", ImVec2(-FLT_MIN, line_height * 4), true);
7522 ImGui::Text("(in ChildE: using same Shortcut)");
7523 ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "...");
7524 ImGui::EndChild();
7525
7526 // 5: In a popup
7527 if (ImGui::Button("Open Popup"))
7528 ImGui::OpenPopup("PopupF");
7529 if (ImGui::BeginPopup("PopupF"))
7530 {
7531 ImGui::Text("(in PopupF)");
7532 ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags) ? "PRESSED" : "...");
7533 // (Commmented because the owner-aware version of Shortcut() is still in imgui_internal.h)
7534 //ImGui::InputText("InputTextG", str, IM_ARRAYSIZE(str), ImGuiInputTextFlags_ReadOnly);
7535 //ImGui::Text("IsWindowFocused: %d, Shortcut: %s", ImGui::IsWindowFocused(), ImGui::Shortcut(key_chord, flags, ImGui::GetItemID()) ? "PRESSED" : "...");
7536 ImGui::EndPopup();
7537 }
7538 ImGui::EndChild();
7539 ImGui::PopStyleColor();
7540
7541 ImGui::TreePop();
7542 }
7543
7544 // Display mouse cursors
7545 IMGUI_DEMO_MARKER("Inputs & Focus/Mouse Cursors");
7546 if (ImGui::TreeNode("Mouse Cursors"))
7547 {
7548 const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" };
7549 IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);
7550
7551 ImGuiMouseCursor current = ImGui::GetMouseCursor();
7552 const char* cursor_name = (current >= ImGuiMouseCursor_Arrow) && (current < ImGuiMouseCursor_COUNT) ? mouse_cursors_names[current] : "N/A";
7553 ImGui::Text("Current mouse cursor = %d: %s", current, cursor_name);
7554 ImGui::BeginDisabled(true);
7555 ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", &io.BackendFlags, ImGuiBackendFlags_HasMouseCursors);
7556 ImGui::EndDisabled();
7557
7558 ImGui::Text("Hover to see mouse cursors:");
7559 ImGui::SameLine(); HelpMarker(
7560 "Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. "
7561 "If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, "
7562 "otherwise your backend needs to handle it.");
7563 for (int i = 0; i < ImGuiMouseCursor_COUNT; i++)
7564 {
7565 char label[32];
7566 sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
7567 ImGui::Bullet(); ImGui::Selectable(label, false);
7568 if (ImGui::IsItemHovered())
7569 ImGui::SetMouseCursor(i);
7570 }
7571 ImGui::TreePop();
7572 }
7573
7574 IMGUI_DEMO_MARKER("Inputs & Focus/Tabbing");
7575 if (ImGui::TreeNode("Tabbing"))
7576 {
7577 ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
7578 static char buf[32] = "hello";
7579 ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
7580 ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
7581 ImGui::InputText("3", buf, IM_ARRAYSIZE(buf));
7582 ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true);
7583 ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf));
7584 ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab.");
7585 ImGui::PopItemFlag();
7586 ImGui::InputText("5", buf, IM_ARRAYSIZE(buf));
7587 ImGui::TreePop();
7588 }
7589
7590 IMGUI_DEMO_MARKER("Inputs & Focus/Focus from code");
7591 if (ImGui::TreeNode("Focus from code"))
7592 {
7593 bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine();
7594 bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine();
7595 bool focus_3 = ImGui::Button("Focus on 3");
7596 int has_focus = 0;
7597 static char buf[128] = "click on a button to set focus";
7598
7599 if (focus_1) ImGui::SetKeyboardFocusHere();
7600 ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
7601 if (ImGui::IsItemActive()) has_focus = 1;
7602
7603 if (focus_2) ImGui::SetKeyboardFocusHere();
7604 ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
7605 if (ImGui::IsItemActive()) has_focus = 2;
7606
7607 ImGui::PushItemFlag(ImGuiItemFlags_NoTabStop, true);
7608 if (focus_3) ImGui::SetKeyboardFocusHere();
7609 ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
7610 if (ImGui::IsItemActive()) has_focus = 3;
7611 ImGui::SameLine(); HelpMarker("Item won't be cycled through when using TAB or Shift+Tab.");
7612 ImGui::PopItemFlag();
7613
7614 if (has_focus)
7615 ImGui::Text("Item with focus: %d", has_focus);
7616 else
7617 ImGui::Text("Item with focus: <none>");
7618
7619 // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item
7620 static float f3[3] = { 0.0f, 0.0f, 0.0f };
7621 int focus_ahead = -1;
7622 if (ImGui::Button("Focus on X")) { focus_ahead = 0; } ImGui::SameLine();
7623 if (ImGui::Button("Focus on Y")) { focus_ahead = 1; } ImGui::SameLine();
7624 if (ImGui::Button("Focus on Z")) { focus_ahead = 2; }
7625 if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead);
7626 ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f);
7627
7628 ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code.");
7629 ImGui::TreePop();
7630 }
7631
7632 IMGUI_DEMO_MARKER("Inputs & Focus/Dragging");
7633 if (ImGui::TreeNode("Dragging"))
7634 {
7635 ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget.");
7636 for (int button = 0; button < 3; button++)
7637 {
7638 ImGui::Text("IsMouseDragging(%d):", button);
7639 ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button));
7640 ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f));
7641 ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f));
7642 }
7643
7644 ImGui::Button("Drag Me");
7645 if (ImGui::IsItemActive())
7646 ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor
7647
7648 // Drag operations gets "unlocked" when the mouse has moved past a certain threshold
7649 // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher
7650 // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta().
7651 ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);
7652 ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);
7653 ImVec2 mouse_delta = io.MouseDelta;
7654 ImGui::Text("GetMouseDragDelta(0):");
7655 ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y);
7656 ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y);
7657 ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y);
7658 ImGui::TreePop();
7659 }
7660 }
7661 }
7662
7663 //-----------------------------------------------------------------------------
7664 // [SECTION] About Window / ShowAboutWindow()
7665 // Access from Dear ImGui Demo -> Tools -> About
7666 //-----------------------------------------------------------------------------
7667
7668 void ImGui::ShowAboutWindow(bool* p_open)
7669 {
7670 if (!ImGui::Begin("About Dear ImGui", p_open, ImGuiWindowFlags_AlwaysAutoResize))
7671 {
7672 ImGui::End();
7673 return;
7674 }
7675 IMGUI_DEMO_MARKER("Tools/About Dear ImGui");
7676 ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
7677
7678 ImGui::TextLinkOpenURL("Homepage", "https://github.com/ocornut/imgui");
7679 ImGui::SameLine();
7680 ImGui::TextLinkOpenURL("FAQ", "https://github.com/ocornut/imgui/blob/master/docs/FAQ.md");
7681 ImGui::SameLine();
7682 ImGui::TextLinkOpenURL("Wiki", "https://github.com/ocornut/imgui/wiki");
7683 ImGui::SameLine();
7684 ImGui::TextLinkOpenURL("Releases", "https://github.com/ocornut/imgui/releases");
7685 ImGui::SameLine();
7686 ImGui::TextLinkOpenURL("Funding", "https://github.com/ocornut/imgui/wiki/Funding");
7687
7688 ImGui::Separator();
7689 ImGui::Text("By Omar Cornut and all Dear ImGui contributors.");
7690 ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
7691 ImGui::Text("If your company uses this, please consider funding the project.");
7692
7693 static bool show_config_info = false;
7694 ImGui::Checkbox("Config/Build Information", &show_config_info);
7695 if (show_config_info)
7696 {
7697 ImGuiIO& io = ImGui::GetIO();
7698 ImGuiStyle& style = ImGui::GetStyle();
7699
7700 bool copy_to_clipboard = ImGui::Button("Copy to clipboard");
7701 ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18);
7702 ImGui::BeginChild(ImGui::GetID("cfg_infos"), child_size, ImGuiChildFlags_FrameStyle);
7703 if (copy_to_clipboard)
7704 {
7705 ImGui::LogToClipboard();
7706 ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub
7707 }
7708
7709 ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
7710 ImGui::Separator();
7711 ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert));
7712 ImGui::Text("define: __cplusplus=%d", (int)__cplusplus);
7713 #ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
7714 ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS");
7715 #endif
7716 #ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
7717 ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS");
7718 #endif
7719 #ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
7720 ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS");
7721 #endif
7722 #ifdef IMGUI_DISABLE_WIN32_FUNCTIONS
7723 ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS");
7724 #endif
7725 #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
7726 ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS");
7727 #endif
7728 #ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
7729 ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS");
7730 #endif
7731 #ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
7732 ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS");
7733 #endif
7734 #ifdef IMGUI_DISABLE_FILE_FUNCTIONS
7735 ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS");
7736 #endif
7737 #ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS
7738 ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS");
7739 #endif
7740 #ifdef IMGUI_USE_BGRA_PACKED_COLOR
7741 ImGui::Text("define: IMGUI_USE_BGRA_PACKED_COLOR");
7742 #endif
7743 #ifdef _WIN32
7744 ImGui::Text("define: _WIN32");
7745 #endif
7746 #ifdef _WIN64
7747 ImGui::Text("define: _WIN64");
7748 #endif
7749 #ifdef __linux__
7750 ImGui::Text("define: __linux__");
7751 #endif
7752 #ifdef __APPLE__
7753 ImGui::Text("define: __APPLE__");
7754 #endif
7755 #ifdef _MSC_VER
7756 ImGui::Text("define: _MSC_VER=%d", _MSC_VER);
7757 #endif
7758 #ifdef _MSVC_LANG
7759 ImGui::Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG);
7760 #endif
7761 #ifdef __MINGW32__
7762 ImGui::Text("define: __MINGW32__");
7763 #endif
7764 #ifdef __MINGW64__
7765 ImGui::Text("define: __MINGW64__");
7766 #endif
7767 #ifdef __GNUC__
7768 ImGui::Text("define: __GNUC__=%d", (int)__GNUC__);
7769 #endif
7770 #ifdef __clang_version__
7771 ImGui::Text("define: __clang_version__=%s", __clang_version__);
7772 #endif
7773 #ifdef __EMSCRIPTEN__
7774 ImGui::Text("define: __EMSCRIPTEN__");
7775 ImGui::Text("Emscripten: %d.%d.%d", __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__);
7776 #endif
7777 ImGui::Separator();
7778 ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL");
7779 ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL");
7780 ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags);
7781 if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard");
7782 if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad");
7783 if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse");
7784 if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange");
7785 if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard) ImGui::Text(" NoKeyboard");
7786 if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor");
7787 if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors");
7788 if (io.ConfigNavMoveSetMousePos) ImGui::Text("io.ConfigNavMoveSetMousePos");
7789 if (io.ConfigNavCaptureKeyboard) ImGui::Text("io.ConfigNavCaptureKeyboard");
7790 if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink");
7791 if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges");
7792 if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly");
7793 if (io.ConfigMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigMemoryCompactTimer = %.1f", io.ConfigMemoryCompactTimer);
7794 ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags);
7795 if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad");
7796 if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors");
7797 if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos");
7798 if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset");
7799 ImGui::Separator();
7800 ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight);
7801 ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y);
7802 ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
7803 ImGui::Separator();
7804 ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y);
7805 ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize);
7806 ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y);
7807 ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding);
7808 ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize);
7809 ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y);
7810 ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y);
7811
7812 if (copy_to_clipboard)
7813 {
7814 ImGui::LogText("\n```\n");
7815 ImGui::LogFinish();
7816 }
7817 ImGui::EndChild();
7818 }
7819 ImGui::End();
7820 }
7821
7822 //-----------------------------------------------------------------------------
7823 // [SECTION] Style Editor / ShowStyleEditor()
7824 //-----------------------------------------------------------------------------
7825 // - ShowFontSelector()
7826 // - ShowStyleSelector()
7827 // - ShowStyleEditor()
7828 //-----------------------------------------------------------------------------
7829
7830 // Forward declare ShowFontAtlas() which isn't worth putting in public API yet
7831 namespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); }
7832
7833 // Demo helper function to select among loaded fonts.
7834 // Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.
7835 void ImGui::ShowFontSelector(const char* label)
7836 {
7837 ImGuiIO& io = ImGui::GetIO();
7838 ImFont* font_current = ImGui::GetFont();
7839 if (ImGui::BeginCombo(label, font_current->GetDebugName()))
7840 {
7841 for (ImFont* font : io.Fonts->Fonts)
7842 {
7843 ImGui::PushID((void*)font);
7844 if (ImGui::Selectable(font->GetDebugName(), font == font_current))
7845 io.FontDefault = font;
7846 ImGui::PopID();
7847 }
7848 ImGui::EndCombo();
7849 }
7850 ImGui::SameLine();
7851 HelpMarker(
7852 "- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n"
7853 "- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
7854 "- Read FAQ and docs/FONTS.md for more details.\n"
7855 "- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
7856 }
7857
7858 // Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.
7859 // Here we use the simplified Combo() api that packs items into a single literal string.
7860 // Useful for quick combo boxes where the choices are known locally.
7861 bool ImGui::ShowStyleSelector(const char* label)
7862 {
7863 static int style_idx = -1;
7864 if (ImGui::Combo(label, &style_idx, "Dark\0Light\0Classic\0"))
7865 {
7866 switch (style_idx)
7867 {
7868 case 0: ImGui::StyleColorsDark(); break;
7869 case 1: ImGui::StyleColorsLight(); break;
7870 case 2: ImGui::StyleColorsClassic(); break;
7871 }
7872 return true;
7873 }
7874 return false;
7875 }
7876
7877 void ImGui::ShowStyleEditor(ImGuiStyle* ref)
7878 {
7879 IMGUI_DEMO_MARKER("Tools/Style Editor");
7880 // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to
7881 // (without a reference style pointer, we will use one compared locally as a reference)
7882 ImGuiStyle& style = ImGui::GetStyle();
7883 static ImGuiStyle ref_saved_style;
7884
7885 // Default to using internal storage as reference
7886 static bool init = true;
7887 if (init && ref == NULL)
7888 ref_saved_style = style;
7889 init = false;
7890 if (ref == NULL)
7891 ref = &ref_saved_style;
7892
7893 ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f);
7894
7895 if (ImGui::ShowStyleSelector("Colors##Selector"))
7896 ref_saved_style = style;
7897 ImGui::ShowFontSelector("Fonts##Selector");
7898
7899 // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f)
7900 if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"))
7901 style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding
7902 { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } }
7903 ImGui::SameLine();
7904 { bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } }
7905 ImGui::SameLine();
7906 { bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } }
7907
7908 // Save/Revert button
7909 if (ImGui::Button("Save Ref"))
7910 *ref = ref_saved_style = style;
7911 ImGui::SameLine();
7912 if (ImGui::Button("Revert Ref"))
7913 style = *ref;
7914 ImGui::SameLine();
7915 HelpMarker(
7916 "Save/Revert in local non-persistent storage. Default Colors definition are not affected. "
7917 "Use \"Export\" below to save them somewhere.");
7918
7919 ImGui::Separator();
7920
7921 if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None))
7922 {
7923 if (ImGui::BeginTabItem("Sizes"))
7924 {
7925 ImGui::SeparatorText("Main");
7926 ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
7927 ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
7928 ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
7929 ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
7930 ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
7931 ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f");
7932 ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f");
7933 ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f");
7934
7935 ImGui::SeparatorText("Borders");
7936 ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f");
7937 ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f");
7938 ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f");
7939 ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f");
7940 ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f");
7941 ImGui::SliderFloat("TabBarBorderSize", &style.TabBarBorderSize, 0.0f, 2.0f, "%.0f");
7942 ImGui::SliderFloat("TabBarOverlineSize", &style.TabBarOverlineSize, 0.0f, 2.0f, "%.0f");
7943 ImGui::SameLine(); HelpMarker("Overline is only drawn over the selected tab when ImGuiTabBarFlags_DrawSelectedOverline is set.");
7944
7945 ImGui::SeparatorText("Rounding");
7946 ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f");
7947 ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f");
7948 ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f");
7949 ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f");
7950 ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f");
7951 ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f");
7952 ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f");
7953
7954 ImGui::SeparatorText("Tables");
7955 ImGui::SliderFloat2("CellPadding", (float*)&style.CellPadding, 0.0f, 20.0f, "%.0f");
7956 ImGui::SliderAngle("TableAngledHeadersAngle", &style.TableAngledHeadersAngle, -50.0f, +50.0f);
7957 ImGui::SliderFloat2("TableAngledHeadersTextAlign", (float*)&style.TableAngledHeadersTextAlign, 0.0f, 1.0f, "%.2f");
7958
7959 ImGui::SeparatorText("Widgets");
7960 ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f");
7961 int window_menu_button_position = style.WindowMenuButtonPosition + 1;
7962 if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0"))
7963 style.WindowMenuButtonPosition = (ImGuiDir)(window_menu_button_position - 1);
7964 ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0");
7965 ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f");
7966 ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content.");
7967 ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f");
7968 ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content.");
7969 ImGui::SliderFloat("SeparatorTextBorderSize", &style.SeparatorTextBorderSize, 0.0f, 10.0f, "%.0f");
7970 ImGui::SliderFloat2("SeparatorTextAlign", (float*)&style.SeparatorTextAlign, 0.0f, 1.0f, "%.2f");
7971 ImGui::SliderFloat2("SeparatorTextPadding", (float*)&style.SeparatorTextPadding, 0.0f, 40.0f, "%.0f");
7972 ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f");
7973
7974 ImGui::SeparatorText("Tooltips");
7975 for (int n = 0; n < 2; n++)
7976 if (ImGui::TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav"))
7977 {
7978 ImGuiHoveredFlags* p = (n == 0) ? &style.HoverFlagsForTooltipMouse : &style.HoverFlagsForTooltipNav;
7979 ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNone", p, ImGuiHoveredFlags_DelayNone);
7980 ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayShort", p, ImGuiHoveredFlags_DelayShort);
7981 ImGui::CheckboxFlags("ImGuiHoveredFlags_DelayNormal", p, ImGuiHoveredFlags_DelayNormal);
7982 ImGui::CheckboxFlags("ImGuiHoveredFlags_Stationary", p, ImGuiHoveredFlags_Stationary);
7983 ImGui::CheckboxFlags("ImGuiHoveredFlags_NoSharedDelay", p, ImGuiHoveredFlags_NoSharedDelay);
7984 ImGui::TreePop();
7985 }
7986
7987 ImGui::SeparatorText("Misc");
7988 ImGui::SliderFloat2("DisplayWindowPadding", (float*)&style.DisplayWindowPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Apply to regular windows: amount which we enforce to keep visible when moving near edges of your screen.");
7989 ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f"); ImGui::SameLine(); HelpMarker("Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).");
7990
7991 ImGui::EndTabItem();
7992 }
7993
7994 if (ImGui::BeginTabItem("Colors"))
7995 {
7996 static int output_dest = 0;
7997 static bool output_only_modified = true;
7998 if (ImGui::Button("Export"))
7999 {
8000 if (output_dest == 0)
8001 ImGui::LogToClipboard();
8002 else
8003 ImGui::LogToTTY();
8004 ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE);
8005 for (int i = 0; i < ImGuiCol_COUNT; i++)
8006 {
8007 const ImVec4& col = style.Colors[i];
8008 const char* name = ImGui::GetStyleColorName(i);
8009 if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0)
8010 ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE,
8011 name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
8012 }
8013 ImGui::LogFinish();
8014 }
8015 ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0");
8016 ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified);
8017
8018 static ImGuiTextFilter filter;
8019 filter.Draw("Filter colors", ImGui::GetFontSize() * 16);
8020
8021 static ImGuiColorEditFlags alpha_flags = 0;
8022 if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();
8023 if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();
8024 if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();
8025 HelpMarker(
8026 "In the color list:\n"
8027 "Left-click on color square to open color picker,\n"
8028 "Right-click to open edit options menu.");
8029
8030 ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX));
8031 ImGui::BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
8032 ImGui::PushItemWidth(ImGui::GetFontSize() * -12);
8033 for (int i = 0; i < ImGuiCol_COUNT; i++)
8034 {
8035 const char* name = ImGui::GetStyleColorName(i);
8036 if (!filter.PassFilter(name))
8037 continue;
8038 ImGui::PushID(i);
8039 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
8040 if (ImGui::Button("?"))
8041 ImGui::DebugFlashStyleColor((ImGuiCol)i);
8042 ImGui::SetItemTooltip("Flash given color to identify places where it is used.");
8043 ImGui::SameLine();
8044 #endif
8045 ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
8046 if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)
8047 {
8048 // Tips: in a real user application, you may want to merge and use an icon font into the main font,
8049 // so instead of "Save"/"Revert" you'd use icons!
8050 // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient!
8051 ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; }
8052 ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; }
8053 }
8054 ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
8055 ImGui::TextUnformatted(name);
8056 ImGui::PopID();
8057 }
8058 ImGui::PopItemWidth();
8059 ImGui::EndChild();
8060
8061 ImGui::EndTabItem();
8062 }
8063
8064 if (ImGui::BeginTabItem("Fonts"))
8065 {
8066 ImGuiIO& io = ImGui::GetIO();
8067 ImFontAtlas* atlas = io.Fonts;
8068 HelpMarker("Read FAQ and docs/FONTS.md for details on font loading.");
8069 ImGui::ShowFontAtlas(atlas);
8070
8071 // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.
8072 // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).
8073 const float MIN_SCALE = 0.3f;
8074 const float MAX_SCALE = 2.0f;
8075 HelpMarker(
8076 "Those are old settings provided for convenience.\n"
8077 "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, "
8078 "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n"
8079 "Using those settings here will give you poor quality results.");
8080 static float window_scale = 1.0f;
8081 ImGui::PushItemWidth(ImGui::GetFontSize() * 8);
8082 if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window
8083 ImGui::SetWindowFontScale(window_scale);
8084 ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything
8085 ImGui::PopItemWidth();
8086
8087 ImGui::EndTabItem();
8088 }
8089
8090 if (ImGui::BeginTabItem("Rendering"))
8091 {
8092 ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
8093 ImGui::SameLine();
8094 HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
8095
8096 ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex);
8097 ImGui::SameLine();
8098 HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering).");
8099
8100 ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
8101 ImGui::PushItemWidth(ImGui::GetFontSize() * 8);
8102 ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f");
8103 if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f;
8104
8105 // When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles.
8106 ImGui::DragFloat("Circle Tessellation Max Error", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, "%.2f", ImGuiSliderFlags_AlwaysClamp);
8107 const bool show_samples = ImGui::IsItemActive();
8108 if (show_samples)
8109 ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos());
8110 if (show_samples && ImGui::BeginTooltip())
8111 {
8112 ImGui::TextUnformatted("(R = radius, N = approx number of segments)");
8113 ImGui::Spacing();
8114 ImDrawList* draw_list = ImGui::GetWindowDrawList();
8115 const float min_widget_width = ImGui::CalcTextSize("R: MMM\nN: MMM").x;
8116 for (int n = 0; n < 8; n++)
8117 {
8118 const float RAD_MIN = 5.0f;
8119 const float RAD_MAX = 70.0f;
8120 const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f);
8121
8122 ImGui::BeginGroup();
8123
8124 // N is not always exact here due to how PathArcTo() function work internally
8125 ImGui::Text("R: %.f\nN: %d", rad, draw_list->_CalcCircleAutoSegmentCount(rad));
8126
8127 const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f);
8128 const float offset_x = floorf(canvas_width * 0.5f);
8129 const float offset_y = floorf(RAD_MAX);
8130
8131 const ImVec2 p1 = ImGui::GetCursorScreenPos();
8132 draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text));
8133 ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2));
8134
8135 /*
8136 const ImVec2 p2 = ImGui::GetCursorScreenPos();
8137 draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text));
8138 ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2));
8139 */
8140
8141 ImGui::EndGroup();
8142 ImGui::SameLine();
8143 }
8144 ImGui::EndTooltip();
8145 }
8146 ImGui::SameLine();
8147 HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically.");
8148
8149 ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
8150 ImGui::DragFloat("Disabled Alpha", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha).");
8151 ImGui::PopItemWidth();
8152
8153 ImGui::EndTabItem();
8154 }
8155
8156 ImGui::EndTabBar();
8157 }
8158
8159 ImGui::PopItemWidth();
8160 }
8161
8162 //-----------------------------------------------------------------------------
8163 // [SECTION] User Guide / ShowUserGuide()
8164 //-----------------------------------------------------------------------------
8165
8166 void ImGui::ShowUserGuide()
8167 {
8168 ImGuiIO& io = ImGui::GetIO();
8169 ImGui::BulletText("Double-click on title bar to collapse window.");
8170 ImGui::BulletText(
8171 "Click and drag on lower corner to resize window\n"
8172 "(double-click to auto fit window to its contents).");
8173 ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text.");
8174 ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
8175 ImGui::BulletText("CTRL+Tab to select a window.");
8176 if (io.FontAllowUserScaling)
8177 ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
8178 ImGui::BulletText("While inputing text:\n");
8179 ImGui::Indent();
8180 ImGui::BulletText("CTRL+Left/Right to word jump.");
8181 ImGui::BulletText("CTRL+A or double-click to select all.");
8182 ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste.");
8183 ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo.");
8184 ImGui::BulletText("ESCAPE to revert.");
8185 ImGui::Unindent();
8186 ImGui::BulletText("With keyboard navigation enabled:");
8187 ImGui::Indent();
8188 ImGui::BulletText("Arrow keys to navigate.");
8189 ImGui::BulletText("Space to activate a widget.");
8190 ImGui::BulletText("Return to input text into a widget.");
8191 ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window.");
8192 ImGui::BulletText("Alt to jump to the menu layer of a window.");
8193 ImGui::Unindent();
8194 }
8195
8196 //-----------------------------------------------------------------------------
8197 // [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()
8198 //-----------------------------------------------------------------------------
8199 // - ShowExampleAppMainMenuBar()
8200 // - ShowExampleMenuFile()
8201 //-----------------------------------------------------------------------------
8202
8203 // Demonstrate creating a "main" fullscreen menu bar and populating it.
8204 // Note the difference between BeginMainMenuBar() and BeginMenuBar():
8205 // - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!)
8206 // - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it.
8207 static void ShowExampleAppMainMenuBar()
8208 {
8209 if (ImGui::BeginMainMenuBar())
8210 {
8211 if (ImGui::BeginMenu("File"))
8212 {
8213 ShowExampleMenuFile();
8214 ImGui::EndMenu();
8215 }
8216 if (ImGui::BeginMenu("Edit"))
8217 {
8218 if (ImGui::MenuItem("Undo", "CTRL+Z")) {}
8219 if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item
8220 ImGui::Separator();
8221 if (ImGui::MenuItem("Cut", "CTRL+X")) {}
8222 if (ImGui::MenuItem("Copy", "CTRL+C")) {}
8223 if (ImGui::MenuItem("Paste", "CTRL+V")) {}
8224 ImGui::EndMenu();
8225 }
8226 ImGui::EndMainMenuBar();
8227 }
8228 }
8229
8230 // Note that shortcuts are currently provided for display only
8231 // (future version will add explicit flags to BeginMenu() to request processing shortcuts)
8232 static void ShowExampleMenuFile()
8233 {
8234 IMGUI_DEMO_MARKER("Examples/Menu");
8235 ImGui::MenuItem("(demo menu)", NULL, false, false);
8236 if (ImGui::MenuItem("New")) {}
8237 if (ImGui::MenuItem("Open", "Ctrl+O")) {}
8238 if (ImGui::BeginMenu("Open Recent"))
8239 {
8240 ImGui::MenuItem("fish_hat.c");
8241 ImGui::MenuItem("fish_hat.inl");
8242 ImGui::MenuItem("fish_hat.h");
8243 if (ImGui::BeginMenu("More.."))
8244 {
8245 ImGui::MenuItem("Hello");
8246 ImGui::MenuItem("Sailor");
8247 if (ImGui::BeginMenu("Recurse.."))
8248 {
8249 ShowExampleMenuFile();
8250 ImGui::EndMenu();
8251 }
8252 ImGui::EndMenu();
8253 }
8254 ImGui::EndMenu();
8255 }
8256 if (ImGui::MenuItem("Save", "Ctrl+S")) {}
8257 if (ImGui::MenuItem("Save As..")) {}
8258
8259 ImGui::Separator();
8260 IMGUI_DEMO_MARKER("Examples/Menu/Options");
8261 if (ImGui::BeginMenu("Options"))
8262 {
8263 static bool enabled = true;
8264 ImGui::MenuItem("Enabled", "", &enabled);
8265 ImGui::BeginChild("child", ImVec2(0, 60), ImGuiChildFlags_Borders);
8266 for (int i = 0; i < 10; i++)
8267 ImGui::Text("Scrolling Text %d", i);
8268 ImGui::EndChild();
8269 static float f = 0.5f;
8270 static int n = 0;
8271 ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
8272 ImGui::InputFloat("Input", &f, 0.1f);
8273 ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
8274 ImGui::EndMenu();
8275 }
8276
8277 IMGUI_DEMO_MARKER("Examples/Menu/Colors");
8278 if (ImGui::BeginMenu("Colors"))
8279 {
8280 float sz = ImGui::GetTextLineHeight();
8281 for (int i = 0; i < ImGuiCol_COUNT; i++)
8282 {
8283 const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
8284 ImVec2 p = ImGui::GetCursorScreenPos();
8285 ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i));
8286 ImGui::Dummy(ImVec2(sz, sz));
8287 ImGui::SameLine();
8288 ImGui::MenuItem(name);
8289 }
8290 ImGui::EndMenu();
8291 }
8292
8293 // Here we demonstrate appending again to the "Options" menu (which we already created above)
8294 // Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice.
8295 // In a real code-base using it would make senses to use this feature from very different code locations.
8296 if (ImGui::BeginMenu("Options")) // <-- Append!
8297 {
8298 IMGUI_DEMO_MARKER("Examples/Menu/Append to an existing menu");
8299 static bool b = true;
8300 ImGui::Checkbox("SomeOption", &b);
8301 ImGui::EndMenu();
8302 }
8303
8304 if (ImGui::BeginMenu("Disabled", false)) // Disabled
8305 {
8306 IM_ASSERT(0);
8307 }
8308 if (ImGui::MenuItem("Checked", NULL, true)) {}
8309 ImGui::Separator();
8310 if (ImGui::MenuItem("Quit", "Alt+F4")) {}
8311 }
8312
8313 //-----------------------------------------------------------------------------
8314 // [SECTION] Example App: Debug Console / ShowExampleAppConsole()
8315 //-----------------------------------------------------------------------------
8316
8317 // Demonstrate creating a simple console window, with scrolling, filtering, completion and history.
8318 // For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.
8319 struct ExampleAppConsole
8320 {
8321 char InputBuf[256];
8322 ImVector<char*> Items;
8323 ImVector<const char*> Commands;
8324 ImVector<char*> History;
8325 int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
8326 ImGuiTextFilter Filter;
8327 bool AutoScroll;
8328 bool ScrollToBottom;
8329
8330 ExampleAppConsole()
8331 {
8332 IMGUI_DEMO_MARKER("Examples/Console");
8333 ClearLog();
8334 memset(InputBuf, 0, sizeof(InputBuf));
8335 HistoryPos = -1;
8336
8337 // "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
8338 Commands.push_back("HELP");
8339 Commands.push_back("HISTORY");
8340 Commands.push_back("CLEAR");
8341 Commands.push_back("CLASSIFY");
8342 AutoScroll = true;
8343 ScrollToBottom = false;
8344 AddLog("Welcome to Dear ImGui!");
8345 }
8346 ~ExampleAppConsole()
8347 {
8348 ClearLog();
8349 for (int i = 0; i < History.Size; i++)
8350 ImGui::MemFree(History[i]);
8351 }
8352
8353 // Portable helpers
8354 static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; }
8355 static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; }
8356 static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = ImGui::MemAlloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); }
8357 static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; }
8358
8359 void ClearLog()
8360 {
8361 for (int i = 0; i < Items.Size; i++)
8362 ImGui::MemFree(Items[i]);
8363 Items.clear();
8364 }
8365
8366 void AddLog(const char* fmt, ...) IM_FMTARGS(2)
8367 {
8368 // FIXME-OPT
8369 char buf[1024];
8370 va_list args;
8371 va_start(args, fmt);
8372 vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
8373 buf[IM_ARRAYSIZE(buf)-1] = 0;
8374 va_end(args);
8375 Items.push_back(Strdup(buf));
8376 }
8377
8378 void Draw(const char* title, bool* p_open)
8379 {
8380 ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
8381 if (!ImGui::Begin(title, p_open))
8382 {
8383 ImGui::End();
8384 return;
8385 }
8386
8387 // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
8388 // So e.g. IsItemHovered() will return true when hovering the title bar.
8389 // Here we create a context menu only available from the title bar.
8390 if (ImGui::BeginPopupContextItem())
8391 {
8392 if (ImGui::MenuItem("Close Console"))
8393 *p_open = false;
8394 ImGui::EndPopup();
8395 }
8396
8397 ImGui::TextWrapped(
8398 "This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate "
8399 "implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
8400 ImGui::TextWrapped("Enter 'HELP' for help.");
8401
8402 // TODO: display items starting from the bottom
8403
8404 if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); }
8405 ImGui::SameLine();
8406 if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); }
8407 ImGui::SameLine();
8408 if (ImGui::SmallButton("Clear")) { ClearLog(); }
8409 ImGui::SameLine();
8410 bool copy_to_clipboard = ImGui::SmallButton("Copy");
8411 //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
8412
8413 ImGui::Separator();
8414
8415 // Options menu
8416 if (ImGui::BeginPopup("Options"))
8417 {
8418 ImGui::Checkbox("Auto-scroll", &AutoScroll);
8419 ImGui::EndPopup();
8420 }
8421
8422 // Options, Filter
8423 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_O, ImGuiInputFlags_Tooltip);
8424 if (ImGui::Button("Options"))
8425 ImGui::OpenPopup("Options");
8426 ImGui::SameLine();
8427 Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
8428 ImGui::Separator();
8429
8430 // Reserve enough left-over height for 1 separator + 1 input text
8431 const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
8432 if (ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_HorizontalScrollbar))
8433 {
8434 if (ImGui::BeginPopupContextWindow())
8435 {
8436 if (ImGui::Selectable("Clear")) ClearLog();
8437 ImGui::EndPopup();
8438 }
8439
8440 // Display every line as a separate entry so we can change their color or add custom widgets.
8441 // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
8442 // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
8443 // to only process visible items. The clipper will automatically measure the height of your first item and then
8444 // "seek" to display only items in the visible area.
8445 // To use the clipper we can replace your standard loop:
8446 // for (int i = 0; i < Items.Size; i++)
8447 // With:
8448 // ImGuiListClipper clipper;
8449 // clipper.Begin(Items.Size);
8450 // while (clipper.Step())
8451 // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
8452 // - That your items are evenly spaced (same height)
8453 // - That you have cheap random access to your elements (you can access them given their index,
8454 // without processing all the ones before)
8455 // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
8456 // We would need random-access on the post-filtered list.
8457 // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
8458 // or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
8459 // and appending newly elements as they are inserted. This is left as a task to the user until we can manage
8460 // to improve this example code!
8461 // If your items are of variable height:
8462 // - Split them into same height items would be simpler and facilitate random-seeking into your list.
8463 // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
8464 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
8465 if (copy_to_clipboard)
8466 ImGui::LogToClipboard();
8467 for (const char* item : Items)
8468 {
8469 if (!Filter.PassFilter(item))
8470 continue;
8471
8472 // Normally you would store more information in your item than just a string.
8473 // (e.g. make Items[] an array of structure, store color/type etc.)
8474 ImVec4 color;
8475 bool has_color = false;
8476 if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; }
8477 else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; }
8478 if (has_color)
8479 ImGui::PushStyleColor(ImGuiCol_Text, color);
8480 ImGui::TextUnformatted(item);
8481 if (has_color)
8482 ImGui::PopStyleColor();
8483 }
8484 if (copy_to_clipboard)
8485 ImGui::LogFinish();
8486
8487 // Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame.
8488 // Using a scrollbar or mouse-wheel will take away from the bottom edge.
8489 if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()))
8490 ImGui::SetScrollHereY(1.0f);
8491 ScrollToBottom = false;
8492
8493 ImGui::PopStyleVar();
8494 }
8495 ImGui::EndChild();
8496 ImGui::Separator();
8497
8498 // Command-line
8499 bool reclaim_focus = false;
8500 ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_EscapeClearsAll | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;
8501 if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this))
8502 {
8503 char* s = InputBuf;
8504 Strtrim(s);
8505 if (s[0])
8506 ExecCommand(s);
8507 strcpy(s, "");
8508 reclaim_focus = true;
8509 }
8510
8511 // Auto-focus on window apparition
8512 ImGui::SetItemDefaultFocus();
8513 if (reclaim_focus)
8514 ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
8515
8516 ImGui::End();
8517 }
8518
8519 void ExecCommand(const char* command_line)
8520 {
8521 AddLog("# %s\n", command_line);
8522
8523 // Insert into history. First find match and delete it so it can be pushed to the back.
8524 // This isn't trying to be smart or optimal.
8525 HistoryPos = -1;
8526 for (int i = History.Size - 1; i >= 0; i--)
8527 if (Stricmp(History[i], command_line) == 0)
8528 {
8529 ImGui::MemFree(History[i]);
8530 History.erase(History.begin() + i);
8531 break;
8532 }
8533 History.push_back(Strdup(command_line));
8534
8535 // Process command
8536 if (Stricmp(command_line, "CLEAR") == 0)
8537 {
8538 ClearLog();
8539 }
8540 else if (Stricmp(command_line, "HELP") == 0)
8541 {
8542 AddLog("Commands:");
8543 for (int i = 0; i < Commands.Size; i++)
8544 AddLog("- %s", Commands[i]);
8545 }
8546 else if (Stricmp(command_line, "HISTORY") == 0)
8547 {
8548 int first = History.Size - 10;
8549 for (int i = first > 0 ? first : 0; i < History.Size; i++)
8550 AddLog("%3d: %s\n", i, History[i]);
8551 }
8552 else
8553 {
8554 AddLog("Unknown command: '%s'\n", command_line);
8555 }
8556
8557 // On command input, we scroll to bottom even if AutoScroll==false
8558 ScrollToBottom = true;
8559 }
8560
8561 // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
8562 static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)
8563 {
8564 ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
8565 return console->TextEditCallback(data);
8566 }
8567
8568 int TextEditCallback(ImGuiInputTextCallbackData* data)
8569 {
8570 //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd);
8571 switch (data->EventFlag)
8572 {
8573 case ImGuiInputTextFlags_CallbackCompletion:
8574 {
8575 // Example of TEXT COMPLETION
8576
8577 // Locate beginning of current word
8578 const char* word_end = data->Buf + data->CursorPos;
8579 const char* word_start = word_end;
8580 while (word_start > data->Buf)
8581 {
8582 const char c = word_start[-1];
8583 if (c == ' ' || c == '\t' || c == ',' || c == ';')
8584 break;
8585 word_start--;
8586 }
8587
8588 // Build a list of candidates
8589 ImVector<const char*> candidates;
8590 for (int i = 0; i < Commands.Size; i++)
8591 if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)
8592 candidates.push_back(Commands[i]);
8593
8594 if (candidates.Size == 0)
8595 {
8596 // No match
8597 AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
8598 }
8599 else if (candidates.Size == 1)
8600 {
8601 // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
8602 data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
8603 data->InsertChars(data->CursorPos, candidates[0]);
8604 data->InsertChars(data->CursorPos, " ");
8605 }
8606 else
8607 {
8608 // Multiple matches. Complete as much as we can..
8609 // So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
8610 int match_len = (int)(word_end - word_start);
8611 for (;;)
8612 {
8613 int c = 0;
8614 bool all_candidates_matches = true;
8615 for (int i = 0; i < candidates.Size && all_candidates_matches; i++)
8616 if (i == 0)
8617 c = toupper(candidates[i][match_len]);
8618 else if (c == 0 || c != toupper(candidates[i][match_len]))
8619 all_candidates_matches = false;
8620 if (!all_candidates_matches)
8621 break;
8622 match_len++;
8623 }
8624
8625 if (match_len > 0)
8626 {
8627 data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
8628 data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
8629 }
8630
8631 // List matches
8632 AddLog("Possible matches:\n");
8633 for (int i = 0; i < candidates.Size; i++)
8634 AddLog("- %s\n", candidates[i]);
8635 }
8636
8637 break;
8638 }
8639 case ImGuiInputTextFlags_CallbackHistory:
8640 {
8641 // Example of HISTORY
8642 const int prev_history_pos = HistoryPos;
8643 if (data->EventKey == ImGuiKey_UpArrow)
8644 {
8645 if (HistoryPos == -1)
8646 HistoryPos = History.Size - 1;
8647 else if (HistoryPos > 0)
8648 HistoryPos--;
8649 }
8650 else if (data->EventKey == ImGuiKey_DownArrow)
8651 {
8652 if (HistoryPos != -1)
8653 if (++HistoryPos >= History.Size)
8654 HistoryPos = -1;
8655 }
8656
8657 // A better implementation would preserve the data on the current input line along with cursor position.
8658 if (prev_history_pos != HistoryPos)
8659 {
8660 const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : "";
8661 data->DeleteChars(0, data->BufTextLen);
8662 data->InsertChars(0, history_str);
8663 }
8664 }
8665 }
8666 return 0;
8667 }
8668 };
8669
8670 static void ShowExampleAppConsole(bool* p_open)
8671 {
8672 static ExampleAppConsole console;
8673 console.Draw("Example: Console", p_open);
8674 }
8675
8676 //-----------------------------------------------------------------------------
8677 // [SECTION] Example App: Debug Log / ShowExampleAppLog()
8678 //-----------------------------------------------------------------------------
8679
8680 // Usage:
8681 // static ExampleAppLog my_log;
8682 // my_log.AddLog("Hello %d world\n", 123);
8683 // my_log.Draw("title");
8684 struct ExampleAppLog
8685 {
8686 ImGuiTextBuffer Buf;
8687 ImGuiTextFilter Filter;
8688 ImVector<int> LineOffsets; // Index to lines offset. We maintain this with AddLog() calls.
8689 bool AutoScroll; // Keep scrolling if already at the bottom.
8690
8691 ExampleAppLog()
8692 {
8693 AutoScroll = true;
8694 Clear();
8695 }
8696
8697 void Clear()
8698 {
8699 Buf.clear();
8700 LineOffsets.clear();
8701 LineOffsets.push_back(0);
8702 }
8703
8704 void AddLog(const char* fmt, ...) IM_FMTARGS(2)
8705 {
8706 int old_size = Buf.size();
8707 va_list args;
8708 va_start(args, fmt);
8709 Buf.appendfv(fmt, args);
8710 va_end(args);
8711 for (int new_size = Buf.size(); old_size < new_size; old_size++)
8712 if (Buf[old_size] == '\n')
8713 LineOffsets.push_back(old_size + 1);
8714 }
8715
8716 void Draw(const char* title, bool* p_open = NULL)
8717 {
8718 if (!ImGui::Begin(title, p_open))
8719 {
8720 ImGui::End();
8721 return;
8722 }
8723
8724 // Options menu
8725 if (ImGui::BeginPopup("Options"))
8726 {
8727 ImGui::Checkbox("Auto-scroll", &AutoScroll);
8728 ImGui::EndPopup();
8729 }
8730
8731 // Main window
8732 if (ImGui::Button("Options"))
8733 ImGui::OpenPopup("Options");
8734 ImGui::SameLine();
8735 bool clear = ImGui::Button("Clear");
8736 ImGui::SameLine();
8737 bool copy = ImGui::Button("Copy");
8738 ImGui::SameLine();
8739 Filter.Draw("Filter", -100.0f);
8740
8741 ImGui::Separator();
8742
8743 if (ImGui::BeginChild("scrolling", ImVec2(0, 0), ImGuiChildFlags_None, ImGuiWindowFlags_HorizontalScrollbar))
8744 {
8745 if (clear)
8746 Clear();
8747 if (copy)
8748 ImGui::LogToClipboard();
8749
8750 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
8751 const char* buf = Buf.begin();
8752 const char* buf_end = Buf.end();
8753 if (Filter.IsActive())
8754 {
8755 // In this example we don't use the clipper when Filter is enabled.
8756 // This is because we don't have random access to the result of our filter.
8757 // A real application processing logs with ten of thousands of entries may want to store the result of
8758 // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp).
8759 for (int line_no = 0; line_no < LineOffsets.Size; line_no++)
8760 {
8761 const char* line_start = buf + LineOffsets[line_no];
8762 const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
8763 if (Filter.PassFilter(line_start, line_end))
8764 ImGui::TextUnformatted(line_start, line_end);
8765 }
8766 }
8767 else
8768 {
8769 // The simplest and easy way to display the entire buffer:
8770 // ImGui::TextUnformatted(buf_begin, buf_end);
8771 // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward
8772 // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are
8773 // within the visible area.
8774 // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them
8775 // on your side is recommended. Using ImGuiListClipper requires
8776 // - A) random access into your data
8777 // - B) items all being the same height,
8778 // both of which we can handle since we have an array pointing to the beginning of each line of text.
8779 // When using the filter (in the block of code above) we don't have random access into the data to display
8780 // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make
8781 // it possible (and would be recommended if you want to search through tens of thousands of entries).
8782 ImGuiListClipper clipper;
8783 clipper.Begin(LineOffsets.Size);
8784 while (clipper.Step())
8785 {
8786 for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
8787 {
8788 const char* line_start = buf + LineOffsets[line_no];
8789 const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
8790 ImGui::TextUnformatted(line_start, line_end);
8791 }
8792 }
8793 clipper.End();
8794 }
8795 ImGui::PopStyleVar();
8796
8797 // Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame.
8798 // Using a scrollbar or mouse-wheel will take away from the bottom edge.
8799 if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())
8800 ImGui::SetScrollHereY(1.0f);
8801 }
8802 ImGui::EndChild();
8803 ImGui::End();
8804 }
8805 };
8806
8807 // Demonstrate creating a simple log window with basic filtering.
8808 static void ShowExampleAppLog(bool* p_open)
8809 {
8810 static ExampleAppLog log;
8811
8812 // For the demo: add a debug button _BEFORE_ the normal log window contents
8813 // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.
8814 // Most of the contents of the window will be added by the log.Draw() call.
8815 ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
8816 ImGui::Begin("Example: Log", p_open);
8817 IMGUI_DEMO_MARKER("Examples/Log");
8818 if (ImGui::SmallButton("[Debug] Add 5 entries"))
8819 {
8820 static int counter = 0;
8821 const char* categories[3] = { "info", "warn", "error" };
8822 const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
8823 for (int n = 0; n < 5; n++)
8824 {
8825 const char* category = categories[counter % IM_ARRAYSIZE(categories)];
8826 const char* word = words[counter % IM_ARRAYSIZE(words)];
8827 log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
8828 ImGui::GetFrameCount(), category, ImGui::GetTime(), word);
8829 counter++;
8830 }
8831 }
8832 ImGui::End();
8833
8834 // Actually call in the regular Log helper (which will Begin() into the same window as we just did)
8835 log.Draw("Example: Log", p_open);
8836 }
8837
8838 //-----------------------------------------------------------------------------
8839 // [SECTION] Example App: Simple Layout / ShowExampleAppLayout()
8840 //-----------------------------------------------------------------------------
8841
8842 // Demonstrate create a window with multiple child windows.
8843 static void ShowExampleAppLayout(bool* p_open)
8844 {
8845 ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
8846 if (ImGui::Begin("Example: Simple layout", p_open, ImGuiWindowFlags_MenuBar))
8847 {
8848 IMGUI_DEMO_MARKER("Examples/Simple layout");
8849 if (ImGui::BeginMenuBar())
8850 {
8851 if (ImGui::BeginMenu("File"))
8852 {
8853 if (ImGui::MenuItem("Close", "Ctrl+W")) { *p_open = false; }
8854 ImGui::EndMenu();
8855 }
8856 ImGui::EndMenuBar();
8857 }
8858
8859 // Left
8860 static int selected = 0;
8861 {
8862 ImGui::BeginChild("left pane", ImVec2(150, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX);
8863 for (int i = 0; i < 100; i++)
8864 {
8865 // FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav
8866 char label[128];
8867 sprintf(label, "MyObject %d", i);
8868 if (ImGui::Selectable(label, selected == i))
8869 selected = i;
8870 }
8871 ImGui::EndChild();
8872 }
8873 ImGui::SameLine();
8874
8875 // Right
8876 {
8877 ImGui::BeginGroup();
8878 ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
8879 ImGui::Text("MyObject: %d", selected);
8880 ImGui::Separator();
8881 if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None))
8882 {
8883 if (ImGui::BeginTabItem("Description"))
8884 {
8885 ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
8886 ImGui::EndTabItem();
8887 }
8888 if (ImGui::BeginTabItem("Details"))
8889 {
8890 ImGui::Text("ID: 0123456789");
8891 ImGui::EndTabItem();
8892 }
8893 ImGui::EndTabBar();
8894 }
8895 ImGui::EndChild();
8896 if (ImGui::Button("Revert")) {}
8897 ImGui::SameLine();
8898 if (ImGui::Button("Save")) {}
8899 ImGui::EndGroup();
8900 }
8901 }
8902 ImGui::End();
8903 }
8904
8905 //-----------------------------------------------------------------------------
8906 // [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
8907 //-----------------------------------------------------------------------------
8908 // Some of the interactions are a bit lack-luster:
8909 // - We would want pressing validating or leaving the filter to somehow restore focus.
8910 // - We may want more advanced filtering (child nodes) and clipper support: both will need extra work.
8911 // - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties.
8912 //-----------------------------------------------------------------------------
8913
8914 struct ExampleAppPropertyEditor
8915 {
8916 ImGuiTextFilter Filter;
8917 ExampleTreeNode* VisibleNode = NULL;
8918
8919 void Draw(ExampleTreeNode* root_node)
8920 {
8921 // Left side: draw tree
8922 // - Currently using a table to benefit from RowBg feature
8923 if (ImGui::BeginChild("##tree", ImVec2(300, 0), ImGuiChildFlags_ResizeX | ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened))
8924 {
8925 ImGui::SetNextItemWidth(-FLT_MIN);
8926 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip);
8927 ImGui::PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
8928 if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_ARRAYSIZE(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll))
8929 Filter.Build();
8930 ImGui::PopItemFlag();
8931
8932 if (ImGui::BeginTable("##bg", 1, ImGuiTableFlags_RowBg))
8933 {
8934 for (ExampleTreeNode* node : root_node->Childs)
8935 if (Filter.PassFilter(node->Name)) // Filter root node
8936 DrawTreeNode(node);
8937 ImGui::EndTable();
8938 }
8939 }
8940 ImGui::EndChild();
8941
8942 // Right side: draw properties
8943 ImGui::SameLine();
8944
8945 ImGui::BeginGroup(); // Lock X position
8946 if (ExampleTreeNode* node = VisibleNode)
8947 {
8948 ImGui::Text("%s", node->Name);
8949 ImGui::TextDisabled("UID: 0x%08X", node->UID);
8950 ImGui::Separator();
8951 if (ImGui::BeginTable("##properties", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY))
8952 {
8953 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed);
8954 ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default twice larger
8955 if (node->HasData)
8956 {
8957 // In a typical application, the structure description would be derived from a data-driven system.
8958 // - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array.
8959 // - Limits and some details are hard-coded to simplify the demo.
8960 for (const ExampleMemberInfo& field_desc : ExampleTreeNodeMemberInfos)
8961 {
8962 ImGui::TableNextRow();
8963 ImGui::PushID(field_desc.Name);
8964 ImGui::TableNextColumn();
8965 ImGui::AlignTextToFramePadding();
8966 ImGui::TextUnformatted(field_desc.Name);
8967 ImGui::TableNextColumn();
8968 void* field_ptr = (void*)(((unsigned char*)node) + field_desc.Offset);
8969 switch (field_desc.DataType)
8970 {
8971 case ImGuiDataType_Bool:
8972 {
8973 IM_ASSERT(field_desc.DataCount == 1);
8974 ImGui::Checkbox("##Editor", (bool*)field_ptr);
8975 break;
8976 }
8977 case ImGuiDataType_S32:
8978 {
8979 int v_min = INT_MIN, v_max = INT_MAX;
8980 ImGui::SetNextItemWidth(-FLT_MIN);
8981 ImGui::DragScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, 1.0f, &v_min, &v_max);
8982 break;
8983 }
8984 case ImGuiDataType_Float:
8985 {
8986 float v_min = 0.0f, v_max = 1.0f;
8987 ImGui::SetNextItemWidth(-FLT_MIN);
8988 ImGui::SliderScalarN("##Editor", field_desc.DataType, field_ptr, field_desc.DataCount, &v_min, &v_max);
8989 break;
8990 }
8991 }
8992 ImGui::PopID();
8993 }
8994 }
8995 ImGui::EndTable();
8996 }
8997 }
8998 ImGui::EndGroup();
8999 }
9000
9001 void DrawTreeNode(ExampleTreeNode* node)
9002 {
9003 ImGui::TableNextRow();
9004 ImGui::TableNextColumn();
9005 ImGui::PushID(node->UID);
9006 ImGuiTreeNodeFlags tree_flags = ImGuiTreeNodeFlags_None;
9007 tree_flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; // Standard opening mode as we are likely to want to add selection afterwards
9008 tree_flags |= ImGuiTreeNodeFlags_NavLeftJumpsBackHere; // Left arrow support
9009 if (node == VisibleNode)
9010 tree_flags |= ImGuiTreeNodeFlags_Selected;
9011 if (node->Childs.Size == 0)
9012 tree_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet;
9013 if (node->DataMyBool == false)
9014 ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyle().Colors[ImGuiCol_TextDisabled]);
9015 bool node_open = ImGui::TreeNodeEx("", tree_flags, "%s", node->Name);
9016 if (node->DataMyBool == false)
9017 ImGui::PopStyleColor();
9018 if (ImGui::IsItemFocused())
9019 VisibleNode = node;
9020 if (node_open)
9021 {
9022 for (ExampleTreeNode* child : node->Childs)
9023 DrawTreeNode(child);
9024 ImGui::TreePop();
9025 }
9026 ImGui::PopID();
9027 }
9028 };
9029
9030 // Demonstrate creating a simple property editor.
9031 static void ShowExampleAppPropertyEditor(bool* p_open, ImGuiDemoWindowData* demo_data)
9032 {
9033 ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);
9034 if (!ImGui::Begin("Example: Property editor", p_open))
9035 {
9036 ImGui::End();
9037 return;
9038 }
9039
9040 IMGUI_DEMO_MARKER("Examples/Property Editor");
9041 static ExampleAppPropertyEditor property_editor;
9042 if (demo_data->DemoTree == NULL)
9043 demo_data->DemoTree = ExampleTree_CreateDemoTree();
9044 property_editor.Draw(demo_data->DemoTree);
9045
9046 ImGui::End();
9047 }
9048
9049 //-----------------------------------------------------------------------------
9050 // [SECTION] Example App: Long Text / ShowExampleAppLongText()
9051 //-----------------------------------------------------------------------------
9052
9053 // Demonstrate/test rendering huge amount of text, and the incidence of clipping.
9054 static void ShowExampleAppLongText(bool* p_open)
9055 {
9056 ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
9057 if (!ImGui::Begin("Example: Long text display", p_open))
9058 {
9059 ImGui::End();
9060 return;
9061 }
9062 IMGUI_DEMO_MARKER("Examples/Long text display");
9063
9064 static int test_type = 0;
9065 static ImGuiTextBuffer log;
9066 static int lines = 0;
9067 ImGui::Text("Printing unusually long amount of text.");
9068 ImGui::Combo("Test type", &test_type,
9069 "Single call to TextUnformatted()\0"
9070 "Multiple calls to Text(), clipped\0"
9071 "Multiple calls to Text(), not clipped (slow)\0");
9072 ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size());
9073 if (ImGui::Button("Clear")) { log.clear(); lines = 0; }
9074 ImGui::SameLine();
9075 if (ImGui::Button("Add 1000 lines"))
9076 {
9077 for (int i = 0; i < 1000; i++)
9078 log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i);
9079 lines += 1000;
9080 }
9081 ImGui::BeginChild("Log");
9082 switch (test_type)
9083 {
9084 case 0:
9085 // Single call to TextUnformatted() with a big buffer
9086 ImGui::TextUnformatted(log.begin(), log.end());
9087 break;
9088 case 1:
9089 {
9090 // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
9091 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
9092 ImGuiListClipper clipper;
9093 clipper.Begin(lines);
9094 while (clipper.Step())
9095 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
9096 ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
9097 ImGui::PopStyleVar();
9098 break;
9099 }
9100 case 2:
9101 // Multiple calls to Text(), not clipped (slow)
9102 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
9103 for (int i = 0; i < lines; i++)
9104 ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
9105 ImGui::PopStyleVar();
9106 break;
9107 }
9108 ImGui::EndChild();
9109 ImGui::End();
9110 }
9111
9112 //-----------------------------------------------------------------------------
9113 // [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()
9114 //-----------------------------------------------------------------------------
9115
9116 // Demonstrate creating a window which gets auto-resized according to its content.
9117 static void ShowExampleAppAutoResize(bool* p_open)
9118 {
9119 if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize))
9120 {
9121 ImGui::End();
9122 return;
9123 }
9124 IMGUI_DEMO_MARKER("Examples/Auto-resizing window");
9125
9126 static int lines = 10;
9127 ImGui::TextUnformatted(
9128 "Window will resize every-frame to the size of its content.\n"
9129 "Note that you probably don't want to query the window size to\n"
9130 "output your content because that would create a feedback loop.");
9131 ImGui::SliderInt("Number of lines", &lines, 1, 20);
9132 for (int i = 0; i < lines; i++)
9133 ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally
9134 ImGui::End();
9135 }
9136
9137 //-----------------------------------------------------------------------------
9138 // [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()
9139 //-----------------------------------------------------------------------------
9140
9141 // Demonstrate creating a window with custom resize constraints.
9142 // Note that size constraints currently don't work on a docked window (when in 'docking' branch)
9143 static void ShowExampleAppConstrainedResize(bool* p_open)
9144 {
9145 struct CustomConstraints
9146 {
9147 // Helper functions to demonstrate programmatic constraints
9148 // FIXME: This doesn't take account of decoration size (e.g. title bar), library should make this easier.
9149 // FIXME: None of the three demos works consistently when resizing from borders.
9150 static void AspectRatio(ImGuiSizeCallbackData* data)
9151 {
9152 float aspect_ratio = *(float*)data->UserData;
9153 data->DesiredSize.y = (float)(int)(data->DesiredSize.x / aspect_ratio);
9154 }
9155 static void Square(ImGuiSizeCallbackData* data)
9156 {
9157 data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y);
9158 }
9159 static void Step(ImGuiSizeCallbackData* data)
9160 {
9161 float step = *(float*)data->UserData;
9162 data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step);
9163 }
9164 };
9165
9166 const char* test_desc[] =
9167 {
9168 "Between 100x100 and 500x500",
9169 "At least 100x100",
9170 "Resize vertical + lock current width",
9171 "Resize horizontal + lock current height",
9172 "Width Between 400 and 500",
9173 "Height at least 400",
9174 "Custom: Aspect Ratio 16:9",
9175 "Custom: Always Square",
9176 "Custom: Fixed Steps (100)",
9177 };
9178
9179 // Options
9180 static bool auto_resize = false;
9181 static bool window_padding = true;
9182 static int type = 6; // Aspect Ratio
9183 static int display_lines = 10;
9184
9185 // Submit constraint
9186 float aspect_ratio = 16.0f / 9.0f;
9187 float fixed_step = 100.0f;
9188 if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)); // Between 100x100 and 500x500
9189 if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100
9190 if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Resize vertical + lock current width
9191 if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Resize horizontal + lock current height
9192 if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width Between and 400 and 500
9193 if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)); // Height at least 400
9194 if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::AspectRatio, (void*)&aspect_ratio); // Aspect ratio
9195 if (type == 7) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
9196 if (type == 8) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)&fixed_step); // Fixed Step
9197
9198 // Submit window
9199 if (!window_padding)
9200 ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
9201 const ImGuiWindowFlags window_flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;
9202 const bool window_open = ImGui::Begin("Example: Constrained Resize", p_open, window_flags);
9203 if (!window_padding)
9204 ImGui::PopStyleVar();
9205 if (window_open)
9206 {
9207 IMGUI_DEMO_MARKER("Examples/Constrained Resizing window");
9208 if (ImGui::GetIO().KeyShift)
9209 {
9210 // Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture.
9211 ImVec2 avail_size = ImGui::GetContentRegionAvail();
9212 ImVec2 pos = ImGui::GetCursorScreenPos();
9213 ImGui::ColorButton("viewport", ImVec4(0.5f, 0.2f, 0.5f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, avail_size);
9214 ImGui::SetCursorScreenPos(ImVec2(pos.x + 10, pos.y + 10));
9215 ImGui::Text("%.2f x %.2f", avail_size.x, avail_size.y);
9216 }
9217 else
9218 {
9219 ImGui::Text("(Hold SHIFT to display a dummy viewport)");
9220 if (ImGui::Button("Set 200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine();
9221 if (ImGui::Button("Set 500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine();
9222 if (ImGui::Button("Set 800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); }
9223 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20);
9224 ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc));
9225 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 20);
9226 ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100);
9227 ImGui::Checkbox("Auto-resize", &auto_resize);
9228 ImGui::Checkbox("Window padding", &window_padding);
9229 for (int i = 0; i < display_lines; i++)
9230 ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, "");
9231 }
9232 }
9233 ImGui::End();
9234 }
9235
9236 //-----------------------------------------------------------------------------
9237 // [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay()
9238 //-----------------------------------------------------------------------------
9239
9240 // Demonstrate creating a simple static window with no decoration
9241 // + a context-menu to choose which corner of the screen to use.
9242 static void ShowExampleAppSimpleOverlay(bool* p_open)
9243 {
9244 static int location = 0;
9245 ImGuiIO& io = ImGui::GetIO();
9246 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;
9247 if (location >= 0)
9248 {
9249 const float PAD = 10.0f;
9250 const ImGuiViewport* viewport = ImGui::GetMainViewport();
9251 ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any!
9252 ImVec2 work_size = viewport->WorkSize;
9253 ImVec2 window_pos, window_pos_pivot;
9254 window_pos.x = (location & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD);
9255 window_pos.y = (location & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD);
9256 window_pos_pivot.x = (location & 1) ? 1.0f : 0.0f;
9257 window_pos_pivot.y = (location & 2) ? 1.0f : 0.0f;
9258 ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
9259 window_flags |= ImGuiWindowFlags_NoMove;
9260 }
9261 else if (location == -2)
9262 {
9263 // Center window
9264 ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
9265 window_flags |= ImGuiWindowFlags_NoMove;
9266 }
9267 ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background
9268 if (ImGui::Begin("Example: Simple overlay", p_open, window_flags))
9269 {
9270 IMGUI_DEMO_MARKER("Examples/Simple Overlay");
9271 ImGui::Text("Simple overlay\n" "(right-click to change position)");
9272 ImGui::Separator();
9273 if (ImGui::IsMousePosValid())
9274 ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
9275 else
9276 ImGui::Text("Mouse Position: <invalid>");
9277 if (ImGui::BeginPopupContextWindow())
9278 {
9279 if (ImGui::MenuItem("Custom", NULL, location == -1)) location = -1;
9280 if (ImGui::MenuItem("Center", NULL, location == -2)) location = -2;
9281 if (ImGui::MenuItem("Top-left", NULL, location == 0)) location = 0;
9282 if (ImGui::MenuItem("Top-right", NULL, location == 1)) location = 1;
9283 if (ImGui::MenuItem("Bottom-left", NULL, location == 2)) location = 2;
9284 if (ImGui::MenuItem("Bottom-right", NULL, location == 3)) location = 3;
9285 if (p_open && ImGui::MenuItem("Close")) *p_open = false;
9286 ImGui::EndPopup();
9287 }
9288 }
9289 ImGui::End();
9290 }
9291
9292 //-----------------------------------------------------------------------------
9293 // [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen()
9294 //-----------------------------------------------------------------------------
9295
9296 // Demonstrate creating a window covering the entire screen/viewport
9297 static void ShowExampleAppFullscreen(bool* p_open)
9298 {
9299 static bool use_work_area = true;
9300 static ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings;
9301
9302 // We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.)
9303 // Based on your use case you may want one or the other.
9304 const ImGuiViewport* viewport = ImGui::GetMainViewport();
9305 ImGui::SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos);
9306 ImGui::SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size);
9307
9308 if (ImGui::Begin("Example: Fullscreen window", p_open, flags))
9309 {
9310 ImGui::Checkbox("Use work area instead of main area", &use_work_area);
9311 ImGui::SameLine();
9312 HelpMarker("Main Area = entire viewport,\nWork Area = entire viewport minus sections used by the main menu bars, task bars etc.\n\nEnable the main-menu bar in Examples menu to see the difference.");
9313
9314 ImGui::CheckboxFlags("ImGuiWindowFlags_NoBackground", &flags, ImGuiWindowFlags_NoBackground);
9315 ImGui::CheckboxFlags("ImGuiWindowFlags_NoDecoration", &flags, ImGuiWindowFlags_NoDecoration);
9316 ImGui::Indent();
9317 ImGui::CheckboxFlags("ImGuiWindowFlags_NoTitleBar", &flags, ImGuiWindowFlags_NoTitleBar);
9318 ImGui::CheckboxFlags("ImGuiWindowFlags_NoCollapse", &flags, ImGuiWindowFlags_NoCollapse);
9319 ImGui::CheckboxFlags("ImGuiWindowFlags_NoScrollbar", &flags, ImGuiWindowFlags_NoScrollbar);
9320 ImGui::Unindent();
9321
9322 if (p_open && ImGui::Button("Close this window"))
9323 *p_open = false;
9324 }
9325 ImGui::End();
9326 }
9327
9328 //-----------------------------------------------------------------------------
9329 // [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()
9330 //-----------------------------------------------------------------------------
9331
9332 // Demonstrate the use of "##" and "###" in identifiers to manipulate ID generation.
9333 // This applies to all regular items as well.
9334 // Read FAQ section "How can I have multiple widgets with the same label?" for details.
9335 static void ShowExampleAppWindowTitles(bool*)
9336 {
9337 const ImGuiViewport* viewport = ImGui::GetMainViewport();
9338 const ImVec2 base_pos = viewport->Pos;
9339
9340 // By default, Windows are uniquely identified by their title.
9341 // You can use the "##" and "###" markers to manipulate the display/ID.
9342
9343 // Using "##" to display same title but have unique identifier.
9344 ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond_FirstUseEver);
9345 ImGui::Begin("Same title as another window##1");
9346 IMGUI_DEMO_MARKER("Examples/Manipulating window titles");
9347 ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
9348 ImGui::End();
9349
9350 ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 200), ImGuiCond_FirstUseEver);
9351 ImGui::Begin("Same title as another window##2");
9352 ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
9353 ImGui::End();
9354
9355 // Using "###" to display a changing title but keep a static identifier "AnimatedTitle"
9356 char buf[128];
9357 sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount());
9358 ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 300), ImGuiCond_FirstUseEver);
9359 ImGui::Begin(buf);
9360 ImGui::Text("This window has a changing title.");
9361 ImGui::End();
9362 }
9363
9364 //-----------------------------------------------------------------------------
9365 // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
9366 //-----------------------------------------------------------------------------
9367
9368 // Add a |_| looking shape
9369 static void PathConcaveShape(ImDrawList* draw_list, float x, float y, float sz)
9370 {
9371 const ImVec2 pos_norms[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } };
9372 for (const ImVec2& p : pos_norms)
9373 draw_list->PathLineTo(ImVec2(x + 0.5f + (int)(sz * p.x), y + 0.5f + (int)(sz * p.y)));
9374 }
9375
9376 // Demonstrate using the low-level ImDrawList to draw custom shapes.
9377 static void ShowExampleAppCustomRendering(bool* p_open)
9378 {
9379 if (!ImGui::Begin("Example: Custom rendering", p_open))
9380 {
9381 ImGui::End();
9382 return;
9383 }
9384 IMGUI_DEMO_MARKER("Examples/Custom Rendering");
9385
9386 // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of
9387 // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your
9388 // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not
9389 // exposed outside (to avoid messing with your types) In this example we are not using the maths operators!
9390
9391 if (ImGui::BeginTabBar("##TabBar"))
9392 {
9393 if (ImGui::BeginTabItem("Primitives"))
9394 {
9395 ImGui::PushItemWidth(-ImGui::GetFontSize() * 15);
9396 ImDrawList* draw_list = ImGui::GetWindowDrawList();
9397
9398 // Draw gradients
9399 // (note that those are currently exacerbating our sRGB/Linear issues)
9400 // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well..
9401 ImGui::Text("Gradients");
9402 ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight());
9403 {
9404 ImVec2 p0 = ImGui::GetCursorScreenPos();
9405 ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
9406 ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255));
9407 ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255));
9408 draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
9409 ImGui::InvisibleButton("##gradient1", gradient_size);
9410 }
9411 {
9412 ImVec2 p0 = ImGui::GetCursorScreenPos();
9413 ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
9414 ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255));
9415 ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255));
9416 draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
9417 ImGui::InvisibleButton("##gradient2", gradient_size);
9418 }
9419
9420 // Draw a bunch of primitives
9421 ImGui::Text("All primitives");
9422 static float sz = 36.0f;
9423 static float thickness = 3.0f;
9424 static int ngon_sides = 6;
9425 static bool circle_segments_override = false;
9426 static int circle_segments_override_v = 12;
9427 static bool curve_segments_override = false;
9428 static int curve_segments_override_v = 8;
9429 static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
9430 ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f");
9431 ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f");
9432 ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12);
9433 ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override);
9434 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
9435 circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40);
9436 ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override);
9437 ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
9438 curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40);
9439 ImGui::ColorEdit4("Color", &colf.x);
9440
9441 const ImVec2 p = ImGui::GetCursorScreenPos();
9442 const ImU32 col = ImColor(colf);
9443 const float spacing = 10.0f;
9444 const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight;
9445 const float rounding = sz / 5.0f;
9446 const int circle_segments = circle_segments_override ? circle_segments_override_v : 0;
9447 const int curve_segments = curve_segments_override ? curve_segments_override_v : 0;
9448 const ImVec2 cp3[3] = { ImVec2(0.0f, sz * 0.6f), ImVec2(sz * 0.5f, -sz * 0.4f), ImVec2(sz, sz) }; // Control points for curves
9449 const ImVec2 cp4[4] = { ImVec2(0.0f, 0.0f), ImVec2(sz * 1.3f, sz * 0.3f), ImVec2(sz - sz * 1.3f, sz - sz * 0.3f), ImVec2(sz, sz) };
9450
9451 float x = p.x + 4.0f;
9452 float y = p.y + 4.0f;
9453 for (int n = 0; n < 2; n++)
9454 {
9455 // First line uses a thickness of 1.0f, second line uses the configurable thickness
9456 float th = (n == 0) ? 1.0f : thickness;
9457 draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon
9458 draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle
9459 draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse
9460 draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, ImDrawFlags_None, th); x += sz + spacing; // Square
9461 draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th); x += sz + spacing; // Square with all rounded corners
9462 draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners
9463 draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle
9464 //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle
9465 PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, ImDrawFlags_Closed, th); x += sz + spacing; // Concave Shape
9466 //draw_list->AddPolyline(concave_shape, IM_ARRAYSIZE(concave_shape), col, ImDrawFlags_Closed, th);
9467 draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!)
9468 draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!)
9469 draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line
9470
9471 // Path
9472 draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f);
9473 draw_list->PathStroke(col, ImDrawFlags_None, th);
9474 x += sz + spacing;
9475
9476 // Quadratic Bezier Curve (3 control points)
9477 draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments);
9478 x += sz + spacing;
9479
9480 // Cubic Bezier Curve (4 control points)
9481 draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments);
9482
9483 x = p.x + 4;
9484 y += sz + spacing;
9485 }
9486
9487 // Filled shapes
9488 draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides); x += sz + spacing; // N-gon
9489 draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments); x += sz + spacing; // Circle
9490 draw_list->AddEllipseFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), ImVec2(sz * 0.5f, sz * 0.3f), col, -0.3f, circle_segments); x += sz + spacing;// Ellipse
9491 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square
9492 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners
9493 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners
9494 draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle
9495 //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle
9496 PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape
9497 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness)
9498 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness)
9499 draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine)
9500
9501 // Path
9502 draw_list->PathArcTo(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, 3.141592f * -0.5f, 3.141592f);
9503 draw_list->PathFillConvex(col);
9504 x += sz + spacing;
9505
9506 // Quadratic Bezier Curve (3 control points)
9507 draw_list->PathLineTo(ImVec2(x + cp3[0].x, y + cp3[0].y));
9508 draw_list->PathBezierQuadraticCurveTo(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), curve_segments);
9509 draw_list->PathFillConvex(col);
9510 x += sz + spacing;
9511
9512 draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255));
9513 x += sz + spacing;
9514
9515 ImGui::Dummy(ImVec2((sz + spacing) * 13.2f, (sz + spacing) * 3.0f));
9516 ImGui::PopItemWidth();
9517 ImGui::EndTabItem();
9518 }
9519
9520 if (ImGui::BeginTabItem("Canvas"))
9521 {
9522 static ImVector<ImVec2> points;
9523 static ImVec2 scrolling(0.0f, 0.0f);
9524 static bool opt_enable_grid = true;
9525 static bool opt_enable_context_menu = true;
9526 static bool adding_line = false;
9527
9528 ImGui::Checkbox("Enable grid", &opt_enable_grid);
9529 ImGui::Checkbox("Enable context menu", &opt_enable_context_menu);
9530 ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.");
9531
9532 // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling.
9533 // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls.
9534 // To use a child window instead we could use, e.g:
9535 // ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding
9536 // ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color
9537 // ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove);
9538 // ImGui::PopStyleColor();
9539 // ImGui::PopStyleVar();
9540 // [...]
9541 // ImGui::EndChild();
9542
9543 // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive()
9544 ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
9545 ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
9546 if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f;
9547 if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f;
9548 ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y);
9549
9550 // Draw border and background color
9551 ImGuiIO& io = ImGui::GetIO();
9552 ImDrawList* draw_list = ImGui::GetWindowDrawList();
9553 draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255));
9554 draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255));
9555
9556 // This will catch our interactions
9557 ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);
9558 const bool is_hovered = ImGui::IsItemHovered(); // Hovered
9559 const bool is_active = ImGui::IsItemActive(); // Held
9560 const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin
9561 const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y);
9562
9563 // Add first and second point
9564 if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left))
9565 {
9566 points.push_back(mouse_pos_in_canvas);
9567 points.push_back(mouse_pos_in_canvas);
9568 adding_line = true;
9569 }
9570 if (adding_line)
9571 {
9572 points.back() = mouse_pos_in_canvas;
9573 if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
9574 adding_line = false;
9575 }
9576
9577 // Pan (we use a zero mouse threshold when there's no context menu)
9578 // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc.
9579 const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f;
9580 if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan))
9581 {
9582 scrolling.x += io.MouseDelta.x;
9583 scrolling.y += io.MouseDelta.y;
9584 }
9585
9586 // Context menu (under default mouse threshold)
9587 ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
9588 if (opt_enable_context_menu && drag_delta.x == 0.0f && drag_delta.y == 0.0f)
9589 ImGui::OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
9590 if (ImGui::BeginPopup("context"))
9591 {
9592 if (adding_line)
9593 points.resize(points.size() - 2);
9594 adding_line = false;
9595 if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); }
9596 if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); }
9597 ImGui::EndPopup();
9598 }
9599
9600 // Draw grid + all lines in the canvas
9601 draw_list->PushClipRect(canvas_p0, canvas_p1, true);
9602 if (opt_enable_grid)
9603 {
9604 const float GRID_STEP = 64.0f;
9605 for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP)
9606 draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40));
9607 for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP)
9608 draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40));
9609 }
9610 for (int n = 0; n < points.Size; n += 2)
9611 draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);
9612 draw_list->PopClipRect();
9613
9614 ImGui::EndTabItem();
9615 }
9616
9617 if (ImGui::BeginTabItem("BG/FG draw lists"))
9618 {
9619 static bool draw_bg = true;
9620 static bool draw_fg = true;
9621 ImGui::Checkbox("Draw in Background draw list", &draw_bg);
9622 ImGui::SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows.");
9623 ImGui::Checkbox("Draw in Foreground draw list", &draw_fg);
9624 ImGui::SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows.");
9625 ImVec2 window_pos = ImGui::GetWindowPos();
9626 ImVec2 window_size = ImGui::GetWindowSize();
9627 ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f);
9628 if (draw_bg)
9629 ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4);
9630 if (draw_fg)
9631 ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10);
9632 ImGui::EndTabItem();
9633 }
9634
9635 // Demonstrate out-of-order rendering via channels splitting
9636 // We use functions in ImDrawList as each draw list contains a convenience splitter,
9637 // but you can also instantiate your own ImDrawListSplitter if you need to nest them.
9638 if (ImGui::BeginTabItem("Draw Channels"))
9639 {
9640 ImDrawList* draw_list = ImGui::GetWindowDrawList();
9641 {
9642 ImGui::Text("Blue shape is drawn first: appears in back");
9643 ImGui::Text("Red shape is drawn after: appears in front");
9644 ImVec2 p0 = ImGui::GetCursorScreenPos();
9645 draw_list->AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)); // Blue
9646 draw_list->AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)); // Red
9647 ImGui::Dummy(ImVec2(75, 75));
9648 }
9649 ImGui::Separator();
9650 {
9651 ImGui::Text("Blue shape is drawn first, into channel 1: appears in front");
9652 ImGui::Text("Red shape is drawn after, into channel 0: appears in back");
9653 ImVec2 p1 = ImGui::GetCursorScreenPos();
9654
9655 // Create 2 channels and draw a Blue shape THEN a Red shape.
9656 // You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls.
9657 draw_list->ChannelsSplit(2);
9658 draw_list->ChannelsSetCurrent(1);
9659 draw_list->AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)); // Blue
9660 draw_list->ChannelsSetCurrent(0);
9661 draw_list->AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)); // Red
9662
9663 // Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1.
9664 // This works by copying draw indices only (vertices are not copied).
9665 draw_list->ChannelsMerge();
9666 ImGui::Dummy(ImVec2(75, 75));
9667 ImGui::Text("After reordering, contents of channel 0 appears below channel 1.");
9668 }
9669 ImGui::EndTabItem();
9670 }
9671
9672 ImGui::EndTabBar();
9673 }
9674
9675 ImGui::End();
9676 }
9677
9678 //-----------------------------------------------------------------------------
9679 // [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
9680 //-----------------------------------------------------------------------------
9681
9682 // Simplified structure to mimic a Document model
9683 struct MyDocument
9684 {
9685 char Name[32]; // Document title
9686 int UID; // Unique ID (necessary as we can change title)
9687 bool Open; // Set when open (we keep an array of all available documents to simplify demo code!)
9688 bool OpenPrev; // Copy of Open from last update.
9689 bool Dirty; // Set when the document has been modified
9690 ImVec4 Color; // An arbitrary variable associated to the document
9691
9692 MyDocument(int uid, const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f))
9693 {
9694 UID = uid;
9695 snprintf(Name, sizeof(Name), "%s", name);
9696 Open = OpenPrev = open;
9697 Dirty = false;
9698 Color = color;
9699 }
9700 void DoOpen() { Open = true; }
9701 void DoForceClose() { Open = false; Dirty = false; }
9702 void DoSave() { Dirty = false; }
9703 };
9704
9705 struct ExampleAppDocuments
9706 {
9707 ImVector<MyDocument> Documents;
9708 ImVector<MyDocument*> CloseQueue;
9709 MyDocument* RenamingDoc = NULL;
9710 bool RenamingStarted = false;
9711
9712 ExampleAppDocuments()
9713 {
9714 Documents.push_back(MyDocument(0, "Lettuce", true, ImVec4(0.4f, 0.8f, 0.4f, 1.0f)));
9715 Documents.push_back(MyDocument(1, "Eggplant", true, ImVec4(0.8f, 0.5f, 1.0f, 1.0f)));
9716 Documents.push_back(MyDocument(2, "Carrot", true, ImVec4(1.0f, 0.8f, 0.5f, 1.0f)));
9717 Documents.push_back(MyDocument(3, "Tomato", false, ImVec4(1.0f, 0.3f, 0.4f, 1.0f)));
9718 Documents.push_back(MyDocument(4, "A Rather Long Title", false, ImVec4(0.4f, 0.8f, 0.8f, 1.0f)));
9719 Documents.push_back(MyDocument(5, "Some Document", false, ImVec4(0.8f, 0.8f, 1.0f, 1.0f)));
9720 }
9721
9722 // As we allow to change document name, we append a never-changing document ID so tabs are stable
9723 void GetTabName(MyDocument* doc, char* out_buf, size_t out_buf_size)
9724 {
9725 snprintf(out_buf, out_buf_size, "%s###doc%d", doc->Name, doc->UID);
9726 }
9727
9728 // Display placeholder contents for the Document
9729 void DisplayDocContents(MyDocument* doc)
9730 {
9731 ImGui::PushID(doc);
9732 ImGui::Text("Document \"%s\"", doc->Name);
9733 ImGui::PushStyleColor(ImGuiCol_Text, doc->Color);
9734 ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
9735 ImGui::PopStyleColor();
9736
9737 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_R, ImGuiInputFlags_Tooltip);
9738 if (ImGui::Button("Rename.."))
9739 {
9740 RenamingDoc = doc;
9741 RenamingStarted = true;
9742 }
9743 ImGui::SameLine();
9744
9745 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_M, ImGuiInputFlags_Tooltip);
9746 if (ImGui::Button("Modify"))
9747 doc->Dirty = true;
9748
9749 ImGui::SameLine();
9750 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_S, ImGuiInputFlags_Tooltip);
9751 if (ImGui::Button("Save"))
9752 doc->DoSave();
9753
9754 ImGui::SameLine();
9755 ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_W, ImGuiInputFlags_Tooltip);
9756 if (ImGui::Button("Close"))
9757 CloseQueue.push_back(doc);
9758 ImGui::ColorEdit3("color", &doc->Color.x); // Useful to test drag and drop and hold-dragged-to-open-tab behavior.
9759 ImGui::PopID();
9760 }
9761
9762 // Display context menu for the Document
9763 void DisplayDocContextMenu(MyDocument* doc)
9764 {
9765 if (!ImGui::BeginPopupContextItem())
9766 return;
9767
9768 char buf[256];
9769 sprintf(buf, "Save %s", doc->Name);
9770 if (ImGui::MenuItem(buf, "Ctrl+S", false, doc->Open))
9771 doc->DoSave();
9772 if (ImGui::MenuItem("Rename...", "Ctrl+R", false, doc->Open))
9773 RenamingDoc = doc;
9774 if (ImGui::MenuItem("Close", "Ctrl+W", false, doc->Open))
9775 CloseQueue.push_back(doc);
9776 ImGui::EndPopup();
9777 }
9778
9779 // [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface.
9780 // If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo,
9781 // as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for
9782 // the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has
9783 // disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively
9784 // give the impression of a flicker for one frame.
9785 // We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch.
9786 // Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag.
9787 void NotifyOfDocumentsClosedElsewhere()
9788 {
9789 for (MyDocument& doc : Documents)
9790 {
9791 if (!doc.Open && doc.OpenPrev)
9792 ImGui::SetTabItemClosed(doc.Name);
9793 doc.OpenPrev = doc.Open;
9794 }
9795 }
9796 };
9797
9798 void ShowExampleAppDocuments(bool* p_open)
9799 {
9800 static ExampleAppDocuments app;
9801
9802 // Options
9803 static bool opt_reorderable = true;
9804 static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_;
9805
9806 bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar);
9807 if (!window_contents_visible)
9808 {
9809 ImGui::End();
9810 return;
9811 }
9812
9813 // Menu
9814 if (ImGui::BeginMenuBar())
9815 {
9816 if (ImGui::BeginMenu("File"))
9817 {
9818 int open_count = 0;
9819 for (MyDocument& doc : app.Documents)
9820 open_count += doc.Open ? 1 : 0;
9821
9822 if (ImGui::BeginMenu("Open", open_count < app.Documents.Size))
9823 {
9824 for (MyDocument& doc : app.Documents)
9825 if (!doc.Open && ImGui::MenuItem(doc.Name))
9826 doc.DoOpen();
9827 ImGui::EndMenu();
9828 }
9829 if (ImGui::MenuItem("Close All Documents", NULL, false, open_count > 0))
9830 for (MyDocument& doc : app.Documents)
9831 app.CloseQueue.push_back(&doc);
9832 if (ImGui::MenuItem("Exit") && p_open)
9833 *p_open = false;
9834 ImGui::EndMenu();
9835 }
9836 ImGui::EndMenuBar();
9837 }
9838
9839 // [Debug] List documents with one checkbox for each
9840 for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
9841 {
9842 MyDocument& doc = app.Documents[doc_n];
9843 if (doc_n > 0)
9844 ImGui::SameLine();
9845 ImGui::PushID(&doc);
9846 if (ImGui::Checkbox(doc.Name, &doc.Open))
9847 if (!doc.Open)
9848 doc.DoForceClose();
9849 ImGui::PopID();
9850 }
9851
9852 ImGui::Separator();
9853
9854 // About the ImGuiWindowFlags_UnsavedDocument / ImGuiTabItemFlags_UnsavedDocument flags.
9855 // They have multiple effects:
9856 // - Display a dot next to the title.
9857 // - Tab is selected when clicking the X close button.
9858 // - Closure is not assumed (will wait for user to stop submitting the tab).
9859 // Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
9860 // We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty
9861 // hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window.
9862 // The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole.
9863
9864 // Submit Tab Bar and Tabs
9865 {
9866 ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0);
9867 tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
9868 if (ImGui::BeginTabBar("##tabs", tab_bar_flags))
9869 {
9870 if (opt_reorderable)
9871 app.NotifyOfDocumentsClosedElsewhere();
9872
9873 // [DEBUG] Stress tests
9874 //if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1; // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on.
9875 //if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name); // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway..
9876
9877 // Submit Tabs
9878 for (MyDocument& doc : app.Documents)
9879 {
9880 if (!doc.Open)
9881 continue;
9882
9883 // As we allow to change document name, we append a never-changing document id so tabs are stable
9884 char doc_name_buf[64];
9885 app.GetTabName(&doc, doc_name_buf, sizeof(doc_name_buf));
9886 ImGuiTabItemFlags tab_flags = (doc.Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0);
9887 bool visible = ImGui::BeginTabItem(doc_name_buf, &doc.Open, tab_flags);
9888
9889 // Cancel attempt to close when unsaved add to save queue so we can display a popup.
9890 if (!doc.Open && doc.Dirty)
9891 {
9892 doc.Open = true;
9893 app.CloseQueue.push_back(&doc);
9894 }
9895
9896 app.DisplayDocContextMenu(&doc);
9897 if (visible)
9898 {
9899 app.DisplayDocContents(&doc);
9900 ImGui::EndTabItem();
9901 }
9902 }
9903
9904 ImGui::EndTabBar();
9905 }
9906 }
9907
9908 // Display renaming UI
9909 if (app.RenamingDoc != NULL)
9910 {
9911 if (app.RenamingStarted)
9912 ImGui::OpenPopup("Rename");
9913 if (ImGui::BeginPopup("Rename"))
9914 {
9915 ImGui::SetNextItemWidth(ImGui::GetFontSize() * 30);
9916 if (ImGui::InputText("###Name", app.RenamingDoc->Name, IM_ARRAYSIZE(app.RenamingDoc->Name), ImGuiInputTextFlags_EnterReturnsTrue))
9917 {
9918 ImGui::CloseCurrentPopup();
9919 app.RenamingDoc = NULL;
9920 }
9921 if (app.RenamingStarted)
9922 ImGui::SetKeyboardFocusHere(-1);
9923 ImGui::EndPopup();
9924 }
9925 else
9926 {
9927 app.RenamingDoc = NULL;
9928 }
9929 app.RenamingStarted = false;
9930 }
9931
9932 // Display closing confirmation UI
9933 if (!app.CloseQueue.empty())
9934 {
9935 int close_queue_unsaved_documents = 0;
9936 for (int n = 0; n < app.CloseQueue.Size; n++)
9937 if (app.CloseQueue[n]->Dirty)
9938 close_queue_unsaved_documents++;
9939
9940 if (close_queue_unsaved_documents == 0)
9941 {
9942 // Close documents when all are unsaved
9943 for (int n = 0; n < app.CloseQueue.Size; n++)
9944 app.CloseQueue[n]->DoForceClose();
9945 app.CloseQueue.clear();
9946 }
9947 else
9948 {
9949 if (!ImGui::IsPopupOpen("Save?"))
9950 ImGui::OpenPopup("Save?");
9951 if (ImGui::BeginPopupModal("Save?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
9952 {
9953 ImGui::Text("Save change to the following items?");
9954 float item_height = ImGui::GetTextLineHeightWithSpacing();
9955 if (ImGui::BeginChild(ImGui::GetID("frame"), ImVec2(-FLT_MIN, 6.25f * item_height), ImGuiChildFlags_FrameStyle))
9956 for (MyDocument* doc : app.CloseQueue)
9957 if (doc->Dirty)
9958 ImGui::Text("%s", doc->Name);
9959 ImGui::EndChild();
9960
9961 ImVec2 button_size(ImGui::GetFontSize() * 7.0f, 0.0f);
9962 if (ImGui::Button("Yes", button_size))
9963 {
9964 for (MyDocument* doc : app.CloseQueue)
9965 {
9966 if (doc->Dirty)
9967 doc->DoSave();
9968 doc->DoForceClose();
9969 }
9970 app.CloseQueue.clear();
9971 ImGui::CloseCurrentPopup();
9972 }
9973 ImGui::SameLine();
9974 if (ImGui::Button("No", button_size))
9975 {
9976 for (MyDocument* doc : app.CloseQueue)
9977 doc->DoForceClose();
9978 app.CloseQueue.clear();
9979 ImGui::CloseCurrentPopup();
9980 }
9981 ImGui::SameLine();
9982 if (ImGui::Button("Cancel", button_size))
9983 {
9984 app.CloseQueue.clear();
9985 ImGui::CloseCurrentPopup();
9986 }
9987 ImGui::EndPopup();
9988 }
9989 }
9990 }
9991
9992 ImGui::End();
9993 }
9994
9995 //-----------------------------------------------------------------------------
9996 // [SECTION] Example App: Assets Browser / ShowExampleAppAssetsBrowser()
9997 //-----------------------------------------------------------------------------
9998
9999 //#include "imgui_internal.h" // NavMoveRequestTryWrapping()
10000
10001 struct ExampleAsset
10002 {
10003 ImGuiID ID;
10004 int Type;
10005
10006 ExampleAsset(ImGuiID id, int type) { ID = id; Type = type; }
10007
10008 static const ImGuiTableSortSpecs* s_current_sort_specs;
10009
10010 static void SortWithSortSpecs(ImGuiTableSortSpecs* sort_specs, ExampleAsset* items, int items_count)
10011 {
10012 s_current_sort_specs = sort_specs; // Store in variable accessible by the sort function.
10013 if (items_count > 1)
10014 qsort(items, (size_t)items_count, sizeof(items[0]), ExampleAsset::CompareWithSortSpecs);
10015 s_current_sort_specs = NULL;
10016 }
10017
10018 // Compare function to be used by qsort()
10019 static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs)
10020 {
10021 const ExampleAsset* a = (const ExampleAsset*)lhs;
10022 const ExampleAsset* b = (const ExampleAsset*)rhs;
10023 for (int n = 0; n < s_current_sort_specs->SpecsCount; n++)
10024 {
10025 const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n];
10026 int delta = 0;
10027 if (sort_spec->ColumnIndex == 0)
10028 delta = ((int)a->ID - (int)b->ID);
10029 else if (sort_spec->ColumnIndex == 1)
10030 delta = (a->Type - b->Type);
10031 if (delta > 0)
10032 return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;
10033 if (delta < 0)
10034 return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1;
10035 }
10036 return ((int)a->ID - (int)b->ID);
10037 }
10038 };
10039 const ImGuiTableSortSpecs* ExampleAsset::s_current_sort_specs = NULL;
10040
10041 struct ExampleAssetsBrowser
10042 {
10043 // Options
10044 bool ShowTypeOverlay = true;
10045 bool AllowSorting = true;
10046 bool AllowDragUnselected = false;
10047 bool AllowBoxSelect = true;
10048 float IconSize = 32.0f;
10049 int IconSpacing = 10;
10050 int IconHitSpacing = 4; // Increase hit-spacing if you want to make it possible to clear or box-select from gaps. Some spacing is required to able to amend with Shift+box-select. Value is small in Explorer.
10051 bool StretchSpacing = true;
10052
10053 // State
10054 ImVector<ExampleAsset> Items; // Our items
10055 ExampleSelectionWithDeletion Selection; // Our selection (ImGuiSelectionBasicStorage + helper funcs to handle deletion)
10056 ImGuiID NextItemId = 0; // Unique identifier when creating new items
10057 bool RequestDelete = false; // Deferred deletion request
10058 bool RequestSort = false; // Deferred sort request
10059 float ZoomWheelAccum = 0.0f; // Mouse wheel accumulator to handle smooth wheels better
10060
10061 // Calculated sizes for layout, output of UpdateLayoutSizes(). Could be locals but our code is simpler this way.
10062 ImVec2 LayoutItemSize;
10063 ImVec2 LayoutItemStep; // == LayoutItemSize + LayoutItemSpacing
10064 float LayoutItemSpacing = 0.0f;
10065 float LayoutSelectableSpacing = 0.0f;
10066 float LayoutOuterPadding = 0.0f;
10067 int LayoutColumnCount = 0;
10068 int LayoutLineCount = 0;
10069
10070 // Functions
10071 ExampleAssetsBrowser()
10072 {
10073 AddItems(10000);
10074 }
10075 void AddItems(int count)
10076 {
10077 if (Items.Size == 0)
10078 NextItemId = 0;
10079 Items.reserve(Items.Size + count);
10080 for (int n = 0; n < count; n++, NextItemId++)
10081 Items.push_back(ExampleAsset(NextItemId, (NextItemId % 20) < 15 ? 0 : (NextItemId % 20) < 18 ? 1 : 2));
10082 RequestSort = true;
10083 }
10084 void ClearItems()
10085 {
10086 Items.clear();
10087 Selection.Clear();
10088 }
10089
10090 // Logic would be written in the main code BeginChild() and outputing to local variables.
10091 // We extracted it into a function so we can call it easily from multiple places.
10092 void UpdateLayoutSizes(float avail_width)
10093 {
10094 // Layout: when not stretching: allow extending into right-most spacing.
10095 LayoutItemSpacing = (float)IconSpacing;
10096 if (StretchSpacing == false)
10097 avail_width += floorf(LayoutItemSpacing * 0.5f);
10098
10099 // Layout: calculate number of icon per line and number of lines
10100 LayoutItemSize = ImVec2(floorf(IconSize), floorf(IconSize));
10101 LayoutColumnCount = IM_MAX((int)(avail_width / (LayoutItemSize.x + LayoutItemSpacing)), 1);
10102 LayoutLineCount = (Items.Size + LayoutColumnCount - 1) / LayoutColumnCount;
10103
10104 // Layout: when stretching: allocate remaining space to more spacing. Round before division, so item_spacing may be non-integer.
10105 if (StretchSpacing && LayoutColumnCount > 1)
10106 LayoutItemSpacing = floorf(avail_width - LayoutItemSize.x * LayoutColumnCount) / LayoutColumnCount;
10107
10108 LayoutItemStep = ImVec2(LayoutItemSize.x + LayoutItemSpacing, LayoutItemSize.y + LayoutItemSpacing);
10109 LayoutSelectableSpacing = IM_MAX(floorf(LayoutItemSpacing) - IconHitSpacing, 0.0f);
10110 LayoutOuterPadding = floorf(LayoutItemSpacing * 0.5f);
10111 }
10112
10113 void Draw(const char* title, bool* p_open)
10114 {
10115 ImGui::SetNextWindowSize(ImVec2(IconSize * 25, IconSize * 15), ImGuiCond_FirstUseEver);
10116 if (!ImGui::Begin(title, p_open, ImGuiWindowFlags_MenuBar))
10117 {
10118 ImGui::End();
10119 return;
10120 }
10121
10122 // Menu bar
10123 if (ImGui::BeginMenuBar())
10124 {
10125 if (ImGui::BeginMenu("File"))
10126 {
10127 if (ImGui::MenuItem("Add 10000 items"))
10128 AddItems(10000);
10129 if (ImGui::MenuItem("Clear items"))
10130 ClearItems();
10131 ImGui::Separator();
10132 if (ImGui::MenuItem("Close", NULL, false, p_open != NULL))
10133 *p_open = false;
10134 ImGui::EndMenu();
10135 }
10136 if (ImGui::BeginMenu("Edit"))
10137 {
10138 if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0))
10139 RequestDelete = true;
10140 ImGui::EndMenu();
10141 }
10142 if (ImGui::BeginMenu("Options"))
10143 {
10144 ImGui::PushItemWidth(ImGui::GetFontSize() * 10);
10145
10146 ImGui::SeparatorText("Contents");
10147 ImGui::Checkbox("Show Type Overlay", &ShowTypeOverlay);
10148 ImGui::Checkbox("Allow Sorting", &AllowSorting);
10149
10150 ImGui::SeparatorText("Selection Behavior");
10151 ImGui::Checkbox("Allow dragging unselected item", &AllowDragUnselected);
10152 ImGui::Checkbox("Allow box-selection", &AllowBoxSelect);
10153
10154 ImGui::SeparatorText("Layout");
10155 ImGui::SliderFloat("Icon Size", &IconSize, 16.0f, 128.0f, "%.0f");
10156 ImGui::SameLine(); HelpMarker("Use CTRL+Wheel to zoom");
10157 ImGui::SliderInt("Icon Spacing", &IconSpacing, 0, 32);
10158 ImGui::SliderInt("Icon Hit Spacing", &IconHitSpacing, 0, 32);
10159 ImGui::Checkbox("Stretch Spacing", &StretchSpacing);
10160 ImGui::PopItemWidth();
10161 ImGui::EndMenu();
10162 }
10163 ImGui::EndMenuBar();
10164 }
10165
10166 // Show a table with ONLY one header row to showcase the idea/possibility of using this to provide a sorting UI
10167 if (AllowSorting)
10168 {
10169 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
10170 ImGuiTableFlags table_flags_for_sort_specs = ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Borders;
10171 if (ImGui::BeginTable("for_sort_specs_only", 2, table_flags_for_sort_specs, ImVec2(0.0f, ImGui::GetFrameHeight())))
10172 {
10173 ImGui::TableSetupColumn("Index");
10174 ImGui::TableSetupColumn("Type");
10175 ImGui::TableHeadersRow();
10176 if (ImGuiTableSortSpecs* sort_specs = ImGui::TableGetSortSpecs())
10177 if (sort_specs->SpecsDirty || RequestSort)
10178 {
10179 ExampleAsset::SortWithSortSpecs(sort_specs, Items.Data, Items.Size);
10180 sort_specs->SpecsDirty = RequestSort = false;
10181 }
10182 ImGui::EndTable();
10183 }
10184 ImGui::PopStyleVar();
10185 }
10186
10187 ImGuiIO& io = ImGui::GetIO();
10188 ImGui::SetNextWindowContentSize(ImVec2(0.0f, LayoutOuterPadding + LayoutLineCount * (LayoutItemSize.y + LayoutItemSpacing)));
10189 if (ImGui::BeginChild("Assets", ImVec2(0.0f, -ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove))
10190 {
10191 ImDrawList* draw_list = ImGui::GetWindowDrawList();
10192
10193 const float avail_width = ImGui::GetContentRegionAvail().x;
10194 UpdateLayoutSizes(avail_width);
10195
10196 // Calculate and store start position.
10197 ImVec2 start_pos = ImGui::GetCursorScreenPos();
10198 start_pos = ImVec2(start_pos.x + LayoutOuterPadding, start_pos.y + LayoutOuterPadding);
10199 ImGui::SetCursorScreenPos(start_pos);
10200
10201 // Multi-select
10202 ImGuiMultiSelectFlags ms_flags = ImGuiMultiSelectFlags_ClearOnEscape | ImGuiMultiSelectFlags_ClearOnClickVoid;
10203
10204 // - Enable box-select (in 2D mode, so that changing box-select rectangle X1/X2 boundaries will affect clipped items)
10205 if (AllowBoxSelect)
10206 ms_flags |= ImGuiMultiSelectFlags_BoxSelect2d;
10207
10208 // - This feature allows dragging an unselected item without selecting it (rarely used)
10209 if (AllowDragUnselected)
10210 ms_flags |= ImGuiMultiSelectFlags_SelectOnClickRelease;
10211
10212 // - Enable keyboard wrapping on X axis
10213 // (FIXME-MULTISELECT: We haven't designed/exposed a general nav wrapping api yet, so this flag is provided as a courtesy to avoid doing:
10214 // ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX);
10215 // When we finish implementing a more general API for this, we will obsolete this flag in favor of the new system)
10216 ms_flags |= ImGuiMultiSelectFlags_NavWrapX;
10217
10218 ImGuiMultiSelectIO* ms_io = ImGui::BeginMultiSelect(ms_flags, Selection.Size, Items.Size);
10219
10220 // Use custom selection adapter: store ID in selection (recommended)
10221 Selection.UserData = this;
10222 Selection.AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage* self_, int idx) { ExampleAssetsBrowser* self = (ExampleAssetsBrowser*)self_->UserData; return self->Items[idx].ID; };
10223 Selection.ApplyRequests(ms_io);
10224
10225 const bool want_delete = (ImGui::Shortcut(ImGuiKey_Delete, ImGuiInputFlags_Repeat) && (Selection.Size > 0)) || RequestDelete;
10226 const int item_curr_idx_to_focus = want_delete ? Selection.ApplyDeletionPreLoop(ms_io, Items.Size) : -1;
10227 RequestDelete = false;
10228
10229 // Push LayoutSelectableSpacing (which is LayoutItemSpacing minus hit-spacing, if we decide to have hit gaps between items)
10230 // Altering style ItemSpacing may seem unnecessary as we position every items using SetCursorScreenPos()...
10231 // But it is necessary for two reasons:
10232 // - Selectables uses it by default to visually fill the space between two items.
10233 // - The vertical spacing would be measured by Clipper to calculate line height if we didn't provide it explicitly (here we do).
10234 ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(LayoutSelectableSpacing, LayoutSelectableSpacing));
10235
10236 // Rendering parameters
10237 const ImU32 icon_type_overlay_colors[3] = { 0, IM_COL32(200, 70, 70, 255), IM_COL32(70, 170, 70, 255) };
10238 const ImU32 icon_bg_color = ImGui::GetColorU32(IM_COL32(35, 35, 35, 220));
10239 const ImVec2 icon_type_overlay_size = ImVec2(4.0f, 4.0f);
10240 const bool display_label = (LayoutItemSize.x >= ImGui::CalcTextSize("999").x);
10241
10242 const int column_count = LayoutColumnCount;
10243 ImGuiListClipper clipper;
10244 clipper.Begin(LayoutLineCount, LayoutItemStep.y);
10245 if (item_curr_idx_to_focus != -1)
10246 clipper.IncludeItemByIndex(item_curr_idx_to_focus / column_count); // Ensure focused item line is not clipped.
10247 if (ms_io->RangeSrcItem != -1)
10248 clipper.IncludeItemByIndex((int)ms_io->RangeSrcItem / column_count); // Ensure RangeSrc item line is not clipped.
10249 while (clipper.Step())
10250 {
10251 for (int line_idx = clipper.DisplayStart; line_idx < clipper.DisplayEnd; line_idx++)
10252 {
10253 const int item_min_idx_for_current_line = line_idx * column_count;
10254 const int item_max_idx_for_current_line = IM_MIN((line_idx + 1) * column_count, Items.Size);
10255 for (int item_idx = item_min_idx_for_current_line; item_idx < item_max_idx_for_current_line; ++item_idx)
10256 {
10257 ExampleAsset* item_data = &Items[item_idx];
10258 ImGui::PushID((int)item_data->ID);
10259
10260 // Position item
10261 ImVec2 pos = ImVec2(start_pos.x + (item_idx % column_count) * LayoutItemStep.x, start_pos.y + line_idx * LayoutItemStep.y);
10262 ImGui::SetCursorScreenPos(pos);
10263
10264 ImGui::SetNextItemSelectionUserData(item_idx);
10265 bool item_is_selected = Selection.Contains((ImGuiID)item_data->ID);
10266 bool item_is_visible = ImGui::IsRectVisible(LayoutItemSize);
10267 ImGui::Selectable("", item_is_selected, ImGuiSelectableFlags_None, LayoutItemSize);
10268
10269 // Update our selection state immediately (without waiting for EndMultiSelect() requests)
10270 // because we use this to alter the color of our text/icon.
10271 if (ImGui::IsItemToggledSelection())
10272 item_is_selected = !item_is_selected;
10273
10274 // Focus (for after deletion)
10275 if (item_curr_idx_to_focus == item_idx)
10276 ImGui::SetKeyboardFocusHere(-1);
10277
10278 // Drag and drop
10279 if (ImGui::BeginDragDropSource())
10280 {
10281 // Create payload with full selection OR single unselected item.
10282 // (the later is only possible when using ImGuiMultiSelectFlags_SelectOnClickRelease)
10283 if (ImGui::GetDragDropPayload() == NULL)
10284 {
10285 ImVector<ImGuiID> payload_items;
10286 void* it = NULL;
10287 ImGuiID id = 0;
10288 if (!item_is_selected)
10289 payload_items.push_back(item_data->ID);
10290 else
10291 while (Selection.GetNextSelectedItem(&it, &id))
10292 payload_items.push_back(id);
10293 ImGui::SetDragDropPayload("ASSETS_BROWSER_ITEMS", payload_items.Data, (size_t)payload_items.size_in_bytes());
10294 }
10295
10296 // Display payload content in tooltip, by extracting it from the payload data
10297 // (we could read from selection, but it is more correct and reusable to read from payload)
10298 const ImGuiPayload* payload = ImGui::GetDragDropPayload();
10299 const int payload_count = (int)payload->DataSize / (int)sizeof(ImGuiID);
10300 ImGui::Text("%d assets", payload_count);
10301
10302 ImGui::EndDragDropSource();
10303 }
10304
10305 // Render icon (a real app would likely display an image/thumbnail here)
10306 // Because we use ImGuiMultiSelectFlags_BoxSelect2d, clipping vertical may occasionally be larger, so we coarse-clip our rendering as well.
10307 if (item_is_visible)
10308 {
10309 ImVec2 box_min(pos.x - 1, pos.y - 1);
10310 ImVec2 box_max(box_min.x + LayoutItemSize.x + 2, box_min.y + LayoutItemSize.y + 2); // Dubious
10311 draw_list->AddRectFilled(box_min, box_max, icon_bg_color); // Background color
10312 if (ShowTypeOverlay && item_data->Type != 0)
10313 {
10314 ImU32 type_col = icon_type_overlay_colors[item_data->Type % IM_ARRAYSIZE(icon_type_overlay_colors)];
10315 draw_list->AddRectFilled(ImVec2(box_max.x - 2 - icon_type_overlay_size.x, box_min.y + 2), ImVec2(box_max.x - 2, box_min.y + 2 + icon_type_overlay_size.y), type_col);
10316 }
10317 if (display_label)
10318 {
10319 ImU32 label_col = ImGui::GetColorU32(item_is_selected ? ImGuiCol_Text : ImGuiCol_TextDisabled);
10320 char label[32];
10321 sprintf(label, "%d", item_data->ID);
10322 draw_list->AddText(ImVec2(box_min.x, box_max.y - ImGui::GetFontSize()), label_col, label);
10323 }
10324 }
10325
10326 ImGui::PopID();
10327 }
10328 }
10329 }
10330 clipper.End();
10331 ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing
10332
10333 // Context menu
10334 if (ImGui::BeginPopupContextWindow())
10335 {
10336 ImGui::Text("Selection: %d items", Selection.Size);
10337 ImGui::Separator();
10338 if (ImGui::MenuItem("Delete", "Del", false, Selection.Size > 0))
10339 RequestDelete = true;
10340 ImGui::EndPopup();
10341 }
10342
10343 ms_io = ImGui::EndMultiSelect();
10344 Selection.ApplyRequests(ms_io);
10345 if (want_delete)
10346 Selection.ApplyDeletionPostLoop(ms_io, Items, item_curr_idx_to_focus);
10347
10348 // Zooming with CTRL+Wheel
10349 if (ImGui::IsWindowAppearing())
10350 ZoomWheelAccum = 0.0f;
10351 if (ImGui::IsWindowHovered() && io.MouseWheel != 0.0f && ImGui::IsKeyDown(ImGuiMod_Ctrl) && ImGui::IsAnyItemActive() == false)
10352 {
10353 ZoomWheelAccum += io.MouseWheel;
10354 if (fabsf(ZoomWheelAccum) >= 1.0f)
10355 {
10356 // Calculate hovered item index from mouse location
10357 // FIXME: Locking aiming on 'hovered_item_idx' (with a cool-down timer) would ensure zoom keeps on it.
10358 const float hovered_item_nx = (io.MousePos.x - start_pos.x + LayoutItemSpacing * 0.5f) / LayoutItemStep.x;
10359 const float hovered_item_ny = (io.MousePos.y - start_pos.y + LayoutItemSpacing * 0.5f) / LayoutItemStep.y;
10360 const int hovered_item_idx = ((int)hovered_item_ny * LayoutColumnCount) + (int)hovered_item_nx;
10361 //ImGui::SetTooltip("%f,%f -> item %d", hovered_item_nx, hovered_item_ny, hovered_item_idx); // Move those 4 lines in block above for easy debugging
10362
10363 // Zoom
10364 IconSize *= powf(1.1f, (float)(int)ZoomWheelAccum);
10365 IconSize = IM_CLAMP(IconSize, 16.0f, 128.0f);
10366 ZoomWheelAccum -= (int)ZoomWheelAccum;
10367 UpdateLayoutSizes(avail_width);
10368
10369 // Manipulate scroll to that we will land at the same Y location of currently hovered item.
10370 // - Calculate next frame position of item under mouse
10371 // - Set new scroll position to be used in next ImGui::BeginChild() call.
10372 float hovered_item_rel_pos_y = ((float)(hovered_item_idx / LayoutColumnCount) + fmodf(hovered_item_ny, 1.0f)) * LayoutItemStep.y;
10373 hovered_item_rel_pos_y += ImGui::GetStyle().WindowPadding.y;
10374 float mouse_local_y = io.MousePos.y - ImGui::GetWindowPos().y;
10375 ImGui::SetScrollY(hovered_item_rel_pos_y - mouse_local_y);
10376 }
10377 }
10378 }
10379 ImGui::EndChild();
10380
10381 ImGui::Text("Selected: %d/%d items", Selection.Size, Items.Size);
10382 ImGui::End();
10383 }
10384 };
10385
10386 void ShowExampleAppAssetsBrowser(bool* p_open)
10387 {
10388 IMGUI_DEMO_MARKER("Examples/Assets Browser");
10389 static ExampleAssetsBrowser assets_browser;
10390 assets_browser.Draw("Example: Assets Browser", p_open);
10391 }
10392
10393 // End of Demo code
10394 #else
10395
10396 void ImGui::ShowAboutWindow(bool*) {}
10397 void ImGui::ShowDemoWindow(bool*) {}
10398 void ImGui::ShowUserGuide() {}
10399 void ImGui::ShowStyleEditor(ImGuiStyle*) {}
10400 bool ImGui::ShowStyleSelector(const char* label) { return false; }
10401 void ImGui::ShowFontSelector(const char* label) {}
10402
10403 #endif
10404
10405 #endif // #ifndef IMGUI_DISABLE