-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
2562 lines (2092 loc) · 82.4 KB
/
main.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
#ifdef _WIN32
#include <Windows.h>
#include <tchar.h>
#endif
#include <iostream>
#include <chrono>
#include <fstream>
#include <cstring>
#include "serial.h"
#include "External/ImGui/imgui.h"
#include "External/ImGui/imgui_internal.h"
#include "structs.h"
#include "helperJson.h"
#include "constants.h"
#include "gui.h"
#include "Audio/Sound_Helper.h"
#include "External/ImGui/imgui_extensions.h"
#include <algorithm>
#include "helper.h"
using namespace helper;
ImVec2 detectionRectSize{ 0, 200 };
uint64_t lastFrameGui = 0;
uint64_t lastFrame = 0;
// Frametime in microseconds
float averageFrametime = 0;
const unsigned int AVERAGE_FRAME_COUNT = 1000;
uint64_t frames[AVERAGE_FRAME_COUNT]{ 0 };
unsigned long long totalFrames = 0;
bool AnalyzeData();
// ---- Functionality ----
SerialStatus serialStatus = Status_Idle;
int selectedPort = 0;
int lastSelectedPort = 0;
InputMode selectedMode = InputMode_Normal;
uint64_t lastInternalTest = 0;
bool isAudioDevConnected = false; // Input device
bool isPlaybackDevConnected = false; // Output device
std::vector<cAudioDeviceInfo> availableAudioDevices;
AudioProcessor audioProcessor([](){
AnalyzeData();
serialStatus = Status_Idle;
});
PaDeviceIndex selectedOutputAudioDeviceIdx = 0;
const UINT AUDIO_SAMPLE_RATE = REC_SAMPLE_RATE;//44100U;
//const UINT TEST_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 10;
//const UINT WARMUP_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 2;
//const UINT AUDIO_BUFFER_SIZE = WARMUP_AUDIO_BUFFER_SIZE + TEST_AUDIO_BUFFER_SIZE;
const UINT INTERNAL_TEST_DELAY = 1195387; // in microseconds
//#ifdef _WIN32
//const UINT AUDIO_SAMPLE_RATE = 10000;//44100U;
//const UINT TEST_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 10;
//const UINT WARMUP_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 2;
//const UINT AUDIO_BUFFER_SIZE = WARMUP_AUDIO_BUFFER_SIZE + TEST_AUDIO_BUFFER_SIZE;
//const UINT INTERNAL_TEST_DELAY = 1195387; // in microseconds
//#else
//UINT PLAYBACK_BUFFER_SIZE = 1000;
//UINT PLAYBACK_SAMPLE_RATE = 10000;
//ALSA_AudioDevice<short> audioPlayer(PLAYBACK_BUFFER_SIZE, PLAYBACK_SAMPLE_RATE);
//
//#define AUDIO_DATA_FORMAT int
//ALSA_RecDevice<AUDIO_DATA_FORMAT>* curAudioDevice;
//UINT AUDIO_SAMPLE_RATE = 44100;//44100;//44100U;
//UINT TEST_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 4;
//const UINT WARMUP_AUDIO_BUFFER_SIZE = AUDIO_SAMPLE_RATE / 2; // On Unix this isn't really a "buffer", but just a delay
//UINT AUDIO_BUFFER_SIZE = TEST_AUDIO_BUFFER_SIZE;
//const UINT INTERNAL_TEST_DELAY = 995387; // in microseconds
//#endif
std::chrono::steady_clock::time_point moddedMouseTimeClicked;
bool wasModdedMouseTimeUpdated = false;
// --------
//bool isSaved = true;
//char savePath[MAX_PATH]{ 0 };
bool isExiting = false;
std::vector<int> unsavedTabs;
bool isGameMode = false;
bool isInternalMode = false;
bool isAudioMode = false;
bool wasMeasurementAddedGUI = false;
bool shouldRunConfiguration = false;
float leftTabWidth = 400;
// Forward declarations
void GotSerialChar(char c);
void ClearData();
void DiscoverAudioDevices();
void StartInternalTest();
void AddMeasurement(UINT internalTime, UINT externalTime, UINT inputTime);
bool CanDoInternalTest(uint64_t time = 0);
bool SetupAudioDevice();
void AttemptConnect();
void AttemptDisconnect();
/*
TODO:
+ Add multiple fonts to chose from.
- Add a way to change background color (?)
+ Add the functionality...
+ Saving measurement records to a json file.
+ Open a window to select which save file you want to open
+ Better fullscreen implementation (ESCAPE to exit etc.)
+ Max Gui fps slider in settings
+ Load the font in earlier selected size (?)
+ Movable black Square for color detection (?) Check for any additional latency this might involve
+ Clear / Reset button
+ Game integration. Please don't get me banned again (needs testing) Update: (testing done)
+ Fix overwriting saves
+ Unsaved work notification
+ Unsaved tabs alert
- Custom Fonts (?)
+ Multiple tabs for measurements
+ Move IO to a separate thread (ONLY if it doesn't introduce additional latency)
+ Fix measurement index when removing (or don't, I don' know)
+ Reset status on disconnect and clear
+ Auto scroll measurements on new added
+ Changing tab name sets the status to unsaved
+ Fix too many tabs obscuring tabs beneath them
+ Check if ANY tab is unsaved when closing
+ Pack Save (Save all the tabs into a single file) (?)
+ Configuration Screen
+ Pack fonts into a byte array and load them that way.
- Add option to display frametime (?) [Should be something like (2/(framerate)) * 1000]
+ See what can be done about the inefficient Serial Comm code
- Inform user of all the available keyboard shortcuts
+ Clean-up the audio code
+ Handle unplugging audio devices mid test
- Arduino debug mode (print sensor values etc.)
- Overall better communication with Arduino
- A way to change the Audio Latency "beep" wave function / frequency
- User-friendly notifications about errors and such
*/
bool isSettingOpen = false;
bool AnalyzeData()
{
UINT iter_offset = 00;
const UINT BUFFER_MAX_VALUE = (1 << (sizeof(short) * 8)) / 2 - 1;
const int BUFFER_THRESHOLD = BUFFER_MAX_VALUE / 5 / (isAudioMode ? 2 : 1);
//serialStatus = Status_Idle;
int baseAvg = 0;
const short AvgCount = 10;
//const int REMAINDER_COUNTDOWN_VALUE = 10;
//int isBufferRemainder = 0; // Value at which last measurement ended gets carried to the current buffer, we have to deal with it.
for (size_t i = iter_offset; i < FRAMES_TO_CAPTURE / MAIN_BUFFER_SIZE_FRACTION; i++)
{
if (i - iter_offset < AvgCount) {
baseAvg += audioProcessor.recordedSamples[i];
continue;
}
else if (i - iter_offset == AvgCount) {
baseAvg /= AvgCount;
baseAvg = abs(baseAvg);
//if (baseAvg > BUFFER_THRESHOLD)
// isBufferRemainder = REMAINDER_COUNTDOWN_VALUE;
}
//if (isBufferRemainder && abs(curAudioDevice->recordBuffer[i]) < BUFFER_THRESHOLD) {
// isBufferRemainder--;
// if (!isBufferRemainder) {
// iter_offset = i - REMAINDER_COUNTDOWN_VALUE;
// baseAvg = 0;
// }
// continue;
//}
short sample = abs(audioProcessor.recordedSamples[i] - baseAvg);
if (sample >= BUFFER_THRESHOLD)
{
float microsElapsed = (1000000ull * (i - iter_offset)) / AUDIO_SAMPLE_RATE;
if (baseAvg > BUFFER_MAX_VALUE * 0.9f || microsElapsed <= 1000)
return false;
#ifdef _DEBUG
std::cout << "latency: " << microsElapsed << ", base val: " << baseAvg << std::endl;
printf("at sample %i\n", i);
#endif // _DEBUG
AddMeasurement(microsElapsed, 0, 0);
return true;
}
}
return false;
}
static int FilterValidPath(ImGuiInputTextCallbackData* data)
{
if (std::find(std::begin(invalidPathCharacters), std::end(invalidPathCharacters), data->EventChar) != std::end(invalidPathCharacters)) return 1;
return 0;
}
void ClearData()
{
serialStatus = Status_Idle;
tabsInfo[selectedTab].latencyData.measurements.clear();
tabsInfo[selectedTab].latencyStats = LatencyStats();
tabsInfo[selectedTab].isSaved = true;
ZeroMemory(tabsInfo[selectedTab].latencyData.note, 1000);
}
// Not the best GUI solution, but it's simple, fast and gets the job done.
int OnGui()
{
ImGuiStyle& style = ImGui::GetStyle();
if (shouldRunConfiguration)
{
ImGui::OpenPopup("Set Up");
shouldRunConfiguration = false;
}
if (ImGui::BeginMenuBar())
{
short openFullscreenCommand = 0;
bool badVerPopupOpen = false;
//static bool saveMeasurementsPopup = false;
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Open", "Ctrl+O")) {
auto res = OpenMeasurements();
if(res & JSON_HANDLE_INFO_BAD_VERSION) {
badVerPopupOpen = true;
//ImGui::OpenPopup("JSON version mismatch!");
//printf("BAD VERSION!\n");
}
}
if (ImGui::MenuItem("Save", "Ctrl+S")) { SaveMeasurements(); }
if (ImGui::MenuItem("Save as", "Ctrl+Shift+S")) { SaveAsMeasurements(); }
if (ImGui::MenuItem("Save Pack", "Alt+S")) { SavePackMeasurements(); }
if (ImGui::MenuItem("Save Pack As", "Alt+Shift+S")) { SavePackAsMeasurements(); }
if (ImGui::MenuItem("Fullscreen", "Alt+Enter")) {
//GUI::SetFullScreenState(isFullscreen);
if (!isFullscreen && !fullscreenModeOpenPopup)
openFullscreenCommand = 1;
else if (!fullscreenModeClosePopup && !fullscreenModeOpenPopup)
openFullscreenCommand = -1;
}
if (ImGui::MenuItem("Settings", "")) { isSettingOpen = !isSettingOpen; }
if (ImGui::MenuItem("Close", "")) { return 1; }
ImGui::EndMenu();
}
// Draw FPS
{
auto menuBarAvail = ImGui::GetContentRegionAvail();
static const float width = ImGui::CalcTextSize("FPS12345FPS FPS123456789FPS").x;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (menuBarAvail.x - width));
ImGui::BeginGroup();
ImGui::Text("FPS:");
ImGui::SameLine();
ImGui::Text("%.1f GUI", ImGui::GetIO().Framerate);
ImGui::SameLine();
// Right click total frames to reset it
ImGui::Text(" %.1f CPU", 1000000.f / averageFrametime);
static uint64_t totalFramerateStartTime{ micros() };
// The framerate is sometimes just too high to be properly displayed by the moving average and it's "small" buffer. So this should show average framerate over the entire program lifespan
TOOLTIP("Avg. framerate: %.1f", ((float)totalFrames / (micros() - totalFramerateStartTime)) * 1000000.f);
if (ImGui::IsItemClicked(1))
{
totalFramerateStartTime = micros();
totalFrames = 0;
}
ImGui::EndGroup();
}
ImGui::EndMenuBar();
if (openFullscreenCommand == 1) {
ImGui::OpenPopup("Enter Fullscreen mode?");
fullscreenModeOpenPopup = true;
}
else if (openFullscreenCommand == -1) {
ImGui::OpenPopup("Exit Fullscreen mode?");
fullscreenModeClosePopup = true;
}
if(badVerPopupOpen)
ImGui::OpenPopup("JSON version mismatch!");
}
if (ImGui::BeginPopupModal("JSON version mismatch!", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove))
{
ImGui::Text("Some of the imported files are either from an older or newer version of the program\nThe data might be corrupted or wrong!");
if (ImGui::Button("Ok", {-1, 0}))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
const auto windowAvail = ImGui::GetContentRegionAvail();
ImGuiIO& io = ImGui::GetIO();
uint64_t curTime = micros();
if (serialStatus != Status_Idle && curTime > (lastInternalTest + SERIAL_NO_RESPONSE_DELAY))
{
serialStatus = Status_Idle;
}
// Handle Shortcuts
ImGuiKey pressedKeys[ImGuiKey_COUNT]{static_cast<ImGuiKey>(0)};
size_t addedKeys = 0;
//ZeroMemory(pressedKeys, ImGuiKey_COUNT);
for (auto key = static_cast<ImGuiKey>(0); key < ImGuiKey_COUNT; (*(int*)&key)++)
{
bool isPressed = ImGui::IsKeyPressed(key, false);
// Shift, ctrl and alt
if ((key >= 641 && key <= 643) || (key >= 527 && key <= 533))
continue;
if (ImGui::IsLegacyKey(key))
continue;
if (isPressed) {
pressedKeys[addedKeys++] = key;
}
}
static bool wasEscapeUp{ true };
if (addedKeys == 1)
{
//const char* name = ImGui::GetKeyName(pressedKeys[0]);
if (io.KeyCtrl)
{
// Moved to the Main function
//io.ClearInputKeys();
//if (pressedKeys[0] == ImGuiKey_S)
//{
// printf("Save intent\n");
// SaveMeasurements();
//}
//if (pressedKeys[0] == ImGuiKey_O)
//{
// OpenMeasurements();
//}
//else if (pressedKeys[0] == ImGuiKey_N)
//{
// auto newTab = TabInfo();
// strcat_s<TAB_NAME_MAX_SIZE>(newTab.name, std::to_string(tabsInfo.size()).c_str());
// tabsInfo.push_back(newTab);
//}
// Doesn't work yet!
if (pressedKeys[0] == ImGuiKey_W)
{
char tabClosePopupName[48];
snprintf(tabClosePopupName, 48, "Save before Closing?###TabExit%i", selectedTab);
ImGui::OpenPopup(tabClosePopupName);
}
}
else if (io.KeyAlt)
{
//io.ClearInputKeys();
// Going fullscreen popup currently with a small issue
// Enter
if (pressedKeys[0] == ImGuiKey_Enter || pressedKeys[0] == ImGuiKey_KeypadEnter)
{
//GUI::g_pSwapChain->GetFullscreenState((BOOL*)&isFullscreen, nullptr);
isFullscreen = GUI::GetFullScreenState();
if (!isFullscreen && !fullscreenModeOpenPopup)
{
ImGui::OpenPopup("Enter Fullscreen mode?");
fullscreenModeOpenPopup = true;
}
else if (!fullscreenModeClosePopup && !fullscreenModeOpenPopup)
{
ImGui::OpenPopup("Exit Fullscreen mode?");
fullscreenModeClosePopup = true;
}
}
}
else if (!io.KeyShift && pressedKeys[0] == ImGuiKey_Escape)
{
bool isFS = GUI::GetFullScreenState();
//GUI::g_pSwapChain->GetFullscreenState(&isFS, nullptr);
isFullscreen = isFS;
if (isFullscreen && !fullscreenModeClosePopup && wasEscapeUp)
{
wasEscapeUp = false;
ImGui::OpenPopup("Exit Fullscreen mode?");
fullscreenModeClosePopup = true;
wasEscapeUp = false;
}
}
}
if (ImGui::BeginPopupModal("Enter Fullscreen mode?", &fullscreenModeOpenPopup, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("Are you sure you want to enter Fullscreen mode?");
TOOLTIP("Press Escape to Exit");
ImGui::SeparatorSpace(0, { 0, 10 });
if (ImGui::Button("Yes") || (IS_ONLY_ENTER_PRESSED && !io.KeyAlt))
{
// I'm pretty sure I should also resize the swapchain buffer to use the new resolution, but maybe later. It looks kind of goofy on displays with odd resolution :shrug:
//GUI::g_pSwapChain->ResizeBuffers(0, 1080, 1920, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
//UINT modesNum = 256;
//DXGI_MODE_DESC monitorModes[256];
//GUI::vOutputs[1]->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, 0, &modesNum, monitorModes);
//DXGI_MODE_DESC mode = monitorModes[modesNum - 1];
//GUI::g_pSwapChain->ResizeTarget(&mode);
//GUI::g_pSwapChain->ResizeBuffers(0, 1080, 1920, DXGI_FORMAT_R8G8B8A8_UNORM, 0);
if (GUI::SetFullScreenState(true) == 0)
isFullscreen = true;
else
isFullscreen = false;
ImGui::CloseCurrentPopup();
fullscreenModeOpenPopup = false;
}
ImGui::SameLine();
if (ImGui::Button("No") || IS_ONLY_ESCAPE_PRESSED)
{
ImGui::CloseCurrentPopup();
fullscreenModeOpenPopup = false;
}
ImGui::EndPopup();
}
if (ImGui::BeginPopupModal("Exit Fullscreen mode?", &fullscreenModeClosePopup, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("Are you sure you want to exit Fullscreen mode?");
ImGui::SeparatorSpace(0, { 0, 10 });
// ImGui doesn't yet support focusing a button
//ImGui::PushAllowKeyboardFocus(true);
//ImGui::PushID("ExitFSYes");
//ImGui::SetKeyboardFocusHere();
//bool isYesDown = ImGui::Button("Yes");
//ImGui::PopID();
////ImGui::SetKeyboardFocusHere(-1);
//auto curWindow = ImGui::GetCurrentWindow();
//ImGui::PopAllowKeyboardFocus();
//ImGui::SetFocusID(curWindow->GetID("ExitFSYes"), curWindow);
if (ImGui::Button("Yes") || IS_ONLY_ENTER_PRESSED)
{
if (GUI::SetFullScreenState(false) == 0)
isFullscreen = false;
else
isFullscreen = true;
ImGui::CloseCurrentPopup();
fullscreenModeClosePopup = false;
}
ImGui::SameLine();
if (ImGui::Button("No") || (IS_ONLY_ESCAPE_PRESSED && wasEscapeUp))
{
wasEscapeUp = false;
ImGui::CloseCurrentPopup();
fullscreenModeClosePopup = false;
}
ImGui::EndPopup();
}
if (ImGui::IsKeyReleased(ImGuiKey_Escape))
wasEscapeUp = true;
// following way might be better, but it requires a use of some weird values like 0xF for CTRL+S
//if (io.InputQueueCharacters.size() == 1)
//{
// ImWchar c = io.InputQueueCharacters[0];
// if (((c > ' ' && c <= 255) ? (char)c : '?' == 's') && io.KeyCtrl)
// {
// SaveMeasurements();
// }
//}
if (isSettingOpen)
{
ImGui::SetNextWindowSize({ 480.0f, 480.0f });
bool wasLastSettingsOpen = isSettingOpen;
if (ImGui::Begin("Settings", &isSettingOpen, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse))
{
// On Settings Window Closed:
if (wasLastSettingsOpen && !isSettingOpen && HasConfigChanged())
{
// Call a popup by name
ImGui::OpenPopup("Save Style?");
}
// Define the messagebox popup
if (ImGui::BeginPopupModal("Save Style?", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
isSettingOpen = true;
ImGui::PushFont(boldFont);
ImGui::Text("Do you want to save before exiting?");
ImGui::PopFont();
ImGui::Separator();
ImGui::Dummy({ 0, ImGui::GetTextLineHeight() });
// These buttons don't really fit the window perfectly with some fonts, I might have to look into that.
ImGui::BeginGroup();
if (ImGui::Button("Save"))
{
SaveCurrentUserConfig();
isSettingOpen = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Discard"))
{
RevertConfig();
isSettingOpen = false;
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndGroup();
ImGui::EndPopup();
}
static int selectedSettings = 0;
const auto avail = ImGui::GetContentRegionAvail();
const char* items[3]{ "Style", "Performance", "Misc" };
// Makes list take ({listBoxSize}*100)% width of the parent
float listBoxSize = 0.3f;
if (ImGui::BeginListBox("##Setting", { avail.x * listBoxSize, avail.y }))
{
for (int i = 0; i < sizeof(items) / sizeof(items[0]); i++)
{
//ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (style.ItemSpacing.x / 2) - 2);
//ImVec2 label_size = ImGui::CalcTextSize(items[i], NULL, true);
bool isSelected = (selectedSettings == i);
//if (ImGui::Selectable(items[i], isSelected, 0, { (avail.x * listBoxSize - (style.ItemSpacing.x) - (style.FramePadding.x * 2)) + 4, label_size.y }, style.FrameRounding))
if (ImGui::Selectable(items[i], isSelected, 0, { 0, 0 }))
{
selectedSettings = i;
}
}
ImGui::EndListBox();
}
ImGui::SameLine();
ImGui::BeginGroup();
switch (selectedSettings)
{
case 0: // Style
{
ImGui::BeginChild("Style", { ((1 - listBoxSize) * avail.x) - style.FramePadding.x * 2, avail.y - ImGui::GetFrameHeightWithSpacing() }, true);
ImGui::ColorEdit4("Main Color", currentUserData.style.mainColor);
ImGui::PushID(02);
ImGui::SliderFloat("Brightness", ¤tUserData.style.mainColorBrightness, -0.5f, 0.5f);
REVERT(¤tUserData.style.mainColorBrightness, backupUserData.style.mainColorBrightness);
ImGui::PopID();
auto _accentColor = ImVec4(*(ImVec4*)currentUserData.style.mainColor);
auto darkerAccent = ImVec4(*(ImVec4*)&_accentColor) * (1 - currentUserData.style.mainColorBrightness);
auto darkestAccent = ImVec4(*(ImVec4*)&_accentColor) * (1 - currentUserData.style.mainColorBrightness * 2);
// Alpha has to be set separatly, because it also gets multiplied times brightness.
auto alphaAccent = ImVec4(*(ImVec4*)currentUserData.style.mainColor).w;
_accentColor.w = alphaAccent;
darkerAccent.w = alphaAccent;
darkestAccent.w = alphaAccent;
ImGui::Dummy({ 0, ImGui::GetFrameHeight() / 2 });
ImVec2 colorsAvail = ImGui::GetContentRegionAvail();
ImGui::ColorButton("Accent Color", (ImVec4)_accentColor, 0, { colorsAvail.x, ImGui::GetFrameHeight() });
ImGui::ColorButton("Accent Color Dark", darkerAccent, 0, { colorsAvail.x, ImGui::GetFrameHeight() });
ImGui::ColorButton("Accent Color Darkest", darkestAccent, 0, { colorsAvail.x, ImGui::GetFrameHeight() });
ImGui::SeparatorSpace(ImGuiSeparatorFlags_Horizontal, { colorsAvail.x * 0.9f, ImGui::GetFrameHeight() });
ImGui::ColorEdit4("Font Color", currentUserData.style.fontColor);
ImGui::PushID(12);
ImGui::SliderFloat("Brightness", ¤tUserData.style.fontColorBrightness, -1.0f, 1.0f, "%.3f");
REVERT(¤tUserData.style.fontColorBrightness, backupUserData.style.fontColorBrightness);
ImGui::PopID();
auto _fontColor = ImVec4(*(ImVec4*)currentUserData.style.fontColor);
auto darkerFont = ImVec4(*(ImVec4*)&_fontColor) * (1 - currentUserData.style.fontColorBrightness);
// Alpha has to be set separatly, because it also gets multiplied times brightness.
auto alphaFont = ImVec4(*(ImVec4*)currentUserData.style.fontColor).w;
_fontColor.w = alphaFont;
darkerFont.w = alphaFont;
ImGui::Dummy({ 0, ImGui::GetFrameHeight() / 2 });
ImGui::ColorButton("Font Color", _fontColor, 0, { colorsAvail.x, ImGui::GetFrameHeight() });
ImGui::ColorButton("Font Color Dark", darkerFont, 0, { colorsAvail.x, ImGui::GetFrameHeight() });
//ImGui::SetCursorPosY(avail.y - ImGui::GetFrameHeight() - style.WindowPadding.y);
//float colors[2][4];
//float brightnesses[2]{ accentBrightness, fontBrightness };
//memcpy(&colors, &accentColor, colorSize);
//memcpy(&colors[1], &fontColor, colorSize);
//ApplyStyle(colors, brightnesses);
ImGui::SeparatorSpace(ImGuiSeparatorFlags_Horizontal, { colorsAvail.x * 0.9f, ImGui::GetFrameHeight() });
ImGui::ColorEdit4("Int. Plot", currentUserData.style.internalPlotColor);
TOOLTIP("Internal plot color");
ImGui::ColorEdit4("Ext. Plot", currentUserData.style.externalPlotColor);
TOOLTIP("External plot color");
ImGui::ColorEdit4("Input Plot", currentUserData.style.inputPlotColor);
TOOLTIP("Input plot color");
ApplyCurrentStyle();
ImGui::SeparatorSpace(ImGuiSeparatorFlags_Horizontal, { colorsAvail.x * 0.9f, ImGui::GetFrameHeight() });
//ImGui::PushFont(io.Fonts->Fonts[fontIndex[selectedFont]]);
// This has to be done manually (instead of ImGui::Combo()) to be able to change the fonts of each selectable to a corresponding one.
if (ImGui::BeginCombo("Font", fonts[currentUserData.style.selectedFont]))
{
for (int i = 0; i < ((io.Fonts->Fonts.Size - 1) / 2) + 1; i++)
{
//auto selectableSpace = ImGui::GetContentRegionAvail();
//ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 2);
ImGui::PushFont(io.Fonts->Fonts[fontIndex[i]]);
bool isSelected = (currentUserData.style.selectedFont == i);
if (ImGui::Selectable(fonts[i], isSelected, 0, { 0, 0 }))
{
if (currentUserData.style.selectedFont != i) {
io.FontDefault = io.Fonts->Fonts[fontIndex[i]];
if (auto _boldFont = GetFontBold(i); _boldFont != nullptr)
boldFont = _boldFont;
else
boldFont = io.Fonts->Fonts[fontIndex[i]];
currentUserData.style.selectedFont = i;
}
}
ImGui::PopFont();
}
ImGui::EndCombo();
}
//ImGui::PopFont();
bool hasFontSizeChanged = ImGui::SliderFloat("Font Size", ¤tUserData.style.fontSize, 0.5f, 2, "%.2f");
REVERT(¤tUserData.style.fontSize, backupUserData.style.fontSize);
if (hasFontSizeChanged || ImGui::IsItemClicked(1))
{
for (int i = 0; i < io.Fonts->Fonts.Size; i++)
{
io.Fonts->Fonts[i]->Scale = currentUserData.style.fontSize;
}
}
ImGui::EndChild();
break;
}
// Performance
case 1:
if (ImGui::BeginChild("Performance", { ((1 - listBoxSize) * avail.x) - style.FramePadding.x * 2, avail.y - ImGui::GetFrameHeightWithSpacing() }, true))
{
auto performanceAvail = ImGui::GetContentRegionAvail();
ImGui::Checkbox("###LockGuiFpsCB", ¤tUserData.performance.lockGuiFps);
TOOLTIP("It's strongly recommended to keep GUI FPS locked for the best performance");
ImGui::BeginDisabled(!currentUserData.performance.lockGuiFps);
ImGui::SameLine();
ImGui::PushItemWidth(performanceAvail.x - ImGui::GetItemRectSize().x - style.FramePadding.x * 3 - ImGui::CalcTextSize("GUI Refresh Rate").x);
//ImGui::SliderInt("GUI FPS", &guiLockedFps, 30, 360, "%.1f");
ImGui::DragInt("GUI Refresh Rate", ¤tUserData.performance.guiLockedFps, .5f, 30, 480);
REVERT(¤tUserData.performance.guiLockedFps, backupUserData.performance.guiLockedFps);
ImGui::PopItemWidth();
ImGui::EndDisabled();
ImGui::Spacing();
ImGui::Checkbox("Show Plots", ¤tUserData.performance.showPlots);
TOOLTIP("Plots can have a small impact on the performance");
ImGui::Spacing();
//ImGui::Checkbox("VSync", ¤tUserData.performance.VSync);
ImGui::SliderInt("VSync", &(int&)currentUserData.performance.VSync, 0, 4, "%d", ImGuiSliderFlags_AlwaysClamp);
TOOLTIP("This setting synchronizes your monitor with the program to avoid screen tearing.\n(Adds a significant amount of latency)");
ImGui::EndChild();
}
break;
// Misc
case 2:
if ((ImGui::BeginChild("Misc", { ((1 - listBoxSize) * avail.x) - style.FramePadding.x * 2, avail.y - ImGui::GetFrameHeightWithSpacing() }, true)))
{
ImGui::Checkbox("Save config locally", ¤tUserData.misc.localUserData);
#ifdef _WIN32
TOOLTIP("Chose whether you want to save config file in the same directory as the program, or in the AppData folder");
#else
TOOLTIP("Chose whether you want to save config file in the same directory as the program, or in the /home/{usr}/.LatencyMeter folder");
#endif
ImGui::EndChild();
}
break;
}
ImGui::BeginGroup();
auto buttonsAvail = ImGui::GetContentRegionAvail();
if (ImGui::Button("Revert", { (buttonsAvail.x / 2 - style.FramePadding.x), ImGui::GetFrameHeight() }))
{
RevertConfig();
}
ImGui::SameLine();
if (ImGui::Button("Save", { (buttonsAvail.x / 2 - style.FramePadding.x), ImGui::GetFrameHeight() }))
{
SaveCurrentUserConfig();
//SaveStyleConfig(colors, brightnesses, selectedFont, fontSize);
}
ImGui::EndGroup();
ImGui::EndGroup();
}
ImGui::End();
}
// TABS
int deletedTabIndex = -1;
if (ImGui::BeginTabBar("TestsTab", ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyScroll))
{
for (size_t tabN = 0; tabN < tabsInfo.size(); tabN++)
{
//char idText[24];
//snprintf(idText, 24, "Tab Item %i", tabN);
//ImGui::PushID(idText);
char tabNameLabel[48];
snprintf(tabNameLabel, 48, "%s###Tab%i", tabsInfo[tabN].name, tabN);
//ImGui::PushItemWidth(ImGui::CalcTextSize(tabNameLabel).x + 100);
//if(!tabsInfo[tabN].isSaved)
// ImGui::SetNextItemWidth(ImGui::CalcTextSize(tabsInfo[tabN].name, NULL).x + (style.FramePadding.x * 2) + 15);
//else
ImGui::SetNextItemWidth(ImGui::CalcTextSize(tabsInfo[tabN].name, NULL).x + (style.FramePadding.x * 2) + (tabsInfo[tabN].isSaved ? 0 : 15));
//selectedTab = tabsInfo.size() - 1;
auto flags = selectedTab == tabN ? ImGuiTabItemFlags_SetSelected : 0;
flags |= tabsInfo[tabN].isSaved ? 0 : ImGuiTabItemFlags_UnsavedDocument;
if (ImGui::BeginTabItem(tabNameLabel, NULL, flags))
{
ImGui::EndTabItem();
}
//ImGui::PopItemWidth();
//ImGui::PopID();
if (ImGui::IsItemHovered())
{
if (ImGui::IsMouseDown(0))
{
selectedTab = tabN;
}
auto mouseDelta = io.MouseWheel;
selectedTab += mouseDelta;
selectedTab = std::clamp(selectedTab, 0, (int)tabsInfo.size() - 1);
}
char popupName[32]{ 0 };
snprintf(popupName, 32, "Change tab %i name", tabN);
char popupTextEdit[32]{ 0 };
snprintf(popupTextEdit, 32, "Ed Txt %i", tabN);
char tabClosePopupName[48];
snprintf(tabClosePopupName, 48, "Save before Closing?###TabExit%i", tabN);
static bool tabExitOpen = true;
bool openTabClose = false;
if (ImGui::IsItemFocused())
{
if (ImGui::IsKeyPressed(ImGuiKey_Delete, false))
{
#ifdef _DEBUG
printf("deleting tab: %i\n", tabN);
#endif
if (tabsInfo.size() > 1)
if (!tabsInfo[tabN].isSaved)
{
ImGui::OpenPopup(tabClosePopupName);
tabExitOpen = true;
}
else
{
deletedTabIndex = tabN;
if (tabN == tabsInfo.size() - 1)
{
ImGuiContext& g = *GImGui;
ImGui::SetFocusID(g.CurrentTabBar->Tabs[tabN-1].ID, ImGui::GetCurrentWindow());
}
// Unfocus so the next items won't get deleted (This can also be achieved by checking if DEL was not down)
//ImGui::SetWindowFocus(nullptr);
}
}
else if (ImGui::IsKeyDown(ImGuiKey_F2))
{
ImGui::OpenPopup(popupTextEdit);
}
if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow))
selectedTab--;
if (ImGui::IsKeyPressed(ImGuiKey_RightArrow))
selectedTab++;
if (io.KeyCtrl)
{
if (pressedKeys[0] == ImGuiKey_W)
if (tabsInfo.size() > 1)
if (!tabsInfo[tabN].isSaved)
{
ImGui::OpenPopup(tabClosePopupName);
tabExitOpen = true;
}
else
{
deletedTabIndex = tabN;
if (tabN == tabsInfo.size() - 1)
{
ImGuiContext& g = *GImGui;
ImGui::SetFocusID(g.CurrentTabBar->Tabs[tabN - 1].ID, ImGui::GetCurrentWindow());
}
}
}
selectedTab = std::clamp(selectedTab, 0, (int)tabsInfo.size() - 1);
}
if (ImGui::BeginPopup(popupTextEdit, ImGuiWindowFlags_NoMove))
{
ImGui::SetKeyboardFocusHere(0);
if (ImGui::InputText("Tab name", tabsInfo[tabN].name, TAB_NAME_MAX_SIZE, ImGuiInputTextFlags_AutoSelectAll))
{
char defaultTabName[8]{ 0 };
snprintf(defaultTabName, 8, "Tab %i", tabN);
tabsInfo[tabN].isSaved = !strcmp(defaultTabName, tabsInfo[tabN].name);
}
ImGui::EndPopup();
}
if (ImGui::IsItemClicked(1) || (ImGui::IsItemHovered() && (ImGui::IsMouseDoubleClicked(0))))
{
#ifdef _DEBUG
printf("Open tab %i tooltip\n", tabN);
#endif
ImGui::OpenPopup(popupName);
}
if (ImGui::BeginPopup(popupName, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))
{
// Check if this name already exists
//ImGui::SetKeyboardFocusHere(0);
if (ImGui::InputText("Tab name", tabsInfo[tabN].name, TAB_NAME_MAX_SIZE, ImGuiInputTextFlags_AutoSelectAll))
{
char defaultTabName[8]{ 0 };
snprintf(defaultTabName, 8, "Tab %i", tabN);
tabsInfo[tabN].isSaved = !strcmp(defaultTabName, tabsInfo[tabN].name);
}
if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Escape))
ImGui::CloseCurrentPopup();
//ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 4);
if (tabsInfo.size() > 1) {
if (ImGui::Button("Close Tab", { -1, 0 }))
{
if (!tabsInfo[tabN].isSaved)
{
ImGui::CloseCurrentPopup();
//ImGui::OpenPopup(tabClosePopupName);
openTabClose = true;
}
else
{
deletedTabIndex = tabN;
ImGui::CloseCurrentPopup();
}
}
}
ImGui::EndPopup();
}
if (openTabClose)
{
tabExitOpen = true;
ImGui::OpenPopup(tabClosePopupName);
}
if (ImGui::BeginPopupModal(tabClosePopupName, &tabExitOpen, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings))
{
ImGui::Text("Are you sure you want to close this tab?\nAll measurements will be lost if you don't save");
ImGui::SeparatorSpace(ImGuiSeparatorFlags_Horizontal, { 0, 10 });
auto popupAvail = ImGui::GetContentRegionAvail();
popupAvail.x -= style.ItemSpacing.x * 2;
if (ImGui::Button("Save", { popupAvail.x / 3, 0 }))
{
if (SaveMeasurements())
deletedTabIndex = tabN;
ImGui::CloseCurrentPopup();
tabExitOpen = false;
}
ImGui::SameLine();
if (ImGui::Button("Discard", { popupAvail.x / 3, 0 }))
{
deletedTabIndex = tabN;
ImGui::CloseCurrentPopup();
tabExitOpen = false;
}
ImGui::SameLine();
if (ImGui::Button("Cancel", { popupAvail.x / 3, 0 }))
{
ImGui::CloseCurrentPopup();
tabExitOpen = false;
}
ImGui::EndPopup();