qwt_plot_curve.cpp 34.8 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 38 39 40 41 42 43 44 45 46
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
 * Qwt Widget Library
 * Copyright (C) 1997   Josef Wilgen
 * Copyright (C) 2002   Uwe Rathmann
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the Qwt License, Version 1.0
 *****************************************************************************/

#include <qpainter.h>
#include <qpixmap.h>
#include <qbitarray.h>
#include "qwt_global.h"
#include "qwt_legend.h"
#include "qwt_legend_item.h"
#include "qwt_data.h"
#include "qwt_scale_map.h"
#include "qwt_double_rect.h"
#include "qwt_math.h"
#include "qwt_clipper.h"
#include "qwt_painter.h"
#include "qwt_plot.h"
#include "qwt_plot_canvas.h"
#include "qwt_curve_fitter.h"
#include "qwt_symbol.h"
#include "qwt_plot_curve.h"

#define SCALE_PEN 0

#if QT_VERSION < 0x040000
#include <qguardedptr.h>
#else
#include <qpointer.h>
#endif

#if QT_VERSION >= 0x040000

#include <qevent.h>
#include <qpaintengine.h>

class QwtPlotCurvePaintHelper: public QObject
{
public:
    QwtPlotCurvePaintHelper(const QwtPlotCurve *curve, int from, int to):
        _curve(curve),
        _from(from),
47
        _to(to) {
pixhawk's avatar
pixhawk committed
48 49
    }

50 51
    virtual bool eventFilter(QObject *, QEvent *event) {
        if ( event->type() == QEvent::Paint ) {
pixhawk's avatar
pixhawk committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
            _curve->draw(_from, _to);
            return true;
        }
        return false;
    }
private:
    const QwtPlotCurve *_curve;
    int _from;
    int _to;
};

#endif // QT_VERSION >= 0x040000

// Creating and initializing a QPainter is an
// expensive operation. So we keep an painter
// open for situations, where we paint outside
// of paint events. This improves the performance
// of incremental painting like in the realtime
// example a lot.
// But it is not possible to have more than
// one QPainter open at the same time. So we
// need to close it before regular paint events
// are processed.

class QwtGuardedPainter: public QObject
{
public:
79
    ~QwtGuardedPainter() {
pixhawk's avatar
pixhawk committed
80 81 82
        end();
    }

83
    QPainter *begin(QwtPlotCanvas *canvas) {
pixhawk's avatar
pixhawk committed
84 85 86
        _canvas = canvas;

        QMap<QwtPlotCanvas *, QPainter *>::iterator it = _map.find(_canvas);
87
        if ( it == _map.end() ) {
pixhawk's avatar
pixhawk committed
88 89 90 91 92 93 94 95 96 97 98 99 100 101
            QPainter *painter = new QPainter(_canvas);
            painter->setClipping(true);
            painter->setClipRect(_canvas->contentsRect());

            it = _map.insert(_canvas, painter);
            _canvas->installEventFilter(this);
        }
#if QT_VERSION < 0x040000
        return it.data();
#else
        return it.value();
#endif
    }

102 103
    void end() {
        if ( _canvas ) {
pixhawk's avatar
pixhawk committed
104
            QMap<QwtPlotCanvas *, QPainter *>::iterator it = _map.find(_canvas);
105
            if ( it != _map.end() ) {
pixhawk's avatar
pixhawk committed
106 107 108 109 110 111 112 113 114 115 116 117
                _canvas->removeEventFilter(this);

#if QT_VERSION < 0x040000
                delete it.data();
#else
                delete it.value();
#endif
                _map.erase(it);
            }
        }
    }

118
    virtual bool eventFilter(QObject *, QEvent *event) {
pixhawk's avatar
pixhawk committed
119 120 121 122 123 124 125
        if ( event->type() == QEvent::Paint )
            end();

        return false;
    }

private:
126
#if QT_VERSION < 0x040000
pixhawk's avatar
pixhawk committed
127 128 129 130 131 132 133 134 135
    QGuardedPtr<QwtPlotCanvas> _canvas;
#else
    QPointer<QwtPlotCanvas> _canvas;
#endif
    static QMap<QwtPlotCanvas *, QPainter *> _map;
};

QMap<QwtPlotCanvas *, QPainter *> QwtGuardedPainter::_map;

136 137
static QwtPolygon clipPolygon(QPainter *painter, int attributes,
                              const QwtPolygon &polygon)
pixhawk's avatar
pixhawk committed
138 139 140 141
{
    bool doClipping = attributes & QwtPlotCurve::ClipPolygons;
    QRect clipRect = painter->window();

142
    if ( !doClipping ) {
pixhawk's avatar
pixhawk committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
#if QT_VERSION >= 0x040000
        const QPaintEngine *pe = painter->paintEngine();
        if ( pe && pe->type() == QPaintEngine::SVG )
#else
        if ( painter->device()->devType() == QInternal::Picture )
#endif
        {
            // The SVG paint engine ignores any clipping,
            // so we enable polygon clipping.

            doClipping = true;
            if ( painter->hasClipping() )
                clipRect &= painter->clipRegion().boundingRect();
        }
    }

    if ( doClipping )
        return QwtClipper::clipPolygon(clipRect, polygon);
161

pixhawk's avatar
pixhawk committed
162 163 164 165 166
    return polygon;
}

static int verifyRange(int size, int &i1, int &i2)
{
167
    if (size < 1)
pixhawk's avatar
pixhawk committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        return 0;

    i1 = qwtLim(i1, 0, size-1);
    i2 = qwtLim(i2, 0, size-1);

    if ( i1 > i2 )
        qSwap(i1, i2);

    return (i2 - i1 + 1);
}

class QwtPlotCurve::PrivateData
{
public:
    class PixelMatrix: private QBitArray
    {
    public:
        PixelMatrix(const QRect& rect):
            QBitArray(rect.width() * rect.height()),
187
            _rect(rect) {
pixhawk's avatar
pixhawk committed
188 189 190
            fill(false);
        }

191
        inline bool testPixel(const QPoint& pos) {
pixhawk's avatar
pixhawk committed
192 193 194
            if ( !_rect.contains(pos) )
                return false;

195 196
            const int idx = _rect.width() * (pos.y() - _rect.y()) +
                            (pos.x() - _rect.x());
pixhawk's avatar
pixhawk committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

            const bool marked = testBit(idx);
            if ( !marked )
                setBit(idx, true);

            return !marked;
        }

    private:
        QRect _rect;
    };

    PrivateData():
        curveType(Yfx),
        style(QwtPlotCurve::Lines),
        reference(0.0),
        attributes(0),
214
        paintAttributes(0) {
pixhawk's avatar
pixhawk committed
215 216 217 218 219
        symbol = new QwtSymbol();
        pen = QPen(Qt::black);
        curveFitter = new QwtSplineCurveFitter;
    }

220
    ~PrivateData() {
pixhawk's avatar
pixhawk committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
        delete symbol;
        delete curveFitter;
    }

    QwtPlotCurve::CurveType curveType;
    QwtPlotCurve::CurveStyle style;
    double reference;

    QwtSymbol *symbol;
    QwtCurveFitter *curveFitter;

    QPen pen;
    QBrush brush;

    int attributes;
    int paintAttributes;

    QwtGuardedPainter guardedPainter;
};

//! Constructor
QwtPlotCurve::QwtPlotCurve():
    QwtPlotItem(QwtText())
{
    init();
}

/*!
  Constructor
250
  \param title title of the curve
pixhawk's avatar
pixhawk committed
251 252 253 254 255 256 257 258 259
*/
QwtPlotCurve::QwtPlotCurve(const QwtText &title):
    QwtPlotItem(title)
{
    init();
}

/*!
  Constructor
260
  \param title title of the curve
pixhawk's avatar
pixhawk committed
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
*/
QwtPlotCurve::QwtPlotCurve(const QString &title):
    QwtPlotItem(QwtText(title))
{
    init();
}

//! Destructor
QwtPlotCurve::~QwtPlotCurve()
{
    delete d_xy;
    delete d_data;
}

/*!
  \brief Initialize data members
*/
void QwtPlotCurve::init()
{
    setItemAttribute(QwtPlotItem::Legend);
    setItemAttribute(QwtPlotItem::AutoScale);

    d_data = new PrivateData;
    d_xy = new QwtPolygonFData(QwtArray<QwtDoublePoint>());

    setZ(20.0);
}

//! \return QwtPlotItem::Rtti_PlotCurve
int QwtPlotCurve::rtti() const
{
    return QwtPlotItem::Rtti_PlotCurve;
}

/*!
  \brief Specify an attribute how to draw the curve

  The attributes can be used to modify the drawing algorithm.

  The following attributes are defined:<dl>
  <dt>PaintFiltered</dt>
  <dd>Tries to reduce the data that has to be painted, by sorting out
      duplicates, or paintings outside the visible area. Might have a
304
      notable impact on curves with many close points.
pixhawk's avatar
pixhawk committed
305 306 307 308 309 310 311 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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      Only a couple of very basic filtering algos are implemented.</dd>
  <dt>ClipPolygons</dt>
  <dd>Clip polygons before painting them. In situations, where points
      are far outside the visible area this might be a great improvement
      for the painting performance ( especially on Windows ).
  </dl>

  The default is, that no paint attributes are enabled.

  \param attribute Paint attribute
  \param on On/Off
  /sa testPaintAttribute()
*/
void QwtPlotCurve::setPaintAttribute(PaintAttribute attribute, bool on)
{
    if ( on )
        d_data->paintAttributes |= attribute;
    else
        d_data->paintAttributes &= ~attribute;
}

/*!
    \brief Return the current paint attributes
    \sa setPaintAttribute
*/
bool QwtPlotCurve::testPaintAttribute(PaintAttribute attribute) const
{
    return (d_data->paintAttributes & attribute);
}

/*!
  \brief Set the curve's drawing style

  Valid styles are:
  <dl>
  <dt>NoCurve</dt>
  <dd>Don't draw a curve. Note: This doesn't affect the symbol. </dd>
  <dt>Lines</dt>
  <dd>Connect the points with straight lines. The lines might
      be interpolated depending on the 'Fitted' option. Curve
      fitting can be configured using setCurveFitter.</dd>
  <dt>Sticks</dt>
  <dd>Draw vertical sticks from a baseline which is defined by setBaseline().</dd>
  <dt>Steps</dt>
  <dd>Connect the points with a step function. The step function
      is drawn from the left to the right or vice versa,
      depending on the 'Inverted' option.</dd>
  <dt>Dots</dt>
  <dd>Draw dots at the locations of the data points. Note:
      This is different from a dotted line (see setPen()).</dd>
  <dt>UserCurve ...</dt>
  <dd>Styles >= UserCurve are reserved for derived
      classes of QwtPlotCurve that overload drawCurve() with
      additional application specific curve types.</dd>
  </dl>
  \sa style()
*/
void QwtPlotCurve::setStyle(CurveStyle style)
{
364
    if ( style != d_data->style ) {
pixhawk's avatar
pixhawk committed
365 366 367 368 369 370 371 372 373
        d_data->style = style;
        itemChanged();
    }
}

/*!
    \brief Return the current style
    \sa setStyle()
*/
374 375 376
QwtPlotCurve::CurveStyle QwtPlotCurve::style() const
{
    return d_data->style;
pixhawk's avatar
pixhawk committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
}

/*!
  \brief Assign a symbol
  \param symbol Symbol
  \sa symbol()
*/
void QwtPlotCurve::setSymbol(const QwtSymbol &symbol )
{
    delete d_data->symbol;
    d_data->symbol = symbol.clone();
    itemChanged();
}

/*!
    \brief Return the current symbol
    \sa setSymbol()
*/
395 396 397
const QwtSymbol &QwtPlotCurve::symbol() const
{
    return *d_data->symbol;
pixhawk's avatar
pixhawk committed
398 399 400 401 402 403 404 405 406
}

/*!
  \brief Assign a pen
  \param pen New pen
  \sa pen(), brush()
*/
void QwtPlotCurve::setPen(const QPen &pen)
{
407
    if ( pen != d_data->pen ) {
pixhawk's avatar
pixhawk committed
408 409 410 411 412 413 414 415 416
        d_data->pen = pen;
        itemChanged();
    }
}

/*!
    \brief Return the pen used to draw the lines
    \sa setPen(), brush()
*/
417 418 419
const QPen& QwtPlotCurve::pen() const
{
    return d_data->pen;
pixhawk's avatar
pixhawk committed
420 421 422
}

/*!
423 424
  \brief Assign a brush.
         In case of brush.style() != QBrush::NoBrush
pixhawk's avatar
pixhawk committed
425 426 427 428
         and style() != QwtPlotCurve::Sticks
         the area between the curve and the baseline will be filled.
         In case !brush.color().isValid() the area will be filled by
         pen.color(). The fill algorithm simply connects the first and the
429 430
         last curve point to the baseline. So the curve data has to be sorted
         (ascending or descending).
pixhawk's avatar
pixhawk committed
431 432 433 434 435
  \param brush New brush
  \sa brush(), setBaseline(), baseline()
*/
void QwtPlotCurve::setBrush(const QBrush &brush)
{
436
    if ( brush != d_data->brush ) {
pixhawk's avatar
pixhawk committed
437 438 439 440 441 442 443 444 445
        d_data->brush = brush;
        itemChanged();
    }
}

/*!
  \brief Return the brush used to fill the area between lines and the baseline
  \sa setBrush(), setBaseline(), baseline()
*/
446
const QBrush& QwtPlotCurve::brush() const
pixhawk's avatar
pixhawk committed
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
{
    return d_data->brush;
}


/*!
  Set data by copying x- and y-values from specified memory blocks.
  Contrary to setCurveRawData(), this function makes a 'deep copy' of
  the data.

  \param xData pointer to x values
  \param yData pointer to y values
  \param size size of xData and yData

  \sa QwtCPointerData
*/
void QwtPlotCurve::setData(const double *xData, const double *yData, int size)
{
    delete d_xy;
    d_xy = new QwtArrayData(xData, yData, size);
    itemChanged();
}

/*!
  \brief Initialize data with x- and y-arrays (explicitly shared)

  \param xData x data
  \param yData y data

  \sa QwtArrayData
*/
478 479
void QwtPlotCurve::setData(const QwtArray<double> &xData,
                           const QwtArray<double> &yData)
pixhawk's avatar
pixhawk committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 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 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
{
    delete d_xy;
    d_xy = new QwtArrayData(xData, yData);
    itemChanged();
}

/*!
  Initialize data with an array of points (explicitly shared).

  \param data Data
  \sa QwtPolygonFData
*/
#if QT_VERSION < 0x040000
void QwtPlotCurve::setData(const QwtArray<QwtDoublePoint> &data)
#else
void QwtPlotCurve::setData(const QPolygonF &data)
#endif
{
    delete d_xy;
    d_xy = new QwtPolygonFData(data);
    itemChanged();
}

/*!
  Initialize data with a pointer to QwtData.

  \param data Data
  \sa QwtData::copy()
*/
void QwtPlotCurve::setData(const QwtData &data)
{
    delete d_xy;
    d_xy = data.copy();
    itemChanged();
}

/*!
  \brief Initialize the data by pointing to memory blocks which are not managed
  by QwtPlotCurve.

  setRawData is provided for efficiency. It is important to keep the pointers
  during the lifetime of the underlying QwtCPointerData class.

  \param xData pointer to x data
  \param yData pointer to y data
  \param size size of x and y

  \sa QwtCPointerData::setData.
*/
void QwtPlotCurve::setRawData(const double *xData, const double *yData, int size)
{
    delete d_xy;
    d_xy = new QwtCPointerData(xData, yData, size);
    itemChanged();
}

/*!
  Returns the bounding rectangle of the curve data. If there is
  no bounding rect, like for empty data the rectangle is invalid.
  \sa QwtData::boundingRect(), QwtDoubleRect::isValid()
*/

QwtDoubleRect QwtPlotCurve::boundingRect() const
{
    if ( d_xy == NULL )
        return QwtDoubleRect(1.0, 1.0, -2.0, -2.0); // invalid

    return d_xy->boundingRect();
}

/*!
  \brief Draw the complete curve

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.

  \sa drawCurve(), drawSymbols()
*/
void QwtPlotCurve::draw(QPainter *painter,
560 561
                        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                        const QRect &) const
pixhawk's avatar
pixhawk committed
562 563 564 565 566 567 568 569 570 571 572 573 574
{
    draw(painter, xMap, yMap, 0, -1);
}

/*!
  \brief Draw a set of points of a curve.

  When observing an measurement while it is running, new points have to be
  added to an existing curve. drawCurve can be used to display them avoiding
  a complete redraw of the canvas.

  Setting plot()->canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true);
  will result in faster painting, if the paint engine of the canvas widget
575
  supports this feature.
pixhawk's avatar
pixhawk committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

  \param from Index of the first point to be painted
  \param to Index of the last point to be painted. If to < 0 the
         curve will be painted to its last point.

  \sa drawCurve(), drawSymbols()
*/
void QwtPlotCurve::draw(int from, int to) const
{
    if ( !plot() )
        return;

    QwtPlotCanvas *canvas = plot()->canvas();

#if QT_VERSION >= 0x040000
#if 0
592
    if ( canvas->paintEngine()->type() == QPaintEngine::OpenGL ) {
pixhawk's avatar
pixhawk committed
593 594 595 596 597 598 599 600 601 602 603
        /*
            OpenGL alway repaint the complete widget.
            So for this operation OpenGL is one of the slowest
            environments.
         */
        canvas->repaint();
        return;
    }
#endif

    if ( !canvas->testAttribute(Qt::WA_WState_InPaintEvent) &&
604
            !canvas->testAttribute(Qt::WA_PaintOutsidePaintEvent) ) {
pixhawk's avatar
pixhawk committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        /*
          We save curve and range in helper and call repaint.
          The helper filters the Paint event, to repeat
          the QwtPlotCurve::draw, but now from inside the paint
          event.
         */

        QwtPlotCurvePaintHelper helper(this, from, to);
        canvas->installEventFilter(&helper);

        const bool noSystemBackground =
            canvas->testAttribute(Qt::WA_NoSystemBackground);
        canvas->setAttribute(Qt::WA_NoSystemBackground, true);
        canvas->repaint();
        canvas->setAttribute(Qt::WA_NoSystemBackground, noSystemBackground);

        return;
    }
#endif

    const QwtScaleMap xMap = plot()->canvasMap(xAxis());
    const QwtScaleMap yMap = plot()->canvasMap(yAxis());

    if ( canvas->testPaintAttribute(QwtPlotCanvas::PaintCached) &&
629
            canvas->paintCache() && !canvas->paintCache()->isNull() ) {
pixhawk's avatar
pixhawk committed
630 631
        QPainter cachePainter((QPixmap *)canvas->paintCache());
        cachePainter.translate(-canvas->contentsRect().x(),
632
                               -canvas->contentsRect().y());
pixhawk's avatar
pixhawk committed
633 634 635 636 637

        draw(&cachePainter, xMap, yMap, from, to);
    }

#if QT_VERSION >= 0x040000
638
    if ( canvas->testAttribute(Qt::WA_WState_InPaintEvent) ) {
pixhawk's avatar
pixhawk committed
639 640 641 642 643 644
        QPainter painter(canvas);

        painter.setClipping(true);
        painter.setClipRect(canvas->contentsRect());

        draw(&painter, xMap, yMap, from, to);
645
    } else
pixhawk's avatar
pixhawk committed
646 647 648 649 650 651 652 653 654 655 656 657 658
#endif
    {
        QPainter *painter = d_data->guardedPainter.begin(canvas);
        draw(painter, xMap, yMap, from, to);
    }
}

/*!
  \brief Draw an interval of the curve
  \param painter Painter
  \param xMap maps x-values into pixel coordinates.
  \param yMap maps y-values into pixel coordinates.
  \param from index of the first point to be painted
659
  \param to index of the last point to be painted. If to < 0 the
pixhawk's avatar
pixhawk committed
660 661 662 663 664
         curve will be painted to its last point.

  \sa drawCurve(), drawSymbols(),
*/
void QwtPlotCurve::draw(QPainter *painter,
665 666
                        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                        int from, int to) const
pixhawk's avatar
pixhawk committed
667 668 669 670 671 672 673
{
    if ( !painter || dataSize() <= 0 )
        return;

    if (to < 0)
        to = dataSize() - 1;

674
    if ( verifyRange(dataSize(), from, to) > 0 ) {
pixhawk's avatar
pixhawk committed
675
        painter->save();
676

pixhawk's avatar
pixhawk committed
677 678 679
        QPen pen = d_data->pen;

#if SCALE_PEN
680
        if ( pen.width() > 0 ) {
pixhawk's avatar
pixhawk committed
681 682 683 684
            const QwtMetricsMap &metricsMap = QwtPainter::metricsMap();
            pen.setWidth(metricsMap.screenToLayoutX(pen.width()));
        }
#endif
685

pixhawk's avatar
pixhawk committed
686 687 688
        painter->setPen(pen);

        /*
689
          Qt 4.0.0 is slow when drawing lines, but it's even
pixhawk's avatar
pixhawk committed
690 691 692 693 694 695 696
          slower when the painter has a brush. So we don't
          set the brush before we really need it.
         */

        drawCurve(painter, d_data->style, xMap, yMap, from, to);
        painter->restore();

697
        if (d_data->symbol->style() != QwtSymbol::NoSymbol) {
pixhawk's avatar
pixhawk committed
698 699 700 701 702 703 704 705
            painter->save();
            drawSymbols(painter, *d_data->symbol, xMap, yMap, from, to);
            painter->restore();
        }
    }
}

/*!
706
  \brief Draw the line part (without symbols) of a curve interval.
pixhawk's avatar
pixhawk committed
707 708 709 710 711 712 713 714 715 716
  \param painter Painter
  \param style curve style, see QwtPlotCurve::CurveStyle
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted
  \sa draw(), drawDots(), drawLines(), drawSteps(), drawSticks()
*/

void QwtPlotCurve::drawCurve(QPainter *painter, int style,
717 718
                             const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                             int from, int to) const
pixhawk's avatar
pixhawk committed
719
{
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    switch (style) {
    case Lines:
        if ( testCurveAttribute(Fitted) ) {
            // we always need the complete
            // curve for fitting
            from = 0;
            to = dataSize() - 1;
        }
        drawLines(painter, xMap, yMap, from, to);
        break;
    case Sticks:
        drawSticks(painter, xMap, yMap, from, to);
        break;
    case Steps:
        drawSteps(painter, xMap, yMap, from, to);
        break;
    case Dots:
        drawDots(painter, xMap, yMap, from, to);
        break;
    case NoCurve:
    default:
        break;
pixhawk's avatar
pixhawk committed
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    }
}

/*!
  \brief Draw lines

  If the CurveAttribute Fitted is enabled a QwtCurveFitter tries
  to interpolate/smooth the curve, before it is painted.

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

757
  \sa setCurveAttribute(), setCurveFitter(), draw(),
pixhawk's avatar
pixhawk committed
758 759 760
      drawLines(), drawDots(), drawSteps(), drawSticks()
*/
void QwtPlotCurve::drawLines(QPainter *painter,
761 762
                             const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                             int from, int to) const
pixhawk's avatar
pixhawk committed
763 764 765 766 767 768
{
    int size = to - from + 1;
    if ( size <= 0 )
        return;

    QwtPolygon polyline;
769
    if ( ( d_data->attributes & Fitted ) && d_data->curveFitter ) {
pixhawk's avatar
pixhawk committed
770 771 772 773 774 775 776 777 778
        // Transform x and y values to window coordinates
        // to avoid a distinction between linear and
        // logarithmic scales.

#if QT_VERSION < 0x040000
        QwtArray<QwtDoublePoint> points(size);
#else
        QPolygonF points(size);
#endif
779
        for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
            QwtDoublePoint &p = points[i];
            p.setX( xMap.xTransform(x(i)) );
            p.setY( yMap.xTransform(y(i)) );
        }

        points = d_data->curveFitter->fitCurve(points);
        size = points.size();

        if ( size == 0 )
            return;

        // Round QwtDoublePoints to QPoints
        // When Qwt support for Qt3 has been dropped (Qwt 6.x)
        // we will use a doubles for painting and the following
        // step will be obsolete.

        polyline.resize(size);

        const QwtDoublePoint *p = points.data();
        QPoint *pl = polyline.data();
800
        if ( d_data->paintAttributes & PaintFiltered ) {
pixhawk's avatar
pixhawk committed
801 802 803 804 805

            QPoint pp(qRound(p[0].x()), qRound(p[0].y()));
            pl[0] = pp;

            int count = 1;
806
            for (int i = 1; i < size; i++) {
pixhawk's avatar
pixhawk committed
807
                const QPoint pi(qRound(p[i].x()), qRound(p[i].y()));
808
                if ( pi != pp ) {
pixhawk's avatar
pixhawk committed
809 810 811 812 813 814
                    pl[count++] = pi;
                    pp = pi;
                }
            }
            if ( count != size )
                polyline.resize(count);
815 816
        } else {
            for ( int i = 0; i < size; i++ ) {
pixhawk's avatar
pixhawk committed
817 818 819 820
                pl[i].setX( qRound(p[i].x()) );
                pl[i].setY( qRound(p[i].y()) );
            }
        }
821
    } else {
pixhawk's avatar
pixhawk committed
822 823
        polyline.resize(size);

824
        if ( d_data->paintAttributes & PaintFiltered ) {
pixhawk's avatar
pixhawk committed
825 826 827 828
            QPoint pp( xMap.transform(x(from)), yMap.transform(y(from)) );
            polyline.setPoint(0, pp);

            int count = 1;
829
            for (int i = from + 1; i <= to; i++) {
pixhawk's avatar
pixhawk committed
830
                const QPoint pi(xMap.transform(x(i)), yMap.transform(y(i)));
831
                if ( pi != pp ) {
pixhawk's avatar
pixhawk committed
832 833 834 835 836 837 838 839
                    polyline.setPoint(count, pi);
                    count++;

                    pp = pi;
                }
            }
            if ( count != size )
                polyline.resize(count);
840 841
        } else {
            for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                int xi = xMap.transform(x(i));
                int yi = yMap.transform(y(i));

                polyline.setPoint(i - from, xi, yi);
            }
        }
    }

    polyline = ::clipPolygon(painter, d_data->paintAttributes, polyline);

    QwtPainter::drawPolyline(painter, polyline);

    if ( d_data->brush.style() != Qt::NoBrush )
        fillCurve(painter, xMap, yMap, polyline);
}

/*!
  Draw sticks

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa draw(), drawCurve(), drawDots(), drawLines(), drawSteps()
*/
void QwtPlotCurve::drawSticks(QPainter *painter,
870 871
                              const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                              int from, int to) const
pixhawk's avatar
pixhawk committed
872 873 874 875
{
    int x0 = xMap.transform(d_data->reference);
    int y0 = yMap.transform(d_data->reference);

876
    for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
        const int xi = xMap.transform(x(i));
        const int yi = yMap.transform(y(i));

        if (d_data->curveType == Xfy)
            QwtPainter::drawLine(painter, x0, yi, xi, yi);
        else
            QwtPainter::drawLine(painter, xi, y0, xi, yi);
    }
}

/*!
  Draw dots

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa draw(), drawCurve(), drawSticks(), drawLines(), drawSteps()
*/
void QwtPlotCurve::drawDots(QPainter *painter,
899 900
                            const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                            int from, int to) const
pixhawk's avatar
pixhawk committed
901 902 903 904 905 906 907 908 909 910 911
{
    const QRect window = painter->window();
    if ( window.isEmpty() )
        return;

    const bool doFill = d_data->brush.style() != Qt::NoBrush;

    QwtPolygon polyline;
    if ( doFill )
        polyline.resize(to - from + 1);

912 913
    if ( to > from && d_data->paintAttributes & PaintFiltered ) {
        if ( doFill ) {
pixhawk's avatar
pixhawk committed
914 915 916 917 918 919
            QPoint pp( xMap.transform(x(from)), yMap.transform(y(from)) );

            QwtPainter::drawPoint(painter, pp.x(), pp.y());
            polyline.setPoint(0, pp);

            int count = 1;
920
            for (int i = from + 1; i <= to; i++) {
pixhawk's avatar
pixhawk committed
921
                const QPoint pi(xMap.transform(x(i)), yMap.transform(y(i)));
922
                if ( pi != pp ) {
pixhawk's avatar
pixhawk committed
923 924 925 926 927 928 929 930 931 932
                    QwtPainter::drawPoint(painter, pi.x(), pi.y());

                    polyline.setPoint(count, pi);
                    count++;

                    pp = pi;
                }
            }
            if ( int(polyline.size()) != count )
                polyline.resize(count);
933
        } else {
pixhawk's avatar
pixhawk committed
934 935 936 937 938
            // if we don't need to fill, we can sort out
            // duplicates independent from the order

            PrivateData::PixelMatrix pixelMatrix(window);

939
            for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
940
                const QPoint p( xMap.transform(x(i)),
941
                                yMap.transform(y(i)) );
pixhawk's avatar
pixhawk committed
942 943 944 945 946

                if ( pixelMatrix.testPixel(p) )
                    QwtPainter::drawPoint(painter, p.x(), p.y());
            }
        }
947 948
    } else {
        for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
949 950 951 952 953 954 955 956 957
            const int xi = xMap.transform(x(i));
            const int yi = yMap.transform(y(i));
            QwtPainter::drawPoint(painter, xi, yi);

            if ( doFill )
                polyline.setPoint(i - from, xi, yi);
        }
    }

958
    if ( doFill ) {
pixhawk's avatar
pixhawk committed
959 960 961 962 963 964 965 966
        polyline = ::clipPolygon(painter, d_data->paintAttributes, polyline);
        fillCurve(painter, xMap, yMap, polyline);
    }
}

/*!
  Draw step function

967
  The direction of the steps depends on Inverted attribute.
pixhawk's avatar
pixhawk committed
968 969 970 971 972 973 974 975 976 977 978

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa CurveAttribute, setCurveAttribute(),
      draw(), drawCurve(), drawDots(), drawLines(), drawSticks()
*/
void QwtPlotCurve::drawSteps(QPainter *painter,
979 980
                             const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                             int from, int to) const
pixhawk's avatar
pixhawk committed
981 982 983 984 985 986 987 988
{
    QwtPolygon polyline(2 * (to - from) + 1);

    bool inverted = d_data->curveType == Yfx;
    if ( d_data->attributes & Inverted )
        inverted = !inverted;

    int i,ip;
989
    for (i = from, ip = 0; i <= to; i++, ip += 2) {
pixhawk's avatar
pixhawk committed
990 991 992
        const int xi = xMap.transform(x(i));
        const int yi = yMap.transform(y(i));

993
        if ( ip > 0 ) {
pixhawk's avatar
pixhawk committed
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
            if (inverted)
                polyline.setPoint(ip - 1, polyline[ip-2].x(), yi);
            else
                polyline.setPoint(ip - 1, xi, polyline[ip-2].y());
        }

        polyline.setPoint(ip, xi, yi);
    }

    polyline = ::clipPolygon(painter, d_data->paintAttributes, polyline);

    QwtPainter::drawPolyline(painter, polyline);

    if ( d_data->brush.style() != Qt::NoBrush )
        fillCurve(painter, xMap, yMap, polyline);
}


/*!
  \brief Specify an attribute for drawing the curve

  The attributes can be used to modify the drawing style.
  The following attributes are defined:<dl>
  <dt>Fitted</dt>
  <dd>For Lines only. A QwtCurveFitter tries to
      interpolate/smooth the curve, before it is painted.
      Note that curve fitting requires temorary memory
1021
      for calculating coefficients and additional points.
pixhawk's avatar
pixhawk committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
      If painting in Fitted mode is slow it might be better
      to fit the points, before they are passed to QwtPlotCurve.
  </dd>
  <dt>Inverted</dt>
  <dd>For Steps only. Draws a step function
      from the right to the left.</dd></dl>

  \param attribute Curve attribute
  \param on On/Off

  /sa testCurveAttribute(), setCurveFitter()
*/
void QwtPlotCurve::setCurveAttribute(CurveAttribute attribute, bool on)
{
    if ( bool(d_data->attributes & attribute) == on )
        return;

    if ( on )
        d_data->attributes |= attribute;
    else
        d_data->attributes &= ~attribute;

    itemChanged();
}

/*!
    \return true, if attribute is enabled
    \sa setCurveAttribute()
*/
1051 1052
bool QwtPlotCurve::testCurveAttribute(CurveAttribute attribute) const
{
pixhawk's avatar
pixhawk committed
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    return d_data->attributes & attribute;
}

/*!
  Assign the curve type

  <dt>QwtPlotCurve::Yfx
  <dd>Draws y as a function of x (the default). The
      baseline is interpreted as a horizontal line
      with y = baseline().</dd>
  <dt>QwtPlotCurve::Xfy
  <dd>Draws x as a function of y. The baseline is
      interpreted as a vertical line with x = baseline().</dd>

  The baseline is used for aligning the sticks, or
  filling the curve with a brush.

  \sa curveType()
*/
void QwtPlotCurve::setCurveType(CurveType curveType)
{
1074
    if ( d_data->curveType != curveType ) {
pixhawk's avatar
pixhawk committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        d_data->curveType = curveType;
        itemChanged();
    }
}

/*!
   Return the curve type
   \sa setCurveType()
*/
QwtPlotCurve::CurveType QwtPlotCurve::curveType() const
{
    return d_data->curveType;
}

void QwtPlotCurve::setCurveFitter(QwtCurveFitter *curveFitter)
{
    delete d_data->curveFitter;
    d_data->curveFitter = curveFitter;

    itemChanged();
}

QwtCurveFitter *QwtPlotCurve::curveFitter() const
{
    return d_data->curveFitter;
}

1102 1103
/*!
  Fill the area between the curve and the baseline with
pixhawk's avatar
pixhawk committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
  the curve brush

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param pa Polygon

  \sa setBrush(), setBaseline(), setCurveType()
*/

void QwtPlotCurve::fillCurve(QPainter *painter,
1115 1116
                             const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                             QwtPolygon &pa) const
pixhawk's avatar
pixhawk committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
{
    if ( d_data->brush.style() == Qt::NoBrush )
        return;

    closePolyline(xMap, yMap, pa);
    if ( pa.count() <= 2 ) // a line can't be filled
        return;

    QBrush b = d_data->brush;
    if ( !b.color().isValid() )
        b.setColor(d_data->pen.color());

    painter->save();

    painter->setPen(QPen(Qt::NoPen));
    painter->setBrush(b);

    QwtPainter::drawPolygon(painter, pa);

    painter->restore();
}

/*!
1140
  \brief Complete a polygon to be a closed polygon
pixhawk's avatar
pixhawk committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
         including the area between the original polygon
         and the baseline.
  \param xMap X map
  \param yMap Y map
  \param pa Polygon to be completed
*/

void QwtPlotCurve::closePolyline(
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    QwtPolygon &pa) const
{
    const int sz = pa.size();
    if ( sz < 2 )
        return;

    pa.resize(sz + 2);

1158
    if ( d_data->curveType == QwtPlotCurve::Xfy ) {
pixhawk's avatar
pixhawk committed
1159
        pa.setPoint(sz,
1160
                    xMap.transform(d_data->reference), pa.point(sz - 1).y());
pixhawk's avatar
pixhawk committed
1161
        pa.setPoint(sz + 1,
1162 1163
                    xMap.transform(d_data->reference), pa.point(0).y());
    } else {
pixhawk's avatar
pixhawk committed
1164
        pa.setPoint(sz,
1165
                    pa.point(sz - 1).x(), yMap.transform(d_data->reference));
pixhawk's avatar
pixhawk committed
1166
        pa.setPoint(pa.size() - 1,
1167
                    pa.point(0).x(), yMap.transform(d_data->reference));
pixhawk's avatar
pixhawk committed
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    }
}

/*!
  \brief Draw symbols
  \param painter Painter
  \param symbol Curve symbol
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa setSymbol(), draw(), drawCurve()
*/
void QwtPlotCurve::drawSymbols(QPainter *painter, const QwtSymbol &symbol,
1183 1184
                               const QwtScaleMap &xMap, const QwtScaleMap &yMap,
                               int from, int to) const
pixhawk's avatar
pixhawk committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
{
    painter->setBrush(symbol.brush());

    const QwtMetricsMap &metricsMap = QwtPainter::metricsMap();

    QPen pen = symbol.pen();

#if SCALE_PEN
    if ( pen.width() > 0 )
        pen.setWidth(metricsMap.screenToLayoutX(pen.width()));
#endif

    painter->setPen(pen);

    QRect rect;
    rect.setSize(metricsMap.screenToLayout(symbol.size()));

1202
    if ( to > from && d_data->paintAttributes & PaintFiltered ) {
pixhawk's avatar
pixhawk committed
1203 1204 1205 1206 1207 1208
        const QRect window = painter->window();
        if ( window.isEmpty() )
            return;

        PrivateData::PixelMatrix pixelMatrix(window);

1209
        for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
1210
            const QPoint pi( xMap.transform(x(i)),
1211
                             yMap.transform(y(i)) );
pixhawk's avatar
pixhawk committed
1212

1213
            if ( pixelMatrix.testPixel(pi) ) {
pixhawk's avatar
pixhawk committed
1214 1215 1216 1217
                rect.moveCenter(pi);
                symbol.draw(painter, rect);
            }
        }
1218 1219
    } else {
        for (int i = from; i <= to; i++) {
pixhawk's avatar
pixhawk committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
            const int xi = xMap.transform(x(i));
            const int yi = yMap.transform(y(i));

            rect.moveCenter(QPoint(xi, yi));
            symbol.draw(painter, rect);
        }
    }
}

/*!
  \brief Set the value of the baseline

  The baseline is needed for filling the curve with a brush or
1233
  the Sticks drawing style.
pixhawk's avatar
pixhawk committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  The default value is 0.0. The interpretation
  of the baseline depends on the CurveType. With QwtPlotCurve::Yfx,
  the baseline is interpreted as a horizontal line at y = baseline(),
  with QwtPlotCurve::Yfy, it is interpreted as a vertical line at
  x = baseline().
  \param reference baseline
  \sa baseline(), setBrush(), setStyle(), setCurveType()
*/
void QwtPlotCurve::setBaseline(double reference)
{
1244
    if ( d_data->reference != reference ) {
pixhawk's avatar
pixhawk committed
1245 1246 1247 1248 1249 1250 1251 1252 1253
        d_data->reference = reference;
        itemChanged();
    }
}

/*!
    Return the value of the baseline
    \sa setBaseline
*/
1254 1255 1256
double QwtPlotCurve::baseline() const
{
    return d_data->reference;
pixhawk's avatar
pixhawk committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
}

/*!
  Return the size of the data arrays
  \sa setData()
*/
int QwtPlotCurve::dataSize() const
{
    return d_xy->size();
}

int QwtPlotCurve::closestPoint(const QPoint &pos, double *dist) const
{
    if ( plot() == NULL || dataSize() <= 0 )
        return -1;

    const QwtScaleMap xMap = plot()->canvasMap(xAxis());
    const QwtScaleMap yMap = plot()->canvasMap(yAxis());

    int index = -1;
    double dmin = 1.0e10;

1279
    for (int i=0; i < dataSize(); i++) {
pixhawk's avatar
pixhawk committed
1280 1281 1282 1283
        const double cx = xMap.xTransform(x(i)) - pos.x();
        const double cy = yMap.xTransform(y(i)) - pos.y();

        const double f = qwtSqr(cx) + qwtSqr(cy);
1284
        if (f < dmin) {
pixhawk's avatar
pixhawk committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            index = i;
            dmin = f;
        }
    }
    if ( dist )
        *dist = sqrt(dmin);

    return index;
}

//!  Update the widget that represents the curve on the legend
void QwtPlotCurve::updateLegend(QwtLegend *legend) const
{
    if ( !legend )
        return;

    QwtPlotItem::updateLegend(legend);

    QWidget *widget = legend->find(this);
    if ( !widget || !widget->inherits("QwtLegendItem") )
        return;

    QwtLegendItem *legendItem = (QwtLegendItem *)widget;

#if QT_VERSION < 0x040000
    const bool doUpdate = legendItem->isUpdatesEnabled();
#else
    const bool doUpdate = legendItem->updatesEnabled();
#endif
    legendItem->setUpdatesEnabled(false);

    const int policy = legend->displayPolicy();

1318
    if (policy == QwtLegend::FixedIdentifier) {
pixhawk's avatar
pixhawk committed
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
        int mode = legend->identifierMode();

        if (mode & QwtLegendItem::ShowLine)
            legendItem->setCurvePen(pen());

        if (mode & QwtLegendItem::ShowSymbol)
            legendItem->setSymbol(symbol());

        if (mode & QwtLegendItem::ShowText)
            legendItem->setText(title());
        else
            legendItem->setText(QwtText());

        legendItem->setIdentifierMode(mode);
1333
    } else if (policy == QwtLegend::AutoIdentifier) {
pixhawk's avatar
pixhawk committed
1334 1335
        int mode = 0;

1336
        if (QwtPlotCurve::NoCurve != style()) {
pixhawk's avatar
pixhawk committed
1337 1338 1339
            legendItem->setCurvePen(pen());
            mode |= QwtLegendItem::ShowLine;
        }
1340
        if (QwtSymbol::NoSymbol != symbol().style()) {
pixhawk's avatar
pixhawk committed
1341 1342 1343
            legendItem->setSymbol(symbol());
            mode |= QwtLegendItem::ShowSymbol;
        }
1344
        if ( !title().isEmpty() ) {
pixhawk's avatar
pixhawk committed
1345 1346
            legendItem->setText(title());
            mode |= QwtLegendItem::ShowText;
1347
        } else {
pixhawk's avatar
pixhawk committed
1348 1349 1350 1351 1352 1353 1354 1355
            legendItem->setText(QwtText());
        }
        legendItem->setIdentifierMode(mode);
    }

    legendItem->setUpdatesEnabled(doUpdate);
    legendItem->update();
}