LinechartWidget.cc 34.1 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 "MainWindow.h"
lm's avatar
lm committed
52
#include "QGC.h"
pixhawk's avatar
pixhawk committed
53
#include "MG.h"
Don Gagne's avatar
Don Gagne committed
54
#include "QGCFileDialog.h"
Don Gagne's avatar
Don Gagne committed
55
#include "QGCMessageBox.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
    connect(ui.recolorButton, SIGNAL(clicked()), this, SLOT(recolor()));
    connect(ui.shortNameCheckBox, SIGNAL(clicked(bool)), this, SLOT(setShortNames(bool)));
109
    connect(ui.plotFilterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(filterCurves(const QString&)));
110
    new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this, SLOT(setPlotFilterLineEditFocus()));
111

112 113
    int labelRow = curvesWidgetLayout->rowCount();

114 115 116
    selectAllCheckBox = new QCheckBox("", this);
    connect(selectAllCheckBox, SIGNAL(clicked(bool)), this, SLOT(selectAllCurves(bool)));
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0, 1, 2);
117 118

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

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

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

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

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

pixhawk's avatar
pixhawk committed
140 141
    // Create the layout
    createLayout();
142

143
    // And make sure we're listening for future style changes
144
    connect(MainWindow::instance(), SIGNAL(styleChanged(MainWindow::QGC_MAINWINDOW_STYLE)), this, SLOT(recolor()));
145

LM's avatar
LM committed
146
    updateTimer->setInterval(updateInterval);
147
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(refresh()));
148
    connect(ui.uasSelectionBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectActiveSystem(int)));
149
    readSettings();
pixhawk's avatar
pixhawk committed
150 151
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    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);
    connect(timeScaleCmb, SIGNAL(currentIndexChanged(int)), this, SLOT(timeScaleChanged(int)));

290 291 292
    // Initialize the "Show units" checkbox. This is configured in the .ui file, so all
    // we do here is attach the clicked() signal.
    connect(ui.showUnitsCheckBox, SIGNAL(clicked()), this, SLOT(writeSettings()));
pixhawk's avatar
pixhawk committed
293

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

    // Connect notifications from the user interface to the plot
    connect(this, SIGNAL(curveRemoved(QString)), activePlot, SLOT(hideCurve(QString)));

    // Update scrollbar when plot window changes (via translator method setPlotWindowPosition()
301 302
//    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));
    connect(activePlot, SIGNAL(curveRemoved(QString)), this, SLOT(removeCurve(QString)));
303 304 305 306 307

    // Update plot when scrollbar is moved (via translator method setPlotWindowPosition()
    connect(this, SIGNAL(plotWindowPositionUpdated(quint64)), activePlot, SLOT(setWindowPosition(quint64)));

    // Set scaling
308 309 310
    connect(scalingLogButton, SIGNAL(toggled(bool)), this, SLOT(toggleLogarithmicScaling(bool)));
}

311 312 313 314 315
void LinechartWidget::timeScaleChanged(int index)
{
    activePlot->setPlotInterval(timeScaleCmb->itemData(index).toInt()*1000);
}

316 317 318 319 320 321
void LinechartWidget::toggleLogarithmicScaling(bool checked)
{
    if(checked)
        activePlot->setLogarithmicScaling();
    else
        activePlot->setLinearScaling();
pixhawk's avatar
pixhawk committed
322 323
}

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

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

        // Add int data
348 349
        if(!isDouble)
            intData.insert(curve+unit, variant.toInt());
350 351
    }

352 353 354 355 356
    if (lastTimestamp == 0 && usec != 0)
    {
        lastTimestamp = usec;
    } else if (usec != 0) {
        // Difference larger than 5 secs, enforce ground time
357
        if (((qint64)usec - (qint64)lastTimestamp) > 5000)
358 359 360 361 362 363
        {
            autoGroundTimeSet = true;
            if (activePlot) activePlot->groundTime();
        }
    }

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

374
            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
375 376 377 378
        }
    }
}

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

pixhawk's avatar
pixhawk committed
436 437 438 439

void LinechartWidget::startLogging()
{
    // Store reference to file
440 441
    // Append correct file ending if needed
    bool abort = false;
lm's avatar
lm committed
442 443

    // Check if any curve is enabled
444
    if (!activePlot->anyCurveVisible()) {
Don Gagne's avatar
Don Gagne committed
445
        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
446 447 448 449
        return;
    }

    // Let user select the log file name
450
    //QDate date(QDate::currentDate());
lm's avatar
lm committed
451
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
Don Gagne's avatar
Don Gagne committed
452
    QString fileName = QGCFileDialog::getSaveFileName(this, tr("Specify log file name"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), tr("Logfile (*.log);;"));
lm's avatar
lm committed
453

Lorenz Meier's avatar
Lorenz Meier committed
454
    while (!(fileName.endsWith(".log")) && !abort && fileName != "") {
Don Gagne's avatar
Don Gagne committed
455 456 457 458 459
        QMessageBox::StandardButton button = QGCMessageBox::critical(tr("Unsuitable file extension for logfile"),
                                                                     tr("Please choose .log as file extension. Click OK to change the file extension, cancel to not start logging."),
                                                                     QMessageBox::Ok | QMessageBox::Cancel,
                                                                     QMessageBox::Ok);
        if (button != QMessageBox::Ok) {
460 461 462
            abort = true;
            break;
        }
Don Gagne's avatar
Don Gagne committed
463
        fileName = QGCFileDialog::getSaveFileName(this, tr("Specify log file name"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), tr("Logfile (*.log);;"));
pixhawk's avatar
pixhawk committed
464
    }
465

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

468
    // Check if the user did not abort the file save dialog
469
    if (!abort && fileName != "") {
470
        logFile = new QFile(fileName);
Lorenz Meier's avatar
Lorenz Meier committed
471
        if (logFile->open(QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text)) {
472
            logging = true;
473 474
            logStartTime = 0;
            curvesWidget->setEnabled(false);
475 476 477 478 479
            logindex++;
            logButton->setText(tr("Stop logging"));
            disconnect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));
            connect(logButton, SIGNAL(clicked()), this, SLOT(stopLogging()));
        }
pixhawk's avatar
pixhawk committed
480 481 482 483 484 485
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
486
    curvesWidget->setEnabled(true);
487
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
488 489 490
        logFile->flush();
        logFile->close();
        // Postprocess log file
491
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
492
        connect(compressor, SIGNAL(finishedFile(QString)), this, SIGNAL(logfileWritten(QString)));
lm's avatar
lm committed
493
        connect(compressor, SIGNAL(logProcessingStatusChanged(QString)), MainWindow::instance(), SLOT(showStatusMessage(QString)));
494

Don Gagne's avatar
Don Gagne committed
495 496 497 498
        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);
499
        bool fill;
Don Gagne's avatar
Don Gagne committed
500
        if (button == QMessageBox::Yes)
501 502 503 504 505 506 507 508 509
        {
            fill = true;
        }
        else
        {
            fill = false;
        }

        compressor->startCompression(fill);
pixhawk's avatar
pixhawk committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    }
    logButton->setText(tr("Start logging"));
    disconnect(logButton, SIGNAL(clicked()), this, SLOT(stopLogging()));
    connect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));
}

/**
 * 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()
 **/
537
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
538
{
539
    LinechartPlot* plot = activePlot;
540
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
541 542 543
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
544
    QLabel* unitLabel;
pixhawk's avatar
pixhawk committed
545
    QLabel* mean;
546
    QLabel* variance;
pixhawk's avatar
pixhawk committed
547

548 549
    curveNames.insert(curve+unit, curve);

550 551
    int labelRow = curvesWidgetLayout->rowCount();

552
    // Checkbox
553
    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
554
    checkBox->setCheckable(true);
555
    checkBox->setObjectName(curve+unit);
556 557
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
558
    checkBoxes.insert(curve+unit, checkBox);
559
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
560

561
    // Icon
562
    QWidget* colorIcon = new QWidget(this);
563
    colorIcons.insert(curve+unit, colorIcon);
pixhawk's avatar
pixhawk committed
564 565
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);
566
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
567

568
    // Label
569
    label = new QLabel(this);
570
    label->setText(getCurveName(curve+unit, ui.shortNameCheckBox->isChecked()));
571
    curveNameLabels.insert(curve+unit, label);
572
    curvesWidgetLayout->addWidget(label, labelRow, 2);
573

pixhawk's avatar
pixhawk committed
574
    // Value
575
    value = new QLabel(this);
pixhawk's avatar
pixhawk committed
576
    value->setNum(0.00);
577
    value->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
578 579
    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));
580
    curveLabels->insert(curve+unit, value);
581
    curvesWidgetLayout->addWidget(value, labelRow, 3);
pixhawk's avatar
pixhawk committed
582

583 584 585 586 587
    // Unit
    unitLabel = new QLabel(this);
    unitLabel->setText(unit);
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
588
    curveUnits.insert(curve+unit, unitLabel);
589
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
590 591
    unitLabel->setVisible(ui.showUnitsCheckBox->isChecked());
    connect(ui.showUnitsCheckBox, SIGNAL(clicked(bool)), unitLabel, SLOT(setVisible(bool)));
592

pixhawk's avatar
pixhawk committed
593
    // Mean
594
    mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
595
    mean->setNum(0.00);
lm's avatar
lm committed
596
    mean->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
597 598
    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));
599 600
    curveMeans->insert(curve+unit, mean);
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
pixhawk's avatar
pixhawk committed
601

602 603 604 605 606
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
607

608
    // Variance
609
    variance = new QLabel(this);
610
    variance->setNum(0.00);
lm's avatar
lm committed
611
    variance->setStyleSheet(QString("QLabel {font-family:\"Courier\"; font-weight: bold;}"));
612 613
    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));
614 615
    curveVariances->insert(curve+unit, variance);
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
616

pixhawk's avatar
pixhawk committed
617 618 619 620 621 622 623 624 625 626 627
    /* 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

628 629 630 631

    // Load visibility settings
    // TODO

pixhawk's avatar
pixhawk committed
632
    // Connect actions
633
    connect(selectAllCheckBox, SIGNAL(clicked(bool)), checkBox, SLOT(setChecked(bool)));
pixhawk's avatar
pixhawk committed
634
    QObject::connect(checkBox, SIGNAL(clicked(bool)), this, SLOT(takeButtonClick(bool)));
635
    QObject::connect(this, SIGNAL(curveVisible(QString, bool)), plot, SLOT(setVisibleById(QString, bool)));
pixhawk's avatar
pixhawk committed
636 637 638

    // Set UI components to initial state
    checkBox->setChecked(false);
639
    plot->setVisibleById(curve+unit, false);
pixhawk's avatar
pixhawk committed
640 641 642 643 644 645 646 647
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
648
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
649
{
650
    Q_UNUSED(curve)
651 652 653 654 655 656 657 658 659 660 661 662 663 664

    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();
665 666 667 668 669 670 671 672
    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);
673
    widget->deleteLater();
674 675 676 677
    QCheckBox* checkbox;
    checkbox = checkBoxes.take(curve);
    curvesWidgetLayout->removeWidget(checkbox);
    checkbox->deleteLater();
678 679 680 681 682
//    intData->remove(curve);
}

void LinechartWidget::recolor()
{
683
    activePlot->styleChanged(MainWindow::instance()->getStyle());
684 685 686
    foreach (QString key, colorIcons.keys())
    {
        QWidget* colorIcon = colorIcons.value(key, 0);
687
        if (colorIcon && !colorIcon->styleSheet().isEmpty())
688
        {
689 690 691
            QString colorstyle;
            QColor color = activePlot->getColorForCurve(key);
            colorstyle = colorstyle.sprintf("QWidget { background-color: #%02X%02X%02X; }", color.red(), color.green(), color.blue());
692 693 694 695 696
            colorIcon->setStyleSheet(colorstyle);
        }
    }
}

697 698 699 700 701
void LinechartWidget::setPlotFilterLineEditFocus()
{
    ui.plotFilterLineEdit->setFocus(Qt::ShortcutFocusReason);
}

702 703
void LinechartWidget::filterCurve(const QString &key, bool match)
{
704 705 706 707 708 709 710 711 712 713
        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);
        }
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
}

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);
        foreach (QString key, colorIcons.keys())
        {
            if (stringMatcher.indexIn(key) < 0)
            {
                filterCurve(key, false);
            }
            else
            {
                filterCurve(key, true);
            }
        }
    }
    else
    {
        /* Show all Elements */
        foreach (QString key, colorIcons.keys())
        {
            filterCurve(key, true);
        }
    }
}

746
QString LinechartWidget::getCurveName(const QString& key, bool shortEnabled)
747
{
748
    if (shortEnabled)
749 750
    {
        QString name;
751 752
        QStringList parts = curveNames.value(key).split(".");
        if (parts.length() > 1)
753
        {
754 755 756 757 758 759
            name = parts.at(1);
        }
        else
        {
            name = parts.at(0);
        }
760

761
        const int sizeLimit = 20;
762

763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        // 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");
785
        }
786 787 788

        // Check if sub-part is still exceeding N chars
        if (name.length() > sizeLimit)
789
        {
790 791 792 793 794
            name.replace("a", "");
            name.replace("e", "");
            name.replace("i", "");
            name.replace("o", "");
            name.replace("u", "");
795
        }
796 797 798 799 800 801 802 803 804 805 806 807 808 809

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

void LinechartWidget::setShortNames(bool enable)
{
    foreach (QString key, curveNames.keys())
    {
        curveNameLabels.value(key)->setText(getCurveName(key, enable));
810
    }
811
}
pixhawk's avatar
pixhawk committed
812

813 814 815
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
816 817 818 819 820 821 822
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
823 824
}

825 826
void LinechartWidget::setActive(bool active)
{
827
    if (activePlot) {
828 829
        activePlot->setActive(active);
    }
830
    if (active) {
831
        updateTimer->start(updateInterval);
832
    } else {
833
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
834 835 836 837 838 839 840 841 842 843 844
    }
}

/**
 * @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
 **/
845 846
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
    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
 **/
892 893
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
894 895 896 897 898 899 900
    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
901
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
902 903 904 905 906 907
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
908
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
        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
 **/
924 925
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
926 927 928 929 930
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
931 932 933
 * 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
934 935 936
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
937 938
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
939 940 941

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

942 943
    if(button != NULL)
    {
944
        activePlot->setVisibleById(button->objectName(), checked);
945 946
        QWidget* colorIcon = colorIcons.value(button->objectName(), 0);
        if (colorIcon)
947
        {
948 949 950 951 952 953 954 955 956 957 958
            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
959
            {
960
                colorIcon->setStyleSheet("");
961 962
            }
        }
pixhawk's avatar
pixhawk committed
963 964 965 966 967 968 969 970 971 972
    }
}

/**
 * @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)
 **/
973 974
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
975 976 977 978 979 980
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}