LinechartWidget.cc 33.4 KB
Newer Older
pixhawk's avatar
pixhawk committed
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
/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PIXHAWK is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Line chart plot widget
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
29
 *   @author Thomas Gubler <thomasgubler@student.ethz.ch>
pixhawk's avatar
pixhawk committed
30 31 32 33 34 35 36 37
 */

#include <QDebug>
#include <QWidget>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QComboBox>
#include <QToolButton>
38
#include <QSizePolicy>
pixhawk's avatar
pixhawk committed
39 40 41 42 43 44
#include <QScrollBar>
#include <QLabel>
#include <QMenu>
#include <QSpinBox>
#include <QColor>
#include <QPalette>
45
#include <QStandardPaths>
46
#include <QShortcut>
pixhawk's avatar
pixhawk committed
47 48 49 50

#include "LinechartWidget.h"
#include "LinechartPlot.h"
#include "LogCompressor.h"
lm's avatar
lm committed
51
#include "QGC.h"
pixhawk's avatar
pixhawk committed
52
#include "MG.h"
Don Gagne's avatar
Don Gagne committed
53
#include "QGCFileDialog.h"
Don Gagne's avatar
Don Gagne committed
54
#include "QGCMessageBox.h"
55
#include "QGCApplication.h"
pixhawk's avatar
pixhawk committed
56

57
LinechartWidget::LinechartWidget(int systemid, QWidget *parent) : QWidget(parent),
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    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
73
    updateTimer(new QTimer()),
74 75
    selectedMAV(-1),
    lastTimestamp(0)
pixhawk's avatar
pixhawk committed
76 77 78
{
    // Add elements defined in Qt Designer
    ui.setupUi(this);
79
    this->setMinimumSize(200, 150);
pixhawk's avatar
pixhawk committed
80 81 82 83

    // Add and customize curve list elements (left side)
    curvesWidget = new QWidget(ui.curveListWidget);
    ui.curveListWidget->setWidget(curvesWidget);
84
    curvesWidgetLayout = new QGridLayout(curvesWidget);
pixhawk's avatar
pixhawk committed
85 86
    curvesWidgetLayout->setMargin(2);
    curvesWidgetLayout->setSpacing(4);
87
    //curvesWidgetLayout->setSizeConstraint(QSizePolicy::Expanding);
88
    curvesWidgetLayout->setAlignment(Qt::AlignTop);
89 90 91 92 93 94 95

    curvesWidgetLayout->setColumnStretch(0, 0);
    curvesWidgetLayout->setColumnStretch(1, 0);
    curvesWidgetLayout->setColumnStretch(2, 80);
    curvesWidgetLayout->setColumnStretch(3, 50);
    curvesWidgetLayout->setColumnStretch(4, 50);
    curvesWidgetLayout->setColumnStretch(5, 50);
96 97
//    horizontalLayout->setColumnStretch(median, 50);
    curvesWidgetLayout->setColumnStretch(6, 50);
98

pixhawk's avatar
pixhawk committed
99 100
    curvesWidget->setLayout(curvesWidgetLayout);

101 102 103 104 105 106
    // Create curve list headings
    QLabel* label;
    QLabel* value;
    QLabel* mean;
    QLabel* variance;

107 108 109 110 111 112
    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);
113

114 115
    int labelRow = curvesWidgetLayout->rowCount();

116
    selectAllCheckBox = new QCheckBox("", this);
117
    connect(selectAllCheckBox, &QCheckBox::clicked, this, &LinechartWidget::selectAllCurves);
118
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0, 1, 2);
119 120

    label = new QLabel(this);
121
    label->setText("Name");
122
    curvesWidgetLayout->addWidget(label, labelRow, 2);
123 124

    // Value
125
    value = new QLabel(this);
126
    value->setText("Val");
127
    curvesWidgetLayout->addWidget(value, labelRow, 3);
128

129
    // Unit
130
    //curvesWidgetLayout->addWidget(new QLabel(tr("Unit")), labelRow, 4);
131

132
    // Mean
133
    mean = new QLabel(this);
134
    mean->setText("Mean");
135
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
136 137

    // Variance
138
    variance = new QLabel(this);
139
    variance->setText("Variance");
140
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
141

pixhawk's avatar
pixhawk committed
142 143
    // Create the layout
    createLayout();
144

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

LM's avatar
LM committed
148
    updateTimer->setInterval(updateInterval);
149 150 151
    connect(updateTimer, &QTimer::timeout, this, &LinechartWidget::refresh);
    connect(ui.uasSelectionBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
            this, &LinechartWidget::selectActiveSystem);
152
    readSettings();
pixhawk's avatar
pixhawk committed
153 154
}

155 156 157
LinechartWidget::~LinechartWidget()
{
    writeSettings();
pixhawk's avatar
pixhawk committed
158
    stopLogging();
159 160
    if (activePlot) delete activePlot;
    activePlot = NULL;
pixhawk's avatar
pixhawk committed
161 162
}

163 164 165 166 167 168 169 170 171 172 173
void LinechartWidget::selectActiveSystem(int mav)
{
    // -1: Unitialized, 0: all
    if (mav != selectedMAV && (selectedMAV != -1))
    {
        // Delete all curves
        // FIXME
    }
    selectedMAV = mav;
}

174 175 176
void LinechartWidget::selectAllCurves(bool all)
{
    QMap<QString, QLabel*>::iterator i;
177
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
178
        activePlot->setVisibleById(i.key(), all);
179 180 181
    }
}

182 183 184 185
void LinechartWidget::writeSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
186 187
    bool enforceGT = (!autoGroundTimeSet && timeButton->isChecked()) ? true : false;
    if (timeButton) settings.setValue("ENFORCE_GROUNDTIME", enforceGT);
188
    if (ui.showUnitsCheckBox) settings.setValue("SHOW_UNITS", ui.showUnitsCheckBox->isChecked());
189
    if (ui.shortNameCheckBox) settings.setValue("SHORT_NAMES", ui.shortNameCheckBox->isChecked());
190 191 192 193 194 195 196
    settings.endGroup();
}

void LinechartWidget::readSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
197
    if (activePlot) {
198 199
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
        activePlot->enforceGroundTime(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
200
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
201
        //userGroundTimeSet = settings.value("USER_GROUNDTIME", timeButton->isChecked()).toBool();
202
    }
203
    if (ui.showUnitsCheckBox) ui.showUnitsCheckBox->setChecked(settings.value("SHOW_UNITS", ui.showUnitsCheckBox->isChecked()).toBool());
204
    if (ui.shortNameCheckBox) ui.shortNameCheckBox->setChecked(settings.value("SHORT_NAMES", ui.shortNameCheckBox->isChecked()).toBool());
205 206 207
    settings.endGroup();
}

pixhawk's avatar
pixhawk committed
208 209 210 211 212 213
void LinechartWidget::createLayout()
{
    // Create actions
    createActions();

    // Setup the plot group box area layout
214 215 216
    QVBoxLayout* vlayout = new QVBoxLayout(ui.diagramGroupBox);
    vlayout->setSpacing(4);
    vlayout->setMargin(2);
pixhawk's avatar
pixhawk committed
217 218

    // Create plot container widget
219 220 221
    activePlot = new LinechartPlot(this, sysid);
    // Activate automatic scrolling
    activePlot->setAutoScroll(true);
pixhawk's avatar
pixhawk committed
222 223 224 225 226

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

227 228 229 230
    vlayout->addWidget(activePlot);

    QHBoxLayout *hlayout = new QHBoxLayout;
    vlayout->addLayout(hlayout);
pixhawk's avatar
pixhawk committed
231 232 233

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
234
    scalingLogButton->setText(tr("LOG"));
pixhawk's avatar
pixhawk committed
235
    scalingLogButton->setCheckable(true);
236 237
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
238
    hlayout->addWidget(scalingLogButton);
pixhawk's avatar
pixhawk committed
239 240 241

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
242 243
    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
244
    averageSpinBox->setMinimum(2);
245 246
    averageSpinBox->setValue(200);
    setAverageWindow(200);
247
    averageSpinBox->setMaximum(9999);
248
    hlayout->addWidget(averageSpinBox);
249
    connect(averageSpinBox,static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &LinechartWidget::setAverageWindow);
pixhawk's avatar
pixhawk committed
250 251 252

    // Log Button
    logButton = new QToolButton(this);
253 254
    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
255
    logButton->setText(tr("Start Logging"));
256
    hlayout->addWidget(logButton);
257
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
258

259
    // Ground time button
260
    timeButton = new QCheckBox(this);
261
    timeButton->setText(tr("Ground Time"));
262 263
    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."));
264
    hlayout->addWidget(timeButton);
265 266
    connect(timeButton.data(), &QCheckBox::clicked, activePlot, &LinechartPlot::enforceGroundTime);
    connect(timeButton.data(), &QCheckBox::clicked, this, &LinechartWidget::writeSettings);
267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    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);
289 290
    connect(timeScaleCmb, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
            this, &LinechartWidget::timeScaleChanged);
291

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

296 297 298 299
    // Add actions
    averageSpinBox->setValue(activePlot->getAverageWindow());

    // Connect notifications from the user interface to the plot
300
    connect(this, &LinechartWidget::curveRemoved, activePlot, &LinechartPlot::hideCurve);
301 302

    // Update scrollbar when plot window changes (via translator method setPlotWindowPosition()
303
//    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));
304
    connect(activePlot, &LinechartPlot::curveRemoved, this, &LinechartWidget::removeCurve);
305 306

    // Update plot when scrollbar is moved (via translator method setPlotWindowPosition()
307 308 309
    //TODO: impossible to
    connect(this, static_cast<void (LinechartWidget::*)(quint64)>(&LinechartWidget::plotWindowPositionUpdated),
            activePlot, &LinechartPlot::setWindowPosition);
310 311

    // Set scaling
312
    connect(scalingLogButton, &QToolButton::toggled, this, &LinechartWidget::toggleLogarithmicScaling);
313 314
}

315 316 317 318 319
void LinechartWidget::timeScaleChanged(int index)
{
    activePlot->setPlotInterval(timeScaleCmb->itemData(index).toInt()*1000);
}

320 321 322 323 324 325
void LinechartWidget::toggleLogarithmicScaling(bool checked)
{
    if(checked)
        activePlot->setLogarithmicScaling();
    else
        activePlot->setLinearScaling();
pixhawk's avatar
pixhawk committed
326 327
}

328
void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, const QVariant &variant, quint64 usec)
329
{
330 331 332 333 334 335
    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;
336

lm's avatar
lm committed
337 338
    if ((selectedMAV == -1 && isVisible()) || (selectedMAV == uasId && isVisible()))
    {
339 340 341 342 343
        // 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
344 345
        if(!label)
        {
346 347
            if(!isDouble)
                intData.insert(curve+unit, 0);
348 349
            addCurve(curve, unit);
        }
350 351

        // Add int data
352 353
        if(!isDouble)
            intData.insert(curve+unit, variant.toInt());
354 355
    }

356 357 358 359
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
360 361
        // Difference larger than 3 secs, enforce ground time
        if (((qint64)usec - (qint64)lastTimestamp) > 3000)
362 363
        {
            autoGroundTimeSet = true;
364 365 366 367 368
            // Tick ground time checkbox, but avoid state switching
            timeButton->blockSignals(true);
            timeButton->setChecked(true);
            timeButton->blockSignals(false);
            if (activePlot) activePlot->enforceGroundTime(true);
369
        }
370
        lastTimestamp = usec;
371 372
    }

373
    // Log data
lm's avatar
lm committed
374 375 376 377
    if (logging)
    {
        if (activePlot->isVisible(curve+unit))
        {
378
            if (usec == 0) usec = QGC::groundTimeMilliseconds();
379 380 381 382
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

383 384
            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());
385 386 387 388
        }
    }
}

389 390
void LinechartWidget::refresh()
{
LM's avatar
LM committed
391
    setUpdatesEnabled(false);
392
    QString str;
393
    // Value
394
    QMap<QString, QLabel*>::iterator i;
395 396
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i) {
        if (intData.contains(i.key())) {
lm's avatar
lm committed
397
            str.sprintf("% 11i", intData.value(i.key()));
398
        } else {
lm's avatar
lm committed
399 400
            double val = activePlot->getCurrentValue(i.key());
            int intval = static_cast<int>(val);
401
            if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
402
                str.sprintf("% 11i", intval);
403
            } else if (intval >= 10000 || intval <= -10000) {
lm's avatar
lm committed
404
                str.sprintf("% 11.2f", val);
405
            } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
406
                str.sprintf("% 11.4f", val);
407
            } else {
lm's avatar
lm committed
408 409
                str.sprintf("% 11.6f", val);
            }
410
        }
411 412 413 414 415
        // Value
        i.value()->setText(str);
    }
    // Mean
    QMap<QString, QLabel*>::iterator j;
416
    for (j = curveMeans->begin(); j != curveMeans->end(); ++j) {
417
        double val = activePlot->getMean(j.key());
lm's avatar
lm committed
418
        int intval = static_cast<int>(val);
419
        if (intval >= 100000 || intval <= -100000) {
lm's avatar
lm committed
420
            str.sprintf("% 11i", intval);
421
        } else if (intval >= 10000 || intval <= -10000) {
422
            str.sprintf("% 11.2f", val);
423
        } else if (intval >= 1000 || intval <= -1000) {
lm's avatar
lm committed
424
            str.sprintf("% 11.4f", val);
425
        } else {
426 427
            str.sprintf("% 11.6f", val);
        }
428 429
        j.value()->setText(str);
    }
430 431 432 433 434 435 436
//    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);
//    }
437
    QMap<QString, QLabel*>::iterator l;
438 439 440 441 442
    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
443
    setUpdatesEnabled(true);
444 445
}

pixhawk's avatar
pixhawk committed
446 447
void LinechartWidget::startLogging()
{
lm's avatar
lm committed
448
    // Check if any curve is enabled
449
    if (!activePlot->anyCurveVisible()) {
dogmaphobic's avatar
dogmaphobic committed
450 451 452
        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
453 454 455 456
        return;
    }

    // Let user select the log file name
457
    // QDate date(QDate::currentDate());
lm's avatar
lm committed
458
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
dogmaphobic's avatar
dogmaphobic committed
459 460 461
    QString fileName = QGCFileDialog::getSaveFileName(this,
        tr("Save Log File"),
        QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
462
        tr("Log Files (*.log)"),
463
        "log"); // Default type
464

465
    qDebug() << "SAVE FILE " << fileName;
466

dogmaphobic's avatar
dogmaphobic committed
467
    if (!fileName.isEmpty()) {
468
        logFile = new QFile(fileName);
Lorenz Meier's avatar
Lorenz Meier committed
469
        if (logFile->open(QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text)) {
470
            logging = true;
471 472
            logStartTime = 0;
            curvesWidget->setEnabled(false);
473 474
            logindex++;
            logButton->setText(tr("Stop logging"));
475 476
            disconnect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
            connect(logButton, &QToolButton::clicked, this, &LinechartWidget::stopLogging);
477
        }
pixhawk's avatar
pixhawk committed
478 479 480 481 482 483
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
484
    curvesWidget->setEnabled(true);
485
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
486 487 488
        logFile->flush();
        logFile->close();
        // Postprocess log file
489
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
490
        connect(compressor, &LogCompressor::finishedFile, this, &LinechartWidget::logfileWritten);
491

dogmaphobic's avatar
dogmaphobic committed
492 493 494 495 496
        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);
497
        bool fill = (button == QMessageBox::Yes);
498 499

        compressor->startCompression(fill);
pixhawk's avatar
pixhawk committed
500 501
    }
    logButton->setText(tr("Start logging"));
502 503
    disconnect(logButton, &QToolButton::clicked, this, &LinechartWidget::stopLogging);
    connect(logButton, &QToolButton::clicked, this, &LinechartWidget::startLogging);
pixhawk's avatar
pixhawk committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
}

/**
 * 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()
 **/
527
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
528
{
529
    LinechartPlot* plot = activePlot;
530
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
531 532 533
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
534
    QLabel* unitLabel;
pixhawk's avatar
pixhawk committed
535
    QLabel* mean;
536
    QLabel* variance;
pixhawk's avatar
pixhawk committed
537

538 539
    curveNames.insert(curve+unit, curve);

540 541
    int labelRow = curvesWidgetLayout->rowCount();

542
    // Checkbox
543
    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
544
    checkBox->setCheckable(true);
545
    checkBox->setObjectName(curve+unit);
546 547
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
548
    checkBoxes.insert(curve+unit, checkBox);
549
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
550

551
    // Icon
552
    QWidget* colorIcon = new QWidget(this);
553
    colorIcons.insert(curve+unit, colorIcon);
pixhawk's avatar
pixhawk committed
554 555
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);
556
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
557

558
    // Label
559
    label = new QLabel(this);
560
    label->setText(getCurveName(curve+unit, ui.shortNameCheckBox->isChecked()));
561
    curveNameLabels.insert(curve+unit, label);
562
    curvesWidgetLayout->addWidget(label, labelRow, 2);
563

pixhawk's avatar
pixhawk committed
564
    // Value
565
    value = new QLabel(this);
pixhawk's avatar
pixhawk committed
566
    value->setNum(0.00);
567
    value->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
568 569
    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));
570
    curveLabels->insert(curve+unit, value);
571
    curvesWidgetLayout->addWidget(value, labelRow, 3);
pixhawk's avatar
pixhawk committed
572

573 574 575 576 577
    // Unit
    unitLabel = new QLabel(this);
    unitLabel->setText(unit);
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
578
    curveUnits.insert(curve+unit, unitLabel);
579
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
580
    unitLabel->setVisible(ui.showUnitsCheckBox->isChecked());
581
    connect(ui.showUnitsCheckBox, &QCheckBox::clicked, unitLabel, &QLabel::setVisible);
582

pixhawk's avatar
pixhawk committed
583
    // Mean
584
    mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
585
    mean->setNum(0.00);
lm's avatar
lm committed
586
    mean->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
587 588
    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));
589 590
    curveMeans->insert(curve+unit, mean);
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
pixhawk's avatar
pixhawk committed
591

592 593 594 595 596
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
597

598
    // Variance
599
    variance = new QLabel(this);
600
    variance->setNum(0.00);
lm's avatar
lm committed
601
    variance->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
602 603
    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));
604 605
    curveVariances->insert(curve+unit, variance);
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
606

pixhawk's avatar
pixhawk committed
607 608 609 610 611 612 613 614 615 616 617
    /* 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

618 619 620
    // Load visibility settings
    // TODO

pixhawk's avatar
pixhawk committed
621
    // Connect actions
622 623 624
    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
625 626 627

    // Set UI components to initial state
    checkBox->setChecked(false);
628
    plot->setVisibleById(curve+unit, false);
pixhawk's avatar
pixhawk committed
629 630 631 632 633 634 635 636
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
637
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
638
{
639
    Q_UNUSED(curve)
640 641 642 643 644 645 646 647 648 649 650 651 652 653

    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();
654 655 656 657 658 659 660 661
    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);
662
    widget->deleteLater();
663 664 665 666
    QCheckBox* checkbox;
    checkbox = checkBoxes.take(curve);
    curvesWidgetLayout->removeWidget(checkbox);
    checkbox->deleteLater();
667 668 669 670 671
//    intData->remove(curve);
}

void LinechartWidget::recolor()
{
672
    activePlot->styleChanged(qgcApp()->styleIsDark());
673
    foreach (const QString &key, colorIcons.keys())
674 675
    {
        QWidget* colorIcon = colorIcons.value(key, 0);
676
        if (colorIcon && !colorIcon->styleSheet().isEmpty())
677
        {
678 679 680
            QString colorstyle;
            QColor color = activePlot->getColorForCurve(key);
            colorstyle = colorstyle.sprintf("QWidget { background-color: #%02X%02X%02X; }", color.red(), color.green(), color.blue());
681 682 683 684 685
            colorIcon->setStyleSheet(colorstyle);
        }
    }
}

686 687 688 689 690
void LinechartWidget::setPlotFilterLineEditFocus()
{
    ui.plotFilterLineEdit->setFocus(Qt::ShortcutFocusReason);
}

691 692
void LinechartWidget::filterCurve(const QString &key, bool match)
{
693 694 695 696 697 698 699 700 701 702
        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);
        }
703 704 705 706 707 708 709 710 711 712
}

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);
713
        foreach (const QString &key, colorIcons.keys())
714 715 716 717 718 719 720 721 722 723 724 725 726 727
        {
            if (stringMatcher.indexIn(key) < 0)
            {
                filterCurve(key, false);
            }
            else
            {
                filterCurve(key, true);
            }
        }
    }
    else
    {
        /* Show all Elements */
728
        foreach (const QString &key, colorIcons.keys())
729 730 731 732 733 734
        {
            filterCurve(key, true);
        }
    }
}

735
QString LinechartWidget::getCurveName(const QString& key, bool shortEnabled)
736
{
737
    if (shortEnabled)
738 739
    {
        QString name;
740 741
        QStringList parts = curveNames.value(key).split(".");
        if (parts.length() > 1)
742
        {
743 744 745 746 747 748
            name = parts.at(1);
        }
        else
        {
            name = parts.at(0);
        }
749

750
        const int sizeLimit = 20;
751

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
        // 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");
774
        }
775 776 777

        // Check if sub-part is still exceeding N chars
        if (name.length() > sizeLimit)
778
        {
779 780 781 782 783
            name.replace("a", "");
            name.replace("e", "");
            name.replace("i", "");
            name.replace("o", "");
            name.replace("u", "");
784
        }
785 786 787 788 789 790 791 792 793 794 795

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

void LinechartWidget::setShortNames(bool enable)
{
796
    foreach (const QString &key, curveNames.keys())
797 798
    {
        curveNameLabels.value(key)->setText(getCurveName(key, enable));
799
    }
800
}
pixhawk's avatar
pixhawk committed
801

802 803 804
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
805 806 807 808 809 810 811
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
812 813
}

814 815
void LinechartWidget::setActive(bool active)
{
816
    if (activePlot) {
817 818
        activePlot->setActive(active);
    }
819
    if (active) {
820
        updateTimer->start(updateInterval);
821
    } else {
822
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
823 824 825 826 827 828 829 830 831 832 833
    }
}

/**
 * @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
 **/
834 835
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
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
    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
 **/
881 882
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
883 884 885 886 887 888 889
    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
890
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
891 892 893 894 895 896
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
897
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
        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
 **/
913 914
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
915 916 917 918 919
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
920 921 922
 * 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
923 924 925
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
926 927
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
928 929 930

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

931 932
    if(button != NULL)
    {
933
        activePlot->setVisibleById(button->objectName(), checked);
934 935
        QWidget* colorIcon = colorIcons.value(button->objectName(), 0);
        if (colorIcon)
936
        {
937 938 939 940 941 942 943 944 945 946 947
            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
948
            {
949
                colorIcon->setStyleSheet("");
950 951
            }
        }
pixhawk's avatar
pixhawk committed
952 953 954 955 956 957 958 959 960 961
    }
}

/**
 * @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)
 **/
962 963
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
964 965 966 967 968 969
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}