forked from ngscopeclient/scopehal-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
3687 lines (3115 loc) · 98.2 KB
/
MainWindow.cpp
File metadata and controls
3687 lines (3115 loc) · 98.2 KB
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
/***********************************************************************************************************************
* *
* ngscopeclient *
* *
* Copyright (c) 2012-2026 Andrew D. Zonenberg and contributors *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief Implementation of most of MainWindow
*/
#include "ngscopeclient.h"
#include "ngscopeclient-version.h"
#include "MainWindow.h"
#include "PreferenceTypes.h"
#include "FileSystem.h"
#include <iostream>
#include <fstream>
#include "DemoOscilloscope.h"
#include "RemoteBridgeOscilloscope.h"
//Dock builder API is not yet public, so might change...
#include "imgui_internal.h"
//Dialogs
#include "BERTDialog.h"
#include "BERTInputChannelDialog.h"
#include "ChannelPropertiesDialog.h"
#include "CreateFilterBrowser.h"
#include "FileBrowser.h"
#include "FilterGraphWorkspace.h"
#include "FilterPropertiesDialog.h"
#include "HistoryDialog.h"
#include "LoadDialog.h"
#include "LogViewerDialog.h"
#include "ManageInstrumentsDialog.h"
#include "MeasurementsDialog.h"
#include "MetricsDialog.h"
#include "NotesDialog.h"
#include "PersistenceSettingsDialog.h"
#include "PowerSupplyDialog.h"
#include "PreferenceDialog.h"
#include "ProtocolAnalyzerDialog.h"
#include "RFGeneratorDialog.h"
#include "SCPIConsoleDialog.h"
#include "ScopeDeskewWizard.h"
#include "TriggerPropertiesDialog.h"
#include <imgui_markdown.h>
#include <filesystem>
#ifdef _WIN32
#include <windows.h>
#include <shlwapi.h>
#else
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <cinttypes>
using namespace std;
extern Event g_rerenderRequestedEvent;
extern unique_ptr<MainWindow> g_mainWindow;
// called by ImGui during ImGui::Begin()
// when switching viewports, just after setting ImGuiStyle.FontScaleDpi
static void MainWindow_OnChangedViewport([[maybe_unused]] ImGuiViewport *vp)
{
if (g_mainWindow != nullptr) {
g_mainWindow->ResetStyle();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
#ifdef __SANITIZE_ADDRESS__
#define SAN_SUFFIX "[ASAN] "
#else
#define SAN_SUFFIX ""
#endif
#ifdef _DEBUG
#define DBG_SUFFIX "[DEBUG BUILD] "
#else
#define DBG_SUFFIX ""
#endif
MainWindow::MainWindow(shared_ptr<QueueHandle> queue, bool maximized, bool restored)
: VulkanWindow("ngscopeclient " NGSCOPECLIENT_VERSION " " DBG_SUFFIX SAN_SUFFIX, queue, maximized, restored)
, m_showDemo(false)
, m_nextWaveformGroup(1)
, m_toolbarIconSize(0)
, m_traceAlpha(0.75)
, m_persistenceDecay(0.8)
, m_session(this)
, m_sessionClosing(true) //reset a default session on the first frame after we start up
, m_fileLoadInProgress(false)
, m_openOnline(false)
, m_showingLoadWarnings(false)
, m_loadConfirmationChecked(false)
, m_texmgr(queue)
, m_needRender(false)
, m_toneMapTime(0)
{
LoadRecentInstrumentList();
LoadRecentFileList();
//Initialize memory pressure callback
g_memoryPressureHandlers.emplace(&OnMemoryPressureStatic);
//Initialize command pool/buffer
vk::CommandPoolCreateInfo poolInfo(
vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
queue->m_family );
m_cmdPool = make_unique<vk::raii::CommandPool>(*g_vkComputeDevice, poolInfo);
vk::CommandBufferAllocateInfo bufinfo(**m_cmdPool, vk::CommandBufferLevel::ePrimary, 1);
m_cmdBuffer = make_unique<vk::raii::CommandBuffer>(
std::move(vk::raii::CommandBuffers(*g_vkComputeDevice, bufinfo).front()));
if(g_hasDebugUtils)
{
g_vkComputeDevice->setDebugUtilsObjectNameEXT(
vk::DebugUtilsObjectNameInfoEXT(
vk::ObjectType::eCommandPool,
reinterpret_cast<uint64_t>(static_cast<VkCommandPool>(**m_cmdPool)),
"MainWindow.m_cmdPool"));
g_vkComputeDevice->setDebugUtilsObjectNameEXT(
vk::DebugUtilsObjectNameInfoEXT(
vk::ObjectType::eCommandBuffer,
reinterpret_cast<int64_t>(static_cast<VkCommandBuffer>(**m_cmdBuffer)),
"MainWindow.m_cmdBuffer"));
}
UpdateFonts();
//Load some textures
m_toolbarIconSize = 0;
LoadToolbarIcons();
LoadGradients();
LoadMiscIcons();
LoadFilterIcons();
LoadStatusBarIcons();
LoadWaveformShapeIcons();
LoadAppIcon();
//Don't move windows when dragging in the body, only the title bar
ImGui::GetIO().ConfigWindowsMoveFromTitleBarOnly = true;
//Update preference settings for viewport mode
auto viewportMode = m_session.GetPreferences().GetEnumRaw("Appearance.Windowing.viewport_mode");
if(viewportMode == VIEWPORT_ENABLE)
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
else
ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
ImGui::GetPlatformIO().Platform_OnChangedViewport = MainWindow_OnChangedViewport;
}
MainWindow::~MainWindow()
{
LogTrace("Application exiting\n");
lock_guard<shared_mutex> lock(g_vulkanActivityMutex);
g_vkComputeDevice->waitIdle();
m_texmgr.clear();
m_cmdBuffer = nullptr;
m_cmdPool = nullptr;
CloseSession();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Session termination
/**
@brief Creates a new session initialized with some default windows
*/
void MainWindow::InitializeDefaultSession()
{
LogTrace("Initializing new session\n");
LogIndenter li;
//Spawn the graph editor
m_graphEditor = make_shared<FilterGraphEditor>(m_session, this);
AddDialog(m_graphEditor);
//Spawn the net browser
m_streamBrowser = make_shared<StreamBrowserDialog>(m_session, this);
AddDialog(m_streamBrowser);
//Spawn the filter browser
m_filterPalette = make_shared<CreateFilterBrowser>(m_session, this);
AddDialog(m_filterPalette);
//Spawn a new workspace for the filter graph stuff
auto w = make_shared<FilterGraphWorkspace>(m_session, this, m_graphEditor, m_filterPalette);
m_workspaces.emplace(w);
//Dock it
m_initialWorkspaceDockRequest = w;
//Spawn the tutorial if requested
//if(m_session.GetPreferences().GetBool("Help.Wizards.first_run_wizard"))
if(false)
{
m_tutorialDialog = make_shared<TutorialWizard>(&m_session, this);
AddDialog(m_tutorialDialog);
}
}
void MainWindow::CloseSession()
{
LogTrace("Closing session\n");
LogIndenter li;
SaveRecentInstrumentList();
//Close background threads in our session before destroying views
m_session.ClearBackgroundThreads();
//Destroy waveform views
LogTrace("Clearing views\n");
for(auto g : m_waveformGroups)
g->Clear();
m_waveformGroups.clear();
m_newWaveformGroups.clear();
m_splitRequests.clear();
m_groupsToClose.clear();
for(auto it : m_pendingChannelDisplayRequests)
it.first->Release();
m_pendingChannelDisplayRequests.clear();
//Clear any open dialogs before destroying the session.
//This ensures that we have a nice well defined shutdown order.
LogTrace("Clearing dialogs\n");
m_logViewerDialog = nullptr;
m_metricsDialog = nullptr;
m_triggerDialog = nullptr;
m_filterPalette = nullptr;
m_streamBrowser = nullptr;
m_historyDialog = nullptr;
m_preferenceDialog = nullptr;
m_persistenceDialog = nullptr;
m_tutorialDialog = nullptr;
m_manageInstrumentsDialog = nullptr;
m_initialWorkspaceDockRequest = nullptr;
m_graphEditor = nullptr;
m_graphEditorConfigBlob = "";
m_graphEditorGroups.clear();
m_fileBrowser = nullptr;
m_measurementsDialog = nullptr;
m_notesDialog = nullptr;
m_meterDialogs.clear();
m_psuDialogs.clear();
m_channelPropertiesDialogs.clear();
m_generatorDialogs.clear();
m_bertDialogs.clear();
m_rfgeneratorDialogs.clear();
m_loadDialogs.clear();
m_dialogs.clear();
m_protocolAnalyzerDialogs.clear();
m_scpiConsoleDialogs.clear();
m_workspaces.clear();
//Clear the actual session object once all views / dialogs having handles to scopes etc have been destroyed
m_session.Clear();
LogTrace("Clear complete\n");
m_sessionClosing = false;
m_sessionFileName = "";
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Add views for new instruments
string MainWindow::NameNewWaveformGroup()
{
LogTrace("Naming new waveform group\n");
LogIndenter li;
int maxretries = 50;
for(int retry=0; retry<maxretries; retry++)
{
//Avoid colliding, check if name is in use and skip if so
int id = (m_nextWaveformGroup ++);
auto nextid = string("Waveform Group ") + to_string(id);
LogTrace("Candidate ID is %s\n", nextid.c_str());
//This is ugly but we dont currently have an index for this.
//Very unlikely we'll ever have enough waveform groups for this to take a perceptible amount of time.
bool collision = false;
for(auto g : m_waveformGroups)
{
if(g->GetRawID() == nextid)
{
LogTrace("ID is in use (by %s), trying again\n", g->GetID().c_str());
collision = true;
break;
}
}
if(!collision)
return nextid;
}
LogError("Failed to name new waveform group (tried %d IDs)\n", maxretries);
return "";
}
/**
@brief Makes sure we have at least one waveform area displaying a given stream
*/
void MainWindow::AddAreaForStreamIfNotAlreadyVisible(StreamDescriptor stream)
{
lock_guard<recursive_mutex> lock(m_waveformGroupsMutex);
//Check if we already have a waveform area displaying it
for(auto group : m_waveformGroups)
{
auto areas = group->GetWaveformAreas();
for(auto area : areas)
{
if(area->IsStreamBeingDisplayed(stream))
return;
}
}
//Not here yet. Add it
auto group = GetBestGroupForWaveform(stream);
auto area = make_shared<WaveformArea>(stream, group, this);
group->AddArea(area);
}
/**
@brief Figure out what group to use for a newly added stream, based on unit compatibility etc
*/
shared_ptr<WaveformGroup> MainWindow::GetBestGroupForWaveform(StreamDescriptor /*stream*/)
{
lock_guard<recursive_mutex> lock(m_waveformGroupsMutex);
//If we have no waveform groups, make one
//TODO: reject existing group if units are incompatible
if(m_waveformGroups.empty())
{
//Make the group
auto name = NameNewWaveformGroup();
auto group = make_shared<WaveformGroup>(this, name);
m_waveformGroups.push_back(group);
//Group is newly created and not yet docked
m_newWaveformGroups.push_back(group);
}
//Get the first compatible waveform group (may or may not be what we just created)
//TODO: reject existing group if units are incompatible
return *m_waveformGroups.begin();
}
/**
@brief Handles creation of a new oscilloscope
@param scope The scope to add
@param createViews True if we should add waveform areas for each enabled channel
*/
void MainWindow::OnScopeAdded(shared_ptr<Oscilloscope> scope, bool createViews)
{
LogTrace("Oscilloscope \"%s\" added\n", scope->m_nickname.c_str());
LogIndenter li;
if(createViews)
{
//Add areas to it
//For now, one area per enabled channel
vector<StreamDescriptor> streams;
//Demo scope gets all channels enabled
bool isDemo = dynamic_pointer_cast<DemoOscilloscope>(scope) != nullptr;
//Headless scopes depend on preference
bool isHeadless = dynamic_pointer_cast<RemoteBridgeOscilloscope>(scope) != nullptr;
auto headlessMode = m_session.GetPreferences().GetEnumRaw("Drivers.General.headless_startup");
//Headless scope? Pick every channel if requested
if( (isHeadless && (headlessMode == HEADLESS_STARTUP_ALL_NON_MSO)) || isDemo )
{
LogTrace("Headless scope, enabling every analog channel\n");
for(size_t i=0; i<scope->GetChannelCount(); i++)
{
auto chan = scope->GetOscilloscopeChannel(i);
if(!chan)
continue;
for(size_t j=0; j<chan->GetStreamCount(); j++)
{
if(chan->GetType(j) == Stream::STREAM_TYPE_ANALOG)
streams.push_back(StreamDescriptor(chan, j));
}
}
//Handle pure logic analyzers
if(streams.empty())
{
LogTrace("No analog channels found. Must be a logic analyzer. Enabling every digital channel\n");
for(size_t i=0; i<scope->GetChannelCount(); i++)
{
auto chan = scope->GetOscilloscopeChannel(i);
if(!chan)
continue;
for(size_t j=0; j<chan->GetStreamCount(); j++)
{
if(chan->GetType(j) == Stream::STREAM_TYPE_DIGITAL)
streams.push_back(StreamDescriptor(chan, j));
}
}
}
}
//Use whatever was enabled when we connected
else
{
for(size_t i=0; i<scope->GetChannelCount(); i++)
{
auto chan = scope->GetOscilloscopeChannel(i);
if(!chan)
continue;
if(!chan->IsEnabled())
continue;
for(size_t j=0; j<chan->GetStreamCount(); j++)
streams.push_back(StreamDescriptor(chan, j));
}
LogTrace("%zu streams were active when we connected\n", streams.size());
//No streams? Grab the first one.
if(streams.empty())
{
LogTrace("Enabling first available scope channel\n");
for(size_t i=0; i<scope->GetChannelCount(); i++)
{
auto chan = scope->GetOscilloscopeChannel(i);
if(!chan)
continue;
for(size_t j=0; j<chan->GetStreamCount(); j++)
{
StreamDescriptor s(chan, j);
auto stype = s.GetType();
if(stype == Stream::STREAM_TYPE_ANALOG_SCALAR)
continue;
if(s.GetFlags() & Stream::STREAM_INFREQUENTLY_USED)
continue;
streams.push_back(s);
break;
}
if(!streams.empty())
break;
}
}
}
//Add waveform areas for the streams
for(auto s : streams)
{
//Skip scalar streams as those don't make sense to put in a plot
auto stype = s.GetType();
if(stype == Stream::STREAM_TYPE_ANALOG_SCALAR)
continue;
//Skip infrequently used streams
if(s.GetFlags() & Stream::STREAM_INFREQUENTLY_USED)
continue;
//If this is a digital stream, add to existing digital waveform areas if one can be found
if(stype == Stream::STREAM_TYPE_DIGITAL)
{
FindAreaForStream(nullptr, s);
continue;
}
//Analog streams get their own area by default
else
{
auto group = GetBestGroupForWaveform(s);
auto area = make_shared<WaveformArea>(s, group, this);
group->AddArea(area);
}
}
}
//Refresh any dialogs that depend on it
RefreshStreamBrowserDialog();
RefreshTriggerPropertiesDialog();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Rendering
void MainWindow::Render()
{
//Shut down session, if requested, before starting the frame
if(m_sessionClosing)
{
{
QueueLock qlock(m_renderQueue);
(*qlock).waitIdle();
}
CloseSession();
InitializeDefaultSession();
}
//Load all of our fonts
UpdateFonts();
VulkanWindow::Render();
}
void MainWindow::DoRender(vk::raii::CommandBuffer& /*cmdBuf*/)
{
}
/**
@brief Run the tone-mapping shader on all of our waveforms
Called by Session::CheckForWaveforms() at the start of each frame if new data is ready to render
*/
void MainWindow::ToneMapAllWaveforms(vk::raii::CommandBuffer& cmdbuf)
{
double start = GetTime();
lock_guard<mutex> lock(m_session.GetRasterizedWaveformMutex());
m_cmdBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
//Tone map the waveforms, holding the group mutex for as short a time as possible
vector<shared_ptr<WaveformGroup>> groups;
{
lock_guard<recursive_mutex> lock2(m_waveformGroupsMutex);
groups = m_waveformGroups;
}
for(auto group : groups)
group->ToneMapAllWaveforms(cmdbuf);
m_cmdBuffer->end();
m_renderQueue->SubmitAndBlock(*m_cmdBuffer);
double dt = GetTime() - start;
m_toneMapTime = dt * FS_PER_SECOND;
}
void MainWindow::RenderWaveformTextures(
vk::raii::CommandBuffer& cmdbuf,
vector<shared_ptr<DisplayedChannel> >& channels)
{
bool clear = m_clearPersistence.exchange(false);
vector<shared_ptr<WaveformGroup>> groups;
{
lock_guard<recursive_mutex> lock2(m_waveformGroupsMutex);
groups = m_waveformGroups;
}
for(auto group : groups)
group->RenderWaveformTextures(cmdbuf, channels, clear);
}
void MainWindow::ResetStyle()
{
auto oldStyle = ImGui::GetStyle();
ImGui::GetStyle() = ImGuiStyle();
auto& style = ImGui::GetStyle();
style.FontSizeBase = oldStyle.FontSizeBase;
style.FontScaleMain = oldStyle.FontScaleMain;
style.FontScaleDpi = oldStyle.FontScaleDpi;
style.ScaleAllSizes(VulkanWindow::m_forceDPIScaling ? VulkanWindow::m_forcedUIScale : style.FontScaleDpi);
switch(m_session.GetPreferences().GetEnumRaw("Appearance.General.theme"))
{
case THEME_LIGHT:
ImGui::StyleColorsLight();
break;
case THEME_DARK:
ImGui::StyleColorsDark();
break;
case THEME_CLASSIC:
ImGui::StyleColorsClassic();
break;
}
}
void MainWindow::RenderUI()
{
//Update window title only if necessary, in case this is expensive on some platforms
string title = m_title + " - ";
if(m_sessionFileName.empty())
title += "[unsaved session]";
else
{
std::filesystem::path path(m_sessionFileName);
title += path.filename().string();
}
if(m_lastWindowTitle != title)
{
m_lastWindowTitle = title;
glfwSetWindowTitle(m_window, title.c_str());
}
auto defaultFont = GetFontPref("Appearance.General.default_font");
ImGui::PushFont(defaultFont.first, defaultFont.second);
ResetStyle();
m_needRender = false;
//Keep references to all of our waveform textures until next frame
//Any groups we're closing will be destroyed at the start of that frame, once rendering has finished
{
lock_guard<recursive_mutex> lock(m_waveformGroupsMutex);
for(auto g : m_waveformGroups)
g->ReferenceWaveformTextures();
}
//Destroy all waveform groups we were asked to close
//Block until all background processing completes to ensure no command buffers are still pending
if(!m_groupsToClose.empty())
{
lock_guard<shared_mutex> lock(g_vulkanActivityMutex);
g_vkComputeDevice->waitIdle();
m_groupsToClose.clear();
}
//Request a refresh of any dirty filters next frame
m_session.RefreshDirtyFiltersNonblocking();
//See if we have new waveform data to look at.
//If we got one, highlight the new waveform in history
if(m_session.CheckForWaveforms(*m_cmdBuffer))
{
if(m_historyDialog != nullptr)
m_historyDialog->UpdateSelectionToLatest();
//Tell protocol analyzer dialogs a new waveform arrived
auto t = m_session.GetHistory().GetMostRecentPoint();
for(auto it : m_protocolAnalyzerDialogs)
it.second->OnWaveformLoaded(t);
}
//Menu for main window
MainMenu();
Toolbar();
//Docking area to put all of the groups in
DockingArea();
//Waveform groups
{
shared_lock<shared_mutex> lock(m_session.GetWaveformDataMutex());
lock_guard<recursive_mutex> lock2(m_waveformGroupsMutex);
for(size_t i=0; i<m_waveformGroups.size(); i++)
{
auto group = m_waveformGroups[i];
if(!group->Render())
{
LogTrace("Closing waveform group %s (i=%zu)\n", group->GetTitle().c_str(), i);
group->Clear();
m_groupsToClose.push_back(i);
}
}
for(ssize_t i = static_cast<ssize_t>(m_groupsToClose.size())-1; i >= 0; i--)
m_waveformGroups.erase(m_waveformGroups.begin() + m_groupsToClose[i]);
}
//Now that we are not holding the render mutex anymore, it's safe to have the session refresh newly created filters
if(!m_pendingChannelDisplayRequests.empty())
{
//Re-run the filter graph so we have an initial waveform to look at
//(This needs to be blocking so that we know the output data format when spawning the viewports)
m_session.RefreshDirtyFilters();
for(auto it : m_pendingChannelDisplayRequests)
{
auto f = it.first;
for(size_t i=0; i<f->GetStreamCount(); i++)
FindAreaForStream(it.second, StreamDescriptor(f, i));
f->Release();
}
m_pendingChannelDisplayRequests.clear();
}
//Dialog boxes
m_session.SetHoveredPacketTimestamp({});
set< shared_ptr<Dialog> > dlgsToClose;
for(auto& dlg : m_dialogs)
{
if(!dlg->Render())
dlgsToClose.emplace(dlg);
}
for(auto& dlg : dlgsToClose)
OnDialogClosed(dlg);
//If we had a history dialog, check if we changed the selection
if( (m_historyDialog != nullptr) && (m_historyDialog->PollForSelectionChanges()))
{
LogTrace("history selection changed\n");
m_historyDialog->LoadHistoryFromSelection(m_session);
auto t = m_historyDialog->GetSelectedPoint();
if(t != TimePoint(0,0))
{
for(auto it : m_protocolAnalyzerDialogs)
it.second->OnWaveformLoaded(t);
}
m_session.RefreshAllFiltersNonblocking();
m_needRender = true;
}
//File browser dialogs
if(m_fileBrowser)
RenderFileBrowser();
//Check if we changed the selected waveform from a protocol analyzer dialog
for(auto it : m_protocolAnalyzerDialogs)
{
if(it.second->PollForSelectionChanges())
{
auto tstamp = it.second->GetSelectedWaveformTimestamp();
auto& hist = m_session.GetHistory();
if(m_historyDialog)
m_historyDialog->SelectTimestamp(tstamp);
auto hpt = hist.GetHistory(tstamp);
if(hpt)
{
hpt->LoadHistoryToSession(m_session);
m_needRender = true;
}
m_session.RefreshAllFiltersNonblocking();
}
}
//Handle error messages and other blocking notifications
RenderReconnectPopup();
RenderErrorPopup();
RenderLoadWarningPopup();
if(m_needRender)
g_rerenderRequestedEvent.Signal();
//DEBUG: draw the demo windows
if(m_showDemo)
ImGui::ShowDemoWindow(&m_showDemo);
ImGui::PopFont();
}
void MainWindow::Toolbar()
{
//Update icons, if needed
LoadToolbarIcons();
//Toolbar should be at the top of the main window.
//Update work area size so docking area doesn't include the toolbar rectangle
auto viewport = ImGui::GetMainViewport();
float toolbarHeight = 2.5 * ImGui::GetFontSize();
m_workPos = ImVec2(viewport->WorkPos.x, viewport->WorkPos.y + toolbarHeight);
m_workSize = ImVec2(viewport->WorkSize.x, viewport->WorkSize.y - toolbarHeight);
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(ImVec2(viewport->WorkSize.x, toolbarHeight));
//Make the toolbar window
auto wflags =
ImGuiWindowFlags_NoDocking |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoCollapse;
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
bool open = true;
ImGui::Begin("toolbar", &open, wflags);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
//Do the actual toolbar buttons
ToolbarButtons();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
//Slider for trace alpha
ImGui::SameLine();
float y = ImGui::GetCursorPosY();
ImGui::SetCursorPosY(y + 5);
ImGui::SetNextItemWidth(6 * toolbarHeight);
if(ImGui::SliderFloat("Intensity", &m_traceAlpha, 0, 0.75, "", ImGuiSliderFlags_Logarithmic))
SetNeedRender();
ImGui::End();
}
/**
@brief Load gradient images
*/
void MainWindow::LoadGradients()
{
LogTrace("Loading eye pattern gradients...\n");
LogIndenter li;
LoadGradient("CRT", "eye-gradient-crt");
LoadGradient("Grayscale", "eye-gradient-grayscale");
LoadGradient("Ironbow", "eye-gradient-ironbow");
LoadGradient("KRain", "eye-gradient-krain");
LoadGradient("Rainbow", "eye-gradient-rainbow");
LoadGradient("Reverse Grayscale", "eye-gradient-reverse-grayscale");
LoadGradient("Reverse Rainbow", "eye-gradient-reverse-rainbow");
LoadGradient("Reverse Viridis", "eye-gradient-reverse-viridis");
LoadGradient("Viridis", "eye-gradient-viridis");
}
/**
@brief Load a single gradient
*/
void MainWindow::LoadGradient(const string& friendlyName, const string& internalName)
{
string prefix = string("icons/gradients/");
m_texmgr.LoadTexture(internalName, FindDataFile(prefix + internalName + ".png"));
m_eyeGradientFriendlyNames[internalName] = friendlyName;
m_eyeGradients.push_back(internalName);
}
bool MainWindow::DropdownButton(const char* id, float height)
{
auto pos = ImGui::GetCursorPos();
auto buttonheight = ImGui::GetFontSize() + ImGui::GetStyle().FramePadding.y;
pos.y += (height - buttonheight);
ImGui::SetCursorPos(pos);
return ImGui::ArrowButton(id, ImGuiDir_Down);
}
void MainWindow::DoTriggerDropdown(const char* action, shared_ptr<TriggerGroup>& group, bool& all)
{
all = false;
ImGuiTableFlags flags =
ImGuiTableFlags_Resizable |
ImGuiTableFlags_BordersOuter |
ImGuiTableFlags_BordersV |
ImGuiTableFlags_RowBg |
ImGuiTableFlags_SizingFixedFit |
ImGuiTableFlags_NoKeepColumnsVisible;
if(ImGui::BeginTable("groups", 3, flags))
{
float width = ImGui::GetFontSize();
ImGui::TableSetupColumn("Default", ImGuiTableColumnFlags_WidthFixed, 4*width);
ImGui::TableSetupColumn("Group", ImGuiTableColumnFlags_WidthFixed, 12*width);
ImGui::TableSetupColumn("Actions", ImGuiTableColumnFlags_WidthFixed, 8*width);
ImGui::TableHeadersRow();
auto groups = m_session.GetTriggerGroups();
for(auto g : groups)
{
ImGui::PushID(g.get());
ImGui::TableNextRow(ImGuiTableRowFlags_None);
//Default checkbox
ImGui::TableSetColumnIndex(0);
ImGui::Checkbox("###default", &g->m_default);
//Group name
ImGui::TableSetColumnIndex(1);
ImGui::TextUnformatted(g->GetDescription().c_str());
//Action buttons
ImGui::TableSetColumnIndex(2);
if(ImGui::Button(action))
group = g;
ImGui::PopID();
}
ImGui::PushID("all");
ImGui::TableNextRow(ImGuiTableRowFlags_None);
ImGui::TableSetColumnIndex(1);
ImGui::TextUnformatted("All");
//Action buttons
ImGui::TableSetColumnIndex(2);
if(ImGui::Button(action))
all = true;
ImGui::PopID();
ImGui::EndTable();
}
}
void MainWindow::TriggerStartDropdown(float buttonsize)
{
if(DropdownButton("trigger-start-dropdown", buttonsize))
ImGui::OpenPopup("TriggerStartMenu");
if(ImGui::BeginPopup("TriggerStartMenu"))
{
bool all = false;
shared_ptr<TriggerGroup> group;
DoTriggerDropdown("Start", group, all);
if(group)
group->Arm(TriggerGroup::TRIGGER_TYPE_NORMAL);
if(all)
m_session.ArmTrigger(TriggerGroup::TRIGGER_TYPE_NORMAL, true);
ImGui::EndPopup();
}
}
void MainWindow::TriggerSingleDropdown(float buttonsize)
{
if(DropdownButton("trigger-single-dropdown", buttonsize))
ImGui::OpenPopup("TriggerSingleMenu");
if(ImGui::BeginPopup("TriggerSingleMenu"))
{
bool all = false;
shared_ptr<TriggerGroup> group;
DoTriggerDropdown("Single", group, all);
//Start trigger for only a specific group
if(group)
group->Arm(TriggerGroup::TRIGGER_TYPE_SINGLE);
//Start trigger for all groups
if(all)
m_session.ArmTrigger(TriggerGroup::TRIGGER_TYPE_SINGLE, true);
ImGui::EndPopup();
}
}
void MainWindow::TriggerForceDropdown(float buttonsize)
{
if(DropdownButton("trigger-force-dropdown", buttonsize))
ImGui::OpenPopup("TriggerForceMenu");
if(ImGui::BeginPopup("TriggerForceMenu"))
{
bool all = false;
shared_ptr<TriggerGroup> group;
DoTriggerDropdown("Force", group, all);
//Start trigger for only a specific group
if(group)
group->Arm(TriggerGroup::TRIGGER_TYPE_FORCED);
//Start trigger for all groups
if(all)
m_session.ArmTrigger(TriggerGroup::TRIGGER_TYPE_FORCED, true);