LinechartWidget.cc 23.7 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 58 59
LinechartWidget::LinechartWidget(int systemid, QWidget *parent) : QWidget(parent),
sysid(systemid),
activePlot(NULL),
pixhawk's avatar
pixhawk committed
60
curvesLock(new QReadWriteLock()),
61
plotWindowLock(),
pixhawk's avatar
pixhawk committed
62 63 64 65 66 67
curveListIndex(0),
curveListCounter(0),
listedCurves(new QList<QString>()),
curveLabels(new QMap<QString, QLabel*>()),
curveMeans(new QMap<QString, QLabel*>()),
curveMedians(new QMap<QString, QLabel*>()),
68
curveVariances(new QMap<QString, QLabel*>()),
69
curveMenu(new QMenu(this)),
pixhawk's avatar
pixhawk committed
70 71
logFile(new QFile()),
logindex(1),
72 73
logging(false),
updateTimer(new QTimer())
pixhawk's avatar
pixhawk committed
74 75 76
{
    // Add elements defined in Qt Designer
    ui.setupUi(this);
77
    this->setMinimumSize(400, 250);
pixhawk's avatar
pixhawk committed
78 79 80 81

    // Add and customize curve list elements (left side)
    curvesWidget = new QWidget(ui.curveListWidget);
    ui.curveListWidget->setWidget(curvesWidget);
82
    curvesWidgetLayout = new QGridLayout(curvesWidget);
pixhawk's avatar
pixhawk committed
83 84
    curvesWidgetLayout->setMargin(2);
    curvesWidgetLayout->setSpacing(4);
85
    //curvesWidgetLayout->setSizeConstraint(QSizePolicy::Expanding);
86
    curvesWidgetLayout->setAlignment(Qt::AlignTop);
87 88 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);
//    horizontalLayout->setColumnStretch(median, 50);
    curvesWidgetLayout->setColumnStretch(5, 50);

pixhawk's avatar
pixhawk committed
96 97
    curvesWidget->setLayout(curvesWidgetLayout);

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

    //horizontalLayout->addWidget(checkBox);

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

    curvesWidgetLayout->addWidget(new QLabel("On"), labelRow, 0, 1, 2);

    label = new QLabel(this);
111
    label->setText("Name");
112
    curvesWidgetLayout->addWidget(label, labelRow, 2);
113 114

    // Value
115
    value = new QLabel(this);
116
    value->setText("Val");
117
    curvesWidgetLayout->addWidget(value, labelRow, 3);
118 119

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

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

pixhawk's avatar
pixhawk committed
129 130 131 132 133 134
    // Add and customize plot elements (right side)

    // Create the layout
    createLayout();
    
    // Add the last actions
135 136
    //connect(this, SIGNAL(plotWindowPositionUpdated(int)), scrollbar, SLOT(setValue(int)));
    //connect(scrollbar, SIGNAL(sliderMoved(int)), this, SLOT(setPlotWindowPosition(int)));
137

138
    updateTimer->setInterval(300);
139 140
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(refresh()));
    updateTimer->start();
pixhawk's avatar
pixhawk committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
}

LinechartWidget::~LinechartWidget() {
    stopLogging();
    delete listedCurves;
    listedCurves = NULL;
}

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
161 162 163
    activePlot = new LinechartPlot(this, sysid);
    // Activate automatic scrolling
    activePlot->setAutoScroll(true);
pixhawk's avatar
pixhawk committed
164 165 166 167 168

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

169
    layout->addWidget(activePlot, 0, 0, 1, 6);
pixhawk's avatar
pixhawk committed
170 171 172 173 174 175 176
    layout->setRowStretch(0, 10);
    layout->setRowStretch(1, 0);

    // Linear scaling button
    scalingLinearButton = createButton(this);
    scalingLinearButton->setDefaultAction(setScalingLinear);
    scalingLinearButton->setCheckable(true);
177 178
    scalingLinearButton->setToolTip(tr("Set linear scale for Y axis"));
    scalingLinearButton->setWhatsThis(tr("Set linear scale for Y axis"));
pixhawk's avatar
pixhawk committed
179 180 181 182 183 184 185
    layout->addWidget(scalingLinearButton, 1, 0);
    layout->setColumnStretch(0, 0);

    // Logarithmic scaling button
    scalingLogButton = createButton(this);
    scalingLogButton->setDefaultAction(setScalingLogarithmic);
    scalingLogButton->setCheckable(true);
186 187
    scalingLogButton->setToolTip(tr("Set logarithmic scale for Y axis"));
    scalingLogButton->setWhatsThis(tr("Set logarithmic scale for Y axis"));
pixhawk's avatar
pixhawk committed
188 189 190 191 192
    layout->addWidget(scalingLogButton, 1, 1);
    layout->setColumnStretch(1, 0);

    // Averaging spin box
    averageSpinBox = new QSpinBox(this);
193 194
    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
195
    averageSpinBox->setMinimum(2);
196 197
    averageSpinBox->setValue(200);
    setAverageWindow(200);
198
    averageSpinBox->setMaximum(9999);
pixhawk's avatar
pixhawk committed
199 200 201 202 203 204
    layout->addWidget(averageSpinBox, 1, 2);
    layout->setColumnStretch(2, 0);
    connect(averageSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setAverageWindow(int)));

    // Log Button
    logButton = new QToolButton(this);
205 206
    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
207 208 209 210 211
    logButton->setText(tr("Start Logging"));
    layout->addWidget(logButton, 1, 3);
    layout->setColumnStretch(3, 0);
    connect(logButton, SIGNAL(clicked()), this, SLOT(startLogging()));

212 213 214 215
    // Ground time button
    QToolButton* timeButton = new QToolButton(this);
    timeButton->setText(tr("Ground Time"));
    timeButton->setCheckable(true);
216 217
    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."));
218 219 220
    bool gTimeDefault = true;
    if (activePlot) activePlot->enforceGroundTime(gTimeDefault);
    timeButton->setChecked(gTimeDefault);
221 222 223 224
    layout->addWidget(timeButton, 1, 4);
    layout->setColumnStretch(4, 0);
    connect(timeButton, SIGNAL(clicked(bool)), activePlot, SLOT(enforceGroundTime(bool)));

pixhawk's avatar
pixhawk committed
225
    // Create the scroll bar
226 227 228 229
    //scrollbar = new QScrollBar(Qt::Horizontal, ui.diagramGroupBox);
    //scrollbar->setMinimum(MIN_TIME_SCROLLBAR_VALUE);
    //scrollbar->setMaximum(MAX_TIME_SCROLLBAR_VALUE);
    //scrollbar->setPageStep(PAGESTEP_TIME_SCROLLBAR_VALUE);
pixhawk's avatar
pixhawk committed
230
    // Set scrollbar to maximum and disable it
231 232
    //scrollbar->setValue(MIN_TIME_SCROLLBAR_VALUE);
    //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
233 234 235 236
    //    scrollbar->setFixedHeight(20);


    // Add scroll bar to layout and make sure it gets all available space
237
    //layout->addWidget(scrollbar, 1, 5);
238
    layout->setColumnStretch(5, 10);
pixhawk's avatar
pixhawk committed
239 240

    ui.diagramGroupBox->setLayout(layout);
241 242 243 244 245 246

    // Add actions
    averageSpinBox->setValue(activePlot->getAverageWindow());

    // Connect notifications from the user interface to the plot
    connect(this, SIGNAL(curveRemoved(QString)), activePlot, SLOT(hideCurve(QString)));
pixhawk's avatar
pixhawk committed
247 248
    //connect(this, SIGNAL(curveSet(QString, int)), activePlot, SLOT(showshowCurveCurve(QString, int)));
    // FIXME
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

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

    // Scrollbar

    // 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
265 266 267 268 269
}

void LinechartWidget::appendData(int uasId, QString curve, double value, quint64 usec)
{
    // Order matters here, first append to plot, then update curve list
270 271
    activePlot->appendData(curve, usec, value);
    // Store data
pixhawk's avatar
pixhawk committed
272 273 274 275
    QLabel* label = curveLabels->value(curve, NULL);
    // Make sure the curve will be created if it does not yet exist
    if(!label)
    {
276
        addCurve(curve);
pixhawk's avatar
pixhawk committed
277 278 279 280 281
    }

    // Log data
    if (logging)
    {
282
        if (activePlot->isVisible(curve))
pixhawk's avatar
pixhawk committed
283
        {
lm's avatar
lm committed
284 285 286 287 288 289 290 291 292 293 294 295
            quint64 time = 0;
            // Adjust time
            if (activePlot->groundTime())
            {
                time = QGC::groundTimeUsecs() - logStartTime;
            }
            else
            {
                time = usec - logStartTime;
            }

            logFile->write(QString(QString::number(time) + "\t" + QString::number(uasId) + "\t" + curve + "\t" + QString::number(value) + "\n").toLatin1());
pixhawk's avatar
pixhawk committed
296 297 298 299 300
            logFile->flush();
        }
    }
}

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
void LinechartWidget::refresh()
{
    QString str;

    QMap<QString, QLabel*>::iterator i;
    for (i = curveLabels->begin(); i != curveLabels->end(); ++i)
    {
        str.sprintf("%+.2f", activePlot->getCurrentValue(i.key()));
        // Value
        i.value()->setText(str);
    }
    // Mean
    QMap<QString, QLabel*>::iterator j;
    for (j = curveMeans->begin(); j != curveMeans->end(); ++j)
    {
        str.sprintf("%+.2f", activePlot->getMean(j.key()));
        j.value()->setText(str);
    }
319 320 321 322 323 324 325
//    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);
//    }
326 327 328 329
    QMap<QString, QLabel*>::iterator l;
    for (l = curveVariances->begin(); l != curveVariances->end(); ++l)
    {
      // Variance
330
       str.sprintf("%.2e", activePlot->getVariance(l.key()));
331 332
      l.value()->setText(str);
   }
333 334
}

pixhawk's avatar
pixhawk committed
335 336 337 338

void LinechartWidget::startLogging()
{
    // Store reference to file
339 340
    // Append correct file ending if needed
    bool abort = false;
lm's avatar
lm committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

    // Check if any curve is enabled
    if (!activePlot->anyCurveVisible())
    {
        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
358
    QString fileName = QFileDialog::getSaveFileName(this, tr("Specify log file name"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation), tr("Logfile (*.csv *.txt);;"));
lm's avatar
lm committed
359 360 361 362 363 364 365 366

    if (!fileName.contains("."))
    {
        // .csv is default extension
        fileName.append(".csv");
    }

    while (!(fileName.endsWith(".txt") || fileName.endsWith(".csv")) && !abort)
pixhawk's avatar
pixhawk committed
367
    {
368 369 370 371 372 373 374 375 376 377 378 379 380
        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);
        if(msgBox.exec() == QMessageBox::Cancel)
        {
            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
381
    }
382 383 384

    // Check if the user did not abort the file save dialog
    if (!abort && fileName != "")
pixhawk's avatar
pixhawk committed
385
    {
386 387 388 389
        logFile = new QFile(fileName);
        if (logFile->open(QIODevice::WriteOnly | QIODevice::Text))
        {
            logging = true;
lm's avatar
lm committed
390
            logStartTime = QGC::groundTimeUsecs();
391 392 393 394 395
            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
396 397 398 399 400 401 402 403 404 405 406
    }
}

void LinechartWidget::stopLogging()
{
    logging = false;
    if (logFile->isOpen())
    {
        logFile->flush();
        logFile->close();
        // Postprocess log file
407
        compressor = new LogCompressor(logFile->fileName(), logFile->fileName());
408
        connect(compressor, SIGNAL(finishedFile(QString)), this, SIGNAL(logfileWritten(QString)));
lm's avatar
lm committed
409 410
        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.");
411
        compressor->startCompression();
pixhawk's avatar
pixhawk committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    }
    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()
 **/
441
void LinechartWidget::addCurve(QString curve)
pixhawk's avatar
pixhawk committed
442
{
443
    createCurveItem(curve);
pixhawk's avatar
pixhawk committed
444 445
}

446
void LinechartWidget::createCurveItem(QString curve)
pixhawk's avatar
pixhawk committed
447
{
448
    LinechartPlot* plot = activePlot;
449
//    QHBoxLayout *horizontalLayout;
pixhawk's avatar
pixhawk committed
450 451 452 453
    QCheckBox *checkBox;
    QLabel* label;
    QLabel* value;
    QLabel* mean;
454
    QLabel* variance;
pixhawk's avatar
pixhawk committed
455

456 457 458
    int labelRow = curvesWidgetLayout->rowCount();

    checkBox = new QCheckBox(this);
pixhawk's avatar
pixhawk committed
459 460
    checkBox->setCheckable(true);
    checkBox->setObjectName(curve);
461 462
    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
463

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

466
    QWidget* colorIcon = new QWidget(this);
pixhawk's avatar
pixhawk committed
467 468 469
    colorIcon->setMinimumSize(QSize(5, 14));
    colorIcon->setMaximumSize(4, 14);

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

472 473
    label = new QLabel(this);
    curvesWidgetLayout->addWidget(label, labelRow, 2);
pixhawk's avatar
pixhawk committed
474 475 476 477 478 479 480 481 482 483 484 485

    //checkBox->setText(QString());
    label->setText(curve);
    QColor color = plot->getColorForCurve(curve);
    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
486
    value = new QLabel(this);
pixhawk's avatar
pixhawk committed
487
    value->setNum(0.00);
488 489
    value->setToolTip(tr("Current value of ") + curve);
    value->setWhatsThis(tr("Current value of ") + curve);
pixhawk's avatar
pixhawk committed
490
    curveLabels->insert(curve, value);
491
    curvesWidgetLayout->addWidget(value, labelRow, 3);
pixhawk's avatar
pixhawk committed
492 493

    // Mean
494
    mean = new QLabel(this);
pixhawk's avatar
pixhawk committed
495
    mean->setNum(0.00);
496 497
    mean->setToolTip(tr("Arithmetic mean of ") + curve);
    mean->setWhatsThis(tr("Arithmetic mean of ") + curve);
pixhawk's avatar
pixhawk committed
498
    curveMeans->insert(curve, mean);
499
    curvesWidgetLayout->addWidget(mean, labelRow, 4);
pixhawk's avatar
pixhawk committed
500

501 502 503 504 505
//    // Median
//    median = new QLabel(form);
//    value->setNum(0.00);
//    curveMedians->insert(curve, median);
//    horizontalLayout->addWidget(median);
pixhawk's avatar
pixhawk committed
506

507
    // Variance
508
    variance = new QLabel(this);
509
    variance->setNum(0.00);
510 511
    variance->setToolTip(tr("Variance of ") + curve);
    variance->setWhatsThis(tr("Variance of ") + curve);
512
    curveVariances->insert(curve, variance);
513
    curvesWidgetLayout->addWidget(variance, labelRow, 5);
514

pixhawk's avatar
pixhawk committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    /* 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

    // Connect actions
    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);
    plot->setVisible(curve, false);
}

/**
 * @brief Remove the curve from the curve list.
 *
 * @param curve The curve to remove
 * @see addCurve()
 **/
541
void LinechartWidget::removeCurve(QString curve)
pixhawk's avatar
pixhawk committed
542
{
543
    Q_UNUSED(curve)
pixhawk's avatar
pixhawk committed
544
    //TODO @todo Ensure that the button for a curve gets deleted when the original curve is deleted
545
    // Remove name
546
    }
pixhawk's avatar
pixhawk committed
547

548 549 550
void LinechartWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
551 552 553 554 555 556 557
    setActive(true);
}

void LinechartWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    setActive(false);
558 559
}

560 561 562 563 564 565
void LinechartWidget::setActive(bool active)
{
    if (activePlot)
    {
        activePlot->setActive(active);
    }
566
    if (active)
pixhawk's avatar
pixhawk committed
567
    {
568 569 570 571 572
        updateTimer->start();
    }
    else
    {
        updateTimer->stop();
pixhawk's avatar
pixhawk committed
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    }
}

/**
 * @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
 **/
void LinechartWidget::setPlotWindowPosition(int scrollBarValue) {
    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
 **/
void LinechartWidget::setPlotWindowPosition(quint64 position) {
    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
638
        //scrollbar->setDisabled(false);
pixhawk's avatar
pixhawk committed
639 640 641 642 643 644
        quint64 scrollInterval = position - activePlot->getMinTime() - activePlot->getPlotInterval();



        pos = (static_cast<double>(scrollInterval) / (activePlot->getDataInterval() - activePlot->getPlotInterval()));
    } else {
645
        //scrollbar->setDisabled(true);
pixhawk's avatar
pixhawk committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
        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
 **/
661 662
void LinechartWidget::setPlotInterval(quint64 interval)
{
pixhawk's avatar
pixhawk committed
663 664 665 666 667 668 669 670 671 672
    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
 **/
673 674
void LinechartWidget::takeButtonClick(bool checked)
{
pixhawk's avatar
pixhawk committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690

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

    if(button != NULL)
    {
        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)
 **/
691 692
QToolButton* LinechartWidget::createButton(QWidget* parent)
{
pixhawk's avatar
pixhawk committed
693 694 695 696 697 698
    QToolButton* button = new QToolButton(parent);
    button->setMinimumSize(QSize(20, 20));
    button->setMaximumSize(60, 20);
    button->setGeometry(button->x(), button->y(), 20, 20);
    return button;
}