LinechartWidget.cc 28.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 29 30 31 32 33 34 35 36 37
/*=====================================================================

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>
 *
 */

#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 45
#include <QScrollBar>
#include <QLabel>
#include <QMenu>
#include <QSpinBox>
#include <QColor>
#include <QPalette>
#include <QFileDialog>
46 47
#include <QDesktopServices>
#include <QMessageBox>
pixhawk's avatar
pixhawk committed
48 49 50 51

#include "LinechartWidget.h"
#include "LinechartPlot.h"
#include "LogCompressor.h"
lm's avatar
lm committed
52
#include "MainWindow.h"
lm's avatar
lm committed
53
#include "QGC.h"
pixhawk's avatar
pixhawk committed
54 55 56
#include "MG.h"


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

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

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

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

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

    //horizontalLayout->addWidget(checkBox);

108 109
    int labelRow = curvesWidgetLayout->rowCount();

110 111 112
    selectAllCheckBox = new QCheckBox("", this);
    connect(selectAllCheckBox, SIGNAL(clicked(bool)), this, SLOT(selectAllCurves(bool)));
    curvesWidgetLayout->addWidget(selectAllCheckBox, labelRow, 0, 1, 2);
113 114

    label = new QLabel(this);
115
    label->setText("Name");
116
    curvesWidgetLayout->addWidget(label, labelRow, 2);
117 118

    // Value
119
    value = new QLabel(this);
120
    value->setText("Val");
121
    curvesWidgetLayout->addWidget(value, labelRow, 3);
122

123
    // Unit
124
    //curvesWidgetLayout->addWidget(new QLabel(tr("Unit")), labelRow, 4);
125

126
    // Mean
127
    mean = new QLabel(this);
128
    mean->setText("Mean");
129
    curvesWidgetLayout->addWidget(mean, labelRow, 5);
130 131

    // Variance
132
    variance = new QLabel(this);
133
    variance->setText("Variance");
134
    curvesWidgetLayout->addWidget(variance, labelRow, 6);
135

pixhawk's avatar
pixhawk committed
136 137 138 139
    // Add and customize plot elements (right side)

    // Create the layout
    createLayout();
140

pixhawk's avatar
pixhawk committed
141
    // Add the last actions
142 143
    //connect(this, SIGNAL(plotWindowPositionUpdated(int)), scrollbar, SLOT(setValue(int)));
    //connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(setPlotWindowPosition(int)));
144

145
    updateTimer->setInterval(300);
146
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(refresh()));
147
    readSettings();
pixhawk's avatar
pixhawk committed
148 149
}

150 151 152
LinechartWidget::~LinechartWidget()
{
    writeSettings();
pixhawk's avatar
pixhawk committed
153 154 155 156 157
    stopLogging();
    delete listedCurves;
    listedCurves = NULL;
}

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

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
void LinechartWidget::writeSettings()
{
    QSettings settings;
    settings.beginGroup("LINECHART");
    if (timeButton) settings.setValue("ENFORCE_GROUNDTIME", timeButton->isChecked());
    if (unitsCheckBox) settings.setValue("SHOW_UNITS", unitsCheckBox->isChecked());
    settings.endGroup();
    settings.sync();
}

void LinechartWidget::readSettings()
{
    QSettings settings;
    settings.sync();
    settings.beginGroup("LINECHART");
181
    if (activePlot) {
182 183 184 185 186 187 188
        timeButton->setChecked(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
        activePlot->enforceGroundTime(settings.value("ENFORCE_GROUNDTIME", timeButton->isChecked()).toBool());
    }
    if (unitsCheckBox) unitsCheckBox->setChecked(settings.value("SHOW_UNITS").toBool());
    settings.endGroup();
}

pixhawk's avatar
pixhawk committed
189 190 191 192 193 194 195 196 197 198 199 200
void LinechartWidget::createLayout()
{
    // Create actions
    createActions();

    // Setup the plot group box area layout
    QGridLayout* layout = new QGridLayout(ui.diagramGroupBox);
    mainLayout = layout;
    layout->setSpacing(4);
    layout->setMargin(2);

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

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

209
    layout->addWidget(activePlot, 0, 0, 1, 6);
pixhawk's avatar
pixhawk committed
210
    layout->setRowStretch(0, 10);
lm's avatar
lm committed
211
    layout->setRowStretch(1, 1);
pixhawk's avatar
pixhawk committed
212 213 214 215 216

    // Linear scaling button
    scalingLinearButton = createButton(this);
    scalingLinearButton->setDefaultAction(setScalingLinear);
    scalingLinearButton->setCheckable(true);
217 218
    scalingLinearButton->setToolTip(tr("Set linear scale for Y axis"));
    scalingLinearButton->setWhatsThis(tr("Set linear scale for Y axis"));
pixhawk's avatar
pixhawk committed
219 220 221 222 223 224 225
    layout->addWidget(scalingLinearButton, 1, 0);
    layout->setColumnStretch(0, 0);

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
    scalingLogButton->setDefaultAction(setScalingLogarithmic);
    scalingLogButton->setCheckable(true);
226 227
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
pixhawk's avatar
pixhawk committed
228 229 230 231 232
    layout->addWidget(scalingLogButton, 1, 1);
    layout->setColumnStretch(1, 0);

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
233 234
    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
235
    averageSpinBox->setMinimum(2);
236 237
    averageSpinBox->setValue(200);
    setAverageWindow(200);
238
    averageSpinBox->setMaximum(9999);
pixhawk's avatar
pixhawk committed
239 240 241 242 243 244
    layout->addWidget(averageSpinBox, 1, 2);
    layout->setColumnStretch(2, 0);
    connect(averageSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAverageWindow(int)));

    // Log Button
    logButton = new QToolButton(this);
245 246
    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
247 248 249 250 251
    logButton->setText(tr("Start Logging"));
    layout->addWidget(logButton, 1, 3);
    layout->setColumnStretch(3, 0);
    connect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));

252
    // Ground time button
253
    timeButton = new QCheckBox(this);
254
    timeButton->setText(tr("Ground Time"));
255 256
    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."));
257 258 259
    bool gTimeDefault = true;
    if (activePlot) activePlot->enforceGroundTime(gTimeDefault);
    timeButton->setChecked(gTimeDefault);
260 261 262
    layout->addWidget(timeButton, 1, 4);
    layout->setColumnStretch(4, 0);
    connect(timeButton, SIGNAL(clicked(bool)), activePlot, SLOT(enforceGroundTime(bool)));
263
    connect(timeButton, SIGNAL(clicked()), this, SLOT(writeSettings()));
264

265 266 267 268 269 270
    unitsCheckBox = new QCheckBox(this);
    unitsCheckBox->setText(tr("Show units"));
    unitsCheckBox->setChecked(true);
    unitsCheckBox->setToolTip(tr("Enable unit display in curve list"));
    unitsCheckBox->setWhatsThis(tr("Enable unit display in curve list"));
    layout->addWidget(unitsCheckBox, 1, 5);
271
    connect(unitsCheckBox, SIGNAL(clicked()), this, SLOT(writeSettings()));
pixhawk's avatar
pixhawk committed
272 273

    ui.diagramGroupBox->setLayout(layout);
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

    // 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()
    connect(activePlot, SIGNAL(windowPositionChanged(quint64)), this, SLOT(setPlotWindowPosition(quint64)));

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

    // Set scaling
    connect(scalingLinearButton, SIGNAL(clicked()), activePlot, SLOT(setLinearScaling()));
    connect(scalingLogButton, SIGNAL(clicked()), activePlot, SLOT(setLogarithmicScaling()));
pixhawk's avatar
pixhawk committed
290 291 292
}

void LinechartWidget::appendData(int uasId, QString curve, double value, quint64 usec)
293 294
{
    static const QString unit("-");
295
    if (isVisible()) {
296 297 298 299 300
        // 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
301
        if(!label) {
302 303 304 305 306
            addCurve(curve, unit);
        }
    }

    // Log data
307 308
    if (logging) {
        if (activePlot->isVisible(curve+unit)) {
309 310 311 312 313 314 315 316 317 318 319 320 321
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
            logFile->flush();
        }
    }
}


void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, double value, quint64 usec)
{
322
    if (isVisible()) {
323 324 325 326 327
        // 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
328
        if(!label) {
329
            //qDebug() << "ADDING CURVE IN APPENDDATE DOUBLE";
330 331 332 333 334
            addCurve(curve, unit);
        }
    }

    // Log data
335 336
    if (logging) {
        if (activePlot->isVisible(curve+unit)) {
337 338 339 340 341 342 343 344 345 346 347
            if (logStartTime == 0) logStartTime = usec;
            qint64 time = usec - logStartTime;
            if (time < 0) time = 0;

            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
            logFile->flush();
        }
    }
}

void LinechartWidget::appendData(int uasId, const QString& curve, const QString& unit, int value, quint64 usec)
pixhawk's avatar
pixhawk committed
348
{
349
    if (isVisible()) {
350
        // Order matters here, first append to plot, then update curve list
351
        activePlot->appendData(curve+unit, usec, value);
352
        // Store data
353
        QLabel* label = curveLabels->value(curve+unit, NULL);
354
        // Make sure the curve will be created if it does not yet exist
355
        if(!label) {
lm's avatar
lm committed
356
            intData.insert(curve+unit, 0);
357
            addCurve(curve, unit);
358
        }
359 360 361

        // Add int data
        intData.insert(curve+unit, value);
pixhawk's avatar
pixhawk committed
362 363 364
    }

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

            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
pixhawk's avatar
pixhawk committed
372 373 374 375 376
            logFile->flush();
        }
    }
}

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

pixhawk's avatar
pixhawk committed
432 433 434 435

void LinechartWidget::startLogging()
{
    // Store reference to file
436 437
    // Append correct file ending if needed
    bool abort = false;
lm's avatar
lm committed
438 439

    // Check if any curve is enabled
440
    if (!activePlot->anyCurveVisible()) {
lm's avatar
lm committed
441 442 443 444 445 446 447 448 449 450 451 452 453
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText("No curves selected for logging.");
        msgBox.setInformativeText("Please check all curves you want to log. Currently no data would be logged, aborting the logging.");
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.exec();
        return;
    }

    // Let user select the log file name
    QDate date(QDate::currentDate());
    // QString("./pixhawk-log-" + date.toString("yyyy-MM-dd") + "-" + QString::number(logindex) + ".log")
lm's avatar
lm committed
454
    QString fileName = QFileDialog::getSaveFileName(this, tr("Specify log file name"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation), tr("Logfile (*.csv *.txt);;"));
lm's avatar
lm committed
455

456
    if (!fileName.contains(".")) {
lm's avatar
lm committed
457 458 459 460
        // .csv is default extension
        fileName.append(".csv");
    }

461
    while (!(fileName.endsWith(".txt") || fileName.endsWith(".csv")) && !abort && fileName != "") {
462 463 464 465 466 467
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText("Unsuitable file extension for logfile");
        msgBox.setInformativeText("Please choose .txt or .csv as file extension. Click OK to change the file extension, cancel to not start logging.");
        msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Ok);
468
        if(msgBox.exec() == QMessageBox::Cancel) {
469 470 471 472 473
            abort = true;
            break;
        }
        fileName = QFileDialog::getSaveFileName(this, tr("Specify log file name"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation), tr("Logfile (*.txt, *.csv);;"));

pixhawk's avatar
pixhawk committed
474
    }
475 476

    // Check if the user did not abort the file save dialog
477
    if (!abort && fileName != "") {
478
        logFile = new QFile(fileName);
479
        if (logFile->open(QIODevice::WriteOnly | QIODevice::Text)) {
480
            logging = true;
481 482
            logStartTime = 0;
            curvesWidget->setEnabled(false);
483 484 485 486 487
            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
488 489 490 491 492 493
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
494
    curvesWidget->setEnabled(true);
495
    if (logFile->isOpen()) {
pixhawk's avatar
pixhawk committed
496 497 498
        logFile->flush();
        logFile->close();
        // Postprocess log file
499
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
500
        connect(compressor, SIGNAL(finishedFile(QString)), this, SIGNAL(logfileWritten(QString)));
lm's avatar
lm committed
501 502
        connect(compressor, SIGNAL(logProcessingStatusChanged(QString)), MainWindow::instance(), SLOT(showStatusMessage(QString)));
        MainWindow::instance()->showInfoMessage("Logging ended", "QGroundControl is now compressing the logfile in a consistent CVS file. This may take a while, you can continue to use QGroundControl. Status updates appear at the bottom of the window.");
503
        compressor->startCompression();
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 527 528 529 530 531 532
    }
    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()
{
    setScalingLogarithmic = new QAction("LOG", this);
    setScalingLinear = new QAction("LIN", this);
}

/**
 * @brief Add a curve to the curve list
 *
 * @param curve The id-string of the curve
 * @see removeCurve()
 **/
533
void LinechartWidget::addCurve(const QString& curve, const QString& unit)
pixhawk's avatar
pixhawk committed
534
{
535
    LinechartPlot* plot = activePlot;
536
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
537 538 539
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
540
    QLabel* unitLabel;
pixhawk's avatar
pixhawk committed
541
    QLabel* mean;
542
    QLabel* variance;
pixhawk's avatar
pixhawk committed
543

544 545 546
    int labelRow = curvesWidgetLayout->rowCount();

    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
547
    checkBox->setCheckable(true);
548
    checkBox->setObjectName(curve+unit);
549 550
    checkBox->setToolTip(tr("Enable the curve in the graph window"));
    checkBox->setWhatsThis(tr("Enable the curve in the graph window"));
pixhawk's avatar
pixhawk committed
551

552
    curvesWidgetLayout->addWidget(checkBox, labelRow, 0);
pixhawk's avatar
pixhawk committed
553

554
    QWidget* colorIcon = new QWidget(this);
pixhawk's avatar
pixhawk committed
555 556 557
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);

558
    curvesWidgetLayout->addWidget(colorIcon, labelRow, 1);
pixhawk's avatar
pixhawk committed
559

560 561
    label = new QLabel(this);
    curvesWidgetLayout->addWidget(label, labelRow, 2);
pixhawk's avatar
pixhawk committed
562 563 564

    //checkBox->setText(QString());
    label->setText(curve);
565
    QColor color = plot->getColorForCurve(curve+unit);
pixhawk's avatar
pixhawk committed
566 567 568 569 570 571 572 573
    if(color.isValid()) {
        QString colorstyle;
        colorstyle = colorstyle.sprintf("QWidget { background-color: #%X%X%X; }", color.red(), color.green(), color.blue());
        colorIcon->setStyleSheet(colorstyle);
        colorIcon->setAutoFillBackground(true);
    }

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

582 583 584 585
    // Unit
    unitLabel = new QLabel(this);
    unitLabel->setText(unit);
    unitLabel->setStyleSheet(QString("QLabel {color: %1;}").arg("#AAAAAA"));
586
    //qDebug() << "UNIT" << unit;
587 588 589
    unitLabel->setToolTip(tr("Unit of ") + curve);
    unitLabel->setWhatsThis(tr("Unit of ") + curve);
    curvesWidgetLayout->addWidget(unitLabel, labelRow, 4);
590
    unitLabel->setVisible(unitsCheckBox->isChecked());
591
    connect(unitsCheckBox, 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 635 636 637 638
    QObject::connect(checkBox, SIGNAL(clicked(bool)), this, SLOT(takeButtonClick(bool)));
    QObject::connect(this, SIGNAL(curveVisible(QString, bool)), plot, SLOT(setVisible(QString, bool)));

    // Set UI components to initial state
    checkBox->setChecked(false);
639
    plot->setVisible(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)
pixhawk's avatar
pixhawk committed
651
    //TODO @todo Ensure that the button for a curve gets deleted when the original curve is deleted
652
    // Remove name
653
}
pixhawk's avatar
pixhawk committed
654

655 656 657
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
658 659 660 661 662 663 664
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
665 666
}

667 668
void LinechartWidget::setActive(bool active)
{
669
    if (activePlot) {
670 671
        activePlot->setActive(active);
    }
672
    if (active) {
673
        updateTimer->start(updateInterval);
674
    } else {
675
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
676 677 678 679 680 681 682 683 684 685 686
    }
}

/**
 * @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
 **/
687 688
void LinechartWidget::setPlotWindowPosition(int scrollBarValue)
{
pixhawk's avatar
pixhawk committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
    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
 **/
734 735
void LinechartWidget::setPlotWindowPosition(quint64 position)
{
pixhawk's avatar
pixhawk committed
736 737 738 739 740 741 742
    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
743
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
744 745 746 747 748 749
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
750
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
        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
 **/
766 767
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
768 769 770 771 772 773 774 775 776 777
    activePlot->setPlotInterval(interval);
}

/**
 * @brief Take the click of a curve activation / deactivation button.
 * This method allows to map a button to a plot curve.The text of the
 * button must equal the curve name to activate / deactivate.
 *
 * @param checked The visibility of the curve: true to display the curve, false otherwise
 **/
778 779
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
780 781 782

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

783
    if(button != NULL) {
pixhawk's avatar
pixhawk committed
784 785 786 787 788 789 790 791 792 793 794
        activePlot->setVisible(button->objectName(), checked);
    }
}

/**
 * @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)
 **/
795 796
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
797 798 799 800 801 802
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}