forked from CWRUChielLab/GDAQRec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplotter.cpp
920 lines (789 loc) · 29.3 KB
/
plotter.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
#include <QtGui>
#include <QMessageBox>
#include <QFileDialog>
#include <QStylePainter>
#include <cmath>
#include "plotter.h"
#include "simple_stats.h"
using namespace std;
const char* sharedTimestampFormat = "%13.6f";
const int sharedTimestampSize = 14;
Plotter::Plotter(QWidget *parent) :
#ifdef Q_WS_MAC
recording(false),
#endif
QWidget(parent),
sharedTimestamp(QDir::homePath() + QString("/.GDAQRec_timestamp"))
{
daqSettings.restore();
daqReader.updateDAQSettings(daqSettings);
fileSamplingRate = daqSettings.samplingRate;
setAutoFillBackground(true);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setFocusPolicy(Qt::StrongFocus);
rubberBandIsShown = false;
newButton = new QToolButton(this);
newButton->setText("New");
newButton->adjustSize();
connect(newButton, SIGNAL(clicked()), this, SLOT(newDocument()));
openButton = new QToolButton(this);
openButton->setText("Open");
openButton->adjustSize();
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
saveButton = new QToolButton(this);
saveButton->setText("Save");
saveButton->adjustSize();
connect(saveButton, SIGNAL(clicked()), this, SLOT(save()));
filteringButton = new QToolButton(this);
filteringButton->setText("Filtering");
filteringButton->adjustSize();
connect(filteringButton, SIGNAL(clicked()), this, SLOT(filtering()));
filteringButton->setCheckable(true);
filteringButton->setChecked(true);
settingsButton = new QToolButton(this);
settingsButton->setText("Settings");
settingsButton->adjustSize();
connect(settingsButton, SIGNAL(clicked()), this, SLOT(settings()));
recordButton = new QToolButton(this);
recordButton->setIcon(QIcon(":/images/record.png"));
recordButton->adjustSize();
connect(recordButton, SIGNAL(clicked()), this, SLOT(toggleRecording()));
zoomInButton = new QToolButton(this);
zoomInButton->setIcon(QIcon(":/images/zoomin.png"));
zoomInButton->adjustSize();
connect(zoomInButton, SIGNAL(clicked()), this, SLOT(zoomIn()));
zoomOutButton = new QToolButton(this);
zoomOutButton->setIcon(QIcon(":/images/zoomout.png"));
zoomOutButton->adjustSize();
connect(zoomOutButton, SIGNAL(clicked()), this, SLOT(zoomOut()));
connect(&daqReader, SIGNAL(newData()), this, SLOT(newData()));
connect(&daqReader, SIGNAL(daqError(const QString&)), this,
SLOT(daqError(const QString&)));
connect(&daqReader, SIGNAL(startedRecording()), this, SLOT(startedRecording()));
#ifdef Q_WS_MAC
connect(&daqReader, SIGNAL(stoppedRecording()), this, SLOT(stoppedRecording()));
#else
connect(&daqReader, SIGNAL(finished()), this, SLOT(stoppedRecording()));
#endif
startTime = QDateTime::currentDateTimeUtc();
saved = true;
traceOffset = 0.0;
clearPlot();
}
void Plotter::clearPlot()
{
zoomStack.clear();
PlotSettings settings;
zoomStack.append(settings);
// start zoomed in, since the top zoom shows the entire waveform
settings.minY = -0.0015;
settings.maxY = 0.0015;
zoomStack.append(settings);
curZoom = 1;
// make the top level zoom as wide as the data
if (!curveMap[0].isEmpty()
&& zoomStack[0].maxX < curveMap[0].last().x()) {
zoomStack[0].maxX = curveMap[0].last().x();
}
zoomInButton->hide();
zoomOutButton->show();
refreshPixmap();
}
void Plotter::zoomOut()
{
if (curZoom > 0) {
--curZoom;
zoomOutButton->setEnabled(curZoom > 0);
zoomInButton->setEnabled(true);
zoomInButton->show();
refreshPixmap();
// if this view was sliding right as the trace grew, keep it on the right
// side of the trace.
if (zoomStack[curZoom].includesRightEdge) {
double newMaxX = curveMap[0].empty()
? zoomStack[curZoom].maxX : curveMap[0].last().x();
double dx = newMaxX - zoomStack[curZoom].maxX;
zoomStack[curZoom].minX += dx;
zoomStack[curZoom].maxX += dx;
zoomStack[curZoom].includesRightEdge = true;
}
}
}
void Plotter::zoomIn()
{
if (curZoom < zoomStack.count() - 1) {
++curZoom;
zoomInButton->setEnabled(curZoom < zoomStack.count() - 1);
zoomOutButton->setEnabled(true);
zoomOutButton->show();
refreshPixmap();
// if this view was sliding right as the trace grew, keep it on the right
// side of the trace.
if (zoomStack[curZoom].includesRightEdge) {
double newMaxX = curveMap[0].empty()
? zoomStack[curZoom].maxX : curveMap[0].last().x();
double dx = newMaxX - zoomStack[curZoom].maxX;
zoomStack[curZoom].minX += dx;
zoomStack[curZoom].maxX += dx;
zoomStack[curZoom].includesRightEdge = true;
}
}
}
void Plotter::startedRecording()
{
recordButton->setIcon(QIcon(":/images/stop.png"));
recordButton->setEnabled(true);
sharedTimestamp.open(QIODevice::ReadWrite);
// Create a file containing the current recording time
char zeroTime[sharedTimestampSize + 1];
qsnprintf(zeroTime, sharedTimestampSize + 1,
sharedTimestampFormat, 0.0);
sharedTimestamp.write(zeroTime, sharedTimestampSize);
sharedTimestamp.flush();
sharedTimestampMemMap =
sharedTimestamp.map(0, sharedTimestampSize);
}
void Plotter::stoppedRecording()
{
recordButton->setIcon(QIcon(":/images/record.png"));
recordButton->setEnabled(true);
// delete the shared recording timestamp
sharedTimestamp.unmap(sharedTimestampMemMap);
sharedTimestamp.close();
sharedTimestamp.remove();
}
void Plotter::toggleRecording()
{
#ifdef Q_WS_MAC
if (recording) {
#else
if (daqReader.isRunning()) {
#endif
recordButton->setEnabled(false);
daqReader.stop();
}
else {
recordButton->setEnabled(false);
settingsButton->setEnabled(false);
#ifdef Q_WS_MAC
recording = true;
daqReader.run();
recording = false;
#else
daqReader.start();
#endif
}
}
bool Plotter::offerToSave()
{
if (!saved) {
int result = QMessageBox::warning(this, tr("GDAQrec"),
tr("There are unsaved data.\nWould you like to save them?"),
QMessageBox::Save | QMessageBox::Default,
QMessageBox::Discard,
QMessageBox::Cancel | QMessageBox::Escape);
switch (result) {
case QMessageBox::Save:
save();
if (saved) {
return true;
}
else {
return false;
}
case QMessageBox::Discard:
return true;
case QMessageBox::Cancel:
return false;
// should never be reached...
default:
return false;
}
}
else {
return true;
}
}
void Plotter::newDocument()
{
if (offerToSave()) {
saved = true;
filename.clear();
curveMap.clear();
filteredCurveMap.clear();
filterMap.clear();
clearPlot();
fileSamplingRate = daqSettings.samplingRate;
recordButton->setEnabled(true);
}
settingsButton->setEnabled(true);
}
void Plotter::open()
{
if (offerToSave()) {
QString newFilename = QFileDialog::getOpenFileName(
this, tr("Open data"), QString(),
tr("Data files (*.csv);;All Files (*)"));
if (!newFilename.isEmpty()) {
QFile file(newFilename);
if (!file.open(QIODevice::ReadOnly)) {
QMessageBox::critical(this, tr("GDAQrec"),
tr("Could not open file ") + newFilename,
QMessageBox::Ok | QMessageBox::Default
);
}
else
{
saved = true;
filename = newFilename;
curveMap.clear();
filterMap.clear();
recordButton->setDisabled(true);
settingsButton->setDisabled(true);
QTextStream in(&file);
simple_stats_t stats;
simple_stats_t_init(&stats);
while (!in.atEnd()) {
QString line = in.readLine();
QStringList coords = line.split(',', QString::SkipEmptyParts);
// TODO: real error checking/recovery
if (coords.count() >= 2) {
double time = coords[0].toDouble();
if (curveMap[0].size() > 0) {
simple_stats_t_append_val(&stats, time - curveMap[0].last().x());
}
for (int i=1; i < coords.size(); ++i) {
curveMap[i-1].append(QPointF(time, coords[i].toDouble()));
}
}
}
char buf[100];
simple_stats_t_to_string(&stats, buf, 100);
qDebug() << " time difference stats: " << buf;
if (curveMap[0].size() < 2) {
QMessageBox::critical(this, tr("GDAQrec"),
tr("File must contain at least 2 data points."),
QMessageBox::Ok | QMessageBox::Default
);
curveMap.clear();
}
double meanDelta = simple_stats_t_average(&stats);
if (meanDelta < 0.0000000001 || meanDelta > 100000000) {
QMessageBox::critical(this, tr("GDAQrec"),
tr("Average time between samples (%1) is really weird.").arg(meanDelta),
QMessageBox::Ok | QMessageBox::Default
);
curveMap.clear();
}
if (stats.min < (meanDelta * 0.9) || stats.max > (meanDelta * 1.1)) {
QMessageBox::critical(this, tr("GDAQrec"),
tr("Min and max times between samples must be within 10\% of average. (%1,%2,%3)").arg(stats.min).arg(stats.max).arg(meanDelta),
QMessageBox::Ok | QMessageBox::Default
);
curveMap.clear();
}
fileSamplingRate = 1.0/meanDelta;
qDebug() << "Sampling rate: " << fileSamplingRate;
updateFilteredData();
clearPlot();
}
}
}
}
void Plotter::save()
{
if (filename.isEmpty()) {
QString suggestedFilename = (startTime.toString(Qt::ISODate) + ".csv");
suggestedFilename.remove(':');
filename = QFileDialog::getSaveFileName(this, tr("Save data"),
suggestedFilename,
tr("Data files (*.csv);;All Files (*)"));
}
if (!filename.isEmpty()) {
FILE* file = fopen(filename.toUtf8(), "w");
if (file != NULL) {
int maxScans = curveMap[0].count()-1;
// the -1 is to ignore partial scans on comedi
for (int scan = 0; scan < maxScans; ++scan) {
fprintf(file, "%.6f", curveMap[0][scan].x());
for (CurveMap::iterator chanIter = curveMap.begin();
chanIter != curveMap.end(); ++chanIter) {
fprintf(file, ",%.6f", (*chanIter)[scan].y());
}
fprintf(file, "\n");
}
fclose(file);
saved = true;
}
else {
filename = QString();
int result = QMessageBox::critical(this, tr("GDAQrec"),
tr("I was unable to create the file \"")
+ filename + tr("\"\n") +
tr("Would you like to try again with a new file name?"),
QMessageBox::Yes | QMessageBox::Default,
QMessageBox::No | QMessageBox::Escape);
if (result == QMessageBox::Yes) {
save();
}
}
}
}
void Plotter::settings()
{
DAQSettingsDialog dialog(daqSettings, this);
if (dialog.exec()) {
daqSettings = dialog.settings;
daqSettings.save();
updateSettings();
}
}
void Plotter::filtering()
{
refreshPixmap();
}
class UpdateTimer
{
QTime timer;
public:
UpdateTimer() {
timer.start();
}
bool shouldSkip() {
if (timer.elapsed() > 100) {
timer.restart();
return false;
}
else {
return true;
}
}
} updateTimer;
void Plotter::newData()
{
if (updateTimer.shouldSkip())
return;
double oldMaxX = curveMap[0].empty()
? zoomStack[curZoom].maxX : curveMap[0].last().x();
int chan0_samples = curveMap[0].size();
daqReader.appendData(&curveMap);
int numScansRead = curveMap[0].size() - chan0_samples;
if (numScansRead > 0) {
if (saved) {
startTime = QDateTime::currentDateTimeUtc();
saved = false;
}
// expand the top level zoom, if needed.
if (zoomStack[0].maxX < curveMap[0].last().x()) {
zoomStack[0].maxX = curveMap[0].last().x();
}
// scroll right if this causes the plot to go from on the page to off of
// the page
double newMaxX = curveMap[0].empty()
? zoomStack[curZoom].maxX : curveMap[0].last().x();
if (zoomStack[curZoom].minX <= oldMaxX
&& oldMaxX <= zoomStack[curZoom].maxX
&& newMaxX > zoomStack[curZoom].maxX
)
{
double dx = newMaxX - zoomStack[curZoom].maxX;
zoomStack[curZoom].minX += dx;
zoomStack[curZoom].maxX += dx;
zoomStack[curZoom].includesRightEdge = true;
}
else
{
zoomStack[curZoom].includesRightEdge = false;
}
// update the shared timestamp
qsnprintf((char*)sharedTimestampMemMap, sharedTimestampSize,
sharedTimestampFormat, curveMap[0].last().x());
updateFilteredData();
refreshPixmap();
}
}
void Plotter::daqError(const QString& errorMessage)
{
QMessageBox::critical(this, tr("GDAQrec"),
tr("The following DAQ error occured:\n") + errorMessage,
QMessageBox::Ok | QMessageBox::Default
);
}
QSize Plotter::minimumSizeHint() const
{
return QSize(6 * Margin, 4 * Margin);
}
QSize Plotter::sizeHint() const
{
return QSize(900, 600);
}
void Plotter::paintEvent(QPaintEvent * /* event */)
{
QStylePainter painter(this);
painter.drawPixmap(0, 0, pixmap);
if (rubberBandIsShown) {
painter.setPen(daqSettings.fgColor);
painter.drawRect(rubberBandRect.normalized()
.adjusted(0, 0, -1, -1));
}
if (hasFocus()) {
QStyleOptionFocusRect option;
option.initFrom(this);
option.backgroundColor = daqSettings.bgColor;
painter.drawPrimitive(QStyle::PE_FrameFocusRect, option);
}
}
void Plotter::resizeEvent(QResizeEvent * /* event */)
{
const int gap = 5; // pixels
int x = width() - (
newButton->width() + gap
+ openButton->width() + gap
+ saveButton->width() + gap
+ settingsButton->width() + gap
+ filteringButton->width() + gap
+ recordButton->width() + gap
+ zoomInButton->width() + gap
+ zoomOutButton->width() + gap);
newButton->move(x, gap);
x += newButton->width() + gap;
openButton->move(x, gap);
x += openButton->width() + gap;
saveButton->move(x, gap);
x += saveButton->width() + gap;
settingsButton->move(x, gap);
x += settingsButton->width() + gap;
filteringButton->move(x, gap);
x += filteringButton->width() + gap;
recordButton->move(x, gap);
x += recordButton->width() + gap;
zoomInButton->move(x, gap);
x += zoomInButton->width() + gap;
zoomOutButton->move(x, gap);
x += zoomOutButton->width() + gap;
refreshPixmap();
}
void Plotter::mousePressEvent(QMouseEvent *event)
{
QRect rect(Margin, Margin,
width() - 2 * Margin, height() - 2 * Margin);
if (event->button() == Qt::LeftButton) {
if (rect.contains(event->pos())) {
rubberBandIsShown = true;
rubberBandRect.setTopLeft(event->pos());
rubberBandRect.setBottomRight(event->pos());
updateRubberBandRegion();
setCursor(Qt::CrossCursor);
}
}
}
void Plotter::mouseMoveEvent(QMouseEvent *event)
{
if (rubberBandIsShown) {
updateRubberBandRegion();
rubberBandRect.setBottomRight(event->pos());
updateRubberBandRegion();
}
}
void Plotter::mouseReleaseEvent(QMouseEvent *event)
{
if ((event->button() == Qt::LeftButton) && rubberBandIsShown) {
rubberBandIsShown = false;
updateRubberBandRegion();
unsetCursor();
QRect rect = rubberBandRect.normalized();
if (rect.width() < 4 || rect.height() < 4)
return;
rect.translate(-Margin, -Margin);
PlotSettings prevSettings = zoomStack[curZoom];
PlotSettings settings;
double dx = prevSettings.spanX() / (width() - 2 * Margin);
double dy = prevSettings.spanY() / (height() - 2 * Margin);
settings.minX = prevSettings.minX + dx * rect.left();
settings.maxX = prevSettings.minX + dx * rect.right();
settings.minY = prevSettings.maxY - dy * rect.bottom();
settings.maxY = prevSettings.maxY - dy * rect.top();
settings.adjust();
zoomStack.resize(curZoom + 1);
zoomStack.append(settings);
zoomIn();
}
}
void Plotter::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Plus:
zoomIn();
break;
case Qt::Key_Minus:
zoomOut();
break;
case Qt::Key_Left:
zoomStack[curZoom].scroll(-1, 0);
refreshPixmap();
break;
case Qt::Key_Right:
zoomStack[curZoom].scroll(+1, 0);
refreshPixmap();
break;
case Qt::Key_Down:
zoomStack[curZoom].scroll(0, -1);
refreshPixmap();
break;
case Qt::Key_Up:
zoomStack[curZoom].scroll(0, +1);
refreshPixmap();
break;
case Qt::Key_S:
if (traceOffset == 0.0) {
traceOffset = 0.1;
} else {
traceOffset = 0.0;
}
refreshPixmap();
break;
case Qt::Key_A:
traceOffset -= 0.01;
refreshPixmap();
break;
case Qt::Key_D:
traceOffset += 0.01;
refreshPixmap();
break;
default:
QWidget::keyPressEvent(event);
}
}
void Plotter::wheelEvent(QWheelEvent *event)
{
int numDegrees = event->delta() / 8;
int numTicks = numDegrees / 15;
if (event->orientation() == Qt::Horizontal) {
zoomStack[curZoom].scroll(numTicks, 0);
} else {
zoomStack[curZoom].scroll(0, numTicks);
}
refreshPixmap();
}
void Plotter::closeEvent(QCloseEvent* event)
{
if (offerToSave())
event->accept();
else
event->ignore();
#ifdef Q_WS_MAC
daqReader.stop();
#endif
if (event->isAccepted() && daqReader.isRunning()) {
daqReader.stop();
daqReader.wait();
}
}
void Plotter::updateRubberBandRegion()
{
QRect rect = rubberBandRect.normalized();
update(rect.left(), rect.top(), rect.width(), 1);
update(rect.left(), rect.top(), 1, rect.height());
update(rect.left(), rect.bottom(), rect.width(), 1);
update(rect.right(), rect.top(), 1, rect.height());
}
void Plotter::updateFilteredData() {
double lowpass_cutoff = 40.0;
unsigned lowpass_order = 12;
double highpass_cutoff = 0.5;
unsigned highpass_order = 2;
for (CurveMap::iterator chanIter = curveMap.begin();
chanIter != curveMap.end(); ++chanIter) {
QVector<QPointF>& rawCurve = chanIter.value();
QVector<QPointF>& filteredCurve = filteredCurveMap[chanIter.key()];
QVector<QuadFilter>& filters = filterMap[chanIter.key()];
// initialize the filters if needed
if (filters.size() == 0) {
for (unsigned int i = 0; i < highpass_order/2; ++i) {
filters.push_back(QuadFilter::CreateHighpass(
highpass_cutoff, highpass_order, i, fileSamplingRate,
((i==0) ? rawCurve.first().y() : 0)));
}
for (unsigned int i = 0; i < lowpass_order/2; ++i) {
filters.push_back(QuadFilter::CreateLowpass(
lowpass_cutoff, lowpass_order, i, fileSamplingRate,
0));
}
}
while (rawCurve.size() > filteredCurve.size()) {
int nowIndex = filteredCurve.size();
double result = rawCurve[nowIndex].y();
for (int i = 0; i < filters.size(); ++i) {
result = filters[i].filterInput(result);
}
QPointF filteredPoint = QPointF(rawCurve[nowIndex].x(), result);
filteredCurve.push_back(filteredPoint);
}
}
}
void Plotter::refreshPixmap()
{
pixmap = QPixmap(size());
pixmap.fill(daqSettings.bgColor);
QPainter painter(&pixmap);
painter.initFrom(this);
drawGrid(&painter);
drawCurves(&painter);
update();
}
void Plotter::drawGrid(QPainter *painter)
{
QRect rect(Margin, Margin,
width() - 2 * Margin, height() - 2 * Margin);
if (!rect.isValid())
return;
PlotSettings settings = zoomStack[curZoom];
QPen quiteDark = QColor(
(daqSettings.fgColor.red() + daqSettings.bgColor.red())/2,
(daqSettings.fgColor.green() + daqSettings.bgColor.green())/2,
(daqSettings.fgColor.blue() + daqSettings.bgColor.blue())/2
);
QPen light = daqSettings.fgColor;
for (int i = 0; i <= settings.numXTicks; ++i) {
int x = rect.left() + (i * (rect.width() - 1)
/ settings.numXTicks);
double label = settings.minX + (i * settings.spanX()
/ settings.numXTicks);
painter->setPen(quiteDark);
painter->drawLine(x, rect.top(), x, rect.bottom());
painter->setPen(light);
painter->drawLine(x, rect.bottom(), x, rect.bottom() + 5);
painter->drawText(x - 50, rect.bottom() + 5, 100, Margin,
Qt::AlignHCenter | Qt::AlignTop,
QString::number(label));
}
for (int j = 0; j <= settings.numYTicks; ++j) {
int y = rect.bottom() - (j * (rect.height() - 1)
/ settings.numYTicks);
double label = settings.minY + (j * settings.spanY()
/ settings.numYTicks);
painter->setPen(quiteDark);
painter->drawLine(rect.left(), y, rect.right(), y);
painter->setPen(light);
painter->drawLine(rect.left() - 5, y, rect.left(), y);
painter->drawText(rect.left() - Margin, y - 10, Margin - 5, 20,
Qt::AlignRight | Qt::AlignVCenter,
QString::number(label));
}
painter->drawRect(rect.adjusted(0, 0, -1, -1));
}
void Plotter::drawCurves(QPainter *painter)
{
PlotSettings settings = zoomStack[curZoom];
QRect rect(Margin, Margin,
width() - 2 * Margin, height() - 2 * Margin);
if (!rect.isValid())
return;
painter->setClipRect(rect.adjusted(+1, +1, -1, -1));
QMapIterator<int, QVector<QPointF> > i(filteringButton->isChecked() ? filteredCurveMap : curveMap);
double offset = 0.0;
while (i.hasNext()) {
i.next();
int id = i.key();
const QVector<QPointF> &data = i.value();
if (data.count() != 0) {
QVector<QPointF> points;
int j;
// skip points off the left edge of the graph
// (use a binary search, since there may be a lot of data)
int lowbound = 0;
int highbound = data.count()-1;
while (lowbound + 1 < highbound) {
int mid = (lowbound + highbound)/2;
if (data[mid].x() < settings.minX) {
lowbound = mid;
}
else {
highbound = mid;
}
}
j = max(0, lowbound-1);
// since there can be many points per pixel, just draw a line
// from the minumum in that pixel to the maximum in that pixel
// (and then to the next pixel) (This speeds up drawing
// dramatically)
int prevX = rect.left()-2;
int minY = 0, maxY = 0; // reinitialized below
bool firstPoint = true;
for (; j < data.count()
&& (j == 0 || data[j-1].x() < settings.maxX); ++j) {
double dx = data[j].x() - settings.minX;
double dy = data[j].y() - settings.minY + offset;
double x = rect.left() + (dx * (rect.width() - 1)
/ settings.spanX());
double y = rect.bottom() - (dy * (rect.height() - 1)
/ settings.spanY());
if (firstPoint) {
minY = maxY = (int)y;
firstPoint = false;
}
if (int(x) != prevX) {
points.append(QPointF(x,minY));
points.append(QPointF(x,maxY));
prevX = int(x);
minY = maxY = int(y);
}
else {
minY = min(int(y), minY);
maxY = max(int(y), maxY);
}
}
QPolygonF polyline(points);
painter->setPen(daqSettings.color[uint(id) % 8]);
painter->drawPolyline(polyline);
}
offset -= traceOffset;
}
}
void Plotter::updateSettings()
{
daqReader.updateDAQSettings(daqSettings);
fileSamplingRate = daqSettings.samplingRate;
refreshPixmap();
}
PlotSettings::PlotSettings()
{
minX = 0.0;
maxX = 10.0;
numXTicks = 10;
minY = -2.0;
maxY = 2.0;
numYTicks = 6;
includesRightEdge = false;
}
void PlotSettings::scroll(double dx, double dy)
{
double stepX = spanX() / numXTicks;
minX += dx * stepX;
maxX += dx * stepX;
double stepY = spanY() / numYTicks;
minY += dy * stepY;
maxY += dy * stepY;
}
void PlotSettings::adjust()
{
adjustAxis(minX, maxX, numXTicks);
adjustAxis(minY, maxY, numYTicks);
}
void PlotSettings::adjustAxis(double &min, double &max,
int &numTicks)
{
const int MinTicks = 4;
double grossStep = (max - min) / MinTicks;
double step = pow(10.0, floor(log10(grossStep)));
if (5 * step < grossStep) {
step *= 5;
} else if (2 * step < grossStep) {
step *= 2;
}
numTicks = int(ceil(max / step) - floor(min / step));
if (numTicks < MinTicks)
numTicks = MinTicks;
min = floor(min / step) * step;
max = ceil(max / step) * step;
}