LinechartWidget.cc 33.4 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"
40
#include "QGCQFileDialog.h"
Don Gagne's avatar
Don Gagne committed
41
#include "QGCMessageBox.h"
42
#include "QGCApplication.h"
43
#include "SettingsManager.h"
pixhawk's avatar
pixhawk committed
44

45
LinechartWidget::LinechartWidget(int systemid, QWidget *parent) : QWidget(parent),
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*>()),
    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);
Gus Grubba's avatar
Gus Grubba committed
66
    this->setMinimumSize(600, 400);
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);
Gus Grubba's avatar
Gus Grubba committed
72 73
    curvesWidgetLayout->setMargin(6);
    curvesWidgetLayout->setSpacing(6);
74
    curvesWidgetLayout->setAlignment(Qt::AlignTop);
Gus Grubba's avatar
Gus Grubba committed
75
    curvesWidgetLayout->setColumnMinimumWidth(0, 10);
76 77

    curvesWidgetLayout->setColumnStretch(0, 0);
Gus Grubba's avatar
Gus Grubba committed
78
    curvesWidgetLayout->setColumnStretch(1, 10);
79 80 81 82
    curvesWidgetLayout->setColumnStretch(2, 80);
    curvesWidgetLayout->setColumnStretch(3, 50);
    curvesWidgetLayout->setColumnStretch(4, 50);
    curvesWidgetLayout->setColumnStretch(5, 50);
83
    curvesWidgetLayout->setColumnStretch(6, 50);
84

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

87
    // Create curve list headings
88 89
    connect(ui.recolorButton, &QPushButton::clicked, this, &LinechartWidget::recolor);
    connect(ui.shortNameCheckBox, &QCheckBox::clicked, this, &LinechartWidget::setShortNames);
90
    connect(ui.plotFilterLineEdit, &QLineEdit::textChanged, this, &LinechartWidget::_restartFilterTimeout);
91 92 93
    QShortcut *shortcut  = new QShortcut(this);
    shortcut->setKey(QKeySequence(Qt::CTRL + Qt::Key_F));
    connect(shortcut, &QShortcut::activated, this, &LinechartWidget::setPlotFilterLineEditFocus);
94

95 96
    int labelRow = curvesWidgetLayout->rowCount();

Gus Grubba's avatar
Gus Grubba committed
97
    selectAllCheckBox = new QCheckBox(this);
98
    connect(selectAllCheckBox, &QCheckBox::clicked, this, &LinechartWidget::selectAllCurves);
Gus Grubba's avatar
Gus Grubba committed
99
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0);
100

Gus Grubba's avatar
Gus Grubba committed
101 102 103 104
    QWidget* colorIcon = new QWidget(this);
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(QSize(5, 14));
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
105

Gus Grubba's avatar
Gus Grubba committed
106 107
    curvesWidgetLayout->addWidget(new QLabel(tr("Name")),     labelRow, 2);
    curvesWidgetLayout->addWidget(new QLabel(tr("Val")),      labelRow, 3, Qt::AlignRight);
108

Gus Grubba's avatar
Gus Grubba committed
109 110
    QLabel* pUnit = new QLabel(tr("Unit"));
    curvesWidgetLayout->addWidget(pUnit,                      labelRow, 4);
111

Gus Grubba's avatar
Gus Grubba committed
112 113
    curvesWidgetLayout->addWidget(new QLabel(tr("Mean")),     labelRow, 5, Qt::AlignRight);
    curvesWidgetLayout->addWidget(new QLabel(tr("Variance")), labelRow, 6, Qt::AlignRight);
114 115


pixhawk's avatar
pixhawk committed
116 117
    // Create the layout
    createLayout();
118

119
    // And make sure we're listening for future style changes
120
    connect(qgcApp()->toolbox()->settingsManager()->appSettings()->indoorPalette(), &Fact::rawValueChanged, this, &LinechartWidget::recolor);
121

LM's avatar
LM committed
122
    updateTimer->setInterval(updateInterval);
123
    connect(updateTimer, &QTimer::timeout, this, &LinechartWidget::refresh);
Gus Grubba's avatar
Gus Grubba committed
124 125
    connect(ui.uasSelectionBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &LinechartWidget::selectActiveSystem);

126
    readSettings();
Gus Grubba's avatar
Gus Grubba committed
127 128
    pUnit->setVisible(ui.showUnitsCheckBox->isChecked());
    connect(ui.showUnitsCheckBox, &QCheckBox::clicked, pUnit, &QLabel::setVisible);
129 130 131

    _filterTimer.setInterval(500);
    connect(&_filterTimer, &QTimer::timeout, this, &LinechartWidget::_filterTimeout);
pixhawk's avatar
pixhawk committed
132 133
}

134 135 136
LinechartWidget::~LinechartWidget()
{
    writeSettings();
pixhawk's avatar
pixhawk committed
137
    stopLogging();
138 139
    if (activePlot) delete activePlot;
    activePlot = NULL;
pixhawk's avatar
pixhawk committed
140 141
}

142 143 144 145 146 147 148 149 150 151 152
void LinechartWidget::selectActiveSystem(int mav)
{
    // -1: Unitialized, 0: all
    if (mav != selectedMAV && (selectedMAV != -1))
    {
        // Delete all curves
        // FIXME
    }
    selectedMAV = mav;
}

153 154 155
void LinechartWidget::selectAllCurves(bool all)
{
    QMap<QString, QLabel*>::iterator i;
156
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
157
        activePlot->setVisibleById(i.key(), all);
158 159 160
    }
}

161 162 163 164
void LinechartWidget::writeSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
165 166
    bool enforceGT = (!autoGroundTimeSet && timeButton->isChecked()) ? true : false;
    if (timeButton) settings.setValue("ENFORCE_GROUNDTIME", enforceGT);
167
    if (ui.showUnitsCheckBox) settings.setValue("SHOW_UNITS", ui.showUnitsCheckBox->isChecked());
168
    if (ui.shortNameCheckBox) settings.setValue("SHORT_NAMES", ui.shortNameCheckBox->isChecked());
169 170 171 172 173 174 175
    settings.endGroup();
}

void LinechartWidget::readSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
176
    if (activePlot) {
177 178
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
        activePlot->enforceGroundTime(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
179
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
180
        //userGroundTimeSet = settings.value("USER_GROUNDTIME", timeButton->isChecked()).toBool();
181
    }
182
    if (ui.showUnitsCheckBox) ui.showUnitsCheckBox->setChecked(settings.value("SHOW_UNITS", ui.showUnitsCheckBox->isChecked()).toBool());
183
    if (ui.shortNameCheckBox) ui.shortNameCheckBox->setChecked(settings.value("SHORT_NAMES", ui.shortNameCheckBox->isChecked()).toBool());
184 185 186
    settings.endGroup();
}

pixhawk's avatar
pixhawk committed
187 188 189 190 191 192
void LinechartWidget::createLayout()
{
    // Create actions
    createActions();

    // Setup the plot group box area layout
193 194 195
    QVBoxLayout* vlayout = new QVBoxLayout(ui.diagramGroupBox);
    vlayout->setSpacing(4);
    vlayout->setMargin(2);
pixhawk's avatar
pixhawk committed
196 197

    // Create plot container widget
198 199 200
    activePlot = new LinechartPlot(this, sysid);
    // Activate automatic scrolling
    activePlot->setAutoScroll(true);
pixhawk's avatar
pixhawk committed
201 202 203 204 205

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

206 207 208 209
    vlayout->addWidget(activePlot);

    QHBoxLayout *hlayout = new QHBoxLayout;
    vlayout->addLayout(hlayout);
pixhawk's avatar
pixhawk committed
210 211 212

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
213
    scalingLogButton->setText(tr("LOG"));
pixhawk's avatar
pixhawk committed
214
    scalingLogButton->setCheckable(true);
215 216
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
217
    hlayout->addWidget(scalingLogButton);
pixhawk's avatar
pixhawk committed
218 219 220

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
221 222
    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
223
    averageSpinBox->setMinimum(2);
224 225
    averageSpinBox->setValue(200);
    setAverageWindow(200);
226
    averageSpinBox->setMaximum(9999);
227
    hlayout->addWidget(averageSpinBox);
228
    connect(averageSpinBox,static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LinechartWidget::setAverageWindow);
pixhawk's avatar
pixhawk committed
229 230 231

    // Log Button
    logButton = new QToolButton(this);
232 233
    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
234
    logButton->setText(tr("Start Logging"));
235
    hlayout->addWidget(logButton);
236
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
237

238
    // Ground time button
239
    timeButton = new QCheckBox(this);
240
    timeButton->setText(tr("Ground Time"));
241 242
    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."));
243
    hlayout->addWidget(timeButton);
244 245
    connect(timeButton.data(), &QCheckBox::clicked, activePlot, &LinechartPlot::enforceGroundTime);
    connect(timeButton.data(), &QCheckBox::clicked, this, &LinechartWidget::writeSettings);
246

247 248
    hlayout->addStretch();

249
    QLabel *timeScaleLabel = new QLabel(tr("Time axis:"));
250 251 252
    hlayout->addWidget(timeScaleLabel);

    timeScaleCmb = new QComboBox(this);
253 254 255 256 257 258 259 260 261 262 263
    timeScaleCmb->addItem(tr("10 seconds"), 10);
    timeScaleCmb->addItem(tr("20 seconds"), 20);
    timeScaleCmb->addItem(tr("30 seconds"), 30);
    timeScaleCmb->addItem(tr("40 seconds"), 40);
    timeScaleCmb->addItem(tr("50 seconds"), 50);
    timeScaleCmb->addItem(tr("1 minute"), 60);
    timeScaleCmb->addItem(tr("2 minutes"), 60*2);
    timeScaleCmb->addItem(tr("3 minutes"), 60*3);
    timeScaleCmb->addItem(tr("4 minutes"), 60*4);
    timeScaleCmb->addItem(tr("5 minutes"), 60*5);
    timeScaleCmb->addItem(tr("10 minutes"), 60*10);
264 265 266 267
    //timeScaleCmb->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    timeScaleCmb->setMinimumContentsLength(12);

    hlayout->addWidget(timeScaleCmb);
268 269
    connect(timeScaleCmb, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
            this, &LinechartWidget::timeScaleChanged);
270

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

275 276 277 278
    // Add actions
    averageSpinBox->setValue(activePlot->getAverageWindow());

    // Connect notifications from the user interface to the plot
279
    connect(this, &LinechartWidget::curveRemoved, activePlot, &LinechartPlot::hideCurve);
280 281

    // Update scrollbar when plot window changes (via translator method setPlotWindowPosition()
282
//    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));
283
    connect(activePlot, &LinechartPlot::curveRemoved, this, &LinechartWidget::removeCurve);
284 285

    // Update plot when scrollbar is moved (via translator method setPlotWindowPosition()
286 287 288
    //TODO: impossible to
    connect(this, static_cast<void (LinechartWidget::*)(quint64)>(&LinechartWidget::plotWindowPositionUpdated),
            activePlot, &LinechartPlot::setWindowPosition);
289 290

    // Set scaling
291
    connect(scalingLogButton, &QToolButton::toggled, this, &LinechartWidget::toggleLogarithmicScaling);
292 293
}

294 295 296 297 298
void LinechartWidget::timeScaleChanged(int index)
{
    activePlot->setPlotInterval(timeScaleCmb->itemData(index).toInt()*1000);
}

299 300 301 302 303 304
void LinechartWidget::toggleLogarithmicScaling(bool checked)
{
    if(checked)
        activePlot->setLogarithmicScaling();
    else
        activePlot->setLinearScaling();
pixhawk's avatar
pixhawk committed
305 306
}

307
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, const QVariant &variant, quint64 usec)
308
{
309 310 311 312 313 314
    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;
Gus Grubba's avatar
Gus Grubba committed
315
    QString curveID = curve + unit;
316

lm's avatar
lm committed
317 318
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
319
        // Order matters here, first append to plot, then update curve list
Gus Grubba's avatar
Gus Grubba committed
320
        activePlot->appendData(curveID, usec, value);
321
        // Store data
Gus Grubba's avatar
Gus Grubba committed
322
        QLabel* label = curveLabels->value(curveID, NULL);
323
        // Make sure the curve will be created if it does not yet exist
lm's avatar
lm committed
324 325
        if(!label)
        {
326
            if(!isDouble)
Gus Grubba's avatar
Gus Grubba committed
327
                intData.insert(curveID, 0);
328 329
            addCurve(curve, unit);
        }
330 331

        // Add int data
332
        if(!isDouble)
Gus Grubba's avatar
Gus Grubba committed
333
            intData.insert(curveID, variant.toInt());
334 335
    }

336 337 338 339
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
340 341
        // Difference larger than 3 secs, enforce ground time
        if (((qint64)usec - (qint64)lastTimestamp) > 3000)
342 343
        {
            autoGroundTimeSet = true;
344 345 346 347 348
            // Tick ground time checkbox, but avoid state switching
            timeButton->blockSignals(true);
            timeButton->setChecked(true);
            timeButton->blockSignals(false);
            if (activePlot) activePlot->enforceGroundTime(true);
349
        }
350
        lastTimestamp = usec;
351 352
    }

353
    // Log data
lm's avatar
lm committed
354 355
    if (logging)
    {
Gus Grubba's avatar
Gus Grubba committed
356
        if (activePlot->isVisible(curveID))
lm's avatar
lm committed
357
        {
358
            if (usec == 0) usec = QGC::groundTimeMilliseconds();
359 360 361 362
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

363 364
            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());
365 366 367 368
        }
    }
}

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

pixhawk's avatar
pixhawk committed
426 427
void LinechartWidget::startLogging()
{
lm's avatar
lm committed
428
    // Check if any curve is enabled
429
    if (!activePlot->anyCurveVisible()) {
dogmaphobic's avatar
dogmaphobic committed
430 431 432
        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
433 434 435 436
        return;
    }

    // Let user select the log file name
437
    // QDate date(QDate::currentDate());
lm's avatar
lm committed
438
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
439
    QString fileName = QGCQFileDialog::getSaveFileName(this,
dogmaphobic's avatar
dogmaphobic committed
440 441
        tr("Save Log File"),
        QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
442
        tr("Log Files (*.log)"),
443
        "log"); // Default type
444

445
    qDebug() << "SAVE FILE " << fileName;
446

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

void LinechartWidget::stopLogging()
{
    logging = false;
464
    curvesWidget->setEnabled(true);
465
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
466 467 468
        logFile->flush();
        logFile->close();
        // Postprocess log file
469
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
470
        connect(compressor, &LogCompressor::finishedFile, this, &LinechartWidget::logfileWritten);
471

dogmaphobic's avatar
dogmaphobic committed
472 473 474 475 476
        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);
477
        bool fill = (button == QMessageBox::Yes);
478 479

        compressor->startCompression(fill);
pixhawk's avatar
pixhawk committed
480 481
    }
    logButton->setText(tr("Start logging"));
482 483
    disconnect(logButton, &QToolButton::clicked, this, &LinechartWidget::stopLogging);
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
}

/**
 * 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()
 **/
507
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
508
{
509
    LinechartPlot* plot = activePlot;
Gus Grubba's avatar
Gus Grubba committed
510 511
    QString curveID = curve + unit;
    curveNames.insert(curveID, curve);
512 513
    int labelRow = curvesWidgetLayout->rowCount();

514
    // Checkbox
Gus Grubba's avatar
Gus Grubba committed
515
    QCheckBox* checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
516
    checkBox->setCheckable(true);
Gus Grubba's avatar
Gus Grubba committed
517
    checkBox->setObjectName(curveID);
518 519
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
Gus Grubba's avatar
Gus Grubba committed
520
    checkBoxes.insert(curveID, checkBox);
521
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
522

523
    // Icon
524
    QWidget* colorIcon = new QWidget(this);
Gus Grubba's avatar
Gus Grubba committed
525
    colorIcons.insert(curveID, colorIcon);
pixhawk's avatar
pixhawk committed
526
    colorIcon->setMinimumSize(QSize(5, 14));
Gus Grubba's avatar
Gus Grubba committed
527
    colorIcon->setMaximumSize(QSize(5, 14));
528
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
529

530
    // Label
Gus Grubba's avatar
Gus Grubba committed
531 532 533
    QLabel* label = new QLabel(this);
    label->setText(getCurveName(curveID, ui.shortNameCheckBox->isChecked()));
    curveNameLabels.insert(curveID, label);
534
    curvesWidgetLayout->addWidget(label, labelRow, 2);
535

pixhawk's avatar
pixhawk committed
536
    // Value
Gus Grubba's avatar
Gus Grubba committed
537
    QLabel* value = new QLabel(this);
pixhawk's avatar
pixhawk committed
538
    value->setNum(0.00);
539
    value->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
540 541
    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));
Gus Grubba's avatar
Gus Grubba committed
542 543
    curveLabels->insert(curveID, value);
    curvesWidgetLayout->addWidget(value, labelRow, 3, Qt::AlignRight);
pixhawk's avatar
pixhawk committed
544

545
    // Unit
Gus Grubba's avatar
Gus Grubba committed
546
    QLabel* unitLabel = new QLabel(this);
547 548 549
    unitLabel->setText(unit);
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
Gus Grubba's avatar
Gus Grubba committed
550
    curveUnits.insert(curveID, unitLabel);
551
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
552
    unitLabel->setVisible(ui.showUnitsCheckBox->isChecked());
553
    connect(ui.showUnitsCheckBox, &QCheckBox::clicked, unitLabel, &QLabel::setVisible);
554

pixhawk's avatar
pixhawk committed
555
    // Mean
Gus Grubba's avatar
Gus Grubba committed
556
    QLabel* mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
557
    mean->setNum(0.00);
lm's avatar
lm committed
558
    mean->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
559 560
    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));
Gus Grubba's avatar
Gus Grubba committed
561 562
    curveMeans->insert(curveID, mean);
    curvesWidgetLayout->addWidget(mean, labelRow, 5, Qt::AlignRight);
pixhawk's avatar
pixhawk committed
563

564 565 566 567 568
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
569

570
    // Variance
Gus Grubba's avatar
Gus Grubba committed
571
    QLabel* variance = new QLabel(this);
572
    variance->setNum(0.00);
lm's avatar
lm committed
573
    variance->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
574 575
    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));
Gus Grubba's avatar
Gus Grubba committed
576 577
    curveVariances->insert(curveID, variance);
    curvesWidgetLayout->addWidget(variance, labelRow, 6, Qt::AlignRight);
578

pixhawk's avatar
pixhawk committed
579 580 581 582 583 584 585 586 587 588 589
    /* 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

590 591 592
    // Load visibility settings
    // TODO

pixhawk's avatar
pixhawk committed
593
    // Connect actions
594 595 596
    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
597 598 599

    // Set UI components to initial state
    checkBox->setChecked(false);
Gus Grubba's avatar
Gus Grubba committed
600
    plot->setVisibleById(curveID, false);
pixhawk's avatar
pixhawk committed
601 602 603 604 605 606 607 608
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
609
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
610
{
611
    Q_UNUSED(curve)
612 613 614 615 616 617 618 619 620 621 622 623 624 625

    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();
626 627 628 629 630 631 632 633
    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);
634
    widget->deleteLater();
635 636 637 638
    QCheckBox* checkbox;
    checkbox = checkBoxes.take(curve);
    curvesWidgetLayout->removeWidget(checkbox);
    checkbox->deleteLater();
639 640 641 642 643
//    intData->remove(curve);
}

void LinechartWidget::recolor()
{
644
    activePlot->styleChanged(qgcApp()->toolbox()->settingsManager()->appSettings()->indoorPalette()->rawValue().toBool());
645
    foreach (const QString &key, colorIcons.keys())
646 647
    {
        QWidget* colorIcon = colorIcons.value(key, 0);
648
        if (colorIcon && !colorIcon->styleSheet().isEmpty())
649
        {
650 651 652
            QString colorstyle;
            QColor color = activePlot->getColorForCurve(key);
            colorstyle = colorstyle.sprintf("QWidget { background-color: #%02X%02X%02X; }", color.red(), color.green(), color.blue());
653 654 655 656 657
            colorIcon->setStyleSheet(colorstyle);
        }
    }
}

658 659 660 661 662
void LinechartWidget::setPlotFilterLineEditFocus()
{
    ui.plotFilterLineEdit->setFocus(Qt::ShortcutFocusReason);
}

663 664
void LinechartWidget::filterCurve(const QString &key, bool match)
{
665 666 667 668 669 670 671
        if (!checkBoxes[key]->isChecked())
        {
            colorIcons[key]->setVisible(match);
            curveNameLabels[key]->setVisible(match);
            (*curveLabels)[key]->setVisible(match);
            (*curveMeans)[key]->setVisible(match);
            (*curveVariances)[key]->setVisible(match);
Gus Grubba's avatar
Gus Grubba committed
672
            curveUnits[key]->setVisible(match && ui.showUnitsCheckBox->isChecked());
673 674
            checkBoxes[key]->setVisible(match);
        }
675 676
}

677 678 679 680 681 682 683 684 685 686
void LinechartWidget::_restartFilterTimeout(void)
{
    _filterTimer.start();
}

void LinechartWidget::_filterTimeout(void)
{
    filterCurves(ui.plotFilterLineEdit->text());
}

687 688 689 690 691 692 693 694
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);
695
        foreach (const QString &key, colorIcons.keys())
696 697 698 699 700 701 702 703 704 705 706 707 708 709
        {
            if (stringMatcher.indexIn(key) < 0)
            {
                filterCurve(key, false);
            }
            else
            {
                filterCurve(key, true);
            }
        }
    }
    else
    {
        /* Show all Elements */
710
        foreach (const QString &key, colorIcons.keys())
711 712 713 714 715 716
        {
            filterCurve(key, true);
        }
    }
}

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

732
        const int sizeLimit = 20;
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        // 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");
756
        }
757 758 759

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

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

void LinechartWidget::setShortNames(bool enable)
{
778
    foreach (const QString &key, curveNames.keys())
779 780
    {
        curveNameLabels.value(key)->setText(getCurveName(key, enable));
781
    }
782
}
pixhawk's avatar
pixhawk committed
783

784 785 786
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
787 788 789 790 791 792 793
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
794 795
}

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

/**
 * @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
 **/
816 817
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
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
    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
 **/
863 864
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
865 866 867 868 869 870 871
    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
872
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
873 874 875 876 877 878
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
879
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
        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
 **/
895 896
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
897 898 899 900 901
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
902 903 904
 * 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
905 906 907
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
908 909
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
910 911 912

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

913 914
    if(button != NULL)
    {
915
        activePlot->setVisibleById(button->objectName(), checked);
916 917
        QWidget* colorIcon = colorIcons.value(button->objectName(), 0);
        if (colorIcon)
918
        {
919 920 921 922 923 924 925 926 927 928 929
            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
930
            {
931
                colorIcon->setStyleSheet("");
932 933
            }
        }
pixhawk's avatar
pixhawk committed
934 935 936 937 938 939 940 941 942 943
    }
}

/**
 * @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)
 **/
944 945
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
946 947 948 949 950 951
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}