forked from opencodewin/MediaEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgui_helper.cpp
3096 lines (2822 loc) · 105 KB
/
imgui_helper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//- Common Code For All Addons needed just to ease inclusion as separate files in user code ----------------------
#include <imgui.h>
#include <imgui_user.h>
#include "imgui_helper.h"
#include <errno.h>
#include <mutex>
#include <thread>
#include <sstream>
#include <iomanip>
#include <fcntl.h>
#include <unistd.h>
#ifdef _WIN32
#include <windows.h>
#include <winerror.h> // For SUCCEEDED macro
#include <shellapi.h> // ShellExecuteA(...) - Shell32.lib
#include <objbase.h> // CoInitializeEx(...) - ole32.lib
#include <shlobj.h> // For SHGetFolderPathW and various CSIDL "magic numbers"
#include <stringapiset.h> // For WideCharToMultiByte
#include <psapi.h>
#include "mman_win.h"
#if IMGUI_RENDERING_DX11
struct IUnknown;
#include <d3d11.h>
#elif IMGUI_RENDERING_DX9
#include <d3d9.h>
#endif
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#define PATH_SETTINGS "\\AppData\\Roaming\\"
#else //_WIN32
#include <unistd.h>
#include <stdlib.h> // system
#include <pwd.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <sys/mman.h>
#endif //_WIN32
#if defined(__APPLE__)
#define PATH_SETTINGS "/Library/Application Support/"
#include <mach/task.h>
#include <mach/mach_init.h>
#include <mach-o/dyld.h>
#elif defined(__linux__)
#include <sys/sysinfo.h>
#define PATH_SETTINGS "/.config/"
#endif
#if defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#define PATH_SETTINGS "/.config/"
#endif
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#if !defined(alloca)
# if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__)
# include <alloca.h> // alloca (glibc uses <alloca.h>. Note that Cygwin may have _WIN32 defined, so the order matters here)
# elif defined(_WIN32)
# include <malloc.h> // alloca
# if !defined(alloca)
# define alloca _alloca // for clang with MS Codegen
# endif //alloca
# elif defined(__GLIBC__) || defined(__sun)
# include <alloca.h> // alloca
# else
# include <stdlib.h> // alloca
# endif
#endif //alloca
#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || \
defined(__WIN64__) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
#define stat _stat
#define stricmp _stricmp
#include <cctype>
// this option need c++17
// Modify By Dicky
#include <Windows.h>
#include <dirent_portable.h> // directly open the dirent file attached to this lib
// Modify By Dicky end
#define PATH_SEP '\\'
#ifndef PATH_MAX
#define PATH_MAX 260
#endif // PATH_MAX
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) || \
defined(__NetBSD__) || defined(__APPLE__) || defined (__EMSCRIPTEN__)
#define stricmp strcasecmp
#include <sys/types.h>
// this option need c++17
#ifndef USE_STD_FILESYSTEM
#include <dirent.h>
#endif // USE_STD_FILESYSTEM
#define PATH_SEP '/'
#endif
#if IMGUI_RENDERING_GL3
#include <imgui_impl_opengl3.h>
#elif IMGUI_RENDERING_GL2
#include <imgui_impl_opengl2.h>
#elif IMGUI_RENDERING_VULKAN
#include <imgui_impl_vulkan.h>
#endif
namespace ImGui {
// ImGui Info
void ShowImGuiInfo()
{
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
ImGui::Text("define: __cplusplus = %d", (int)__cplusplus);
ImGui::Separator();
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_FILE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS");
#endif
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
ImGui::Text("define: IMGUI_USE_BGRA_PACKED_COLOR");
#endif
#ifdef _WIN32
ImGui::Text("define: _WIN32");
#endif
#ifdef _WIN64
ImGui::Text("define: _WIN64");
#endif
#ifdef __linux__
ImGui::Text("define: __linux__");
#endif
#ifdef __APPLE__
ImGui::Text("define: __APPLE__");
#endif
#ifdef _MSC_VER
ImGui::Text("define: _MSC_VER=%d", _MSC_VER);
#endif
#ifdef _MSVC_LANG
ImGui::Text("define: _MSVC_LANG=%d", (int)_MSVC_LANG);
#endif
#ifdef __MINGW32__
ImGui::Text("define: __MINGW32__");
#endif
#ifdef __MINGW64__
ImGui::Text("define: __MINGW64__");
#endif
#ifdef __GNUC__
ImGui::Text("define: __GNUC__ = %d", (int)__GNUC__);
#endif
#ifdef __clang_version__
ImGui::Text("define: __clang_version__ = %s", __clang_version__);
#endif
ImGui::Separator();
ImGui::Text("Backend Platform Name: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL");
ImGui::Text("Backend Renderer Name: %s", io.BackendRendererName ? io.BackendRendererName : "NULL");
#if IMGUI_RENDERING_VULKAN
ImGui::Text("Backend GPU: %s", ImGui_ImplVulkan_GetDeviceName().c_str());
ImGui::Text("Backend Vulkan API: %s", ImGui_ImplVulkan_GetApiVersion().c_str());
ImGui::Text("Backend Vulkan Drv: %s", ImGui_ImplVulkan_GetDrvVersion().c_str());
ImGui::Separator();
#elif IMGUI_OPENGL
#if IMGUI_RENDERING_GL3
ImGui::Text("Gl Loader: %s", ImGui_ImplOpenGL3_GLLoaderName().c_str());
ImGui::Text("GL Version: %s", ImGui_ImplOpenGL3_GetVerion().c_str());
#elif IMGUI_RENDERING_GL2
ImGui::Text("Gl Loader: %s", ImGui_ImplOpenGL2_GLLoaderName().c_str());
ImGui::Text("GL Version: %s", ImGui_ImplOpenGL2_GetVerion().c_str());
#endif
#endif
ImGui::Text("Flash Timer: %.1f", io.ConfigMemoryCompactTimer >= 0.0f ? io.ConfigMemoryCompactTimer : 0);
ImGui::Separator();
ImGui::Text("Fonts: %d fonts", io.Fonts->Fonts.Size);
ImGui::Text("Texure Size: %d x %d", io.Fonts->TexWidth, io.Fonts->TexHeight);
ImGui::Text("Display Size: %.2f x %.2f", io.DisplaySize.x, io.DisplaySize.y);
ImGui::Text("Display Framebuffer Scale: %.2f %.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
}
bool OpenWithDefaultApplication(const char* url,bool exploreModeForWindowsOS)
{
# ifdef _WIN32
//CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); // Needed ??? Well, let's suppose the user initializes it himself for now"
return ((size_t)ShellExecuteA( NULL, exploreModeForWindowsOS ? "explore" : "open", url, "", ".", SW_SHOWNORMAL ))>32;
# else //_WIN32
if (exploreModeForWindowsOS) exploreModeForWindowsOS = false; // No warnings
char tmp[4096];
const char* openPrograms[]={"xdg-open","gnome-open"}; // Not sure what can I append here for MacOS
static int openProgramIndex=-2;
if (openProgramIndex==-2) {
openProgramIndex=-1;
for (size_t i=0,sz=sizeof(openPrograms)/sizeof(openPrograms[0]);i<sz;i++) {
strcpy(tmp,"/usr/bin/"); // Well, we should check all the folders inside $PATH... and we ASSUME that /usr/bin IS inside $PATH (see below)
strcat(tmp,openPrograms[i]);
FILE* fd = (FILE *)ImFileOpen(tmp,"r");
if (fd) {
fclose(fd);
openProgramIndex = (int)i;
//printf(stderr,"found %s\n",tmp);
break;
}
}
}
// Note that here we strip the prefix "/usr/bin" and just use openPrograms[openProgramsIndex].
// Also note that if nothing has been found we use "xdg-open" (that might still work if it exists in $PATH, but not in /usr/bin).
strcpy(tmp,openPrograms[openProgramIndex<0?0:openProgramIndex]);
strcat(tmp," \"");
strcat(tmp,url);
strcat(tmp,"\"");
return system(tmp)==0;
# endif //_WIN32
}
void CloseAllPopupMenus() {
ImGuiContext& g = *GImGui;
while (g.OpenPopupStack.size() > 0) g.OpenPopupStack.pop_back();
}
// Posted by Omar in one post. It might turn useful...
bool IsItemActiveLastFrame() {
ImGuiContext& g = *GImGui;
if (g.ActiveIdPreviousFrame)
return g.ActiveIdPreviousFrame== g.LastItemData.ID;
return false;
}
bool IsItemJustReleased() {
return IsItemActiveLastFrame() && !ImGui::IsItemActive();
}
bool IsItemDisabled() {
ImGuiContext& g = *GImGui;
return (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == ImGuiItemFlags_Disabled;
}
void Debug_DrawItemRect(const ImVec4& col)
{
auto drawList = ImGui::GetWindowDrawList();
auto itemMin = ImGui::GetItemRectMin();
auto itemMax = ImGui::GetItemRectMax();
drawList->AddRect(itemMin, itemMax, ImColor(col));
}
const ImFont *GetFont(int fntIndex) {return (fntIndex>=0 && fntIndex<ImGui::GetIO().Fonts->Fonts.size()) ? ImGui::GetIO().Fonts->Fonts[fntIndex] : NULL;}
void PushFont(int fntIndex) {
IM_ASSERT(fntIndex>=0 && fntIndex<ImGui::GetIO().Fonts->Fonts.size());
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[fntIndex]);
}
void TextColoredV(int fntIndex, const ImVec4 &col, const char *fmt, va_list args) {
ImGui::PushFont(fntIndex);
ImGui::TextColoredV(col,fmt, args);
ImGui::PopFont();
}
void TextColored(int fntIndex, const ImVec4 &col, const char *fmt,...) {
va_list args;
va_start(args, fmt);
TextColoredV(fntIndex,col, fmt, args);
va_end(args);
}
void TextV(int fntIndex, const char *fmt, va_list args) {
if (ImGui::GetCurrentWindow()->SkipItems) return;
ImGuiContext& g = *GImGui;
const char* text, *text_end;
ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
ImGui::PushFont(fntIndex);
TextUnformatted(text, text_end);
ImGui::PopFont();
}
void Text(int fntIndex, const char *fmt,...) {
va_list args;
va_start(args, fmt);
TextV(fntIndex,fmt, args);
va_end(args);
}
bool GetTexCoordsFromGlyph(unsigned short glyph, ImVec2 &uv0, ImVec2 &uv1)
{
if (!GImGui->Font) return false;
const ImFontGlyph* g = GImGui->Font->FindGlyph(glyph);
if (g) {
uv0.x = g->U0; uv0.y = g->V0;
uv1.x = g->U1; uv1.y = g->V1;
return true;
}
return false;
}
float CalcMainMenuHeight()
{
// Warning: according to https://github.com/ocornut/imgui/issues/252 this approach can fail [Better call ImGui::GetWindowSize().y from inside the menu and store the result somewhere]
if (GImGui->FontBaseSize>0) return GImGui->FontBaseSize + GImGui->Style.FramePadding.y * 2.0f;
else {
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
ImFont* font = ImGui::GetFont();
if (!font) {
if (io.Fonts->Fonts.size()>0) font = io.Fonts->Fonts[0];
else return (14)+style.FramePadding.y * 2.0f;
}
return (io.FontGlobalScale * font->Scale * font->FontSize) + style.FramePadding.y * 2.0f;
}
}
void RenderMouseCursor(const char* mouse_cursor, ImVec2 offset, float base_scale, float rotate, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
{
ImGuiViewportP* viewport = (ImGuiViewportP*)ImGui::GetWindowViewport();
ImDrawList* draw_list = ImGui::GetForegroundDrawList(viewport);
ImGuiIO& io = ImGui::GetIO();
const float FontSize = draw_list->_Data->FontSize;
ImVec2 size(FontSize, FontSize);
const ImVec2 pos = io.MousePos - offset;
const float scale = base_scale * viewport->DpiScale;
if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
return;
ImGui::SetMouseCursor(ImGuiMouseCursor_None);
int rotation_start_index = draw_list->VtxBuffer.Size;
draw_list->AddText(pos + ImVec2(-1, -1), col_border, mouse_cursor);
draw_list->AddText(pos + ImVec2(1, 1), col_shadow, mouse_cursor);
draw_list->AddText(pos, col_fill, mouse_cursor);
if (rotate != 0.f)
{
float rad = M_PI / 180 * (90 - rotate);
ImVec2 l(FLT_MAX, FLT_MAX), u(-FLT_MAX, -FLT_MAX); // bounds
auto& buf = draw_list->VtxBuffer;
float s = sin(rad), c = cos(rad);
for (int i = rotation_start_index; i < buf.Size; i++)
l = ImMin(l, buf[i].pos), u = ImMax(u, buf[i].pos);
ImVec2 center = ImVec2((l.x + u.x) / 2, (l.y + u.y) / 2);
center = ImRotate(center, s, c) - center;
for (int i = rotation_start_index; i < buf.Size; i++)
buf[i].pos = ImRotate(buf[i].pos, s, c) - center;
}
}
// These two methods are inspired by imguidock.cpp
void PutInBackground(const char* optionalRootWindowName)
{
ImGuiWindow* w = optionalRootWindowName ? FindWindowByName(optionalRootWindowName) : GetCurrentWindow();
if (!w) return;
ImGuiContext& g = *GImGui;
if (g.Windows[0] == w) return;
const int isz = g.Windows.Size;
for (int i = 0; i < isz; i++)
{
if (g.Windows[i] == w)
{
for (int j = i; j > 0; --j) g.Windows[j] = g.Windows[j-1]; // shifts [0,j-1] to [1,j]
g.Windows[0] = w;
break;
}
}
}
void PutInForeground(const char* optionalRootWindowName)
{
ImGuiWindow* w = optionalRootWindowName ? FindWindowByName(optionalRootWindowName) : GetCurrentWindow();
if (!w) return;
ImGuiContext& g = *GImGui;
const int iszMinusOne = g.Windows.Size - 1;
if (iszMinusOne<0 || g.Windows[iszMinusOne] == w) return;
for (int i = iszMinusOne; i >= 0; --i)
{
if (g.Windows[i] == w)
{
for (int j = i; j < iszMinusOne; j++) g.Windows[j] = g.Windows[j+1]; // shifts [i+1,iszMinusOne] to [i,iszMinusOne-1]
g.Windows[iszMinusOne] = w;
break;
}
}
}
ScopedItemWidth::ScopedItemWidth(float width)
{
ImGui::PushItemWidth(width);
}
ScopedItemWidth::~ScopedItemWidth()
{
Release();
}
void ScopedItemWidth::Release()
{
if (m_IsDone)
return;
ImGui::PopItemWidth();
m_IsDone = true;
}
ScopedDisableItem::ScopedDisableItem(bool disable, float disabledAlpha)
: m_Disable(disable)
{
if (!m_Disable)
return;
ImGuiContext& g = *GImGui;
auto wasDisabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == ImGuiItemFlags_Disabled;
ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
auto& stale = ImGui::GetStyle();
m_LastAlpha = stale.Alpha;
// Don't override alpha if we're already in disabled context.
if (!wasDisabled)
stale.Alpha = disabledAlpha;
}
ScopedDisableItem::~ScopedDisableItem()
{
Release();
}
void ScopedDisableItem::Release()
{
if (!m_Disable)
return;
auto& stale = ImGui::GetStyle();
stale.Alpha = m_LastAlpha;
ImGui::PopItemFlag();
m_Disable = false;
}
ScopedSuspendLayout::ScopedSuspendLayout()
{
m_Window = ImGui::GetCurrentWindow();
m_CursorPos = m_Window->DC.CursorPos;
m_CursorPosPrevLine = m_Window->DC.CursorPosPrevLine;
m_CursorMaxPos = m_Window->DC.CursorMaxPos;
m_CurrLineSize = m_Window->DC.CurrLineSize;
m_PrevLineSize = m_Window->DC.PrevLineSize;
m_CurrLineTextBaseOffset = m_Window->DC.CurrLineTextBaseOffset;
m_PrevLineTextBaseOffset = m_Window->DC.PrevLineTextBaseOffset;
}
ScopedSuspendLayout::~ScopedSuspendLayout()
{
Release();
}
void ScopedSuspendLayout::Release()
{
if (m_Window == nullptr)
return;
m_Window->DC.CursorPos = m_CursorPos;
m_Window->DC.CursorPosPrevLine = m_CursorPosPrevLine;
m_Window->DC.CursorMaxPos = m_CursorMaxPos;
m_Window->DC.CurrLineSize = m_CurrLineSize;
m_Window->DC.PrevLineSize = m_PrevLineSize;
m_Window->DC.CurrLineTextBaseOffset = m_CurrLineTextBaseOffset;
m_Window->DC.PrevLineTextBaseOffset = m_PrevLineTextBaseOffset;
m_Window = nullptr;
}
ItemBackgroundRenderer::ItemBackgroundRenderer(OnDrawCallback onDrawBackground)
: m_OnDrawBackground(std::move(onDrawBackground))
{
m_DrawList = ImGui::GetWindowDrawList();
m_Splitter.Split(m_DrawList, 2);
m_Splitter.SetCurrentChannel(m_DrawList, 1);
}
ItemBackgroundRenderer::~ItemBackgroundRenderer()
{
Commit();
}
void ItemBackgroundRenderer::Commit()
{
if (m_Splitter._Current == 0)
return;
m_Splitter.SetCurrentChannel(m_DrawList, 0);
if (m_OnDrawBackground)
m_OnDrawBackground(m_DrawList);
m_Splitter.Merge(m_DrawList);
}
void ItemBackgroundRenderer::Discard()
{
if (m_Splitter._Current == 1)
m_Splitter.Merge(m_DrawList);
}
StorageHandler<MostRecentlyUsedList::Settings> MostRecentlyUsedList::s_Storage;
void MostRecentlyUsedList::Install(ImGuiContext* context)
{
context->SettingsHandlers.push_back(s_Storage.MakeHandler("MostRecentlyUsedList"));
s_Storage.ReadLine = [](ImGuiContext*, Settings* entry, const char* line)
{
const char* lineEnd = line + strlen(line);
auto parseListEntry = [lineEnd](const char* line, int& index) -> const char*
{
char* indexEnd = nullptr;
errno = 0;
index = strtol(line, &indexEnd, 10);
if (errno == ERANGE)
return nullptr;
if (indexEnd >= lineEnd)
return nullptr;
if (*indexEnd != '=')
return nullptr;
return indexEnd + 1;
};
int index = 0;
if (auto path = parseListEntry(line, index))
{
if (static_cast<int>(entry->m_List.size()) <= index)
entry->m_List.resize(index + 1);
entry->m_List[index] = path;
}
};
s_Storage.WriteAll = [](ImGuiContext*, ImGuiTextBuffer* out_buf, const StorageHandler<Settings>::Storage& storage)
{
for (auto& entry : storage)
{
out_buf->appendf("[%s][##%s]\n", "MostRecentlyUsedList", entry.first.c_str());
int index = 0;
for (auto& value : entry.second->m_List)
out_buf->appendf("%d=%s\n", index++, value.c_str());
out_buf->append("\n");
}
};
}
MostRecentlyUsedList::MostRecentlyUsedList(const char* id, int capacity /*= 10*/)
: m_ID(id)
, m_Capacity(capacity)
, m_List(s_Storage.FindOrCreate(id)->m_List)
{
}
void MostRecentlyUsedList::Add(const std::string& item)
{
Add(item.c_str());
}
void MostRecentlyUsedList::Add(const char* item)
{
auto itemIt = std::find(m_List.begin(), m_List.end(), item);
if (itemIt != m_List.end())
{
// Item is already on the list. Rotate list to move it to the
// first place.
std::rotate(m_List.begin(), itemIt, itemIt + 1);
}
else
{
// Push new item to the back, rotate list to move it to the front,
// pop back last element if we're over capacity.
m_List.push_back(item);
std::rotate(m_List.begin(), m_List.end() - 1, m_List.end());
if (static_cast<int>(m_List.size()) > m_Capacity)
m_List.pop_back();
}
PushToStorage();
ImGui::MarkIniSettingsDirty();
}
void MostRecentlyUsedList::Clear()
{
if (m_List.empty())
return;
m_List.resize(0);
PushToStorage();
ImGui::MarkIniSettingsDirty();
}
const std::vector<std::string>& MostRecentlyUsedList::GetList() const
{
return m_List;
}
int MostRecentlyUsedList::Size() const
{
return static_cast<int>(m_List.size());
}
void MostRecentlyUsedList::PullFromStorage()
{
if (auto settings = s_Storage.Find(m_ID.c_str()))
m_List = settings->m_List;
}
void MostRecentlyUsedList::PushToStorage()
{
auto settings = s_Storage.FindOrCreate(m_ID.c_str());
settings->m_List = m_List;
}
void Grid::Begin(const char* id, int columns, float width)
{
Begin(ImGui::GetID(id), columns, width);
}
void Grid::Begin(ImU32 id, int columns, float width)
{
m_CursorPos = ImGui::GetCursorScreenPos();
ImGui::PushID(id);
m_Columns = ImMax(1, columns);
m_Storage = ImGui::GetStateStorage();
for (int i = 0; i < columns; ++i)
{
ImGui::PushID(ColumnSeed());
m_Storage->SetFloat(ImGui::GetID("MaximumColumnWidthAcc"), -1.0f);
ImGui::PopID();
}
m_ColumnAlignment = 0.0f;
m_MinimumWidth = width;
ImGui::BeginGroup();
EnterCell(0, 0);
}
void Grid::NextColumn(bool keep_max)
{
LeaveCell(keep_max);
int nextColumn = m_Column + 1;
int nextRow = 0;
if (nextColumn > m_Columns)
{
nextColumn -= m_Columns;
nextRow += 1;
}
auto cursorPos = m_CursorPos;
for (int i = 0; i < nextColumn; ++i)
{
ImGui::PushID(ColumnSeed(i));
auto maximumColumnWidth = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidth"), -1.0f);
ImGui::PopID();
if (maximumColumnWidth > 0.0f)
cursorPos.x += maximumColumnWidth + ImGui::GetStyle().ItemSpacing.x;
}
ImGui::SetCursorScreenPos(cursorPos);
EnterCell(nextColumn, nextRow);
}
void Grid::NextRow()
{
LeaveCell();
auto cursorPos = ImGui::GetCursorScreenPos();
cursorPos.x = m_CursorPos.x;
for (int i = 0; i < m_Column; ++i)
{
ImGui::PushID(ColumnSeed(i));
auto maximumColumnWidth = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidth"), -1.0f);
ImGui::PopID();
if (maximumColumnWidth > 0.0f)
cursorPos.x += maximumColumnWidth + ImGui::GetStyle().ItemSpacing.x;
}
ImGui::SetCursorScreenPos(cursorPos);
EnterCell(m_Column, m_Row + 1);
}
void Grid::EnterCell(int column, int row)
{
m_Column = column;
m_Row = row;
ImGui::PushID(ColumnSeed());
m_MaximumColumnWidthAcc = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidthAcc"), -1.0f);
auto maximumColumnWidth = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidth"), -1.0f);
ImGui::PopID();
ImGui::PushID(Seed());
auto lastCellWidth = m_Storage->GetFloat(ImGui::GetID("LastCellWidth"), -1.0f);
if (maximumColumnWidth >= 0.0f && lastCellWidth >= 0.0f)
{
auto freeSpace = maximumColumnWidth - lastCellWidth;
auto offset = ImFloor(m_ColumnAlignment * freeSpace);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
ImGui::Dummy(ImVec2(offset, 0.0f));
ImGui::SameLine(0.0f, 0.0f);
ImGui::PopStyleVar();
}
ImGui::BeginGroup();
}
void Grid::LeaveCell(bool keep_max)
{
ImGui::EndGroup();
auto itemSize = ImGui::GetItemRectSize();
m_Storage->SetFloat(ImGui::GetID("LastCellWidth"), itemSize.x);
ImGui::PopID();
m_MaximumColumnWidthAcc = keep_max ? ImMax(m_MaximumColumnWidthAcc, itemSize.x) : itemSize.x;
ImGui::PushID(ColumnSeed());
m_Storage->SetFloat(ImGui::GetID("MaximumColumnWidthAcc"), m_MaximumColumnWidthAcc);
ImGui::PopID();
}
void Grid::SetColumnAlignment(float alignment)
{
alignment = ImClamp(alignment, 0.0f, 1.0f);
m_ColumnAlignment = alignment;
}
void Grid::End()
{
LeaveCell();
ImGui::EndGroup();
float totalWidth = 0.0f;
for (int i = 0; i < m_Columns; ++i)
{
ImGui::PushID(ColumnSeed(i));
auto currentMaxCellWidth = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidthAcc"), -1.0f);
totalWidth += currentMaxCellWidth;
m_Storage->SetFloat(ImGui::GetID("MaximumColumnWidth"), currentMaxCellWidth);
ImGui::PopID();
}
if (totalWidth < m_MinimumWidth)
{
auto spaceToDivide = m_MinimumWidth - totalWidth;
auto spacePerColumn = ImCeil(spaceToDivide / m_Columns);
for (int i = 0; i < m_Columns; ++i)
{
ImGui::PushID(ColumnSeed(i));
auto columnWidth = m_Storage->GetFloat(ImGui::GetID("MaximumColumnWidth"), -1.0f);
columnWidth += spacePerColumn;
m_Storage->SetFloat(ImGui::GetID("MaximumColumnWidth"), columnWidth);
ImGui::PopID();
spaceToDivide -= spacePerColumn;
if (spaceToDivide < 0)
spacePerColumn += spaceToDivide;
}
}
ImGui::PopID();
}
} // namespace Imgui
#include <stdio.h> // FILE
namespace ImGuiHelper
{
static const char* FieldTypeNames[ImGui::FT_COUNT+1] = {"INT","UNSIGNED","FLOAT","DOUBLE","STRING","ENUM","BOOL","COLOR","TEXTLINE","CUSTOM","COUNT"};
static const char* FieldTypeFormats[ImGui::FT_COUNT]={"%d","%u","%f","%f","%s","%d","%d","%f","%s","%s"};
static const char* FieldTypeFormatsWithCustomPrecision[ImGui::FT_COUNT]={"%.*d","%*u","%.*f","%.*f","%*s","%*d","%*d","%.*f","%*s","%*s"};
void Deserializer::clear()
{
if (f_data) ImGui::MemFree(f_data);
f_data = NULL;f_size=0;
}
bool Deserializer::loadFromFile(const char *filename)
{
clear();
if (!filename) return false;
FILE* f;
if ((f = (FILE *)ImFileOpen(filename, "rt")) == NULL) return false;
if (fseek(f, 0, SEEK_END))
{
fclose(f);
return false;
}
const long f_size_signed = ftell(f);
if (f_size_signed == -1)
{
fclose(f);
return false;
}
f_size = (size_t)f_size_signed;
if (fseek(f, 0, SEEK_SET))
{
fclose(f);
return false;
}
f_data = (char*)ImGui::MemAlloc(f_size+1);
f_size = fread(f_data, 1, f_size, f); // Text conversion alter read size so let's not be fussy about return value
fclose(f);
if (f_size == 0)
{
clear();
return false;
}
f_data[f_size] = 0;
++f_size;
return true;
}
bool Deserializer::allocate(size_t sizeToAllocate, const char *optionalTextToCopy, size_t optionalTextToCopySize)
{
clear();
if (sizeToAllocate==0) return false;
f_size = sizeToAllocate;
f_data = (char*)ImGui::MemAlloc(f_size);
if (!f_data) {clear();return false;}
if (optionalTextToCopy && optionalTextToCopySize>0) memcpy(f_data,optionalTextToCopy,optionalTextToCopySize>f_size ? f_size:optionalTextToCopySize);
return true;
}
Deserializer::Deserializer(const char *filename) : f_data(NULL),f_size(0)
{
if (filename) loadFromFile(filename);
}
Deserializer::Deserializer(const char *text, size_t textSizeInBytes) : f_data(NULL),f_size(0)
{
allocate(textSizeInBytes,text,textSizeInBytes);
}
const char* Deserializer::parse(Deserializer::ParseCallback cb, void *userPtr, const char *optionalBufferStart) const
{
if (!cb || !f_data || f_size==0) return NULL;
//------------------------------------------------
// Parse file in memory
char name[128];name[0]='\0';
char typeName[32];char format[32]="";bool quitParsing = false;
char charBuffer[sizeof(double)*10];void* voidBuffer = (void*) &charBuffer[0];
static char textBuffer[2050];
const char* varName = NULL;int numArrayElements = 0;FieldType ft = ImGui::FT_COUNT;
const char* buf_end = f_data + f_size-1;
for (const char* line_start = optionalBufferStart ? optionalBufferStart : f_data; line_start < buf_end; )
{
const char* line_end = line_start;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++;
if (name[0]=='\0' && line_start[0] == '[' && line_end > line_start && line_end[-1] == ']')
{
ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1);
//fprintf(stderr,"name: %s\n",name); // dbg
// Here we have something like: FLOAT-4:VariableName
// We have to split into FLOAT 4 VariableName
varName = NULL;numArrayElements = 0;ft = ImGui::FT_COUNT;format[0]='\0';
const char* colonCh = strchr(name,':');
const char* minusCh = strchr(name,'-');
if (!colonCh)
{
fprintf(stderr,"ImGuiHelper::Deserializer::parse(...) warning (skipping line with no semicolon). name: %s\n",name); // dbg
name[0]='\0';
}
else
{
ptrdiff_t diff = 0,diff2 = 0;
if (!minusCh || (minusCh-colonCh)>0) {diff = (colonCh-name);numArrayElements=1;}
else
{
diff = (minusCh-name);
diff2 = colonCh-minusCh;
if (diff2>1 && diff2<7)
{
static char buff[8];
strncpy(&buff[0],(const char*) &minusCh[1],diff2);buff[diff2-1]='\0';
sscanf(buff,"%d",&numArrayElements);
//fprintf(stderr,"WARN: %s\n",buff);
}
else if (diff>0) numArrayElements = ((char)name[diff+1]-(char)'0'); // TODO: FT_STRING needs multibytes -> rewrite!
}
if (diff>0)
{
const size_t len = (size_t)(diff>31?31:diff);
strncpy(typeName,name,len);typeName[len]='\0';
for (int t=0;t<=ImGui::FT_COUNT;t++)
{
if (strcmp(typeName,FieldTypeNames[t])==0)
{
ft = (FieldType) t;break;
}
}
varName = ++colonCh;
const bool isTextOrCustomType = ft==ImGui::FT_STRING || ft==ImGui::FT_TEXTLINE || ft==ImGui::FT_CUSTOM;
if (ft==ImGui::FT_COUNT || numArrayElements<1 || (numArrayElements>4 && !isTextOrCustomType))
{
fprintf(stderr,"ImGuiHelper::Deserializer::parse(...) Error (wrong type detected): line:%s type:%d numArrayElements:%d varName:%s typeName:%s\n",name,(int)ft,numArrayElements,varName,typeName);
varName=NULL;
}
else
{
if (ft==ImGui::FT_STRING && varName && varName[0]!='\0')
{
if (numArrayElements==1 && (!minusCh || (minusCh-colonCh)>0))
{
numArrayElements=0; // NEW! To handle blank strings ""
}
//Process soon here, as the string can be multiline
line_start = ++line_end;
//--------------------------------------------------------
int cnt = 0;
while (line_end < buf_end && cnt++ < numArrayElements-1) ++line_end;
textBuffer[0]=textBuffer[2049]='\0';
const int maxLen = numArrayElements>0 ? (cnt>2049?2049:cnt) : 0;
strncpy(textBuffer,line_start,maxLen+1);
textBuffer[maxLen]='\0';
quitParsing = cb(ft,numArrayElements,(void*)textBuffer,varName,userPtr);
//fprintf(stderr,"Deserializer::parse(...) value:\"%s\" to type:%d numArrayElements:%d varName:%s maxLen:%d\n",textBuffer,(int)ft,numArrayElements,varName,maxLen); // dbg
//else fprintf(stderr,"Deserializer::parse(...) Error converting value:\"%s\" to type:%d numArrayElements:%d varName:%s\n",line_start,(int)ft,numArrayElements,varName); // dbg
//--------------------------------------------------------
ft = ImGui::FT_COUNT;name[0]='\0';varName=NULL; // mandatory
}
else if (!isTextOrCustomType)
{
format[0]='\0';
for (int t=0;t<numArrayElements;t++)
{
if (t>0) strcat(format," ");
strcat(format,FieldTypeFormats[ft]);
}
// DBG:
//fprintf(stderr,"Deserializer::parse(...) DBG: line:%s type:%d numArrayElements:%d varName:%s format:%s\n",name,(int)ft,numArrayElements,varName,format); // dbg
}
}
}
}
}
else if (varName && varName[0]!='\0')
{
switch (ft)
{
case ImGui::FT_FLOAT:
case ImGui::FT_COLOR:
{
float* p = (float*) voidBuffer;
if ((numArrayElements==1 && sscanf(line_start, format, p)==numArrayElements) ||
(numArrayElements==2 && sscanf(line_start, format, &p[0],&p[1])==numArrayElements) ||
(numArrayElements==3 && sscanf(line_start, format, &p[0],&p[1],&p[2])==numArrayElements) ||
(numArrayElements==4 && sscanf(line_start, format, &p[0],&p[1],&p[2],&p[3])==numArrayElements))
quitParsing = cb(ft,numArrayElements,voidBuffer,varName,userPtr);
else fprintf(stderr,"Deserializer::parse(...) Error converting value:\"%s\" to type:%d numArrayElements:%d varName:%s\n",line_start,(int)ft,numArrayElements,varName); // dbg
}
break;
case ImGui::FT_DOUBLE:
{
double* p = (double*) voidBuffer;
if ((numArrayElements==1 && sscanf(line_start, format, p)==numArrayElements) ||
(numArrayElements==2 && sscanf(line_start, format, &p[0],&p[1])==numArrayElements) ||
(numArrayElements==3 && sscanf(line_start, format, &p[0],&p[1],&p[2])==numArrayElements) ||
(numArrayElements==4 && sscanf(line_start, format, &p[0],&p[1],&p[2],&p[3])==numArrayElements))