forked from ngscopeclient/scopehal-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveformGroup.cpp
More file actions
1476 lines (1251 loc) · 43.6 KB
/
WaveformGroup.cpp
File metadata and controls
1476 lines (1251 loc) · 43.6 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-2025 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 WaveformGroup
*/
#include "ngscopeclient.h"
#include "WaveformGroup.h"
#include "MainWindow.h"
#include "imgui_internal.h"
#include "../../scopeprotocols/EyePattern.h"
#include "../../scopeprotocols/ConstellationFilter.h"
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction
WaveformGroup::WaveformGroup(MainWindow* parent, const string& title)
: m_parent(parent)
, m_xpos(0)
, m_width(0)
, m_pixelsPerXUnit(0.00005)
, m_xAxisOffset(0)
, m_title(title)
, m_id(title)
, m_xAxisUnit(Unit::UNIT_FS)
, m_dragState(DRAG_STATE_NONE)
, m_dragMarker(nullptr)
, m_tLastMouseMove(GetTime())
, m_timelineHeight(0)
, m_mouseOverTriggerArrow(false)
, m_mouseOverMarker(false)
, m_scopeTriggerDuringDrag(nullptr)
, m_displayingEye(false)
, m_xAxisCursorMode(X_CURSOR_NONE)
{
m_xAxisCursorPositions[0] = 0;
m_xAxisCursorPositions[1] = 0;
}
WaveformGroup::~WaveformGroup()
{
Clear();
}
void WaveformGroup::Clear()
{
lock_guard<mutex> lock(m_areaMutex);
LogTrace("Destroying areas\n");
LogIndenter li;
m_areas.clear();
LogTrace("All areas removed\n");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Area management
void WaveformGroup::AddArea(shared_ptr<WaveformArea>& area)
{
lock_guard<mutex> lock(m_areaMutex);
{
//If this is our first area, adopt its X axis unit as our own
if(m_areas.empty())
m_xAxisUnit = area->GetStream(0).GetXAxisUnits();
m_areas.push_back(area);
}
m_parent->RefreshStreamBrowserDialog();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Rendering
/**
@brief Run the tone-mapping shader on all of our waveforms
Called by MainWindow::ToneMapAllWaveforms() at the start of each frame if new data is ready to render
*/
void WaveformGroup::ToneMapAllWaveforms(vk::raii::CommandBuffer& cmdbuf)
{
auto areas = GetWaveformAreas();
for(auto a : areas)
a->ToneMapAllWaveforms(cmdbuf);
}
void WaveformGroup::ReferenceWaveformTextures()
{
auto areas = GetWaveformAreas();
for(auto a : areas)
a->ReferenceWaveformTextures();
}
void WaveformGroup::RenderWaveformTextures(
vk::raii::CommandBuffer& cmdbuf,
vector<shared_ptr<DisplayedChannel> >& channels,
bool clearPersistence)
{
bool clearThisGroupOnly = m_clearPersistence.exchange(false);
auto areas = GetWaveformAreas();
for(auto a : areas)
a->RenderWaveformTextures(cmdbuf, channels, clearThisGroupOnly || clearPersistence);
}
bool WaveformGroup::Render()
{
auto areas = GetWaveformAreas();
bool open = true;
ImGui::SetNextWindowSize(ImVec2(320, 240), ImGuiCond_Appearing);
if(!ImGui::Begin(GetID().c_str(), &open, ImGuiWindowFlags_NoScrollWithMouse))
{
//tabbed out, don't draw anything until we're back in the foreground
TitleHoverHelp();
ImGui::End();
return true;
}
//Check for right click on the title bar
//see https://github.com/ocornut/imgui/issues/7914
if(ImGui::BeginPopupContextItem())
{
ImGui::InputText("Name", &m_title);
ImGui::EndPopup();
}
TitleHoverHelp();
auto pos = ImGui::GetCursorScreenPos();
ImVec2 clientArea = ImGui::GetContentRegionAvail();
m_width = clientArea.x;
float yAxisWidthSpaced = GetYAxisWidth() + GetSpacing();
float plotWidth = clientArea.x - yAxisWidthSpaced;
//Update X axis unit
if(!areas.empty())
{
m_displayingEye = false;
m_xAxisUnit = areas[0]->GetStream(0).GetXAxisUnits();
//Autoscale eye patterns
auto firstStream = areas[0]->GetFirstAnalogOrDensityStream();
if(firstStream && (firstStream.GetType() == Stream::STREAM_TYPE_EYE))
{
auto eye = dynamic_cast<EyeWaveform*>(firstStream.GetData());
if(eye && eye->GetWidth())
{
m_pixelsPerXUnit = plotWidth / (2*eye->GetUIWidth());
m_xAxisOffset = -PixelsToXAxisUnits(plotWidth/2);
m_displayingEye = true;
}
}
if(firstStream && (firstStream.GetType() == Stream::STREAM_TYPE_CONSTELLATION))
{
//voltage range is in V, but x axis is in uV because it needs t obe integers
auto vrange = firstStream.GetVoltageRange();
m_pixelsPerXUnit = plotWidth / (1e6 * vrange);
m_xAxisOffset = -PixelsToXAxisUnits(plotWidth/2);
m_displayingEye = true;
}
}
//Render the timeline
m_timelineHeight = 2.5 * ImGui::GetFontSize();
RenderTimeline(plotWidth, m_timelineHeight);
//Close any areas that we destroyed last frame
//Block until all background processing completes to ensure no command buffers are still pending
if(!m_areasToClose.empty())
{
g_vkComputeDevice->waitIdle();
m_areasToClose.clear();
}
//Render our waveform areas
//TODO: waveform areas full of protocol or digital decodes should be fixed size while analog will fill the gap?
//Anything we closed is removed from the list THIS frame, so we stop rendering to them etc
//but not actually destroyed until next frame
for(size_t i=0; i<areas.size(); i++)
{
if(!areas[i]->Render(i, areas.size(), clientArea))
m_areasToClose.push_back(i);
}
for(ssize_t i=static_cast<ssize_t>(m_areasToClose.size()) - 1; i >= 0; i--)
m_areas.erase(m_areas.begin() + m_areasToClose[i]);
if(!m_areasToClose.empty())
m_parent->RefreshStreamBrowserDialog();
//If we no longer have any areas in the group, close the group
if(areas.empty())
open = false;
//Render cursors over everything else
ImVec2 plotSize(plotWidth, clientArea.y);
RenderXAxisCursors(pos, plotSize);
if(m_xAxisCursorMode != X_CURSOR_NONE)
DoCursorReadouts();
RenderMarkers(pos, plotSize);
ImGui::End();
return open;
}
void WaveformGroup::TitleHoverHelp()
{
if(ImGui::IsItemHovered())
{
m_parent->AddStatusHelp("mouse_lmb_drag", "Move group");
m_parent->AddStatusHelp("mouse_rmb", "Rename group");
}
}
/**
@brief Run the popup window with cursor values
*/
void WaveformGroup::DoCursorReadouts()
{
auto areas = GetWaveformAreas();
bool hasSecondCursor = (m_xAxisCursorMode == X_CURSOR_DUAL);
string name = string("Cursors (") + m_title + ")";
float width = ImGui::GetFontSize();
ImGui::SetNextWindowSize(ImVec2(45*width, 15*width), ImGuiCond_Appearing);
if(ImGui::Begin(name.c_str(), nullptr, ImGuiWindowFlags_NoCollapse))
{
static ImGuiTableFlags flags =
ImGuiTableFlags_Resizable |
ImGuiTableFlags_BordersOuter |
ImGuiTableFlags_BordersV |
ImGuiTableFlags_ScrollY;
//Add columns for second cursor if enabled
int ncols = 2;
if(hasSecondCursor)
ncols += 3;
if(ImGui::BeginTable("cursors", ncols, flags))
{
//Header row
//TODO: only show in-band power column if units match up?
ImGui::TableSetupScrollFreeze(0, 1); //Header row does not scroll
ImGui::TableSetupColumn("Channel", ImGuiTableColumnFlags_WidthFixed, 10*width);
ImGui::TableSetupColumn("Value 1", ImGuiTableColumnFlags_WidthFixed, 8*width);
if(hasSecondCursor)
{
ImGui::TableSetupColumn("Value 2", ImGuiTableColumnFlags_WidthFixed, 8*width);
ImGui::TableSetupColumn("Delta", ImGuiTableColumnFlags_WidthFixed, 8*width);
ImGui::TableSetupColumn("Band", ImGuiTableColumnFlags_WidthFixed, 8*width);
}
ImGui::TableHeadersRow();
//Readout for each channel in all of our waveform areas
for(auto a : areas)
{
for(size_t i=0; i<a->GetStreamCount(); i++)
{
auto stream = a->GetStream(i);
auto sname = stream.GetName();
//Prepare to pretty print
auto data = stream.GetData();
string sv1 = "(no data)";
string sv2 = "(no data)";
string svd = "(no data)";
switch(stream.GetType())
{
//Analog path
case Stream::STREAM_TYPE_ANALOG:
{
bool zhold = (stream.GetFlags() & Stream::STREAM_DO_NOT_INTERPOLATE) ? true : false;
auto v1 = GetValueAtTime(data, m_xAxisCursorPositions[0], zhold);
auto v2 = GetValueAtTime(data, m_xAxisCursorPositions[1], zhold);
if(v1)
sv1 = stream.GetYAxisUnits().PrettyPrint(v1.value());
if(v2)
sv2 = stream.GetYAxisUnits().PrettyPrint(v2.value());
if(v1 && v2)
svd = stream.GetYAxisUnits().PrettyPrint(v2.value() - v1.value());
}
break;
//Digital path
case Stream::STREAM_TYPE_DIGITAL:
{
auto v1 = GetDigitalValueAtTime(data, m_xAxisCursorPositions[0]);
auto v2 = GetDigitalValueAtTime(data, m_xAxisCursorPositions[1]);
if(v1)
sv1 = to_string(v1.value());
if(v2)
sv2 = to_string(v2.value());
svd = "";
}
break;
//TODO
case Stream::STREAM_TYPE_DIGITAL_BUS:
sv1 = "(unimplemented)";
sv2 = "(unimplemented)";
svd = "(unimplemented)";
break;
//Cursor readout on density plots makes no sense
//TODO: read out eye height or something for eyes?
case Stream::STREAM_TYPE_EYE:
case Stream::STREAM_TYPE_SPECTROGRAM:
case Stream::STREAM_TYPE_WATERFALL:
case Stream::STREAM_TYPE_TRIGGER:
case Stream::STREAM_TYPE_UNDEFINED:
case Stream::STREAM_TYPE_ANALOG_SCALAR:
case Stream::STREAM_TYPE_CONSTELLATION:
sv1 = "";
sv2 = "";
svd = "";
break;
//Read out protocol decode stuff
case Stream::STREAM_TYPE_PROTOCOL:
{
auto v1 = GetProtocolValueAtTime(data, m_xAxisCursorPositions[0]);
auto v2 = GetProtocolValueAtTime(data, m_xAxisCursorPositions[1]);
if(v1)
sv1 = v1.value();
if(v2)
sv2 = v2.value();
svd = "";
}
break;
}
ImGui::PushID(sname.c_str());
ImGui::TableNextRow(ImGuiTableRowFlags_None, 0);
//Channel name
ImGui::TableSetColumnIndex(0);
auto color = ColorFromString(stream.m_channel->m_displaycolor);
ImGui::PushStyleColor(ImGuiCol_Text, color);
ImGui::TextUnformatted(sname.c_str());
ImGui::PopStyleColor();
//Cursor 0 value
ImGui::TableSetColumnIndex(1);
RightJustifiedText(sv1);
if(hasSecondCursor)
{
//Cursor 1 value
ImGui::TableSetColumnIndex(2);
RightJustifiedText(sv2);
//Delta
ImGui::TableSetColumnIndex(3);
RightJustifiedText(svd);
//In-band power
Unit punit(Unit::UNIT_COUNTS);
bool ok = true;
switch(stream.GetYAxisUnits().GetType())
{
case Unit::UNIT_DBM:
punit = Unit(Unit::UNIT_DBM);
break;
case Unit::UNIT_W_M2_NM:
punit = Unit(Unit::UNIT_W_M2);
break;
default:
ok = false;
}
if(ok)
{
auto power = GetInBandPower(
data,
stream.GetYAxisUnits(),
m_xAxisCursorPositions[0],
m_xAxisCursorPositions[1]);
ImGui::TableSetColumnIndex(4);
RightJustifiedText(punit.PrettyPrint(power));
}
}
ImGui::PopID();
}
}
ImGui::EndTable();
}
}
ImGui::End();
}
/**
@brief Calculates the in-band power between two frequencies
*/
float WaveformGroup::GetInBandPower(WaveformBase* wfm, Unit yunit, int64_t t1, int64_t t2)
{
auto swfm = dynamic_cast<SparseAnalogWaveform*>(wfm);
auto uwfm = dynamic_cast<UniformAnalogWaveform*>(wfm);
//Make sure we have data
if(!swfm && !uwfm)
return 0;
if(!wfm->size())
return 0;
//Get the samples and start/end indexex
auto& samples = swfm ? swfm->m_samples : uwfm->m_samples;
bool err1;
bool err2;
auto ileft = GetIndexNearestAtOrBeforeTimestamp(wfm, t1, err1);
auto iright = GetIndexNearestAtOrBeforeTimestamp(wfm, t2, err2);
if(err1)
ileft = 0;
if(err2)
iright = wfm->size() - 1;
//Sum the in-band power
//Note that if it's in dBm we have to go to linear units and back
bool is_log = (yunit == Unit::UNIT_DBM);
bool is_irradiance = (yunit == Unit::UNIT_W_M2_NM);
float total = 0;
for(size_t i=ileft; i <= iright; i++)
{
float f = samples[i];
if(is_log)
total += pow(10, (f - 30) / 10); //assume
else if(is_irradiance)
total += f * GetDurationScaled(swfm, uwfm, i) * 1e-3; //scale by pm to nm
else
total += f;
}
if(is_log)
total = 10 * log10(total) + 30;
return total;
}
/**
@brief Render our markers (and the hovered-packet indicator if any)
*/
void WaveformGroup::RenderMarkers(ImVec2 pos, ImVec2 size)
{
m_mouseOverMarker = false;
//Don't draw anything if our unit isn't fs
//TODO: support units for frequency domain channels etc?
//TODO: early out if eye pattern
if(m_xAxisUnit != Unit(Unit::UNIT_FS))
return;
//Don't crash if we have no areas
if(m_areas.empty())
return;
auto& session = m_parent->GetSession();
auto wavetime = m_areas[0]->GetWaveformTimestamp();
auto& markers = session.GetMarkers(wavetime);
auto packetHover = session.GetHoveredPacketTimestamp();
//Create a child window for all of our drawing
//(this is needed so we're above the WaveformArea's in z order, but behind popup windows)
ImGui::SetNextWindowPos(pos, ImGuiCond_Always);
if(ImGui::BeginChild("markers", size, false, ImGuiWindowFlags_NoInputs))
{
auto list = ImGui::GetWindowDrawList();
auto& prefs = m_parent->GetSession().GetPreferences();
auto color = prefs.GetColor("Appearance.Cursors.marker_color");
auto hcolor = prefs.GetColor("Appearance.Cursors.hover_color");
auto font = m_parent->GetFontPref("Appearance.Cursors.label_font");
ImGui::PushFont(font.first, font.second);
//Draw the markers
for(auto& m : markers)
{
//Lines
float xpos = round(XAxisUnitsToXPosition(m.m_offset));
list->AddLine(ImVec2(xpos, pos.y), ImVec2(xpos, pos.y + size.y), color);
//Text
//Anchor bottom right at the cursor
auto str = m.m_name + ": " + m_xAxisUnit.PrettyPrint(m.m_offset);
auto tsize = ImGui::CalcTextSize(str.c_str());
float padding = 2;
float wrounding = 2;
float textTop = pos.y + m_timelineHeight - (padding + tsize.y);
list->AddRectFilled(
ImVec2(xpos - (2*padding + tsize.x), textTop - padding ),
ImVec2(xpos - 1, pos.y + m_timelineHeight),
ImGui::GetColorU32(ImGuiCol_PopupBg),
wrounding);
list->AddText(
ImVec2(xpos - (padding + tsize.x), textTop),
color,
str.c_str());
}
//Draw the hovered packet, if any
if(packetHover)
{
//Calculate the delta between the times
auto offset = packetHover.value() - wavetime;
//Lines
auto xpos = round(XAxisUnitsToXPosition(offset));
list->AddLine(ImVec2(xpos, pos.y), ImVec2(xpos, pos.y + size.y), hcolor);
}
ImGui::PopFont();
}
ImGui::EndChild();
if(m_dragState == DRAG_STATE_MARKER)
m_parent->AddStatusHelp("mouse_lmb_drag", "Move marker");
auto mouse = ImGui::GetMousePos();
if(!IsMouseOverButtonInWaveformArea())
{
for(auto& m : markers)
{
//Child window doesn't get mouse events (this flag is needed so we can pass mouse events to the WaveformArea's)
//So we have to do all of our interaction processing inside the top level window
//TODO: this is basically DoCursor(), can we de-duplicate this code?
float xpos = round(XAxisUnitsToXPosition(m.m_offset));
float searchRadius = 0.25 * ImGui::GetFontSize();
//Check if the mouse hit us
if(ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows))
{
if( fabs(mouse.x - xpos) < searchRadius)
{
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
m_mouseOverMarker = true;
m_parent->AddStatusHelp("mouse_lmb", "");
m_parent->AddStatusHelp("mouse_lmb_drag", "Move marker");
//Start dragging if clicked
if(ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
if(m_dragState == DRAG_STATE_NONE)
{
LogTrace("starting to drag marker %s\n", m.m_name.c_str());
m_dragState = DRAG_STATE_MARKER;
m_dragMarker = &m;
}
else
LogTrace("ignoring click on marker because m_dragState = %d\n", m_dragState);
}
}
}
}
}
//If dragging, move the cursor to track
if(m_dragState == DRAG_STATE_MARKER)
{
if(ImGui::IsMouseReleased(ImGuiMouseButton_Left))
{
LogTrace("done dragging marker %s\n", m_dragMarker->m_name.c_str());
m_dragState = DRAG_STATE_NONE;
}
auto newpos = XPositionToXAxisUnits(mouse.x);
if(m_dragMarker->m_offset != newpos)
{
auto name = m_dragMarker->m_name;
m_dragMarker->m_offset = newpos;
m_parent->GetSession().OnMarkerChanged();
//Find the marker again
//This is needed because OnMarkerChanged() sorts the list of markers
//which can potentially invalidate our pointer
for(auto& m : markers)
{
if(m.m_name == name)
{
m_dragMarker = &m;
break;
}
}
}
if(m_dragState == DRAG_STATE_NONE)
m_dragMarker = nullptr;
}
}
/**
@brief Returns true if the mouse is over a channel button or similar UI element in a WaveformArea
*/
bool WaveformGroup::IsMouseOverButtonInWaveformArea()
{
for(auto& p : m_areas)
{
if(p->IsMouseOverButtonAtEndOfRender())
return true;
}
return false;
}
/**
@brief Render our cursors
*/
void WaveformGroup::RenderXAxisCursors(ImVec2 pos, ImVec2 size)
{
//No cursors? Nothing to do
if(m_xAxisCursorMode == X_CURSOR_NONE)
{
//Exit cursor drag state if we no longer have a cursor to drag
if( (m_dragState == DRAG_STATE_X_CURSOR0) || (m_dragState == DRAG_STATE_X_CURSOR1) )
m_dragState = DRAG_STATE_NONE;
return;
}
//Create a child window for all of our drawing
//(this is needed so we're above the WaveformArea's in z order, but behind popup windows)
ImGui::SetNextWindowPos(pos, ImGuiCond_Always);
if(ImGui::BeginChild("cursors", size, false, ImGuiWindowFlags_NoInputs))
{
auto list = ImGui::GetWindowDrawList();
auto& prefs = m_parent->GetSession().GetPreferences();
auto cursor0_color = prefs.GetColor("Appearance.Cursors.cursor_1_color");
auto cursor1_color = prefs.GetColor("Appearance.Cursors.cursor_2_color");
auto fill_color = prefs.GetColor("Appearance.Cursors.cursor_fill_color");
auto font = m_parent->GetFontPref("Appearance.Cursors.label_font");
ImGui::PushFont(font.first, font.second);
float xpos0 = round(XAxisUnitsToXPosition(m_xAxisCursorPositions[0]));
float xpos1 = round(XAxisUnitsToXPosition(m_xAxisCursorPositions[1]));
//Fill between if dual cursor
if(m_xAxisCursorMode == X_CURSOR_DUAL)
list->AddRectFilled(ImVec2(xpos0, pos.y), ImVec2(xpos1, pos.y + size.y), fill_color);
//First cursor
list->AddLine(ImVec2(xpos0, pos.y), ImVec2(xpos0, pos.y + size.y), cursor0_color, 1);
//Text
//Anchor bottom right at the cursor
auto str = string("X1: ") + m_xAxisUnit.PrettyPrint(m_xAxisCursorPositions[0]);
auto tsize = ImGui::CalcTextSize(str.c_str());
float padding = 2;
float wrounding = 2;
float textTop = pos.y + m_timelineHeight - (padding + tsize.y);
list->AddRectFilled(
ImVec2(xpos0 - (2*padding + tsize.x), textTop - padding ),
ImVec2(xpos0 - 1, pos.y + m_timelineHeight),
ImGui::GetColorU32(ImGuiCol_PopupBg),
wrounding);
list->AddText(
ImVec2(xpos0 - (padding + tsize.x), textTop),
cursor0_color,
str.c_str());
//Second cursor
if(m_xAxisCursorMode == X_CURSOR_DUAL)
{
list->AddLine(ImVec2(xpos1, pos.y), ImVec2(xpos1, pos.y + size.y), cursor1_color, 1);
int64_t delta = m_xAxisCursorPositions[1] - m_xAxisCursorPositions[0];
str = string("X2: ") + m_xAxisUnit.PrettyPrint(m_xAxisCursorPositions[1]) + "\n" +
"ΔX = " + m_xAxisUnit.PrettyPrint(delta);
//If X axis is time domain, show frequency dual
Unit hz(Unit::UNIT_HZ);
if(m_xAxisUnit.GetType() == Unit::UNIT_FS)
str += string(" (") + hz.PrettyPrint(FS_PER_SECOND / delta) + ")";
//Text
tsize = ImGui::CalcTextSize(str.c_str());
textTop = pos.y + m_timelineHeight - (padding + tsize.y);
list->AddRectFilled(
ImVec2(xpos1 + 1, textTop - padding ),
ImVec2(xpos1 + (2*padding + tsize.x), pos.y + m_timelineHeight),
ImGui::GetColorU32(ImGuiCol_PopupBg),
wrounding);
list->AddText(
ImVec2(xpos1 + padding, textTop),
cursor1_color,
str.c_str());
}
//not dragging if we no longer have a second cursor
else if(m_dragState == DRAG_STATE_X_CURSOR1)
m_dragState = DRAG_STATE_NONE;
//TODO: text for value readouts, in-band power, etc
ImGui::PopFont();
}
ImGui::EndChild();
//Default help text related to cursors (may change if we're over a cursor)
if(ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) &&
!IsMouseOverButtonInWaveformArea() &&
(m_dragState == DRAG_STATE_NONE) )
{
if(m_xAxisCursorMode != X_CURSOR_NONE)
m_parent->AddStatusHelp("mouse_lmb", "Place first cursor");
if(m_xAxisCursorMode == X_CURSOR_DUAL)
m_parent->AddStatusHelp("mouse_lmb_drag", "Place second cursor");
}
if( (m_dragState == DRAG_STATE_X_CURSOR0) || (m_dragState == DRAG_STATE_X_CURSOR1) )
m_parent->AddStatusHelp("mouse_lmb_drag", "Move cursor");
//Child window doesn't get mouse events (this flag is needed so we can pass mouse events to the WaveformArea's)
//So we have to do all of our interaction processing inside the top level window
DoCursor(0, DRAG_STATE_X_CURSOR0);
if(m_xAxisCursorMode == X_CURSOR_DUAL)
DoCursor(1, DRAG_STATE_X_CURSOR1);
//If not currently dragging, a click places cursor 0 and starts dragging cursor 1 (if enabled)
//Don't process this if a popup is open
if( ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) &&
(m_dragState == DRAG_STATE_NONE) &&
ImGui::IsMouseClicked(ImGuiMouseButton_Left) &&
!IsMouseOverButtonInWaveformArea() &&
!ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel) &&
!m_mouseOverMarker)
{
auto xpos = ImGui::GetMousePos().x;
//Don't check for clicks outside of the main plot area
//(clicks on the Y axis should not be treated as cursor events)
if(xpos < (pos.x + m_width - GetYAxisWidth()) )
{
m_xAxisCursorPositions[0] = XPositionToXAxisUnits(xpos);
m_parent->OnCursorMoved(m_xAxisCursorPositions[0]);
if(m_xAxisCursorMode == X_CURSOR_DUAL)
{
m_dragState = DRAG_STATE_X_CURSOR1;
m_xAxisCursorPositions[1] = m_xAxisCursorPositions[0];
}
else
m_dragState = DRAG_STATE_X_CURSOR0;
}
}
//Cursor 0 should always be left of cursor 1 (if both are enabled).
//If they get swapped, exchange them.
if( (m_xAxisCursorPositions[0] > m_xAxisCursorPositions[1]) && (m_xAxisCursorMode == X_CURSOR_DUAL) )
{
//Swap the cursors themselves
int64_t tmp = m_xAxisCursorPositions[0];
m_xAxisCursorPositions[0] = m_xAxisCursorPositions[1];
m_xAxisCursorPositions[1] = tmp;
//If dragging one cursor, switch to dragging the other
if(m_dragState == DRAG_STATE_X_CURSOR0)
m_dragState = DRAG_STATE_X_CURSOR1;
else if(m_dragState == DRAG_STATE_X_CURSOR1)
m_dragState = DRAG_STATE_X_CURSOR0;
}
}
void WaveformGroup::DoCursor(int iCursor, DragState state)
{
float xpos = round(XAxisUnitsToXPosition(m_xAxisCursorPositions[iCursor]));
float searchRadius = 0.5 * ImGui::GetFontSize();
//Check if the mouse hit us
auto mouse = ImGui::GetMousePos();
if(ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows) && !IsMouseOverButtonInWaveformArea())
{
if( fabs(mouse.x - xpos) < searchRadius)
{
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);
m_parent->AddStatusHelp("mouse_lmb", "");
m_parent->AddStatusHelp("mouse_lmb_drag", "Move cursor");
//Start dragging if clicked
if(ImGui::IsMouseClicked(ImGuiMouseButton_Left))
m_dragState = state;
}
}
//If dragging, move the cursor to track
if(m_dragState == state)
{
if(ImGui::IsMouseReleased(ImGuiMouseButton_Left))
m_dragState = DRAG_STATE_NONE;
m_xAxisCursorPositions[iCursor] = XPositionToXAxisUnits(mouse.x);
if(iCursor == 0)
m_parent->OnCursorMoved(m_xAxisCursorPositions[iCursor]);
}
}
void WaveformGroup::RenderTimeline(float width, float height)
{
ImGui::BeginChild("timeline", ImVec2(width, height));
auto list = ImGui::GetWindowDrawList();
//Style settings
auto& prefs = m_parent->GetSession().GetPreferences();
auto color = prefs.GetColor("Appearance.Timeline.axis_color");
auto textcolor = prefs.GetColor("Appearance.Timeline.text_color");
auto font = m_parent->GetFontPref("Appearance.Timeline.x_axis_font");
ImGui::PushFont(font.first, font.second);
//Reserve an empty area for the timeline
auto pos = ImGui::GetWindowPos();
m_xpos = pos.x;
ImGui::Dummy(ImVec2(width, height));
//Detect mouse movement
double tnow = GetTime();
auto mouseDelta = ImGui::GetIO().MouseDelta;
if( (mouseDelta.x != 0) || (mouseDelta.y != 0) )
m_tLastMouseMove = tnow;
ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelY);
if(ImGui::IsItemHovered())
{
//Catch mouse wheel events
auto wheel = ImGui::GetIO().MouseWheel;
if(wheel != 0)
OnMouseWheel(wheel);
//Start dragging
if(ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
if(!m_displayingEye)
m_dragState = DRAG_STATE_TIMELINE;
}
//Autoscale on middle mouse
if(ImGui::IsMouseClicked(ImGuiMouseButton_Middle))
{
AutofitHorizontal(width);
}
}
if(ImGui::BeginPopupContextWindow())
{
if(ImGui::MenuItem("Autofit")){
AutofitHorizontal(width);
}
ImGui::EndPopup();
}
//Handle dragging
//(Mouse is allowed to leave the window, as long as original click was within us)
if(m_dragState == DRAG_STATE_TIMELINE)
{
//Use relative delta, not drag delta, since we update the offset every frame
float dx = mouseDelta.x;
if(dx != 0)
{
m_xAxisOffset -= PixelsToXAxisUnits(dx);
ClearPersistence();
}
if(ImGui::IsMouseReleased(ImGuiMouseButton_Left))
m_dragState = DRAG_STATE_NONE;
}
//Dimensions for various things
float fineTickLength = 10;
float coarseTickLength = height;
const double min_label_grad_width = 6 * ImGui::GetFontSize(); //Minimum distance between text labels
float thickLineWidth = 2;
float thinLineWidth = 1;
float ymid = pos.y + height/2;
//Top line
list->PathLineTo(pos);
list->PathLineTo(ImVec2(pos.x + width, pos.y));
list->PathStroke(color, 0, thickLineWidth);
//Figure out rounding granularity, based on our time scales
float xscale = m_pixelsPerXUnit;
int64_t width_xunits = width / xscale;
auto round_divisor = GetRoundingDivisor(width_xunits);
//Figure out about how much time per graduation to use
double grad_xunits_nominal = min_label_grad_width / xscale;
//Round so the division sizes are sane
double units_per_grad = grad_xunits_nominal * 1.0 / round_divisor;
double base = 5;
double log_units = log(units_per_grad) / log(base);
double log_units_rounded = ceil(log_units);
double units_rounded = pow(base, log_units_rounded);
float textMargin = 2;
int64_t grad_xunits_rounded = round(units_rounded * round_divisor);
//avoid divide-by-zero in weird cases with no waveform etc
if(grad_xunits_rounded == 0)
{
ImGui::PopFont();
ImGui::EndChild();
return;
}
//Calculate number of ticks within a division
double nsubticks = 5;
double subtick = grad_xunits_rounded / nsubticks;
//Find the start time (rounded as needed)
double tstart = round(m_xAxisOffset / grad_xunits_rounded) * grad_xunits_rounded;
//Print tick marks and labels
for(double t = tstart - grad_xunits_rounded; t < (tstart + width_xunits + grad_xunits_rounded); t += grad_xunits_rounded)
{
double x = (t - m_xAxisOffset) * xscale;
//Draw fine ticks first (even if the labeled graduation doesn't fit)
for(int tick=1; tick < nsubticks; tick++)
{
double subx = (t - m_xAxisOffset + tick*subtick) * xscale;
if(subx < 0)
continue;
if(subx > width)
break;
subx += pos.x;
list->PathLineTo(ImVec2(subx, pos.y));
list->PathLineTo(ImVec2(subx, pos.y + fineTickLength));
list->PathStroke(color, 0, thinLineWidth);
}
if(x < 0)
continue;
if(x > width)
break;
//Coarse ticks
x += pos.x;
list->PathLineTo(ImVec2(x, pos.y));
list->PathLineTo(ImVec2(x, pos.y + coarseTickLength));
list->PathStroke(color, 0, thickLineWidth);
//Render label
list->AddText(
ImVec2(x + textMargin, ymid),
textcolor,
m_xAxisUnit.PrettyPrint(t).c_str());
}
RenderTriggerPositionArrows(pos, height);
//Help messages in status bar
if(ImGui::IsWindowHovered())
{
if(m_mouseOverTriggerArrow)
m_parent->AddStatusHelp("mouse_lmb_drag", "Move trigger position");
else
m_parent->AddStatusHelp("mouse_lmb_drag", "Pan timeline");
m_parent->AddStatusHelp("mouse_wheel", "Zoom horizontal axis");