LinechartWidget.cc 32.9 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
pixhawk's avatar
pixhawk committed
9 10 11 12 13 14 15


/**
 * @file
 *   @brief Line chart plot widget
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
16
 *   @author Thomas Gubler <thomasgubler@student.ethz.ch>
pixhawk's avatar
pixhawk committed
17 18 19 20 21 22 23 24
 */

#include <QDebug>
#include <QWidget>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QComboBox>
#include <QToolButton>
25
#include <QSizePolicy>
pixhawk's avatar
pixhawk committed
26 27 28 29 30 31
#include <QScrollBar>
#include <QLabel>
#include <QMenu>
#include <QSpinBox>
#include <QColor>
#include <QPalette>
32
#include <QStandardPaths>
33
#include <QShortcut>
pixhawk's avatar
pixhawk committed
34 35 36 37

#include "LinechartWidget.h"
#include "LinechartPlot.h"
#include "LogCompressor.h"
lm's avatar
lm committed
38
#include "QGC.h"
pixhawk's avatar
pixhawk committed
39
#include "MG.h"
Don Gagne's avatar
Don Gagne committed
40
#include "QGCFileDialog.h"
Don Gagne's avatar
Don Gagne committed
41
#include "QGCMessageBox.h"
42
#include "QGCApplication.h"
pixhawk's avatar
pixhawk committed
43

44
LinechartWidget::LinechartWidget(int systemid, QWidget *parent) : QWidget(parent),
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    sysid(systemid),
    activePlot(NULL),
    curvesLock(new QReadWriteLock()),
    plotWindowLock(),
    curveListIndex(0),
    curveListCounter(0),
    curveLabels(new QMap<QString, QLabel*>()),
    curveMeans(new QMap<QString, QLabel*>()),
    curveMedians(new QMap<QString, QLabel*>()),
    curveVariances(new QMap<QString, QLabel*>()),
    curveMenu(new QMenu(this)),
    logFile(new QFile()),
    logindex(1),
    logging(false),
    logStartTime(0),
lm's avatar
lm committed
60
    updateTimer(new QTimer()),
61 62
    selectedMAV(-1),
    lastTimestamp(0)
pixhawk's avatar
pixhawk committed
63 64 65
{
    // Add elements defined in Qt Designer
    ui.setupUi(this);
66
    this->setMinimumSize(200, 150);
pixhawk's avatar
pixhawk committed
67 68 69 70

    // Add and customize curve list elements (left side)
    curvesWidget = new QWidget(ui.curveListWidget);
    ui.curveListWidget->setWidget(curvesWidget);
71
    curvesWidgetLayout = new QGridLayout(curvesWidget);
pixhawk's avatar
pixhawk committed
72 73
    curvesWidgetLayout->setMargin(2);
    curvesWidgetLayout->setSpacing(4);
74
    //curvesWidgetLayout->setSizeConstraint(QSizePolicy::Expanding);
75
    curvesWidgetLayout->setAlignment(Qt::AlignTop);
76 77 78 79 80 81 82

    curvesWidgetLayout->setColumnStretch(0, 0);
    curvesWidgetLayout->setColumnStretch(1, 0);
    curvesWidgetLayout->setColumnStretch(2, 80);
    curvesWidgetLayout->setColumnStretch(3, 50);
    curvesWidgetLayout->setColumnStretch(4, 50);
    curvesWidgetLayout->setColumnStretch(5, 50);
83 84
//    horizontalLayout->setColumnStretch(median, 50);
    curvesWidgetLayout->setColumnStretch(6, 50);
85

pixhawk's avatar
pixhawk committed
86 87
    curvesWidget->setLayout(curvesWidgetLayout);

88 89 90 91 92 93
    // Create curve list headings
    QLabel* label;
    QLabel* value;
    QLabel* mean;
    QLabel* variance;

94 95 96 97 98 99
    connect(ui.recolorButton, &QPushButton::clicked, this, &LinechartWidget::recolor);
    connect(ui.shortNameCheckBox, &QCheckBox::clicked, this, &LinechartWidget::setShortNames);
    connect(ui.plotFilterLineEdit, &QLineEdit::textChanged, this, &LinechartWidget::filterCurves);
    QShortcut *shortcut  = new QShortcut(this);
    shortcut->setKey(QKeySequence(Qt::CTRL + Qt::Key_F));
    connect(shortcut, &QShortcut::activated, this, &LinechartWidget::setPlotFilterLineEditFocus);
100

101 102
    int labelRow = curvesWidgetLayout->rowCount();

103
    selectAllCheckBox = new QCheckBox("", this);
104
    connect(selectAllCheckBox, &QCheckBox::clicked, this, &LinechartWidget::selectAllCurves);
105
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0, 1, 2);
106 107

    label = new QLabel(this);
108
    label->setText("Name");
109
    curvesWidgetLayout->addWidget(label, labelRow, 2);
110 111

    // Value
112
    value = new QLabel(this);
113
    value->setText("Val");
114
    curvesWidgetLayout->addWidget(value, labelRow, 3);
115

116
    // Unit
117
    //curvesWidgetLayout->addWidget(new QLabel(tr("Unit")), labelRow, 4);
118

119
    // Mean
120
    mean = new QLabel(this);
121
    mean->setText("Mean");
122
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
123 124

    // Variance
125
    variance = new QLabel(this);
126
    variance->setText("Variance");
127
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
128

pixhawk's avatar
pixhawk committed
129 130
    // Create the layout
    createLayout();
131

132
    // And make sure we're listening for future style changes
133
    connect(qgcApp(), &QGCApplication::styleChanged, this, &LinechartWidget::recolor);
134

LM's avatar
LM committed
135
    updateTimer->setInterval(updateInterval);
136 137 138
    connect(updateTimer, &QTimer::timeout, this, &LinechartWidget::refresh);
    connect(ui.uasSelectionBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
            this, &LinechartWidget::selectActiveSystem);
139
    readSettings();
pixhawk's avatar
pixhawk committed
140 141
}

142 143 144
LinechartWidget::~LinechartWidget()
{
    writeSettings();
pixhawk's avatar
pixhawk committed
145
    stopLogging();
146 147
    if (activePlot) delete activePlot;
    activePlot = NULL;
pixhawk's avatar
pixhawk committed
148 149
}

150 151 152 153 154 155 156 157 158 159 160
void LinechartWidget::selectActiveSystem(int mav)
{
    // -1: Unitialized, 0: all
    if (mav != selectedMAV && (selectedMAV != -1))
    {
        // Delete all curves
        // FIXME
    }
    selectedMAV = mav;
}

161 162 163
void LinechartWidget::selectAllCurves(bool all)
{
    QMap<QString, QLabel*>::iterator i;
164
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
165
        activePlot->setVisibleById(i.key(), all);
166 167 168
    }
}

169 170 171 172
void LinechartWidget::writeSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
173 174
    bool enforceGT = (!autoGroundTimeSet && timeButton->isChecked()) ? true : false;
    if (timeButton) settings.setValue("ENFORCE_GROUNDTIME", enforceGT);
175
    if (ui.showUnitsCheckBox) settings.setValue("SHOW_UNITS", ui.showUnitsCheckBox->isChecked());
176
    if (ui.shortNameCheckBox) settings.setValue("SHORT_NAMES", ui.shortNameCheckBox->isChecked());
177 178 179 180 181 182 183
    settings.endGroup();
}

void LinechartWidget::readSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
184
    if (activePlot) {
185 186
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
        activePlot->enforceGroundTime(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
187
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
188
        //userGroundTimeSet = settings.value("USER_GROUNDTIME", timeButton->isChecked()).toBool();
189
    }
190
    if (ui.showUnitsCheckBox) ui.showUnitsCheckBox->setChecked(settings.value("SHOW_UNITS", ui.showUnitsCheckBox->isChecked()).toBool());
191
    if (ui.shortNameCheckBox) ui.shortNameCheckBox->setChecked(settings.value("SHORT_NAMES", ui.shortNameCheckBox->isChecked()).toBool());
192 193 194
    settings.endGroup();
}

pixhawk's avatar
pixhawk committed
195 196 197 198 199 200
void LinechartWidget::createLayout()
{
    // Create actions
    createActions();

    // Setup the plot group box area layout
201 202 203
    QVBoxLayout* vlayout = new QVBoxLayout(ui.diagramGroupBox);
    vlayout->setSpacing(4);
    vlayout->setMargin(2);
pixhawk's avatar
pixhawk committed
204 205

    // Create plot container widget
206 207 208
    activePlot = new LinechartPlot(this, sysid);
    // Activate automatic scrolling
    activePlot->setAutoScroll(true);
pixhawk's avatar
pixhawk committed
209 210 211 212 213

    // TODO Proper Initialization needed
    //    activePlot = getPlot(0);
    //    plotContainer->setPlot(activePlot);

214 215 216 217
    vlayout->addWidget(activePlot);

    QHBoxLayout *hlayout = new QHBoxLayout;
    vlayout->addLayout(hlayout);
pixhawk's avatar
pixhawk committed
218 219 220

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
221
    scalingLogButton->setText(tr("LOG"));
pixhawk's avatar
pixhawk committed
222
    scalingLogButton->setCheckable(true);
223 224
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
225
    hlayout->addWidget(scalingLogButton);
pixhawk's avatar
pixhawk committed
226 227 228

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
229 230
    averageSpinBox->setToolTip(tr("Sliding window size to calculate mean and variance"));
    averageSpinBox->setWhatsThis(tr("Sliding window size to calculate mean and variance"));
pixhawk's avatar
pixhawk committed
231
    averageSpinBox->setMinimum(2);
232 233
    averageSpinBox->setValue(200);
    setAverageWindow(200);
234
    averageSpinBox->setMaximum(9999);
235
    hlayout->addWidget(averageSpinBox);
236
    connect(averageSpinBox,static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LinechartWidget::setAverageWindow);
pixhawk's avatar
pixhawk committed
237 238 239

    // Log Button
    logButton = new QToolButton(this);
240 241
    logButton->setToolTip(tr("Start to log curve data into a CSV or TXT file"));
    logButton->setWhatsThis(tr("Start to log curve data into a CSV or TXT file"));
pixhawk's avatar
pixhawk committed
242
    logButton->setText(tr("Start Logging"));
243
    hlayout->addWidget(logButton);
244
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
245

246
    // Ground time button
247
    timeButton = new QCheckBox(this);
248
    timeButton->setText(tr("Ground Time"));
249 250
    timeButton->setToolTip(tr("Overwrite timestamp of data from vehicle with ground receive time. Helps if the plots are not visible because of missing or invalid onboard time."));
    timeButton->setWhatsThis(tr("Overwrite timestamp of data from vehicle with ground receive time. Helps if the plots are not visible because of missing or invalid onboard time."));
251
    hlayout->addWidget(timeButton);
252 253
    connect(timeButton.data(), &QCheckBox::clicked, activePlot, &LinechartPlot::enforceGroundTime);
    connect(timeButton.data(), &QCheckBox::clicked, this, &LinechartWidget::writeSettings);
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    hlayout->addStretch();

    QLabel *timeScaleLabel = new QLabel("Time axis:");
    hlayout->addWidget(timeScaleLabel);

    timeScaleCmb = new QComboBox(this);
    timeScaleCmb->addItem("10 seconds", 10);
    timeScaleCmb->addItem("20 seconds", 20);
    timeScaleCmb->addItem("30 seconds", 30);
    timeScaleCmb->addItem("40 seconds", 40);
    timeScaleCmb->addItem("50 seconds", 50);
    timeScaleCmb->addItem("1 minute", 60);
    timeScaleCmb->addItem("2 minutes", 60*2);
    timeScaleCmb->addItem("3 minutes", 60*3);
    timeScaleCmb->addItem("4 minutes", 60*4);
    timeScaleCmb->addItem("5 minutes", 60*5);
    timeScaleCmb->addItem("10 minutes", 60*10);
    //timeScaleCmb->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    timeScaleCmb->setMinimumContentsLength(12);

    hlayout->addWidget(timeScaleCmb);
276 277
    connect(timeScaleCmb, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
            this, &LinechartWidget::timeScaleChanged);
278

279 280
    // Initialize the "Show units" checkbox. This is configured in the .ui file, so all
    // we do here is attach the clicked() signal.
281
    connect(ui.showUnitsCheckBox, &QCheckBox::clicked, this, &LinechartWidget::writeSettings);
pixhawk's avatar
pixhawk committed
282

283 284 285 286
    // Add actions
    averageSpinBox->setValue(activePlot->getAverageWindow());

    // Connect notifications from the user interface to the plot
287
    connect(this, &LinechartWidget::curveRemoved, activePlot, &LinechartPlot::hideCurve);
288 289

    // Update scrollbar when plot window changes (via translator method setPlotWindowPosition()
290
//    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));
291
    connect(activePlot, &LinechartPlot::curveRemoved, this, &LinechartWidget::removeCurve);
292 293

    // Update plot when scrollbar is moved (via translator method setPlotWindowPosition()
294 295 296
    //TODO: impossible to
    connect(this, static_cast<void (LinechartWidget::*)(quint64)>(&LinechartWidget::plotWindowPositionUpdated),
            activePlot, &LinechartPlot::setWindowPosition);
297 298

    // Set scaling
299
    connect(scalingLogButton, &QToolButton::toggled, this, &LinechartWidget::toggleLogarithmicScaling);
300 301
}

302 303 304 305 306
void LinechartWidget::timeScaleChanged(int index)
{
    activePlot->setPlotInterval(timeScaleCmb->itemData(index).toInt()*1000);
}

307 308 309 310 311 312
void LinechartWidget::toggleLogarithmicScaling(bool checked)
{
    if(checked)
        activePlot->setLogarithmicScaling();
    else
        activePlot->setLinearScaling();
pixhawk's avatar
pixhawk committed
313 314
}

315
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, const QVariant &variant, quint64 usec)
316
{
317 318 319 320 321 322
    QMetaType::Type type = static_cast<QMetaType::Type>(variant.type());
    bool ok;
    double value = variant.toDouble(&ok);
    if(!ok || type == QMetaType::QByteArray || type == QMetaType::QString)
        return;
    bool isDouble = type == QMetaType::Float || type == QMetaType::Double;
323

lm's avatar
lm committed
324 325
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
326 327 328 329 330
        // Order matters here, first append to plot, then update curve list
        activePlot->appendData(curve+unit, usec, value);
        // Store data
        QLabel* label = curveLabels->value(curve+unit, NULL);
        // Make sure the curve will be created if it does not yet exist
lm's avatar
lm committed
331 332
        if(!label)
        {
333 334
            if(!isDouble)
                intData.insert(curve+unit, 0);
335 336
            addCurve(curve, unit);
        }
337 338

        // Add int data
339 340
        if(!isDouble)
            intData.insert(curve+unit, variant.toInt());
341 342
    }

343 344 345 346
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
347 348
        // Difference larger than 3 secs, enforce ground time
        if (((qint64)usec - (qint64)lastTimestamp) > 3000)
349 350
        {
            autoGroundTimeSet = true;
351 352 353 354 355
            // Tick ground time checkbox, but avoid state switching
            timeButton->blockSignals(true);
            timeButton->setChecked(true);
            timeButton->blockSignals(false);
            if (activePlot) activePlot->enforceGroundTime(true);
356
        }
357
        lastTimestamp = usec;
358 359
    }

360
    // Log data
lm's avatar
lm committed
361 362 363 364
    if (logging)
    {
        if (activePlot->isVisible(curve+unit))
        {
365
            if (usec == 0) usec = QGC::groundTimeMilliseconds();
366 367 368 369
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

370 371
            QString line = QString("%1\t%2\t%3\t%4\n").arg(time).arg(uasId).arg(curve).arg(value, 0, 'e', 15);
            logFile->write(line.toLatin1());
372 373 374 375
        }
    }
}

376 377
void LinechartWidget::refresh()
{
LM's avatar
LM committed
378
    setUpdatesEnabled(false);
379
    QString str;
380
    // Value
381
    QMap<QString, QLabel*>::iterator i;
382 383
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
        if (intData.contains(i.key())) {
lm's avatar
lm committed
384
            str.sprintf("% 11i", intData.value(i.key()));
385
        } else {
lm's avatar
lm committed
386 387
            double val = activePlot->getCurrentValue(i.key());
            int intval = static_cast<int>(val);
388
            if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
389
                str.sprintf("% 11i", intval);
390
            } else if (intval >= 10000 || intval <= -10000) {
lm's avatar
lm committed
391
                str.sprintf("% 11.2f", val);
392
            } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
393
                str.sprintf("% 11.4f", val);
394
            } else {
lm's avatar
lm committed
395 396
                str.sprintf("% 11.6f", val);
            }
397
        }
398 399 400 401 402
        // Value
        i.value()->setText(str);
    }
    // Mean
    QMap<QString, QLabel*>::iterator j;
403
    for (j = curveMeans->begin(); j != curveMeans->end(); ++j) {
404
        double val = activePlot->getMean(j.key());
lm's avatar
lm committed
405
        int intval = static_cast<int>(val);
406
        if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
407
            str.sprintf("% 11i", intval);
408
        } else if (intval >= 10000 || intval <= -10000) {
409
            str.sprintf("% 11.2f", val);
410
        } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
411
            str.sprintf("% 11.4f", val);
412
        } else {
413 414
            str.sprintf("% 11.6f", val);
        }
415 416
        j.value()->setText(str);
    }
417 418 419 420 421 422 423
//    QMap<QString, QLabel*>::iterator k;
//    for (k = curveMedians->begin(); k != curveMedians->end(); ++k)
//    {
//        // Median
//        str.sprintf("%+.2f", activePlot->getMedian(k.key()));
//        k.value()->setText(str);
//    }
424
    QMap<QString, QLabel*>::iterator l;
425 426 427 428 429
    for (l = curveVariances->begin(); l != curveVariances->end(); ++l) {
        // Variance
        str.sprintf("% 8.3e", activePlot->getVariance(l.key()));
        l.value()->setText(str);
    }
LM's avatar
LM committed
430
    setUpdatesEnabled(true);
431 432
}

pixhawk's avatar
pixhawk committed
433 434
void LinechartWidget::startLogging()
{
lm's avatar
lm committed
435
    // Check if any curve is enabled
436
    if (!activePlot->anyCurveVisible()) {
dogmaphobic's avatar
dogmaphobic committed
437 438 439
        QGCMessageBox::critical(
            tr("No curves selected for logging."),
            tr("Please check all curves you want to log. Currently no data would be logged. Aborting the logging."));
lm's avatar
lm committed
440 441 442 443
        return;
    }

    // Let user select the log file name
444
    // QDate date(QDate::currentDate());
lm's avatar
lm committed
445
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
dogmaphobic's avatar
dogmaphobic committed
446 447 448
    QString fileName = QGCFileDialog::getSaveFileName(this,
        tr("Save Log File"),
        QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
449
        tr("Log Files (*.log)"),
450
        "log"); // Default type
451

452
    qDebug() << "SAVE FILE " << fileName;
453

dogmaphobic's avatar
dogmaphobic committed
454
    if (!fileName.isEmpty()) {
455
        logFile = new QFile(fileName);
Lorenz Meier's avatar
Lorenz Meier committed
456
        if (logFile->open(QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text)) {
457
            logging = true;
458 459
            logStartTime = 0;
            curvesWidget->setEnabled(false);
460 461
            logindex++;
            logButton->setText(tr("Stop logging"));
462 463
            disconnect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
            connect(logButton, &QToolButton::clicked, this, &LinechartWidget::stopLogging);
464
        }
pixhawk's avatar
pixhawk committed
465 466 467 468 469 470
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
471
    curvesWidget->setEnabled(true);
472
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
473 474 475
        logFile->flush();
        logFile->close();
        // Postprocess log file
476
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
477
        connect(compressor, &LogCompressor::finishedFile, this, &LinechartWidget::logfileWritten);
478

dogmaphobic's avatar
dogmaphobic committed
479 480 481 482 483
        QMessageBox::StandardButton button = QGCMessageBox::question(
            tr("Starting Log Compression"),
            tr("Should empty fields (e.g. due to packet drops) be filled with the previous value of the same variable (zero order hold)?"),
            QMessageBox::Yes | QMessageBox::No,
            QMessageBox::No);
484
        bool fill = (button == QMessageBox::Yes);
485 486

        compressor->startCompression(fill);
pixhawk's avatar
pixhawk committed
487 488
    }
    logButton->setText(tr("Start logging"));
489 490
    disconnect(logButton, &QToolButton::clicked, this, &LinechartWidget::stopLogging);
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
}

/**
 * The average window size defines the width of the sliding average
 * filter. It also defines the width of the sliding median filter.
 *
 * @param windowSize with (in values) of the sliding average/median filter. Minimum is 2
 */
void LinechartWidget::setAverageWindow(int windowSize)
{
    if (windowSize > 1) activePlot->setAverageWindow(windowSize);
}

void LinechartWidget::createActions()
{
}

/**
 * @brief Add a curve to the curve list
 *
 * @param curve The id-string of the curve
 * @see removeCurve()
 **/
514
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
515
{
516
    LinechartPlot* plot = activePlot;
517
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
518 519 520
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
521
    QLabel* unitLabel;
pixhawk's avatar
pixhawk committed
522
    QLabel* mean;
523
    QLabel* variance;
pixhawk's avatar
pixhawk committed
524

525 526
    curveNames.insert(curve+unit, curve);

527 528
    int labelRow = curvesWidgetLayout->rowCount();

529
    // Checkbox
530
    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
531
    checkBox->setCheckable(true);
532
    checkBox->setObjectName(curve+unit);
533 534
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
535
    checkBoxes.insert(curve+unit, checkBox);
536
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
537

538
    // Icon
539
    QWidget* colorIcon = new QWidget(this);
540
    colorIcons.insert(curve+unit, colorIcon);
pixhawk's avatar
pixhawk committed
541 542
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);
543
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
544

545
    // Label
546
    label = new QLabel(this);
547
    label->setText(getCurveName(curve+unit, ui.shortNameCheckBox->isChecked()));
548
    curveNameLabels.insert(curve+unit, label);
549
    curvesWidgetLayout->addWidget(label, labelRow, 2);
550

pixhawk's avatar
pixhawk committed
551
    // Value
552
    value = new QLabel(this);
pixhawk's avatar
pixhawk committed
553
    value->setNum(0.00);
554
    value->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
555 556
    value->setToolTip(tr("Current value of %1 in %2 units").arg(curve, unit));
    value->setWhatsThis(tr("Current value of %1 in %2 units").arg(curve, unit));
557
    curveLabels->insert(curve+unit, value);
558
    curvesWidgetLayout->addWidget(value, labelRow, 3);
pixhawk's avatar
pixhawk committed
559

560 561 562 563 564
    // Unit
    unitLabel = new QLabel(this);
    unitLabel->setText(unit);
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
565
    curveUnits.insert(curve+unit, unitLabel);
566
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
567
    unitLabel->setVisible(ui.showUnitsCheckBox->isChecked());
568
    connect(ui.showUnitsCheckBox, &QCheckBox::clicked, unitLabel, &QLabel::setVisible);
569

pixhawk's avatar
pixhawk committed
570
    // Mean
571
    mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
572
    mean->setNum(0.00);
lm's avatar
lm committed
573
    mean->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
574 575
    mean->setToolTip(tr("Arithmetic mean of %1 in %2 units").arg(curve, unit));
    mean->setWhatsThis(tr("Arithmetic mean of %1 in %2 units").arg(curve, unit));
576 577
    curveMeans->insert(curve+unit, mean);
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
pixhawk's avatar
pixhawk committed
578

579 580 581 582 583
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
584

585
    // Variance
586
    variance = new QLabel(this);
587
    variance->setNum(0.00);
lm's avatar
lm committed
588
    variance->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
589 590
    variance->setToolTip(tr("Variance of %1 in (%2)^2 units").arg(curve, unit));
    variance->setWhatsThis(tr("Variance of %1 in (%2)^2 units").arg(curve, unit));
591 592
    curveVariances->insert(curve+unit, variance);
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
593

pixhawk's avatar
pixhawk committed
594 595 596 597 598 599 600 601 602 603 604
    /* Color picker
    QColor color = QColorDialog::getColor(Qt::green, this);
         if (color.isValid()) {
             colorLabel->setText(color.name());
             colorLabel->setPalette(QPalette(color));
             colorLabel->setAutoFillBackground(true);
         }
        */

    // Set stretch factors so that the label gets the whole space

605 606 607
    // Load visibility settings
    // TODO

pixhawk's avatar
pixhawk committed
608
    // Connect actions
609 610 611
    connect(selectAllCheckBox, &QCheckBox::clicked, checkBox, &QCheckBox::setChecked);
    QObject::connect(checkBox, &QCheckBox::clicked, this, &LinechartWidget::takeButtonClick);
    QObject::connect(this, &LinechartWidget::curveVisible, plot, &LinechartPlot::setVisibleById);
pixhawk's avatar
pixhawk committed
612 613 614

    // Set UI components to initial state
    checkBox->setChecked(false);
615
    plot->setVisibleById(curve+unit, false);
pixhawk's avatar
pixhawk committed
616 617 618 619 620 621 622 623
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
624
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
625
{
626
    Q_UNUSED(curve)
627 628 629 630 631 632 633 634 635 636 637 638 639 640

    QWidget* widget = NULL;
    widget = curveLabels->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveMeans->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveMedians->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveVariances->take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
641 642 643 644 645 646 647 648
    widget = colorIcons.take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveNameLabels.take(curve);
    curvesWidgetLayout->removeWidget(widget);
    widget->deleteLater();
    widget = curveUnits.take(curve);
    curvesWidgetLayout->removeWidget(widget);
649
    widget->deleteLater();
650 651 652 653
    QCheckBox* checkbox;
    checkbox = checkBoxes.take(curve);
    curvesWidgetLayout->removeWidget(checkbox);
    checkbox->deleteLater();
654 655 656 657 658
//    intData->remove(curve);
}

void LinechartWidget::recolor()
{
659
    activePlot->styleChanged(qgcApp()->styleIsDark());
660
    foreach (const QString &key, colorIcons.keys())
661 662
    {
        QWidget* colorIcon = colorIcons.value(key, 0);
663
        if (colorIcon && !colorIcon->styleSheet().isEmpty())
664
        {
665 666 667
            QString colorstyle;
            QColor color = activePlot->getColorForCurve(key);
            colorstyle = colorstyle.sprintf("QWidget { background-color: #%02X%02X%02X; }", color.red(), color.green(), color.blue());
668 669 670 671 672
            colorIcon->setStyleSheet(colorstyle);
        }
    }
}

673 674 675 676 677
void LinechartWidget::setPlotFilterLineEditFocus()
{
    ui.plotFilterLineEdit->setFocus(Qt::ShortcutFocusReason);
}

678 679
void LinechartWidget::filterCurve(const QString &key, bool match)
{
680 681 682 683 684 685 686 687 688 689
        if (!checkBoxes[key]->isChecked())
        {
            colorIcons[key]->setVisible(match);
            curveNameLabels[key]->setVisible(match);
            (*curveLabels)[key]->setVisible(match);
            (*curveMeans)[key]->setVisible(match);
            (*curveVariances)[key]->setVisible(match);
            curveUnits[key]->setVisible(match);
            checkBoxes[key]->setVisible(match);
        }
690 691 692 693 694 695 696 697 698 699
}

void LinechartWidget::filterCurves(const QString &filter)
{
    //qDebug() << "filterCurves: filter: " << filter;

    if (filter != "")
    {
        /* Hide Elements which do not match the filter pattern */
        QStringMatcher stringMatcher(filter, Qt::CaseInsensitive);
700
        foreach (const QString &key, colorIcons.keys())
701 702 703 704 705 706 707 708 709 710 711 712 713 714
        {
            if (stringMatcher.indexIn(key) < 0)
            {
                filterCurve(key, false);
            }
            else
            {
                filterCurve(key, true);
            }
        }
    }
    else
    {
        /* Show all Elements */
715
        foreach (const QString &key, colorIcons.keys())
716 717 718 719 720 721
        {
            filterCurve(key, true);
        }
    }
}

722
QString LinechartWidget::getCurveName(const QString& key, bool shortEnabled)
723
{
724
    if (shortEnabled)
725 726
    {
        QString name;
727 728
        QStringList parts = curveNames.value(key).split(".");
        if (parts.length() > 1)
729
        {
730 731 732 733 734 735
            name = parts.at(1);
        }
        else
        {
            name = parts.at(0);
        }
736

737
        const int sizeLimit = 20;
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
        // Replace known words with abbreviations
        if (name.length() > sizeLimit)
        {
            name.replace("gyroscope", "gyro");
            name.replace("accelerometer", "acc");
            name.replace("magnetometer", "mag");
            name.replace("distance", "dist");
            name.replace("ailerons", "ail");
            name.replace("altitude", "alt");
            name.replace("waypoint", "wp");
            name.replace("throttle", "thr");
            name.replace("elevator", "elev");
            name.replace("rudder", "rud");
            name.replace("error", "err");
            name.replace("version", "ver");
            name.replace("message", "msg");
            name.replace("count", "cnt");
            name.replace("value", "val");
            name.replace("source", "src");
            name.replace("index", "idx");
            name.replace("type", "typ");
            name.replace("mode", "mod");
761
        }
762 763 764

        // Check if sub-part is still exceeding N chars
        if (name.length() > sizeLimit)
765
        {
766 767 768 769 770
            name.replace("a", "");
            name.replace("e", "");
            name.replace("i", "");
            name.replace("o", "");
            name.replace("u", "");
771
        }
772 773 774 775 776 777 778 779 780 781 782

        return name;
    }
    else
    {
        return curveNames.value(key);
    }
}

void LinechartWidget::setShortNames(bool enable)
{
783
    foreach (const QString &key, curveNames.keys())
784 785
    {
        curveNameLabels.value(key)->setText(getCurveName(key, enable));
786
    }
787
}
pixhawk's avatar
pixhawk committed
788

789 790 791
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
792 793 794 795 796 797 798
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
799 800
}

801 802
void LinechartWidget::setActive(bool active)
{
803
    if (activePlot) {
804 805
        activePlot->setActive(active);
    }
806
    if (active) {
807
        updateTimer->start(updateInterval);
808
    } else {
809
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
810 811 812 813 814 815 816 817 818 819 820
    }
}

/**
 * @brief Set the position of the plot window.
 * The plot covers only a portion of the complete time series. The scrollbar
 * allows to select a window of the time series. The right edge of the window is
 * defined proportional to the position of the scrollbar.
 *
 * @param scrollBarValue The value of the scrollbar, in the range from MIN_TIME_SCROLLBAR_VALUE to MAX_TIME_SCROLLBAR_VALUE
 **/
821 822
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
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
    plotWindowLock.lockForWrite();
    // Disable automatic scrolling immediately
    int scrollBarRange = (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE);
    double position = (static_cast<double>(scrollBarValue) - MIN_TIME_SCROLLBAR_VALUE) / scrollBarRange;
    quint64 scrollInterval;

    // Activate automatic scrolling if scrollbar is at the right edge
    if(scrollBarValue > MAX_TIME_SCROLLBAR_VALUE - (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE) * 0.01f) {
        activePlot->setAutoScroll(true);
    } else {
        activePlot->setAutoScroll(false);
        quint64 rightPosition;
        /* If the data exceeds the plot window, choose the position according to the scrollbar position */
        if(activePlot->getDataInterval() > activePlot->getPlotInterval()) {
            scrollInterval = activePlot->getDataInterval() - activePlot->getPlotInterval();
            rightPosition = activePlot->getMinTime() + activePlot->getPlotInterval() + (scrollInterval * position);
        } else {
            /* If the data interval is smaller as the plot interval, clamp the scrollbar to the right */
            rightPosition = activePlot->getMinTime() + activePlot->getPlotInterval();
        }
        emit plotWindowPositionUpdated(rightPosition);
    }


    // The slider position must be mapped onto an interval of datainterval - plotinterval,
    // because the slider position defines the right edge of the plot window. The leftmost
    // slider position must therefore map to the start of the data interval + plot interval
    // to ensure that the plot is not empty

    //  start> |-- plot interval --||-- (data interval - plotinterval) --| <end

    //@TODO Add notification of scrollbar here
    //plot->setWindowPosition(rightPosition);

    plotWindowLock.unlock();
}

/**
 * @brief Receive an updated plot window position.
 * The plot window can be changed by the arrival of new data or by
 * other user interaction. The scrollbar and other UI components
 * can be notified by calling this method.
 *
 * @param position The absolute position of the right edge of the plot window, in milliseconds
 **/
868 869
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
870 871 872 873 874 875 876
    plotWindowLock.lockForWrite();
    // Calculate the relative position
    double pos;

    // A relative position makes only sense if the plot is filled
    if(activePlot->getDataInterval() > activePlot->getPlotInterval()) {
        //TODO @todo Implement the scrollbar enabling in a more elegant way
877
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
878 879 880 881 882 883
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
884
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        pos = 1;
    }
    plotWindowLock.unlock();

    emit plotWindowPositionUpdated(static_cast<int>(pos * (MAX_TIME_SCROLLBAR_VALUE - MIN_TIME_SCROLLBAR_VALUE)));
}

/**
 * @brief Set the time interval the plot displays.
 * The time interval of the plot can be adjusted by this method. If the
 * data covers less time than the interval, the plot will be filled from
 * the right to left
 *
 * @param interval The time interval to plot
 **/
900 901
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
902 903 904 905 906
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
907 908 909
 * This method allows to map a button to a plot curve. The text of the
 * button must equal the curve name to activate / deactivate. If the checkbox
 * was clicked, show the curve color, otherwise clear the coloring.
pixhawk's avatar
pixhawk committed
910 911 912
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
913 914
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
915 916 917

    QCheckBox* button = qobject_cast<QCheckBox*>(QObject::sender());

918 919
    if(button != NULL)
    {
920
        activePlot->setVisibleById(button->objectName(), checked);
921 922
        QWidget* colorIcon = colorIcons.value(button->objectName(), 0);
        if (colorIcon)
923
        {
924 925 926 927 928 929 930 931 932 933 934
            if (checked)
            {
                QColor color = activePlot->getColorForCurve(button->objectName());
                if (color.isValid())
                {
                    QString colorstyle;
                    colorstyle = colorstyle.sprintf("QWidget { background-color: #%02X%02X%02X; }", color.red(), color.green(), color.blue());
                    colorIcon->setStyleSheet(colorstyle);
                }
            }
            else
935
            {
936
                colorIcon->setStyleSheet("");
937 938
            }
        }
pixhawk's avatar
pixhawk committed
939 940 941 942 943 944 945 946 947 948
    }
}

/**
 * @brief Factory method to create a new button.
 *
 * @param imagename The name of the image (should be placed at the standard icon location)
 * @param text The button text
 * @param parent The parent object (to ensure that the memory is freed after the deletion of the button)
 **/
949 950
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
951 952 953 954 955 956
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}