ksignalplotter.cpp 38.2 KB
Newer Older
1
/*
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 Copyright (c) 2006 - 2009 John Tapsell <tapsell@kde.org>

 This program 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 2 of
 the License or (at your option) version 3 or any later version
 accepted by the membership of KDE e.V. (or its successor approved
 by the membership of KDE e.V.), which shall act as a proxy 
 defined in Section 14 of version 3 of the license.

 This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
19 20 21

*/

22 23 24 25 26 27 28
#ifdef GRAPHICS_SIGNAL_PLOTTER
#define KSignalPlotter KGraphicsSignalPlotter
#define KSignalPlotterPrivate KGraphicsSignalPlotterPrivate
#include "kgraphicssignalplotter.h"
#else
#undef KSignalPlotter
#undef KSignalPlotterPrivate
29
#include "ksignalplotter.h"
30 31
#endif

32
#include "ksignalplotter_p.h"
33
#include "ksignalplotter_debug.h"
34

35 36 37 38
#include <QPainter>
#include <QPixmap>
#include <QPainterPath>
#include <QPaintEvent>
39
#include <QEvent>
Hrvoje Senjan's avatar
Hrvoje Senjan committed
40
#include <QDebug>
41 42

#ifdef GRAPHICS_SIGNAL_PLOTTER
43 44
#include <QGraphicsSceneResizeEvent>
#include <QStyleOptionGraphicsItem>
45
#endif
46

47
#include <kiconloader.h>
48
#include <cmath>
49 50 51
#include <limits>

#ifdef SVG_SUPPORT
52
#include <Plasma/Svg>
53
#include <Plasma/Theme>
54 55 56 57
#endif


#define VERTICAL_LINE_OFFSET 1
Yuri Chornoivan's avatar
Yuri Chornoivan committed
58
//Never store less 1000 samples if not visible.  This is kinda arbitrary
59 60
#define NUM_SAMPLES_WHEN_INVISIBLE ((uint)1000)

61 62 63 64
#ifdef GRAPHICS_SIGNAL_PLOTTER
KGraphicsSignalPlotter::KGraphicsSignalPlotter( QGraphicsItem *parent)
  : QGraphicsWidget(parent), d(new KGraphicsSignalPlotterPrivate(this))
#else
65
KSignalPlotter::KSignalPlotter( QWidget *parent)
66 67
  : QWidget(parent), d(new KSignalPlotterPrivate(this))
#endif
68
{
69
    qRegisterMetaType<KLocalizedString>("KLocalizedString");
70 71
    // Anything smaller than this does not make sense.
    setMinimumSize( KIconLoader::SizeSmall, KIconLoader::SizeSmall);
72 73 74
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    sizePolicy.setHeightForWidth(false);
    setSizePolicy( sizePolicy );
75

76 77
#ifdef GRAPHICS_SIGNAL_PLOTTER
    setFlag(QGraphicsItem::ItemClipsToShape);
78
#endif
79
}
80

81 82
KSignalPlotter::~KSignalPlotter()
{
Laurent Montel's avatar
Laurent Montel committed
83
    delete d;
84 85 86 87 88 89 90 91 92 93 94 95 96
}

KLocalizedString KSignalPlotter::unit() const {
    return d->mUnit;
}
void KSignalPlotter::setUnit(const KLocalizedString &unit) {
    d->mUnit = unit;
}

void KSignalPlotter::addBeam( const QColor &color )
{
    //When we add a new beam, go back and set the data for this beam to NaN for all the other times, to pad it out.
    //This is because it makes it easier for moveSensors
97
    for(QList< QList<qreal> >::Iterator it = d->mBeamData.begin(), total = d->mBeamData.end(); it != total; ++it) {
98
        (*it).append( std::numeric_limits<qreal>::quiet_NaN() );
99 100
    }
    d->mBeamColors.append(color);
John Tapsell's avatar
John Tapsell committed
101
    d->mBeamColorsLight.append(color.lighter());
102 103 104 105 106 107 108 109
}

QColor KSignalPlotter::beamColor( int index ) const {
    return d->mBeamColors[ index ];
}

void KSignalPlotter::setBeamColor( int index, const QColor &color ) {
    if(!color.isValid()) {
110
        qCDebug(LIBKSYSGUARD_KSIGNALPLOTTER) << "Invalid color";
111 112 113
        return;
    }
    if( index >= d->mBeamColors.count() ) {
114
        qCDebug(LIBKSYSGUARD_KSIGNALPLOTTER) << "Invalid index" << index;
115 116
        return;
    }
John Tapsell's avatar
John Tapsell committed
117
    Q_ASSERT(d->mBeamColors.count() == d->mBeamColorsLight.count());
118 119

    d->mBeamColors[ index ] = color;
120
    d->mBeamColorsLight[ index ] = color.lighter();
121 122 123 124 125 126
}

int KSignalPlotter::numBeams() const {
    return d->mBeamColors.count();
}

127
void KSignalPlotter::addSample( const QList<qreal>& sampleBuf )
128 129
{
    d->addSample(sampleBuf);
130 131 132
#ifdef USE_SEPERATE_WIDGET
    d->mGraphWidget->update();
#else
133
    update(d->mPlottingArea);
134
#endif
135 136 137
}
void KSignalPlotter::reorderBeams( const QList<int>& newOrder )
{
138
    d->reorderBeams(newOrder);
139 140
}

141
void KSignalPlotter::changeRange( qreal min, qreal max )
142 143 144 145 146 147 148 149 150 151
{
    if( min == d->mUserMinValue && max == d->mUserMaxValue ) return;
    d->mUserMinValue = min;
    d->mUserMaxValue = max;
    d->calculateNiceRange();
}

void KSignalPlotter::removeBeam( int index )
{
    if(index >= d->mBeamColors.size()) return;
John Tapsell's avatar
John Tapsell committed
152
    if(index >= d->mBeamColorsLight.size()) return;
153
    d->mBeamColors.removeAt( index );
John Tapsell's avatar
John Tapsell committed
154
    d->mBeamColorsLight.removeAt(index);
155

156
    QList< QList<qreal> >::Iterator i;
157 158 159 160 161 162 163 164
    for(i = d->mBeamData.begin(); i != d->mBeamData.end(); ++i) {
        if( (*i).size() >= index)
            (*i).removeAt(index);
    }
    if(d->mUseAutoRange)
        d->rescale();
}

165
void KSignalPlotter::setScaleDownBy( qreal value )
166 167 168 169 170 171 172
{
    if(d->mScaleDownBy == value) return;
    d->mScaleDownBy = value;
    d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
    d->calculateNiceRange();
    update();
}
173
qreal KSignalPlotter::scaleDownBy() const
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
{
    return d->mScaleDownBy;
}

void KSignalPlotter::setUseAutoRange( bool value )
{
    d->mUseAutoRange = value;
    d->calculateNiceRange();
    //this change will be detected in paint and the image cache regenerated
}

bool KSignalPlotter::useAutoRange() const
{
    return d->mUseAutoRange;
}

190
void KSignalPlotter::setMinimumValue( qreal min )
191 192 193 194
{
    if(min == d->mUserMinValue) return;
    d->mUserMinValue = min;
    d->calculateNiceRange();
195
    update();
196 197 198
    //this change will be detected in paint and the image cache regenerated
}

199
qreal KSignalPlotter::minimumValue() const
200 201 202 203
{
    return d->mUserMinValue;
}

204
void KSignalPlotter::setMaximumValue( qreal max )
205 206 207 208
{
    if(max == d->mUserMaxValue) return;
    d->mUserMaxValue = max;
    d->calculateNiceRange();
209
    update();
210 211 212
    //this change will be detected in paint and the image cache regenerated
}

213
qreal KSignalPlotter::maximumValue() const
214 215 216 217
{
    return d->mUserMaxValue;
}

218
qreal KSignalPlotter::currentMaximumRangeValue() const
219 220 221 222
{
    return d->mNiceMaxValue;
}

223
qreal KSignalPlotter::currentMinimumRangeValue() const
224 225 226 227 228 229
{
    return d->mNiceMinValue;
}

void KSignalPlotter::setHorizontalScale( uint scale )
{
230
    if (scale == d->mHorizontalScale || scale == 0)
231 232 233 234
        return;

    d->mHorizontalScale = scale;
    d->updateDataBuffers();
235 236 237 238 239 240
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    update();
}

int KSignalPlotter::horizontalScale() const
{
    return d->mHorizontalScale;
}

void KSignalPlotter::setShowVerticalLines( bool value )
{
    if(d->mShowVerticalLines == value) return;
    d->mShowVerticalLines = value;
    d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif
    update();
}

bool KSignalPlotter::showVerticalLines() const
{
    return d->mShowVerticalLines;
}

void KSignalPlotter::setVerticalLinesDistance( uint distance )
{
    if(distance == d->mVerticalLinesDistance) return;
    d->mVerticalLinesDistance = distance;
    d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif
    update();
}

uint KSignalPlotter::verticalLinesDistance() const
{
    return d->mVerticalLinesDistance;
}

void KSignalPlotter::setVerticalLinesScroll( bool value )
{
    if(value == d->mVerticalLinesScroll) return;
    d->mVerticalLinesScroll = value;
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif
    update();
}

bool KSignalPlotter::verticalLinesScroll() const
{
    return d->mVerticalLinesScroll;
}

void KSignalPlotter::setShowHorizontalLines( bool value )
{
    if(value == d->mShowHorizontalLines) return;
    d->mShowHorizontalLines = value;
306 307 308 309 310 311
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    update();
}

bool KSignalPlotter::showHorizontalLines() const
{
    return d->mShowHorizontalLines;
}

void KSignalPlotter::setShowAxis( bool value )
{
    if(value == d->mShowAxis) return;
    d->mShowAxis = value;
    d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif
    update();
}

bool KSignalPlotter::showAxis() const
{
    return d->mShowAxis;
}

QString KSignalPlotter::svgBackground() const {
    return d->mSvgFilename;
}
void KSignalPlotter::setSvgBackground( const QString &filename )
{
    if(d->mSvgFilename == filename) return;
    d->mSvgFilename = filename;
345 346 347 348 349 350 351 352 353 354
#ifdef SVG_SUPPORT
    if(filename.isEmpty()) {
        delete d->mSvgRenderer;
        d->mSvgRenderer = NULL;
    } else {
        if(!d->mSvgRenderer)
            d->mSvgRenderer = new Plasma::Svg(this);
        d->mSvgRenderer->setImagePath(d->mSvgFilename);
    }
#endif
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    d->mBackgroundImage = QPixmap();
    update();
}

void KSignalPlotter::setMaxAxisTextWidth(int axisTextWidth)
{
    if(d->mAxisTextWidth == axisTextWidth) return;
    d->mAxisTextWidth = axisTextWidth;
    d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
    update();
}

int KSignalPlotter::maxAxisTextWidth() const
{
    return d->mAxisTextWidth;
}
void KSignalPlotter::changeEvent ( QEvent * event )
{
373 374 375 376 377 378 379 380 381 382 383 384
    switch (event->type()) {
        case QEvent::ApplicationPaletteChange:
        case QEvent::PaletteChange:
        case QEvent::FontChange:
        case QEvent::LanguageChange:
        case QEvent::LocaleChange:
        case QEvent::LayoutDirectionChange:
            d->mBackgroundImage = QPixmap(); //we changed a paint setting, so reset the cache
            update();
            break;
        default: //Do nothing
            break;
385 386
    }
}
387 388 389 390 391 392
#ifdef GRAPHICS_SIGNAL_PLOTTER
void KGraphicsSignalPlotter::resizeEvent( QGraphicsSceneResizeEvent* event )
{
    QRect boundingBox(QPoint(0,0), event->newSize().toSize());
    int fontHeight = QFontMetrics(font()).height();
#else
393 394 395 396
void KSignalPlotter::resizeEvent( QResizeEvent* event )
{
    QRect boundingBox(QPoint(0,0), event->size());
    int fontHeight = fontMetrics().height();
397
#endif
398 399 400 401 402 403 404 405 406 407 408
    if( d->mShowAxis && d->mAxisTextWidth != 0 && boundingBox.width() > (d->mAxisTextWidth*1.10+2) && boundingBox.height() > fontHeight ) {  //if there's room to draw the labels, then draw them!
        //We want to adjust the size of plotter bit inside so that the axis text aligns nicely at the top and bottom
        //but we don't want to sacrifice too much of the available room, so don't use it if it will take more than 20% of the available space
        qreal offset = (fontHeight+1)/2;
        if(offset < boundingBox.height() * 0.1)
            boundingBox.adjust(0,offset, 0, -offset);

        int padding = 1;
        if(boundingBox.width() > d->mAxisTextWidth + 50)
            padding = 10; //If there's plenty of room, at 10 pixels for padding the axis text, so that it looks nice

409
        if ( layoutDirection() == Qt::RightToLeft )
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
            boundingBox.setRight(boundingBox.right() - d->mAxisTextWidth - padding);
        else
            boundingBox.setLeft(d->mAxisTextWidth+padding);
        d->mActualAxisTextWidth = d->mAxisTextWidth;
    } else {
        d->mActualAxisTextWidth = 0;
    }
    if(d->mShowThinFrame)
        boundingBox.adjust(0,0,-1,-1);

    // Remember bounding box to pass to update, so that we only update the plotting area the next time, if that's the only that thing that has changed
    d->mPlottingArea = boundingBox;

    //Calculate the new number of horizontal lines
    int newHorizontalLinesCount = qBound(0, (int)(boundingBox.height() / fontHeight)-2, 4);
    if(newHorizontalLinesCount != d->mHorizontalLinesCount) {
        d->mHorizontalLinesCount = newHorizontalLinesCount;
        d->calculateNiceRange();
    }
#ifdef USE_QIMAGE
    d->mScrollableImage = QImage();
#else
    d->mScrollableImage = QPixmap();
#endif

#ifdef USE_SEPERATE_WIDGET
436 437
    d->mGraphWidget->setVisible(true);
    d->mGraphWidget->setGeometry(boundingBox);
438 439
#endif

440 441 442
    d->updateDataBuffers();
}

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
KSignalPlotterPrivate::KSignalPlotterPrivate(KSignalPlotter *q_ptr_) : q(q_ptr_)
{
    mPrecision = 0;
    mMaxSamples = NUM_SAMPLES_WHEN_INVISIBLE;
    mMinValue = mMaxValue = std::numeric_limits<qreal>::quiet_NaN();
    mUserMinValue = mUserMaxValue = 0.0;
    mNiceMinValue = mNiceMaxValue = 0.0;
    mNiceRange = 0;
    mUseAutoRange = true;
    mScaleDownBy = 1;
    mShowThinFrame = true;
    mSmoothGraph = true;
    mShowVerticalLines = false;
    mVerticalLinesDistance = 30;
    mVerticalLinesScroll = true;
    mVerticalLinesOffset = 0;
    mHorizontalScale = 6;
    mShowHorizontalLines = true;
    mHorizontalLinesCount = 4;
    mShowAxis = true;
    mAxisTextWidth = 0;
    mScrollOffset = 0;
    mStackBeams = false;
    mFillOpacity = 20;
    mRescaleTime = 0;
    mUnit = ki18n("%1");
    mAxisTextOverlapsPlotter = false;
    mActualAxisTextWidth = 0;
#ifdef USE_SEPERATE_WIDGET
    mGraphWidget = new GraphWidget(q); ///< This is the widget that draws the actual graph
    mGraphWidget->signalPlotterPrivate = this;
    mGraphWidget->setVisible(false);
#endif
}

void KSignalPlotterPrivate::recalculateMaxMinValueForSample(const QList<qreal>&sampleBuf, int time )
{
    if(mStackBeams) {
        qreal value=0;
        for(int i = sampleBuf.count()-1; i>= 0; i--) {
            qreal newValue = sampleBuf[i];
484
            if( !std::isinf(newValue) && !std::isnan(newValue) )
485 486
                value += newValue;
        }
487 488
        if(std::isnan(mMinValue) || mMinValue > value) mMinValue = value;
        if(std::isnan(mMaxValue) || mMaxValue < value) mMaxValue = value;
489 490 491 492 493 494
        if(value > 0.7*mMaxValue)
            mRescaleTime = time;
    } else {
        qreal value;
        for(int i = sampleBuf.count()-1; i>= 0; i--) {
            value = sampleBuf[i];
495 496 497
            if( !std::isinf(value) && !std::isnan(value) ) {
                if(std::isnan(mMinValue) || mMinValue > value) mMinValue = value;
                if(std::isnan(mMaxValue) || mMaxValue < value) mMaxValue = value;
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                if(value > 0.7*mMaxValue)
                    mRescaleTime = time;
            }
        }
    }
}

void KSignalPlotterPrivate::rescale() {
    mMaxValue = mMinValue = std::numeric_limits<qreal>::quiet_NaN();
    for(int i = mBeamData.count()-1; i >= 0; i--) {
        recalculateMaxMinValueForSample(mBeamData[i], i);
    }
    calculateNiceRange();
}

void KSignalPlotterPrivate::addSample( const QList<qreal>& sampleBuf )
{
    if(sampleBuf.count() != mBeamColors.count()) {
516
        qCDebug(LIBKSYSGUARD_KSIGNALPLOTTER) << "Sample data discarded - contains wrong number of beams";
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
        return;
    }
    mBeamData.prepend(sampleBuf);
    if((unsigned int)mBeamData.size() > mMaxSamples) {
        mBeamData.removeLast(); // we have too many.  Remove the last item
        if((unsigned int)mBeamData.size() > mMaxSamples)
            mBeamData.removeLast(); // If we still have too many, then we have resized the widget.  Remove one more.  That way we will slowly resize to the new size
    }

    if(mUseAutoRange) {
        recalculateMaxMinValueForSample(sampleBuf, 0);

        if(mRescaleTime++ > mMaxSamples)
            rescale();
        else if(mMinValue < mNiceMinValue || mMaxValue > mNiceMaxValue || (mMaxValue > mUserMaxValue && mNiceRange != 1 && mMaxValue < (mNiceRange*0.75 + mNiceMinValue)) || mNiceRange == 0)
            calculateNiceRange();
    } else {
        if(mMinValue < mNiceMinValue || mMaxValue > mNiceMaxValue || (mMaxValue > mUserMaxValue && mNiceRange != 1 && mMaxValue < (mNiceRange*0.75 + mNiceMinValue)) || mNiceRange == 0)
            calculateNiceRange();
    }

    if(mScrollableImage.isNull())
        return;
    QPainter pCache(&mScrollableImage);
    drawBeamToScrollableImage(&pCache, 0);
}

void KSignalPlotterPrivate::reorderBeams( const QList<int>& newOrder )
{
    if(newOrder.count() != mBeamColors.count()) {
        return;
    }
    QList< QList<qreal> >::Iterator it;
    for(it = mBeamData.begin(); it != mBeamData.end(); ++it) {
        if(newOrder.count() != (*it).count()) {
552
            qCWarning(LIBKSYSGUARD_KSIGNALPLOTTER) << "Serious problem in move sample.  beamdata[i] has " << (*it).count() << " and neworder has " << newOrder.count();
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        } else {
            QList<qreal> newBeam;
            for(int i = 0; i < newOrder.count(); i++) {
                int newIndex = newOrder[i];
                newBeam.append((*it).at(newIndex));
            }
            (*it) = newBeam;
        }
    }
    QList< QColor > newBeamColors;
    QList< QColor > newBeamColorsDark;
    for(int i = 0; i < newOrder.count(); i++) {
        int newIndex = newOrder[i];
        newBeamColors.append(mBeamColors.at(newIndex));
        newBeamColorsDark.append(mBeamColorsLight.at(newIndex));
    }
    mBeamColors = newBeamColors;
    mBeamColorsLight = newBeamColorsDark;
}

573 574 575 576 577 578 579 580 581 582 583 584
void KSignalPlotterPrivate::updateDataBuffers()
{

    /*  This is called when the widget has resized
     *
     *  Determine new number of samples first.
     *  +0.5 to ensure rounding up
     *  +4 for extra data points so there is
     *     1) no wasted space and
     *     2) no loss of precision when drawing the first data point.
     */
    if(q->isVisible())
585
        mMaxSamples = uint(q->size().width() / mHorizontalScale + 4);
586
    else //If it's not visible, we can't rely on sensible values for width.  Store some minimum number of data points
587
        mMaxSamples = qMin((uint)(q->size().width() / mHorizontalScale + 4), NUM_SAMPLES_WHEN_INVISIBLE);
588 589
}

590 591 592 593 594
#ifdef GRAPHICS_SIGNAL_PLOTTER
void KGraphicsSignalPlotter::paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    Q_UNUSED(widget);
#else
595 596 597 598
void KSignalPlotter::paintEvent( QPaintEvent* event)
{
    if (testAttribute(Qt::WA_PendingResizeEvent))
        return; // lets not do this more than necessary, shall we?
599 600 601
    QPainter p(this);
    QPainter *painter = &p;
#endif
602

603 604
    uint w = size().width();
    uint h = size().height();
605
    /* Do not do repaints when the widget is not yet setup properly. */
606
    if ( w <= 2 || h <= 2 )
607 608
        return;

609 610 611 612 613
#ifdef GRAPHICS_SIGNAL_PLOTTER
    bool onlyDrawPlotter = option && d->mPlottingArea.contains(option->exposedRect.toRect());
#else
    bool onlyDrawPlotter = event && d->mPlottingArea.contains(event->rect());
#endif
614

615 616 617 618 619 620
#ifdef USE_SEPERATE_WIDGET
    if(onlyDrawPlotter)
        return; //The painting will be handled entirely by GraphWidget::paintEvent
#endif

    if(!onlyDrawPlotter && d->mShowThinFrame)
621
        d->drawThinFrame(painter, d->mPlottingArea.adjusted(0,0,1,1)); //We have a 'frame' in the bottom and right - so subtract them from the view
622 623

#ifndef USE_SEPERATE_WIDGET
624
    d->drawWidget(painter, d->mPlottingArea); //Draw the widget only if we don't have a GraphWidget to draw it for us
625 626 627
#endif

    if(d->mShowAxis) {
628 629 630
#ifdef GRAPHICS_SIGNAL_PLOTTER
        int fontheight = QFontMetrics(font()).height();
#else
631
        int fontheight = fontMetrics().height();
632
#endif
633
        if( d->mPlottingArea.height() > fontheight ) {  //if there's room to draw the labels, then draw them!
634
            d->drawAxisText(painter, QRect(0,0,w,h));
635 636 637 638 639
        }
    }
}
#ifdef USE_SEPERATE_WIDGET
void GraphWidget::paintEvent( QPaintEvent*)
640
{
641 642
    if (testAttribute(Qt::WA_PendingResizeEvent))
        return; // lets not do this more than necessary, shall we?
643

644 645 646 647 648 649
    uint w = width();
    uint h = height();
    /* Do not do repaints when the widget is not yet setup properly. */
    if ( w <= 2 || h <= 2 )
        return;
    QPainter p(this);
650

651
    signalPlotterPrivate->drawWidget(&p, QRect(0,0,w,h));
652

653 654 655 656 657 658 659 660 661 662 663
    if(signalPlotterPrivate->mAxisTextOverlapsPlotter && signalPlotterPrivate->mShowAxis) {
        uint fontheight = signalPlotterPrivate->q->fontMetrics().height();
        if( h > fontheight ) {  //if there's room to draw the labels, then draw them!
            QSize originalSize = signalPlotterPrivate->q->size();
            signalPlotterPrivate->drawAxisText(&p, QRect(-signalPlotterPrivate->mPlottingArea.topLeft(), originalSize));
        }
    }
}
#endif
void KSignalPlotterPrivate::drawWidget(QPainter *p, const QRect &boundingBox)
{
664 665 666 667
#ifdef SVG_SUPPORT
    if(!mSvgFilename.isEmpty()) {
        if(mBackgroundImage.isNull() || mBackgroundImage.height() != boundingBox.height() || mBackgroundImage.width() != boundingBox.width()) { //recreate on resize etc
            updateSvgBackground(boundingBox);
668
        }
669
        p->drawPixmap(boundingBox, mBackgroundImage);
670
    }
671
#endif
672

673 674
    if( mScrollableImage.isNull() )
        redrawScrollableImage();
675 676

    //We draw the pixmap in two halves, wrapping around the window
677
    if(mScrollOffset > 1) {
John Tapsell's avatar
John Tapsell committed
678
#ifdef USE_QIMAGE
679
        p->drawImage(boundingBox.right() - mScrollOffset+2, boundingBox.top(), mScrollableImage, 0, 0, mScrollOffset-1, boundingBox.height());
John Tapsell's avatar
John Tapsell committed
680
#else
681
        p->drawPixmap(boundingBox.right() - mScrollOffset+2, boundingBox.top(), mScrollableImage, 0, 0, mScrollOffset-1, boundingBox.height());
John Tapsell's avatar
John Tapsell committed
682
#endif
683 684 685
    }
    int widthOfSecondHalf = boundingBox.width() - mScrollOffset + 1;
    if(widthOfSecondHalf > 0) {
686
#ifdef USE_QIMAGE
687
        p->drawImage(boundingBox.left(), boundingBox.top(), mScrollableImage, mScrollableImage.width() - widthOfSecondHalf-1, 0, widthOfSecondHalf, boundingBox.height());
688
#else
689
        p->drawPixmap(boundingBox.left(), boundingBox.top(), mScrollableImage, mScrollableImage.width() - widthOfSecondHalf-1, 0, widthOfSecondHalf, boundingBox.height());
690 691 692
#endif
    }

693 694 695
    /* Draw scope-like grid vertical lines if it doesn't move.  If it does move, draw it in the dynamic part of the code*/
    if(mShowVerticalLines && !mVerticalLinesScroll)
        drawVerticalLines(p, boundingBox);
696
}
697
void KSignalPlotterPrivate::drawBackground(QPainter *p, const QRect &boundingBox) const
698
{
699 700 701 702 703 704 705 706 707 708
    p->setRenderHint(QPainter::Antialiasing, false);
#ifdef SVG_SUPPORT
    if(!mSvgFilename.isEmpty()) //our background is an svg, so don't paint over the top of it
        p->fillRect(boundingBox, Qt::transparent);
    else
#endif
        p->fillRect(boundingBox, q->palette().brush(QPalette::Base));

    if ( mShowHorizontalLines )
        drawHorizontalLines(p, boundingBox.adjusted(0,0,1,0));
709

710 711 712 713 714
    if ( mShowVerticalLines && mVerticalLinesScroll )
        drawVerticalLines(p, boundingBox, mVerticalLinesOffset);

    p->setRenderHint(QPainter::Antialiasing, true);
}
715

716 717 718 719 720 721 722 723 724 725 726 727 728
bool KSignalPlotter::thinFrame() const
{
    return d->mShowThinFrame;
}
void KSignalPlotter::setThinFrame(bool thinFrame)
{
    if(thinFrame == d->mShowThinFrame)
        return;

    d->mShowThinFrame = thinFrame;
    update(); //Trigger a repaint
}

729
#ifdef SVG_SUPPORT
730 731 732 733 734 735 736 737 738 739 740 741
void KSignalPlotterPrivate::updateSvgBackground(const QRect &boundingBox)
{
    Q_ASSERT(!mSvgFilename.isEmpty());
    Q_ASSERT(boundingBox.isNull());
    mBackgroundImage = QPixmap(boundingBox.width(), boundingBox.height());
    Q_ASSERT(!mBackgroundImage.isNull());
    QPainter pCache(&mBackgroundImage);
    pCache.fill( q->palette().color(QPalette::Base) );

    svgRenderer->resize(boundingBox.size());
    svgRenderer->paint(&pCache, 0, 0);

742
}
743
#endif
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
void KSignalPlotterPrivate::redrawScrollableImage()
{
    //Align width of bounding box to the size of the horizontal scale
    int alignedWidth = ((mPlottingArea.width() + 1) / mHorizontalScale + 1) * mHorizontalScale;
    //Redraw the whole thing
#ifdef USE_QIMAGE
    mScrollableImage = QImage(alignedWidth, mPlottingArea.height(),QImage::Format_ARGB32_Premultiplied);
#else
    mScrollableImage = QPixmap(alignedWidth, mPlottingArea.height());
#endif
    Q_ASSERT(!mScrollableImage.isNull());

    mScrollOffset = 0;
    mVerticalLinesOffset = mVerticalLinesDistance - mHorizontalScale+1; // mVerticalLinesDistance - alignedWidth % mVerticalLinesDistance;
    //We need to draw the background for areas without a beam
    int withoutBeamWidth = qMax(mBeamData.size()-1, 0) * mHorizontalScale;
    QPainter pCache(&mScrollableImage);
    if(withoutBeamWidth < mScrollableImage.width())
        drawBackground(&pCache, QRect(withoutBeamWidth, 0, alignedWidth - withoutBeamWidth, mScrollableImage.height()));

    /* Draw scope-like grid vertical lines */
    mVerticalLinesOffset = 0;
    if(mBeamData.size() > 2) {
        for(int i = mBeamData.size()-2; i >= 0; i--)
            drawBeamToScrollableImage(&pCache, i);
    }
}
771 772 773

void KSignalPlotterPrivate::drawThinFrame(QPainter *p, const QRect &boundingBox)
{
774
    /* Draw a line along the bottom and the right side of the
775
     * widget to create a 3D like look. */
776
    p->setRenderHint(QPainter::Antialiasing, false);
777 778 779
    p->setPen( QPen(q->palette().color( QPalette::Light ), 0) );
    p->drawLine( boundingBox.bottomLeft(), boundingBox.bottomRight());
    p->drawLine( boundingBox.bottomRight(), boundingBox.topRight());
780
    p->setRenderHint(QPainter::Antialiasing, true);
781 782 783 784
}

void KSignalPlotterPrivate::calculateNiceRange()
{
785 786
    qreal max = mUserMaxValue;
    qreal min = mUserMinValue;
787
    if( mUseAutoRange ) {
788
        if(!std::isnan(mMaxValue) && mMaxValue * 0.99 > max)  //Allow max value to go very slightly over the given max, for rounding reasons
789
            max = mMaxValue;
790
        if(!std::isnan(mMinValue) && mMinValue * 0.99 < min) {
791 792 793 794 795 796 797 798 799
            min = mMinValue;
        }
    }

    /* If the range is too small we will force it to 1.0 since it
     * looks a lot nicer. */
    if(max - min < 0.000001 )
        max = min +1;

800
    qreal range = max - min;
801 802

    // Massage the range so that the grid shows some nice values.
803
    qreal step;
804 805 806 807 808 809 810 811 812 813 814
    int number_lines_above_zero = 0;
    int number_lines_below_zero = 0;
    //If y=0 is visible and have at least 1 horizontal lines make sure that we have a line crossing through 0
    bool alignToXAxis = min < 0 && max > 0 && mHorizontalLinesCount >= 1;
    if( alignToXAxis ) {
        number_lines_above_zero = int( mHorizontalLinesCount * max / range);
        number_lines_below_zero = mHorizontalLinesCount - number_lines_above_zero -1; //subtract 1 line for the actual 0 line
        step = qMax( max / (mScaleDownBy*(number_lines_above_zero+1)), -min/(mScaleDownBy*(number_lines_below_zero+1)));
    } else
        step = range / (mScaleDownBy*(mHorizontalLinesCount+1));

815 816
    const int sigFigs = 2;                                   //Number of significant figures of the step to use.  Update the 0.05 below if this changes
    int logdim = (int)floor( log10( step ) ) - (sigFigs-1);  //find the order of the number, reduced by 1.  E.g. if step=1234 then logdim is 3-1=2
817
    qreal dim = pow( (qreal)10.0, logdim );                //e.g.  if step=1234, logdim=2, so dim = 100
818 819
    int a = (int)ceil( step / dim - 0.000005);                   //so a = ceil(1234/100) = ceil(12.34) = 13    (we subtract an epsilon)

820
    if(logdim >= 0)
821 822 823
        mPrecision = 0;                                      //Work out the number of decimal places.  e.g. If step=1.5, then logdim = -1 so precision is 1
    else if(a % 10 == 0)                                     //We just happened to round to a nice number, requiring 1 less precision
        mPrecision = -logdim - 1;
824
    else
825 826
        mPrecision = -logdim;
    step = dim*a;                                            //e.g. if step=1234, dim=100, a=13  so step= 1300.  So 1234 was rounded up to 1300
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848

    range = mScaleDownBy * step * (mHorizontalLinesCount+1);

    if( alignToXAxis ) {
        max = mScaleDownBy * step * (number_lines_above_zero+1);
        min = -mScaleDownBy * step * (number_lines_below_zero+1);
    } else
        max = min + range;

    if( mNiceMinValue == min && mNiceRange == range)
        return;  //nothing changed

    mNiceMaxValue = max;
    mNiceMinValue = min;
    mNiceRange = range;

#ifdef USE_QIMAGE
    mScrollableImage = QImage();
#else
    mScrollableImage = QPixmap();
#endif
    emit q->axisScaleChanged();
849
    q->update();
850 851
}

852
void KSignalPlotterPrivate::drawVerticalLines(QPainter *p, const QRect &boundingBox, int offset) const
853
{
854 855 856 857
    QColor color = q->palette().color(QPalette::Window);
    if(!mVerticalLinesScroll)
        color.setAlpha(127);
    p->setPen( QPen(color, 0) );
858

859 860
    p->setRenderHint(QPainter::Antialiasing, false);
    for ( int x = boundingBox.right() - ( offset % mVerticalLinesDistance); x >= boundingBox.left(); x -= mVerticalLinesDistance )
861
        p->drawLine( x, boundingBox.top(), x, boundingBox.bottom()  );
862
    p->setRenderHint(QPainter::Antialiasing, true);
863 864
}

865
void KSignalPlotterPrivate::drawBeamToScrollableImage(QPainter *p, int index)
866 867 868
{
    QRect cacheBoundingBox = QRect(mScrollOffset, 0, mHorizontalScale, mScrollableImage.height());

869 870
    drawBackground(p, cacheBoundingBox);
    drawBeam(p, cacheBoundingBox, mHorizontalScale, index);
871 872

    mScrollOffset += mHorizontalScale;
873
    mVerticalLinesOffset = (mVerticalLinesOffset + mHorizontalScale) % mVerticalLinesDistance;
874 875
    if(mScrollOffset >= mScrollableImage.width()-1) {
        mScrollOffset = 0;
876
        mVerticalLinesOffset--; //We skip over the last pixel drawn
877 878 879 880 881 882 883
    }
}

void KSignalPlotterPrivate::drawBeam(QPainter *p, const QRect &boundingBox, int horizontalScale, int index)
{
    if(mNiceRange == 0) return;
    QPen pen;
884 885 886 887 888
    if(mHorizontalScale == 1) //Don't use a pen width of 2 if there's only 1 pixel between points
        pen.setWidth(1);
    else
        pen.setWidth(2);

889 890
    pen.setCapStyle(Qt::FlatCap);

891
    qreal scaleFac = (boundingBox.height()-2) / mNiceRange;
892 893 894
    if(mBeamData.size() - 1 <= index )
        return;  // Something went wrong?

895 896
    const QList<qreal> &datapoints = mBeamData[index];
    const QList<qreal> &prev_datapoints = mBeamData[index+1];
897
    bool hasPrevPrevDatapoints = (index +2 < mBeamData.size()); //used for bezier curve gradient calculation
898
    const QList<qreal> &prev_prev_datapoints = hasPrevPrevDatapoints?mBeamData[index+2]:prev_datapoints;
899

900 901
    qreal x0 = boundingBox.right();
    qreal x1 = qMax(boundingBox.right() - horizontalScale, 0);
902 903 904 905

    qreal xaxis = boundingBox.bottom();
    if( mNiceMinValue < 0)
       xaxis = qMax(qreal(xaxis + mNiceMinValue*scaleFac), qreal(boundingBox.top()));
906 907 908

    const int count = qMin(datapoints.size(), mBeamColors.size());
    QVector<QPainterPath> paths(count);
909 910 911 912 913 914 915 916 917
    QPointF previous_c0;
    QPointF previous_c1;
    QPointF previous_c2;
    QPointF previous_c3;
    qreal previous_point0 = 0;
    qreal previous_point1 = 0;
    qreal previous_point2 = 0;
    bool firstLine = true;
    for (int j = 0; j < count; ++j) {
918
        qreal point0 = datapoints[j];
919
        if( std::isnan(point0) )
920 921
            continue; //Just do not draw points with nans. skip them

922 923
        qreal point1 = prev_datapoints[j];
        qreal point2 = prev_prev_datapoints[j];
924

925
        if(std::isnan(point1))
926
            point1 = point0;
927
        else if(mSmoothGraph && !std::isinf(point1)) {
928 929 930
            // Apply a weighted average just to smooth the graph out a bit
            // Do not try to smooth infinities or nans
            point0 = (2*point0 + point1)/3;
931
            if(!std::isnan(point2) && !std::isinf(point2))
932 933 934
                point1 = (2*point1 + point2)/3;
            // We don't bother to average out y2.  This will introduce slight inaccuracies in the gradients, but they aren't really noticeable.
        }
935
        if(std::isnan(point2))
936 937
            point2 = point1;

938 939 940 941 942 943 944 945 946
        if (mStackBeams) {
            point0 = previous_point0 = previous_point0 + point0;
            point1 = previous_point1 = previous_point1 + point1;
            point2 = previous_point2 = previous_point2 + point2;
        }

        qreal y0 = qBound((qreal)boundingBox.top(), boundingBox.bottom() - (point0 - mNiceMinValue)*scaleFac, (qreal)boundingBox.bottom());
        qreal y1 = qBound((qreal)boundingBox.top(), boundingBox.bottom() - (point1 - mNiceMinValue)*scaleFac, (qreal)boundingBox.bottom());
        qreal y2 = qBound((qreal)boundingBox.top(), boundingBox.bottom() - (point2 - mNiceMinValue)*scaleFac, (qreal)boundingBox.bottom());
947

948
        QPainterPath &path = paths[j];
949 950 951
        path.moveTo( x1, y1);
        QPointF c1( x1 + horizontalScale/3.0, (4* y1 - y2)/3.0 );//Control point 1 - same gradient as prev_prev_datapoint to prev_datapoint
        QPointF c2( x1 + 2*horizontalScale/3.0, (2* y0 + y1)/3.0);//Control point 2 - same gradient as prev_datapoint to datapoint
952 953
        QPointF c3(x0,y0);
        path.cubicTo( c1, c2, c3 );
954
        if(mFillOpacity) {
955
            QPainterPath fillPath = path; //Make a copy to do our fill
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
            if (!mStackBeams || firstLine) {
                fillPath.lineTo(x0, xaxis);
                fillPath.lineTo(x1, xaxis);
                fillPath.lineTo(x1,y1);
            } else {
                fillPath.lineTo(x0, previous_c3.y());
                fillPath.cubicTo(previous_c2, previous_c1, previous_c0);
                fillPath.lineTo(x1, y1);
            }
            if (mStackBeams) {
                previous_c0 = QPointF(x1,y1);
                previous_c1 = c1;
                previous_c2 = c2;
                previous_c3 = c3;
            }
971 972
            QColor fillColor = mBeamColors[j];
            fillColor.setAlpha(mFillOpacity);
973
            p->fillPath(fillPath, fillColor);
974
        }
975
        firstLine = false;
976
    }
977 978
    for(int j = count-1; j >= 0 ; --j) {
        if(mFillOpacity)
John Tapsell's avatar
John Tapsell committed
979 980 981
            pen.setColor(mBeamColorsLight.at(j));
        else
            pen.setColor(mBeamColors.at(j));
982 983
        p->strokePath(paths.at(j),pen);
    }
984 985 986 987
}
void KSignalPlotterPrivate::drawAxisText(QPainter *p, const QRect &boundingBox)
{
    if(mHorizontalLinesCount < 0) return;
988
    p->setFont( q->font() );
989
    qreal stepsize = mNiceRange/(mScaleDownBy*(mHorizontalLinesCount+1));
990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    if(mActualAxisTextWidth == 0) //If we are drawing completely inside the plotter area, using the Text color
        p->setPen( QPen( q->palette().brush(QPalette::Text), 0) );
    else
        p->setPen( QPen( q->palette().brush(QPalette::WindowText), 0) );
    int axisTitleIndex=1;
    QString val;
    int numItems = mHorizontalLinesCount +2;
    int fontHeight = p->fontMetrics().height();
    if(numItems == 2 && boundingBox.height() < fontHeight*2 )
        numItems = 1;
    mAxisTextOverlapsPlotter = false;
    for ( int y = 0; y < numItems; y++, axisTitleIndex++) {
        int y_coord = boundingBox.top() + (y * (boundingBox.height()-fontHeight)) /(mHorizontalLinesCount+1);  //Make sure it's y*h first to avoid rounding bugs
1003
        qreal value;
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        if(y == mHorizontalLinesCount+1)
            value = mNiceMinValue/mScaleDownBy; //sometimes using the formulas gives us a value very slightly off
        else
            value = mNiceMaxValue/mScaleDownBy - y * stepsize;

        val = scaledValueAsString(value, mPrecision);
        QRect textBoundingRect = p->fontMetrics().boundingRect(val);

        if(textBoundingRect.width() > mActualAxisTextWidth)
            mAxisTextOverlapsPlotter = true;
        int offset = qMax(mActualAxisTextWidth - textBoundingRect.right(), -textBoundingRect.left());
1015
        if ( q->layoutDirection() == Qt::RightToLeft )
1016 1017 1018 1019 1020 1021
            p->drawText( boundingBox.left(), y_coord, boundingBox.width() - offset , fontHeight+1, Qt::AlignLeft | Qt::AlignTop, val);
        else
            p->drawText( boundingBox.left() + offset, y_coord, boundingBox.width() - offset, fontHeight+1, Qt::AlignLeft | Qt::AlignTop, val);
    }
}

1022
void KSignalPlotterPrivate::drawHorizontalLines(QPainter *p, const QRect &boundingBox) const
1023 1024
{
    if(mHorizontalLinesCount <= 0) return;
1025
    p->setPen( QPen(q->palette().color(QPalette::Window) ));
1026 1027 1028 1029 1030 1031 1032
    for ( int y = 0; y <= mHorizontalLinesCount+1; y++ ) {
        //note that the y_coord starts from 0.  so we draw from pixel number 0 to h-1.  Thus the -1 in the y_coord
        int y_coord =  boundingBox.top() + (y * (boundingBox.height()-1)) / (mHorizontalLinesCount+1);  //Make sure it's y*h first to avoid rounding bugs
        p->drawLine( boundingBox.left(), y_coord, boundingBox.right() - 1, y_coord);
    }
}

1033 1034 1035 1036 1037
int KSignalPlotter::currentAxisPrecision() const
{
    return d->mPrecision;
}

1038
qreal KSignalPlotter::lastValue( int i) const
1039
{
1040
    if(d->mBeamData.isEmpty() || d->mBeamData.first().size() <= i) return std::numeric_limits<qreal>::quiet_NaN();