File indexing completed on 2024-04-14 03:41:08

0001 /*
0002     QCustomPlot, an easy to use, modern plotting widget for Qt
0003     SPDX-FileCopyrightText: 2011-2021 Emanuel Eichhammer <http://www.qcustomplot.com/>
0004 
0005     SPDX-License-Identifier: GPL-3.0-or-later
0006 */
0007 
0008 #include "qcustomplot.h"
0009 
0010 
0011 /* including file 'src/vector2d.cpp'       */
0012 /* modified 2021-03-29T02:30:44, size 7973 */
0013 
0014 ////////////////////////////////////////////////////////////////////////////////////////////////////
0015 //////////////////// QCPVector2D
0016 ////////////////////////////////////////////////////////////////////////////////////////////////////
0017 
0018 /*! \class QCPVector2D
0019   \brief Represents two doubles as a mathematical 2D vector
0020   
0021   This class acts as a replacement for QVector2D with the advantage of double precision instead of
0022   single, and some convenience methods tailored for the QCustomPlot library.
0023 */
0024 
0025 /* start documentation of inline functions */
0026 
0027 /*! \fn void QCPVector2D::setX(double x)
0028   
0029   Sets the x coordinate of this vector to \a x.
0030   
0031   \see setY
0032 */
0033 
0034 /*! \fn void QCPVector2D::setY(double y)
0035   
0036   Sets the y coordinate of this vector to \a y.
0037   
0038   \see setX
0039 */
0040 
0041 /*! \fn double QCPVector2D::length() const
0042   
0043   Returns the length of this vector.
0044   
0045   \see lengthSquared
0046 */
0047 
0048 /*! \fn double QCPVector2D::lengthSquared() const
0049   
0050   Returns the squared length of this vector. In some situations, e.g. when just trying to find the
0051   shortest vector of a group, this is faster than calculating \ref length, because it avoids
0052   calculation of a square root.
0053   
0054   \see length
0055 */
0056 
0057 /*! \fn double QCPVector2D::angle() const
0058   
0059   Returns the angle of the vector in radians. The angle is measured between the positive x line and
0060   the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In
0061   screen/widget coordinates where the y axis is inverted, the angle appears clockwise.
0062 */
0063 
0064 /*! \fn QPoint QCPVector2D::toPoint() const
0065   
0066   Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
0067   information.
0068   
0069   \see toPointF
0070 */
0071 
0072 /*! \fn QPointF QCPVector2D::toPointF() const
0073   
0074   Returns a QPointF which has the x and y coordinates of this vector.
0075   
0076   \see toPoint
0077 */
0078 
0079 /*! \fn bool QCPVector2D::isNull() const
0080   
0081   Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
0082   coordinates, i.e. if both are binary equal to 0.
0083 */
0084 
0085 /*! \fn QCPVector2D QCPVector2D::perpendicular() const
0086   
0087   Returns a vector perpendicular to this vector, with the same length.
0088 */
0089 
0090 /*! \fn double QCPVector2D::dot() const
0091   
0092   Returns the dot/scalar product of this vector with the specified vector \a vec.
0093 */
0094 
0095 /* end documentation of inline functions */
0096 
0097 /*!
0098   Creates a QCPVector2D object and initializes the x and y coordinates to 0.
0099 */
0100 QCPVector2D::QCPVector2D() :
0101   mX(0),
0102   mY(0)
0103 {
0104 }
0105 
0106 /*!
0107   Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
0108   values.
0109 */
0110 QCPVector2D::QCPVector2D(double x, double y) :
0111   mX(x),
0112   mY(y)
0113 {
0114 }
0115 
0116 /*!
0117   Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
0118   the specified \a point.
0119 */
0120 QCPVector2D::QCPVector2D(const QPoint &point) :
0121   mX(point.x()),
0122   mY(point.y())
0123 {
0124 }
0125 
0126 /*!
0127   Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
0128   the specified \a point.
0129 */
0130 QCPVector2D::QCPVector2D(const QPointF &point) :
0131   mX(point.x()),
0132   mY(point.y())
0133 {
0134 }
0135 
0136 /*!
0137   Normalizes this vector. After this operation, the length of the vector is equal to 1.
0138   
0139   If the vector has both entries set to zero, this method does nothing.
0140   
0141   \see normalized, length, lengthSquared
0142 */
0143 void QCPVector2D::normalize()
0144 {
0145   if (mX == 0.0 && mY == 0.0) return;
0146   const double lenInv = 1.0/length();
0147   mX *= lenInv;
0148   mY *= lenInv;
0149 }
0150 
0151 /*!
0152   Returns a normalized version of this vector. The length of the returned vector is equal to 1.
0153   
0154   If the vector has both entries set to zero, this method returns the vector unmodified.
0155   
0156   \see normalize, length, lengthSquared
0157 */
0158 QCPVector2D QCPVector2D::normalized() const
0159 {
0160   if (mX == 0.0 && mY == 0.0) return *this;
0161   const double lenInv = 1.0/length();
0162   return QCPVector2D(mX*lenInv, mY*lenInv);
0163 }
0164 
0165 /*! \overload
0166   
0167   Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
0168   segment given by \a start and \a end.
0169   
0170   \see distanceToStraightLine
0171 */
0172 double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
0173 {
0174   const QCPVector2D v(end-start);
0175   const double vLengthSqr = v.lengthSquared();
0176   if (!qFuzzyIsNull(vLengthSqr))
0177   {
0178     const double mu = v.dot(*this-start)/vLengthSqr;
0179     if (mu < 0)
0180       return (*this-start).lengthSquared();
0181     else if (mu > 1)
0182       return (*this-end).lengthSquared();
0183     else
0184       return ((start + mu*v)-*this).lengthSquared();
0185   } else
0186     return (*this-start).lengthSquared();
0187 }
0188 
0189 /*! \overload
0190   
0191   Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
0192   segment given by \a line.
0193   
0194   \see distanceToStraightLine
0195 */
0196 double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
0197 {
0198   return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
0199 }
0200 
0201 /*!
0202   Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
0203   line given by a \a base point and a \a direction vector.
0204   
0205   \see distanceSquaredToLine
0206 */
0207 double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
0208 {
0209   return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
0210 }
0211 
0212 /*!
0213   Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
0214   factor.
0215 */
0216 QCPVector2D &QCPVector2D::operator*=(double factor)
0217 {
0218   mX *= factor;
0219   mY *= factor;
0220   return *this;
0221 }
0222 
0223 /*!
0224   Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
0225   divisor.
0226 */
0227 QCPVector2D &QCPVector2D::operator/=(double divisor)
0228 {
0229   mX /= divisor;
0230   mY /= divisor;
0231   return *this;
0232 }
0233 
0234 /*!
0235   Adds the given \a vector to this vector component-wise.
0236 */
0237 QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
0238 {
0239   mX += vector.mX;
0240   mY += vector.mY;
0241   return *this;
0242 }
0243 
0244 /*!
0245   subtracts the given \a vector from this vector component-wise.
0246 */
0247 QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
0248 {
0249   mX -= vector.mX;
0250   mY -= vector.mY;
0251   return *this;
0252 }
0253 /* end of 'src/vector2d.cpp' */
0254 
0255 
0256 /* including file 'src/painter.cpp'        */
0257 /* modified 2021-03-29T02:30:44, size 8656 */
0258 
0259 ////////////////////////////////////////////////////////////////////////////////////////////////////
0260 //////////////////// QCPPainter
0261 ////////////////////////////////////////////////////////////////////////////////////////////////////
0262 
0263 /*! \class QCPPainter
0264   \brief QPainter subclass used internally
0265   
0266   This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
0267   consistency between antialiased and non-antialiased painting. Further it provides workarounds
0268   for QPainter quirks.
0269   
0270   \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
0271   restore. So while it is possible to pass a QCPPainter instance to a function that expects a
0272   QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
0273   it will call the base class implementations of the functions actually hidden by QCPPainter).
0274 */
0275 
0276 /*!
0277   Creates a new QCPPainter instance and sets default values
0278 */
0279 QCPPainter::QCPPainter() :
0280   mModes(pmDefault),
0281   mIsAntialiasing(false)
0282 {
0283   // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
0284   // a call to begin() will follow
0285 }
0286 
0287 /*!
0288   Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
0289   like the analogous QPainter constructor, begins painting on \a device immediately.
0290   
0291   Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
0292 */
0293 QCPPainter::QCPPainter(QPaintDevice *device) :
0294   QPainter(device),
0295   mModes(pmDefault),
0296   mIsAntialiasing(false)
0297 {
0298 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
0299   if (isActive())
0300     setRenderHint(QPainter::NonCosmeticDefaultPen);
0301 #endif
0302 }
0303 
0304 /*!
0305   Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
0306   QCPPainter.
0307   
0308   \note this function hides the non-virtual base class implementation.
0309 */
0310 void QCPPainter::setPen(const QPen &pen)
0311 {
0312   QPainter::setPen(pen);
0313   if (mModes.testFlag(pmNonCosmetic))
0314     makeNonCosmetic();
0315 }
0316 
0317 /*! \overload
0318   
0319   Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
0320   this QCPPainter.
0321   
0322   \note this function hides the non-virtual base class implementation.
0323 */
0324 void QCPPainter::setPen(const QColor &color)
0325 {
0326   QPainter::setPen(color);
0327   if (mModes.testFlag(pmNonCosmetic))
0328     makeNonCosmetic();
0329 }
0330 
0331 /*! \overload
0332   
0333   Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
0334   this QCPPainter.
0335   
0336   \note this function hides the non-virtual base class implementation.
0337 */
0338 void QCPPainter::setPen(Qt::PenStyle penStyle)
0339 {
0340   QPainter::setPen(penStyle);
0341   if (mModes.testFlag(pmNonCosmetic))
0342     makeNonCosmetic();
0343 }
0344 
0345 /*! \overload
0346   
0347   Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
0348   antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
0349   integer coordinates and then passes it to the original drawLine.
0350   
0351   \note this function hides the non-virtual base class implementation.
0352 */
0353 void QCPPainter::drawLine(const QLineF &line)
0354 {
0355   if (mIsAntialiasing || mModes.testFlag(pmVectorized))
0356     QPainter::drawLine(line);
0357   else
0358     QPainter::drawLine(line.toLine());
0359 }
0360 
0361 /*!
0362   Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
0363   with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
0364   antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
0365   AA/Non-AA painting).
0366 */
0367 void QCPPainter::setAntialiasing(bool enabled)
0368 {
0369   setRenderHint(QPainter::Antialiasing, enabled);
0370   if (mIsAntialiasing != enabled)
0371   {
0372     mIsAntialiasing = enabled;
0373     if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
0374     {
0375       if (mIsAntialiasing)
0376         translate(0.5, 0.5);
0377       else
0378         translate(-0.5, -0.5);
0379     }
0380   }
0381 }
0382 
0383 /*!
0384   Sets the mode of the painter. This controls whether the painter shall adjust its
0385   fixes/workarounds optimized for certain output devices.
0386 */
0387 void QCPPainter::setModes(QCPPainter::PainterModes modes)
0388 {
0389   mModes = modes;
0390 }
0391 
0392 /*!
0393   Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
0394   device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
0395   all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
0396   behaviour.
0397   
0398   The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
0399   the render hint as appropriate.
0400   
0401   \note this function hides the non-virtual base class implementation.
0402 */
0403 bool QCPPainter::begin(QPaintDevice *device)
0404 {
0405   bool result = QPainter::begin(device);
0406 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
0407   if (result)
0408     setRenderHint(QPainter::NonCosmeticDefaultPen);
0409 #endif
0410   return result;
0411 }
0412 
0413 /*! \overload
0414   
0415   Sets the mode of the painter. This controls whether the painter shall adjust its
0416   fixes/workarounds optimized for certain output devices.
0417 */
0418 void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
0419 {
0420   if (!enabled && mModes.testFlag(mode))
0421     mModes &= ~mode;
0422   else if (enabled && !mModes.testFlag(mode))
0423     mModes |= mode;
0424 }
0425 
0426 /*!
0427   Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
0428   QPainter, the save/restore functions are reimplemented to also save/restore those members.
0429   
0430   \note this function hides the non-virtual base class implementation.
0431   
0432   \see restore
0433 */
0434 void QCPPainter::save()
0435 {
0436   mAntialiasingStack.push(mIsAntialiasing);
0437   QPainter::save();
0438 }
0439 
0440 /*!
0441   Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
0442   QPainter, the save/restore functions are reimplemented to also save/restore those members.
0443   
0444   \note this function hides the non-virtual base class implementation.
0445   
0446   \see save
0447 */
0448 void QCPPainter::restore()
0449 {
0450   if (!mAntialiasingStack.isEmpty())
0451     mIsAntialiasing = mAntialiasingStack.pop();
0452   else
0453     qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
0454   QPainter::restore();
0455 }
0456 
0457 /*!
0458   Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
0459   overrides when the \ref pmNonCosmetic mode is set.
0460 */
0461 void QCPPainter::makeNonCosmetic()
0462 {
0463   if (qFuzzyIsNull(pen().widthF()))
0464   {
0465     QPen p = pen();
0466     p.setWidth(1);
0467     QPainter::setPen(p);
0468   }
0469 }
0470 /* end of 'src/painter.cpp' */
0471 
0472 
0473 /* including file 'src/paintbuffer.cpp'     */
0474 /* modified 2021-03-29T02:30:44, size 18915 */
0475 
0476 ////////////////////////////////////////////////////////////////////////////////////////////////////
0477 //////////////////// QCPAbstractPaintBuffer
0478 ////////////////////////////////////////////////////////////////////////////////////////////////////
0479 
0480 /*! \class QCPAbstractPaintBuffer
0481   \brief The abstract base class for paint buffers, which define the rendering backend
0482 
0483   This abstract base class defines the basic interface that a paint buffer needs to provide in
0484   order to be usable by QCustomPlot.
0485 
0486   A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
0487   the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
0488   QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
0489   painting is complete, \ref donePainting is called, so the paint buffer implementation can do
0490   clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
0491   using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
0492   previous frame.
0493 
0494   The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
0495   software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
0496   frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
0497   They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
0498 */
0499 
0500 /* start documentation of pure virtual functions */
0501 
0502 /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
0503 
0504   Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
0505   responsibility to delete the painter after the painting operations are complete is given to the
0506   caller of this method.
0507 
0508   Once you are done using the painter, delete the painter and call \ref donePainting.
0509 
0510   While a painter generated with this method is active, you must not call \ref setSize, \ref
0511   setDevicePixelRatio or \ref clear.
0512 
0513   This method may return 0, if a painter couldn't be activated on the buffer. This usually
0514   indicates a problem with the respective painting backend.
0515 */
0516 
0517 /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
0518 
0519   Draws the contents of this buffer with the provided \a painter. This is the method that is used
0520   to finally join all paint buffers and draw them onto the screen.
0521 */
0522 
0523 /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
0524 
0525   Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
0526   named color \c Qt::transparent.
0527 
0528   This method must not be called if there is currently a painter (acquired with \ref startPainting)
0529   active.
0530 */
0531 
0532 /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
0533 
0534   Reallocates the internal buffer with the currently configured size (\ref setSize) and device
0535   pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
0536   properties are changed on this paint buffer.
0537 
0538   \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
0539   in their constructor, to perform the first allocation (this can not be done by the base class
0540   because calling pure virtual methods in base class constructors is not possible).
0541 */
0542 
0543 /* end documentation of pure virtual functions */
0544 /* start documentation of inline functions */
0545 
0546 /*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
0547 
0548   If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
0549   call this method as soon as you are done with the painting operations and have deleted the
0550   painter.
0551 
0552   paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
0553   default implementation does nothing.
0554 */
0555 
0556 /* end documentation of inline functions */
0557 
0558 /*!
0559   Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
0560 
0561   Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
0562 */
0563 QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
0564   mSize(size),
0565   mDevicePixelRatio(devicePixelRatio),
0566   mInvalidated(true)
0567 {
0568 }
0569 
0570 QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
0571 {
0572 }
0573 
0574 /*!
0575   Sets the paint buffer size.
0576 
0577   The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
0578   by \ref startPainting are invalidated and must not be used after calling this method.
0579 
0580   If \a size is already the current buffer size, this method does nothing.
0581 */
0582 void QCPAbstractPaintBuffer::setSize(const QSize &size)
0583 {
0584   if (mSize != size)
0585   {
0586     mSize = size;
0587     reallocateBuffer();
0588   }
0589 }
0590 
0591 /*!
0592   Sets the invalidated flag to \a invalidated.
0593 
0594   This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
0595   instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
0596   layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
0597   QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
0598   replots them, instead of only the layer on which the replot was called.
0599 
0600   The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
0601   were added or removed from this buffer, or if they were reordered. It is set to false as soon as
0602   all associated \ref QCPLayer instances are drawn onto the buffer.
0603 
0604   Under normal circumstances, it is not necessary to manually call this method.
0605 */
0606 void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
0607 {
0608   mInvalidated = invalidated;
0609 }
0610 
0611 /*!
0612   Sets the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
0613   The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
0614 
0615   The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
0616   by \ref startPainting are invalidated and must not be used after calling this method.
0617 
0618   \note This method is only available for Qt versions 5.4 and higher.
0619 */
0620 void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
0621 {
0622   if (!qFuzzyCompare(ratio, mDevicePixelRatio))
0623   {
0624 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
0625     mDevicePixelRatio = ratio;
0626     reallocateBuffer();
0627 #else
0628     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
0629     mDevicePixelRatio = 1.0;
0630 #endif
0631   }
0632 }
0633 
0634 ////////////////////////////////////////////////////////////////////////////////////////////////////
0635 //////////////////// QCPPaintBufferPixmap
0636 ////////////////////////////////////////////////////////////////////////////////////////////////////
0637 
0638 /*! \class QCPPaintBufferPixmap
0639   \brief A paint buffer based on QPixmap, using software raster rendering
0640 
0641   This paint buffer is the default and fall-back paint buffer which uses software rendering and
0642   QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
0643 */
0644 
0645 /*!
0646   Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
0647   applicable.
0648 */
0649 QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
0650   QCPAbstractPaintBuffer(size, devicePixelRatio)
0651 {
0652   QCPPaintBufferPixmap::reallocateBuffer();
0653 }
0654 
0655 QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
0656 {
0657 }
0658 
0659 /* inherits documentation from base class */
0660 QCPPainter *QCPPaintBufferPixmap::startPainting()
0661 {
0662   QCPPainter *result = new QCPPainter(&mBuffer);
0663 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
0664   result->setRenderHint(QPainter::HighQualityAntialiasing);
0665 #endif
0666   return result;
0667 }
0668 
0669 /* inherits documentation from base class */
0670 void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
0671 {
0672   if (painter && painter->isActive())
0673     painter->drawPixmap(0, 0, mBuffer);
0674   else
0675     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
0676 }
0677 
0678 /* inherits documentation from base class */
0679 void QCPPaintBufferPixmap::clear(const QColor &color)
0680 {
0681   mBuffer.fill(color);
0682 }
0683 
0684 /* inherits documentation from base class */
0685 void QCPPaintBufferPixmap::reallocateBuffer()
0686 {
0687   setInvalidated();
0688   if (!qFuzzyCompare(1.0, mDevicePixelRatio))
0689   {
0690 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
0691     mBuffer = QPixmap(mSize*mDevicePixelRatio);
0692     mBuffer.setDevicePixelRatio(mDevicePixelRatio);
0693 #else
0694     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
0695     mDevicePixelRatio = 1.0;
0696     mBuffer = QPixmap(mSize);
0697 #endif
0698   } else
0699   {
0700     mBuffer = QPixmap(mSize);
0701   }
0702 }
0703 
0704 
0705 #ifdef QCP_OPENGL_PBUFFER
0706 ////////////////////////////////////////////////////////////////////////////////////////////////////
0707 //////////////////// QCPPaintBufferGlPbuffer
0708 ////////////////////////////////////////////////////////////////////////////////////////////////////
0709 
0710 /*! \class QCPPaintBufferGlPbuffer
0711   \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
0712 
0713   This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
0714   rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
0715   (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
0716 
0717   The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
0718   supported by the system.
0719 */
0720 
0721 /*!
0722   Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
0723   devicePixelRatio, if applicable.
0724 
0725   The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
0726   result in higher quality antialiasing. If the specified \a multisamples value exceeds the
0727   capability of the graphics hardware, the highest supported multisampling is used.
0728 */
0729 QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
0730   QCPAbstractPaintBuffer(size, devicePixelRatio),
0731   mGlPBuffer(0),
0732   mMultisamples(qMax(0, multisamples))
0733 {
0734   QCPPaintBufferGlPbuffer::reallocateBuffer();
0735 }
0736 
0737 QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
0738 {
0739   if (mGlPBuffer)
0740     delete mGlPBuffer;
0741 }
0742 
0743 /* inherits documentation from base class */
0744 QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
0745 {
0746   if (!mGlPBuffer->isValid())
0747   {
0748     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
0749     return 0;
0750   }
0751   
0752   QCPPainter *result = new QCPPainter(mGlPBuffer);
0753   result->setRenderHint(QPainter::HighQualityAntialiasing);
0754   return result;
0755 }
0756 
0757 /* inherits documentation from base class */
0758 void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
0759 {
0760   if (!painter || !painter->isActive())
0761   {
0762     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
0763     return;
0764   }
0765   if (!mGlPBuffer->isValid())
0766   {
0767     qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
0768     return;
0769   }
0770   painter->drawImage(0, 0, mGlPBuffer->toImage());
0771 }
0772 
0773 /* inherits documentation from base class */
0774 void QCPPaintBufferGlPbuffer::clear(const QColor &color)
0775 {
0776   if (mGlPBuffer->isValid())
0777   {
0778     mGlPBuffer->makeCurrent();
0779     glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
0780     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
0781     mGlPBuffer->doneCurrent();
0782   } else
0783     qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
0784 }
0785 
0786 /* inherits documentation from base class */
0787 void QCPPaintBufferGlPbuffer::reallocateBuffer()
0788 {
0789   if (mGlPBuffer)
0790     delete mGlPBuffer;
0791   
0792   QGLFormat format;
0793   format.setAlpha(true);
0794   format.setSamples(mMultisamples);
0795   mGlPBuffer = new QGLPixelBuffer(mSize, format);
0796 }
0797 #endif // QCP_OPENGL_PBUFFER
0798 
0799 
0800 #ifdef QCP_OPENGL_FBO
0801 ////////////////////////////////////////////////////////////////////////////////////////////////////
0802 //////////////////// QCPPaintBufferGlFbo
0803 ////////////////////////////////////////////////////////////////////////////////////////////////////
0804 
0805 /*! \class QCPPaintBufferGlFbo
0806   \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
0807 
0808   This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
0809   rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
0810   higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
0811 
0812   The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
0813   supported by the system.
0814 */
0815 
0816 /*!
0817   Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
0818   if applicable.
0819 
0820   All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
0821   externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
0822   QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
0823   instance.
0824 */
0825 QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
0826   QCPAbstractPaintBuffer(size, devicePixelRatio),
0827   mGlContext(glContext),
0828   mGlPaintDevice(glPaintDevice),
0829   mGlFrameBuffer(0)
0830 {
0831   QCPPaintBufferGlFbo::reallocateBuffer();
0832 }
0833 
0834 QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
0835 {
0836   if (mGlFrameBuffer)
0837     delete mGlFrameBuffer;
0838 }
0839 
0840 /* inherits documentation from base class */
0841 QCPPainter *QCPPaintBufferGlFbo::startPainting()
0842 {
0843   QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
0844   QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
0845   if (!paintDevice)
0846   {
0847     qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
0848     return 0;
0849   }
0850   if (!context)
0851   {
0852     qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
0853     return 0;
0854   }
0855   if (!mGlFrameBuffer)
0856   {
0857     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
0858     return 0;
0859   }
0860   
0861   if (QOpenGLContext::currentContext() != context.data())
0862     context->makeCurrent(context->surface());
0863   mGlFrameBuffer->bind();
0864   QCPPainter *result = new QCPPainter(paintDevice.data());
0865 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
0866   result->setRenderHint(QPainter::HighQualityAntialiasing);
0867 #endif
0868   return result;
0869 }
0870 
0871 /* inherits documentation from base class */
0872 void QCPPaintBufferGlFbo::donePainting()
0873 {
0874   if (mGlFrameBuffer && mGlFrameBuffer->isBound())
0875     mGlFrameBuffer->release();
0876   else
0877     qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
0878 }
0879 
0880 /* inherits documentation from base class */
0881 void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
0882 {
0883   if (!painter || !painter->isActive())
0884   {
0885     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
0886     return;
0887   }
0888   if (!mGlFrameBuffer)
0889   {
0890     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
0891     return;
0892   }
0893   painter->drawImage(0, 0, mGlFrameBuffer->toImage());
0894 }
0895 
0896 /* inherits documentation from base class */
0897 void QCPPaintBufferGlFbo::clear(const QColor &color)
0898 {
0899   QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
0900   if (!context)
0901   {
0902     qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
0903     return;
0904   }
0905   if (!mGlFrameBuffer)
0906   {
0907     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
0908     return;
0909   }
0910   
0911   if (QOpenGLContext::currentContext() != context.data())
0912     context->makeCurrent(context->surface());
0913   mGlFrameBuffer->bind();
0914   glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
0915   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
0916   mGlFrameBuffer->release();
0917 }
0918 
0919 /* inherits documentation from base class */
0920 void QCPPaintBufferGlFbo::reallocateBuffer()
0921 {
0922   // release and delete possibly existing framebuffer:
0923   if (mGlFrameBuffer)
0924   {
0925     if (mGlFrameBuffer->isBound())
0926       mGlFrameBuffer->release();
0927     delete mGlFrameBuffer;
0928     mGlFrameBuffer = 0;
0929   }
0930   
0931   QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
0932   QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
0933   if (!paintDevice)
0934   {
0935     qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
0936     return;
0937   }
0938   if (!context)
0939   {
0940     qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
0941     return;
0942   }
0943   
0944   // create new fbo with appropriate size:
0945   context->makeCurrent(context->surface());
0946   QOpenGLFramebufferObjectFormat frameBufferFormat;
0947   frameBufferFormat.setSamples(context->format().samples());
0948   frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
0949   mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
0950   if (paintDevice->size() != mSize*mDevicePixelRatio)
0951     paintDevice->setSize(mSize*mDevicePixelRatio);
0952 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
0953   paintDevice->setDevicePixelRatio(mDevicePixelRatio);
0954 #endif
0955 }
0956 #endif // QCP_OPENGL_FBO
0957 /* end of 'src/paintbuffer.cpp' */
0958 
0959 
0960 /* including file 'src/layer.cpp'           */
0961 /* modified 2021-03-29T02:30:44, size 37615 */
0962 
0963 ////////////////////////////////////////////////////////////////////////////////////////////////////
0964 //////////////////// QCPLayer
0965 ////////////////////////////////////////////////////////////////////////////////////////////////////
0966 
0967 /*! \class QCPLayer
0968   \brief A layer that may contain objects, to control the rendering order
0969 
0970   The Layering system of QCustomPlot is the mechanism to control the rendering order of the
0971   elements inside the plot.
0972 
0973   It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
0974   one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
0975   QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
0976   bottom to top and successively draws the layerables of the layers into the paint buffer(s).
0977 
0978   A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
0979   class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
0980 
0981   \section qcplayer-defaultlayers Default layers
0982 
0983   Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
0984   "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
0985   selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
0986   the default axes and legend, so they will be drawn above plottables. In the middle, there is the
0987   "main" layer. It is initially empty and set as the current layer (see
0988   QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
0989   layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
0990   tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
0991   everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
0992   course, the layer affiliation of the individual objects can be changed as required (\ref
0993   QCPLayerable::setLayer).
0994 
0995   \section qcplayer-ordering Controlling the rendering order via layers
0996 
0997   Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
0998   you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
0999   current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
1000   objects normally. They will be placed on the new layer automatically, due to the current layer
1001   setting. Alternatively you could have also ignored the current layer setting and just moved the
1002   objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
1003 
1004   It is also possible to move whole layers. For example, If you want the grid to be shown in front
1005   of all plottables/items on the "main" layer, just move it above "main" with
1006   QCustomPlot::moveLayer.
1007 
1008   The rendering order within one layer is simply by order of creation or insertion. The item
1009   created last (or added last to the layer), is drawn on top of all other objects on that layer.
1010 
1011   When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
1012   the deleted layer, see QCustomPlot::removeLayer.
1013 
1014   \section qcplayer-buffering Replotting only a specific layer
1015 
1016   If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
1017   layer by calling \ref replot. In certain situations this can provide better replot performance,
1018   compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
1019   initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
1020   QCustomPlot instance is the "overlay" layer, containing the selection rect.
1021 */
1022 
1023 /* start documentation of inline functions */
1024 
1025 /*! \fn QList<QCPLayerable*> QCPLayer::children() const
1026   
1027   Returns a list of all layerables on this layer. The order corresponds to the rendering order:
1028   layerables with higher indices are drawn above layerables with lower indices.
1029 */
1030 
1031 /*! \fn int QCPLayer::index() const
1032   
1033   Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
1034   accessed via \ref QCustomPlot::layer.
1035   
1036   Layers with higher indices will be drawn above layers with lower indices.
1037 */
1038 
1039 /* end documentation of inline functions */
1040 
1041 /*!
1042   Creates a new QCPLayer instance.
1043   
1044   Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
1045   
1046   \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
1047   This check is only performed by \ref QCustomPlot::addLayer.
1048 */
1049 QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
1050   QObject(parentPlot),
1051   mParentPlot(parentPlot),
1052   mName(layerName),
1053   mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
1054   mVisible(true),
1055   mMode(lmLogical)
1056 {
1057   // Note: no need to make sure layerName is unique, because layer
1058   // management is done with QCustomPlot functions.
1059 }
1060 
1061 QCPLayer::~QCPLayer()
1062 {
1063   // If child layerables are still on this layer, detach them, so they don't try to reach back to this
1064   // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
1065   // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
1066   // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
1067   
1068   while (!mChildren.isEmpty())
1069     mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild()
1070   
1071   if (mParentPlot->currentLayer() == this)
1072     qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand.";
1073 }
1074 
1075 /*!
1076   Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
1077   layer will be invisible.
1078 
1079   This function doesn't change the visibility property of the layerables (\ref
1080   QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
1081   visibility of the parent layer into account.
1082 */
1083 void QCPLayer::setVisible(bool visible)
1084 {
1085   mVisible = visible;
1086 }
1087 
1088 /*!
1089   Sets the rendering mode of this layer.
1090 
1091   If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
1092   the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
1093   QCPLayer::replot, without needing to replot all other layers.
1094 
1095   Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
1096   and can't be replotted individually.
1097 
1098   Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
1099   layers below, above and for the layer itself. This increases the memory consumption and
1100   (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
1101   you should carefully choose which layers benefit from having their own paint buffer. A typical
1102   example would be a layer which contains certain layerables (e.g. items) that need to be changed
1103   and thus replotted regularly, while all other layerables on other layers stay static. By default,
1104   only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
1105   rect.
1106 
1107   \see replot
1108 */
1109 void QCPLayer::setMode(QCPLayer::LayerMode mode)
1110 {
1111   if (mMode != mode)
1112   {
1113     mMode = mode;
1114     if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
1115       pb->setInvalidated();
1116   }
1117 }
1118 
1119 /*! \internal
1120 
1121   Draws the contents of this layer with the provided \a painter.
1122 
1123   \see replot, drawToPaintBuffer
1124 */
1125 void QCPLayer::draw(QCPPainter *painter)
1126 {
1127   foreach (QCPLayerable *child, mChildren)
1128   {
1129     if (child->realVisibility())
1130     {
1131       painter->save();
1132       painter->setClipRect(child->clipRect().translated(0, -1));
1133       child->applyDefaultAntialiasingHint(painter);
1134       child->draw(painter);
1135       painter->restore();
1136     }
1137   }
1138 }
1139 
1140 /*! \internal
1141 
1142   Draws the contents of this layer into the paint buffer which is associated with this layer. The
1143   association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
1144   QCustomPlot::setupPaintBuffers).
1145 
1146   \see draw
1147 */
1148 void QCPLayer::drawToPaintBuffer()
1149 {
1150   if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
1151   {
1152     if (QCPPainter *painter = pb->startPainting())
1153     {
1154       if (painter->isActive())
1155         draw(painter);
1156       else
1157         qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
1158       delete painter;
1159       pb->donePainting();
1160     } else
1161       qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter";
1162   } else
1163     qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
1164 }
1165 
1166 /*!
1167   If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
1168   the layerables on this specific layer, without the need to replot all other layers (as a call to
1169   \ref QCustomPlot::replot would do).
1170 
1171   QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
1172   or any layerable-layer-association has changed since the last full replot and any other paint
1173   buffers were thus invalidated.
1174 
1175   If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
1176   the parent QCustomPlot instance.
1177 
1178   \see draw
1179 */
1180 void QCPLayer::replot()
1181 {
1182   if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
1183   {
1184     if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
1185     {
1186       pb->clear(Qt::transparent);
1187       drawToPaintBuffer();
1188       pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag
1189       mParentPlot->update();
1190     } else
1191       qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
1192   } else
1193     mParentPlot->replot();
1194 }
1195 
1196 /*! \internal
1197   
1198   Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
1199   be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
1200   
1201   This function does not change the \a mLayer member of \a layerable to this layer. (Use
1202   QCPLayerable::setLayer to change the layer of an object, not this function.)
1203   
1204   \see removeChild
1205 */
1206 void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
1207 {
1208   if (!mChildren.contains(layerable))
1209   {
1210     if (prepend)
1211       mChildren.prepend(layerable);
1212     else
1213       mChildren.append(layerable);
1214     if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
1215       pb->setInvalidated();
1216   } else
1217     qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
1218 }
1219 
1220 /*! \internal
1221   
1222   Removes the \a layerable from the list of this layer.
1223   
1224   This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
1225   to change the layer of an object, not this function.)
1226   
1227   \see addChild
1228 */
1229 void QCPLayer::removeChild(QCPLayerable *layerable)
1230 {
1231   if (mChildren.removeOne(layerable))
1232   {
1233     if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
1234       pb->setInvalidated();
1235   } else
1236     qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
1237 }
1238 
1239 
1240 ////////////////////////////////////////////////////////////////////////////////////////////////////
1241 //////////////////// QCPLayerable
1242 ////////////////////////////////////////////////////////////////////////////////////////////////////
1243 
1244 /*! \class QCPLayerable
1245   \brief Base class for all drawable objects
1246   
1247   This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
1248   etc.
1249 
1250   Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
1251   the layers accordingly.
1252   
1253   For details about the layering mechanism, see the QCPLayer documentation.
1254 */
1255 
1256 /* start documentation of inline functions */
1257 
1258 /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
1259  
1260   Returns the parent layerable of this layerable. The parent layerable is used to provide
1261   visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
1262   only get drawn if their parent layerables are visible, too.
1263   
1264   Note that a parent layerable is not necessarily also the QObject parent for memory management.
1265   Further, a layerable doesn't always have a parent layerable, so this function may return \c
1266   nullptr.
1267   
1268   A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
1269   set manually by the user.
1270 */
1271 
1272 /* end documentation of inline functions */
1273 /* start documentation of pure virtual functions */
1274 
1275 /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
1276   \internal
1277   
1278   This function applies the default antialiasing setting to the specified \a painter, using the
1279   function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
1280   \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
1281   setting may be specified individually, this function should set the antialiasing state of the
1282   most prominent entity. In this case however, the \ref draw function usually calls the specialized
1283   versions of this function before drawing each entity, effectively overriding the setting of the
1284   default antialiasing hint.
1285   
1286   <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
1287   line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
1288   QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
1289   the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
1290   antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
1291   QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
1292   calls the respective specialized applyAntialiasingHint function.
1293   
1294   <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
1295   setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
1296   all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
1297   respective layerable subclass.) Consequently it only has the normal
1298   QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
1299   care about setting any antialiasing states, because the default antialiasing hint is already set
1300   on the painter when the \ref draw function is called, and that's the state it wants to draw the
1301   line with.
1302 */
1303 
1304 /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
1305   \internal
1306   
1307   This function draws the layerable with the specified \a painter. It is only called by
1308   QCustomPlot, if the layerable is visible (\ref setVisible).
1309   
1310   Before this function is called, the painter's antialiasing state is set via \ref
1311   applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
1312   set to \ref clipRect.
1313 */
1314 
1315 /* end documentation of pure virtual functions */
1316 /* start documentation of signals */
1317 
1318 /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
1319   
1320   This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
1321   a different layer.
1322   
1323   \see setLayer
1324 */
1325 
1326 /* end documentation of signals */
1327 
1328 /*!
1329   Creates a new QCPLayerable instance.
1330   
1331   Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
1332   derived classes.
1333   
1334   If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
1335   targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
1336   QCustomPlot::setCurrentLayer).
1337   
1338   It is possible to provide \c nullptr as \a plot. In that case, you should assign a parent plot at
1339   a later time with \ref initializeParentPlot.
1340   
1341   The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
1342   parents are mainly used to control visibility in a hierarchy of layerables. This means a
1343   layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
1344   parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
1345   plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
1346   QCPLayerable subclasses, to guarantee a working destruction hierarchy.
1347 */
1348 QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
1349   QObject(plot),
1350   mVisible(true),
1351   mParentPlot(plot),
1352   mParentLayerable(parentLayerable),
1353   mLayer(nullptr),
1354   mAntialiased(true)
1355 {
1356   if (mParentPlot)
1357   {
1358     if (targetLayer.isEmpty())
1359       setLayer(mParentPlot->currentLayer());
1360     else if (!setLayer(targetLayer))
1361       qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
1362   }
1363 }
1364 
1365 QCPLayerable::~QCPLayerable()
1366 {
1367   if (mLayer)
1368   {
1369     mLayer->removeChild(this);
1370     mLayer = nullptr;
1371   }
1372 }
1373 
1374 /*!
1375   Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
1376   on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
1377   possible.
1378 */
1379 void QCPLayerable::setVisible(bool on)
1380 {
1381   mVisible = on;
1382 }
1383 
1384 /*!
1385   Sets the \a layer of this layerable object. The object will be placed on top of the other objects
1386   already on \a layer.
1387   
1388   If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
1389   interact/receive events).
1390   
1391   Returns true if the layer of this layerable was successfully changed to \a layer.
1392 */
1393 bool QCPLayerable::setLayer(QCPLayer *layer)
1394 {
1395   return moveToLayer(layer, false);
1396 }
1397 
1398 /*! \overload
1399   Sets the layer of this layerable object by name
1400   
1401   Returns true on success, i.e. if \a layerName is a valid layer name.
1402 */
1403 bool QCPLayerable::setLayer(const QString &layerName)
1404 {
1405   if (!mParentPlot)
1406   {
1407     qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
1408     return false;
1409   }
1410   if (QCPLayer *layer = mParentPlot->layer(layerName))
1411   {
1412     return setLayer(layer);
1413   } else
1414   {
1415     qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
1416     return false;
1417   }
1418 }
1419 
1420 /*!
1421   Sets whether this object will be drawn antialiased or not.
1422   
1423   Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
1424   QCustomPlot::setNotAntialiasedElements.
1425 */
1426 void QCPLayerable::setAntialiased(bool enabled)
1427 {
1428   mAntialiased = enabled;
1429 }
1430 
1431 /*!
1432   Returns whether this layerable is visible, taking the visibility of the layerable parent and the
1433   visibility of this layerable's layer into account. This is the method that is consulted to decide
1434   whether a layerable shall be drawn or not.
1435   
1436   If this layerable has a direct layerable parent (usually set via hierarchies implemented in
1437   subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
1438   layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
1439   true.
1440 */
1441 bool QCPLayerable::realVisibility() const
1442 {
1443   return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
1444 }
1445 
1446 /*!
1447   This function is used to decide whether a click hits a layerable object or not.
1448 
1449   \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
1450   shortest pixel distance of this point to the object. If the object is either invisible or the
1451   distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
1452   object is not selectable, -1.0 is returned, too.
1453 
1454   If the object is represented not by single lines but by an area like a \ref QCPItemText or the
1455   bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
1456   these cases this function thus returns a constant value greater zero but still below the parent
1457   plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
1458   
1459   Providing a constant value for area objects allows selecting line objects even when they are
1460   obscured by such area objects, by clicking close to the lines (i.e. closer than
1461   0.99*selectionTolerance).
1462   
1463   The actual setting of the selection state is not done by this function. This is handled by the
1464   parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
1465   via the \ref selectEvent/\ref deselectEvent methods.
1466   
1467   \a details is an optional output parameter. Every layerable subclass may place any information
1468   in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
1469   decides on the basis of this selectTest call, that the object was successfully selected. The
1470   subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
1471   objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
1472   is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
1473   placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
1474   selected doesn't have to be done a second time for a single selection operation.
1475   
1476   In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a
1477   details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos.
1478   
1479   You may pass \c nullptr as \a details to indicate that you are not interested in those selection
1480   details.
1481   
1482   \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions,
1483   QCPAbstractPlottable1D::selectTestRect
1484 */
1485 double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
1486 {
1487   Q_UNUSED(pos)
1488   Q_UNUSED(onlySelectable)
1489   Q_UNUSED(details)
1490   return -1.0;
1491 }
1492 
1493 /*! \internal
1494   
1495   Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
1496   passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot
1497   to another one.
1498   
1499   Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function
1500   does not make \a parentPlot the QObject-parent of this layerable. If you want this, call
1501   QObject::setParent(\a parentPlot) in addition to this function.
1502   
1503   Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
1504   make the layerable appear on the QCustomPlot.
1505   
1506   The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
1507   so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
1508   QCPLayout does).
1509 */
1510 void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
1511 {
1512   if (mParentPlot)
1513   {
1514     qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
1515     return;
1516   }
1517   
1518   if (!parentPlot)
1519     qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
1520   
1521   mParentPlot = parentPlot;
1522   parentPlotInitialized(mParentPlot);
1523 }
1524 
1525 /*! \internal
1526   
1527   Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
1528   become the QObject-parent (for memory management) of this layerable.
1529   
1530   The parent layerable has influence on the return value of the \ref realVisibility method. Only
1531   layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
1532   drawn.
1533   
1534   \see realVisibility
1535 */
1536 void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
1537 {
1538   mParentLayerable = parentLayerable;
1539 }
1540 
1541 /*! \internal
1542   
1543   Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
1544   the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
1545   false, the object will be appended.
1546   
1547   Returns true on success, i.e. if \a layer is a valid layer.
1548 */
1549 bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
1550 {
1551   if (layer && !mParentPlot)
1552   {
1553     qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
1554     return false;
1555   }
1556   if (layer && layer->parentPlot() != mParentPlot)
1557   {
1558     qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
1559     return false;
1560   }
1561   
1562   QCPLayer *oldLayer = mLayer;
1563   if (mLayer)
1564     mLayer->removeChild(this);
1565   mLayer = layer;
1566   if (mLayer)
1567     mLayer->addChild(this, prepend);
1568   if (mLayer != oldLayer)
1569     emit layerChanged(mLayer);
1570   return true;
1571 }
1572 
1573 /*! \internal
1574 
1575   Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
1576   localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
1577   QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
1578   controlled via \a overrideElement.
1579 */
1580 void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
1581 {
1582   if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
1583     painter->setAntialiasing(false);
1584   else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
1585     painter->setAntialiasing(true);
1586   else
1587     painter->setAntialiasing(localAntialiased);
1588 }
1589 
1590 /*! \internal
1591 
1592   This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
1593   of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor,
1594   and the parent plot is set at a later time.
1595   
1596   For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
1597   QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
1598   element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
1599   propagate the parent plot to all the children of the hierarchy, the top level element then uses
1600   this function to pass the parent plot on to its child elements.
1601   
1602   The default implementation does nothing.
1603   
1604   \see initializeParentPlot
1605 */
1606 void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
1607 {
1608    Q_UNUSED(parentPlot)
1609 }
1610 
1611 /*! \internal
1612 
1613   Returns the selection category this layerable shall belong to. The selection category is used in
1614   conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
1615   which aren't.
1616   
1617   Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
1618   QCP::iSelectOther. This is what the default implementation returns.
1619   
1620   \see QCustomPlot::setInteractions
1621 */
1622 QCP::Interaction QCPLayerable::selectionCategory() const
1623 {
1624   return QCP::iSelectOther;
1625 }
1626 
1627 /*! \internal
1628   
1629   Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
1630   parent QCustomPlot. Specific subclasses may reimplement this function to provide different
1631   clipping rects.
1632   
1633   The returned clipping rect is set on the painter before the draw function of the respective
1634   object is called.
1635 */
1636 QRect QCPLayerable::clipRect() const
1637 {
1638   if (mParentPlot)
1639     return mParentPlot->viewport();
1640   else
1641     return {};
1642 }
1643 
1644 /*! \internal
1645   
1646   This event is called when the layerable shall be selected, as a consequence of a click by the
1647   user. Subclasses should react to it by setting their selection state appropriately. The default
1648   implementation does nothing.
1649   
1650   \a event is the mouse event that caused the selection. \a additive indicates, whether the user
1651   was holding the multi-select-modifier while performing the selection (see \ref
1652   QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
1653   (i.e. become selected when unselected and unselected when selected).
1654   
1655   Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
1656   returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
1657   The \a details data you output from \ref selectTest is fed back via \a details here. You may
1658   use it to transport any kind of information from the selectTest to the possibly subsequent
1659   selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
1660   that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
1661   to do the calculation again to find out which part was actually clicked.
1662   
1663   \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
1664   set the value either to true or false, depending on whether the selection state of this layerable
1665   was actually changed. For layerables that only are selectable as a whole and not in parts, this
1666   is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
1667   selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
1668   layerable was previously unselected and now is switched to the selected state.
1669   
1670   \see selectTest, deselectEvent
1671 */
1672 void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
1673 {
1674   Q_UNUSED(event)
1675   Q_UNUSED(additive)
1676   Q_UNUSED(details)
1677   Q_UNUSED(selectionStateChanged)
1678 }
1679 
1680 /*! \internal
1681   
1682   This event is called when the layerable shall be deselected, either as consequence of a user
1683   interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
1684   unsetting their selection appropriately.
1685   
1686   just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
1687   return true or false when the selection state of this layerable has changed or not changed,
1688   respectively.
1689   
1690   \see selectTest, selectEvent
1691 */
1692 void QCPLayerable::deselectEvent(bool *selectionStateChanged)
1693 {
1694   Q_UNUSED(selectionStateChanged)
1695 }
1696 
1697 /*!
1698   This event gets called when the user presses a mouse button while the cursor is over the
1699   layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
1700   selectTest.
1701 
1702   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1703   event->pos(). The parameter \a details contains layerable-specific details about the hit, which
1704   were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
1705   like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
1706   \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
1707   SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
1708 
1709   QCustomPlot uses an event propagation system that works the same as Qt's system. If your
1710   layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
1711   its reimplementation, the event will be propagated to the next layerable in the stacking order.
1712 
1713   Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
1714   will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
1715   interaction (a "mouse interaction" in this context ends with the release).
1716 
1717   The default implementation does nothing except explicitly ignoring the event with \c
1718   event->ignore().
1719 
1720   \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
1721 */
1722 void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
1723 {
1724   Q_UNUSED(details)
1725   event->ignore();
1726 }
1727 
1728 /*!
1729   This event gets called when the user moves the mouse while holding a mouse button, after this
1730   layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
1731 
1732   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1733   event->pos(). The parameter \a startPos indicates the position where the initial \ref
1734   mousePressEvent occurred, that started the mouse interaction.
1735 
1736   The default implementation does nothing.
1737 
1738   \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
1739 */
1740 void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
1741 {
1742   Q_UNUSED(startPos)
1743   event->ignore();
1744 }
1745 
1746 /*!
1747   This event gets called when the user releases the mouse button, after this layerable has become
1748   the mouse grabber by accepting the preceding \ref mousePressEvent.
1749 
1750   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1751   event->pos(). The parameter \a startPos indicates the position where the initial \ref
1752   mousePressEvent occurred, that started the mouse interaction.
1753 
1754   The default implementation does nothing.
1755 
1756   \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
1757 */
1758 void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
1759 {
1760   Q_UNUSED(startPos)
1761   event->ignore();
1762 }
1763 
1764 /*!
1765   This event gets called when the user presses the mouse button a second time in a double-click,
1766   while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
1767   preceding call to \ref selectTest.
1768 
1769   The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
1770   case of a double-click, the event succession is
1771   <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
1772 
1773   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1774   event->pos(). The parameter \a details contains layerable-specific details about the hit, which
1775   were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
1776   like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
1777   \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
1778   SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
1779 
1780   Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
1781   it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
1782   and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
1783   with the release).
1784 
1785   The default implementation does nothing except explicitly ignoring the event with \c
1786   event->ignore().
1787 
1788   \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
1789 */
1790 void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
1791 {
1792   Q_UNUSED(details)
1793   event->ignore();
1794 }
1795 
1796 /*!
1797   This event gets called when the user turns the mouse scroll wheel while the cursor is over the
1798   layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
1799   selectTest.
1800 
1801   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1802   event->pos().
1803 
1804   The \c event->angleDelta() indicates how far the mouse wheel was turned, which is usually +/- 120
1805   for single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
1806   accumulate to one event, making the delta larger. On the other hand, if the wheel has very smooth
1807   steps or none at all, the delta may be smaller.
1808 
1809   The default implementation does nothing.
1810 
1811   \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
1812 */
1813 void QCPLayerable::wheelEvent(QWheelEvent *event)
1814 {
1815   event->ignore();
1816 }
1817 /* end of 'src/layer.cpp' */
1818 
1819 
1820 /* including file 'src/axis/range.cpp'      */
1821 /* modified 2021-03-29T02:30:44, size 12221 */
1822 
1823 ////////////////////////////////////////////////////////////////////////////////////////////////////
1824 //////////////////// QCPRange
1825 ////////////////////////////////////////////////////////////////////////////////////////////////////
1826 /*! \class QCPRange
1827   \brief Represents the range an axis is encompassing.
1828   
1829   contains a \a lower and \a upper double value and provides convenience input, output and
1830   modification functions.
1831   
1832   \see QCPAxis::setRange
1833 */
1834 
1835 /* start of documentation of inline functions */
1836 
1837 /*! \fn double QCPRange::size() const
1838 
1839   Returns the size of the range, i.e. \a upper-\a lower
1840 */
1841 
1842 /*! \fn double QCPRange::center() const
1843 
1844   Returns the center of the range, i.e. (\a upper+\a lower)*0.5
1845 */
1846 
1847 /*! \fn void QCPRange::normalize()
1848 
1849   Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
1850   swapped.
1851 */
1852 
1853 /*! \fn bool QCPRange::contains(double value) const
1854 
1855   Returns true when \a value lies within or exactly on the borders of the range.
1856 */
1857 
1858 /*! \fn QCPRange &QCPRange::operator+=(const double& value)
1859 
1860   Adds \a value to both boundaries of the range.
1861 */
1862 
1863 /*! \fn QCPRange &QCPRange::operator-=(const double& value)
1864 
1865   Subtracts \a value from both boundaries of the range.
1866 */
1867 
1868 /*! \fn QCPRange &QCPRange::operator*=(const double& value)
1869 
1870   Multiplies both boundaries of the range by \a value.
1871 */
1872 
1873 /*! \fn QCPRange &QCPRange::operator/=(const double& value)
1874 
1875   Divides both boundaries of the range by \a value.
1876 */
1877 
1878 /* end of documentation of inline functions */
1879 
1880 /*!
1881   Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
1882   intervals would cause errors due to the 11-bit exponent of double precision numbers,
1883   corresponding to a minimum magnitude of roughly 1e-308.
1884 
1885   \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
1886   values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
1887   prevent axis ranges from obtaining underflowing ranges.
1888 
1889   \see validRange, maxRange
1890 */
1891 const double QCPRange::minRange = 1e-280;
1892 
1893 /*!
1894   Maximum values (negative and positive) the range will accept in range-changing functions.
1895   Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
1896   corresponding to a maximum magnitude of roughly 1e308.
1897 
1898   \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
1899   values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
1900   prevent axis ranges from obtaining overflowing ranges.
1901 
1902   \see validRange, minRange
1903 */
1904 const double QCPRange::maxRange = 1e250;
1905 
1906 /*!
1907   Constructs a range with \a lower and \a upper set to zero.
1908 */
1909 QCPRange::QCPRange() :
1910   lower(0),
1911   upper(0)
1912 {
1913 }
1914 
1915 /*! \overload
1916 
1917   Constructs a range with the specified \a lower and \a upper values.
1918 
1919   The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
1920   smaller than \a upper, they will be swapped.
1921 */
1922 QCPRange::QCPRange(double lower, double upper) :
1923   lower(lower),
1924   upper(upper)
1925 {
1926   normalize();
1927 }
1928 
1929 /*! \overload
1930 
1931   Expands this range such that \a otherRange is contained in the new range. It is assumed that both
1932   this range and \a otherRange are normalized (see \ref normalize).
1933 
1934   If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
1935   of \a otherRange.
1936 
1937   If \a otherRange is already inside the current range, this function does nothing.
1938 
1939   \see expanded
1940 */
1941 void QCPRange::expand(const QCPRange &otherRange)
1942 {
1943   if (lower > otherRange.lower || qIsNaN(lower))
1944     lower = otherRange.lower;
1945   if (upper < otherRange.upper || qIsNaN(upper))
1946     upper = otherRange.upper;
1947 }
1948 
1949 /*! \overload
1950 
1951   Expands this range such that \a includeCoord is contained in the new range. It is assumed that
1952   this range is normalized (see \ref normalize).
1953 
1954   If this range contains NaN as lower or upper bound, the respective bound will be set to \a
1955   includeCoord.
1956 
1957   If \a includeCoord is already inside the current range, this function does nothing.
1958 
1959   \see expand
1960 */
1961 void QCPRange::expand(double includeCoord)
1962 {
1963   if (lower > includeCoord || qIsNaN(lower))
1964     lower = includeCoord;
1965   if (upper < includeCoord || qIsNaN(upper))
1966     upper = includeCoord;
1967 }
1968 
1969 
1970 /*! \overload
1971 
1972   Returns an expanded range that contains this and \a otherRange. It is assumed that both this
1973   range and \a otherRange are normalized (see \ref normalize).
1974 
1975   If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
1976   \a otherRange.
1977 
1978   \see expand
1979 */
1980 QCPRange QCPRange::expanded(const QCPRange &otherRange) const
1981 {
1982   QCPRange result = *this;
1983   result.expand(otherRange);
1984   return result;
1985 }
1986 
1987 /*! \overload
1988 
1989   Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
1990   range is normalized (see \ref normalize).
1991 
1992   If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
1993   includeCoord.
1994 
1995   \see expand
1996 */
1997 QCPRange QCPRange::expanded(double includeCoord) const
1998 {
1999   QCPRange result = *this;
2000   result.expand(includeCoord);
2001   return result;
2002 }
2003 
2004 /*!
2005   Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
2006   upperBound. If possible, the size of the current range is preserved in the process.
2007   
2008   If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
2009   QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
2010   QCPRange::maxRange.
2011 */
2012 QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
2013 {
2014   if (lowerBound > upperBound)
2015     qSwap(lowerBound, upperBound);
2016   
2017   QCPRange result(lower, upper);
2018   if (result.lower < lowerBound)
2019   {
2020     result.lower = lowerBound;
2021     result.upper = lowerBound + size();
2022     if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
2023       result.upper = upperBound;
2024   } else if (result.upper > upperBound)
2025   {
2026     result.upper = upperBound;
2027     result.lower = upperBound - size();
2028     if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
2029       result.lower = lowerBound;
2030   }
2031   
2032   return result;
2033 }
2034 
2035 /*!
2036   Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
2037   the range won't span the positive and negative sign domain, i.e. contain zero. Further
2038   \a lower will always be numerically smaller (or equal) to \a upper.
2039   
2040   If the original range does span positive and negative sign domains or contains zero,
2041   the returned range will try to approximate the original range as good as possible.
2042   If the positive interval of the original range is wider than the negative interval, the
2043   returned range will only contain the positive interval, with lower bound set to \a rangeFac or
2044   \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
2045   is wider than the positive interval, this time by changing the \a upper bound.
2046 */
2047 QCPRange QCPRange::sanitizedForLogScale() const
2048 {
2049   double rangeFac = 1e-3;
2050   QCPRange sanitizedRange(lower, upper);
2051   sanitizedRange.normalize();
2052   // can't have range spanning negative and positive values in log plot, so change range to fix it
2053   //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
2054   if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
2055   {
2056     // case lower is 0
2057     if (rangeFac < sanitizedRange.upper*rangeFac)
2058       sanitizedRange.lower = rangeFac;
2059     else
2060       sanitizedRange.lower = sanitizedRange.upper*rangeFac;
2061   } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
2062   else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
2063   {
2064     // case upper is 0
2065     if (-rangeFac > sanitizedRange.lower*rangeFac)
2066       sanitizedRange.upper = -rangeFac;
2067     else
2068       sanitizedRange.upper = sanitizedRange.lower*rangeFac;
2069   } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
2070   {
2071     // find out whether negative or positive interval is wider to decide which sign domain will be chosen
2072     if (-sanitizedRange.lower > sanitizedRange.upper)
2073     {
2074       // negative is wider, do same as in case upper is 0
2075       if (-rangeFac > sanitizedRange.lower*rangeFac)
2076         sanitizedRange.upper = -rangeFac;
2077       else
2078         sanitizedRange.upper = sanitizedRange.lower*rangeFac;
2079     } else
2080     {
2081       // positive is wider, do same as in case lower is 0
2082       if (rangeFac < sanitizedRange.upper*rangeFac)
2083         sanitizedRange.lower = rangeFac;
2084       else
2085         sanitizedRange.lower = sanitizedRange.upper*rangeFac;
2086     }
2087   }
2088   // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
2089   return sanitizedRange;
2090 }
2091 
2092 /*!
2093   Returns a sanitized version of the range. Sanitized means for linear scales, that
2094   \a lower will always be numerically smaller (or equal) to \a upper.
2095 */
2096 QCPRange QCPRange::sanitizedForLinScale() const
2097 {
2098   QCPRange sanitizedRange(lower, upper);
2099   sanitizedRange.normalize();
2100   return sanitizedRange;
2101 }
2102 
2103 /*!
2104   Checks, whether the specified range is within valid bounds, which are defined
2105   as QCPRange::maxRange and QCPRange::minRange.
2106   A valid range means:
2107   \li range bounds within -maxRange and maxRange
2108   \li range size above minRange
2109   \li range size below maxRange
2110 */
2111 bool QCPRange::validRange(double lower, double upper)
2112 {
2113   return (lower > -maxRange &&
2114           upper < maxRange &&
2115           qAbs(lower-upper) > minRange &&
2116           qAbs(lower-upper) < maxRange &&
2117           !(lower > 0 && qIsInf(upper/lower)) &&
2118           !(upper < 0 && qIsInf(lower/upper)));
2119 }
2120 
2121 /*!
2122   \overload
2123   Checks, whether the specified range is within valid bounds, which are defined
2124   as QCPRange::maxRange and QCPRange::minRange.
2125   A valid range means:
2126   \li range bounds within -maxRange and maxRange
2127   \li range size above minRange
2128   \li range size below maxRange
2129 */
2130 bool QCPRange::validRange(const QCPRange &range)
2131 {
2132   return (range.lower > -maxRange &&
2133           range.upper < maxRange &&
2134           qAbs(range.lower-range.upper) > minRange &&
2135           qAbs(range.lower-range.upper) < maxRange &&
2136           !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
2137           !(range.upper < 0 && qIsInf(range.lower/range.upper)));
2138 }
2139 /* end of 'src/axis/range.cpp' */
2140 
2141 
2142 /* including file 'src/selection.cpp'       */
2143 /* modified 2021-03-29T02:30:44, size 21837 */
2144 
2145 ////////////////////////////////////////////////////////////////////////////////////////////////////
2146 //////////////////// QCPDataRange
2147 ////////////////////////////////////////////////////////////////////////////////////////////////////
2148 
2149 /*! \class QCPDataRange
2150   \brief Describes a data range given by begin and end index
2151   
2152   QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
2153   of a contiguous set of data points. The \a end index corresponds to the data point just after the
2154   last data point of the data range, like in standard iterators.
2155 
2156   Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
2157   modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
2158   used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
2159   QCPDataSelection is thus used.
2160   
2161   Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
2162   e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
2163   contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
2164   used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
2165   \ref QCPDataSelection.
2166   
2167   %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
2168   QCPDataRange.
2169   
2170   \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
2171   in floating point plot coordinates, e.g. the current axis range.
2172 */
2173 
2174 /* start documentation of inline functions */
2175 
2176 /*! \fn int QCPDataRange::size() const
2177   
2178   Returns the number of data points described by this data range. This is equal to the end index
2179   minus the begin index.
2180   
2181   \see length
2182 */
2183 
2184 /*! \fn int QCPDataRange::length() const
2185   
2186   Returns the number of data points described by this data range. Equivalent to \ref size.
2187 */
2188 
2189 /*! \fn void QCPDataRange::setBegin(int begin)
2190   
2191   Sets the begin of this data range. The \a begin index points to the first data point that is part
2192   of the data range.
2193   
2194   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2195   
2196   \see setEnd
2197 */
2198 
2199 /*! \fn void QCPDataRange::setEnd(int end)
2200   
2201   Sets the end of this data range. The \a end index points to the data point just after the last
2202   data point that is part of the data range.
2203   
2204   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2205   
2206   \see setBegin
2207 */
2208 
2209 /*! \fn bool QCPDataRange::isValid() const
2210   
2211   Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
2212   an end index greater or equal to the begin index.
2213   
2214   \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
2215   (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
2216   methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
2217   invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
2218   (\ref isEmpty), since its \ref length can be negative and thus non-zero.
2219 */
2220 
2221 /*! \fn bool QCPDataRange::isEmpty() const
2222   
2223   Returns whether this range is empty, i.e. whether its begin index equals its end index.
2224   
2225   \see size, length
2226 */
2227 
2228 /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
2229   
2230   Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
2231   indices, respectively.
2232 */
2233 
2234 /* end documentation of inline functions */
2235 
2236 /*!
2237   Creates an empty QCPDataRange, with begin and end set to 0.
2238 */
2239 QCPDataRange::QCPDataRange() :
2240   mBegin(0),
2241   mEnd(0)
2242 {
2243 }
2244 
2245 /*!
2246   Creates a QCPDataRange, initialized with the specified \a begin and \a end.
2247   
2248   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2249 */
2250 QCPDataRange::QCPDataRange(int begin, int end) :
2251   mBegin(begin),
2252   mEnd(end)
2253 {
2254 }
2255 
2256 /*!
2257   Returns a data range that matches this data range, except that parts exceeding \a other are
2258   excluded.
2259   
2260   This method is very similar to \ref intersection, with one distinction: If this range and the \a
2261   other range share no intersection, the returned data range will be empty with begin and end set
2262   to the respective boundary side of \a other, at which this range is residing. (\ref intersection
2263   would just return a range with begin and end set to 0.)
2264 */
2265 QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
2266 {
2267   QCPDataRange result(intersection(other));
2268   if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
2269   {
2270     if (mEnd <= other.mBegin)
2271       result = QCPDataRange(other.mBegin, other.mBegin);
2272     else
2273       result = QCPDataRange(other.mEnd, other.mEnd);
2274   }
2275   return result;
2276 }
2277 
2278 /*!
2279   Returns a data range that contains both this data range as well as \a other.
2280 */
2281 QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
2282 {
2283   return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)};
2284 }
2285 
2286 /*!
2287   Returns the data range which is contained in both this data range and \a other.
2288   
2289   This method is very similar to \ref bounded, with one distinction: If this range and the \a other
2290   range share no intersection, the returned data range will be empty with begin and end set to 0.
2291   (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
2292   depending on which side this range is on.)
2293   
2294   \see QCPDataSelection::intersection
2295 */
2296 QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
2297 {
2298   QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
2299   if (result.isValid())
2300     return result;
2301   else
2302     return {};
2303 }
2304 
2305 /*!
2306   Returns whether this data range and \a other share common data points.
2307   
2308   \see intersection, contains
2309 */
2310 bool QCPDataRange::intersects(const QCPDataRange &other) const
2311 {
2312    return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
2313              (mEnd <= other.mBegin && mEnd < other.mEnd) );
2314 }
2315 
2316 /*!
2317   Returns whether all data points of \a other are also contained inside this data range.
2318   
2319   \see intersects
2320 */
2321 bool QCPDataRange::contains(const QCPDataRange &other) const
2322 {
2323   return mBegin <= other.mBegin && mEnd >= other.mEnd;
2324 }
2325 
2326 
2327 
2328 ////////////////////////////////////////////////////////////////////////////////////////////////////
2329 //////////////////// QCPDataSelection
2330 ////////////////////////////////////////////////////////////////////////////////////////////////////
2331 
2332 /*! \class QCPDataSelection
2333   \brief Describes a data set by holding multiple QCPDataRange instances
2334   
2335   QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
2336   disjoint) set of data selection.
2337   
2338   The data selection can be modified with addition and subtraction operators which take
2339   QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
2340   \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
2341   
2342   The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
2343   instances. QCPDataSelection automatically simplifies when using the addition/subtraction
2344   operators. The only case when \ref simplify is left to the user, is when calling \ref
2345   addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
2346   ranges will be added to the selection successively and the overhead for simplifying after each
2347   iteration shall be avoided. In this case, you should make sure to call \ref simplify after
2348   completing the operation.
2349   
2350   Use \ref enforceType to bring the data selection into a state complying with the constraints for
2351   selections defined in \ref QCP::SelectionType.
2352   
2353   %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
2354   QCPDataRange.
2355   
2356   \section qcpdataselection-iterating Iterating over a data selection
2357   
2358   As an example, the following code snippet calculates the average value of a graph's data
2359   \ref QCPAbstractPlottable::selection "selection":
2360   
2361   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
2362   
2363 */
2364 
2365 /* start documentation of inline functions */
2366 
2367 /*! \fn int QCPDataSelection::dataRangeCount() const
2368   
2369   Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
2370   dataRange via their index.
2371   
2372   \see dataRange, dataPointCount
2373 */
2374 
2375 /*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
2376   
2377   Returns all data ranges that make up the data selection. If the data selection is simplified (the
2378   usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
2379   index.
2380   
2381   \see dataRange
2382 */
2383 
2384 /*! \fn bool QCPDataSelection::isEmpty() const
2385   
2386   Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
2387   instance.
2388   
2389   \see dataRangeCount
2390 */
2391 
2392 /* end documentation of inline functions */
2393 
2394 /*!
2395   Creates an empty QCPDataSelection.
2396 */
2397 QCPDataSelection::QCPDataSelection()
2398 {
2399 }
2400 
2401 /*!
2402   Creates a QCPDataSelection containing the provided \a range.
2403 */
2404 QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
2405 {
2406   mDataRanges.append(range);
2407 }
2408 
2409 /*!
2410   Returns true if this selection is identical (contains the same data ranges with the same begin
2411   and end indices) to \a other.
2412 
2413   Note that both data selections must be in simplified state (the usual state of the selection, see
2414   \ref simplify) for this operator to return correct results.
2415 */
2416 bool QCPDataSelection::operator==(const QCPDataSelection &other) const
2417 {
2418   if (mDataRanges.size() != other.mDataRanges.size())
2419     return false;
2420   for (int i=0; i<mDataRanges.size(); ++i)
2421   {
2422     if (mDataRanges.at(i) != other.mDataRanges.at(i))
2423       return false;
2424   }
2425   return true;
2426 }
2427 
2428 /*!
2429   Adds the data selection of \a other to this data selection, and then simplifies this data
2430   selection (see \ref simplify).
2431 */
2432 QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
2433 {
2434   mDataRanges << other.mDataRanges;
2435   simplify();
2436   return *this;
2437 }
2438 
2439 /*!
2440   Adds the data range \a other to this data selection, and then simplifies this data selection (see
2441   \ref simplify).
2442 */
2443 QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
2444 {
2445   addDataRange(other);
2446   return *this;
2447 }
2448 
2449 /*!
2450   Removes all data point indices that are described by \a other from this data selection.
2451 */
2452 QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
2453 {
2454   for (int i=0; i<other.dataRangeCount(); ++i)
2455     *this -= other.dataRange(i);
2456   
2457   return *this;
2458 }
2459 
2460 /*!
2461   Removes all data point indices that are described by \a other from this data selection.
2462 */
2463 QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
2464 {
2465   if (other.isEmpty() || isEmpty())
2466     return *this;
2467   
2468   simplify();
2469   int i=0;
2470   while (i < mDataRanges.size())
2471   {
2472     const int thisBegin = mDataRanges.at(i).begin();
2473     const int thisEnd = mDataRanges.at(i).end();
2474     if (thisBegin >= other.end())
2475       break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
2476     
2477     if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
2478     {
2479       if (thisBegin >= other.begin()) // range leading segment is encompassed
2480       {
2481         if (thisEnd <= other.end()) // range fully encompassed, remove completely
2482         {
2483           mDataRanges.removeAt(i);
2484           continue;
2485         } else // only leading segment is encompassed, trim accordingly
2486           mDataRanges[i].setBegin(other.end());
2487       } else // leading segment is not encompassed
2488       {
2489         if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
2490         {
2491           mDataRanges[i].setEnd(other.begin());
2492         } else // other lies inside this range, so split range
2493         {
2494           mDataRanges[i].setEnd(other.begin());
2495           mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
2496           break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
2497         }
2498       }
2499     }
2500     ++i;
2501   }
2502   
2503   return *this;
2504 }
2505 
2506 /*!
2507   Returns the total number of data points contained in all data ranges that make up this data
2508   selection.
2509 */
2510 int QCPDataSelection::dataPointCount() const
2511 {
2512   int result = 0;
2513   foreach (QCPDataRange dataRange, mDataRanges)
2514     result += dataRange.length();
2515   return result;
2516 }
2517 
2518 /*!
2519   Returns the data range with the specified \a index.
2520   
2521   If the data selection is simplified (the usual state of the selection, see \ref simplify), the
2522   ranges are sorted by ascending data point index.
2523   
2524   \see dataRangeCount
2525 */
2526 QCPDataRange QCPDataSelection::dataRange(int index) const
2527 {
2528   if (index >= 0 && index < mDataRanges.size())
2529   {
2530     return mDataRanges.at(index);
2531   } else
2532   {
2533     qDebug() << Q_FUNC_INFO << "index out of range:" << index;
2534     return {};
2535   }
2536 }
2537 
2538 /*!
2539   Returns a \ref QCPDataRange which spans the entire data selection, including possible
2540   intermediate segments which are not part of the original data selection.
2541 */
2542 QCPDataRange QCPDataSelection::span() const
2543 {
2544   if (isEmpty())
2545     return {};
2546   else
2547     return {mDataRanges.first().begin(), mDataRanges.last().end()};
2548 }
2549 
2550 /*!
2551   Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
2552   allows disabling immediate simplification by setting \a simplify to false. This can improve
2553   performance if adding a very large amount of data ranges successively. In this case, make sure to
2554   call \ref simplify manually, after the operation.
2555 */
2556 void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
2557 {
2558   mDataRanges.append(dataRange);
2559   if (simplify)
2560     this->simplify();
2561 }
2562 
2563 /*!
2564   Removes all data ranges. The data selection then contains no data points.
2565   
2566   \ref isEmpty
2567 */
2568 void QCPDataSelection::clear()
2569 {
2570   mDataRanges.clear();
2571 }
2572 
2573 /*!
2574   Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
2575   or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
2576   prevents possible double-counting when iterating over the data points held by the data ranges.
2577 
2578   This method is automatically called when using the addition/subtraction operators. The only case
2579   when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
2580   simplify explicitly set to false.
2581 */
2582 void QCPDataSelection::simplify()
2583 {
2584   // remove any empty ranges:
2585   for (int i=mDataRanges.size()-1; i>=0; --i)
2586   {
2587     if (mDataRanges.at(i).isEmpty())
2588       mDataRanges.removeAt(i);
2589   }
2590   if (mDataRanges.isEmpty())
2591     return;
2592   
2593   // sort ranges by starting value, ascending:
2594   std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
2595   
2596   // join overlapping/contiguous ranges:
2597   int i = 1;
2598   while (i < mDataRanges.size())
2599   {
2600     if (mDataRanges.at(i-1).end() >= mDataRanges.at(i).begin()) // range i overlaps/joins with i-1, so expand range i-1 appropriately and remove range i from list
2601     {
2602       mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
2603       mDataRanges.removeAt(i);
2604     } else
2605       ++i;
2606   }
2607 }
2608 
2609 /*!
2610   Makes sure this data selection conforms to the specified \a type selection type. Before the type
2611   is enforced, \ref simplify is called.
2612   
2613   Depending on \a type, enforcing means adding new data points that were previously not part of the
2614   selection, or removing data points from the selection. If the current selection already conforms
2615   to \a type, the data selection is not changed.
2616   
2617   \see QCP::SelectionType
2618 */
2619 void QCPDataSelection::enforceType(QCP::SelectionType type)
2620 {
2621   simplify();
2622   switch (type)
2623   {
2624     case QCP::stNone:
2625     {
2626       mDataRanges.clear();
2627       break;
2628     }
2629     case QCP::stWhole:
2630     {
2631       // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
2632       break;
2633     }
2634     case QCP::stSingleData:
2635     {
2636       // reduce all data ranges to the single first data point:
2637       if (!mDataRanges.isEmpty())
2638       {
2639         if (mDataRanges.size() > 1)
2640           mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
2641         if (mDataRanges.first().length() > 1)
2642           mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
2643       }
2644       break;
2645     }
2646     case QCP::stDataRange:
2647     {
2648       if (!isEmpty())
2649         mDataRanges = QList<QCPDataRange>() << span();
2650       break;
2651     }
2652     case QCP::stMultipleDataRanges:
2653     {
2654       // this is the selection type that allows all concievable combinations of ranges, so do nothing
2655       break;
2656     }
2657   }
2658 }
2659 
2660 /*!
2661   Returns true if the data selection \a other is contained entirely in this data selection, i.e.
2662   all data point indices that are in \a other are also in this data selection.
2663   
2664   \see QCPDataRange::contains
2665 */
2666 bool QCPDataSelection::contains(const QCPDataSelection &other) const
2667 {
2668   if (other.isEmpty()) return false;
2669   
2670   int otherIndex = 0;
2671   int thisIndex = 0;
2672   while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
2673   {
2674     if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
2675       ++otherIndex;
2676     else
2677       ++thisIndex;
2678   }
2679   return thisIndex < mDataRanges.size(); // if thisIndex ran all the way to the end to find a containing range for the current otherIndex, other is not contained in this
2680 }
2681 
2682 /*!
2683   Returns a data selection containing the points which are both in this data selection and in the
2684   data range \a other.
2685 
2686   A common use case is to limit an unknown data selection to the valid range of a data container,
2687   using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
2688   data selection without exceeding the data container's bounds.
2689 */
2690 QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
2691 {
2692   QCPDataSelection result;
2693   foreach (QCPDataRange dataRange, mDataRanges)
2694     result.addDataRange(dataRange.intersection(other), false);
2695   result.simplify();
2696   return result;
2697 }
2698 
2699 /*!
2700   Returns a data selection containing the points which are both in this data selection and in the
2701   data selection \a other.
2702 */
2703 QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
2704 {
2705   QCPDataSelection result;
2706   for (int i=0; i<other.dataRangeCount(); ++i)
2707     result += intersection(other.dataRange(i));
2708   result.simplify();
2709   return result;
2710 }
2711 
2712 /*!
2713   Returns a data selection which is the exact inverse of this data selection, with \a outerRange
2714   defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
2715   this data selection, it is expanded accordingly.
2716 
2717   For example, this method can be used to retrieve all unselected segments by setting \a outerRange
2718   to the full data range of the plottable, and calling this method on a data selection holding the
2719   selected segments.
2720 */
2721 QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
2722 {
2723   if (isEmpty())
2724     return QCPDataSelection(outerRange);
2725   QCPDataRange fullRange = outerRange.expanded(span());
2726   
2727   QCPDataSelection result;
2728   // first unselected segment:
2729   if (mDataRanges.first().begin() != fullRange.begin())
2730     result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
2731   // intermediate unselected segments:
2732   for (int i=1; i<mDataRanges.size(); ++i)
2733     result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
2734   // last unselected segment:
2735   if (mDataRanges.last().end() != fullRange.end())
2736     result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
2737   result.simplify();
2738   return result;
2739 }
2740 /* end of 'src/selection.cpp' */
2741 
2742 
2743 /* including file 'src/selectionrect.cpp'  */
2744 /* modified 2021-03-29T02:30:44, size 9215 */
2745 
2746 ////////////////////////////////////////////////////////////////////////////////////////////////////
2747 //////////////////// QCPSelectionRect
2748 ////////////////////////////////////////////////////////////////////////////////////////////////////
2749 
2750 /*! \class QCPSelectionRect
2751   \brief Provides rect/rubber-band data selection and range zoom interaction
2752   
2753   QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
2754   \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
2755   instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
2756   according rect shape is drawn. At the begin, during, and after completion of the interaction, it
2757   emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
2758   
2759   The QCustomPlot instance connects own slots to the current selection rect instance, in order to
2760   react to an accepted selection rect interaction accordingly.
2761   
2762   \ref isActive can be used to check whether the selection rect is currently active. An ongoing
2763   selection interaction can be cancelled programmatically via calling \ref cancel at any time.
2764   
2765   The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
2766 
2767   If you wish to provide custom behaviour, e.g. a different visual representation of the selection
2768   rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
2769   your subclass to \ref QCustomPlot::setSelectionRect.
2770 */
2771 
2772 /* start of documentation of inline functions */
2773 
2774 /*! \fn bool QCPSelectionRect::isActive() const
2775    
2776   Returns true if there is currently a selection going on, i.e. the user has started dragging a
2777   selection rect, but hasn't released the mouse button yet.
2778     
2779   \see cancel
2780 */
2781 
2782 /* end of documentation of inline functions */
2783 /* start documentation of signals */
2784 
2785 /*! \fn void QCPSelectionRect::started(QMouseEvent *event);
2786    
2787   This signal is emitted when a selection rect interaction was initiated, i.e. the user just
2788   started dragging the selection rect with the mouse.
2789 */
2790 
2791 /*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
2792   
2793   This signal is emitted while the selection rect interaction is ongoing and the \a rect has
2794   changed its size due to the user moving the mouse.
2795   
2796   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2797   upper or left side of the selection rect origin.
2798 */
2799 
2800 /*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
2801   
2802   This signal is emitted when the selection interaction was cancelled. Note that \a event is \c
2803   nullptr if the selection interaction was cancelled programmatically, by a call to \ref cancel.
2804   
2805   The user may cancel the selection interaction by pressing the escape key. In this case, \a event
2806   holds the respective input event.
2807   
2808   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2809   upper or left side of the selection rect origin.
2810 */
2811 
2812 /*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
2813   
2814   This signal is emitted when the selection interaction was completed by the user releasing the
2815   mouse button.
2816     
2817   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2818   upper or left side of the selection rect origin.
2819 */
2820 
2821 /* end documentation of signals */
2822 
2823 /*!
2824   Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
2825   pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
2826   QCustomPlot widget.
2827 */
2828 QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
2829   QCPLayerable(parentPlot),
2830   mPen(QBrush(Qt::gray), 0, Qt::DashLine),
2831   mBrush(Qt::NoBrush),
2832   mActive(false)
2833 {
2834 }
2835 
2836 QCPSelectionRect::~QCPSelectionRect()
2837 {
2838   cancel();
2839 }
2840 
2841 /*!
2842   A convenience function which returns the coordinate range of the provided \a axis, that this
2843   selection rect currently encompasses.
2844 */
2845 QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
2846 {
2847   if (axis)
2848   {
2849     if (axis->orientation() == Qt::Horizontal)
2850       return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())};
2851     else
2852       return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())};
2853   } else
2854   {
2855     qDebug() << Q_FUNC_INFO << "called with axis zero";
2856     return {};
2857   }
2858 }
2859 
2860 /*!
2861   Sets the pen that will be used to draw the selection rect outline.
2862   
2863   \see setBrush
2864 */
2865 void QCPSelectionRect::setPen(const QPen &pen)
2866 {
2867   mPen = pen;
2868 }
2869 
2870 /*!
2871   Sets the brush that will be used to fill the selection rect. By default the selection rect is not
2872   filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
2873   
2874   \see setPen
2875 */
2876 void QCPSelectionRect::setBrush(const QBrush &brush)
2877 {
2878   mBrush = brush;
2879 }
2880 
2881 /*!
2882   If there is currently a selection interaction going on (\ref isActive), the interaction is
2883   canceled. The selection rect will emit the \ref canceled signal.
2884 */
2885 void QCPSelectionRect::cancel()
2886 {
2887   if (mActive)
2888   {
2889     mActive = false;
2890     emit canceled(mRect, nullptr);
2891   }
2892 }
2893 
2894 /*! \internal
2895   
2896   This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
2897   The default implementation sets the selection rect to active, initializes the selection rect
2898   geometry and emits the \ref started signal.
2899 */
2900 void QCPSelectionRect::startSelection(QMouseEvent *event)
2901 {
2902   mActive = true;
2903   mRect = QRect(event->pos(), event->pos());
2904   emit started(event);
2905 }
2906 
2907 /*! \internal
2908   
2909   This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
2910   to update its geometry. The default implementation updates the rect and emits the \ref changed
2911   signal.
2912 */
2913 void QCPSelectionRect::moveSelection(QMouseEvent *event)
2914 {
2915   mRect.setBottomRight(event->pos());
2916   emit changed(mRect, event);
2917   layer()->replot();
2918 }
2919 
2920 /*! \internal
2921   
2922   This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
2923   finished by the user releasing the mouse button. The default implementation deactivates the
2924   selection rect and emits the \ref accepted signal.
2925 */
2926 void QCPSelectionRect::endSelection(QMouseEvent *event)
2927 {
2928   mRect.setBottomRight(event->pos());
2929   mActive = false;
2930   emit accepted(mRect, event);
2931 }
2932 
2933 /*! \internal
2934   
2935   This method is called by QCustomPlot when a key has been pressed by the user while the selection
2936   rect interaction is active. The default implementation allows to \ref cancel the interaction by
2937   hitting the escape key.
2938 */
2939 void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
2940 {
2941   if (event->key() == Qt::Key_Escape && mActive)
2942   {
2943     mActive = false;
2944     emit canceled(mRect, event);
2945   }
2946 }
2947 
2948 /* inherits documentation from base class */
2949 void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
2950 {
2951   applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
2952 }
2953 
2954 /*! \internal
2955   
2956   If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
2957   
2958   \seebaseclassmethod
2959 */
2960 void QCPSelectionRect::draw(QCPPainter *painter)
2961 {
2962   if (mActive)
2963   {
2964     painter->setPen(mPen);
2965     painter->setBrush(mBrush);
2966     painter->drawRect(mRect);
2967   }
2968 }
2969 /* end of 'src/selectionrect.cpp' */
2970 
2971 
2972 /* including file 'src/layout.cpp'          */
2973 /* modified 2021-03-29T02:30:44, size 78863 */
2974 
2975 ////////////////////////////////////////////////////////////////////////////////////////////////////
2976 //////////////////// QCPMarginGroup
2977 ////////////////////////////////////////////////////////////////////////////////////////////////////
2978 
2979 /*! \class QCPMarginGroup
2980   \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
2981   
2982   QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
2983   they will all have the same size, based on the largest required margin in the group.
2984   
2985   \n
2986   \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
2987   \n
2988   
2989   In certain situations it is desirable that margins at specific sides are synchronized across
2990   layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
2991   provide a cleaner look to the user if the left and right margins of the two axis rects are of the
2992   same size. The left axis of the top axis rect will then be at the same horizontal position as the
2993   left axis of the lower axis rect, making them appear aligned. The same applies for the right
2994   axes. This is what QCPMarginGroup makes possible.
2995   
2996   To add/remove a specific side of a layout element to/from a margin group, use the \ref
2997   QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
2998   \ref clear, or just delete the margin group.
2999   
3000   \section QCPMarginGroup-example Example
3001   
3002   First create a margin group:
3003   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
3004   Then set this group on the layout element sides:
3005   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
3006   Here, we've used the first two axis rects of the plot and synchronized their left margins with
3007   each other and their right margins with each other.
3008 */
3009 
3010 /* start documentation of inline functions */
3011 
3012 /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
3013   
3014   Returns a list of all layout elements that have their margin \a side associated with this margin
3015   group.
3016 */
3017 
3018 /* end documentation of inline functions */
3019 
3020 /*!
3021   Creates a new QCPMarginGroup instance in \a parentPlot.
3022 */
3023 QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
3024   QObject(parentPlot),
3025   mParentPlot(parentPlot)
3026 {
3027   mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
3028   mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
3029   mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
3030   mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
3031 }
3032 
3033 QCPMarginGroup::~QCPMarginGroup()
3034 {
3035   clear();
3036 }
3037 
3038 /*!
3039   Returns whether this margin group is empty. If this function returns true, no layout elements use
3040   this margin group to synchronize margin sides.
3041 */
3042 bool QCPMarginGroup::isEmpty() const
3043 {
3044   QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
3045   while (it.hasNext())
3046   {
3047     it.next();
3048     if (!it.value().isEmpty())
3049       return false;
3050   }
3051   return true;
3052 }
3053 
3054 /*!
3055   Clears this margin group. The synchronization of the margin sides that use this margin group is
3056   lifted and they will use their individual margin sizes again.
3057 */
3058 void QCPMarginGroup::clear()
3059 {
3060   // make all children remove themselves from this margin group:
3061   QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
3062   while (it.hasNext())
3063   {
3064     it.next();
3065     const QList<QCPLayoutElement*> elements = it.value();
3066     for (int i=elements.size()-1; i>=0; --i)
3067       elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild
3068   }
3069 }
3070 
3071 /*! \internal
3072   
3073   Returns the synchronized common margin for \a side. This is the margin value that will be used by
3074   the layout element on the respective side, if it is part of this margin group.
3075   
3076   The common margin is calculated by requesting the automatic margin (\ref
3077   QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
3078   group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
3079   account, too.)
3080 */
3081 int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
3082 {
3083   // query all automatic margins of the layout elements in this margin group side and find maximum:
3084   int result = 0;
3085   foreach (QCPLayoutElement *el, mChildren.value(side))
3086   {
3087     if (!el->autoMargins().testFlag(side))
3088       continue;
3089     int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side));
3090     if (m > result)
3091       result = m;
3092   }
3093   return result;
3094 }
3095 
3096 /*! \internal
3097   
3098   Adds \a element to the internal list of child elements, for the margin \a side.
3099   
3100   This function does not modify the margin group property of \a element.
3101 */
3102 void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
3103 {
3104   if (!mChildren[side].contains(element))
3105     mChildren[side].append(element);
3106   else
3107     qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
3108 }
3109 
3110 /*! \internal
3111   
3112   Removes \a element from the internal list of child elements, for the margin \a side.
3113   
3114   This function does not modify the margin group property of \a element.
3115 */
3116 void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
3117 {
3118   if (!mChildren[side].removeOne(element))
3119     qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
3120 }
3121 
3122 
3123 ////////////////////////////////////////////////////////////////////////////////////////////////////
3124 //////////////////// QCPLayoutElement
3125 ////////////////////////////////////////////////////////////////////////////////////////////////////
3126 
3127 /*! \class QCPLayoutElement
3128   \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
3129   
3130   This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
3131   
3132   A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
3133   (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
3134   between outer and inner rect is called its margin. The margin can either be set to automatic or
3135   manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
3136   set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
3137   the layout element subclass will control the value itself (via \ref calculateAutoMargin).
3138   
3139   Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
3140   layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
3141   QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
3142   
3143   Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
3144   invisible by themselves, because they don't draw anything. Their only purpose is to manage the
3145   position and size of other layout elements. This category of layout elements usually use
3146   QCPLayout as base class. Then there is the category of layout elements which actually draw
3147   something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
3148   not necessarily mean that the latter category can't have child layout elements. QCPLegend for
3149   instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
3150   elements in the grid layout.
3151 */
3152 
3153 /* start documentation of inline functions */
3154 
3155 /*! \fn QCPLayout *QCPLayoutElement::layout() const
3156   
3157   Returns the parent layout of this layout element.
3158 */
3159 
3160 /*! \fn QRect QCPLayoutElement::rect() const
3161   
3162   Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
3163   setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
3164   
3165   In some cases, the area between outer and inner rect is left blank. In other cases the margin
3166   area is used to display peripheral graphics while the main content is in the inner rect. This is
3167   where automatic margin calculation becomes interesting because it allows the layout element to
3168   adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
3169   draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
3170   \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
3171   
3172   \see outerRect
3173 */
3174 
3175 /*! \fn QRect QCPLayoutElement::outerRect() const
3176   
3177   Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
3178   margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
3179   setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
3180   
3181   \see rect
3182 */
3183 
3184 /* end documentation of inline functions */
3185 
3186 /*!
3187   Creates an instance of QCPLayoutElement and sets default values.
3188 */
3189 QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
3190   QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
3191   mParentLayout(nullptr),
3192   mMinimumSize(),
3193   mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
3194   mSizeConstraintRect(scrInnerRect),
3195   mRect(0, 0, 0, 0),
3196   mOuterRect(0, 0, 0, 0),
3197   mMargins(0, 0, 0, 0),
3198   mMinimumMargins(0, 0, 0, 0),
3199   mAutoMargins(QCP::msAll)
3200 {
3201 }
3202 
3203 QCPLayoutElement::~QCPLayoutElement()
3204 {
3205   setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any
3206   // unregister at layout:
3207   if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
3208     mParentLayout->take(this);
3209 }
3210 
3211 /*!
3212   Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
3213   sets the position and size of this layout element using this function.
3214   
3215   Calling this function externally has no effect, since the layout will overwrite any changes to
3216   the outer rect upon the next replot.
3217   
3218   The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
3219   
3220   \see rect
3221 */
3222 void QCPLayoutElement::setOuterRect(const QRect &rect)
3223 {
3224   if (mOuterRect != rect)
3225   {
3226     mOuterRect = rect;
3227     mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
3228   }
3229 }
3230 
3231 /*!
3232   Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
3233   sides, this function is used to manually set the margin on those sides. Sides that are still set
3234   to be handled automatically are ignored and may have any value in \a margins.
3235   
3236   The margin is the distance between the outer rect (controlled by the parent layout via \ref
3237   setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
3238   element).
3239   
3240   \see setAutoMargins
3241 */
3242 void QCPLayoutElement::setMargins(const QMargins &margins)
3243 {
3244   if (mMargins != margins)
3245   {
3246     mMargins = margins;
3247     mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
3248   }
3249 }
3250 
3251 /*!
3252   If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
3253   minimum values for those margins.
3254   
3255   The minimum values are not enforced on margin sides that were set to be under manual control via
3256   \ref setAutoMargins.
3257   
3258   \see setAutoMargins
3259 */
3260 void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
3261 {
3262   if (mMinimumMargins != margins)
3263   {
3264     mMinimumMargins = margins;
3265   }
3266 }
3267 
3268 /*!
3269   Sets on which sides the margin shall be calculated automatically. If a side is calculated
3270   automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
3271   set to be controlled manually, the value may be specified with \ref setMargins.
3272   
3273   Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
3274   setMarginGroup), to synchronize (align) it with other layout elements in the plot.
3275   
3276   \see setMinimumMargins, setMargins, QCP::MarginSide
3277 */
3278 void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
3279 {
3280   mAutoMargins = sides;
3281 }
3282 
3283 /*!
3284   Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
3285   by changing row/column sizes in the layout accordingly.
3286   
3287   If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
3288   layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
3289   propagates the layout's size constraints to the outside by setting its own minimum QWidget size
3290   accordingly, so violations of \a size should be exceptions.
3291   
3292   Whether this constraint applies to the inner or the outer rect can be specified with \ref
3293   setSizeConstraintRect (see \ref rect and \ref outerRect).
3294 */
3295 void QCPLayoutElement::setMinimumSize(const QSize &size)
3296 {
3297   if (mMinimumSize != size)
3298   {
3299     mMinimumSize = size;
3300     if (mParentLayout)
3301       mParentLayout->sizeConstraintsChanged();
3302   }
3303 }
3304 
3305 /*! \overload
3306   
3307   Sets the minimum size of this layout element.
3308   
3309   Whether this constraint applies to the inner or the outer rect can be specified with \ref
3310   setSizeConstraintRect (see \ref rect and \ref outerRect).
3311 */
3312 void QCPLayoutElement::setMinimumSize(int width, int height)
3313 {
3314   setMinimumSize(QSize(width, height));
3315 }
3316 
3317 /*!
3318   Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
3319   by changing row/column sizes in the layout accordingly.
3320   
3321   Whether this constraint applies to the inner or the outer rect can be specified with \ref
3322   setSizeConstraintRect (see \ref rect and \ref outerRect).
3323 */
3324 void QCPLayoutElement::setMaximumSize(const QSize &size)
3325 {
3326   if (mMaximumSize != size)
3327   {
3328     mMaximumSize = size;
3329     if (mParentLayout)
3330       mParentLayout->sizeConstraintsChanged();
3331   }
3332 }
3333 
3334 /*! \overload
3335   
3336   Sets the maximum size of this layout element.
3337   
3338   Whether this constraint applies to the inner or the outer rect can be specified with \ref
3339   setSizeConstraintRect (see \ref rect and \ref outerRect).
3340 */
3341 void QCPLayoutElement::setMaximumSize(int width, int height)
3342 {
3343   setMaximumSize(QSize(width, height));
3344 }
3345 
3346 /*!
3347   Sets to which rect of a layout element the size constraints apply. Size constraints can be set
3348   via \ref setMinimumSize and \ref setMaximumSize.
3349   
3350   The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
3351   labels), whereas the inner rect (\ref rect) does not.
3352   
3353   \see setMinimumSize, setMaximumSize
3354 */
3355 void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
3356 {
3357   if (mSizeConstraintRect != constraintRect)
3358   {
3359     mSizeConstraintRect = constraintRect;
3360     if (mParentLayout)
3361       mParentLayout->sizeConstraintsChanged();
3362   }
3363 }
3364 
3365 /*!
3366   Sets the margin \a group of the specified margin \a sides.
3367   
3368   Margin groups allow synchronizing specified margins across layout elements, see the documentation
3369   of \ref QCPMarginGroup.
3370   
3371   To unset the margin group of \a sides, set \a group to \c nullptr.
3372   
3373   Note that margin groups only work for margin sides that are set to automatic (\ref
3374   setAutoMargins).
3375   
3376   \see QCP::MarginSide
3377 */
3378 void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
3379 {
3380   QVector<QCP::MarginSide> sideVector;
3381   if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
3382   if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
3383   if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
3384   if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
3385   
3386   foreach (QCP::MarginSide side, sideVector)
3387   {
3388     if (marginGroup(side) != group)
3389     {
3390       QCPMarginGroup *oldGroup = marginGroup(side);
3391       if (oldGroup) // unregister at old group
3392         oldGroup->removeChild(side, this);
3393       
3394       if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
3395       {
3396         mMarginGroups.remove(side);
3397       } else // setting to a new group
3398       {
3399         mMarginGroups[side] = group;
3400         group->addChild(side, this);
3401       }
3402     }
3403   }
3404 }
3405 
3406 /*!
3407   Updates the layout element and sub-elements. This function is automatically called before every
3408   replot by the parent layout element. It is called multiple times, once for every \ref
3409   UpdatePhase. The phases are run through in the order of the enum values. For details about what
3410   happens at the different phases, see the documentation of \ref UpdatePhase.
3411   
3412   Layout elements that have child elements should call the \ref update method of their child
3413   elements, and pass the current \a phase unchanged.
3414   
3415   The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
3416   Subclasses should make sure to call the base class implementation.
3417 */
3418 void QCPLayoutElement::update(UpdatePhase phase)
3419 {
3420   if (phase == upMargins)
3421   {
3422     if (mAutoMargins != QCP::msNone)
3423     {
3424       // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
3425       QMargins newMargins = mMargins;
3426       const QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
3427       foreach (QCP::MarginSide side, allMarginSides)
3428       {
3429         if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
3430         {
3431           if (mMarginGroups.contains(side))
3432             QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
3433           else
3434             QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
3435           // apply minimum margin restrictions:
3436           if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
3437             QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
3438         }
3439       }
3440       setMargins(newMargins);
3441     }
3442   }
3443 }
3444 
3445 /*!
3446   Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
3447   if no manual minimum size is set.
3448   
3449   if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
3450   (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
3451   allowed size of this layout element.
3452 
3453   A manual minimum size is considered set if it is non-zero.
3454   
3455   The default implementation simply returns the sum of the horizontal margins for the width and the
3456   sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
3457   about the layout element's content to provide size hints.
3458 */
3459 QSize QCPLayoutElement::minimumOuterSizeHint() const
3460 {
3461   return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()};
3462 }
3463 
3464 /*!
3465   Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
3466   if no manual maximum size is set.
3467   
3468   if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
3469   size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
3470   maximum allowed size of this layout element.
3471 
3472   A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
3473   
3474   The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
3475   no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
3476   element's content to provide size hints.
3477 */
3478 QSize QCPLayoutElement::maximumOuterSizeHint() const
3479 {
3480   return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
3481 }
3482 
3483 /*!
3484   Returns a list of all child elements in this layout element. If \a recursive is true, all
3485   sub-child elements are included in the list, too.
3486   
3487   \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may
3488   have empty cells which yield \c nullptr at the respective index.
3489 */
3490 QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
3491 {
3492   Q_UNUSED(recursive)
3493   return QList<QCPLayoutElement*>();
3494 }
3495 
3496 /*!
3497   Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
3498   rect, this method returns a value corresponding to 0.99 times the parent plot's selection
3499   tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
3500   true, -1.0 is returned.
3501   
3502   See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
3503   
3504   QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
3505   behaviour.
3506 */
3507 double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
3508 {
3509   Q_UNUSED(details)
3510   
3511   if (onlySelectable)
3512     return -1;
3513   
3514   if (QRectF(mOuterRect).contains(pos))
3515   {
3516     if (mParentPlot)
3517       return mParentPlot->selectionTolerance()*0.99;
3518     else
3519     {
3520       qDebug() << Q_FUNC_INFO << "parent plot not defined";
3521       return -1;
3522     }
3523   } else
3524     return -1;
3525 }
3526 
3527 /*! \internal
3528   
3529   propagates the parent plot initialization to all child elements, by calling \ref
3530   QCPLayerable::initializeParentPlot on them.
3531 */
3532 void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
3533 {
3534   foreach (QCPLayoutElement *el, elements(false))
3535   {
3536     if (!el->parentPlot())
3537       el->initializeParentPlot(parentPlot);
3538   }
3539 }
3540 
3541 /*! \internal
3542   
3543   Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
3544   side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
3545   returned value will not be smaller than the specified minimum margin.
3546   
3547   The default implementation just returns the respective manual margin (\ref setMargins) or the
3548   minimum margin, whichever is larger.
3549 */
3550 int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
3551 {
3552   return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
3553 }
3554 
3555 /*! \internal
3556   
3557   This virtual method is called when this layout element was moved to a different QCPLayout, or
3558   when this layout element has changed its logical position (e.g. row and/or column) within the
3559   same QCPLayout. Subclasses may use this to react accordingly.
3560   
3561   Since this method is called after the completion of the move, you can access the new parent
3562   layout via \ref layout().
3563   
3564   The default implementation does nothing.
3565 */
3566 void QCPLayoutElement::layoutChanged()
3567 {
3568 }
3569 
3570 ////////////////////////////////////////////////////////////////////////////////////////////////////
3571 //////////////////// QCPLayout
3572 ////////////////////////////////////////////////////////////////////////////////////////////////////
3573 
3574 /*! \class QCPLayout
3575   \brief The abstract base class for layouts
3576   
3577   This is an abstract base class for layout elements whose main purpose is to define the position
3578   and size of other child layout elements. In most cases, layouts don't draw anything themselves
3579   (but there are exceptions to this, e.g. QCPLegend).
3580   
3581   QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
3582   
3583   QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
3584   functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
3585   simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
3586   to this interface which are more specialized to the form of the layout. For example, \ref
3587   QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
3588   more conveniently.
3589   
3590   Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
3591   subclasses like QCPLayoutGrid or QCPLayoutInset.
3592   
3593   For a general introduction to the layout system, see the dedicated documentation page \ref
3594   thelayoutsystem "The Layout System".
3595 */
3596 
3597 /* start documentation of pure virtual functions */
3598 
3599 /*! \fn virtual int QCPLayout::elementCount() const = 0
3600   
3601   Returns the number of elements/cells in the layout.
3602   
3603   \see elements, elementAt
3604 */
3605 
3606 /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
3607   
3608   Returns the element in the cell with the given \a index. If \a index is invalid, returns \c
3609   nullptr.
3610   
3611   Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
3612   QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function
3613   to check whether a cell is empty or not.
3614   
3615   \see elements, elementCount, takeAt
3616 */
3617 
3618 /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
3619   
3620   Removes the element with the given \a index from the layout and returns it.
3621   
3622   If the \a index is invalid or the cell with that index is empty, returns \c nullptr.
3623   
3624   Note that some layouts don't remove the respective cell right away but leave an empty cell after
3625   successful removal of the layout element. To collapse empty cells, use \ref simplify.
3626   
3627   \see elementAt, take
3628 */
3629 
3630 /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
3631   
3632   Removes the specified \a element from the layout and returns true on success.
3633   
3634   If the \a element isn't in this layout, returns false.
3635   
3636   Note that some layouts don't remove the respective cell right away but leave an empty cell after
3637   successful removal of the layout element. To collapse empty cells, use \ref simplify.
3638   
3639   \see takeAt
3640 */
3641 
3642 /* end documentation of pure virtual functions */
3643 
3644 /*!
3645   Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
3646   is an abstract base class, it can't be instantiated directly.
3647 */
3648 QCPLayout::QCPLayout()
3649 {
3650 }
3651 
3652 /*!
3653   If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
3654   reposition and resize their cells.
3655   
3656   Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
3657   
3658   For details about this method and the update phases, see the documentation of \ref
3659   QCPLayoutElement::update.
3660 */
3661 void QCPLayout::update(UpdatePhase phase)
3662 {
3663   QCPLayoutElement::update(phase);
3664   
3665   // set child element rects according to layout:
3666   if (phase == upLayout)
3667     updateLayout();
3668   
3669   // propagate update call to child elements:
3670   const int elCount = elementCount();
3671   for (int i=0; i<elCount; ++i)
3672   {
3673     if (QCPLayoutElement *el = elementAt(i))
3674       el->update(phase);
3675   }
3676 }
3677 
3678 /* inherits documentation from base class */
3679 QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
3680 {
3681   const int c = elementCount();
3682   QList<QCPLayoutElement*> result;
3683 #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
3684   result.reserve(c);
3685 #endif
3686   for (int i=0; i<c; ++i)
3687     result.append(elementAt(i));
3688   if (recursive)
3689   {
3690     for (int i=0; i<c; ++i)
3691     {
3692       if (result.at(i))
3693         result << result.at(i)->elements(recursive);
3694     }
3695   }
3696   return result;
3697 }
3698 
3699 /*!
3700   Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
3701   default implementation does nothing.
3702   
3703   Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
3704   simplification while QCPLayoutGrid does.
3705 */
3706 void QCPLayout::simplify()
3707 {
3708 }
3709 
3710 /*!
3711   Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
3712   invalid or points to an empty cell, returns false.
3713   
3714   This function internally uses \ref takeAt to remove the element from the layout and then deletes
3715   the returned element. Note that some layouts don't remove the respective cell right away but leave an
3716   empty cell after successful removal of the layout element. To collapse empty cells, use \ref
3717   simplify.
3718   
3719   \see remove, takeAt
3720 */
3721 bool QCPLayout::removeAt(int index)
3722 {
3723   if (QCPLayoutElement *el = takeAt(index))
3724   {
3725     delete el;
3726     return true;
3727   } else
3728     return false;
3729 }
3730 
3731 /*!
3732   Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
3733   layout, returns false.
3734   
3735   This function internally uses \ref takeAt to remove the element from the layout and then deletes
3736   the element. Note that some layouts don't remove the respective cell right away but leave an
3737   empty cell after successful removal of the layout element. To collapse empty cells, use \ref
3738   simplify.
3739   
3740   \see removeAt, take
3741 */
3742 bool QCPLayout::remove(QCPLayoutElement *element)
3743 {
3744   if (take(element))
3745   {
3746     delete element;
3747     return true;
3748   } else
3749     return false;
3750 }
3751 
3752 /*!
3753   Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
3754   all empty cells are collapsed.
3755   
3756   \see remove, removeAt
3757 */
3758 void QCPLayout::clear()
3759 {
3760   for (int i=elementCount()-1; i>=0; --i)
3761   {
3762     if (elementAt(i))
3763       removeAt(i);
3764   }
3765   simplify();
3766 }
3767 
3768 /*!
3769   Subclasses call this method to report changed (minimum/maximum) size constraints.
3770   
3771   If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
3772   sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
3773   QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
3774   it may update itself and resize cells accordingly.
3775 */
3776 void QCPLayout::sizeConstraintsChanged() const
3777 {
3778   if (QWidget *w = qobject_cast<QWidget*>(parent()))
3779     w->updateGeometry();
3780   else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
3781     l->sizeConstraintsChanged();
3782 }
3783 
3784 /*! \internal
3785   
3786   Subclasses reimplement this method to update the position and sizes of the child elements/cells
3787   via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
3788   
3789   The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
3790   within that rect.
3791   
3792   \ref getSectionSizes may help with the reimplementation of this function.
3793   
3794   \see update
3795 */
3796 void QCPLayout::updateLayout()
3797 {
3798 }
3799 
3800 
3801 /*! \internal
3802   
3803   Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
3804   \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
3805   
3806   Further, if \a el didn't previously have a parent plot, calls \ref
3807   QCPLayerable::initializeParentPlot on \a el to set the paret plot.
3808   
3809   This method is used by subclass specific methods that add elements to the layout. Note that this
3810   method only changes properties in \a el. The removal from the old layout and the insertion into
3811   the new layout must be done additionally.
3812 */
3813 void QCPLayout::adoptElement(QCPLayoutElement *el)
3814 {
3815   if (el)
3816   {
3817     el->mParentLayout = this;
3818     el->setParentLayerable(this);
3819     el->setParent(this);
3820     if (!el->parentPlot())
3821       el->initializeParentPlot(mParentPlot);
3822     el->layoutChanged();
3823   } else
3824     qDebug() << Q_FUNC_INFO << "Null element passed";
3825 }
3826 
3827 /*! \internal
3828   
3829   Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
3830   and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
3831   QCustomPlot.
3832   
3833   This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
3834   take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
3835   the old layout must be done additionally.
3836 */
3837 void QCPLayout::releaseElement(QCPLayoutElement *el)
3838 {
3839   if (el)
3840   {
3841     el->mParentLayout = nullptr;
3842     el->setParentLayerable(nullptr);
3843     el->setParent(mParentPlot);
3844     // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
3845   } else
3846     qDebug() << Q_FUNC_INFO << "Null element passed";
3847 }
3848 
3849 /*! \internal
3850   
3851   This is a helper function for the implementation of \ref updateLayout in subclasses.
3852   
3853   It calculates the sizes of one-dimensional sections with provided constraints on maximum section
3854   sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
3855   
3856   The QVector entries refer to the sections. Thus all QVectors must have the same size.
3857   
3858   \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
3859   imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
3860   
3861   \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
3862   imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
3863   \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
3864   not exceeding the allowed total size is taken to be more important than not going below minimum
3865   section sizes.)
3866   
3867   \a stretchFactors give the relative proportions of the sections to each other. If all sections
3868   shall be scaled equally, set all values equal. If the first section shall be double the size of
3869   each individual other section, set the first number of \a stretchFactors to double the value of
3870   the other individual values (e.g. {2, 1, 1, 1}).
3871   
3872   \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
3873   actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
3874   you could distribute the remaining difference on the sections.
3875   
3876   The return value is a QVector containing the section sizes.
3877 */
3878 QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
3879 {
3880   if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
3881   {
3882     qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
3883     return QVector<int>();
3884   }
3885   if (stretchFactors.isEmpty())
3886     return QVector<int>();
3887   int sectionCount = stretchFactors.size();
3888   QVector<double> sectionSizes(sectionCount);
3889   // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
3890   int minSizeSum = 0;
3891   for (int i=0; i<sectionCount; ++i)
3892     minSizeSum += minSizes.at(i);
3893   if (totalSize < minSizeSum)
3894   {
3895     // new stretch factors are minimum sizes and minimum sizes are set to zero:
3896     for (int i=0; i<sectionCount; ++i)
3897     {
3898       stretchFactors[i] = minSizes.at(i);
3899       minSizes[i] = 0;
3900     }
3901   }
3902   
3903   QList<int> minimumLockedSections;
3904   QList<int> unfinishedSections;
3905   for (int i=0; i<sectionCount; ++i)
3906     unfinishedSections.append(i);
3907   double freeSize = totalSize;
3908   
3909   int outerIterations = 0;
3910   while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
3911   {
3912     ++outerIterations;
3913     int innerIterations = 0;
3914     while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
3915     {
3916       ++innerIterations;
3917       // find section that hits its maximum next:
3918       int nextId = -1;
3919       double nextMax = 1e12;
3920       foreach (int secId, unfinishedSections)
3921       {
3922         double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
3923         if (hitsMaxAt < nextMax)
3924         {
3925           nextMax = hitsMaxAt;
3926           nextId = secId;
3927         }
3928       }
3929       // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
3930       // actually hits its maximum, without exceeding the total size when we add up all sections)
3931       double stretchFactorSum = 0;
3932       foreach (int secId, unfinishedSections)
3933         stretchFactorSum += stretchFactors.at(secId);
3934       double nextMaxLimit = freeSize/stretchFactorSum;
3935       if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
3936       {
3937         foreach (int secId, unfinishedSections)
3938         {
3939           sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections
3940           freeSize -= nextMax*stretchFactors.at(secId);
3941         }
3942         unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
3943       } else // next maximum isn't hit, just distribute rest of free space on remaining sections
3944       {
3945         foreach (int secId, unfinishedSections)
3946           sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections
3947         unfinishedSections.clear();
3948       }
3949     }
3950     if (innerIterations == sectionCount*2)
3951       qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
3952     
3953     // now check whether the resulting section sizes violate minimum restrictions:
3954     bool foundMinimumViolation = false;
3955     for (int i=0; i<sectionSizes.size(); ++i)
3956     {
3957       if (minimumLockedSections.contains(i))
3958         continue;
3959       if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
3960       {
3961         sectionSizes[i] = minSizes.at(i); // set it to minimum
3962         foundMinimumViolation = true; // make sure we repeat the whole optimization process
3963         minimumLockedSections.append(i);
3964       }
3965     }
3966     if (foundMinimumViolation)
3967     {
3968       freeSize = totalSize;
3969       for (int i=0; i<sectionCount; ++i)
3970       {
3971         if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
3972           unfinishedSections.append(i);
3973         else
3974           freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
3975       }
3976       // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
3977       foreach (int secId, unfinishedSections)
3978         sectionSizes[secId] = 0;
3979     }
3980   }
3981   if (outerIterations == sectionCount*2)
3982     qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
3983   
3984   QVector<int> result(sectionCount);
3985   for (int i=0; i<sectionCount; ++i)
3986     result[i] = qRound(sectionSizes.at(i));
3987   return result;
3988 }
3989 
3990 /*! \internal
3991   
3992   This is a helper function for the implementation of subclasses.
3993   
3994   It returns the minimum size that should finally be used for the outer rect of the passed layout
3995   element \a el.
3996   
3997   It takes into account whether a manual minimum size is set (\ref
3998   QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
3999   QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
4000   size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
4001 */
4002 QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
4003 {
4004   QSize minOuterHint = el->minimumOuterSizeHint();
4005   QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0)
4006   if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
4007     minOuter.rwidth() += el->margins().left() + el->margins().right();
4008   if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
4009     minOuter.rheight() += el->margins().top() + el->margins().bottom();
4010   
4011   return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
4012                minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()};
4013 }
4014 
4015 /*! \internal
4016   
4017   This is a helper function for the implementation of subclasses.
4018   
4019   It returns the maximum size that should finally be used for the outer rect of the passed layout
4020   element \a el.
4021   
4022   It takes into account whether a manual maximum size is set (\ref
4023   QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
4024   QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
4025   size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
4026 */
4027 QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
4028 {
4029   QSize maxOuterHint = el->maximumOuterSizeHint();
4030   QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX)
4031   if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
4032     maxOuter.rwidth() += el->margins().left() + el->margins().right();
4033   if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
4034     maxOuter.rheight() += el->margins().top() + el->margins().bottom();
4035   
4036   return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
4037                maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()};
4038 }
4039 
4040 
4041 ////////////////////////////////////////////////////////////////////////////////////////////////////
4042 //////////////////// QCPLayoutGrid
4043 ////////////////////////////////////////////////////////////////////////////////////////////////////
4044 
4045 /*! \class QCPLayoutGrid
4046   \brief A layout that arranges child elements in a grid
4047 
4048   Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
4049   \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
4050 
4051   Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
4052   column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
4053   hasElement, that element can be retrieved with \ref element. If rows and columns that only have
4054   empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
4055   adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
4056   remove.
4057 
4058   If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
4059   column, the grid layout will choose the position according to the current \ref setFillOrder and
4060   the wrapping (\ref setWrap).
4061 
4062   Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
4063 */
4064 
4065 /* start documentation of inline functions */
4066 
4067 /*! \fn int QCPLayoutGrid::rowCount() const
4068 
4069   Returns the number of rows in the layout.
4070 
4071   \see columnCount
4072 */
4073 
4074 /*! \fn int QCPLayoutGrid::columnCount() const
4075 
4076   Returns the number of columns in the layout.
4077 
4078   \see rowCount
4079 */
4080 
4081 /* end documentation of inline functions */
4082 
4083 /*!
4084   Creates an instance of QCPLayoutGrid and sets default values.
4085 */
4086 QCPLayoutGrid::QCPLayoutGrid() :
4087   mColumnSpacing(5),
4088   mRowSpacing(5),
4089   mWrap(0),
4090   mFillOrder(foColumnsFirst)
4091 {
4092 }
4093 
4094 QCPLayoutGrid::~QCPLayoutGrid()
4095 {
4096   // clear all child layout elements. This is important because only the specific layouts know how
4097   // to handle removing elements (clear calls virtual removeAt method to do that).
4098   clear();
4099 }
4100 
4101 /*!
4102   Returns the element in the cell in \a row and \a column.
4103   
4104   Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a
4105   qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
4106   
4107   \see addElement, hasElement
4108 */
4109 QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
4110 {
4111   if (row >= 0 && row < mElements.size())
4112   {
4113     if (column >= 0 && column < mElements.first().size())
4114     {
4115       if (QCPLayoutElement *result = mElements.at(row).at(column))
4116         return result;
4117       else
4118         qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
4119     } else
4120       qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
4121   } else
4122     qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
4123   return nullptr;
4124 }
4125 
4126 
4127 /*! \overload
4128 
4129   Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
4130   is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
4131   accordingly.
4132 
4133   Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
4134   didn't already have an element.
4135 
4136   Use the overload of this method without explicit row/column index to place the element according
4137   to the configured fill order and wrapping settings.
4138 
4139   \see element, hasElement, take, remove
4140 */
4141 bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
4142 {
4143   if (!hasElement(row, column))
4144   {
4145     if (element && element->layout()) // remove from old layout first
4146       element->layout()->take(element);
4147     expandTo(row+1, column+1);
4148     mElements[row][column] = element;
4149     if (element)
4150       adoptElement(element);
4151     return true;
4152   } else
4153     qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
4154   return false;
4155 }
4156 
4157 /*! \overload
4158 
4159   Adds the \a element to the next empty cell according to the current fill order (\ref
4160   setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
4161   removed from there. If necessary, the layout is expanded to hold the new element.
4162 
4163   Returns true if the element was added successfully.
4164 
4165   \see setFillOrder, setWrap, element, hasElement, take, remove
4166 */
4167 bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
4168 {
4169   int rowIndex = 0;
4170   int colIndex = 0;
4171   if (mFillOrder == foColumnsFirst)
4172   {
4173     while (hasElement(rowIndex, colIndex))
4174     {
4175       ++colIndex;
4176       if (colIndex >= mWrap && mWrap > 0)
4177       {
4178         colIndex = 0;
4179         ++rowIndex;
4180       }
4181     }
4182   } else
4183   {
4184     while (hasElement(rowIndex, colIndex))
4185     {
4186       ++rowIndex;
4187       if (rowIndex >= mWrap && mWrap > 0)
4188       {
4189         rowIndex = 0;
4190         ++colIndex;
4191       }
4192     }
4193   }
4194   return addElement(rowIndex, colIndex, element);
4195 }
4196 
4197 /*!
4198   Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
4199   empty.
4200   
4201   \see element
4202 */
4203 bool QCPLayoutGrid::hasElement(int row, int column)
4204 {
4205   if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
4206     return mElements.at(row).at(column);
4207   else
4208     return false;
4209 }
4210 
4211 /*!
4212   Sets the stretch \a factor of \a column.
4213   
4214   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4215   their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
4216   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
4217   QCPLayoutElement::setSizeConstraintRect.)
4218   
4219   The default stretch factor of newly created rows/columns is 1.
4220   
4221   \see setColumnStretchFactors, setRowStretchFactor
4222 */
4223 void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
4224 {
4225   if (column >= 0 && column < columnCount())
4226   {
4227     if (factor > 0)
4228       mColumnStretchFactors[column] = factor;
4229     else
4230       qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
4231   } else
4232     qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
4233 }
4234 
4235 /*!
4236   Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
4237   
4238   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4239   their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
4240   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
4241   QCPLayoutElement::setSizeConstraintRect.)
4242   
4243   The default stretch factor of newly created rows/columns is 1.
4244   
4245   \see setColumnStretchFactor, setRowStretchFactors
4246 */
4247 void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
4248 {
4249   if (factors.size() == mColumnStretchFactors.size())
4250   {
4251     mColumnStretchFactors = factors;
4252     for (int i=0; i<mColumnStretchFactors.size(); ++i)
4253     {
4254       if (mColumnStretchFactors.at(i) <= 0)
4255       {
4256         qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
4257         mColumnStretchFactors[i] = 1;
4258       }
4259     }
4260   } else
4261     qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
4262 }
4263 
4264 /*!
4265   Sets the stretch \a factor of \a row.
4266   
4267   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4268   their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
4269   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
4270   QCPLayoutElement::setSizeConstraintRect.)
4271   
4272   The default stretch factor of newly created rows/columns is 1.
4273   
4274   \see setColumnStretchFactors, setRowStretchFactor
4275 */
4276 void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
4277 {
4278   if (row >= 0 && row < rowCount())
4279   {
4280     if (factor > 0)
4281       mRowStretchFactors[row] = factor;
4282     else
4283       qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
4284   } else
4285     qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
4286 }
4287 
4288 /*!
4289   Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
4290   
4291   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4292   their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
4293   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
4294   QCPLayoutElement::setSizeConstraintRect.)
4295   
4296   The default stretch factor of newly created rows/columns is 1.
4297   
4298   \see setRowStretchFactor, setColumnStretchFactors
4299 */
4300 void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
4301 {
4302   if (factors.size() == mRowStretchFactors.size())
4303   {
4304     mRowStretchFactors = factors;
4305     for (int i=0; i<mRowStretchFactors.size(); ++i)
4306     {
4307       if (mRowStretchFactors.at(i) <= 0)
4308       {
4309         qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
4310         mRowStretchFactors[i] = 1;
4311       }
4312     }
4313   } else
4314     qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
4315 }
4316 
4317 /*!
4318   Sets the gap that is left blank between columns to \a pixels.
4319   
4320   \see setRowSpacing
4321 */
4322 void QCPLayoutGrid::setColumnSpacing(int pixels)
4323 {
4324   mColumnSpacing = pixels;
4325 }
4326 
4327 /*!
4328   Sets the gap that is left blank between rows to \a pixels.
4329   
4330   \see setColumnSpacing
4331 */
4332 void QCPLayoutGrid::setRowSpacing(int pixels)
4333 {
4334   mRowSpacing = pixels;
4335 }
4336 
4337 /*!
4338   Sets the maximum number of columns or rows that are used, before new elements added with \ref
4339   addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
4340   on \ref setFillOrder, whether rows or columns are wrapped.
4341 
4342   If \a count is set to zero, no wrapping will ever occur.
4343   
4344   If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
4345   rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
4346   done).
4347 
4348   Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
4349   explicitly stated row and column is not subject to wrapping and can place elements even beyond
4350   the specified wrapping point.
4351 
4352   \see setFillOrder
4353 */
4354 void QCPLayoutGrid::setWrap(int count)
4355 {
4356   mWrap = qMax(0, count);
4357 }
4358 
4359 /*!
4360   Sets the filling order and wrapping behaviour that is used when adding new elements with the
4361   method \ref addElement(QCPLayoutElement*).
4362 
4363   The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
4364   can control at which row/column count wrapping into the next column/row will occur. If you set it
4365   to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
4366   linear index used e.g. in \ref elementAt and \ref takeAt. The default fill order for \ref
4367   QCPLayoutGrid is \ref foColumnsFirst.
4368 
4369   If you want to have all current elements arranged in the new order, set \a rearrange to true. The
4370   elements will be rearranged in a way that tries to preserve their linear index. However, empty
4371   cells are skipped during build-up of the new cell order, which shifts the succeeding element's
4372   index. The rearranging is performed even if the specified \a order is already the current fill
4373   order. Thus this method can be used to re-wrap the current elements.
4374 
4375   If \a rearrange is false, the current element arrangement is not changed, which means the
4376   linear indexes change (because the linear index is dependent on the fill order).
4377 
4378   Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
4379   explicitly stated row and column is not subject to wrapping and can place elements even beyond
4380   the specified wrapping point.
4381 
4382   \see setWrap, addElement(QCPLayoutElement*)
4383 */
4384 void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
4385 {
4386   // if rearranging, take all elements via linear index of old fill order:
4387   const int elCount = elementCount();
4388   QVector<QCPLayoutElement*> tempElements;
4389   if (rearrange)
4390   {
4391     tempElements.reserve(elCount);
4392     for (int i=0; i<elCount; ++i)
4393     {
4394       if (elementAt(i))
4395         tempElements.append(takeAt(i));
4396     }
4397     simplify();
4398   }
4399   // change fill order as requested:
4400   mFillOrder = order;
4401   // if rearranging, re-insert via linear index according to new fill order:
4402   if (rearrange)
4403   {
4404     foreach (QCPLayoutElement *tempElement, tempElements)
4405       addElement(tempElement);
4406   }
4407 }
4408 
4409 /*!
4410   Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
4411   row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
4412   
4413   If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
4414   this function does nothing in that dimension.
4415   
4416   Newly created cells are empty, new rows and columns have the stretch factor 1.
4417   
4418   Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
4419   specified row and column, using this function.
4420   
4421   \see simplify
4422 */
4423 void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
4424 {
4425   // add rows as necessary:
4426   while (rowCount() < newRowCount)
4427   {
4428     mElements.append(QList<QCPLayoutElement*>());
4429     mRowStretchFactors.append(1);
4430   }
4431   // go through rows and expand columns as necessary:
4432   int newColCount = qMax(columnCount(), newColumnCount);
4433   for (int i=0; i<rowCount(); ++i)
4434   {
4435     while (mElements.at(i).size() < newColCount)
4436       mElements[i].append(nullptr);
4437   }
4438   while (mColumnStretchFactors.size() < newColCount)
4439     mColumnStretchFactors.append(1);
4440 }
4441 
4442 /*!
4443   Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
4444   range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
4445   
4446   \see insertColumn
4447 */
4448 void QCPLayoutGrid::insertRow(int newIndex)
4449 {
4450   if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
4451   {
4452     expandTo(1, 1);
4453     return;
4454   }
4455   
4456   if (newIndex < 0)
4457     newIndex = 0;
4458   if (newIndex > rowCount())
4459     newIndex = rowCount();
4460   
4461   mRowStretchFactors.insert(newIndex, 1);
4462   QList<QCPLayoutElement*> newRow;
4463   for (int col=0; col<columnCount(); ++col)
4464     newRow.append(nullptr);
4465   mElements.insert(newIndex, newRow);
4466 }
4467 
4468 /*!
4469   Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
4470   newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
4471   right).
4472   
4473   \see insertRow
4474 */
4475 void QCPLayoutGrid::insertColumn(int newIndex)
4476 {
4477   if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
4478   {
4479     expandTo(1, 1);
4480     return;
4481   }
4482   
4483   if (newIndex < 0)
4484     newIndex = 0;
4485   if (newIndex > columnCount())
4486     newIndex = columnCount();
4487   
4488   mColumnStretchFactors.insert(newIndex, 1);
4489   for (int row=0; row<rowCount(); ++row)
4490     mElements[row].insert(newIndex, nullptr);
4491 }
4492 
4493 /*!
4494   Converts the given \a row and \a column to the linear index used by some methods of \ref
4495   QCPLayoutGrid and \ref QCPLayout.
4496 
4497   The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
4498   indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
4499   increase top to bottom and then left to right.
4500 
4501   For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
4502   greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
4503 
4504   \see indexToRowCol
4505 */
4506 int QCPLayoutGrid::rowColToIndex(int row, int column) const
4507 {
4508   if (row >= 0 && row < rowCount())
4509   {
4510     if (column >= 0 && column < columnCount())
4511     {
4512       switch (mFillOrder)
4513       {
4514         case foRowsFirst: return column*rowCount() + row;
4515         case foColumnsFirst: return row*columnCount() + column;
4516       }
4517     } else
4518       qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
4519   } else
4520     qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
4521   return 0;
4522 }
4523 
4524 /*!
4525   Converts the linear index to row and column indices and writes the result to \a row and \a
4526   column.
4527 
4528   The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
4529   indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
4530   increase top to bottom and then left to right.
4531 
4532   If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
4533 
4534   For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
4535   i.e. greater or equal to zero and smaller than the current \ref elementCount.
4536 
4537   \see rowColToIndex
4538 */
4539 void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
4540 {
4541   row = -1;
4542   column = -1;
4543   const int nCols = columnCount();
4544   const int nRows = rowCount();
4545   if (nCols == 0 || nRows == 0)
4546     return;
4547   if (index < 0 || index >= elementCount())
4548   {
4549     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
4550     return;
4551   }
4552   
4553   switch (mFillOrder)
4554   {
4555     case foRowsFirst:
4556     {
4557       column = index / nRows;
4558       row = index % nRows;
4559       break;
4560     }
4561     case foColumnsFirst:
4562     {
4563       row = index / nCols;
4564       column = index % nCols;
4565       break;
4566     }
4567   }
4568 }
4569 
4570 /* inherits documentation from base class */
4571 void QCPLayoutGrid::updateLayout()
4572 {
4573   QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
4574   getMinimumRowColSizes(&minColWidths, &minRowHeights);
4575   getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
4576   
4577   int totalRowSpacing = (rowCount()-1) * mRowSpacing;
4578   int totalColSpacing = (columnCount()-1) * mColumnSpacing;
4579   QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
4580   QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
4581   
4582   // go through cells and set rects accordingly:
4583   int yOffset = mRect.top();
4584   for (int row=0; row<rowCount(); ++row)
4585   {
4586     if (row > 0)
4587       yOffset += rowHeights.at(row-1)+mRowSpacing;
4588     int xOffset = mRect.left();
4589     for (int col=0; col<columnCount(); ++col)
4590     {
4591       if (col > 0)
4592         xOffset += colWidths.at(col-1)+mColumnSpacing;
4593       if (mElements.at(row).at(col))
4594         mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
4595     }
4596   }
4597 }
4598 
4599 /*!
4600   \seebaseclassmethod
4601 
4602   Note that the association of the linear \a index to the row/column based cells depends on the
4603   current setting of \ref setFillOrder.
4604 
4605   \see rowColToIndex
4606 */
4607 QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
4608 {
4609   if (index >= 0 && index < elementCount())
4610   {
4611     int row, col;
4612     indexToRowCol(index, row, col);
4613     return mElements.at(row).at(col);
4614   } else
4615     return nullptr;
4616 }
4617 
4618 /*!
4619   \seebaseclassmethod
4620 
4621   Note that the association of the linear \a index to the row/column based cells depends on the
4622   current setting of \ref setFillOrder.
4623 
4624   \see rowColToIndex
4625 */
4626 QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
4627 {
4628   if (QCPLayoutElement *el = elementAt(index))
4629   {
4630     releaseElement(el);
4631     int row, col;
4632     indexToRowCol(index, row, col);
4633     mElements[row][col] = nullptr;
4634     return el;
4635   } else
4636   {
4637     qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
4638     return nullptr;
4639   }
4640 }
4641 
4642 /* inherits documentation from base class */
4643 bool QCPLayoutGrid::take(QCPLayoutElement *element)
4644 {
4645   if (element)
4646   {
4647     for (int i=0; i<elementCount(); ++i)
4648     {
4649       if (elementAt(i) == element)
4650       {
4651         takeAt(i);
4652         return true;
4653       }
4654     }
4655     qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
4656   } else
4657     qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
4658   return false;
4659 }
4660 
4661 /* inherits documentation from base class */
4662 QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
4663 {
4664   QList<QCPLayoutElement*> result;
4665   const int elCount = elementCount();
4666 #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
4667   result.reserve(elCount);
4668 #endif
4669   for (int i=0; i<elCount; ++i)
4670     result.append(elementAt(i));
4671   if (recursive)
4672   {
4673     for (int i=0; i<elCount; ++i)
4674     {
4675       if (result.at(i))
4676         result << result.at(i)->elements(recursive);
4677     }
4678   }
4679   return result;
4680 }
4681 
4682 /*!
4683   Simplifies the layout by collapsing rows and columns which only contain empty cells.
4684 */
4685 void QCPLayoutGrid::simplify()
4686 {
4687   // remove rows with only empty cells:
4688   for (int row=rowCount()-1; row>=0; --row)
4689   {
4690     bool hasElements = false;
4691     for (int col=0; col<columnCount(); ++col)
4692     {
4693       if (mElements.at(row).at(col))
4694       {
4695         hasElements = true;
4696         break;
4697       }
4698     }
4699     if (!hasElements)
4700     {
4701       mRowStretchFactors.removeAt(row);
4702       mElements.removeAt(row);
4703       if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
4704         mColumnStretchFactors.clear();
4705     }
4706   }
4707   
4708   // remove columns with only empty cells:
4709   for (int col=columnCount()-1; col>=0; --col)
4710   {
4711     bool hasElements = false;
4712     for (int row=0; row<rowCount(); ++row)
4713     {
4714       if (mElements.at(row).at(col))
4715       {
4716         hasElements = true;
4717         break;
4718       }
4719     }
4720     if (!hasElements)
4721     {
4722       mColumnStretchFactors.removeAt(col);
4723       for (int row=0; row<rowCount(); ++row)
4724         mElements[row].removeAt(col);
4725     }
4726   }
4727 }
4728 
4729 /* inherits documentation from base class */
4730 QSize QCPLayoutGrid::minimumOuterSizeHint() const
4731 {
4732   QVector<int> minColWidths, minRowHeights;
4733   getMinimumRowColSizes(&minColWidths, &minRowHeights);
4734   QSize result(0, 0);
4735   foreach (int w, minColWidths)
4736     result.rwidth() += w;
4737   foreach (int h, minRowHeights)
4738     result.rheight() += h;
4739   result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
4740   result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
4741   result.rwidth() += mMargins.left()+mMargins.right();
4742   result.rheight() += mMargins.top()+mMargins.bottom();
4743   return result;
4744 }
4745 
4746 /* inherits documentation from base class */
4747 QSize QCPLayoutGrid::maximumOuterSizeHint() const
4748 {
4749   QVector<int> maxColWidths, maxRowHeights;
4750   getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
4751   
4752   QSize result(0, 0);
4753   foreach (int w, maxColWidths)
4754     result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX));
4755   foreach (int h, maxRowHeights)
4756     result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX));
4757   result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
4758   result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
4759   result.rwidth() += mMargins.left()+mMargins.right();
4760   result.rheight() += mMargins.top()+mMargins.bottom();
4761   if (result.height() > QWIDGETSIZE_MAX)
4762     result.setHeight(QWIDGETSIZE_MAX);
4763   if (result.width() > QWIDGETSIZE_MAX)
4764     result.setWidth(QWIDGETSIZE_MAX);
4765   return result;
4766 }
4767 
4768 /*! \internal
4769   
4770   Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
4771   respectively.
4772   
4773   The minimum height of a row is the largest minimum height of any element's outer rect in that
4774   row. The minimum width of a column is the largest minimum width of any element's outer rect in
4775   that column.
4776   
4777   This is a helper function for \ref updateLayout.
4778   
4779   \see getMaximumRowColSizes
4780 */
4781 void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
4782 {
4783   *minColWidths = QVector<int>(columnCount(), 0);
4784   *minRowHeights = QVector<int>(rowCount(), 0);
4785   for (int row=0; row<rowCount(); ++row)
4786   {
4787     for (int col=0; col<columnCount(); ++col)
4788     {
4789       if (QCPLayoutElement *el = mElements.at(row).at(col))
4790       {
4791         QSize minSize = getFinalMinimumOuterSize(el);
4792         if (minColWidths->at(col) < minSize.width())
4793           (*minColWidths)[col] = minSize.width();
4794         if (minRowHeights->at(row) < minSize.height())
4795           (*minRowHeights)[row] = minSize.height();
4796       }
4797     }
4798   }
4799 }
4800 
4801 /*! \internal
4802   
4803   Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
4804   respectively.
4805   
4806   The maximum height of a row is the smallest maximum height of any element's outer rect in that
4807   row. The maximum width of a column is the smallest maximum width of any element's outer rect in
4808   that column.
4809   
4810   This is a helper function for \ref updateLayout.
4811   
4812   \see getMinimumRowColSizes
4813 */
4814 void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
4815 {
4816   *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
4817   *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
4818   for (int row=0; row<rowCount(); ++row)
4819   {
4820     for (int col=0; col<columnCount(); ++col)
4821     {
4822       if (QCPLayoutElement *el = mElements.at(row).at(col))
4823       {
4824         QSize maxSize = getFinalMaximumOuterSize(el);
4825         if (maxColWidths->at(col) > maxSize.width())
4826           (*maxColWidths)[col] = maxSize.width();
4827         if (maxRowHeights->at(row) > maxSize.height())
4828           (*maxRowHeights)[row] = maxSize.height();
4829       }
4830     }
4831   }
4832 }
4833 
4834 
4835 ////////////////////////////////////////////////////////////////////////////////////////////////////
4836 //////////////////// QCPLayoutInset
4837 ////////////////////////////////////////////////////////////////////////////////////////////////////
4838 /*! \class QCPLayoutInset
4839   \brief A layout that places child elements aligned to the border or arbitrarily positioned
4840   
4841   Elements are placed either aligned to the border or at arbitrary position in the area of the
4842   layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
4843   setInsetPlacement).
4844 
4845   Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
4846   addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
4847   placement will default to \ref ipBorderAligned and the element will be aligned according to the
4848   \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
4849   arbitrary position and size, defined by \a rect.
4850   
4851   The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
4852   
4853   This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
4854 */
4855 
4856 /* start documentation of inline functions */
4857 
4858 /*! \fn virtual void QCPLayoutInset::simplify()
4859   
4860   The QCPInsetLayout does not need simplification since it can never have empty cells due to its
4861   linear index structure. This method does nothing.
4862 */
4863 
4864 /* end documentation of inline functions */
4865 
4866 /*!
4867   Creates an instance of QCPLayoutInset and sets default values.
4868 */
4869 QCPLayoutInset::QCPLayoutInset()
4870 {
4871 }
4872 
4873 QCPLayoutInset::~QCPLayoutInset()
4874 {
4875   // clear all child layout elements. This is important because only the specific layouts know how
4876   // to handle removing elements (clear calls virtual removeAt method to do that).
4877   clear();
4878 }
4879 
4880 /*!
4881   Returns the placement type of the element with the specified \a index.
4882 */
4883 QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
4884 {
4885   if (elementAt(index))
4886     return mInsetPlacement.at(index);
4887   else
4888   {
4889     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4890     return ipFree;
4891   }
4892 }
4893 
4894 /*!
4895   Returns the alignment of the element with the specified \a index. The alignment only has a
4896   meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
4897 */
4898 Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
4899 {
4900   if (elementAt(index))
4901     return mInsetAlignment.at(index);
4902   else
4903   {
4904     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4905 #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
4906     return nullptr;
4907 #else
4908     return {};
4909 #endif
4910   }
4911 }
4912 
4913 /*!
4914   Returns the rect of the element with the specified \a index. The rect only has a
4915   meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
4916 */
4917 QRectF QCPLayoutInset::insetRect(int index) const
4918 {
4919   if (elementAt(index))
4920     return mInsetRect.at(index);
4921   else
4922   {
4923     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4924     return {};
4925   }
4926 }
4927 
4928 /*!
4929   Sets the inset placement type of the element with the specified \a index to \a placement.
4930   
4931   \see InsetPlacement
4932 */
4933 void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
4934 {
4935   if (elementAt(index))
4936     mInsetPlacement[index] = placement;
4937   else
4938     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4939 }
4940 
4941 /*!
4942   If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
4943   is used to set the alignment of the element with the specified \a index to \a alignment.
4944   
4945   \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
4946   Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
4947   alignment flags will be ignored.
4948 */
4949 void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
4950 {
4951   if (elementAt(index))
4952     mInsetAlignment[index] = alignment;
4953   else
4954     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4955 }
4956 
4957 /*!
4958   If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
4959   position and size of the element with the specified \a index to \a rect.
4960   
4961   \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
4962   will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
4963   corner of the layout, with 35% width and height of the parent layout.
4964   
4965   Note that the minimum and maximum sizes of the embedded element (\ref
4966   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
4967 */
4968 void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
4969 {
4970   if (elementAt(index))
4971     mInsetRect[index] = rect;
4972   else
4973     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4974 }
4975 
4976 /* inherits documentation from base class */
4977 void QCPLayoutInset::updateLayout()
4978 {
4979   for (int i=0; i<mElements.size(); ++i)
4980   {
4981     QCPLayoutElement *el = mElements.at(i);
4982     QRect insetRect;
4983     QSize finalMinSize = getFinalMinimumOuterSize(el);
4984     QSize finalMaxSize = getFinalMaximumOuterSize(el);
4985     if (mInsetPlacement.at(i) == ipFree)
4986     {
4987       insetRect = QRect(int( rect().x()+rect().width()*mInsetRect.at(i).x() ),
4988                         int( rect().y()+rect().height()*mInsetRect.at(i).y() ),
4989                         int( rect().width()*mInsetRect.at(i).width() ),
4990                         int( rect().height()*mInsetRect.at(i).height() ));
4991       if (insetRect.size().width() < finalMinSize.width())
4992         insetRect.setWidth(finalMinSize.width());
4993       if (insetRect.size().height() < finalMinSize.height())
4994         insetRect.setHeight(finalMinSize.height());
4995       if (insetRect.size().width() > finalMaxSize.width())
4996         insetRect.setWidth(finalMaxSize.width());
4997       if (insetRect.size().height() > finalMaxSize.height())
4998         insetRect.setHeight(finalMaxSize.height());
4999     } else if (mInsetPlacement.at(i) == ipBorderAligned)
5000     {
5001       insetRect.setSize(finalMinSize);
5002       Qt::Alignment al = mInsetAlignment.at(i);
5003       if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
5004       else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
5005       else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter
5006       if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
5007       else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
5008       else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter
5009     }
5010     mElements.at(i)->setOuterRect(insetRect);
5011   }
5012 }
5013 
5014 /* inherits documentation from base class */
5015 int QCPLayoutInset::elementCount() const
5016 {
5017   return mElements.size();
5018 }
5019 
5020 /* inherits documentation from base class */
5021 QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
5022 {
5023   if (index >= 0 && index < mElements.size())
5024     return mElements.at(index);
5025   else
5026     return nullptr;
5027 }
5028 
5029 /* inherits documentation from base class */
5030 QCPLayoutElement *QCPLayoutInset::takeAt(int index)
5031 {
5032   if (QCPLayoutElement *el = elementAt(index))
5033   {
5034     releaseElement(el);
5035     mElements.removeAt(index);
5036     mInsetPlacement.removeAt(index);
5037     mInsetAlignment.removeAt(index);
5038     mInsetRect.removeAt(index);
5039     return el;
5040   } else
5041   {
5042     qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
5043     return nullptr;
5044   }
5045 }
5046 
5047 /* inherits documentation from base class */
5048 bool QCPLayoutInset::take(QCPLayoutElement *element)
5049 {
5050   if (element)
5051   {
5052     for (int i=0; i<elementCount(); ++i)
5053     {
5054       if (elementAt(i) == element)
5055       {
5056         takeAt(i);
5057         return true;
5058       }
5059     }
5060     qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
5061   } else
5062     qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
5063   return false;
5064 }
5065 
5066 /*!
5067   The inset layout is sensitive to events only at areas where its (visible) child elements are
5068   sensitive. If the selectTest method of any of the child elements returns a positive number for \a
5069   pos, this method returns a value corresponding to 0.99 times the parent plot's selection
5070   tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
5071   -1.0 is returned.
5072   
5073   See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
5074 */
5075 double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
5076 {
5077   Q_UNUSED(details)
5078   if (onlySelectable)
5079     return -1;
5080   
5081   foreach (QCPLayoutElement *el, mElements)
5082   {
5083     // inset layout shall only return positive selectTest, if actually an inset object is at pos
5084     // else it would block the entire underlying QCPAxisRect with its surface.
5085     if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0)
5086       return mParentPlot->selectionTolerance()*0.99;
5087   }
5088   return -1;
5089 }
5090 
5091 /*!
5092   Adds the specified \a element to the layout as an inset aligned at the border (\ref
5093   setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
5094   alignment.
5095   
5096   \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
5097   Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
5098   alignment flags will be ignored.
5099   
5100   \see addElement(QCPLayoutElement *element, const QRectF &rect)
5101 */
5102 void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
5103 {
5104   if (element)
5105   {
5106     if (element->layout()) // remove from old layout first
5107       element->layout()->take(element);
5108     mElements.append(element);
5109     mInsetPlacement.append(ipBorderAligned);
5110     mInsetAlignment.append(alignment);
5111     mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
5112     adoptElement(element);
5113   } else
5114     qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
5115 }
5116 
5117 /*!
5118   Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
5119   setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
5120   rect.
5121   
5122   \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
5123   will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
5124   corner of the layout, with 35% width and height of the parent layout.
5125   
5126   \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
5127 */
5128 void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
5129 {
5130   if (element)
5131   {
5132     if (element->layout()) // remove from old layout first
5133       element->layout()->take(element);
5134     mElements.append(element);
5135     mInsetPlacement.append(ipFree);
5136     mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
5137     mInsetRect.append(rect);
5138     adoptElement(element);
5139   } else
5140     qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
5141 }
5142 /* end of 'src/layout.cpp' */
5143 
5144 
5145 /* including file 'src/lineending.cpp'      */
5146 /* modified 2021-03-29T02:30:44, size 11189 */
5147 
5148 ////////////////////////////////////////////////////////////////////////////////////////////////////
5149 //////////////////// QCPLineEnding
5150 ////////////////////////////////////////////////////////////////////////////////////////////////////
5151 
5152 /*! \class QCPLineEnding
5153   \brief Handles the different ending decorations for line-like items
5154   
5155   \image html QCPLineEnding.png "The various ending styles currently supported"
5156   
5157   For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
5158   has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
5159  
5160   The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
5161   be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
5162   the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
5163   For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
5164   directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
5165   respective arrow point inward.
5166   
5167   Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
5168   QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
5169   \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
5170 */
5171 
5172 /*!
5173   Creates a QCPLineEnding instance with default values (style \ref esNone).
5174 */
5175 QCPLineEnding::QCPLineEnding() :
5176   mStyle(esNone),
5177   mWidth(8),
5178   mLength(10),
5179   mInverted(false)
5180 {
5181 }
5182 
5183 /*!
5184   Creates a QCPLineEnding instance with the specified values.
5185 */
5186 QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
5187   mStyle(style),
5188   mWidth(width),
5189   mLength(length),
5190   mInverted(inverted)
5191 {
5192 }
5193 
5194 /*!
5195   Sets the style of the ending decoration.
5196 */
5197 void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
5198 {
5199   mStyle = style;
5200 }
5201 
5202 /*!
5203   Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
5204   width defines the size perpendicular to the arrow's pointing direction.
5205   
5206   \see setLength
5207 */
5208 void QCPLineEnding::setWidth(double width)
5209 {
5210   mWidth = width;
5211 }
5212 
5213 /*!
5214   Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
5215   length defines the size in pointing direction.
5216   
5217   \see setWidth
5218 */
5219 void QCPLineEnding::setLength(double length)
5220 {
5221   mLength = length;
5222 }
5223 
5224 /*!
5225   Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
5226   inward when \a inverted is set to true.
5227 
5228   Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
5229   discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
5230   affected by it, which can be used to control to which side the half bar points to.
5231 */
5232 void QCPLineEnding::setInverted(bool inverted)
5233 {
5234   mInverted = inverted;
5235 }
5236 
5237 /*! \internal
5238   
5239   Returns the maximum pixel radius the ending decoration might cover, starting from the position
5240   the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
5241   
5242   This is relevant for clipping. Only omit painting of the decoration when the position where the
5243   decoration is supposed to be drawn is farther away from the clipping rect than the returned
5244   distance.
5245 */
5246 double QCPLineEnding::boundingDistance() const
5247 {
5248   switch (mStyle)
5249   {
5250     case esNone:
5251       return 0;
5252       
5253     case esFlatArrow:
5254     case esSpikeArrow:
5255     case esLineArrow:
5256     case esSkewedBar:
5257       return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
5258       
5259     case esDisc:
5260     case esSquare:
5261     case esDiamond:
5262     case esBar:
5263     case esHalfBar:
5264       return mWidth*1.42; // items that only have a width -> width*sqrt(2)
5265 
5266   }
5267   return 0;
5268 }
5269 
5270 /*!
5271   Starting from the origin of this line ending (which is style specific), returns the length
5272   covered by the line ending symbol, in backward direction.
5273   
5274   For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
5275   both have the same \ref setLength value, because the spike arrow has an inward curved back, which
5276   reduces the length along its center axis (the drawing origin for arrows is at the tip).
5277   
5278   This function is used for precise, style specific placement of line endings, for example in
5279   QCPAxes.
5280 */
5281 double QCPLineEnding::realLength() const
5282 {
5283   switch (mStyle)
5284   {
5285     case esNone:
5286     case esLineArrow:
5287     case esSkewedBar:
5288     case esBar:
5289     case esHalfBar:
5290       return 0;
5291       
5292     case esFlatArrow:
5293       return mLength;
5294       
5295     case esDisc:
5296     case esSquare:
5297     case esDiamond:
5298       return mWidth*0.5;
5299       
5300     case esSpikeArrow:
5301       return mLength*0.8;
5302   }
5303   return 0;
5304 }
5305 
5306 /*! \internal
5307   
5308   Draws the line ending with the specified \a painter at the position \a pos. The direction of the
5309   line ending is controlled with \a dir.
5310 */
5311 void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
5312 {
5313   if (mStyle == esNone)
5314     return;
5315   
5316   QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
5317   if (lengthVec.isNull())
5318     lengthVec = QCPVector2D(1, 0);
5319   QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
5320   
5321   QPen penBackup = painter->pen();
5322   QBrush brushBackup = painter->brush();
5323   QPen miterPen = penBackup;
5324   miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
5325   QBrush brush(painter->pen().color(), Qt::SolidPattern);
5326   switch (mStyle)
5327   {
5328     case esNone: break;
5329     case esFlatArrow:
5330     {
5331       QPointF points[3] = {pos.toPointF(),
5332                            (pos-lengthVec+widthVec).toPointF(),
5333                            (pos-lengthVec-widthVec).toPointF()
5334                           };
5335       painter->setPen(miterPen);
5336       painter->setBrush(brush);
5337       painter->drawConvexPolygon(points, 3);
5338       painter->setBrush(brushBackup);
5339       painter->setPen(penBackup);
5340       break;
5341     }
5342     case esSpikeArrow:
5343     {
5344       QPointF points[4] = {pos.toPointF(),
5345                            (pos-lengthVec+widthVec).toPointF(),
5346                            (pos-lengthVec*0.8).toPointF(),
5347                            (pos-lengthVec-widthVec).toPointF()
5348                           };
5349       painter->setPen(miterPen);
5350       painter->setBrush(brush);
5351       painter->drawConvexPolygon(points, 4);
5352       painter->setBrush(brushBackup);
5353       painter->setPen(penBackup);
5354       break;
5355     }
5356     case esLineArrow:
5357     {
5358       QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
5359                            pos.toPointF(),
5360                            (pos-lengthVec-widthVec).toPointF()
5361                           };
5362       painter->setPen(miterPen);
5363       painter->drawPolyline(points, 3);
5364       painter->setPen(penBackup);
5365       break;
5366     }
5367     case esDisc:
5368     {
5369       painter->setBrush(brush);
5370       painter->drawEllipse(pos.toPointF(),  mWidth*0.5, mWidth*0.5);
5371       painter->setBrush(brushBackup);
5372       break;
5373     }
5374     case esSquare:
5375     {
5376       QCPVector2D widthVecPerp = widthVec.perpendicular();
5377       QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
5378                            (pos-widthVecPerp-widthVec).toPointF(),
5379                            (pos+widthVecPerp-widthVec).toPointF(),
5380                            (pos+widthVecPerp+widthVec).toPointF()
5381                           };
5382       painter->setPen(miterPen);
5383       painter->setBrush(brush);
5384       painter->drawConvexPolygon(points, 4);
5385       painter->setBrush(brushBackup);
5386       painter->setPen(penBackup);
5387       break;
5388     }
5389     case esDiamond:
5390     {
5391       QCPVector2D widthVecPerp = widthVec.perpendicular();
5392       QPointF points[4] = {(pos-widthVecPerp).toPointF(),
5393                            (pos-widthVec).toPointF(),
5394                            (pos+widthVecPerp).toPointF(),
5395                            (pos+widthVec).toPointF()
5396                           };
5397       painter->setPen(miterPen);
5398       painter->setBrush(brush);
5399       painter->drawConvexPolygon(points, 4);
5400       painter->setBrush(brushBackup);
5401       painter->setPen(penBackup);
5402       break;
5403     }
5404     case esBar:
5405     {
5406       painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
5407       break;
5408     }
5409     case esHalfBar:
5410     {
5411       painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
5412       break;
5413     }
5414     case esSkewedBar:
5415     {
5416       QCPVector2D shift;
5417       if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic))
5418         shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5);
5419       // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
5420       painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(),
5421                         (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF());
5422       break;
5423     }
5424   }
5425 }
5426 
5427 /*! \internal
5428   \overload
5429   
5430   Draws the line ending. The direction is controlled with the \a angle parameter in radians.
5431 */
5432 void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
5433 {
5434   draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
5435 }
5436 /* end of 'src/lineending.cpp' */
5437 
5438 
5439 /* including file 'src/axis/labelpainter.cpp' */
5440 /* modified 2021-03-29T02:30:44, size 27296   */
5441 
5442 
5443 ////////////////////////////////////////////////////////////////////////////////////////////////////
5444 //////////////////// QCPLabelPainterPrivate
5445 ////////////////////////////////////////////////////////////////////////////////////////////////////
5446 
5447 /*! \class QCPLabelPainterPrivate
5448 
5449   \internal
5450   \brief (Private)
5451   
5452   This is a private class and not part of the public QCustomPlot interface.
5453   
5454 */
5455 
5456 const QChar QCPLabelPainterPrivate::SymbolDot(183);
5457 const QChar QCPLabelPainterPrivate::SymbolCross(215);
5458 
5459 /*!
5460   Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new
5461   instance on every redraw, to utilize the caching mechanisms.
5462   
5463   the \a parentPlot does not take ownership of the label painter. Make sure
5464   to delete it appropriately.
5465 */
5466 QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) :
5467   mAnchorMode(amRectangular),
5468   mAnchorSide(asLeft),
5469   mAnchorReferenceType(artNormal),
5470   mColor(Qt::black),
5471   mPadding(0),
5472   mRotation(0),
5473   mSubstituteExponent(true),
5474   mMultiplicationSymbol(QChar(215)),
5475   mAbbreviateDecimalPowers(false),
5476   mParentPlot(parentPlot),
5477   mLabelCache(16)
5478 {
5479   analyzeFontMetrics();
5480 }
5481 
5482 QCPLabelPainterPrivate::~QCPLabelPainterPrivate()
5483 {
5484 }
5485 
5486 void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side)
5487 {
5488   mAnchorSide = side;
5489 }
5490 
5491 void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode)
5492 {
5493   mAnchorMode = mode;
5494 }
5495 
5496 void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint)
5497 {
5498   mAnchorReference = pixelPoint;
5499 }
5500 
5501 void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type)
5502 {
5503   mAnchorReferenceType = type;
5504 }
5505 
5506 void QCPLabelPainterPrivate::setFont(const QFont &font)
5507 {
5508   if (mFont != font)
5509   {
5510     mFont = font;
5511     analyzeFontMetrics();
5512   }
5513 }
5514 
5515 void QCPLabelPainterPrivate::setColor(const QColor &color)
5516 {
5517   mColor = color;
5518 }
5519 
5520 void QCPLabelPainterPrivate::setPadding(int padding)
5521 {
5522   mPadding = padding;
5523 }
5524 
5525 void QCPLabelPainterPrivate::setRotation(double rotation)
5526 {
5527   mRotation = qBound(-90.0, rotation, 90.0);
5528 }
5529 
5530 void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled)
5531 {
5532   mSubstituteExponent = enabled;
5533 }
5534 
5535 void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol)
5536 {
5537   mMultiplicationSymbol = symbol;
5538 }
5539 
5540 void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled)
5541 {
5542   mAbbreviateDecimalPowers = enabled;
5543 }
5544 
5545 void QCPLabelPainterPrivate::setCacheSize(int labelCount)
5546 {
5547   mLabelCache.setMaxCost(labelCount);
5548 }
5549 
5550 int QCPLabelPainterPrivate::cacheSize() const
5551 {
5552   return mLabelCache.maxCost();
5553 }
5554 
5555 void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text)
5556 {
5557   double realRotation = mRotation;
5558   
5559   AnchorSide realSide = mAnchorSide;
5560   // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference
5561   if (mAnchorMode == amSkewedUpright)
5562   {
5563     realSide = skewedAnchorSide(tickPos, 0.2, 0.3); 
5564   } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent
5565   {
5566     realSide = skewedAnchorSide(tickPos, 0, 0);
5567     realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0;
5568     if (realRotation > 90) realRotation -= 180;
5569     else if (realRotation < -90) realRotation += 180;
5570   }
5571   
5572   realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label
5573   drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text);
5574 }
5575 
5576 /*! \internal
5577   
5578   Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
5579   direction) needed to fit the axis.
5580 */
5581 /* TODO: needed?
5582 int QCPLabelPainterPrivate::size() const
5583 {
5584   int result = 0;
5585   // get length of tick marks pointing outwards:
5586   if (!tickPositions.isEmpty())
5587     result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
5588   
5589   // calculate size of tick labels:
5590   if (tickLabelSide == QCPAxis::lsOutside)
5591   {
5592     QSize tickLabelsSize(0, 0);
5593     if (!tickLabels.isEmpty())
5594     {
5595       for (int i=0; i<tickLabels.size(); ++i)
5596         getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
5597       result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
5598     result += tickLabelPadding;
5599     }
5600   }
5601   
5602   // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
5603   if (!label.isEmpty())
5604   {
5605     QFontMetrics fontMetrics(labelFont);
5606     QRect bounds;
5607     bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
5608     result += bounds.height() + labelPadding;
5609   }
5610 
5611   return result;
5612 }
5613 */
5614 
5615 /*! \internal
5616   
5617   Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
5618   method is called automatically if any parameters have changed that invalidate the cached labels,
5619   such as font, color, etc. Usually you won't need to call this method manually.
5620 */
5621 void QCPLabelPainterPrivate::clearCache()
5622 {
5623   mLabelCache.clear();
5624 }
5625 
5626 /*! \internal
5627   
5628   Returns a hash that allows uniquely identifying whether the label parameters have changed such
5629   that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
5630   return value of this method hasn't changed since the last redraw, the respective label parameters
5631   haven't changed and cached labels may be used.
5632 */
5633 QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const
5634 {
5635   QByteArray result;
5636   result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
5637   result.append(QByteArray::number(mRotation));
5638   //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property
5639   result.append(QByteArray::number((int)mSubstituteExponent));
5640   result.append(QString(mMultiplicationSymbol).toUtf8());
5641   result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16));
5642   result.append(mFont.toString().toLatin1());
5643   return result;
5644 }
5645 
5646 /*! \internal
5647   
5648   Draws a single tick label with the provided \a painter, utilizing the internal label cache to
5649   significantly speed up drawing of labels that were drawn in previous calls. The tick label is
5650   always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
5651   pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
5652   for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
5653   at which the label should be drawn.
5654   
5655   In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
5656   largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
5657   drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
5658   tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
5659   holds.
5660   
5661   The label is drawn with the font and pen that are currently set on the \a painter. To draw
5662   superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
5663   getTickLabelData).
5664 */
5665 void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text)
5666 {
5667   // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
5668   if (text.isEmpty()) return;
5669   QSize finalSize;
5670 
5671   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
5672   {
5673     QByteArray key = cacheKey(text, color, rotation, side);
5674     CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards)
5675     if (!cachedLabel)  // no cached label existed, create it
5676     {
5677       LabelData labelData = getTickLabelData(font, color, rotation, side, text);
5678       cachedLabel = createCachedLabel(labelData);
5679     }
5680     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
5681     bool labelClippedByBorder = false;
5682     /*
5683     if (tickLabelSide == QCPAxis::lsOutside)
5684     {
5685       if (QCPAxis::orientation(type) == Qt::Horizontal)
5686         labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
5687       else
5688         labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
5689     }
5690     */
5691     if (!labelClippedByBorder)
5692     {
5693       painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap);
5694       finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list?
5695     }
5696     mLabelCache.insert(QString::fromUtf8(key), cachedLabel);
5697   } else // label caching disabled, draw text directly on surface:
5698   {
5699     LabelData labelData = getTickLabelData(font, color, rotation, side, text);
5700     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
5701      bool labelClippedByBorder = false;
5702      /*
5703     if (tickLabelSide == QCPAxis::lsOutside)
5704     {
5705       if (QCPAxis::orientation(type) == Qt::Horizontal)
5706         labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
5707       else
5708         labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
5709     }
5710     */
5711     if (!labelClippedByBorder)
5712     {
5713       drawText(painter, pos, labelData);
5714       finalSize = labelData.rotatedTotalBounds.size();
5715     }
5716   }
5717   /*
5718   // expand passed tickLabelsSize if current tick label is larger:
5719   if (finalSize.width() > tickLabelsSize->width())
5720     tickLabelsSize->setWidth(finalSize.width());
5721   if (finalSize.height() > tickLabelsSize->height())
5722     tickLabelsSize->setHeight(finalSize.height());
5723   */
5724 }
5725 
5726 QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos)
5727 {
5728   switch (mAnchorMode)
5729   {
5730     case amRectangular:
5731     {
5732       switch (mAnchorSide)
5733       {
5734         case asLeft:   return tickPos+QPointF(mPadding, 0);
5735         case asRight:  return tickPos+QPointF(-mPadding, 0);
5736         case asTop:    return tickPos+QPointF(0, mPadding);
5737         case asBottom: return tickPos+QPointF(0, -mPadding);
5738         case asTopLeft:     return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
5739         case asTopRight:    return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
5740         case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
5741         case asBottomLeft:  return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
5742       }
5743       break; // To appease the compiler. All possible values in above case.
5744     }
5745     case amSkewedUpright:
5746     case amSkewedRotated:
5747     {
5748       QCPVector2D anchorNormal(tickPos-mAnchorReference);
5749       if (mAnchorReferenceType == artTangent)
5750         anchorNormal = anchorNormal.perpendicular();
5751       anchorNormal.normalize();
5752       return tickPos+(anchorNormal*mPadding).toPointF();
5753     }
5754   }
5755   return tickPos;
5756 }
5757 
5758 /*! \internal
5759   
5760   This is a \ref placeTickLabel helper function.
5761   
5762   Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
5763   y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
5764   directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
5765   QCP::phCacheLabels plotting hint is not set.
5766 */
5767 void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const
5768 {
5769   // backup painter settings that we're about to change:
5770   QTransform oldTransform = painter->transform();
5771   QFont oldFont = painter->font();
5772   QPen oldPen = painter->pen();
5773   
5774   // transform painter to position/rotation:
5775   painter->translate(pos);
5776   painter->setTransform(labelData.transform, true);
5777   
5778   // draw text:
5779   painter->setFont(labelData.baseFont);
5780   painter->setPen(QPen(labelData.color));
5781   if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting
5782   {
5783     painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
5784     if (!labelData.suffixPart.isEmpty())
5785       painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
5786     painter->setFont(labelData.expFont);
5787     painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip,  labelData.expPart);
5788   } else
5789   {
5790     painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
5791   }
5792   
5793   /* Debug code to draw label bounding boxes, baseline, and capheight
5794   painter->save();
5795   painter->setPen(QPen(QColor(0, 0, 0, 150)));
5796   painter->drawRect(labelData.totalBounds);
5797   const int baseline = labelData.totalBounds.height()-mLetterDescent;
5798   painter->setPen(QPen(QColor(255, 0, 0, 150)));
5799   painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline));
5800   painter->setPen(QPen(QColor(0, 0, 255, 150)));
5801   painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight));
5802   painter->restore();
5803   */
5804   
5805   // reset painter settings to what it was before:
5806   painter->setTransform(oldTransform);
5807   painter->setFont(oldFont);
5808   painter->setPen(oldPen);
5809 }
5810 
5811 /*! \internal
5812   
5813   This is a \ref placeTickLabel helper function.
5814   
5815   Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
5816   processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
5817   exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
5818 */
5819 QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const
5820 {
5821   LabelData result;
5822   result.rotation = rotation;
5823   result.side = side;
5824   result.color = color;
5825   
5826   // determine whether beautiful decimal powers should be used
5827   bool useBeautifulPowers = false;
5828   int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
5829   int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
5830   if (mSubstituteExponent)
5831   {
5832     ePos = text.indexOf(QLatin1Char('e'));
5833     if (ePos > 0 && text.at(ePos-1).isDigit())
5834     {
5835       eLast = ePos;
5836       while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
5837         ++eLast;
5838       if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
5839         useBeautifulPowers = true;
5840     }
5841   }
5842   
5843   // calculate text bounding rects and do string preparation for beautiful decimal powers:
5844   result.baseFont = font;
5845   if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
5846     result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
5847   
5848   QFontMetrics baseFontMetrics(result.baseFont);
5849   if (useBeautifulPowers)
5850   {
5851     // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
5852     result.basePart = text.left(ePos);
5853     result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
5854     // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
5855     if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1"))
5856       result.basePart = QLatin1String("10");
5857     else
5858       result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10");
5859     result.expPart = text.mid(ePos+1, eLast-ePos);
5860     // clip "+" and leading zeros off expPart:
5861     while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
5862       result.expPart.remove(1, 1);
5863     if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
5864       result.expPart.remove(0, 1);
5865     // prepare smaller font for exponent:
5866     result.expFont = font;
5867     if (result.expFont.pointSize() > 0)
5868       result.expFont.setPointSize(result.expFont.pointSize()*0.75);
5869     else
5870       result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
5871     // calculate bounding rects of base part(s), exponent part and total one:
5872     result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
5873     result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
5874     if (!result.suffixPart.isEmpty())
5875       result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
5876     result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
5877   } else // useBeautifulPowers == false
5878   {
5879     result.basePart = text;
5880     result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
5881   }
5882   result.totalBounds.moveTopLeft(QPoint(0, 0));
5883   applyAnchorTransform(result);
5884   result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds);
5885   
5886   return result;
5887 }
5888 
5889 void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const
5890 {
5891   if (!qFuzzyIsNull(labelData.rotation))
5892     labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system)
5893   
5894   // from now on we translate in rotated label-local coordinate system.
5895   // shift origin of coordinate system to appropriate point on label:
5896   labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters
5897   
5898   if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically
5899     labelData.transform.translate(0, -mLetterCapHeight/2.0);
5900   else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally
5901     labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
5902   
5903   if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right
5904     labelData.transform.translate(-labelData.totalBounds.width(), 0);
5905   if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!)
5906     labelData.transform.translate(0, -mLetterCapHeight);
5907 }
5908 
5909 /*! \internal
5910   
5911   Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
5912   to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
5913   margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
5914   smaller width/height.
5915 */
5916 /*
5917 void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text,  QSize *tickLabelsSize) const
5918 {
5919   // note: this function must return the same tick label sizes as the placeTickLabel function.
5920   QSize finalSize;
5921   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
5922   {
5923     const CachedLabel *cachedLabel = mLabelCache.object(text);
5924     finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
5925   } else // label caching disabled or no label with this text cached:
5926   {
5927     // TODO: LabelData labelData = getTickLabelData(font, text);
5928     // TODO: finalSize = labelData.rotatedTotalBounds.size();
5929   }
5930   
5931   // expand passed tickLabelsSize if current tick label is larger:
5932   if (finalSize.width() > tickLabelsSize->width())
5933     tickLabelsSize->setWidth(finalSize.width());
5934   if (finalSize.height() > tickLabelsSize->height())
5935     tickLabelsSize->setHeight(finalSize.height());
5936 }
5937 */
5938 
5939 QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const
5940 {
5941   CachedLabel *result = new CachedLabel;
5942   
5943   // allocate pixmap with the correct size and pixel ratio:
5944   if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
5945   {
5946     result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
5947 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
5948 #  ifdef QCP_DEVICEPIXELRATIO_FLOAT
5949     result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
5950 #  else
5951     result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
5952 #  endif
5953 #endif
5954   } else
5955     result->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
5956   result->pixmap.fill(Qt::transparent);
5957   
5958   // draw the label into the pixmap
5959   // offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos.
5960   // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0)
5961   result->offset = labelData.rotatedTotalBounds.topLeft();
5962   QCPPainter cachePainter(&result->pixmap);
5963   drawText(&cachePainter, -result->offset, labelData);
5964   return result;
5965 }
5966 
5967 QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const
5968 {
5969   return text.toUtf8()+
5970       QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+
5971       QByteArray::number(color.alpha()+256*(int)side, 36)+
5972       QByteArray::number((int)(rotation*100)%36000, 36);
5973 }
5974 
5975 QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const
5976 {
5977   QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference);
5978   if (mAnchorReferenceType == artTangent)
5979     anchorNormal = anchorNormal.perpendicular();
5980   const double radius = anchorNormal.length();
5981   const double sideHorz = sideExpandHorz*radius;
5982   const double sideVert = sideExpandVert*radius;
5983   if (anchorNormal.x() > sideHorz)
5984   {
5985     if (anchorNormal.y() > sideVert) return asTopLeft;
5986     else if (anchorNormal.y() < -sideVert) return asBottomLeft;
5987     else return asLeft;
5988   } else if (anchorNormal.x() < -sideHorz)
5989   {
5990     if (anchorNormal.y() > sideVert) return asTopRight;
5991     else if (anchorNormal.y() < -sideVert) return asBottomRight;
5992     else return asRight;
5993   } else
5994   {
5995     if (anchorNormal.y() > 0) return asTop;
5996     else return asBottom;
5997   }
5998   return asBottom; // should never be reached
5999 }
6000 
6001 QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const
6002 {
6003   AnchorSide result = side;
6004   const bool rotateClockwise = rotation > 0;
6005   if (!qFuzzyIsNull(rotation))
6006   {
6007     if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately:
6008     {
6009       if (side == asTop) result = rotateClockwise ? asLeft : asRight;
6010       else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
6011       else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop;
6012       else if (side == asTopRight) result = rotateClockwise ? asTop : asRight;
6013       else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft;
6014       else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom;
6015     } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
6016     {
6017       if (side == asLeft) result = rotateClockwise ? asBottom : asTop;
6018       else if (side == asRight) result = rotateClockwise ? asTop : asBottom;
6019       else if (side == asTop) result = rotateClockwise ? asLeft : asRight;
6020       else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
6021       else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight;
6022       else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight;
6023       else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft;
6024       else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft;
6025     }
6026   }
6027   return result;
6028 }
6029 
6030 void QCPLabelPainterPrivate::analyzeFontMetrics()
6031 {
6032   const QFontMetrics fm(mFont);
6033   mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change
6034   mLetterDescent = fm.descent();
6035 }
6036 /* end of 'src/axis/labelpainter.cpp' */
6037 
6038 
6039 /* including file 'src/axis/axisticker.cpp' */
6040 /* modified 2021-03-29T02:30:44, size 18688 */
6041 
6042 ////////////////////////////////////////////////////////////////////////////////////////////////////
6043 //////////////////// QCPAxisTicker
6044 ////////////////////////////////////////////////////////////////////////////////////////////////////
6045 /*! \class QCPAxisTicker
6046   \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
6047   
6048   Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
6049   and tick labels for the current axis range. The ticker of an axis can be set via \ref
6050   QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
6051   axes can share the same ticker instance.
6052   
6053   This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
6054   reasonable tick step (the separation between ticks) which results in readable tick labels. The
6055   number of ticks that should be approximately generated can be set via \ref setTickCount.
6056   Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
6057   sacrifices readability to better match the specified tick count (\ref
6058   QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
6059   QCPAxisTicker::tssReadability), which is the default.
6060   
6061   The following more specialized axis ticker subclasses are available, see details in the
6062   respective class documentation:
6063   
6064   <center>
6065   <table>
6066   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
6067   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
6068   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
6069   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
6070   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
6071   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
6072     \image html axisticker-time2.png</td></tr>
6073   </table>
6074   </center>
6075   
6076   \section axisticker-subclassing Creating own axis tickers
6077   
6078   Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
6079   reimplementing some or all of the available virtual methods.
6080 
6081   In the simplest case you might wish to just generate different tick steps than the other tickers,
6082   so you only reimplement the method \ref getTickStep. If you additionally want control over the
6083   string that will be shown as tick label, reimplement \ref getTickLabel.
6084   
6085   If you wish to have complete control, you can generate the tick vectors and tick label vectors
6086   yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
6087   implementations use the previously mentioned virtual methods \ref getTickStep and \ref
6088   getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
6089   of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
6090   
6091   The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
6092   placement control is obtained by reimplementing \ref createSubTickVector.
6093   
6094   See the documentation of all these virtual methods in QCPAxisTicker for detailed information
6095   about the parameters and expected return values.
6096 */
6097 
6098 /*!
6099   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6100   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6101 */
6102 QCPAxisTicker::QCPAxisTicker() :
6103   mTickStepStrategy(tssReadability),
6104   mTickCount(5),
6105   mTickOrigin(0)
6106 {
6107 }
6108 
6109 QCPAxisTicker::~QCPAxisTicker()
6110 {
6111   
6112 }
6113 
6114 /*!
6115   Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
6116   available strategies, see \ref TickStepStrategy.
6117 */
6118 void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
6119 {
6120   mTickStepStrategy = strategy;
6121 }
6122 
6123 /*!
6124   Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
6125   is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
6126   the requested number of ticks.
6127 
6128   Whether the readability has priority over meeting the requested \a count can be specified with
6129   \ref setTickStepStrategy.
6130 */
6131 void QCPAxisTicker::setTickCount(int count)
6132 {
6133   if (count > 0)
6134     mTickCount = count;
6135   else
6136     qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
6137 }
6138 
6139 /*!
6140   Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
6141   concept and doesn't need to be inside the currently visible axis range.
6142   
6143   By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
6144   step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
6145   {-4, 1, 6, 11, 16,...}.
6146 */
6147 void QCPAxisTicker::setTickOrigin(double origin)
6148 {
6149   mTickOrigin = origin;
6150 }
6151 
6152 /*!
6153   This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
6154   tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
6155   
6156   The ticks are generated for the specified \a range. The generated labels typically follow the
6157   specified \a locale, \a formatChar and number \a precision, however this might be different (or
6158   even irrelevant) for certain QCPAxisTicker subclasses.
6159   
6160   The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
6161   The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not
6162   needed) and are respectively filled with sub tick coordinates, and tick label strings belonging
6163   to \a ticks by index.
6164 */
6165 void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
6166 {
6167   // generate (major) ticks:
6168   double tickStep = getTickStep(range);
6169   ticks = createTickVector(tickStep, range);
6170   trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
6171   
6172   // generate sub ticks between major ticks:
6173   if (subTicks)
6174   {
6175     if (!ticks.isEmpty())
6176     {
6177       *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
6178       trimTicks(range, *subTicks, false);
6179     } else
6180       *subTicks = QVector<double>();
6181   }
6182   
6183   // finally trim also outliers (no further clipping happens in axis drawing):
6184   trimTicks(range, ticks, false);
6185   // generate labels for visible ticks if requested:
6186   if (tickLabels)
6187     *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
6188 }
6189 
6190 /*! \internal
6191   
6192   Takes the entire currently visible axis range and returns a sensible tick step in
6193   order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
6194   setTickCount, \ref setTickStepStrategy).
6195   
6196   If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
6197   implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
6198   function.
6199 */
6200 double QCPAxisTicker::getTickStep(const QCPRange &range)
6201 {
6202   double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6203   return cleanMantissa(exactStep);
6204 }
6205 
6206 /*! \internal
6207   
6208   Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
6209   an appropriate number of sub ticks for that specific tick step.
6210   
6211   Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
6212 */
6213 int QCPAxisTicker::getSubTickCount(double tickStep)
6214 {
6215   int result = 1; // default to 1, if no proper value can be found
6216   
6217   // separate integer and fractional part of mantissa:
6218   double epsilon = 0.01;
6219   double intPartf;
6220   int intPart;
6221   double fracPart = modf(getMantissa(tickStep), &intPartf);
6222   intPart = int(intPartf);
6223   
6224   // handle cases with (almost) integer mantissa:
6225   if (fracPart < epsilon || 1.0-fracPart < epsilon)
6226   {
6227     if (1.0-fracPart < epsilon)
6228       ++intPart;
6229     switch (intPart)
6230     {
6231       case 1: result = 4; break; // 1.0 -> 0.2 substep
6232       case 2: result = 3; break; // 2.0 -> 0.5 substep
6233       case 3: result = 2; break; // 3.0 -> 1.0 substep
6234       case 4: result = 3; break; // 4.0 -> 1.0 substep
6235       case 5: result = 4; break; // 5.0 -> 1.0 substep
6236       case 6: result = 2; break; // 6.0 -> 2.0 substep
6237       case 7: result = 6; break; // 7.0 -> 1.0 substep
6238       case 8: result = 3; break; // 8.0 -> 2.0 substep
6239       case 9: result = 2; break; // 9.0 -> 3.0 substep
6240     }
6241   } else
6242   {
6243     // handle cases with significantly fractional mantissa:
6244     if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
6245     {
6246       switch (intPart)
6247       {
6248         case 1: result = 2; break; // 1.5 -> 0.5 substep
6249         case 2: result = 4; break; // 2.5 -> 0.5 substep
6250         case 3: result = 4; break; // 3.5 -> 0.7 substep
6251         case 4: result = 2; break; // 4.5 -> 1.5 substep
6252         case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
6253         case 6: result = 4; break; // 6.5 -> 1.3 substep
6254         case 7: result = 2; break; // 7.5 -> 2.5 substep
6255         case 8: result = 4; break; // 8.5 -> 1.7 substep
6256         case 9: result = 4; break; // 9.5 -> 1.9 substep
6257       }
6258     }
6259     // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
6260   }
6261   
6262   return result;
6263 }
6264 
6265 /*! \internal
6266   
6267   This method returns the tick label string as it should be printed under the \a tick coordinate.
6268   If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
6269   precision.
6270   
6271   If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
6272   enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
6273   be formatted accordingly using multiplication symbol and superscript during rendering of the
6274   label automatically.
6275 */
6276 QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
6277 {
6278   return locale.toString(tick, formatChar.toLatin1(), precision);
6279 }
6280 
6281 /*! \internal
6282   
6283   Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
6284   subTickCount sub ticks between each tick pair given in \a ticks.
6285   
6286   If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
6287   reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
6288   base its result on \a subTickCount or \a ticks.
6289 */
6290 QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
6291 {
6292   QVector<double> result;
6293   if (subTickCount <= 0 || ticks.size() < 2)
6294     return result;
6295   
6296   result.reserve((ticks.size()-1)*subTickCount);
6297   for (int i=1; i<ticks.size(); ++i)
6298   {
6299     double subTickStep = (ticks.at(i)-ticks.at(i-1))/double(subTickCount+1);
6300     for (int k=1; k<=subTickCount; ++k)
6301       result.append(ticks.at(i-1) + k*subTickStep);
6302   }
6303   return result;
6304 }
6305 
6306 /*! \internal
6307   
6308   Returns a vector containing all coordinates of ticks that should be drawn. The default
6309   implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
6310   step origin, see \ref setTickOrigin) distributed over the passed \a range.
6311   
6312   In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
6313   last tick coordinates returned by this method are just below/above the provided \a range.
6314   Otherwise the outer intervals won't contain any sub ticks.
6315   
6316   If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
6317   this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
6318   result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
6319   QCPAxisTickerLog.
6320 */
6321 QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
6322 {
6323   QVector<double> result;
6324   // Generate tick positions according to tickStep:
6325   qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision
6326   qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision
6327   int tickcount = int(lastStep-firstStep+1);
6328   if (tickcount < 0) tickcount = 0;
6329   result.resize(tickcount);
6330   for (int i=0; i<tickcount; ++i)
6331     result[i] = mTickOrigin + (firstStep+i)*tickStep;
6332   return result;
6333 }
6334 
6335 /*! \internal
6336   
6337   Returns a vector containing all tick label strings corresponding to the tick coordinates provided
6338   in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
6339   strings.
6340   
6341   It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
6342   reimplementing \ref getTickLabel often achieves the intended result easier.
6343 */
6344 QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
6345 {
6346   QVector<QString> result;
6347   result.reserve(ticks.size());
6348   foreach (double tickCoord, ticks)
6349     result.append(getTickLabel(tickCoord, locale, formatChar, precision));
6350   return result;
6351 }
6352 
6353 /*! \internal
6354   
6355   Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
6356   keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
6357   
6358   The passed \a ticks must be sorted in ascending order.
6359 */
6360 void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
6361 {
6362   bool lowFound = false;
6363   bool highFound = false;
6364   int lowIndex = 0;
6365   int highIndex = -1;
6366   
6367   for (int i=0; i < ticks.size(); ++i)
6368   {
6369     if (ticks.at(i) >= range.lower)
6370     {
6371       lowFound = true;
6372       lowIndex = i;
6373       break;
6374     }
6375   }
6376   for (int i=ticks.size()-1; i >= 0; --i)
6377   {
6378     if (ticks.at(i) <= range.upper)
6379     {
6380       highFound = true;
6381       highIndex = i;
6382       break;
6383     }
6384   }
6385   
6386   if (highFound && lowFound)
6387   {
6388     int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
6389     int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
6390     if (trimFront > 0 || trimBack > 0)
6391       ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
6392   } else // all ticks are either all below or all above the range
6393     ticks.clear();
6394 }
6395 
6396 /*! \internal
6397   
6398   Returns the coordinate contained in \a candidates which is closest to the provided \a target.
6399   
6400   This method assumes \a candidates is not empty and sorted in ascending order.
6401 */
6402 double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
6403 {
6404   if (candidates.size() == 1)
6405     return candidates.first();
6406   QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
6407   if (it == candidates.constEnd())
6408     return *(it-1);
6409   else if (it == candidates.constBegin())
6410     return *it;
6411   else
6412     return target-*(it-1) < *it-target ? *(it-1) : *it;
6413 }
6414 
6415 /*! \internal
6416   
6417   Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
6418   returns the magnitude of \a input as a power of 10.
6419   
6420   For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
6421 */
6422 double QCPAxisTicker::getMantissa(double input, double *magnitude) const
6423 {
6424   const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
6425   if (magnitude) *magnitude = mag;
6426   return input/mag;
6427 }
6428 
6429 /*! \internal
6430   
6431   Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
6432   strongly the mantissa is altered, and thus how strong the result deviates from the original \a
6433   input, depends on the current tick step strategy (see \ref setTickStepStrategy).
6434 */
6435 double QCPAxisTicker::cleanMantissa(double input) const
6436 {
6437   double magnitude;
6438   const double mantissa = getMantissa(input, &magnitude);
6439   switch (mTickStepStrategy)
6440   {
6441     case tssReadability:
6442     {
6443       return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
6444     }
6445     case tssMeetTickCount:
6446     {
6447       // this gives effectively a mantissa of 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0
6448       if (mantissa <= 5.0)
6449         return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
6450       else
6451         return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
6452     }
6453   }
6454   return input;
6455 }
6456 /* end of 'src/axis/axisticker.cpp' */
6457 
6458 
6459 /* including file 'src/axis/axistickerdatetime.cpp' */
6460 /* modified 2021-03-29T02:30:44, size 18829         */
6461 
6462 ////////////////////////////////////////////////////////////////////////////////////////////////////
6463 //////////////////// QCPAxisTickerDateTime
6464 ////////////////////////////////////////////////////////////////////////////////////////////////////
6465 /*! \class QCPAxisTickerDateTime
6466   \brief Specialized axis ticker for calendar dates and times as axis ticks
6467   
6468   \image html axisticker-datetime.png
6469   
6470   This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
6471   plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
6472   UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
6473   with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
6474   by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
6475   and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
6476   millisecond on all Qt versions.
6477   
6478   The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
6479   If a different time spec or time zone shall be used for the tick label appearance, see \ref
6480   setDateTimeSpec or \ref setTimeZone, respectively.
6481   
6482   This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
6483   ticks. For example, if the axis range spans a few years such that there is one tick per year,
6484   ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
6485   will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
6486   the image above: even though the number of days varies month by month, this ticker generates
6487   ticks on the same day of each month.
6488   
6489   If you would like to change the date/time that is used as a (mathematical) starting date for the
6490   ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
6491   QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
6492   9:45 of every year.
6493   
6494   The ticker can be created and assigned to an axis like this:
6495   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
6496   
6497   \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
6498   milliseconds, and are not interested in the intricacies of real calendar dates with months and
6499   (leap) years, have a look at QCPAxisTickerTime instead.
6500 */
6501 
6502 /*!
6503   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6504   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6505 */
6506 QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
6507   mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
6508   mDateTimeSpec(Qt::LocalTime),
6509   mDateStrategy(dsNone)
6510 {
6511   setTickCount(4);
6512 }
6513 
6514 /*!
6515   Sets the format in which dates and times are displayed as tick labels. For details about the \a
6516   format string, see the documentation of QDateTime::toString().
6517   
6518   Typical expressions are
6519   <table>
6520     <tr><td>\c d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
6521     <tr><td>\c dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
6522     <tr><td>\c ddd</td><td>The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
6523     <tr><td>\c dddd</td><td>The long localized day name (e.g. 'Monday' to 'Sunday'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
6524     <tr><td>\c M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
6525     <tr><td>\c MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
6526     <tr><td>\c MMM</td><td>The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
6527     <tr><td>\c MMMM</td><td>The long localized month name (e.g. 'January' to 'December'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
6528     <tr><td>\c yy</td><td>The year as a two digit number (00 to 99)</td></tr>
6529     <tr><td>\c yyyy</td><td>The year as a four digit number. If the year is negative, a minus sign is prepended, making five characters.</td></tr>
6530     <tr><td>\c h</td><td>The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)</td></tr>
6531     <tr><td>\c hh</td><td>The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)</td></tr>
6532     <tr><td>\c H</td><td>The hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
6533     <tr><td>\c HH</td><td>The hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
6534     <tr><td>\c m</td><td>The minute without a leading zero (0 to 59)</td></tr>
6535     <tr><td>\c mm</td><td>The minute with a leading zero (00 to 59)</td></tr>
6536     <tr><td>\c s</td><td>The whole second, without any leading zero (0 to 59)</td></tr>
6537     <tr><td>\c ss</td><td>The whole second, with a leading zero where applicable (00 to 59)</td></tr>
6538     <tr><td>\c z</td><td>The fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus "s.z" reports the seconds to full available (millisecond) precision without trailing zeroes.</td></tr>
6539     <tr><td>\c zzz</td><td>The fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).</td></tr>
6540     <tr><td>\c AP or \c A</td><td>Use AM/PM display. A/AP will be replaced by an upper-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
6541     <tr><td>\c ap or \c a</td><td>Use am/pm display. a/ap will be replaced by a lower-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
6542     <tr><td>\c t</td><td>The timezone (for example "CEST")</td></tr>
6543   </table>
6544   
6545   Newlines can be inserted with \c "\n", literal strings (even when containing above expressions)
6546   by encapsulating them using single-quotes. A literal single quote can be generated by using two
6547   consecutive single quotes in the format.
6548   
6549   \see setDateTimeSpec, setTimeZone
6550 */
6551 void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
6552 {
6553   mDateTimeFormat = format;
6554 }
6555 
6556 /*!
6557   Sets the time spec that is used for creating the tick labels from corresponding dates/times.
6558 
6559   The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
6560   <tt>Qt::LocalTime</tt>. However, if the displayed tick labels shall be given in UTC, set \a spec
6561   to <tt>Qt::UTC</tt>.
6562   
6563   Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets
6564   \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c
6565   Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly.
6566   
6567   \see setDateTimeFormat, setTimeZone
6568 */
6569 void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
6570 {
6571   mDateTimeSpec = spec;
6572 }
6573 
6574 # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
6575 /*!
6576   Sets the time zone that is used for creating the tick labels from corresponding dates/times. The
6577   time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone.
6578   
6579   \see setDateTimeFormat, setTimeZone
6580 */
6581 void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone)
6582 {
6583   mTimeZone = zone;
6584   mDateTimeSpec = Qt::TimeZone;
6585 }
6586 #endif
6587 
6588 /*!
6589   Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
6590   00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
6591   directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
6592   
6593   This is useful to define the month/day/time recurring at greater tick interval steps. For
6594   example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
6595   per year, the ticks will end up on 15. July at 9:45 of every year.
6596 */
6597 void QCPAxisTickerDateTime::setTickOrigin(double origin)
6598 {
6599   QCPAxisTicker::setTickOrigin(origin);
6600 }
6601 
6602 /*!
6603   Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
6604   
6605   This is useful to define the month/day/time recurring at greater tick interval steps. For
6606   example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
6607   per year, the ticks will end up on 15. July at 9:45 of every year.
6608 */
6609 void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
6610 {
6611   setTickOrigin(dateTimeToKey(origin));
6612 }
6613 
6614 /*! \internal
6615   
6616   Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
6617   monthly, bi-monthly, etc.
6618   
6619   Note that this tick step isn't used exactly when generating the tick vector in \ref
6620   createTickVector, but only as a guiding value requiring some correction for each individual tick
6621   interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
6622   in the month to the last day in the previous month from tick to tick, due to the non-uniform
6623   length of months. The same problem arises with leap years.
6624   
6625   \seebaseclassmethod
6626 */
6627 double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
6628 {
6629   double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6630   
6631   mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector
6632   if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
6633   {
6634     result = cleanMantissa(result);
6635   } else if (result < 86400*30.4375*12) // below a year
6636   {
6637     result = pickClosest(result, QVector<double>()
6638                              << 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range
6639                              << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
6640                              << 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years)
6641     if (result > 86400*30.4375-1) // month tick intervals or larger
6642       mDateStrategy = dsUniformDayInMonth;
6643     else if (result > 3600*24-1) // day tick intervals or larger
6644       mDateStrategy = dsUniformTimeInDay;
6645   } else // more than a year, go back to normal clean mantissa algorithm but in units of years
6646   {
6647     const double secondsPerYear = 86400*30.4375*12; // average including leap years
6648     result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
6649     mDateStrategy = dsUniformDayInMonth;
6650   }
6651   return result;
6652 }
6653 
6654 /*! \internal
6655   
6656   Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
6657   monthly, bi-monthly, etc.
6658   
6659   \seebaseclassmethod
6660 */
6661 int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
6662 {
6663   int result = QCPAxisTicker::getSubTickCount(tickStep);
6664   switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
6665   {
6666     case 5*60: result = 4; break;
6667     case 10*60: result = 1; break;
6668     case 15*60: result = 2; break;
6669     case 30*60: result = 1; break;
6670     case 60*60: result = 3; break;
6671     case 3600*2: result = 3; break;
6672     case 3600*3: result = 2; break;
6673     case 3600*6: result = 1; break;
6674     case 3600*12: result = 3; break;
6675     case 3600*24: result = 3; break;
6676     case 86400*2: result = 1; break;
6677     case 86400*5: result = 4; break;
6678     case 86400*7: result = 6; break;
6679     case 86400*14: result = 1; break;
6680     case int(86400*30.4375+0.5): result = 3; break;
6681     case int(86400*30.4375*2+0.5): result = 1; break;
6682     case int(86400*30.4375*3+0.5): result = 2; break;
6683     case int(86400*30.4375*6+0.5): result = 5; break;
6684     case int(86400*30.4375*12+0.5): result = 3; break;
6685   }
6686   return result;
6687 }
6688 
6689 /*! \internal
6690   
6691   Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
6692   (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
6693   setTimeZone).
6694   
6695   \seebaseclassmethod
6696 */
6697 QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
6698 {
6699   Q_UNUSED(precision)
6700   Q_UNUSED(formatChar)
6701 # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
6702   if (mDateTimeSpec == Qt::TimeZone)
6703     return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
6704   else
6705     return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
6706 # else
6707   return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
6708 # endif
6709 }
6710 
6711 /*! \internal
6712   
6713   Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
6714   non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
6715   
6716   \seebaseclassmethod
6717 */
6718 QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
6719 {
6720   QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
6721   if (!result.isEmpty())
6722   {
6723     if (mDateStrategy == dsUniformTimeInDay)
6724     {
6725       QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
6726       QDateTime tickDateTime;
6727       for (int i=0; i<result.size(); ++i)
6728       {
6729         tickDateTime = keyToDateTime(result.at(i));
6730         tickDateTime.setTime(uniformDateTime.time());
6731         result[i] = dateTimeToKey(tickDateTime);
6732       }
6733     } else if (mDateStrategy == dsUniformDayInMonth)
6734     {
6735       QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
6736       QDateTime tickDateTime;
6737       for (int i=0; i<result.size(); ++i)
6738       {
6739         tickDateTime = keyToDateTime(result.at(i));
6740         tickDateTime.setTime(uniformDateTime.time());
6741         int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February)
6742         if (thisUniformDay-tickDateTime.date().day() < -15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
6743           tickDateTime = tickDateTime.addMonths(1);
6744         else if (thisUniformDay-tickDateTime.date().day() > 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
6745           tickDateTime = tickDateTime.addMonths(-1);
6746         tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
6747         result[i] = dateTimeToKey(tickDateTime);
6748       }
6749     }
6750   }
6751   return result;
6752 }
6753 
6754 /*!
6755   A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
6756   QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
6757   
6758   The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
6759   works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
6760   
6761   \see dateTimeToKey
6762 */
6763 QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
6764 {
6765 # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
6766   return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
6767 # else
6768   return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
6769 # endif
6770 }
6771 
6772 /*! \overload
6773   
6774   A convenience method which turns a QDateTime object into a double value that corresponds to
6775   seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
6776   QCPAxisTickerDateTime.
6777   
6778   The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
6779   works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
6780   
6781   \see keyToDateTime
6782 */
6783 double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
6784 {
6785 # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
6786   return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
6787 # else
6788   return dateTime.toMSecsSinceEpoch()/1000.0;
6789 # endif
6790 }
6791 
6792 /*! \overload
6793   
6794   A convenience method which turns a QDate object into a double value that corresponds to seconds
6795   since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
6796   as axis coordinates by QCPAxisTickerDateTime.
6797   
6798   The returned value will be the start of the passed day of \a date, interpreted in the given \a
6799   timeSpec.
6800   
6801   \see keyToDateTime
6802 */
6803 double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
6804 {
6805 # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
6806   return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
6807 # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
6808   return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
6809 # else
6810   return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
6811 # endif
6812 }
6813 /* end of 'src/axis/axistickerdatetime.cpp' */
6814 
6815 
6816 /* including file 'src/axis/axistickertime.cpp' */
6817 /* modified 2021-03-29T02:30:44, size 11745     */
6818 
6819 ////////////////////////////////////////////////////////////////////////////////////////////////////
6820 //////////////////// QCPAxisTickerTime
6821 ////////////////////////////////////////////////////////////////////////////////////////////////////
6822 /*! \class QCPAxisTickerTime
6823   \brief Specialized axis ticker for time spans in units of milliseconds to days
6824   
6825   \image html axisticker-time.png
6826   
6827   This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
6828   
6829   The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
6830   setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
6831   zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
6832   and time.
6833   
6834   The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
6835   largest available unit in the format specified with \ref setTimeFormat, any time spans above will
6836   be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
6837   coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
6838   label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
6839   unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
6840   zero will carry a leading minus sign.
6841   
6842   The ticker can be created and assigned to an axis like this:
6843   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
6844   
6845   Here is an example of a time axis providing time information in days, hours and minutes. Due to
6846   the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
6847   decided to use tick steps of 12 hours:
6848   
6849   \image html axisticker-time2.png
6850   
6851   The format string for this example is
6852   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
6853   
6854   \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
6855   instead.
6856 */
6857 
6858 /*!
6859   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6860   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6861 */
6862 QCPAxisTickerTime::QCPAxisTickerTime() :
6863   mTimeFormat(QLatin1String("%h:%m:%s")),
6864   mSmallestUnit(tuSeconds),
6865   mBiggestUnit(tuHours)
6866 {
6867   setTickCount(4);
6868   mFieldWidth[tuMilliseconds] = 3;
6869   mFieldWidth[tuSeconds] = 2;
6870   mFieldWidth[tuMinutes] = 2;
6871   mFieldWidth[tuHours] = 2;
6872   mFieldWidth[tuDays] = 1;
6873   
6874   mFormatPattern[tuMilliseconds] = QLatin1String("%z");
6875   mFormatPattern[tuSeconds] = QLatin1String("%s");
6876   mFormatPattern[tuMinutes] = QLatin1String("%m");
6877   mFormatPattern[tuHours] = QLatin1String("%h");
6878   mFormatPattern[tuDays] = QLatin1String("%d");
6879 }
6880 
6881 /*!
6882   Sets the format that will be used to display time in the tick labels.
6883   
6884   The available patterns are:
6885   - %%z for milliseconds
6886   - %%s for seconds
6887   - %%m for minutes
6888   - %%h for hours
6889   - %%d for days
6890   
6891   The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
6892   
6893   The largest unit that appears in \a format will carry all the remaining time of a certain tick
6894   coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
6895   largest unit it might become larger than 59 in order to consume larger time values. If on the
6896   other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
6897   carry to the hour digit.
6898 */
6899 void QCPAxisTickerTime::setTimeFormat(const QString &format)
6900 {
6901   mTimeFormat = format;
6902   
6903   // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
6904   // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
6905   mSmallestUnit = tuMilliseconds;
6906   mBiggestUnit = tuMilliseconds;
6907   bool hasSmallest = false;
6908   for (int i = tuMilliseconds; i <= tuDays; ++i)
6909   {
6910     TimeUnit unit = static_cast<TimeUnit>(i);
6911     if (mTimeFormat.contains(mFormatPattern.value(unit)))
6912     {
6913       if (!hasSmallest)
6914       {
6915         mSmallestUnit = unit;
6916         hasSmallest = true;
6917       }
6918       mBiggestUnit = unit;
6919     }
6920   }
6921 }
6922 
6923 /*!
6924   Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
6925   label. If the number for the specific unit is shorter than \a width, it will be padded with an
6926   according number of zeros to the left in order to reach the field width.
6927   
6928   \see setTimeFormat
6929 */
6930 void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
6931 {
6932   mFieldWidth[unit] = qMax(width, 1);
6933 }
6934 
6935 /*! \internal
6936 
6937   Returns the tick step appropriate for time displays, depending on the provided \a range and the
6938   smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
6939   of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
6940   that require sub-minute precision to be displayed correctly.
6941   
6942   \seebaseclassmethod
6943 */
6944 double QCPAxisTickerTime::getTickStep(const QCPRange &range)
6945 {
6946   double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6947   
6948   if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
6949   {
6950     if (mSmallestUnit == tuMilliseconds)
6951       result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
6952     else // have no milliseconds available in format, so stick with 1 second tickstep
6953       result = 1.0;
6954   } else if (result < 3600*24) // below a day
6955   {
6956     // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
6957     QVector<double> availableSteps;
6958     // seconds range:
6959     if (mSmallestUnit <= tuSeconds)
6960       availableSteps << 1;
6961     if (mSmallestUnit == tuMilliseconds)
6962       availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
6963     else if (mSmallestUnit == tuSeconds)
6964       availableSteps << 2;
6965     if (mSmallestUnit <= tuSeconds)
6966       availableSteps << 5 << 10 << 15 << 30;
6967     // minutes range:
6968     if (mSmallestUnit <= tuMinutes)
6969       availableSteps << 1*60;
6970     if (mSmallestUnit <= tuSeconds)
6971       availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
6972     else if (mSmallestUnit == tuMinutes)
6973       availableSteps << 2*60;
6974     if (mSmallestUnit <= tuMinutes)
6975       availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
6976     // hours range:
6977     if (mSmallestUnit <= tuHours)
6978       availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
6979     // pick available step that is most appropriate to approximate ideal step:
6980     result = pickClosest(result, availableSteps);
6981   } else // more than a day, go back to normal clean mantissa algorithm but in units of days
6982   {
6983     const double secondsPerDay = 3600*24;
6984     result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
6985   }
6986   return result;
6987 }
6988 
6989 /*! \internal
6990 
6991   Returns the sub tick count appropriate for the provided \a tickStep and time displays.
6992   
6993   \seebaseclassmethod
6994 */
6995 int QCPAxisTickerTime::getSubTickCount(double tickStep)
6996 {
6997   int result = QCPAxisTicker::getSubTickCount(tickStep);
6998   switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
6999   {
7000     case 5*60: result = 4; break;
7001     case 10*60: result = 1; break;
7002     case 15*60: result = 2; break;
7003     case 30*60: result = 1; break;
7004     case 60*60: result = 3; break;
7005     case 3600*2: result = 3; break;
7006     case 3600*3: result = 2; break;
7007     case 3600*6: result = 1; break;
7008     case 3600*12: result = 3; break;
7009     case 3600*24: result = 3; break;
7010   }
7011   return result;
7012 }
7013 
7014 /*! \internal
7015   
7016   Returns the tick label corresponding to the provided \a tick and the configured format and field
7017   widths (\ref setTimeFormat, \ref setFieldWidth).
7018   
7019   \seebaseclassmethod
7020 */
7021 QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
7022 {
7023   Q_UNUSED(precision)
7024   Q_UNUSED(formatChar)
7025   Q_UNUSED(locale)
7026   bool negative = tick < 0;
7027   if (negative) tick *= -1;
7028   double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
7029   double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
7030   
7031   restValues[tuMilliseconds] = tick*1000;
7032   values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
7033   values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
7034   values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
7035   values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
7036   // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
7037   
7038   // 2017-07-03: JM force wrap of hours value
7039   if (restValues[tuHours] > 24)
7040       restValues[tuHours] -= 24;
7041 
7042   QString result = mTimeFormat;
7043   for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
7044   {
7045     TimeUnit iUnit = static_cast<TimeUnit>(i);
7046     replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
7047   }
7048   if (negative)
7049     result.prepend(QLatin1Char('-'));
7050   return result;
7051 }
7052 
7053 /*! \internal
7054   
7055   Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
7056   \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
7057 */
7058 void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
7059 {
7060   QString valueStr = QString::number(value);
7061   while (valueStr.size() < mFieldWidth.value(unit))
7062     valueStr.prepend(QLatin1Char('0'));
7063   
7064   text.replace(mFormatPattern.value(unit), valueStr);
7065 }
7066 /* end of 'src/axis/axistickertime.cpp' */
7067 
7068 
7069 /* including file 'src/axis/axistickerfixed.cpp' */
7070 /* modified 2021-03-29T02:30:44, size 5575       */
7071 
7072 ////////////////////////////////////////////////////////////////////////////////////////////////////
7073 //////////////////// QCPAxisTickerFixed
7074 ////////////////////////////////////////////////////////////////////////////////////////////////////
7075 /*! \class QCPAxisTickerFixed
7076   \brief Specialized axis ticker with a fixed tick step
7077   
7078   \image html axisticker-fixed.png
7079   
7080   This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
7081   is also possible to allow integer multiples and integer powers of the specified tick step with
7082   \ref setScaleStrategy.
7083   
7084   A typical application of this ticker is to make an axis only display integers, by setting the
7085   tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
7086   
7087   Another case is when a certain number has a special meaning and axis ticks should only appear at
7088   multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
7089   because despite the name it is not limited to only pi symbols/values.
7090   
7091   The ticker can be created and assigned to an axis like this:
7092   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
7093 */
7094 
7095 /*!
7096   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
7097   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
7098 */
7099 QCPAxisTickerFixed::QCPAxisTickerFixed() :
7100   mTickStep(1.0),
7101   mScaleStrategy(ssNone)
7102 {
7103 }
7104 
7105 /*!
7106   Sets the fixed tick interval to \a step.
7107   
7108   The axis ticker will only use this tick step when generating axis ticks. This might cause a very
7109   high tick density and overlapping labels if the axis range is zoomed out. Using \ref
7110   setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
7111   step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
7112   setTickCount).
7113 */
7114 void QCPAxisTickerFixed::setTickStep(double step)
7115 {
7116   if (step > 0)
7117     mTickStep = step;
7118   else
7119     qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
7120 }
7121 
7122 /*!
7123   Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
7124   modifications may be applied to it before calculating the finally used tick step, such as
7125   permitting multiples or powers. See \ref ScaleStrategy for details.
7126   
7127   The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
7128 */
7129 void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
7130 {
7131   mScaleStrategy = strategy;
7132 }
7133 
7134 /*! \internal
7135   
7136   Determines the actually used tick step from the specified tick step and scale strategy (\ref
7137   setTickStep, \ref setScaleStrategy).
7138   
7139   This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
7140   ssNone, a modification of it to allow varying the number of ticks in the current axis range.
7141   
7142   \seebaseclassmethod
7143 */
7144 double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
7145 {
7146   switch (mScaleStrategy)
7147   {
7148     case ssNone:
7149     {
7150       return mTickStep;
7151     }
7152     case ssMultiples:
7153     {
7154       double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
7155       if (exactStep < mTickStep)
7156         return mTickStep;
7157       else
7158         return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
7159     }
7160     case ssPowers:
7161     {
7162       double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
7163       return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
7164     }
7165   }
7166   return mTickStep;
7167 }
7168 /* end of 'src/axis/axistickerfixed.cpp' */
7169 
7170 
7171 /* including file 'src/axis/axistickertext.cpp' */
7172 /* modified 2021-03-29T02:30:44, size 8742      */
7173 
7174 ////////////////////////////////////////////////////////////////////////////////////////////////////
7175 //////////////////// QCPAxisTickerText
7176 ////////////////////////////////////////////////////////////////////////////////////////////////////
7177 /*! \class QCPAxisTickerText
7178   \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
7179   
7180   \image html axisticker-text.png
7181   
7182   This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
7183   coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
7184   time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
7185   and modify the tick/label data there.
7186   
7187   This is useful for cases where the axis represents categories rather than numerical values.
7188   
7189   If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
7190   the axis range), it is a sign that you should probably create an own ticker by subclassing
7191   QCPAxisTicker, instead of using this one.
7192   
7193   The ticker can be created and assigned to an axis like this:
7194   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
7195 */
7196 
7197 /* start of documentation of inline functions */
7198 
7199 /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
7200   
7201   Returns a non-const reference to the internal map which stores the tick coordinates and their
7202   labels.
7203 
7204   You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
7205   using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
7206 */
7207 
7208 /* end of documentation of inline functions */
7209 
7210 /*!
7211   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
7212   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
7213 */
7214 QCPAxisTickerText::QCPAxisTickerText() :
7215   mSubTickCount(0)
7216 {
7217 }
7218 
7219 /*! \overload
7220   
7221   Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
7222   coordinate, and the map value is the string that will appear as tick label.
7223   
7224   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
7225   getter.
7226   
7227   \see addTicks, addTick, clear
7228 */
7229 void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
7230 {
7231   mTicks = ticks;
7232 }
7233 
7234 /*! \overload
7235   
7236   Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
7237   coordinates, and the entries of \a labels are the respective strings that will appear as tick
7238   labels.
7239   
7240   \see addTicks, addTick, clear
7241 */
7242 void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
7243 {
7244   clear();
7245   addTicks(positions, labels);
7246 }
7247 
7248 /*!
7249   Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
7250   automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
7251   method.
7252 */
7253 void QCPAxisTickerText::setSubTickCount(int subTicks)
7254 {
7255   if (subTicks >= 0)
7256     mSubTickCount = subTicks;
7257   else
7258     qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
7259 }
7260 
7261 /*!
7262   Clears all ticks.
7263   
7264   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
7265   getter.
7266   
7267   \see setTicks, addTicks, addTick
7268 */
7269 void QCPAxisTickerText::clear()
7270 {
7271   mTicks.clear();
7272 }
7273 
7274 /*!
7275   Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
7276   label.
7277   
7278   \see addTicks, setTicks, clear
7279 */
7280 void QCPAxisTickerText::addTick(double position, const QString &label)
7281 {
7282   mTicks.insert(position, label);
7283 }
7284 
7285 /*! \overload
7286   
7287   Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
7288   the axis coordinate, and the map value is the string that will appear as tick label.
7289   
7290   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
7291   getter.
7292   
7293   \see addTick, setTicks, clear
7294 */
7295 void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
7296 {
7297 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
7298   mTicks.unite(ticks);
7299 #else
7300   mTicks.insert(ticks);
7301 #endif
7302 }
7303 
7304 /*! \overload
7305   
7306   Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
7307   the axis coordinates, and the entries of \a labels are the respective strings that will appear as
7308   tick labels.
7309   
7310   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
7311   getter.
7312   
7313   \see addTick, setTicks, clear
7314 */
7315 void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
7316 {
7317   if (positions.size() != labels.size())
7318     qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
7319   int n = qMin(positions.size(), labels.size());
7320   for (int i=0; i<n; ++i)
7321     mTicks.insert(positions.at(i), labels.at(i));
7322 }
7323 
7324 /*!
7325   Since the tick coordinates are provided externally, this method implementation does nothing.
7326   
7327   \seebaseclassmethod
7328 */
7329 double QCPAxisTickerText::getTickStep(const QCPRange &range)
7330 {
7331   // text axis ticker has manual tick positions, so doesn't need this method
7332   Q_UNUSED(range)
7333   return 1.0;
7334 }
7335 
7336 /*!
7337   Returns the sub tick count that was configured with \ref setSubTickCount.
7338   
7339   \seebaseclassmethod
7340 */
7341 int QCPAxisTickerText::getSubTickCount(double tickStep)
7342 {
7343   Q_UNUSED(tickStep)
7344   return mSubTickCount;
7345 }
7346 
7347 /*!
7348   Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
7349   the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
7350   
7351   \seebaseclassmethod
7352 */
7353 QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
7354 {
7355   Q_UNUSED(locale)
7356   Q_UNUSED(formatChar)
7357   Q_UNUSED(precision)
7358   return mTicks.value(tick);
7359 }
7360 
7361 /*!
7362   Returns the externally provided tick coordinates which are in the specified \a range. If
7363   available, one tick above and below the range is provided in addition, to allow possible sub tick
7364   calculation. The parameter \a tickStep is ignored.
7365   
7366   \seebaseclassmethod
7367 */
7368 QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
7369 {
7370   Q_UNUSED(tickStep)
7371   QVector<double> result;
7372   if (mTicks.isEmpty())
7373     return result;
7374   
7375   const QMap<double, QString> constTicks(mTicks);
7376   QMap<double, QString>::const_iterator start = constTicks.lowerBound(range.lower);
7377   QMap<double, QString>::const_iterator end = constTicks.upperBound(range.upper);
7378   // this method should try to give one tick outside of range so proper subticks can be generated:
7379   if (start != mTicks.constBegin()) --start;
7380   if (end != mTicks.constEnd()) ++end;
7381   for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
7382     result.append(it.key());
7383   
7384   return result;
7385 }
7386 /* end of 'src/axis/axistickertext.cpp' */
7387 
7388 
7389 /* including file 'src/axis/axistickerpi.cpp' */
7390 /* modified 2021-03-29T02:30:44, size 11177   */
7391 
7392 ////////////////////////////////////////////////////////////////////////////////////////////////////
7393 //////////////////// QCPAxisTickerPi
7394 ////////////////////////////////////////////////////////////////////////////////////////////////////
7395 /*! \class QCPAxisTickerPi
7396   \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
7397   
7398   \image html axisticker-pi.png
7399   
7400   This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
7401   constant with a numerical value specified with \ref setPiValue and an appearance in the tick
7402   labels specified with \ref setPiSymbol.
7403   
7404   Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
7405   tick label can be configured with \ref setFractionStyle.
7406   
7407   The ticker can be created and assigned to an axis like this:
7408   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
7409 */
7410 
7411 /*!
7412   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
7413   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
7414 */
7415 QCPAxisTickerPi::QCPAxisTickerPi() :
7416   mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
7417   mPiValue(M_PI),
7418   mPeriodicity(0),
7419   mFractionStyle(fsUnicodeFractions),
7420   mPiTickStep(0)
7421 {
7422   setTickCount(4);
7423 }
7424 
7425 /*!
7426   Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
7427   label.
7428   
7429   If a space shall appear between the number and the symbol, make sure the space is contained in \a
7430   symbol.
7431 */
7432 void QCPAxisTickerPi::setPiSymbol(QString symbol)
7433 {
7434   mPiSymbol = symbol;
7435 }
7436 
7437 /*!
7438   Sets the numerical value that the symbolic constant has.
7439 
7440   This will be used to place the appropriate fractions of the symbol at the respective axis
7441   coordinates.
7442 */
7443 void QCPAxisTickerPi::setPiValue(double pi)
7444 {
7445   mPiValue = pi;
7446 }
7447 
7448 /*!
7449   Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
7450   symbolic constant.
7451   
7452   To disable periodicity, set \a multiplesOfPi to zero.
7453   
7454   For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
7455 */
7456 void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
7457 {
7458   mPeriodicity = qAbs(multiplesOfPi);
7459 }
7460 
7461 /*!
7462   Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
7463   labels. See \ref FractionStyle for the various options.
7464 */
7465 void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
7466 {
7467   mFractionStyle = style;
7468 }
7469 
7470 /*! \internal
7471   
7472   Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
7473   the numerical/fractional part preceding the symbolic constant is made to have a readable
7474   mantissa.
7475   
7476   \seebaseclassmethod
7477 */
7478 double QCPAxisTickerPi::getTickStep(const QCPRange &range)
7479 {
7480   mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
7481   mPiTickStep = cleanMantissa(mPiTickStep);
7482   return mPiTickStep*mPiValue;
7483 }
7484 
7485 /*! \internal
7486   
7487   Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
7488   consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
7489   reasonably, and not the total tick coordinate.
7490   
7491   \seebaseclassmethod
7492 */
7493 int QCPAxisTickerPi::getSubTickCount(double tickStep)
7494 {
7495   return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
7496 }
7497 
7498 /*! \internal
7499   
7500   Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
7501   formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
7502   symbol is specified with \ref setPiSymbol.
7503   
7504   \seebaseclassmethod
7505 */
7506 QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
7507 {
7508   double tickInPis = tick/mPiValue;
7509   if (mPeriodicity > 0)
7510     tickInPis = fmod(tickInPis, mPeriodicity);
7511   
7512   if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
7513   {
7514     // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
7515     int denominator = 1000;
7516     int numerator = qRound(tickInPis*denominator);
7517     simplifyFraction(numerator, denominator);
7518     if (qAbs(numerator) == 1 && denominator == 1)
7519       return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
7520     else if (numerator == 0)
7521       return QLatin1String("0");
7522     else
7523       return fractionToString(numerator, denominator) + mPiSymbol;
7524   } else
7525   {
7526     if (qFuzzyIsNull(tickInPis))
7527       return QLatin1String("0");
7528     else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
7529       return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
7530     else
7531       return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
7532   }
7533 }
7534 
7535 /*! \internal
7536   
7537   Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
7538   the fraction is in irreducible form, i.e. numerator and denominator don't share any common
7539   factors which could be cancelled.
7540 */
7541 void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
7542 {
7543   if (numerator == 0 || denominator == 0)
7544     return;
7545   
7546   int num = numerator;
7547   int denom = denominator;
7548   while (denom != 0) // euclidean gcd algorithm
7549   {
7550     int oldDenom = denom;
7551     denom = num % denom;
7552     num = oldDenom;
7553   }
7554   // num is now gcd of numerator and denominator
7555   numerator /= num;
7556   denominator /= num;
7557 }
7558 
7559 /*! \internal
7560   
7561   Takes the fraction given by \a numerator and \a denominator and returns a string representation.
7562   The result depends on the configured fraction style (\ref setFractionStyle).
7563   
7564   This method is used to format the numerical/fractional part when generating tick labels. It
7565   simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
7566   any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
7567 */
7568 QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
7569 {
7570   if (denominator == 0)
7571   {
7572     qDebug() << Q_FUNC_INFO << "called with zero denominator";
7573     return QString();
7574   }
7575   if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
7576   {
7577     qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
7578     return QString::number(numerator/double(denominator)); // failsafe
7579   }
7580   int sign = numerator*denominator < 0 ? -1 : 1;
7581   numerator = qAbs(numerator);
7582   denominator = qAbs(denominator);
7583   
7584   if (denominator == 1)
7585   {
7586     return QString::number(sign*numerator);
7587   } else
7588   {
7589     int integerPart = numerator/denominator;
7590     int remainder = numerator%denominator;
7591     if (remainder == 0)
7592     {
7593       return QString::number(sign*integerPart);
7594     } else
7595     {
7596       if (mFractionStyle == fsAsciiFractions)
7597       {
7598         return QString(QLatin1String("%1%2%3/%4"))
7599             .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
7600             .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
7601             .arg(remainder)
7602             .arg(denominator);
7603       } else if (mFractionStyle == fsUnicodeFractions)
7604       {
7605         return QString(QLatin1String("%1%2%3"))
7606             .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
7607             .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
7608             .arg(unicodeFraction(remainder, denominator));
7609       }
7610     }
7611   }
7612   return QString();
7613 }
7614 
7615 /*! \internal
7616   
7617   Returns the unicode string representation of the fraction given by \a numerator and \a
7618   denominator. This is the representation used in \ref fractionToString when the fraction style
7619   (\ref setFractionStyle) is \ref fsUnicodeFractions.
7620   
7621   This method doesn't use the single-character common fractions but builds each fraction from a
7622   superscript unicode number, the unicode fraction character, and a subscript unicode number.
7623 */
7624 QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
7625 {
7626   return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
7627 }
7628 
7629 /*! \internal
7630   
7631   Returns the unicode string representing \a number as superscript. This is used to build
7632   unicode fractions in \ref unicodeFraction.
7633 */
7634 QString QCPAxisTickerPi::unicodeSuperscript(int number) const
7635 {
7636   if (number == 0)
7637     return QString(QChar(0x2070));
7638   
7639   QString result;
7640   while (number > 0)
7641   {
7642     const int digit = number%10;
7643     switch (digit)
7644     {
7645       case 1: { result.prepend(QChar(0x00B9)); break; }
7646       case 2: { result.prepend(QChar(0x00B2)); break; }
7647       case 3: { result.prepend(QChar(0x00B3)); break; }
7648       default: { result.prepend(QChar(0x2070+digit)); break; }
7649     }
7650     number /= 10;
7651   }
7652   return result;
7653 }
7654 
7655 /*! \internal
7656   
7657   Returns the unicode string representing \a number as subscript. This is used to build unicode
7658   fractions in \ref unicodeFraction.
7659 */
7660 QString QCPAxisTickerPi::unicodeSubscript(int number) const
7661 {
7662   if (number == 0)
7663     return QString(QChar(0x2080));
7664   
7665   QString result;
7666   while (number > 0)
7667   {
7668     result.prepend(QChar(0x2080+number%10));
7669     number /= 10;
7670   }
7671   return result;
7672 }
7673 /* end of 'src/axis/axistickerpi.cpp' */
7674 
7675 
7676 /* including file 'src/axis/axistickerlog.cpp' */
7677 /* modified 2021-03-29T02:30:44, size 7890     */
7678 
7679 ////////////////////////////////////////////////////////////////////////////////////////////////////
7680 //////////////////// QCPAxisTickerLog
7681 ////////////////////////////////////////////////////////////////////////////////////////////////////
7682 /*! \class QCPAxisTickerLog
7683   \brief Specialized axis ticker suited for logarithmic axes
7684   
7685   \image html axisticker-log.png
7686   
7687   This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
7688   axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
7689   
7690   Especially in the case of a log base equal to 10 (the default), it might be desirable to have
7691   tick labels in the form of powers of ten without mantissa display. To achieve this, set the
7692   number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
7693   QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
7694   powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
7695   
7696   \image html axisticker-log-powers.png
7697 
7698   The ticker can be created and assigned to an axis like this:
7699   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
7700   
7701   Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
7702   corresponding to one multiplication by the log base. If the user zooms in further than that, no
7703   new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
7704   situation, this ticker falls back to regular tick generation if the axis range would be covered
7705   by too few logarithmically placed ticks.
7706 */
7707 
7708 /*!
7709   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
7710   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
7711 */
7712 QCPAxisTickerLog::QCPAxisTickerLog() :
7713   mLogBase(10.0),
7714   mSubTickCount(8), // generates 10 intervals
7715   mLogBaseLnInv(1.0/qLn(mLogBase))
7716 {
7717 }
7718 
7719 /*!
7720   Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
7721   powers of \a base.
7722 */
7723 void QCPAxisTickerLog::setLogBase(double base)
7724 {
7725   if (base > 0)
7726   {
7727     mLogBase = base;
7728     mLogBaseLnInv = 1.0/qLn(mLogBase);
7729   } else
7730     qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
7731 }
7732 
7733 /*!
7734   Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
7735   linearly to provide a better visual guide, so the sub tick density increases toward the higher
7736   tick.
7737   
7738   Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
7739   the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
7740   ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
7741   namely at 20, 30, 40, 50, 60, 70, 80 and 90.
7742 */
7743 void QCPAxisTickerLog::setSubTickCount(int subTicks)
7744 {
7745   if (subTicks >= 0)
7746     mSubTickCount = subTicks;
7747   else
7748     qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
7749 }
7750 
7751 /*! \internal
7752   
7753   Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
7754   automatic sub tick count calculation necessary.
7755   
7756   \seebaseclassmethod
7757 */
7758 int QCPAxisTickerLog::getSubTickCount(double tickStep)
7759 {
7760   Q_UNUSED(tickStep)
7761   return mSubTickCount;
7762 }
7763 
7764 /*! \internal
7765   
7766   Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
7767   provided \a range. The step in which the power increases tick by tick is chosen in order to keep
7768   the total number of ticks as close as possible to the tick count (\ref setTickCount).
7769 
7770   The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
7771   zoomed in very far such that not enough logarithmically placed ticks would be visible, this
7772   function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
7773   
7774   \seebaseclassmethod
7775 */
7776 QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
7777 {
7778   QVector<double> result;
7779   if (range.lower > 0 && range.upper > 0) // positive range
7780   {
7781     const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
7782     if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
7783       return QCPAxisTicker::createTickVector(tickStep, range);
7784     const double exactPowerStep =  baseTickCount/double(mTickCount+1e-10);
7785     const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
7786     double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
7787     result.append(currentTick);
7788     while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
7789     {
7790       currentTick *= newLogBase;
7791       result.append(currentTick);
7792     }
7793   } else if (range.lower < 0 && range.upper < 0) // negative range
7794   {
7795     const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
7796     if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
7797       return QCPAxisTicker::createTickVector(tickStep, range);
7798     const double exactPowerStep =  baseTickCount/double(mTickCount+1e-10);
7799     const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
7800     double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
7801     result.append(currentTick);
7802     while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
7803     {
7804       currentTick /= newLogBase;
7805       result.append(currentTick);
7806     }
7807   } else // invalid range for logarithmic scale, because lower and upper have different sign
7808   {
7809     qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
7810   }
7811   
7812   return result;
7813 }
7814 /* end of 'src/axis/axistickerlog.cpp' */
7815 
7816 
7817 /* including file 'src/axis/axis.cpp'       */
7818 /* modified 2021-03-29T02:30:44, size 99883 */
7819 
7820 
7821 ////////////////////////////////////////////////////////////////////////////////////////////////////
7822 //////////////////// QCPGrid
7823 ////////////////////////////////////////////////////////////////////////////////////////////////////
7824 
7825 /*! \class QCPGrid
7826   \brief Responsible for drawing the grid of a QCPAxis.
7827   
7828   This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
7829   grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
7830   QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
7831   
7832   The axis and grid drawing was split into two classes to allow them to be placed on different
7833   layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
7834   in the background and the axes in the foreground, and any plottables/items in between. This
7835   described situation is the default setup, see the QCPLayer documentation.
7836 */
7837 
7838 /*!
7839   Creates a QCPGrid instance and sets default values.
7840   
7841   You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
7842 */
7843 QCPGrid::QCPGrid(QCPAxis *parentAxis) :
7844   QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
7845   mSubGridVisible{},
7846   mAntialiasedSubGrid{},
7847   mAntialiasedZeroLine{},
7848   mParentAxis(parentAxis)
7849 {
7850   // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
7851   setParent(parentAxis);
7852   setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
7853   setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
7854   setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
7855   setSubGridVisible(false);
7856   setAntialiased(false);
7857   setAntialiasedSubGrid(false);
7858   setAntialiasedZeroLine(false);
7859 }
7860 
7861 /*!
7862   Sets whether grid lines at sub tick marks are drawn.
7863   
7864   \see setSubGridPen
7865 */
7866 void QCPGrid::setSubGridVisible(bool visible)
7867 {
7868   mSubGridVisible = visible;
7869 }
7870 
7871 /*!
7872   Sets whether sub grid lines are drawn antialiased.
7873 */
7874 void QCPGrid::setAntialiasedSubGrid(bool enabled)
7875 {
7876   mAntialiasedSubGrid = enabled;
7877 }
7878 
7879 /*!
7880   Sets whether zero lines are drawn antialiased.
7881 */
7882 void QCPGrid::setAntialiasedZeroLine(bool enabled)
7883 {
7884   mAntialiasedZeroLine = enabled;
7885 }
7886 
7887 /*!
7888   Sets the pen with which (major) grid lines are drawn.
7889 */
7890 void QCPGrid::setPen(const QPen &pen)
7891 {
7892   mPen = pen;
7893 }
7894 
7895 /*!
7896   Sets the pen with which sub grid lines are drawn.
7897 */
7898 void QCPGrid::setSubGridPen(const QPen &pen)
7899 {
7900   mSubGridPen = pen;
7901 }
7902 
7903 /*!
7904   Sets the pen with which zero lines are drawn.
7905   
7906   Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
7907   lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
7908 */
7909 void QCPGrid::setZeroLinePen(const QPen &pen)
7910 {
7911   mZeroLinePen = pen;
7912 }
7913 
7914 /*! \internal
7915 
7916   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
7917   before drawing the major grid lines.
7918 
7919   This is the antialiasing state the painter passed to the \ref draw method is in by default.
7920   
7921   This function takes into account the local setting of the antialiasing flag as well as the
7922   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
7923   QCustomPlot::setNotAntialiasedElements.
7924   
7925   \see setAntialiased
7926 */
7927 void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
7928 {
7929   applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
7930 }
7931 
7932 /*! \internal
7933   
7934   Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
7935   over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
7936 */
7937 void QCPGrid::draw(QCPPainter *painter)
7938 {
7939   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
7940   
7941   if (mParentAxis->subTicks() && mSubGridVisible)
7942     drawSubGridLines(painter);
7943   drawGridLines(painter);
7944 }
7945 
7946 /*! \internal
7947   
7948   Draws the main grid lines and possibly a zero line with the specified painter.
7949   
7950   This is a helper function called by \ref draw.
7951 */
7952 void QCPGrid::drawGridLines(QCPPainter *painter) const
7953 {
7954   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
7955   
7956   const int tickCount = mParentAxis->mTickVector.size();
7957   double t; // helper variable, result of coordinate-to-pixel transforms
7958   if (mParentAxis->orientation() == Qt::Horizontal)
7959   {
7960     // draw zeroline:
7961     int zeroLineIndex = -1;
7962     if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
7963     {
7964       applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
7965       painter->setPen(mZeroLinePen);
7966       double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
7967       for (int i=0; i<tickCount; ++i)
7968       {
7969         if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
7970         {
7971           zeroLineIndex = i;
7972           t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
7973           painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
7974           break;
7975         }
7976       }
7977     }
7978     // draw grid lines:
7979     applyDefaultAntialiasingHint(painter);
7980     painter->setPen(mPen);
7981     for (int i=0; i<tickCount; ++i)
7982     {
7983       if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
7984       t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
7985       painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
7986     }
7987   } else
7988   {
7989     // draw zeroline:
7990     int zeroLineIndex = -1;
7991     if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
7992     {
7993       applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
7994       painter->setPen(mZeroLinePen);
7995       double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
7996       for (int i=0; i<tickCount; ++i)
7997       {
7998         if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
7999         {
8000           zeroLineIndex = i;
8001           t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
8002           painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
8003           break;
8004         }
8005       }
8006     }
8007     // draw grid lines:
8008     applyDefaultAntialiasingHint(painter);
8009     painter->setPen(mPen);
8010     for (int i=0; i<tickCount; ++i)
8011     {
8012       if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
8013       t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
8014       painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
8015     }
8016   }
8017 }
8018 
8019 /*! \internal
8020   
8021   Draws the sub grid lines with the specified painter.
8022   
8023   This is a helper function called by \ref draw.
8024 */
8025 void QCPGrid::drawSubGridLines(QCPPainter *painter) const
8026 {
8027   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
8028   
8029   applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
8030   double t; // helper variable, result of coordinate-to-pixel transforms
8031   painter->setPen(mSubGridPen);
8032   if (mParentAxis->orientation() == Qt::Horizontal)
8033   {
8034     foreach (double tickCoord, mParentAxis->mSubTickVector)
8035     {
8036       t = mParentAxis->coordToPixel(tickCoord); // x
8037       painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
8038     }
8039   } else
8040   {
8041     foreach (double tickCoord, mParentAxis->mSubTickVector)
8042     {
8043       t = mParentAxis->coordToPixel(tickCoord); // y
8044       painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
8045     }
8046   }
8047 }
8048 
8049 
8050 ////////////////////////////////////////////////////////////////////////////////////////////////////
8051 //////////////////// QCPAxis
8052 ////////////////////////////////////////////////////////////////////////////////////////////////////
8053 
8054 /*! \class QCPAxis
8055   \brief Manages a single axis inside a QCustomPlot.
8056 
8057   Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
8058   QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
8059   QCustomPlot::yAxis2 (right).
8060   
8061   Axes are always part of an axis rect, see QCPAxisRect.
8062   \image html AxisNamesOverview.png
8063   <center>Naming convention of axis parts</center>
8064   \n
8065     
8066   \image html AxisRectSpacingOverview.png
8067   <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
8068   on the left represents the QCustomPlot widget border.</center>
8069   
8070   Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
8071   tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
8072   the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
8073   documentation of QCPAxisTicker.
8074 */
8075 
8076 /* start of documentation of inline functions */
8077 
8078 /*! \fn Qt::Orientation QCPAxis::orientation() const
8079 
8080   Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
8081   from the axis type (left, top, right or bottom).
8082 
8083   \see orientation(AxisType type), pixelOrientation
8084 */
8085 
8086 /*! \fn QCPGrid *QCPAxis::grid() const
8087   
8088   Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
8089   grid is displayed.
8090 */
8091 
8092 /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
8093 
8094   Returns the orientation of the specified axis type
8095 
8096   \see orientation(), pixelOrientation
8097 */
8098 
8099 /*! \fn int QCPAxis::pixelOrientation() const
8100 
8101   Returns which direction points towards higher coordinate values/keys, in pixel space.
8102 
8103   This method returns either 1 or -1. If it returns 1, then going in the positive direction along
8104   the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
8105   On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
8106   from lower to higher axis coordinates.
8107 
8108   For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
8109   without having to care about reversed or vertically aligned axes:
8110 
8111   \code
8112   double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
8113   \endcode
8114 
8115   \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
8116 */
8117 
8118 /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
8119 
8120   Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
8121   responsible for generating the tick positions and tick labels of this axis. You can access the
8122   \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
8123   (\ref QCPAxisTicker::setTickCount).
8124 
8125   You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
8126   the documentation there. A new axis ticker can be set with \ref setTicker.
8127 
8128   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
8129   ticker simply by passing the same shared pointer to multiple axes.
8130 
8131   \see setTicker
8132 */
8133 
8134 /* end of documentation of inline functions */
8135 /* start of documentation of signals */
8136 
8137 /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
8138 
8139   This signal is emitted when the range of this axis has changed. You can connect it to the \ref
8140   setRange slot of another axis to communicate the new range to the other axis, in order for it to
8141   be synchronized.
8142   
8143   You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
8144   This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
8145   range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
8146   slot would limit the x axis to ranges between 0 and 10:
8147   \code
8148   customPlot->xAxis->setRange(newRange.bounded(0, 10))
8149   \endcode
8150 */
8151 
8152 /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
8153   \overload
8154   
8155   Additionally to the new range, this signal also provides the previous range held by the axis as
8156   \a oldRange.
8157 */
8158 
8159 /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
8160   
8161   This signal is emitted when the scale type changes, by calls to \ref setScaleType
8162 */
8163 
8164 /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
8165   
8166   This signal is emitted when the selection state of this axis has changed, either by user interaction
8167   or by a direct call to \ref setSelectedParts.
8168 */
8169 
8170 /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
8171   
8172   This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
8173 */
8174 
8175 /* end of documentation of signals */
8176 
8177 /*!
8178   Constructs an Axis instance of Type \a type for the axis rect \a parent.
8179   
8180   Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
8181   them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
8182   create them manually and then inject them also via \ref QCPAxisRect::addAxis.
8183 */
8184 QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
8185   QCPLayerable(parent->parentPlot(), QString(), parent),
8186   // axis base:
8187   mAxisType(type),
8188   mAxisRect(parent),
8189   mPadding(5),
8190   mOrientation(orientation(type)),
8191   mSelectableParts(spAxis | spTickLabels | spAxisLabel),
8192   mSelectedParts(spNone),
8193   mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8194   mSelectedBasePen(QPen(Qt::blue, 2)),
8195   // axis label:
8196   mLabel(),
8197   mLabelFont(mParentPlot->font()),
8198   mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
8199   mLabelColor(Qt::black),
8200   mSelectedLabelColor(Qt::blue),
8201   // tick labels:
8202   mTickLabels(true),
8203   mTickLabelFont(mParentPlot->font()),
8204   mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
8205   mTickLabelColor(Qt::black),
8206   mSelectedTickLabelColor(Qt::blue),
8207   mNumberPrecision(6),
8208   mNumberFormatChar('g'),
8209   mNumberBeautifulPowers(true),
8210   // ticks and subticks:
8211   mTicks(true),
8212   mSubTicks(true),
8213   mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8214   mSelectedTickPen(QPen(Qt::blue, 2)),
8215   mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8216   mSelectedSubTickPen(QPen(Qt::blue, 2)),
8217   // scale and range:
8218   mRange(0, 5),
8219   mRangeReversed(false),
8220   mScaleType(stLinear),
8221   // internal members:
8222   mGrid(new QCPGrid(this)),
8223   mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
8224   mTicker(new QCPAxisTicker),
8225   mCachedMarginValid(false),
8226   mCachedMargin(0),
8227   mDragging(false)
8228 {
8229   setParent(parent);
8230   mGrid->setVisible(false);
8231   setAntialiased(false);
8232   setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
8233   
8234   if (type == atTop)
8235   {
8236     setTickLabelPadding(3);
8237     setLabelPadding(6);
8238   } else if (type == atRight)
8239   {
8240     setTickLabelPadding(7);
8241     setLabelPadding(12);
8242   } else if (type == atBottom)
8243   {
8244     setTickLabelPadding(3);
8245     setLabelPadding(3);
8246   } else if (type == atLeft)
8247   {
8248     setTickLabelPadding(5);
8249     setLabelPadding(10);
8250   }
8251 }
8252 
8253 QCPAxis::~QCPAxis()
8254 {
8255   delete mAxisPainter;
8256   delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
8257 }
8258 
8259 /* No documentation as it is a property getter */
8260 int QCPAxis::tickLabelPadding() const
8261 {
8262   return mAxisPainter->tickLabelPadding;
8263 }
8264 
8265 /* No documentation as it is a property getter */
8266 double QCPAxis::tickLabelRotation() const
8267 {
8268   return mAxisPainter->tickLabelRotation;
8269 }
8270 
8271 /* No documentation as it is a property getter */
8272 QCPAxis::LabelSide QCPAxis::tickLabelSide() const
8273 {
8274   return mAxisPainter->tickLabelSide;
8275 }
8276 
8277 /* No documentation as it is a property getter */
8278 QString QCPAxis::numberFormat() const
8279 {
8280   QString result;
8281   result.append(mNumberFormatChar);
8282   if (mNumberBeautifulPowers)
8283   {
8284     result.append(QLatin1Char('b'));
8285     if (mAxisPainter->numberMultiplyCross)
8286       result.append(QLatin1Char('c'));
8287   }
8288   return result;
8289 }
8290 
8291 /* No documentation as it is a property getter */
8292 int QCPAxis::tickLengthIn() const
8293 {
8294   return mAxisPainter->tickLengthIn;
8295 }
8296 
8297 /* No documentation as it is a property getter */
8298 int QCPAxis::tickLengthOut() const
8299 {
8300   return mAxisPainter->tickLengthOut;
8301 }
8302 
8303 /* No documentation as it is a property getter */
8304 int QCPAxis::subTickLengthIn() const
8305 {
8306   return mAxisPainter->subTickLengthIn;
8307 }
8308 
8309 /* No documentation as it is a property getter */
8310 int QCPAxis::subTickLengthOut() const
8311 {
8312   return mAxisPainter->subTickLengthOut;
8313 }
8314 
8315 /* No documentation as it is a property getter */
8316 int QCPAxis::labelPadding() const
8317 {
8318   return mAxisPainter->labelPadding;
8319 }
8320 
8321 /* No documentation as it is a property getter */
8322 int QCPAxis::offset() const
8323 {
8324   return mAxisPainter->offset;
8325 }
8326 
8327 /* No documentation as it is a property getter */
8328 QCPLineEnding QCPAxis::lowerEnding() const
8329 {
8330   return mAxisPainter->lowerEnding;
8331 }
8332 
8333 /* No documentation as it is a property getter */
8334 QCPLineEnding QCPAxis::upperEnding() const
8335 {
8336   return mAxisPainter->upperEnding;
8337 }
8338 
8339 /*!
8340   Sets whether the axis uses a linear scale or a logarithmic scale.
8341   
8342   Note that this method controls the coordinate transformation. For logarithmic scales, you will
8343   likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
8344   the axis ticker to an instance of \ref QCPAxisTickerLog :
8345   
8346   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
8347   
8348   See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
8349   creation.
8350   
8351   \ref setNumberPrecision
8352 */
8353 void QCPAxis::setScaleType(QCPAxis::ScaleType type)
8354 {
8355   if (mScaleType != type)
8356   {
8357     mScaleType = type;
8358     if (mScaleType == stLogarithmic)
8359       setRange(mRange.sanitizedForLogScale());
8360     mCachedMarginValid = false;
8361     emit scaleTypeChanged(mScaleType);
8362   }
8363 }
8364 
8365 /*!
8366   Sets the range of the axis.
8367   
8368   This slot may be connected with the \ref rangeChanged signal of another axis so this axis
8369   is always synchronized with the other axis range, when it changes.
8370   
8371   To invert the direction of an axis, use \ref setRangeReversed.
8372 */
8373 void QCPAxis::setRange(const QCPRange &range)
8374 {
8375   if (range.lower == mRange.lower && range.upper == mRange.upper)
8376     return;
8377   
8378   if (!QCPRange::validRange(range)) return;
8379   QCPRange oldRange = mRange;
8380   if (mScaleType == stLogarithmic)
8381   {
8382     mRange = range.sanitizedForLogScale();
8383   } else
8384   {
8385     mRange = range.sanitizedForLinScale();
8386   }
8387   emit rangeChanged(mRange);
8388   emit rangeChanged(mRange, oldRange);
8389 }
8390 
8391 /*!
8392   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
8393   (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
8394   
8395   However, even when \a selectable is set to a value not allowing the selection of a specific part,
8396   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
8397   directly.
8398   
8399   \see SelectablePart, setSelectedParts
8400 */
8401 void QCPAxis::setSelectableParts(const SelectableParts &selectable)
8402 {
8403   if (mSelectableParts != selectable)
8404   {
8405     mSelectableParts = selectable;
8406     emit selectableChanged(mSelectableParts);
8407   }
8408 }
8409 
8410 /*!
8411   Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
8412   is selected, it uses a different pen/font.
8413   
8414   The entire selection mechanism for axes is handled automatically when \ref
8415   QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
8416   wish to change the selection state manually.
8417   
8418   This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
8419   
8420   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
8421   
8422   \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
8423   setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
8424 */
8425 void QCPAxis::setSelectedParts(const SelectableParts &selected)
8426 {
8427   if (mSelectedParts != selected)
8428   {
8429     mSelectedParts = selected;
8430     emit selectionChanged(mSelectedParts);
8431   }
8432 }
8433 
8434 /*!
8435   \overload
8436   
8437   Sets the lower and upper bound of the axis range.
8438   
8439   To invert the direction of an axis, use \ref setRangeReversed.
8440   
8441   There is also a slot to set a range, see \ref setRange(const QCPRange &range).
8442 */
8443 void QCPAxis::setRange(double lower, double upper)
8444 {
8445   if (lower == mRange.lower && upper == mRange.upper)
8446     return;
8447   
8448   if (!QCPRange::validRange(lower, upper)) return;
8449   QCPRange oldRange = mRange;
8450   mRange.lower = lower;
8451   mRange.upper = upper;
8452   if (mScaleType == stLogarithmic)
8453   {
8454     mRange = mRange.sanitizedForLogScale();
8455   } else
8456   {
8457     mRange = mRange.sanitizedForLinScale();
8458   }
8459   emit rangeChanged(mRange);
8460   emit rangeChanged(mRange, oldRange);
8461 }
8462 
8463 /*!
8464   \overload
8465   
8466   Sets the range of the axis.
8467   
8468   The \a position coordinate indicates together with the \a alignment parameter, where the new
8469   range will be positioned. \a size defines the size of the new axis range. \a alignment may be
8470   Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
8471   or center of the range to be aligned with \a position. Any other values of \a alignment will
8472   default to Qt::AlignCenter.
8473 */
8474 void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
8475 {
8476   if (alignment == Qt::AlignLeft)
8477     setRange(position, position+size);
8478   else if (alignment == Qt::AlignRight)
8479     setRange(position-size, position);
8480   else // alignment == Qt::AlignCenter
8481     setRange(position-size/2.0, position+size/2.0);
8482 }
8483 
8484 /*!
8485   Sets the lower bound of the axis range. The upper bound is not changed.
8486   \see setRange
8487 */
8488 void QCPAxis::setRangeLower(double lower)
8489 {
8490   if (mRange.lower == lower)
8491     return;
8492   
8493   QCPRange oldRange = mRange;
8494   mRange.lower = lower;
8495   if (mScaleType == stLogarithmic)
8496   {
8497     mRange = mRange.sanitizedForLogScale();
8498   } else
8499   {
8500     mRange = mRange.sanitizedForLinScale();
8501   }
8502   emit rangeChanged(mRange);
8503   emit rangeChanged(mRange, oldRange);
8504 }
8505 
8506 /*!
8507   Sets the upper bound of the axis range. The lower bound is not changed.
8508   \see setRange
8509 */
8510 void QCPAxis::setRangeUpper(double upper)
8511 {
8512   if (mRange.upper == upper)
8513     return;
8514   
8515   QCPRange oldRange = mRange;
8516   mRange.upper = upper;
8517   if (mScaleType == stLogarithmic)
8518   {
8519     mRange = mRange.sanitizedForLogScale();
8520   } else
8521   {
8522     mRange = mRange.sanitizedForLinScale();
8523   }
8524   emit rangeChanged(mRange);
8525   emit rangeChanged(mRange, oldRange);
8526 }
8527 
8528 /*!
8529   Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
8530   axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
8531   direction of increasing values is inverted.
8532 
8533   Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
8534   of the \ref setRange interface will still reference the mathematically smaller number than the \a
8535   upper part.
8536 */
8537 void QCPAxis::setRangeReversed(bool reversed)
8538 {
8539   mRangeReversed = reversed;
8540 }
8541 
8542 /*!
8543   The axis ticker is responsible for generating the tick positions and tick labels. See the
8544   documentation of QCPAxisTicker for details on how to work with axis tickers.
8545   
8546   You can change the tick positioning/labeling behaviour of this axis by setting a different
8547   QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
8548   ticker, access it via \ref ticker.
8549   
8550   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
8551   ticker simply by passing the same shared pointer to multiple axes.
8552   
8553   \see ticker
8554 */
8555 void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
8556 {
8557   if (ticker)
8558     mTicker = ticker;
8559   else
8560     qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
8561   // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
8562 }
8563 
8564 /*!
8565   Sets whether tick marks are displayed.
8566 
8567   Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
8568   that, see \ref setTickLabels.
8569   
8570   \see setSubTicks
8571 */
8572 void QCPAxis::setTicks(bool show)
8573 {
8574   if (mTicks != show)
8575   {
8576     mTicks = show;
8577     mCachedMarginValid = false;
8578   }
8579 }
8580 
8581 /*!
8582   Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
8583 */
8584 void QCPAxis::setTickLabels(bool show)
8585 {
8586   if (mTickLabels != show)
8587   {
8588     mTickLabels = show;
8589     mCachedMarginValid = false;
8590     if (!mTickLabels)
8591       mTickVectorLabels.clear();
8592   }
8593 }
8594 
8595 /*!
8596   Sets the distance between the axis base line (including any outward ticks) and the tick labels.
8597   \see setLabelPadding, setPadding
8598 */
8599 void QCPAxis::setTickLabelPadding(int padding)
8600 {
8601   if (mAxisPainter->tickLabelPadding != padding)
8602   {
8603     mAxisPainter->tickLabelPadding = padding;
8604     mCachedMarginValid = false;
8605   }
8606 }
8607 
8608 /*!
8609   Sets the font of the tick labels.
8610   
8611   \see setTickLabels, setTickLabelColor
8612 */
8613 void QCPAxis::setTickLabelFont(const QFont &font)
8614 {
8615   if (font != mTickLabelFont)
8616   {
8617     mTickLabelFont = font;
8618     mCachedMarginValid = false;
8619   }
8620 }
8621 
8622 /*!
8623   Sets the color of the tick labels.
8624   
8625   \see setTickLabels, setTickLabelFont
8626 */
8627 void QCPAxis::setTickLabelColor(const QColor &color)
8628 {
8629   mTickLabelColor = color;
8630 }
8631 
8632 /*!
8633   Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
8634   the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
8635   from -90 to 90 degrees.
8636   
8637   If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
8638   other angles, the label is drawn with an offset such that it seems to point toward or away from
8639   the tick mark.
8640 */
8641 void QCPAxis::setTickLabelRotation(double degrees)
8642 {
8643   if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
8644   {
8645     mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
8646     mCachedMarginValid = false;
8647   }
8648 }
8649 
8650 /*!
8651   Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
8652   
8653   The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
8654   to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
8655   appear on the inside are additionally clipped to the axis rect.
8656 */
8657 void QCPAxis::setTickLabelSide(LabelSide side)
8658 {
8659   mAxisPainter->tickLabelSide = side;
8660   mCachedMarginValid = false;
8661 }
8662 
8663 /*!
8664   Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
8665   of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
8666   that, see the "Argument Formats" section in the detailed description of the QString class.
8667   
8668   \a formatCode is a string of one, two or three characters.
8669 
8670   <b>The first character</b> is identical to
8671   the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
8672   format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
8673   the precision set by \ref setNumberPrecision represents the number of digits after the decimal
8674   point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
8675   digits, trailing zeroes are omitted.
8676 
8677   <b>The second and third characters</b> are optional and specific to QCustomPlot:\n
8678   If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
8679   "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
8680   "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
8681   [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
8682   If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
8683   be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
8684   cross and 183 (0xB7) for the dot.
8685   
8686   Examples for \a formatCode:
8687   \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
8688   normal scientific format is used
8689   \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
8690   beautifully typeset decimal powers and a dot as multiplication sign
8691   \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
8692   multiplication sign
8693   \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
8694   powers. Format code will be reduced to 'f'.
8695   \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
8696   code will not be changed.
8697 */
8698 void QCPAxis::setNumberFormat(const QString &formatCode)
8699 {
8700   if (formatCode.isEmpty())
8701   {
8702     qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
8703     return;
8704   }
8705   mCachedMarginValid = false;
8706   
8707   // interpret first char as number format char:
8708   QString allowedFormatChars(QLatin1String("eEfgG"));
8709   if (allowedFormatChars.contains(formatCode.at(0)))
8710   {
8711     mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
8712   } else
8713   {
8714     qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
8715     return;
8716   }
8717   if (formatCode.length() < 2)
8718   {
8719     mNumberBeautifulPowers = false;
8720     mAxisPainter->numberMultiplyCross = false;
8721     return;
8722   }
8723   
8724   // interpret second char as indicator for beautiful decimal powers:
8725   if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
8726   {
8727     mNumberBeautifulPowers = true;
8728   } else
8729   {
8730     qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
8731     return;
8732   }
8733   if (formatCode.length() < 3)
8734   {
8735     mAxisPainter->numberMultiplyCross = false;
8736     return;
8737   }
8738   
8739   // interpret third char as indicator for dot or cross multiplication symbol:
8740   if (formatCode.at(2) == QLatin1Char('c'))
8741   {
8742     mAxisPainter->numberMultiplyCross = true;
8743   } else if (formatCode.at(2) == QLatin1Char('d'))
8744   {
8745     mAxisPainter->numberMultiplyCross = false;
8746   } else
8747   {
8748     qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
8749     return;
8750   }
8751 }
8752 
8753 /*!
8754   Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
8755   for details. The effect of precisions are most notably for number Formats starting with 'e', see
8756   \ref setNumberFormat
8757 */
8758 void QCPAxis::setNumberPrecision(int precision)
8759 {
8760   if (mNumberPrecision != precision)
8761   {
8762     mNumberPrecision = precision;
8763     mCachedMarginValid = false;
8764   }
8765 }
8766 
8767 /*!
8768   Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
8769   plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
8770   zero, the tick labels and axis label will increase their distance to the axis accordingly, so
8771   they won't collide with the ticks.
8772   
8773   \see setSubTickLength, setTickLengthIn, setTickLengthOut
8774 */
8775 void QCPAxis::setTickLength(int inside, int outside)
8776 {
8777   setTickLengthIn(inside);
8778   setTickLengthOut(outside);
8779 }
8780 
8781 /*!
8782   Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
8783   inside the plot.
8784   
8785   \see setTickLengthOut, setTickLength, setSubTickLength
8786 */
8787 void QCPAxis::setTickLengthIn(int inside)
8788 {
8789   if (mAxisPainter->tickLengthIn != inside)
8790   {
8791     mAxisPainter->tickLengthIn = inside;
8792   }
8793 }
8794 
8795 /*!
8796   Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
8797   outside the plot. If \a outside is greater than zero, the tick labels and axis label will
8798   increase their distance to the axis accordingly, so they won't collide with the ticks.
8799   
8800   \see setTickLengthIn, setTickLength, setSubTickLength
8801 */
8802 void QCPAxis::setTickLengthOut(int outside)
8803 {
8804   if (mAxisPainter->tickLengthOut != outside)
8805   {
8806     mAxisPainter->tickLengthOut = outside;
8807     mCachedMarginValid = false; // only outside tick length can change margin
8808   }
8809 }
8810 
8811 /*!
8812   Sets whether sub tick marks are displayed.
8813   
8814   Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
8815   
8816   \see setTicks
8817 */
8818 void QCPAxis::setSubTicks(bool show)
8819 {
8820   if (mSubTicks != show)
8821   {
8822     mSubTicks = show;
8823     mCachedMarginValid = false;
8824   }
8825 }
8826 
8827 /*!
8828   Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
8829   the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
8830   than zero, the tick labels and axis label will increase their distance to the axis accordingly,
8831   so they won't collide with the ticks.
8832   
8833   \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
8834 */
8835 void QCPAxis::setSubTickLength(int inside, int outside)
8836 {
8837   setSubTickLengthIn(inside);
8838   setSubTickLengthOut(outside);
8839 }
8840 
8841 /*!
8842   Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
8843   the plot.
8844   
8845   \see setSubTickLengthOut, setSubTickLength, setTickLength
8846 */
8847 void QCPAxis::setSubTickLengthIn(int inside)
8848 {
8849   if (mAxisPainter->subTickLengthIn != inside)
8850   {
8851     mAxisPainter->subTickLengthIn = inside;
8852   }
8853 }
8854 
8855 /*!
8856   Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
8857   outside the plot. If \a outside is greater than zero, the tick labels will increase their
8858   distance to the axis accordingly, so they won't collide with the ticks.
8859   
8860   \see setSubTickLengthIn, setSubTickLength, setTickLength
8861 */
8862 void QCPAxis::setSubTickLengthOut(int outside)
8863 {
8864   if (mAxisPainter->subTickLengthOut != outside)
8865   {
8866     mAxisPainter->subTickLengthOut = outside;
8867     mCachedMarginValid = false; // only outside tick length can change margin
8868   }
8869 }
8870 
8871 /*!
8872   Sets the pen, the axis base line is drawn with.
8873   
8874   \see setTickPen, setSubTickPen
8875 */
8876 void QCPAxis::setBasePen(const QPen &pen)
8877 {
8878   mBasePen = pen;
8879 }
8880 
8881 /*!
8882   Sets the pen, tick marks will be drawn with.
8883   
8884   \see setTickLength, setBasePen
8885 */
8886 void QCPAxis::setTickPen(const QPen &pen)
8887 {
8888   mTickPen = pen;
8889 }
8890 
8891 /*!
8892   Sets the pen, subtick marks will be drawn with.
8893   
8894   \see setSubTickCount, setSubTickLength, setBasePen
8895 */
8896 void QCPAxis::setSubTickPen(const QPen &pen)
8897 {
8898   mSubTickPen = pen;
8899 }
8900 
8901 /*!
8902   Sets the font of the axis label.
8903   
8904   \see setLabelColor
8905 */
8906 void QCPAxis::setLabelFont(const QFont &font)
8907 {
8908   if (mLabelFont != font)
8909   {
8910     mLabelFont = font;
8911     mCachedMarginValid = false;
8912   }
8913 }
8914 
8915 /*!
8916   Sets the color of the axis label.
8917   
8918   \see setLabelFont
8919 */
8920 void QCPAxis::setLabelColor(const QColor &color)
8921 {
8922   mLabelColor = color;
8923 }
8924 
8925 /*!
8926   Sets the text of the axis label that will be shown below/above or next to the axis, depending on
8927   its orientation. To disable axis labels, pass an empty string as \a str.
8928 */
8929 void QCPAxis::setLabel(const QString &str)
8930 {
8931   if (mLabel != str)
8932   {
8933     mLabel = str;
8934     mCachedMarginValid = false;
8935   }
8936 }
8937 
8938 /*!
8939   Sets the distance between the tick labels and the axis label.
8940   
8941   \see setTickLabelPadding, setPadding
8942 */
8943 void QCPAxis::setLabelPadding(int padding)
8944 {
8945   if (mAxisPainter->labelPadding != padding)
8946   {
8947     mAxisPainter->labelPadding = padding;
8948     mCachedMarginValid = false;
8949   }
8950 }
8951 
8952 /*!
8953   Sets the padding of the axis.
8954 
8955   When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
8956   that is left blank.
8957   
8958   The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
8959   
8960   \see setLabelPadding, setTickLabelPadding
8961 */
8962 void QCPAxis::setPadding(int padding)
8963 {
8964   if (mPadding != padding)
8965   {
8966     mPadding = padding;
8967     mCachedMarginValid = false;
8968   }
8969 }
8970 
8971 /*!
8972   Sets the offset the axis has to its axis rect side.
8973   
8974   If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
8975   only the offset of the inner most axis has meaning (even if it is set to be invisible). The
8976   offset of the other, outer axes is controlled automatically, to place them at appropriate
8977   positions.
8978 */
8979 void QCPAxis::setOffset(int offset)
8980 {
8981   mAxisPainter->offset = offset;
8982 }
8983 
8984 /*!
8985   Sets the font that is used for tick labels when they are selected.
8986   
8987   \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8988 */
8989 void QCPAxis::setSelectedTickLabelFont(const QFont &font)
8990 {
8991   if (font != mSelectedTickLabelFont)
8992   {
8993     mSelectedTickLabelFont = font;
8994     // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
8995   }
8996 }
8997 
8998 /*!
8999   Sets the font that is used for the axis label when it is selected.
9000   
9001   \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9002 */
9003 void QCPAxis::setSelectedLabelFont(const QFont &font)
9004 {
9005   mSelectedLabelFont = font;
9006   // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
9007 }
9008 
9009 /*!
9010   Sets the color that is used for tick labels when they are selected.
9011   
9012   \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9013 */
9014 void QCPAxis::setSelectedTickLabelColor(const QColor &color)
9015 {
9016   if (color != mSelectedTickLabelColor)
9017   {
9018     mSelectedTickLabelColor = color;
9019   }
9020 }
9021 
9022 /*!
9023   Sets the color that is used for the axis label when it is selected.
9024   
9025   \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9026 */
9027 void QCPAxis::setSelectedLabelColor(const QColor &color)
9028 {
9029   mSelectedLabelColor = color;
9030 }
9031 
9032 /*!
9033   Sets the pen that is used to draw the axis base line when selected.
9034   
9035   \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9036 */
9037 void QCPAxis::setSelectedBasePen(const QPen &pen)
9038 {
9039   mSelectedBasePen = pen;
9040 }
9041 
9042 /*!
9043   Sets the pen that is used to draw the (major) ticks when selected.
9044   
9045   \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9046 */
9047 void QCPAxis::setSelectedTickPen(const QPen &pen)
9048 {
9049   mSelectedTickPen = pen;
9050 }
9051 
9052 /*!
9053   Sets the pen that is used to draw the subticks when selected.
9054   
9055   \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
9056 */
9057 void QCPAxis::setSelectedSubTickPen(const QPen &pen)
9058 {
9059   mSelectedSubTickPen = pen;
9060 }
9061 
9062 /*!
9063   Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
9064   styles.
9065   
9066   For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
9067   Note that this meaning does not change when the axis range is reversed with \ref
9068   setRangeReversed.
9069   
9070   \see setUpperEnding
9071 */
9072 void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
9073 {
9074   mAxisPainter->lowerEnding = ending;
9075 }
9076 
9077 /*!
9078   Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
9079   styles.
9080   
9081   For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
9082   Note that this meaning does not change when the axis range is reversed with \ref
9083   setRangeReversed.
9084   
9085   \see setLowerEnding
9086 */
9087 void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
9088 {
9089   mAxisPainter->upperEnding = ending;
9090 }
9091 
9092 /*!
9093   If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
9094   bounds of the range. The range is simply moved by \a diff.
9095   
9096   If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
9097   corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
9098 */
9099 void QCPAxis::moveRange(double diff)
9100 {
9101   QCPRange oldRange = mRange;
9102   if (mScaleType == stLinear)
9103   {
9104     mRange.lower += diff;
9105     mRange.upper += diff;
9106   } else // mScaleType == stLogarithmic
9107   {
9108     mRange.lower *= diff;
9109     mRange.upper *= diff;
9110   }
9111   emit rangeChanged(mRange);
9112   emit rangeChanged(mRange, oldRange);
9113 }
9114 
9115 /*!
9116   Scales the range of this axis by \a factor around the center of the current axis range. For
9117   example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
9118   range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
9119   the center will have moved symmetrically closer).
9120 
9121   If you wish to scale around a different coordinate than the current axis range center, use the
9122   overload \ref scaleRange(double factor, double center).
9123 */
9124 void QCPAxis::scaleRange(double factor)
9125 {
9126   scaleRange(factor, range().center());
9127 }
9128 
9129 /*! \overload
9130 
9131   Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
9132   factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
9133   coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
9134   around 1.0 will have moved symmetrically closer to 1.0).
9135 
9136   \see scaleRange(double factor)
9137 */
9138 void QCPAxis::scaleRange(double factor, double center)
9139 {
9140   QCPRange oldRange = mRange;
9141   if (mScaleType == stLinear)
9142   {
9143     QCPRange newRange;
9144     newRange.lower = (mRange.lower-center)*factor + center;
9145     newRange.upper = (mRange.upper-center)*factor + center;
9146     if (QCPRange::validRange(newRange))
9147       mRange = newRange.sanitizedForLinScale();
9148   } else // mScaleType == stLogarithmic
9149   {
9150     if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
9151     {
9152       QCPRange newRange;
9153       newRange.lower = qPow(mRange.lower/center, factor)*center;
9154       newRange.upper = qPow(mRange.upper/center, factor)*center;
9155       if (QCPRange::validRange(newRange))
9156         mRange = newRange.sanitizedForLogScale();
9157     } else
9158       qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
9159   }
9160   emit rangeChanged(mRange);
9161   emit rangeChanged(mRange, oldRange);
9162 }
9163 
9164 /*!
9165   Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
9166   be done around the center of the current axis range.
9167 
9168   For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
9169   plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
9170   axis rect has.
9171 
9172   This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
9173   indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
9174   won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
9175   will follow.
9176 */
9177 void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
9178 {
9179   int otherPixelSize, ownPixelSize;
9180   
9181   if (otherAxis->orientation() == Qt::Horizontal)
9182     otherPixelSize = otherAxis->axisRect()->width();
9183   else
9184     otherPixelSize = otherAxis->axisRect()->height();
9185   
9186   if (orientation() == Qt::Horizontal)
9187     ownPixelSize = axisRect()->width();
9188   else
9189     ownPixelSize = axisRect()->height();
9190   
9191   double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
9192   setRange(range().center(), newRangeSize, Qt::AlignCenter);
9193 }
9194 
9195 /*!
9196   Changes the axis range such that all plottables associated with this axis are fully visible in
9197   that dimension.
9198   
9199   \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
9200 */
9201 void QCPAxis::rescale(bool onlyVisiblePlottables)
9202 {
9203   QCPRange newRange;
9204   bool haveRange = false;
9205   foreach (QCPAbstractPlottable *plottable, plottables())
9206   {
9207     if (!plottable->realVisibility() && onlyVisiblePlottables)
9208       continue;
9209     QCPRange plottableRange;
9210     bool currentFoundRange;
9211     QCP::SignDomain signDomain = QCP::sdBoth;
9212     if (mScaleType == stLogarithmic)
9213       signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
9214     if (plottable->keyAxis() == this)
9215       plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
9216     else
9217       plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
9218     if (currentFoundRange)
9219     {
9220       if (!haveRange)
9221         newRange = plottableRange;
9222       else
9223         newRange.expand(plottableRange);
9224       haveRange = true;
9225     }
9226   }
9227   if (haveRange)
9228   {
9229     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
9230     {
9231       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
9232       if (mScaleType == stLinear)
9233       {
9234         newRange.lower = center-mRange.size()/2.0;
9235         newRange.upper = center+mRange.size()/2.0;
9236       } else // mScaleType == stLogarithmic
9237       {
9238         newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
9239         newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
9240       }
9241     }
9242     setRange(newRange);
9243   }
9244 }
9245 
9246 /*!
9247   Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
9248 */
9249 double QCPAxis::pixelToCoord(double value) const
9250 {
9251   if (orientation() == Qt::Horizontal)
9252   {
9253     if (mScaleType == stLinear)
9254     {
9255       if (!mRangeReversed)
9256         return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower;
9257       else
9258         return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper;
9259     } else // mScaleType == stLogarithmic
9260     {
9261       if (!mRangeReversed)
9262         return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower;
9263       else
9264         return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper;
9265     }
9266   } else // orientation() == Qt::Vertical
9267   {
9268     if (mScaleType == stLinear)
9269     {
9270       if (!mRangeReversed)
9271         return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower;
9272       else
9273         return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper;
9274     } else // mScaleType == stLogarithmic
9275     {
9276       if (!mRangeReversed)
9277         return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower;
9278       else
9279         return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper;
9280     }
9281   }
9282 }
9283 
9284 /*!
9285   Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
9286 */
9287 double QCPAxis::coordToPixel(double value) const
9288 {
9289   if (orientation() == Qt::Horizontal)
9290   {
9291     if (mScaleType == stLinear)
9292     {
9293       if (!mRangeReversed)
9294         return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
9295       else
9296         return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
9297     } else // mScaleType == stLogarithmic
9298     {
9299       if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
9300         return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
9301       else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
9302         return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
9303       else
9304       {
9305         if (!mRangeReversed)
9306           return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
9307         else
9308           return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
9309       }
9310     }
9311   } else // orientation() == Qt::Vertical
9312   {
9313     if (mScaleType == stLinear)
9314     {
9315       if (!mRangeReversed)
9316         return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
9317       else
9318         return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
9319     } else // mScaleType == stLogarithmic
9320     {
9321       if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
9322         return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
9323       else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
9324         return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
9325       else
9326       {
9327         if (!mRangeReversed)
9328           return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
9329         else
9330           return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
9331       }
9332     }
9333   }
9334 }
9335 
9336 /*!
9337   Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
9338   is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
9339   function does not change the current selection state of the axis.
9340   
9341   If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
9342   
9343   \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
9344 */
9345 QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
9346 {
9347   if (!mVisible)
9348     return spNone;
9349   
9350   if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
9351     return spAxis;
9352   else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
9353     return spTickLabels;
9354   else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
9355     return spAxisLabel;
9356   else
9357     return spNone;
9358 }
9359 
9360 /* inherits documentation from base class */
9361 double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
9362 {
9363   if (!mParentPlot) return -1;
9364   SelectablePart part = getPartAt(pos);
9365   if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
9366     return -1;
9367   
9368   if (details)
9369     details->setValue(part);
9370   return mParentPlot->selectionTolerance()*0.99;
9371 }
9372 
9373 /*!
9374   Returns a list of all the plottables that have this axis as key or value axis.
9375   
9376   If you are only interested in plottables of type QCPGraph, see \ref graphs.
9377   
9378   \see graphs, items
9379 */
9380 QList<QCPAbstractPlottable*> QCPAxis::plottables() const
9381 {
9382   QList<QCPAbstractPlottable*> result;
9383   if (!mParentPlot) return result;
9384   
9385   foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
9386   {
9387     if (plottable->keyAxis() == this || plottable->valueAxis() == this)
9388       result.append(plottable);
9389   }
9390   return result;
9391 }
9392 
9393 /*!
9394   Returns a list of all the graphs that have this axis as key or value axis.
9395   
9396   \see plottables, items
9397 */
9398 QList<QCPGraph*> QCPAxis::graphs() const
9399 {
9400   QList<QCPGraph*> result;
9401   if (!mParentPlot) return result;
9402   
9403   foreach (QCPGraph *graph, mParentPlot->mGraphs)
9404   {
9405     if (graph->keyAxis() == this || graph->valueAxis() == this)
9406       result.append(graph);
9407   }
9408   return result;
9409 }
9410 
9411 /*!
9412   Returns a list of all the items that are associated with this axis. An item is considered
9413   associated with an axis if at least one of its positions uses the axis as key or value axis.
9414   
9415   \see plottables, graphs
9416 */
9417 QList<QCPAbstractItem*> QCPAxis::items() const
9418 {
9419   QList<QCPAbstractItem*> result;
9420   if (!mParentPlot) return result;
9421   
9422   foreach (QCPAbstractItem *item, mParentPlot->mItems)
9423   {
9424     foreach (QCPItemPosition *position, item->positions())
9425     {
9426       if (position->keyAxis() == this || position->valueAxis() == this)
9427       {
9428         result.append(item);
9429         break;
9430       }
9431     }
9432   }
9433   return result;
9434 }
9435 
9436 /*!
9437   Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
9438   QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
9439 */
9440 QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
9441 {
9442   switch (side)
9443   {
9444     case QCP::msLeft: return atLeft;
9445     case QCP::msRight: return atRight;
9446     case QCP::msTop: return atTop;
9447     case QCP::msBottom: return atBottom;
9448     default: break;
9449   }
9450   qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
9451   return atLeft;
9452 }
9453 
9454 /*!
9455   Returns the axis type that describes the opposite axis of an axis with the specified \a type.
9456 */
9457 QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
9458 {
9459   switch (type)
9460   {
9461     case atLeft: return atRight;
9462     case atRight: return atLeft;
9463     case atBottom: return atTop;
9464     case atTop: return atBottom;
9465   }
9466   qDebug() << Q_FUNC_INFO << "invalid axis type";
9467   return atLeft;
9468 }
9469 
9470 /* inherits documentation from base class */
9471 void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
9472 {
9473   Q_UNUSED(event)
9474   SelectablePart part = details.value<SelectablePart>();
9475   if (mSelectableParts.testFlag(part))
9476   {
9477     SelectableParts selBefore = mSelectedParts;
9478     setSelectedParts(additive ? mSelectedParts^part : part);
9479     if (selectionStateChanged)
9480       *selectionStateChanged = mSelectedParts != selBefore;
9481   }
9482 }
9483 
9484 /* inherits documentation from base class */
9485 void QCPAxis::deselectEvent(bool *selectionStateChanged)
9486 {
9487   SelectableParts selBefore = mSelectedParts;
9488   setSelectedParts(mSelectedParts & ~mSelectableParts);
9489   if (selectionStateChanged)
9490     *selectionStateChanged = mSelectedParts != selBefore;
9491 }
9492 
9493 /*! \internal
9494   
9495   This mouse event reimplementation provides the functionality to let the user drag individual axes
9496   exclusively, by startig the drag on top of the axis.
9497 
9498   For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
9499   must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
9500   (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
9501   QCPAxisRect::setRangeDragAxes)
9502   
9503   \seebaseclassmethod
9504   
9505   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
9506   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
9507 */
9508 void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
9509 {
9510   Q_UNUSED(details)
9511   if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
9512       !mAxisRect->rangeDrag().testFlag(orientation()) ||
9513       !mAxisRect->rangeDragAxes(orientation()).contains(this))
9514   {
9515     event->ignore();
9516     return;
9517   }
9518   
9519   if (event->buttons() & Qt::LeftButton)
9520   {
9521     mDragging = true;
9522     // initialize antialiasing backup in case we start dragging:
9523     if (mParentPlot->noAntialiasingOnDrag())
9524     {
9525       mAADragBackup = mParentPlot->antialiasedElements();
9526       mNotAADragBackup = mParentPlot->notAntialiasedElements();
9527     }
9528     // Mouse range dragging interaction:
9529     if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
9530       mDragStartRange = mRange;
9531   }
9532 }
9533 
9534 /*! \internal
9535   
9536   This mouse event reimplementation provides the functionality to let the user drag individual axes
9537   exclusively, by startig the drag on top of the axis.
9538   
9539   \seebaseclassmethod
9540   
9541   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
9542   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
9543   
9544   \see QCPAxis::mousePressEvent
9545 */
9546 void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
9547 {
9548   if (mDragging)
9549   {
9550     const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
9551     const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
9552     if (mScaleType == QCPAxis::stLinear)
9553     {
9554       const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
9555       setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
9556     } else if (mScaleType == QCPAxis::stLogarithmic)
9557     {
9558       const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
9559       setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
9560     }
9561     
9562     if (mParentPlot->noAntialiasingOnDrag())
9563       mParentPlot->setNotAntialiasedElements(QCP::aeAll);
9564     mParentPlot->replot(QCustomPlot::rpQueuedReplot);
9565   }
9566 }
9567 
9568 /*! \internal
9569   
9570   This mouse event reimplementation provides the functionality to let the user drag individual axes
9571   exclusively, by startig the drag on top of the axis.
9572   
9573   \seebaseclassmethod
9574   
9575   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
9576   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
9577   
9578   \see QCPAxis::mousePressEvent
9579 */
9580 void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
9581 {
9582   Q_UNUSED(event)
9583   Q_UNUSED(startPos)
9584   mDragging = false;
9585   if (mParentPlot->noAntialiasingOnDrag())
9586   {
9587     mParentPlot->setAntialiasedElements(mAADragBackup);
9588     mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
9589   }
9590 }
9591 
9592 /*! \internal
9593   
9594   This mouse event reimplementation provides the functionality to let the user zoom individual axes
9595   exclusively, by performing the wheel event on top of the axis.
9596 
9597   For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
9598   must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
9599   (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
9600   QCPAxisRect::setRangeZoomAxes)
9601   
9602   \seebaseclassmethod
9603   
9604   \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
9605   axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
9606 */
9607 void QCPAxis::wheelEvent(QWheelEvent *event)
9608 {
9609   // Mouse range zooming interaction:
9610   if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
9611       !mAxisRect->rangeZoom().testFlag(orientation()) ||
9612       !mAxisRect->rangeZoomAxes(orientation()).contains(this))
9613   {
9614     event->ignore();
9615     return;
9616   }
9617   
9618 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
9619   const double delta = event->delta();
9620 #else
9621   const double delta = event->angleDelta().y();
9622 #endif
9623   
9624 #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
9625   const QPointF pos = event->pos();
9626 #else
9627   const QPointF pos = event->position();
9628 #endif
9629   
9630   const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
9631   const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
9632   scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
9633   mParentPlot->replot();
9634 }
9635 
9636 /*! \internal
9637 
9638   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
9639   before drawing axis lines.
9640 
9641   This is the antialiasing state the painter passed to the \ref draw method is in by default.
9642   
9643   This function takes into account the local setting of the antialiasing flag as well as the
9644   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
9645   QCustomPlot::setNotAntialiasedElements.
9646   
9647   \seebaseclassmethod
9648   
9649   \see setAntialiased
9650 */
9651 void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
9652 {
9653   applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
9654 }
9655 
9656 /*! \internal
9657   
9658   Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
9659 
9660   \seebaseclassmethod
9661 */
9662 void QCPAxis::draw(QCPPainter *painter)
9663 {
9664   QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
9665   QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
9666   QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
9667   tickPositions.reserve(mTickVector.size());
9668   tickLabels.reserve(mTickVector.size());
9669   subTickPositions.reserve(mSubTickVector.size());
9670   
9671   if (mTicks)
9672   {
9673     for (int i=0; i<mTickVector.size(); ++i)
9674     {
9675       tickPositions.append(coordToPixel(mTickVector.at(i)));
9676       if (mTickLabels)
9677         tickLabels.append(mTickVectorLabels.at(i));
9678     }
9679 
9680     if (mSubTicks)
9681     {
9682       const int subTickCount = mSubTickVector.size();
9683       for (int i=0; i<subTickCount; ++i)
9684         subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
9685     }
9686   }
9687   
9688   // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
9689   // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
9690   mAxisPainter->type = mAxisType;
9691   mAxisPainter->basePen = getBasePen();
9692   mAxisPainter->labelFont = getLabelFont();
9693   mAxisPainter->labelColor = getLabelColor();
9694   mAxisPainter->label = mLabel;
9695   mAxisPainter->substituteExponent = mNumberBeautifulPowers;
9696   mAxisPainter->tickPen = getTickPen();
9697   mAxisPainter->subTickPen = getSubTickPen();
9698   mAxisPainter->tickLabelFont = getTickLabelFont();
9699   mAxisPainter->tickLabelColor = getTickLabelColor();
9700   mAxisPainter->axisRect = mAxisRect->rect();
9701   mAxisPainter->viewportRect = mParentPlot->viewport();
9702   mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
9703   mAxisPainter->reversedEndings = mRangeReversed;
9704   mAxisPainter->tickPositions = tickPositions;
9705   mAxisPainter->tickLabels = tickLabels;
9706   mAxisPainter->subTickPositions = subTickPositions;
9707   mAxisPainter->draw(painter);
9708 }
9709 
9710 /*! \internal
9711   
9712   Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
9713   QCPAxisTicker::generate on the currently installed ticker.
9714   
9715   If a change in the label text/count is detected, the cached axis margin is invalidated to make
9716   sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
9717 */
9718 void QCPAxis::setupTickVectors()
9719 {
9720   if (!mParentPlot) return;
9721   if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
9722   
9723   QVector<QString> oldLabels = mTickVectorLabels;
9724   mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
9725   mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
9726 }
9727 
9728 /*! \internal
9729   
9730   Returns the pen that is used to draw the axis base line. Depending on the selection state, this
9731   is either mSelectedBasePen or mBasePen.
9732 */
9733 QPen QCPAxis::getBasePen() const
9734 {
9735   return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
9736 }
9737 
9738 /*! \internal
9739   
9740   Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
9741   is either mSelectedTickPen or mTickPen.
9742 */
9743 QPen QCPAxis::getTickPen() const
9744 {
9745   return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
9746 }
9747 
9748 /*! \internal
9749   
9750   Returns the pen that is used to draw the subticks. Depending on the selection state, this
9751   is either mSelectedSubTickPen or mSubTickPen.
9752 */
9753 QPen QCPAxis::getSubTickPen() const
9754 {
9755   return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
9756 }
9757 
9758 /*! \internal
9759   
9760   Returns the font that is used to draw the tick labels. Depending on the selection state, this
9761   is either mSelectedTickLabelFont or mTickLabelFont.
9762 */
9763 QFont QCPAxis::getTickLabelFont() const
9764 {
9765   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
9766 }
9767 
9768 /*! \internal
9769   
9770   Returns the font that is used to draw the axis label. Depending on the selection state, this
9771   is either mSelectedLabelFont or mLabelFont.
9772 */
9773 QFont QCPAxis::getLabelFont() const
9774 {
9775   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
9776 }
9777 
9778 /*! \internal
9779   
9780   Returns the color that is used to draw the tick labels. Depending on the selection state, this
9781   is either mSelectedTickLabelColor or mTickLabelColor.
9782 */
9783 QColor QCPAxis::getTickLabelColor() const
9784 {
9785   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
9786 }
9787 
9788 /*! \internal
9789   
9790   Returns the color that is used to draw the axis label. Depending on the selection state, this
9791   is either mSelectedLabelColor or mLabelColor.
9792 */
9793 QColor QCPAxis::getLabelColor() const
9794 {
9795   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
9796 }
9797 
9798 /*! \internal
9799   
9800   Returns the appropriate outward margin for this axis. It is needed if \ref
9801   QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
9802   atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
9803   margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
9804   so changing one function likely requires the modification of the other one as well.
9805   
9806   The margin consists of the outward tick length, tick label padding, tick label size, label
9807   padding, label size, and padding.
9808   
9809   The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
9810   unchanged are very fast.
9811 */
9812 int QCPAxis::calculateMargin()
9813 {
9814   if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
9815     return 0;
9816   
9817   if (mCachedMarginValid)
9818     return mCachedMargin;
9819   
9820   // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
9821   int margin = 0;
9822   
9823   QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
9824   QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
9825   tickPositions.reserve(mTickVector.size());
9826   tickLabels.reserve(mTickVector.size());
9827   
9828   if (mTicks)
9829   {
9830     for (int i=0; i<mTickVector.size(); ++i)
9831     {
9832       tickPositions.append(coordToPixel(mTickVector.at(i)));
9833       if (mTickLabels)
9834         tickLabels.append(mTickVectorLabels.at(i));
9835     }
9836   }
9837   // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
9838   // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
9839   mAxisPainter->type = mAxisType;
9840   mAxisPainter->labelFont = getLabelFont();
9841   mAxisPainter->label = mLabel;
9842   mAxisPainter->tickLabelFont = mTickLabelFont;
9843   mAxisPainter->axisRect = mAxisRect->rect();
9844   mAxisPainter->viewportRect = mParentPlot->viewport();
9845   mAxisPainter->tickPositions = tickPositions;
9846   mAxisPainter->tickLabels = tickLabels;
9847   margin += mAxisPainter->size();
9848   margin += mPadding;
9849 
9850   mCachedMargin = margin;
9851   mCachedMarginValid = true;
9852   return margin;
9853 }
9854 
9855 /* inherits documentation from base class */
9856 QCP::Interaction QCPAxis::selectionCategory() const
9857 {
9858   return QCP::iSelectAxes;
9859 }
9860 
9861 
9862 ////////////////////////////////////////////////////////////////////////////////////////////////////
9863 //////////////////// QCPAxisPainterPrivate
9864 ////////////////////////////////////////////////////////////////////////////////////////////////////
9865 
9866 /*! \class QCPAxisPainterPrivate
9867 
9868   \internal
9869   \brief (Private)
9870   
9871   This is a private class and not part of the public QCustomPlot interface.
9872   
9873   It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
9874   axis label. It also buffers the labels to reduce replot times. The parameters are configured by
9875   directly accessing the public member variables.
9876 */
9877 
9878 /*!
9879   Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
9880   redraw, to utilize the caching mechanisms.
9881 */
9882 QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
9883   type(QCPAxis::atLeft),
9884   basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
9885   lowerEnding(QCPLineEnding::esNone),
9886   upperEnding(QCPLineEnding::esNone),
9887   labelPadding(0),
9888   tickLabelPadding(0),
9889   tickLabelRotation(0),
9890   tickLabelSide(QCPAxis::lsOutside),
9891   substituteExponent(true),
9892   numberMultiplyCross(false),
9893   tickLengthIn(5),
9894   tickLengthOut(0),
9895   subTickLengthIn(2),
9896   subTickLengthOut(0),
9897   tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
9898   subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
9899   offset(0),
9900   abbreviateDecimalPowers(false),
9901   reversedEndings(false),
9902   mParentPlot(parentPlot),
9903   mLabelCache(16) // cache at most 16 (tick) labels
9904 {
9905 }
9906 
9907 QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
9908 {
9909 }
9910 
9911 /*! \internal
9912   
9913   Draws the axis with the specified \a painter.
9914   
9915   The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
9916   here, too.
9917 */
9918 void QCPAxisPainterPrivate::draw(QCPPainter *painter)
9919 {
9920   QByteArray newHash = generateLabelParameterHash();
9921   if (newHash != mLabelParameterHash)
9922   {
9923     mLabelCache.clear();
9924     mLabelParameterHash = newHash;
9925   }
9926   
9927   QPoint origin;
9928   switch (type)
9929   {
9930     case QCPAxis::atLeft:   origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
9931     case QCPAxis::atRight:  origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
9932     case QCPAxis::atTop:    origin = axisRect.topLeft()    +QPoint(0, -offset); break;
9933     case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
9934   }
9935 
9936   double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
9937   switch (type)
9938   {
9939     case QCPAxis::atTop: yCor = -1; break;
9940     case QCPAxis::atRight: xCor = 1; break;
9941     default: break;
9942   }
9943   int margin = 0;
9944   // draw baseline:
9945   QLineF baseLine;
9946   painter->setPen(basePen);
9947   if (QCPAxis::orientation(type) == Qt::Horizontal)
9948     baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
9949   else
9950     baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
9951   if (reversedEndings)
9952     baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
9953   painter->drawLine(baseLine);
9954   
9955   // draw ticks:
9956   if (!tickPositions.isEmpty())
9957   {
9958     painter->setPen(tickPen);
9959     int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
9960     if (QCPAxis::orientation(type) == Qt::Horizontal)
9961     {
9962       foreach (double tickPos, tickPositions)
9963         painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor));
9964     } else
9965     {
9966       foreach (double tickPos, tickPositions)
9967         painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor));
9968     }
9969   }
9970   
9971   // draw subticks:
9972   if (!subTickPositions.isEmpty())
9973   {
9974     painter->setPen(subTickPen);
9975     // direction of ticks ("inward" is right for left axis and left for right axis)
9976     int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
9977     if (QCPAxis::orientation(type) == Qt::Horizontal)
9978     {
9979       foreach (double subTickPos, subTickPositions)
9980         painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
9981     } else
9982     {
9983       foreach (double subTickPos, subTickPositions)
9984         painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
9985     }
9986   }
9987   margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
9988   
9989   // draw axis base endings:
9990   bool antialiasingBackup = painter->antialiasing();
9991   painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
9992   painter->setBrush(QBrush(basePen.color()));
9993   QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
9994   if (lowerEnding.style() != QCPLineEnding::esNone)
9995     lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
9996   if (upperEnding.style() != QCPLineEnding::esNone)
9997     upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
9998   painter->setAntialiasing(antialiasingBackup);
9999   
10000   // tick labels:
10001   QRect oldClipRect;
10002   if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
10003   {
10004     oldClipRect = painter->clipRegion().boundingRect();
10005     painter->setClipRect(axisRect);
10006   }
10007   QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
10008   if (!tickLabels.isEmpty())
10009   {
10010     if (tickLabelSide == QCPAxis::lsOutside)
10011       margin += tickLabelPadding;
10012     painter->setFont(tickLabelFont);
10013     painter->setPen(QPen(tickLabelColor));
10014     const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
10015     int distanceToAxis = margin;
10016     if (tickLabelSide == QCPAxis::lsInside)
10017       distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
10018     for (int i=0; i<maxLabelIndex; ++i)
10019       placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
10020     if (tickLabelSide == QCPAxis::lsOutside)
10021       margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
10022   }
10023   if (tickLabelSide == QCPAxis::lsInside)
10024     painter->setClipRect(oldClipRect);
10025   
10026   // axis label:
10027   QRect labelBounds;
10028   if (!label.isEmpty())
10029   {
10030     margin += labelPadding;
10031     painter->setFont(labelFont);
10032     painter->setPen(QPen(labelColor));
10033     labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
10034     if (type == QCPAxis::atLeft)
10035     {
10036       QTransform oldTransform = painter->transform();
10037       painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
10038       painter->rotate(-90);
10039       painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
10040       painter->setTransform(oldTransform);
10041     }
10042     else if (type == QCPAxis::atRight)
10043     {
10044       QTransform oldTransform = painter->transform();
10045       painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
10046       painter->rotate(90);
10047       painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
10048       painter->setTransform(oldTransform);
10049     }
10050     else if (type == QCPAxis::atTop)
10051       painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
10052     else if (type == QCPAxis::atBottom)
10053       painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
10054   }
10055   
10056   // set selection boxes:
10057   int selectionTolerance = 0;
10058   if (mParentPlot)
10059     selectionTolerance = mParentPlot->selectionTolerance();
10060   else
10061     qDebug() << Q_FUNC_INFO << "mParentPlot is null";
10062   int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
10063   int selAxisInSize = selectionTolerance;
10064   int selTickLabelSize;
10065   int selTickLabelOffset;
10066   if (tickLabelSide == QCPAxis::lsOutside)
10067   {
10068     selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
10069     selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
10070   } else
10071   {
10072     selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
10073     selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
10074   }
10075   int selLabelSize = labelBounds.height();
10076   int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
10077   if (type == QCPAxis::atLeft)
10078   {
10079     mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
10080     mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
10081     mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
10082   } else if (type == QCPAxis::atRight)
10083   {
10084     mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
10085     mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
10086     mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
10087   } else if (type == QCPAxis::atTop)
10088   {
10089     mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
10090     mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
10091     mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
10092   } else if (type == QCPAxis::atBottom)
10093   {
10094     mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
10095     mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
10096     mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
10097   }
10098   mAxisSelectionBox = mAxisSelectionBox.normalized();
10099   mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
10100   mLabelSelectionBox = mLabelSelectionBox.normalized();
10101   // draw hitboxes for debug purposes:
10102   //painter->setBrush(Qt::NoBrush);
10103   //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
10104 }
10105 
10106 /*! \internal
10107   
10108   Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
10109   direction) needed to fit the axis.
10110 */
10111 int QCPAxisPainterPrivate::size()
10112 {
10113   int result = 0;
10114 
10115   QByteArray newHash = generateLabelParameterHash();
10116   if (newHash != mLabelParameterHash)
10117   {
10118     mLabelCache.clear();
10119     mLabelParameterHash = newHash;
10120   }
10121   
10122   // get length of tick marks pointing outwards:
10123   if (!tickPositions.isEmpty())
10124     result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
10125   
10126   // calculate size of tick labels:
10127   if (tickLabelSide == QCPAxis::lsOutside)
10128   {
10129     QSize tickLabelsSize(0, 0);
10130     if (!tickLabels.isEmpty())
10131     {
10132       foreach (const QString &tickLabel, tickLabels)
10133         getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
10134       result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
10135     result += tickLabelPadding;
10136     }
10137   }
10138   
10139   // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
10140   if (!label.isEmpty())
10141   {
10142     QFontMetrics fontMetrics(labelFont);
10143     QRect bounds;
10144     bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
10145     result += bounds.height() + labelPadding;
10146   }
10147 
10148   return result;
10149 }
10150 
10151 /*! \internal
10152   
10153   Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
10154   method is called automatically in \ref draw, if any parameters have changed that invalidate the
10155   cached labels, such as font, color, etc.
10156 */
10157 void QCPAxisPainterPrivate::clearCache()
10158 {
10159   mLabelCache.clear();
10160 }
10161 
10162 /*! \internal
10163   
10164   Returns a hash that allows uniquely identifying whether the label parameters have changed such
10165   that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
10166   return value of this method hasn't changed since the last redraw, the respective label parameters
10167   haven't changed and cached labels may be used.
10168 */
10169 QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
10170 {
10171   QByteArray result;
10172   result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
10173   result.append(QByteArray::number(tickLabelRotation));
10174   result.append(QByteArray::number(int(tickLabelSide)));
10175   result.append(QByteArray::number(int(substituteExponent)));
10176   result.append(QByteArray::number(int(numberMultiplyCross)));
10177   result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
10178   result.append(tickLabelFont.toString().toLatin1());
10179   return result;
10180 }
10181 
10182 /*! \internal
10183   
10184   Draws a single tick label with the provided \a painter, utilizing the internal label cache to
10185   significantly speed up drawing of labels that were drawn in previous calls. The tick label is
10186   always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
10187   pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
10188   for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
10189   at which the label should be drawn.
10190   
10191   In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
10192   largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
10193   drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
10194   tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
10195   holds.
10196   
10197   The label is drawn with the font and pen that are currently set on the \a painter. To draw
10198   superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
10199   getTickLabelData).
10200 */
10201 void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
10202 {
10203   // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
10204   if (text.isEmpty()) return;
10205   QSize finalSize;
10206   QPointF labelAnchor;
10207   switch (type)
10208   {
10209     case QCPAxis::atLeft:   labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
10210     case QCPAxis::atRight:  labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
10211     case QCPAxis::atTop:    labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
10212     case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
10213   }
10214   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
10215   {
10216     CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
10217     if (!cachedLabel)  // no cached label existed, create it
10218     {
10219       cachedLabel = new CachedLabel;
10220       TickLabelData labelData = getTickLabelData(painter->font(), text);
10221       cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
10222       if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
10223       {
10224         cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
10225 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
10226 #  ifdef QCP_DEVICEPIXELRATIO_FLOAT
10227         cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
10228 #  else
10229         cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
10230 #  endif
10231 #endif
10232       } else
10233         cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
10234       cachedLabel->pixmap.fill(Qt::transparent);
10235       QCPPainter cachePainter(&cachedLabel->pixmap);
10236       cachePainter.setPen(painter->pen());
10237       drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
10238     }
10239     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
10240     bool labelClippedByBorder = false;
10241     if (tickLabelSide == QCPAxis::lsOutside)
10242     {
10243       if (QCPAxis::orientation(type) == Qt::Horizontal)
10244         labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
10245       else
10246         labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
10247     }
10248     if (!labelClippedByBorder)
10249     {
10250       painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
10251       finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
10252     }
10253     mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
10254   } else // label caching disabled, draw text directly on surface:
10255   {
10256     TickLabelData labelData = getTickLabelData(painter->font(), text);
10257     QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
10258     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
10259      bool labelClippedByBorder = false;
10260     if (tickLabelSide == QCPAxis::lsOutside)
10261     {
10262       if (QCPAxis::orientation(type) == Qt::Horizontal)
10263         labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
10264       else
10265         labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
10266     }
10267     if (!labelClippedByBorder)
10268     {
10269       drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
10270       finalSize = labelData.rotatedTotalBounds.size();
10271     }
10272   }
10273   
10274   // expand passed tickLabelsSize if current tick label is larger:
10275   if (finalSize.width() > tickLabelsSize->width())
10276     tickLabelsSize->setWidth(finalSize.width());
10277   if (finalSize.height() > tickLabelsSize->height())
10278     tickLabelsSize->setHeight(finalSize.height());
10279 }
10280 
10281 /*! \internal
10282   
10283   This is a \ref placeTickLabel helper function.
10284   
10285   Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
10286   y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
10287   directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
10288   QCP::phCacheLabels plotting hint is not set.
10289 */
10290 void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
10291 {
10292   // backup painter settings that we're about to change:
10293   QTransform oldTransform = painter->transform();
10294   QFont oldFont = painter->font();
10295   
10296   // transform painter to position/rotation:
10297   painter->translate(x, y);
10298   if (!qFuzzyIsNull(tickLabelRotation))
10299     painter->rotate(tickLabelRotation);
10300   
10301   // draw text:
10302   if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
10303   {
10304     painter->setFont(labelData.baseFont);
10305     painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
10306     if (!labelData.suffixPart.isEmpty())
10307       painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
10308     painter->setFont(labelData.expFont);
10309     painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip,  labelData.expPart);
10310   } else
10311   {
10312     painter->setFont(labelData.baseFont);
10313     painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
10314   }
10315   
10316   // reset painter settings to what it was before:
10317   painter->setTransform(oldTransform);
10318   painter->setFont(oldFont);
10319 }
10320 
10321 /*! \internal
10322   
10323   This is a \ref placeTickLabel helper function.
10324   
10325   Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
10326   processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
10327   exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
10328 */
10329 QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
10330 {
10331   TickLabelData result;
10332   
10333   // determine whether beautiful decimal powers should be used
10334   bool useBeautifulPowers = false;
10335   int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
10336   int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
10337   if (substituteExponent)
10338   {
10339     ePos = text.indexOf(QLatin1Char('e'));
10340     if (ePos > 0 && text.at(ePos-1).isDigit())
10341     {
10342       eLast = ePos;
10343       while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
10344         ++eLast;
10345       if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
10346         useBeautifulPowers = true;
10347     }
10348   }
10349   
10350   // calculate text bounding rects and do string preparation for beautiful decimal powers:
10351   result.baseFont = font;
10352   if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
10353     result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
10354   if (useBeautifulPowers)
10355   {
10356     // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
10357     result.basePart = text.left(ePos);
10358     result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
10359     // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
10360     if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
10361       result.basePart = QLatin1String("10");
10362     else
10363       result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
10364     result.expPart = text.mid(ePos+1, eLast-ePos);
10365     // clip "+" and leading zeros off expPart:
10366     while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
10367       result.expPart.remove(1, 1);
10368     if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
10369       result.expPart.remove(0, 1);
10370     // prepare smaller font for exponent:
10371     result.expFont = font;
10372     if (result.expFont.pointSize() > 0)
10373       result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
10374     else
10375       result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
10376     // calculate bounding rects of base part(s), exponent part and total one:
10377     result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
10378     result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
10379     if (!result.suffixPart.isEmpty())
10380       result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
10381     result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
10382   } else // useBeautifulPowers == false
10383   {
10384     result.basePart = text;
10385     result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
10386   }
10387   result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
10388   
10389   // calculate possibly different bounding rect after rotation:
10390   result.rotatedTotalBounds = result.totalBounds;
10391   if (!qFuzzyIsNull(tickLabelRotation))
10392   {
10393     QTransform transform;
10394     transform.rotate(tickLabelRotation);
10395     result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
10396   }
10397   
10398   return result;
10399 }
10400 
10401 /*! \internal
10402   
10403   This is a \ref placeTickLabel helper function.
10404   
10405   Calculates the offset at which the top left corner of the specified tick label shall be drawn.
10406   The offset is relative to a point right next to the tick the label belongs to.
10407   
10408   This function is thus responsible for e.g. centering tick labels under ticks and positioning them
10409   appropriately when they are rotated.
10410 */
10411 QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
10412 {
10413   /*
10414     calculate label offset from base point at tick (non-trivial, for best visual appearance): short
10415     explanation for bottom axis: The anchor, i.e. the point in the label that is placed
10416     horizontally under the corresponding tick is always on the label side that is closer to the
10417     axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
10418     is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
10419     will be centered under the tick (i.e. displaced horizontally by half its height). At the same
10420     time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
10421     labels.
10422   */
10423   bool doRotation = !qFuzzyIsNull(tickLabelRotation);
10424   bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
10425   double radians = tickLabelRotation/180.0*M_PI;
10426   double x = 0;
10427   double y = 0;
10428   if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
10429   {
10430     if (doRotation)
10431     {
10432       if (tickLabelRotation > 0)
10433       {
10434         x = -qCos(radians)*labelData.totalBounds.width();
10435         y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
10436       } else
10437       {
10438         x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
10439         y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
10440       }
10441     } else
10442     {
10443       x = -labelData.totalBounds.width();
10444       y = -labelData.totalBounds.height()/2.0;
10445     }
10446   } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
10447   {
10448     if (doRotation)
10449     {
10450       if (tickLabelRotation > 0)
10451       {
10452         x = +qSin(radians)*labelData.totalBounds.height();
10453         y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
10454       } else
10455       {
10456         x = 0;
10457         y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
10458       }
10459     } else
10460     {
10461       x = 0;
10462       y = -labelData.totalBounds.height()/2.0;
10463     }
10464   } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
10465   {
10466     if (doRotation)
10467     {
10468       if (tickLabelRotation > 0)
10469       {
10470         x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
10471         y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
10472       } else
10473       {
10474         x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
10475         y = -qCos(-radians)*labelData.totalBounds.height();
10476       }
10477     } else
10478     {
10479       x = -labelData.totalBounds.width()/2.0;
10480       y = -labelData.totalBounds.height();
10481     }
10482   } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
10483   {
10484     if (doRotation)
10485     {
10486       if (tickLabelRotation > 0)
10487       {
10488         x = +qSin(radians)*labelData.totalBounds.height()/2.0;
10489         y = 0;
10490       } else
10491       {
10492         x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
10493         y = +qSin(-radians)*labelData.totalBounds.width();
10494       }
10495     } else
10496     {
10497       x = -labelData.totalBounds.width()/2.0;
10498       y = 0;
10499     }
10500   }
10501   
10502   return {x, y};
10503 }
10504 
10505 /*! \internal
10506   
10507   Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
10508   to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
10509   margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
10510   smaller width/height.
10511 */
10512 void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text,  QSize *tickLabelsSize) const
10513 {
10514   // note: this function must return the same tick label sizes as the placeTickLabel function.
10515   QSize finalSize;
10516   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
10517   {
10518     const CachedLabel *cachedLabel = mLabelCache.object(text);
10519     finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
10520   } else // label caching disabled or no label with this text cached:
10521   {
10522     TickLabelData labelData = getTickLabelData(font, text);
10523     finalSize = labelData.rotatedTotalBounds.size();
10524   }
10525   
10526   // expand passed tickLabelsSize if current tick label is larger:
10527   if (finalSize.width() > tickLabelsSize->width())
10528     tickLabelsSize->setWidth(finalSize.width());
10529   if (finalSize.height() > tickLabelsSize->height())
10530     tickLabelsSize->setHeight(finalSize.height());
10531 }
10532 /* end of 'src/axis/axis.cpp' */
10533 
10534 
10535 /* including file 'src/scatterstyle.cpp'    */
10536 /* modified 2021-03-29T02:30:44, size 17466 */
10537 
10538 ////////////////////////////////////////////////////////////////////////////////////////////////////
10539 //////////////////// QCPScatterStyle
10540 ////////////////////////////////////////////////////////////////////////////////////////////////////
10541 
10542 /*! \class QCPScatterStyle
10543   \brief Represents the visual appearance of scatter points
10544   
10545   This class holds information about shape, color and size of scatter points. In plottables like
10546   QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
10547   QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
10548   
10549   A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
10550   fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
10551   be controlled with \ref setSize.
10552 
10553   \section QCPScatterStyle-defining Specifying a scatter style
10554   
10555   You can set all these configurations either by calling the respective functions on an instance:
10556   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
10557   
10558   Or you can use one of the various constructors that take different parameter combinations, making
10559   it easy to specify a scatter style in a single call, like so:
10560   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
10561   
10562   \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
10563   
10564   There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
10565   QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
10566   isPenDefined will return false. It leads to scatter points that inherit the pen from the
10567   plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
10568   color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
10569   it very convenient to set up typical scatter settings:
10570   
10571   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
10572 
10573   Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
10574   because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
10575   into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
10576   constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
10577   ScatterShape, where actually a QCPScatterStyle is expected.
10578   
10579   \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
10580   
10581   QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
10582 
10583   For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
10584   setCustomPath function or call the constructor that takes a painter path. The scatter shape will
10585   automatically be set to \ref ssCustom.
10586   
10587   For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
10588   constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
10589   Note that \ref setSize does not influence the appearance of the pixmap.
10590 */
10591 
10592 /* start documentation of inline functions */
10593 
10594 /*! \fn bool QCPScatterStyle::isNone() const
10595   
10596   Returns whether the scatter shape is \ref ssNone.
10597   
10598   \see setShape
10599 */
10600 
10601 /*! \fn bool QCPScatterStyle::isPenDefined() const
10602   
10603   Returns whether a pen has been defined for this scatter style.
10604   
10605   The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
10606   are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
10607   is undefined, the pen of the respective plottable will be used for drawing scatters.
10608   
10609   If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
10610   \ref undefinePen.
10611   
10612   \see setPen
10613 */
10614 
10615 /* end documentation of inline functions */
10616 
10617 /*!
10618   Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
10619   
10620   Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
10621   from the plottable that uses this scatter style.
10622 */
10623 QCPScatterStyle::QCPScatterStyle() :
10624   mSize(6),
10625   mShape(ssNone),
10626   mPen(Qt::NoPen),
10627   mBrush(Qt::NoBrush),
10628   mPenDefined(false)
10629 {
10630 }
10631 
10632 /*!
10633   Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
10634   brush is defined.
10635   
10636   Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
10637   from the plottable that uses this scatter style.
10638 */
10639 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
10640   mSize(size),
10641   mShape(shape),
10642   mPen(Qt::NoPen),
10643   mBrush(Qt::NoBrush),
10644   mPenDefined(false)
10645 {
10646 }
10647 
10648 /*!
10649   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
10650   and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
10651 */
10652 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
10653   mSize(size),
10654   mShape(shape),
10655   mPen(QPen(color)),
10656   mBrush(Qt::NoBrush),
10657   mPenDefined(true)
10658 {
10659 }
10660 
10661 /*!
10662   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
10663   the brush color to \a fill (with a solid pattern), and size to \a size.
10664 */
10665 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
10666   mSize(size),
10667   mShape(shape),
10668   mPen(QPen(color)),
10669   mBrush(QBrush(fill)),
10670   mPenDefined(true)
10671 {
10672 }
10673 
10674 /*!
10675   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
10676   brush to \a brush, and size to \a size.
10677   
10678   \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
10679   and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
10680   <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
10681   doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
10682   <tt>Qt::NoPen</tt> for a QColor and use the
10683   \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
10684   constructor instead (which will lead to an unexpected look of the scatter points). To prevent
10685   this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
10686   instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
10687   wanted.
10688 */
10689 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
10690   mSize(size),
10691   mShape(shape),
10692   mPen(pen),
10693   mBrush(brush),
10694   mPenDefined(pen.style() != Qt::NoPen)
10695 {
10696 }
10697 
10698 /*!
10699   Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
10700   is set to \ref ssPixmap.
10701 */
10702 QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
10703   mSize(5),
10704   mShape(ssPixmap),
10705   mPen(Qt::NoPen),
10706   mBrush(Qt::NoBrush),
10707   mPixmap(pixmap),
10708   mPenDefined(false)
10709 {
10710 }
10711 
10712 /*!
10713   Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
10714   scatter shape is set to \ref ssCustom.
10715   
10716   The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
10717   different meaning than for built-in scatter points: The custom path will be drawn scaled by a
10718   factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
10719   original size by default. To for example double the size of the path, set \a size to 12.
10720 */
10721 QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
10722   mSize(size),
10723   mShape(ssCustom),
10724   mPen(pen),
10725   mBrush(brush),
10726   mCustomPath(customPath),
10727   mPenDefined(pen.style() != Qt::NoPen)
10728 {
10729 }
10730 
10731 /*!
10732   Copies the specified \a properties from the \a other scatter style to this scatter style.
10733 */
10734 void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
10735 {
10736   if (properties.testFlag(spPen))
10737   {
10738     setPen(other.pen());
10739     if (!other.isPenDefined())
10740       undefinePen();
10741   }
10742   if (properties.testFlag(spBrush))
10743     setBrush(other.brush());
10744   if (properties.testFlag(spSize))
10745     setSize(other.size());
10746   if (properties.testFlag(spShape))
10747   {
10748     setShape(other.shape());
10749     if (other.shape() == ssPixmap)
10750       setPixmap(other.pixmap());
10751     else if (other.shape() == ssCustom)
10752       setCustomPath(other.customPath());
10753   }
10754 }
10755 
10756 /*!
10757   Sets the size (pixel diameter) of the drawn scatter points to \a size.
10758   
10759   \see setShape
10760 */
10761 void QCPScatterStyle::setSize(double size)
10762 {
10763   mSize = size;
10764 }
10765 
10766 /*!
10767   Sets the shape to \a shape.
10768   
10769   Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
10770   ssPixmap and \ref ssCustom, respectively.
10771   
10772   \see setSize
10773 */
10774 void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
10775 {
10776   mShape = shape;
10777 }
10778 
10779 /*!
10780   Sets the pen that will be used to draw scatter points to \a pen.
10781   
10782   If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
10783   a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
10784   previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
10785   
10786   \see setBrush
10787 */
10788 void QCPScatterStyle::setPen(const QPen &pen)
10789 {
10790   mPenDefined = true;
10791   mPen = pen;
10792 }
10793 
10794 /*!
10795   Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
10796   shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
10797   
10798   \see setPen
10799 */
10800 void QCPScatterStyle::setBrush(const QBrush &brush)
10801 {
10802   mBrush = brush;
10803 }
10804 
10805 /*!
10806   Sets the pixmap that will be drawn as scatter point to \a pixmap.
10807   
10808   Note that \ref setSize does not influence the appearance of the pixmap.
10809   
10810   The scatter shape is automatically set to \ref ssPixmap.
10811 */
10812 void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
10813 {
10814   setShape(ssPixmap);
10815   mPixmap = pixmap;
10816 }
10817 
10818 /*!
10819   Sets the custom shape that will be drawn as scatter point to \a customPath.
10820   
10821   The scatter shape is automatically set to \ref ssCustom.
10822 */
10823 void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
10824 {
10825   setShape(ssCustom);
10826   mCustomPath = customPath;
10827 }
10828 
10829 /*!
10830   Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
10831   implies).
10832 
10833   A call to \ref setPen will define a pen.
10834 */
10835 void QCPScatterStyle::undefinePen()
10836 {
10837   mPenDefined = false;
10838 }
10839 
10840 /*!
10841   Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
10842   undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
10843   
10844   This function is used by plottables (or any class that wants to draw scatters) just before a
10845   number of scatters with this style shall be drawn with the \a painter.
10846   
10847   \see drawShape
10848 */
10849 void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
10850 {
10851   painter->setPen(mPenDefined ? mPen : defaultPen);
10852   painter->setBrush(mBrush);
10853 }
10854 
10855 /*!
10856   Draws the scatter shape with \a painter at position \a pos.
10857   
10858   This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
10859   called before scatter points are drawn with \ref drawShape.
10860   
10861   \see applyTo
10862 */
10863 void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
10864 {
10865   drawShape(painter, pos.x(), pos.y());
10866 }
10867 
10868 /*! \overload
10869   Draws the scatter shape with \a painter at position \a x and \a y.
10870 */
10871 void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
10872 {
10873   double w = mSize/2.0;
10874   switch (mShape)
10875   {
10876     case ssNone: break;
10877     case ssDot:
10878     {
10879       painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
10880       break;
10881     }
10882     case ssCross:
10883     {
10884       painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
10885       painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
10886       break;
10887     }
10888     case ssPlus:
10889     {
10890       painter->drawLine(QLineF(x-w,   y, x+w,   y));
10891       painter->drawLine(QLineF(  x, y+w,   x, y-w));
10892       break;
10893     }
10894     case ssCircle:
10895     {
10896       painter->drawEllipse(QPointF(x , y), w, w);
10897       break;
10898     }
10899     case ssDisc:
10900     {
10901       QBrush b = painter->brush();
10902       painter->setBrush(painter->pen().color());
10903       painter->drawEllipse(QPointF(x , y), w, w);
10904       painter->setBrush(b);
10905       break;
10906     }
10907     case ssSquare:
10908     {
10909       painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
10910       break;
10911     }
10912     case ssDiamond:
10913     {
10914       QPointF lineArray[4] = {QPointF(x-w,   y),
10915                               QPointF(  x, y-w),
10916                               QPointF(x+w,   y),
10917                               QPointF(  x, y+w)};
10918       painter->drawPolygon(lineArray, 4);
10919       break;
10920     }
10921     case ssStar:
10922     {
10923       painter->drawLine(QLineF(x-w,   y, x+w,   y));
10924       painter->drawLine(QLineF(  x, y+w,   x, y-w));
10925       painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
10926       painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
10927       break;
10928     }
10929     case ssTriangle:
10930     {
10931       QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
10932                               QPointF(x+w, y+0.755*w),
10933                               QPointF(  x, y-0.977*w)};
10934       painter->drawPolygon(lineArray, 3);
10935       break;
10936     }
10937     case ssTriangleInverted:
10938     {
10939       QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
10940                               QPointF(x+w, y-0.755*w),
10941                               QPointF(  x, y+0.977*w)};
10942       painter->drawPolygon(lineArray, 3);
10943       break;
10944     }
10945     case ssCrossSquare:
10946     {
10947       painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
10948       painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
10949       painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
10950       break;
10951     }
10952     case ssPlusSquare:
10953     {
10954       painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
10955       painter->drawLine(QLineF(x-w,   y, x+w*0.95,   y));
10956       painter->drawLine(QLineF(  x, y+w,        x, y-w));
10957       break;
10958     }
10959     case ssCrossCircle:
10960     {
10961       painter->drawEllipse(QPointF(x, y), w, w);
10962       painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
10963       painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
10964       break;
10965     }
10966     case ssPlusCircle:
10967     {
10968       painter->drawEllipse(QPointF(x, y), w, w);
10969       painter->drawLine(QLineF(x-w,   y, x+w,   y));
10970       painter->drawLine(QLineF(  x, y+w,   x, y-w));
10971       break;
10972     }
10973     case ssPeace:
10974     {
10975       painter->drawEllipse(QPointF(x, y), w, w);
10976       painter->drawLine(QLineF(x, y-w,         x,       y+w));
10977       painter->drawLine(QLineF(x,   y, x-w*0.707, y+w*0.707));
10978       painter->drawLine(QLineF(x,   y, x+w*0.707, y+w*0.707));
10979       break;
10980     }
10981     case ssPixmap:
10982     {
10983       const double widthHalf = mPixmap.width()*0.5;
10984       const double heightHalf = mPixmap.height()*0.5;
10985 #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
10986       const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
10987 #else
10988       const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
10989 #endif
10990       if (clipRect.contains(x, y))
10991         painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap);
10992       break;
10993     }
10994     case ssCustom:
10995     {
10996       QTransform oldTransform = painter->transform();
10997       painter->translate(x, y);
10998       painter->scale(mSize/6.0, mSize/6.0);
10999       painter->drawPath(mCustomPath);
11000       painter->setTransform(oldTransform);
11001       break;
11002     }
11003   }
11004 }
11005 /* end of 'src/scatterstyle.cpp' */
11006 
11007 
11008 /* including file 'src/plottable.cpp'       */
11009 /* modified 2021-03-29T02:30:44, size 38818 */
11010 
11011 ////////////////////////////////////////////////////////////////////////////////////////////////////
11012 //////////////////// QCPSelectionDecorator
11013 ////////////////////////////////////////////////////////////////////////////////////////////////////
11014 
11015 /*! \class QCPSelectionDecorator
11016   \brief Controls how a plottable's data selection is drawn
11017   
11018   Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
11019   QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
11020   
11021   The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
11022   scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
11023   QCPScatterStyle is itself composed of different properties such as color shape and size, the
11024   decorator allows specifying exactly which of those properties shall be used for the selected data
11025   point, via \ref setUsedScatterProperties.
11026   
11027   A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
11028   QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
11029   of selected segments.
11030   
11031   Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
11032   especially useful since plottables take ownership of the passed selection decorator, and thus the
11033   same decorator instance can not be passed to multiple plottables.
11034   
11035   Selection decorators can also themselves perform drawing operations by reimplementing \ref
11036   drawDecoration, which is called by the plottable's draw method. The base class \ref
11037   QCPSelectionDecorator does not make use of this however. For example, \ref
11038   QCPSelectionDecoratorBracket draws brackets around selected data segments.
11039 */
11040 
11041 /*!
11042   Creates a new QCPSelectionDecorator instance with default values
11043 */
11044 QCPSelectionDecorator::QCPSelectionDecorator() :
11045   mPen(QColor(80, 80, 255), 2.5),
11046   mBrush(Qt::NoBrush),
11047   mUsedScatterProperties(QCPScatterStyle::spNone),
11048   mPlottable(nullptr)
11049 {
11050 }
11051 
11052 QCPSelectionDecorator::~QCPSelectionDecorator()
11053 {
11054 }
11055 
11056 /*!
11057   Sets the pen that will be used by the parent plottable to draw selected data segments.
11058 */
11059 void QCPSelectionDecorator::setPen(const QPen &pen)
11060 {
11061   mPen = pen;
11062 }
11063 
11064 /*!
11065   Sets the brush that will be used by the parent plottable to draw selected data segments.
11066 */
11067 void QCPSelectionDecorator::setBrush(const QBrush &brush)
11068 {
11069   mBrush = brush;
11070 }
11071 
11072 /*!
11073   Sets the scatter style that will be used by the parent plottable to draw scatters in selected
11074   data segments.
11075   
11076   \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
11077   plottable. The used properties can also be changed via \ref setUsedScatterProperties.
11078 */
11079 void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
11080 {
11081   mScatterStyle = scatterStyle;
11082   setUsedScatterProperties(usedProperties);
11083 }
11084 
11085 /*!
11086   Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
11087   will be used for selected data segments. All properties of the scatter style that are not
11088   specified in \a properties will remain as specified in the plottable's original scatter style.
11089   
11090   \see QCPScatterStyle::ScatterProperty
11091 */
11092 void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
11093 {
11094   mUsedScatterProperties = properties;
11095 }
11096 
11097 /*!
11098   Sets the pen of \a painter to the pen of this selection decorator.
11099   
11100   \see applyBrush, getFinalScatterStyle
11101 */
11102 void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
11103 {
11104   painter->setPen(mPen);
11105 }
11106 
11107 /*!
11108   Sets the brush of \a painter to the brush of this selection decorator.
11109   
11110   \see applyPen, getFinalScatterStyle
11111 */
11112 void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
11113 {
11114   painter->setBrush(mBrush);
11115 }
11116 
11117 /*!
11118   Returns the scatter style that the parent plottable shall use for selected scatter points. The
11119   plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
11120   on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
11121   selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
11122   
11123   \see applyPen, applyBrush, setScatterStyle
11124 */
11125 QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
11126 {
11127   QCPScatterStyle result(unselectedStyle);
11128   result.setFromOther(mScatterStyle, mUsedScatterProperties);
11129   
11130   // if style shall inherit pen from plottable (has no own pen defined), give it the selected
11131   // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
11132   // plottable:
11133   if (!result.isPenDefined())
11134     result.setPen(mPen);
11135   
11136   return result;
11137 }
11138 
11139 /*!
11140   Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
11141   this selection decorator.
11142 */
11143 void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
11144 {
11145   setPen(other->pen());
11146   setBrush(other->brush());
11147   setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
11148 }
11149 
11150 /*!
11151   This method is called by all plottables' draw methods to allow custom selection decorations to be
11152   drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
11153   selection for which the decoration shall be drawn.
11154   
11155   The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
11156   this method does nothing.
11157 */
11158 void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
11159 {
11160   Q_UNUSED(painter)
11161   Q_UNUSED(selection)
11162 }
11163 
11164 /*! \internal
11165   
11166   This method is called as soon as a selection decorator is associated with a plottable, by a call
11167   to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
11168   data points via the \ref QCPAbstractPlottable::interface1D interface).
11169   
11170   If the selection decorator was already added to a different plottable before, this method aborts
11171   the registration and returns false.
11172 */
11173 bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
11174 {
11175   if (!mPlottable)
11176   {
11177     mPlottable = plottable;
11178     return true;
11179   } else
11180   {
11181     qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
11182     return false;
11183   }
11184 }
11185 
11186 
11187 ////////////////////////////////////////////////////////////////////////////////////////////////////
11188 //////////////////// QCPAbstractPlottable
11189 ////////////////////////////////////////////////////////////////////////////////////////////////////
11190 
11191 /*! \class QCPAbstractPlottable
11192   \brief The abstract base class for all data representing objects in a plot.
11193 
11194   It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
11195   abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
11196   create new ways of displaying data (see "Creating own plottables" below). Plottables that display
11197   one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
11198   each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
11199   there.
11200   
11201   All further specifics are in the subclasses, for example:
11202   \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
11203   (typically created with \ref QCustomPlot::addGraph)
11204   \li A parametric curve: \ref QCPCurve
11205   \li A bar chart: \ref QCPBars
11206   \li A statistical box plot: \ref QCPStatisticalBox
11207   \li A color encoded two-dimensional map: \ref QCPColorMap
11208   \li An OHLC/Candlestick chart: \ref QCPFinancial
11209   
11210   \section plottables-subclassing Creating own plottables
11211   
11212   Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
11213   two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
11214   data dimensions. If you want to display data with only one logical key dimension, you should
11215   rather derive from \ref QCPAbstractPlottable1D.
11216   
11217   If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
11218   implement:
11219   \li \ref selectTest
11220   \li \ref draw
11221   \li \ref drawLegendIcon
11222   \li \ref getKeyRange
11223   \li \ref getValueRange
11224   
11225   See the documentation of those functions for what they need to do.
11226   
11227   For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
11228   coordinates to pixel coordinates. This function is quite convenient, because it takes the
11229   orientation of the key and value axes into account for you (x and y are swapped when the key axis
11230   is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
11231   to translate many points in a loop like QCPGraph), you can directly use \ref
11232   QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
11233   yourself.
11234   
11235   Here are some important members you inherit from QCPAbstractPlottable:
11236   <table>
11237   <tr>
11238     <td>QCustomPlot *\b mParentPlot</td>
11239     <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
11240   </tr><tr>
11241     <td>QString \b mName</td>
11242     <td>The name of the plottable.</td>
11243   </tr><tr>
11244     <td>QPen \b mPen</td>
11245     <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
11246         (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
11247   </tr><tr>
11248     <td>QBrush \b mBrush</td>
11249     <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
11250         (e.g. QCPGraph uses this brush to control filling under the graph)</td>
11251   </tr><tr>
11252     <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
11253     <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
11254         to pixels in either the key or value dimension. Make sure to check whether the pointer is \c nullptr before using it. If one of
11255         the axes is null, don't draw the plottable.</td>
11256   </tr><tr>
11257     <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
11258     <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
11259         When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
11260         Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
11261   </tr><tr>
11262     <td>\ref QCP::SelectionType \b mSelectable</td>
11263     <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
11264         by QCPAbstractPlottable automatically.</td>
11265   </tr><tr>
11266     <td>\ref QCPDataSelection \b mSelection</td>
11267     <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
11268   </tr>
11269   </table>
11270 */
11271 
11272 /* start of documentation of inline functions */
11273 
11274 /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
11275   
11276   Provides access to the selection decorator of this plottable. The selection decorator controls
11277   how selected data ranges are drawn (e.g. their pen color and fill), see \ref
11278   QCPSelectionDecorator for details.
11279   
11280   If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
11281   setSelectionDecorator.
11282 */
11283 
11284 /*! \fn bool QCPAbstractPlottable::selected() const
11285   
11286   Returns true if there are any data points of the plottable currently selected. Use \ref selection
11287   to retrieve the current \ref QCPDataSelection.
11288 */
11289 
11290 /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
11291   
11292   Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
11293   this plottable.
11294   
11295   \see selected, setSelection, setSelectable
11296 */
11297 
11298 /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
11299   
11300   If this plottable is a one-dimensional plottable, i.e. it implements the \ref
11301   QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
11302   of a \ref QCPColorMap) returns zero.
11303   
11304   You can use this method to gain read access to data coordinates while holding a pointer to the
11305   abstract base class only.
11306 */
11307 
11308 /* end of documentation of inline functions */
11309 /* start of documentation of pure virtual functions */
11310 
11311 /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
11312   \internal
11313   
11314   called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
11315   of this plottable inside \a rect, next to the plottable name.
11316   
11317   The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
11318   appear outside the legend icon border.
11319 */
11320 
11321 /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
11322   
11323   Returns the coordinate range that all data in this plottable span in the key axis dimension. For
11324   logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
11325   QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
11326   negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
11327   will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
11328   QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
11329   be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
11330 
11331   Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
11332   this function may have size zero (e.g. when there is only one data point). In this case \a
11333   foundRange would return true, but the returned range is not a valid range in terms of \ref
11334   QCPRange::validRange.
11335   
11336   \see rescaleAxes, getValueRange
11337 */
11338 
11339 /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
11340   
11341   Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
11342   in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
11343   QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
11344   domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
11345   all positive points will be ignored for range calculation. For no restriction, just set \a
11346   inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
11347   whether a range could be found or not. If this is false, you shouldn't use the returned range
11348   (e.g. no points in data).
11349   
11350   If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
11351   all data points are considered, without any restriction on the keys.
11352 
11353   Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
11354   this function may have size zero (e.g. when there is only one data point). In this case \a
11355   foundRange would return true, but the returned range is not a valid range in terms of \ref
11356   QCPRange::validRange.
11357   
11358   \see rescaleAxes, getKeyRange
11359 */
11360 
11361 /* end of documentation of pure virtual functions */
11362 /* start of documentation of signals */
11363 
11364 /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
11365   
11366   This signal is emitted when the selection state of this plottable has changed, either by user
11367   interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
11368   there are any points selected or not.
11369   
11370   \see selectionChanged(const QCPDataSelection &selection)
11371 */
11372 
11373 /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
11374   
11375   This signal is emitted when the selection state of this plottable has changed, either by user
11376   interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
11377   currently selected data ranges.
11378   
11379   \see selectionChanged(bool selected)
11380 */
11381 
11382 /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
11383   
11384   This signal is emitted when the selectability of this plottable has changed.
11385   
11386   \see setSelectable
11387 */
11388 
11389 /* end of documentation of signals */
11390 
11391 /*!
11392   Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
11393   its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
11394   and have perpendicular orientations. If either of these restrictions is violated, a corresponding
11395   message is printed to the debug output (qDebug), the construction is not aborted, though.
11396   
11397   Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
11398   it can't be directly instantiated.
11399   
11400   You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
11401 */
11402 QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
11403   QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
11404   mName(),
11405   mAntialiasedFill(true),
11406   mAntialiasedScatters(true),
11407   mPen(Qt::black),
11408   mBrush(Qt::NoBrush),
11409   mKeyAxis(keyAxis),
11410   mValueAxis(valueAxis),
11411   mSelectable(QCP::stWhole),
11412   mSelectionDecorator(nullptr)
11413 {
11414   if (keyAxis->parentPlot() != valueAxis->parentPlot())
11415     qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
11416   if (keyAxis->orientation() == valueAxis->orientation())
11417     qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
11418   
11419   mParentPlot->registerPlottable(this);
11420   setSelectionDecorator(new QCPSelectionDecorator);
11421 }
11422 
11423 QCPAbstractPlottable::~QCPAbstractPlottable()
11424 {
11425   if (mSelectionDecorator)
11426   {
11427     delete mSelectionDecorator;
11428     mSelectionDecorator = nullptr;
11429   }
11430 }
11431 
11432 /*!
11433    The name is the textual representation of this plottable as it is displayed in the legend
11434    (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
11435 */
11436 void QCPAbstractPlottable::setName(const QString &name)
11437 {
11438   mName = name;
11439 }
11440 
11441 /*!
11442   Sets whether fills of this plottable are drawn antialiased or not.
11443   
11444   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
11445   QCustomPlot::setNotAntialiasedElements.
11446 */
11447 void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
11448 {
11449   mAntialiasedFill = enabled;
11450 }
11451 
11452 /*!
11453   Sets whether the scatter symbols of this plottable are drawn antialiased or not.
11454   
11455   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
11456   QCustomPlot::setNotAntialiasedElements.
11457 */
11458 void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
11459 {
11460   mAntialiasedScatters = enabled;
11461 }
11462 
11463 /*!
11464   The pen is used to draw basic lines that make up the plottable representation in the
11465   plot.
11466   
11467   For example, the \ref QCPGraph subclass draws its graph lines with this pen.
11468 
11469   \see setBrush
11470 */
11471 void QCPAbstractPlottable::setPen(const QPen &pen)
11472 {
11473   mPen = pen;
11474 }
11475 
11476 /*!
11477   The brush is used to draw basic fills of the plottable representation in the
11478   plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
11479   
11480   For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
11481   it's not set to Qt::NoBrush.
11482 
11483   \see setPen
11484 */
11485 void QCPAbstractPlottable::setBrush(const QBrush &brush)
11486 {
11487   mBrush = brush;
11488 }
11489 
11490 /*!
11491   The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
11492   to the plottable's value axis. This function performs no checks to make sure this is the case.
11493   The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
11494   y-axis (QCustomPlot::yAxis) as value axis.
11495   
11496   Normally, the key and value axes are set in the constructor of the plottable (or \ref
11497   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
11498 
11499   \see setValueAxis
11500 */
11501 void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
11502 {
11503   mKeyAxis = axis;
11504 }
11505 
11506 /*!
11507   The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
11508   orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
11509   case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
11510   the y-axis (QCustomPlot::yAxis) as value axis.
11511 
11512   Normally, the key and value axes are set in the constructor of the plottable (or \ref
11513   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
11514   
11515   \see setKeyAxis
11516 */
11517 void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
11518 {
11519   mValueAxis = axis;
11520 }
11521 
11522 
11523 /*!
11524   Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
11525   (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
11526   selectionDecorator).
11527   
11528   The entire selection mechanism for plottables is handled automatically when \ref
11529   QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
11530   you wish to change the selection state programmatically.
11531   
11532   Using \ref setSelectable you can further specify for each plottable whether and to which
11533   granularity it is selectable. If \a selection is not compatible with the current \ref
11534   QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
11535   accordingly (see \ref QCPDataSelection::enforceType).
11536   
11537   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
11538   
11539   \see setSelectable, selectTest
11540 */
11541 void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
11542 {
11543   selection.enforceType(mSelectable);
11544   if (mSelection != selection)
11545   {
11546     mSelection = selection;
11547     emit selectionChanged(selected());
11548     emit selectionChanged(mSelection);
11549   }
11550 }
11551 
11552 /*!
11553   Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
11554   customize the visual representation of selected data ranges further than by using the default
11555   QCPSelectionDecorator.
11556   
11557   The plottable takes ownership of the \a decorator.
11558   
11559   The currently set decorator can be accessed via \ref selectionDecorator.
11560 */
11561 void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
11562 {
11563   if (decorator)
11564   {
11565     if (decorator->registerWithPlottable(this))
11566     {
11567       delete mSelectionDecorator; // delete old decorator if necessary
11568       mSelectionDecorator = decorator;
11569     }
11570   } else if (mSelectionDecorator) // just clear decorator
11571   {
11572     delete mSelectionDecorator;
11573     mSelectionDecorator = nullptr;
11574   }
11575 }
11576 
11577 /*!
11578   Sets whether and to which granularity this plottable can be selected.
11579 
11580   A selection can happen by clicking on the QCustomPlot surface (When \ref
11581   QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
11582   (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
11583   calling \ref setSelection.
11584   
11585   \see setSelection, QCP::SelectionType
11586 */
11587 void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
11588 {
11589   if (mSelectable != selectable)
11590   {
11591     mSelectable = selectable;
11592     QCPDataSelection oldSelection = mSelection;
11593     mSelection.enforceType(mSelectable);
11594     emit selectableChanged(mSelectable);
11595     if (mSelection != oldSelection)
11596     {
11597       emit selectionChanged(selected());
11598       emit selectionChanged(mSelection);
11599     }
11600   }
11601 }
11602 
11603 
11604 /*!
11605   Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
11606   taking the orientations of the axes associated with this plottable into account (e.g. whether key
11607   represents x or y).
11608 
11609   \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
11610 
11611   \see pixelsToCoords, QCPAxis::coordToPixel
11612 */
11613 void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
11614 {
11615   QCPAxis *keyAxis = mKeyAxis.data();
11616   QCPAxis *valueAxis = mValueAxis.data();
11617   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
11618   
11619   if (keyAxis->orientation() == Qt::Horizontal)
11620   {
11621     x = keyAxis->coordToPixel(key);
11622     y = valueAxis->coordToPixel(value);
11623   } else
11624   {
11625     y = keyAxis->coordToPixel(key);
11626     x = valueAxis->coordToPixel(value);
11627   }
11628 }
11629 
11630 /*! \overload
11631 
11632   Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
11633 */
11634 const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
11635 {
11636   QCPAxis *keyAxis = mKeyAxis.data();
11637   QCPAxis *valueAxis = mValueAxis.data();
11638   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
11639   
11640   if (keyAxis->orientation() == Qt::Horizontal)
11641     return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
11642   else
11643     return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
11644 }
11645 
11646 /*!
11647   Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
11648   taking the orientations of the axes associated with this plottable into account (e.g. whether key
11649   represents x or y).
11650 
11651   \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
11652 
11653   \see coordsToPixels, QCPAxis::coordToPixel
11654 */
11655 void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
11656 {
11657   QCPAxis *keyAxis = mKeyAxis.data();
11658   QCPAxis *valueAxis = mValueAxis.data();
11659   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
11660   
11661   if (keyAxis->orientation() == Qt::Horizontal)
11662   {
11663     key = keyAxis->pixelToCoord(x);
11664     value = valueAxis->pixelToCoord(y);
11665   } else
11666   {
11667     key = keyAxis->pixelToCoord(y);
11668     value = valueAxis->pixelToCoord(x);
11669   }
11670 }
11671 
11672 /*! \overload
11673 
11674   Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
11675 */
11676 void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
11677 {
11678   pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
11679 }
11680 
11681 /*!
11682   Rescales the key and value axes associated with this plottable to contain all displayed data, so
11683   the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
11684   sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
11685   Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
11686   outside of that domain.
11687   
11688   \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
11689   multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
11690   \a onlyEnlarge set to false (the default), and all subsequent set to true.
11691   
11692   \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
11693 */
11694 void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
11695 {
11696   rescaleKeyAxis(onlyEnlarge);
11697   rescaleValueAxis(onlyEnlarge);
11698 }
11699 
11700 /*!
11701   Rescales the key axis of the plottable so the whole plottable is visible.
11702   
11703   See \ref rescaleAxes for detailed behaviour.
11704 */
11705 void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
11706 {
11707   QCPAxis *keyAxis = mKeyAxis.data();
11708   if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
11709   
11710   QCP::SignDomain signDomain = QCP::sdBoth;
11711   if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
11712     signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
11713   
11714   bool foundRange;
11715   QCPRange newRange = getKeyRange(foundRange, signDomain);
11716   if (foundRange)
11717   {
11718     if (onlyEnlarge)
11719       newRange.expand(keyAxis->range());
11720     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
11721     {
11722       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
11723       if (keyAxis->scaleType() == QCPAxis::stLinear)
11724       {
11725         newRange.lower = center-keyAxis->range().size()/2.0;
11726         newRange.upper = center+keyAxis->range().size()/2.0;
11727       } else // scaleType() == stLogarithmic
11728       {
11729         newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
11730         newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
11731       }
11732     }
11733     keyAxis->setRange(newRange);
11734   }
11735 }
11736 
11737 /*!
11738   Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
11739   set to true, only the data points which are in the currently visible key axis range are
11740   considered.
11741 
11742   Returns true if the axis was actually scaled. This might not be the case if this plottable has an
11743   invalid range, e.g. because it has no data points.
11744 
11745   See \ref rescaleAxes for detailed behaviour.
11746 */
11747 void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
11748 {
11749   QCPAxis *keyAxis = mKeyAxis.data();
11750   QCPAxis *valueAxis = mValueAxis.data();
11751   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
11752   
11753   QCP::SignDomain signDomain = QCP::sdBoth;
11754   if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
11755     signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
11756   
11757   bool foundRange;
11758   QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
11759   if (foundRange)
11760   {
11761     if (onlyEnlarge)
11762       newRange.expand(valueAxis->range());
11763     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
11764     {
11765       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
11766       if (valueAxis->scaleType() == QCPAxis::stLinear)
11767       {
11768         newRange.lower = center-valueAxis->range().size()/2.0;
11769         newRange.upper = center+valueAxis->range().size()/2.0;
11770       } else // scaleType() == stLogarithmic
11771       {
11772         newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
11773         newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
11774       }
11775     }
11776     valueAxis->setRange(newRange);
11777   }
11778 }
11779 
11780 /*! \overload
11781 
11782   Adds this plottable to the specified \a legend.
11783 
11784   Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
11785   when the legend exists and a legend item associated with this plottable isn't already in the
11786   legend.
11787 
11788   If the plottable needs a more specialized representation in the legend, you can create a
11789   corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
11790   of calling this method.
11791 
11792   \see removeFromLegend, QCPLegend::addItem
11793 */
11794 bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
11795 {
11796   if (!legend)
11797   {
11798     qDebug() << Q_FUNC_INFO << "passed legend is null";
11799     return false;
11800   }
11801   if (legend->parentPlot() != mParentPlot)
11802   {
11803     qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
11804     return false;
11805   }
11806   
11807   if (!legend->hasItemWithPlottable(this))
11808   {
11809     legend->addItem(new QCPPlottableLegendItem(legend, this));
11810     return true;
11811   } else
11812     return false;
11813 }
11814 
11815 /*! \overload
11816 
11817   Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
11818 
11819   \see removeFromLegend
11820 */
11821 bool QCPAbstractPlottable::addToLegend()
11822 {
11823   if (!mParentPlot || !mParentPlot->legend)
11824     return false;
11825   else
11826     return addToLegend(mParentPlot->legend);
11827 }
11828 
11829 /*! \overload
11830 
11831   Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
11832   that is associated with this plottable is removed.
11833 
11834   Returns true on success, i.e. if the legend exists and a legend item associated with this
11835   plottable was found and removed.
11836 
11837   \see addToLegend, QCPLegend::removeItem
11838 */
11839 bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
11840 {
11841   if (!legend)
11842   {
11843     qDebug() << Q_FUNC_INFO << "passed legend is null";
11844     return false;
11845   }
11846   
11847   if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
11848     return legend->removeItem(lip);
11849   else
11850     return false;
11851 }
11852 
11853 /*! \overload
11854 
11855   Removes the plottable from the legend of the parent QCustomPlot.
11856 
11857   \see addToLegend
11858 */
11859 bool QCPAbstractPlottable::removeFromLegend() const
11860 {
11861   if (!mParentPlot || !mParentPlot->legend)
11862     return false;
11863   else
11864     return removeFromLegend(mParentPlot->legend);
11865 }
11866 
11867 /* inherits documentation from base class */
11868 QRect QCPAbstractPlottable::clipRect() const
11869 {
11870   if (mKeyAxis && mValueAxis)
11871     return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
11872   else
11873     return {};
11874 }
11875 
11876 /* inherits documentation from base class */
11877 QCP::Interaction QCPAbstractPlottable::selectionCategory() const
11878 {
11879   return QCP::iSelectPlottables;
11880 }
11881 
11882 /*! \internal
11883 
11884   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
11885   before drawing plottable lines.
11886 
11887   This is the antialiasing state the painter passed to the \ref draw method is in by default.
11888   
11889   This function takes into account the local setting of the antialiasing flag as well as the
11890   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
11891   QCustomPlot::setNotAntialiasedElements.
11892   
11893   \seebaseclassmethod
11894   
11895   \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
11896 */
11897 void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
11898 {
11899   applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
11900 }
11901 
11902 /*! \internal
11903 
11904   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
11905   before drawing plottable fills.
11906   
11907   This function takes into account the local setting of the antialiasing flag as well as the
11908   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
11909   QCustomPlot::setNotAntialiasedElements.
11910   
11911   \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
11912 */
11913 void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
11914 {
11915   applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
11916 }
11917 
11918 /*! \internal
11919 
11920   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
11921   before drawing plottable scatter points.
11922   
11923   This function takes into account the local setting of the antialiasing flag as well as the
11924   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
11925   QCustomPlot::setNotAntialiasedElements.
11926   
11927   \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
11928 */
11929 void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
11930 {
11931   applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
11932 }
11933 
11934 /* inherits documentation from base class */
11935 void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
11936 {
11937   Q_UNUSED(event)
11938   
11939   if (mSelectable != QCP::stNone)
11940   {
11941     QCPDataSelection newSelection = details.value<QCPDataSelection>();
11942     QCPDataSelection selectionBefore = mSelection;
11943     if (additive)
11944     {
11945       if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
11946       {
11947         if (selected())
11948           setSelection(QCPDataSelection());
11949         else
11950           setSelection(newSelection);
11951       } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
11952       {
11953         if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
11954           setSelection(mSelection-newSelection);
11955         else
11956           setSelection(mSelection+newSelection);
11957       }
11958     } else
11959       setSelection(newSelection);
11960     if (selectionStateChanged)
11961       *selectionStateChanged = mSelection != selectionBefore;
11962   }
11963 }
11964 
11965 /* inherits documentation from base class */
11966 void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
11967 {
11968   if (mSelectable != QCP::stNone)
11969   {
11970     QCPDataSelection selectionBefore = mSelection;
11971     setSelection(QCPDataSelection());
11972     if (selectionStateChanged)
11973       *selectionStateChanged = mSelection != selectionBefore;
11974   }
11975 }
11976 /* end of 'src/plottable.cpp' */
11977 
11978 
11979 /* including file 'src/item.cpp'            */
11980 /* modified 2021-03-29T02:30:44, size 49486 */
11981 
11982 ////////////////////////////////////////////////////////////////////////////////////////////////////
11983 //////////////////// QCPItemAnchor
11984 ////////////////////////////////////////////////////////////////////////////////////////////////////
11985 
11986 /*! \class QCPItemAnchor
11987   \brief An anchor of an item to which positions can be attached to.
11988   
11989   An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
11990   control anything on its item, but provides a way to tie other items via their positions to the
11991   anchor.
11992 
11993   For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
11994   Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
11995   attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
11996   calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
11997   QCPItemRect. This way the start of the line will now always follow the respective anchor location
11998   on the rect item.
11999   
12000   Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
12001   anchor to other positions.
12002   
12003   To learn how to provide anchors in your own item subclasses, see the subclassing section of the
12004   QCPAbstractItem documentation.
12005 */
12006 
12007 /* start documentation of inline functions */
12008 
12009 /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
12010   
12011   Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
12012   QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
12013   
12014   This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
12015   dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
12016   gcc compiler).
12017 */
12018 
12019 /* end documentation of inline functions */
12020 
12021 /*!
12022   Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
12023   you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
12024   explained in the subclassing section of the QCPAbstractItem documentation.
12025 */
12026 QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
12027   mName(name),
12028   mParentPlot(parentPlot),
12029   mParentItem(parentItem),
12030   mAnchorId(anchorId)
12031 {
12032 }
12033 
12034 QCPItemAnchor::~QCPItemAnchor()
12035 {
12036   // unregister as parent at children:
12037   foreach (QCPItemPosition *child, mChildrenX.values())
12038   {
12039     if (child->parentAnchorX() == this)
12040       child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
12041   }
12042   foreach (QCPItemPosition *child, mChildrenY.values())
12043   {
12044     if (child->parentAnchorY() == this)
12045       child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
12046   }
12047 }
12048 
12049 /*!
12050   Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
12051   
12052   The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
12053   parent item, QCPItemAnchor is just an intermediary.
12054 */
12055 QPointF QCPItemAnchor::pixelPosition() const
12056 {
12057   if (mParentItem)
12058   {
12059     if (mAnchorId > -1)
12060     {
12061       return mParentItem->anchorPixelPosition(mAnchorId);
12062     } else
12063     {
12064       qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
12065       return {};
12066     }
12067   } else
12068   {
12069     qDebug() << Q_FUNC_INFO << "no parent item set";
12070     return {};
12071   }
12072 }
12073 
12074 /*! \internal
12075 
12076   Adds \a pos to the childX list of this anchor, which keeps track of which children use this
12077   anchor as parent anchor for the respective coordinate. This is necessary to notify the children
12078   prior to destruction of the anchor.
12079   
12080   Note that this function does not change the parent setting in \a pos.
12081 */
12082 void QCPItemAnchor::addChildX(QCPItemPosition *pos)
12083 {
12084   if (!mChildrenX.contains(pos))
12085     mChildrenX.insert(pos);
12086   else
12087     qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
12088 }
12089 
12090 /*! \internal
12091 
12092   Removes \a pos from the childX list of this anchor.
12093   
12094   Note that this function does not change the parent setting in \a pos.
12095 */
12096 void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
12097 {
12098   if (!mChildrenX.remove(pos))
12099     qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
12100 }
12101 
12102 /*! \internal
12103 
12104   Adds \a pos to the childY list of this anchor, which keeps track of which children use this
12105   anchor as parent anchor for the respective coordinate. This is necessary to notify the children
12106   prior to destruction of the anchor.
12107   
12108   Note that this function does not change the parent setting in \a pos.
12109 */
12110 void QCPItemAnchor::addChildY(QCPItemPosition *pos)
12111 {
12112   if (!mChildrenY.contains(pos))
12113     mChildrenY.insert(pos);
12114   else
12115     qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
12116 }
12117 
12118 /*! \internal
12119 
12120   Removes \a pos from the childY list of this anchor.
12121   
12122   Note that this function does not change the parent setting in \a pos.
12123 */
12124 void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
12125 {
12126   if (!mChildrenY.remove(pos))
12127     qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
12128 }
12129 
12130 
12131 ////////////////////////////////////////////////////////////////////////////////////////////////////
12132 //////////////////// QCPItemPosition
12133 ////////////////////////////////////////////////////////////////////////////////////////////////////
12134 
12135 /*! \class QCPItemPosition
12136   \brief Manages the position of an item.
12137   
12138   Every item has at least one public QCPItemPosition member pointer which provides ways to position the
12139   item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
12140   \a topLeft and \a bottomRight.
12141 
12142   QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
12143   defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
12144   coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
12145   the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
12146   possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
12147   setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
12148   top in the Y direction, while following a plot coordinate in the X direction.
12149 
12150   A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
12151   multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
12152   are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
12153   means directly ontop of the parent anchor. For example, You could attach the \a start position of
12154   a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
12155   always be centered under the text label, no matter where the text is moved to. For more advanced
12156   plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
12157   \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
12158   direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
12159   in Y.
12160 
12161   Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
12162   anchor for other positions.
12163 
12164   To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
12165   works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
12166   setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
12167   pixel values.
12168 */
12169 
12170 /* start documentation of inline functions */
12171 
12172 /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
12173   
12174   Returns the current position type.
12175   
12176   If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
12177   type of the X coordinate. In that case rather use \a typeX() and \a typeY().
12178   
12179   \see setType
12180 */
12181 
12182 /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
12183   
12184   Returns the current parent anchor.
12185   
12186   If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
12187   this method returns the parent anchor of the Y coordinate. In that case rather use \a
12188   parentAnchorX() and \a parentAnchorY().
12189   
12190   \see setParentAnchor
12191 */
12192 
12193 /* end documentation of inline functions */
12194 
12195 /*!
12196   Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
12197   you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
12198   explained in the subclassing section of the QCPAbstractItem documentation.
12199 */
12200 QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
12201   QCPItemAnchor(parentPlot, parentItem, name),
12202   mPositionTypeX(ptAbsolute),
12203   mPositionTypeY(ptAbsolute),
12204   mKey(0),
12205   mValue(0),
12206   mParentAnchorX(nullptr),
12207   mParentAnchorY(nullptr)
12208 {
12209 }
12210 
12211 QCPItemPosition::~QCPItemPosition()
12212 {
12213   // unregister as parent at children:
12214   // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
12215   //       the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
12216   foreach (QCPItemPosition *child, mChildrenX.values())
12217   {
12218     if (child->parentAnchorX() == this)
12219       child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
12220   }
12221   foreach (QCPItemPosition *child, mChildrenY.values())
12222   {
12223     if (child->parentAnchorY() == this)
12224       child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
12225   }
12226   // unregister as child in parent:
12227   if (mParentAnchorX)
12228     mParentAnchorX->removeChildX(this);
12229   if (mParentAnchorY)
12230     mParentAnchorY->removeChildY(this);
12231 }
12232 
12233 /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
12234 QCPAxisRect *QCPItemPosition::axisRect() const
12235 {
12236   return mAxisRect.data();
12237 }
12238 
12239 /*!
12240   Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
12241   should be handled and how the QCPItemPosition should behave in the plot.
12242   
12243   The possible values for \a type can be separated in two main categories:
12244 
12245   \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
12246   and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
12247   By default, the QCustomPlot's x- and yAxis are used.
12248   
12249   \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
12250   corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
12251   ptAxisRectRatio. They differ only in the way the absolute position is described, see the
12252   documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
12253   the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
12254   
12255   Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
12256   has no parent anchor (\ref setParentAnchor).
12257   
12258   If the type is changed, the apparent pixel position on the plot is preserved. This means
12259   the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
12260   
12261   This method sets the type for both X and Y directions. It is also possible to set different types
12262   for X and Y, see \ref setTypeX, \ref setTypeY.
12263 */
12264 void QCPItemPosition::setType(QCPItemPosition::PositionType type)
12265 {
12266   setTypeX(type);
12267   setTypeY(type);
12268 }
12269 
12270 /*!
12271   This method sets the position type of the X coordinate to \a type.
12272   
12273   For a detailed description of what a position type is, see the documentation of \ref setType.
12274   
12275   \see setType, setTypeY
12276 */
12277 void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
12278 {
12279   if (mPositionTypeX != type)
12280   {
12281     // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
12282     // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
12283     bool retainPixelPosition = true;
12284     if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
12285       retainPixelPosition = false;
12286     if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
12287       retainPixelPosition = false;
12288     
12289     QPointF pixel;
12290     if (retainPixelPosition)
12291       pixel = pixelPosition();
12292     
12293     mPositionTypeX = type;
12294     
12295     if (retainPixelPosition)
12296       setPixelPosition(pixel);
12297   }
12298 }
12299 
12300 /*!
12301   This method sets the position type of the Y coordinate to \a type.
12302   
12303   For a detailed description of what a position type is, see the documentation of \ref setType.
12304   
12305   \see setType, setTypeX
12306 */
12307 void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
12308 {
12309   if (mPositionTypeY != type)
12310   {
12311     // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
12312     // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
12313     bool retainPixelPosition = true;
12314     if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
12315       retainPixelPosition = false;
12316     if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
12317       retainPixelPosition = false;
12318     
12319     QPointF pixel;
12320     if (retainPixelPosition)
12321       pixel = pixelPosition();
12322     
12323     mPositionTypeY = type;
12324     
12325     if (retainPixelPosition)
12326       setPixelPosition(pixel);
12327   }
12328 }
12329 
12330 /*!
12331   Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
12332   follow any position changes of the anchor. The local coordinate system of positions with a parent
12333   anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
12334   the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
12335   
12336   if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
12337   during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
12338   will be exactly on top of the parent anchor.
12339   
12340   To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
12341   
12342   If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
12343   set to \ref ptAbsolute, to keep the position in a valid state.
12344   
12345   This method sets the parent anchor for both X and Y directions. It is also possible to set
12346   different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
12347 */
12348 bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
12349 {
12350   bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
12351   bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
12352   return successX && successY;
12353 }
12354 
12355 /*!
12356   This method sets the parent anchor of the X coordinate to \a parentAnchor.
12357   
12358   For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
12359   
12360   \see setParentAnchor, setParentAnchorY
12361 */
12362 bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
12363 {
12364   // make sure self is not assigned as parent:
12365   if (parentAnchor == this)
12366   {
12367     qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
12368     return false;
12369   }
12370   // make sure no recursive parent-child-relationships are created:
12371   QCPItemAnchor *currentParent = parentAnchor;
12372   while (currentParent)
12373   {
12374     if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
12375     {
12376       // is a QCPItemPosition, might have further parent, so keep iterating
12377       if (currentParentPos == this)
12378       {
12379         qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
12380         return false;
12381       }
12382       currentParent = currentParentPos->parentAnchorX();
12383     } else
12384     {
12385       // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
12386       // same, to prevent a position being child of an anchor which itself depends on the position,
12387       // because they're both on the same item:
12388       if (currentParent->mParentItem == mParentItem)
12389       {
12390         qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
12391         return false;
12392       }
12393       break;
12394     }
12395   }
12396   
12397   // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
12398   if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
12399     setTypeX(ptAbsolute);
12400   
12401   // save pixel position:
12402   QPointF pixelP;
12403   if (keepPixelPosition)
12404     pixelP = pixelPosition();
12405   // unregister at current parent anchor:
12406   if (mParentAnchorX)
12407     mParentAnchorX->removeChildX(this);
12408   // register at new parent anchor:
12409   if (parentAnchor)
12410     parentAnchor->addChildX(this);
12411   mParentAnchorX = parentAnchor;
12412   // restore pixel position under new parent:
12413   if (keepPixelPosition)
12414     setPixelPosition(pixelP);
12415   else
12416     setCoords(0, coords().y());
12417   return true;
12418 }
12419 
12420 /*!
12421   This method sets the parent anchor of the Y coordinate to \a parentAnchor.
12422   
12423   For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
12424   
12425   \see setParentAnchor, setParentAnchorX
12426 */
12427 bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
12428 {
12429   // make sure self is not assigned as parent:
12430   if (parentAnchor == this)
12431   {
12432     qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
12433     return false;
12434   }
12435   // make sure no recursive parent-child-relationships are created:
12436   QCPItemAnchor *currentParent = parentAnchor;
12437   while (currentParent)
12438   {
12439     if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
12440     {
12441       // is a QCPItemPosition, might have further parent, so keep iterating
12442       if (currentParentPos == this)
12443       {
12444         qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
12445         return false;
12446       }
12447       currentParent = currentParentPos->parentAnchorY();
12448     } else
12449     {
12450       // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
12451       // same, to prevent a position being child of an anchor which itself depends on the position,
12452       // because they're both on the same item:
12453       if (currentParent->mParentItem == mParentItem)
12454       {
12455         qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
12456         return false;
12457       }
12458       break;
12459     }
12460   }
12461   
12462   // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
12463   if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
12464     setTypeY(ptAbsolute);
12465   
12466   // save pixel position:
12467   QPointF pixelP;
12468   if (keepPixelPosition)
12469     pixelP = pixelPosition();
12470   // unregister at current parent anchor:
12471   if (mParentAnchorY)
12472     mParentAnchorY->removeChildY(this);
12473   // register at new parent anchor:
12474   if (parentAnchor)
12475     parentAnchor->addChildY(this);
12476   mParentAnchorY = parentAnchor;
12477   // restore pixel position under new parent:
12478   if (keepPixelPosition)
12479     setPixelPosition(pixelP);
12480   else
12481     setCoords(coords().x(), 0);
12482   return true;
12483 }
12484 
12485 /*!
12486   Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
12487   (\ref setType, \ref setTypeX, \ref setTypeY).
12488   
12489   For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
12490   on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
12491   QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
12492   plot coordinate system defined by the axes set by \ref setAxes. By default those are the
12493   QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
12494   coordinate types and their meaning.
12495   
12496   If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
12497   value must also be provided in the different coordinate systems. Here, the X type refers to \a
12498   key, and the Y type refers to \a value.
12499 
12500   \see setPixelPosition
12501 */
12502 void QCPItemPosition::setCoords(double key, double value)
12503 {
12504   mKey = key;
12505   mValue = value;
12506 }
12507 
12508 /*! \overload
12509 
12510   Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
12511   meaning of \a value of the \ref setCoords(double key, double value) method.
12512 */
12513 void QCPItemPosition::setCoords(const QPointF &pos)
12514 {
12515   setCoords(pos.x(), pos.y());
12516 }
12517 
12518 /*!
12519   Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
12520   includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
12521 
12522   \see setPixelPosition
12523 */
12524 QPointF QCPItemPosition::pixelPosition() const
12525 {
12526   QPointF result;
12527   
12528   // determine X:
12529   switch (mPositionTypeX)
12530   {
12531     case ptAbsolute:
12532     {
12533       result.rx() = mKey;
12534       if (mParentAnchorX)
12535         result.rx() += mParentAnchorX->pixelPosition().x();
12536       break;
12537     }
12538     case ptViewportRatio:
12539     {
12540       result.rx() = mKey*mParentPlot->viewport().width();
12541       if (mParentAnchorX)
12542         result.rx() += mParentAnchorX->pixelPosition().x();
12543       else
12544         result.rx() += mParentPlot->viewport().left();
12545       break;
12546     }
12547     case ptAxisRectRatio:
12548     {
12549       if (mAxisRect)
12550       {
12551         result.rx() = mKey*mAxisRect.data()->width();
12552         if (mParentAnchorX)
12553           result.rx() += mParentAnchorX->pixelPosition().x();
12554         else
12555           result.rx() += mAxisRect.data()->left();
12556       } else
12557         qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
12558       break;
12559     }
12560     case ptPlotCoords:
12561     {
12562       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
12563         result.rx() = mKeyAxis.data()->coordToPixel(mKey);
12564       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
12565         result.rx() = mValueAxis.data()->coordToPixel(mValue);
12566       else
12567         qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
12568       break;
12569     }
12570   }
12571   
12572   // determine Y:
12573   switch (mPositionTypeY)
12574   {
12575     case ptAbsolute:
12576     {
12577       result.ry() = mValue;
12578       if (mParentAnchorY)
12579         result.ry() += mParentAnchorY->pixelPosition().y();
12580       break;
12581     }
12582     case ptViewportRatio:
12583     {
12584       result.ry() = mValue*mParentPlot->viewport().height();
12585       if (mParentAnchorY)
12586         result.ry() += mParentAnchorY->pixelPosition().y();
12587       else
12588         result.ry() += mParentPlot->viewport().top();
12589       break;
12590     }
12591     case ptAxisRectRatio:
12592     {
12593       if (mAxisRect)
12594       {
12595         result.ry() = mValue*mAxisRect.data()->height();
12596         if (mParentAnchorY)
12597           result.ry() += mParentAnchorY->pixelPosition().y();
12598         else
12599           result.ry() += mAxisRect.data()->top();
12600       } else
12601         qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
12602       break;
12603     }
12604     case ptPlotCoords:
12605     {
12606       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
12607         result.ry() = mKeyAxis.data()->coordToPixel(mKey);
12608       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
12609         result.ry() = mValueAxis.data()->coordToPixel(mValue);
12610       else
12611         qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
12612       break;
12613     }
12614   }
12615   
12616   return result;
12617 }
12618 
12619 /*!
12620   When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
12621   coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
12622   yAxis of the QCustomPlot.
12623 */
12624 void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
12625 {
12626   mKeyAxis = keyAxis;
12627   mValueAxis = valueAxis;
12628 }
12629 
12630 /*!
12631   When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
12632   coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
12633   the QCustomPlot.
12634 */
12635 void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
12636 {
12637   mAxisRect = axisRect;
12638 }
12639 
12640 /*!
12641   Sets the apparent pixel position. This works no matter what type (\ref setType) this
12642   QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
12643   appropriately, to make the position finally appear at the specified pixel values.
12644 
12645   Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
12646   identical to that of \ref setCoords.
12647 
12648   \see pixelPosition, setCoords
12649 */
12650 void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
12651 {
12652   double x = pixelPosition.x();
12653   double y = pixelPosition.y();
12654   
12655   switch (mPositionTypeX)
12656   {
12657     case ptAbsolute:
12658     {
12659       if (mParentAnchorX)
12660         x -= mParentAnchorX->pixelPosition().x();
12661       break;
12662     }
12663     case ptViewportRatio:
12664     {
12665       if (mParentAnchorX)
12666         x -= mParentAnchorX->pixelPosition().x();
12667       else
12668         x -= mParentPlot->viewport().left();
12669       x /= double(mParentPlot->viewport().width());
12670       break;
12671     }
12672     case ptAxisRectRatio:
12673     {
12674       if (mAxisRect)
12675       {
12676         if (mParentAnchorX)
12677           x -= mParentAnchorX->pixelPosition().x();
12678         else
12679           x -= mAxisRect.data()->left();
12680         x /= double(mAxisRect.data()->width());
12681       } else
12682         qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
12683       break;
12684     }
12685     case ptPlotCoords:
12686     {
12687       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
12688         x = mKeyAxis.data()->pixelToCoord(x);
12689       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
12690         y = mValueAxis.data()->pixelToCoord(x);
12691       else
12692         qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
12693       break;
12694     }
12695   }
12696   
12697   switch (mPositionTypeY)
12698   {
12699     case ptAbsolute:
12700     {
12701       if (mParentAnchorY)
12702         y -= mParentAnchorY->pixelPosition().y();
12703       break;
12704     }
12705     case ptViewportRatio:
12706     {
12707       if (mParentAnchorY)
12708         y -= mParentAnchorY->pixelPosition().y();
12709       else
12710         y -= mParentPlot->viewport().top();
12711       y /= double(mParentPlot->viewport().height());
12712       break;
12713     }
12714     case ptAxisRectRatio:
12715     {
12716       if (mAxisRect)
12717       {
12718         if (mParentAnchorY)
12719           y -= mParentAnchorY->pixelPosition().y();
12720         else
12721           y -= mAxisRect.data()->top();
12722         y /= double(mAxisRect.data()->height());
12723       } else
12724         qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
12725       break;
12726     }
12727     case ptPlotCoords:
12728     {
12729       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
12730         x = mKeyAxis.data()->pixelToCoord(y);
12731       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
12732         y = mValueAxis.data()->pixelToCoord(y);
12733       else
12734         qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
12735       break;
12736     }
12737   }
12738   
12739   setCoords(x, y);
12740 }
12741 
12742 
12743 ////////////////////////////////////////////////////////////////////////////////////////////////////
12744 //////////////////// QCPAbstractItem
12745 ////////////////////////////////////////////////////////////////////////////////////////////////////
12746 
12747 /*! \class QCPAbstractItem
12748   \brief The abstract base class for all items in a plot.
12749   
12750   In QCustomPlot, items are supplemental graphical elements that are neither plottables
12751   (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
12752   plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
12753   specific item has at least one QCPItemPosition member which controls the positioning. Some items
12754   are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
12755   example, QCPItemRect has \a topLeft and \a bottomRight).
12756   
12757   This abstract base class defines a very basic interface like visibility and clipping. Since this
12758   class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
12759   yourself to create new items.
12760   
12761   The built-in items are:
12762   <table>
12763   <tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
12764   <tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
12765   <tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
12766   <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
12767   <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
12768   <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
12769   <tr><td>QCPItemText</td><td>A text label</td></tr>
12770   <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
12771   <tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
12772   </table>
12773   
12774   \section items-clipping Clipping
12775 
12776   Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
12777   To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
12778   "setClipToAxisRect(false)".
12779 
12780   On the other hand if you want the item to be clipped to a different axis rect, specify it via
12781   \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
12782   in principle is independent of the coordinate axes the item might be tied to via its position
12783   members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
12784   also contains the axes used for the item positions.
12785   
12786   \section items-using Using items
12787   
12788   First you instantiate the item you want to use and add it to the plot:
12789   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
12790   by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
12791   set the plot coordinates where the line should start/end:
12792   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
12793   If we don't want the line to be positioned in plot coordinates but a different coordinate system,
12794   e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
12795   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
12796   Then we can set the coordinates, this time in pixels:
12797   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
12798   and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
12799   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
12800   
12801   For more advanced plots, it is even possible to set different types and parent anchors per X/Y
12802   coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
12803   QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
12804   
12805   \section items-subclassing Creating own items
12806   
12807   To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
12808   virtual functions, you must implement:
12809   \li \ref selectTest
12810   \li \ref draw
12811   
12812   See the documentation of those functions for what they need to do.
12813   
12814   \subsection items-positioning Allowing the item to be positioned
12815   
12816   As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
12817   have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
12818   a public member of type QCPItemPosition like so:
12819   
12820   \code QCPItemPosition * const myPosition;\endcode
12821   
12822   the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
12823   instance it points to, can be modified, of course).
12824   The initialization of this pointer is made easy with the \ref createPosition function. Just assign
12825   the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
12826   takes a string which is the name of the position, typically this is identical to the variable name.
12827   For example, the constructor of QCPItemExample could look like this:
12828   
12829   \code
12830   QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
12831     QCPAbstractItem(parentPlot),
12832     myPosition(createPosition("myPosition"))
12833   {
12834     // other constructor code
12835   }
12836   \endcode
12837   
12838   \subsection items-drawing The draw function
12839   
12840   To give your item a visual representation, reimplement the \ref draw function and use the passed
12841   QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
12842   position member(s) via \ref QCPItemPosition::pixelPosition.
12843 
12844   To optimize performance you should calculate a bounding rect first (don't forget to take the pen
12845   width into account), check whether it intersects the \ref clipRect, and only draw the item at all
12846   if this is the case.
12847   
12848   \subsection items-selection The selectTest function
12849   
12850   Your implementation of the \ref selectTest function may use the helpers \ref
12851   QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
12852   selection test becomes significantly simpler for most items. See the documentation of \ref
12853   selectTest for what the function parameters mean and what the function should return.
12854   
12855   \subsection anchors Providing anchors
12856   
12857   Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
12858   member, e.g.
12859   
12860   \code QCPItemAnchor * const bottom;\endcode
12861 
12862   and create it in the constructor with the \ref createAnchor function, assigning it a name and an
12863   anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
12864   Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
12865   provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
12866   anchorId) function.
12867   
12868   In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
12869   position when anything attached to the anchor needs to know the coordinates.
12870 */
12871 
12872 /* start of documentation of inline functions */
12873 
12874 /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
12875   
12876   Returns all positions of the item in a list.
12877   
12878   \see anchors, position
12879 */
12880 
12881 /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
12882   
12883   Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
12884   also an anchor, the list will also contain the positions of this item.
12885   
12886   \see positions, anchor
12887 */
12888 
12889 /* end of documentation of inline functions */
12890 /* start documentation of pure virtual functions */
12891 
12892 /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
12893   \internal
12894   
12895   Draws this item with the provided \a painter.
12896   
12897   The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
12898   function is called. The clipRect depends on the clipping settings defined by \ref
12899   setClipToAxisRect and \ref setClipAxisRect.
12900 */
12901 
12902 /* end documentation of pure virtual functions */
12903 /* start documentation of signals */
12904 
12905 /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
12906   This signal is emitted when the selection state of this item has changed, either by user interaction
12907   or by a direct call to \ref setSelected.
12908 */
12909 
12910 /* end documentation of signals */
12911 
12912 /*!
12913   Base class constructor which initializes base class members.
12914 */
12915 QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
12916   QCPLayerable(parentPlot),
12917   mClipToAxisRect(false),
12918   mSelectable(true),
12919   mSelected(false)
12920 {
12921   parentPlot->registerItem(this);
12922   
12923   QList<QCPAxisRect*> rects = parentPlot->axisRects();
12924   if (!rects.isEmpty())
12925   {
12926     setClipToAxisRect(true);
12927     setClipAxisRect(rects.first());
12928   }
12929 }
12930 
12931 QCPAbstractItem::~QCPAbstractItem()
12932 {
12933   // don't delete mPositions because every position is also an anchor and thus in mAnchors
12934   qDeleteAll(mAnchors);
12935 }
12936 
12937 /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
12938 QCPAxisRect *QCPAbstractItem::clipAxisRect() const
12939 {
12940   return mClipAxisRect.data();
12941 }
12942 
12943 /*!
12944   Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
12945   entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
12946   
12947   \see setClipAxisRect
12948 */
12949 void QCPAbstractItem::setClipToAxisRect(bool clip)
12950 {
12951   mClipToAxisRect = clip;
12952   if (mClipToAxisRect)
12953     setParentLayerable(mClipAxisRect.data());
12954 }
12955 
12956 /*!
12957   Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
12958   setClipToAxisRect is set to true.
12959   
12960   \see setClipToAxisRect
12961 */
12962 void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
12963 {
12964   mClipAxisRect = rect;
12965   if (mClipToAxisRect)
12966     setParentLayerable(mClipAxisRect.data());
12967 }
12968 
12969 /*!
12970   Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
12971   (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
12972   
12973   However, even when \a selectable was set to false, it is possible to set the selection manually,
12974   by calling \ref setSelected.
12975   
12976   \see QCustomPlot::setInteractions, setSelected
12977 */
12978 void QCPAbstractItem::setSelectable(bool selectable)
12979 {
12980   if (mSelectable != selectable)
12981   {
12982     mSelectable = selectable;
12983     emit selectableChanged(mSelectable);
12984   }
12985 }
12986 
12987 /*!
12988   Sets whether this item is selected or not. When selected, it might use a different visual
12989   appearance (e.g. pen and brush), this depends on the specific item though.
12990 
12991   The entire selection mechanism for items is handled automatically when \ref
12992   QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
12993   function when you wish to change the selection state manually.
12994   
12995   This function can change the selection state even when \ref setSelectable was set to false.
12996   
12997   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
12998   
12999   \see setSelectable, selectTest
13000 */
13001 void QCPAbstractItem::setSelected(bool selected)
13002 {
13003   if (mSelected != selected)
13004   {
13005     mSelected = selected;
13006     emit selectionChanged(mSelected);
13007   }
13008 }
13009 
13010 /*!
13011   Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
13012   that name, returns \c nullptr.
13013   
13014   This function provides an alternative way to access item positions. Normally, you access
13015   positions direcly by their member pointers (which typically have the same variable name as \a
13016   name).
13017   
13018   \see positions, anchor
13019 */
13020 QCPItemPosition *QCPAbstractItem::position(const QString &name) const
13021 {
13022   foreach (QCPItemPosition *position, mPositions)
13023   {
13024     if (position->name() == name)
13025       return position;
13026   }
13027   qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
13028   return nullptr;
13029 }
13030 
13031 /*!
13032   Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
13033   that name, returns \c nullptr.
13034   
13035   This function provides an alternative way to access item anchors. Normally, you access
13036   anchors direcly by their member pointers (which typically have the same variable name as \a
13037   name).
13038   
13039   \see anchors, position
13040 */
13041 QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
13042 {
13043   foreach (QCPItemAnchor *anchor, mAnchors)
13044   {
13045     if (anchor->name() == name)
13046       return anchor;
13047   }
13048   qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
13049   return nullptr;
13050 }
13051 
13052 /*!
13053   Returns whether this item has an anchor with the specified \a name.
13054   
13055   Note that you can check for positions with this function, too. This is because every position is
13056   also an anchor (QCPItemPosition inherits from QCPItemAnchor).
13057   
13058   \see anchor, position
13059 */
13060 bool QCPAbstractItem::hasAnchor(const QString &name) const
13061 {
13062   foreach (QCPItemAnchor *anchor, mAnchors)
13063   {
13064     if (anchor->name() == name)
13065       return true;
13066   }
13067   return false;
13068 }
13069 
13070 /*! \internal
13071   
13072   Returns the rect the visual representation of this item is clipped to. This depends on the
13073   current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
13074   
13075   If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
13076   
13077   \see draw
13078 */
13079 QRect QCPAbstractItem::clipRect() const
13080 {
13081   if (mClipToAxisRect && mClipAxisRect)
13082     return mClipAxisRect.data()->rect();
13083   else
13084     return mParentPlot->viewport();
13085 }
13086 
13087 /*! \internal
13088 
13089   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
13090   before drawing item lines.
13091 
13092   This is the antialiasing state the painter passed to the \ref draw method is in by default.
13093   
13094   This function takes into account the local setting of the antialiasing flag as well as the
13095   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
13096   QCustomPlot::setNotAntialiasedElements.
13097   
13098   \see setAntialiased
13099 */
13100 void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
13101 {
13102   applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
13103 }
13104 
13105 /*! \internal
13106 
13107   A convenience function which returns the selectTest value for a specified \a rect and a specified
13108   click position \a pos. \a filledRect defines whether a click inside the rect should also be
13109   considered a hit or whether only the rect border is sensitive to hits.
13110   
13111   This function may be used to help with the implementation of the \ref selectTest function for
13112   specific items.
13113   
13114   For example, if your item consists of four rects, call this function four times, once for each
13115   rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
13116   returned values.
13117 */
13118 double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
13119 {
13120   double result = -1;
13121 
13122   // distance to border:
13123   const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
13124                                               << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
13125   const QCPVector2D posVec(pos);
13126   double minDistSqr = (std::numeric_limits<double>::max)();
13127   foreach (const QLineF &line, lines)
13128   {
13129     double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
13130     if (distSqr < minDistSqr)
13131       minDistSqr = distSqr;
13132   }
13133   result = qSqrt(minDistSqr);
13134   
13135   // filled rect, allow click inside to count as hit:
13136   if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
13137   {
13138     if (rect.contains(pos))
13139       result = mParentPlot->selectionTolerance()*0.99;
13140   }
13141   return result;
13142 }
13143 
13144 /*! \internal
13145 
13146   Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
13147   item subclasses if they want to provide anchors (QCPItemAnchor).
13148   
13149   For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
13150   ids and returns the respective pixel points of the specified anchor.
13151   
13152   \see createAnchor
13153 */
13154 QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
13155 {
13156   qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
13157   return {};
13158 }
13159 
13160 /*! \internal
13161 
13162   Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
13163   \a name must be a unique string that is usually identical to the variable name of the position
13164   member (This is needed to provide the name-based \ref position access to positions).
13165   
13166   Don't delete positions created by this function manually, as the item will take care of it.
13167   
13168   Use this function in the constructor (initialization list) of the specific item subclass to
13169   create each position member. Don't create QCPItemPositions with \b new yourself, because they
13170   won't be registered with the item properly.
13171   
13172   \see createAnchor
13173 */
13174 QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
13175 {
13176   if (hasAnchor(name))
13177     qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
13178   QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
13179   mPositions.append(newPosition);
13180   mAnchors.append(newPosition); // every position is also an anchor
13181   newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
13182   newPosition->setType(QCPItemPosition::ptPlotCoords);
13183   if (mParentPlot->axisRect())
13184     newPosition->setAxisRect(mParentPlot->axisRect());
13185   newPosition->setCoords(0, 0);
13186   return newPosition;
13187 }
13188 
13189 /*! \internal
13190 
13191   Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
13192   \a name must be a unique string that is usually identical to the variable name of the anchor
13193   member (This is needed to provide the name based \ref anchor access to anchors).
13194   
13195   The \a anchorId must be a number identifying the created anchor. It is recommended to create an
13196   enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
13197   to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
13198   the correct pixel coordinates for the passed anchor id.
13199   
13200   Don't delete anchors created by this function manually, as the item will take care of it.
13201   
13202   Use this function in the constructor (initialization list) of the specific item subclass to
13203   create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
13204   won't be registered with the item properly.
13205   
13206   \see createPosition
13207 */
13208 QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
13209 {
13210   if (hasAnchor(name))
13211     qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
13212   QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
13213   mAnchors.append(newAnchor);
13214   return newAnchor;
13215 }
13216 
13217 /* inherits documentation from base class */
13218 void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
13219 {
13220   Q_UNUSED(event)
13221   Q_UNUSED(details)
13222   if (mSelectable)
13223   {
13224     bool selBefore = mSelected;
13225     setSelected(additive ? !mSelected : true);
13226     if (selectionStateChanged)
13227       *selectionStateChanged = mSelected != selBefore;
13228   }
13229 }
13230 
13231 /* inherits documentation from base class */
13232 void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
13233 {
13234   if (mSelectable)
13235   {
13236     bool selBefore = mSelected;
13237     setSelected(false);
13238     if (selectionStateChanged)
13239       *selectionStateChanged = mSelected != selBefore;
13240   }
13241 }
13242 
13243 /* inherits documentation from base class */
13244 QCP::Interaction QCPAbstractItem::selectionCategory() const
13245 {
13246   return QCP::iSelectItems;
13247 }
13248 /* end of 'src/item.cpp' */
13249 
13250 
13251 /* including file 'src/core.cpp'             */
13252 /* modified 2021-03-29T02:30:44, size 127198 */
13253 
13254 ////////////////////////////////////////////////////////////////////////////////////////////////////
13255 //////////////////// QCustomPlot
13256 ////////////////////////////////////////////////////////////////////////////////////////////////////
13257 
13258 /*! \class QCustomPlot
13259   
13260   \brief The central class of the library. This is the QWidget which displays the plot and
13261   interacts with the user.
13262   
13263   For tutorials on how to use QCustomPlot, see the website\n
13264   http://www.qcustomplot.com/
13265 */
13266 
13267 /* start of documentation of inline functions */
13268 
13269 /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
13270   
13271   Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
13272   to handle and draw selection rect interactions (see \ref setSelectionRectMode).
13273   
13274   \see setSelectionRect
13275 */
13276 
13277 /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
13278   
13279   Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
13280   one cell with the main QCPAxisRect inside.
13281 */
13282 
13283 /* end of documentation of inline functions */
13284 /* start of documentation of signals */
13285 
13286 /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
13287 
13288   This signal is emitted when the QCustomPlot receives a mouse double click event.
13289 */
13290 
13291 /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
13292 
13293   This signal is emitted when the QCustomPlot receives a mouse press event.
13294   
13295   It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
13296   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
13297   QCPAxisRect::setRangeDragAxes.
13298 */
13299 
13300 /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
13301 
13302   This signal is emitted when the QCustomPlot receives a mouse move event.
13303   
13304   It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
13305   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
13306   QCPAxisRect::setRangeDragAxes.
13307   
13308   \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
13309   because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
13310   a meaning for the range drag axes that were set at that moment. If you want to change the drag
13311   axes, consider doing this in the \ref mousePress signal instead.
13312 */
13313 
13314 /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
13315 
13316   This signal is emitted when the QCustomPlot receives a mouse release event.
13317   
13318   It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
13319   slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
13320   \ref QCPAbstractPlottable::setSelectable.
13321 */
13322 
13323 /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
13324 
13325   This signal is emitted when the QCustomPlot receives a mouse wheel event.
13326   
13327   It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
13328   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
13329   QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
13330 */
13331 
13332 /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
13333 
13334   This signal is emitted when a plottable is clicked.
13335 
13336   \a event is the mouse event that caused the click and \a plottable is the plottable that received
13337   the click. The parameter \a dataIndex indicates the data point that was closest to the click
13338   position.
13339 
13340   \see plottableDoubleClick
13341 */
13342 
13343 /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
13344 
13345   This signal is emitted when a plottable is double clicked.
13346 
13347   \a event is the mouse event that caused the click and \a plottable is the plottable that received
13348   the click. The parameter \a dataIndex indicates the data point that was closest to the click
13349   position.
13350 
13351   \see plottableClick
13352 */
13353 
13354 /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
13355   
13356   This signal is emitted when an item is clicked.
13357 
13358   \a event is the mouse event that caused the click and \a item is the item that received the
13359   click.
13360   
13361   \see itemDoubleClick
13362 */
13363 
13364 /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
13365   
13366   This signal is emitted when an item is double clicked.
13367   
13368   \a event is the mouse event that caused the click and \a item is the item that received the
13369   click.
13370   
13371   \see itemClick
13372 */
13373 
13374 /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
13375   
13376   This signal is emitted when an axis is clicked.
13377   
13378   \a event is the mouse event that caused the click, \a axis is the axis that received the click and
13379   \a part indicates the part of the axis that was clicked.
13380   
13381   \see axisDoubleClick
13382 */
13383 
13384 /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
13385 
13386   This signal is emitted when an axis is double clicked.
13387   
13388   \a event is the mouse event that caused the click, \a axis is the axis that received the click and
13389   \a part indicates the part of the axis that was clicked.
13390   
13391   \see axisClick
13392 */
13393 
13394 /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
13395 
13396   This signal is emitted when a legend (item) is clicked.
13397   
13398   \a event is the mouse event that caused the click, \a legend is the legend that received the
13399   click and \a item is the legend item that received the click. If only the legend and no item is
13400   clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
13401   between two items.
13402   
13403   \see legendDoubleClick
13404 */
13405 
13406 /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend,  QCPAbstractLegendItem *item, QMouseEvent *event)
13407 
13408   This signal is emitted when a legend (item) is double clicked.
13409   
13410   \a event is the mouse event that caused the click, \a legend is the legend that received the
13411   click and \a item is the legend item that received the click. If only the legend and no item is
13412   clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
13413   between two items.
13414   
13415   \see legendClick
13416 */
13417 
13418 /*! \fn void QCustomPlot::selectionChangedByUser()
13419   
13420   This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
13421   clicking. It is not emitted when the selection state of an object has changed programmatically by
13422   a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
13423   deselectAll.
13424   
13425   In addition to this signal, selectable objects also provide individual signals, for example \ref
13426   QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
13427   are emitted even if the selection state is changed programmatically.
13428   
13429   See the documentation of \ref setInteractions for details about the selection mechanism.
13430   
13431   \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
13432 */
13433 
13434 /*! \fn void QCustomPlot::beforeReplot()
13435   
13436   This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
13437   replot).
13438   
13439   It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
13440   replot synchronously, it won't cause an infinite recursion.
13441   
13442   \see replot, afterReplot, afterLayout
13443 */
13444 
13445 /*! \fn void QCustomPlot::afterLayout()
13446 
13447   This signal is emitted immediately after the layout step has been completed, which occurs right
13448   before drawing the plot. This is typically during a call to \ref replot, and in such cases this
13449   signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
13450   signals however, this signal is also emitted during off-screen painting, such as when calling
13451   \ref toPixmap or \ref savePdf.
13452 
13453   The layout step queries all layouts and layout elements in the plot for their proposed size and
13454   arranges the objects accordingly as preparation for the subsequent drawing step. Through this
13455   signal, you have the opportunity to update certain things in your plot that depend crucially on
13456   the exact dimensions/positioning of layout elements such as axes and axis rects.
13457 
13458   \warning However, changing any parameters of this QCustomPlot instance which would normally
13459   affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
13460   a second run of the layout step. It will propagate directly to the draw step and may cause
13461   graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
13462 
13463   \see updateLayout, beforeReplot, afterReplot
13464 */
13465 
13466 /*! \fn void QCustomPlot::afterReplot()
13467   
13468   This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
13469   replot).
13470   
13471   It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
13472   replot synchronously, it won't cause an infinite recursion.
13473   
13474   \see replot, beforeReplot, afterLayout
13475 */
13476 
13477 /* end of documentation of signals */
13478 /* start of documentation of public members */
13479 
13480 /*! \var QCPAxis *QCustomPlot::xAxis
13481 
13482   A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
13483   
13484   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
13485   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
13486   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
13487   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
13488   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
13489   default legend is removed due to manipulation of the layout system (e.g. by removing the main
13490   axis rect), the corresponding pointers become \c nullptr.
13491   
13492   If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
13493   axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
13494   the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
13495   is added after the main legend was removed before.
13496 */
13497 
13498 /*! \var QCPAxis *QCustomPlot::yAxis
13499 
13500   A pointer to the primary y Axis (left) of the main axis rect of the plot.
13501   
13502   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
13503   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
13504   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
13505   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
13506   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
13507   default legend is removed due to manipulation of the layout system (e.g. by removing the main
13508   axis rect), the corresponding pointers become \c nullptr.
13509   
13510   If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
13511   axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
13512   the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
13513   is added after the main legend was removed before.
13514 */
13515 
13516 /*! \var QCPAxis *QCustomPlot::xAxis2
13517 
13518   A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
13519   invisible by default. Use QCPAxis::setVisible to change this (or use \ref
13520   QCPAxisRect::setupFullAxesBox).
13521   
13522   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
13523   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
13524   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
13525   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
13526   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
13527   default legend is removed due to manipulation of the layout system (e.g. by removing the main
13528   axis rect), the corresponding pointers become \c nullptr.
13529   
13530   If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
13531   axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
13532   the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
13533   is added after the main legend was removed before.
13534 */
13535 
13536 /*! \var QCPAxis *QCustomPlot::yAxis2
13537 
13538   A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
13539   invisible by default. Use QCPAxis::setVisible to change this (or use \ref
13540   QCPAxisRect::setupFullAxesBox).
13541   
13542   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
13543   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
13544   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
13545   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
13546   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
13547   default legend is removed due to manipulation of the layout system (e.g. by removing the main
13548   axis rect), the corresponding pointers become \c nullptr.
13549   
13550   If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
13551   axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
13552   the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
13553   is added after the main legend was removed before.
13554 */
13555 
13556 /*! \var QCPLegend *QCustomPlot::legend
13557 
13558   A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
13559   QCPLegend::setVisible to change this.
13560   
13561   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
13562   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
13563   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
13564   layout system\endlink to add multiple legends to the plot, use the layout system interface to
13565   access the new legend. For example, legends can be placed inside an axis rect's \ref
13566   QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
13567   the default legend is removed due to manipulation of the layout system (e.g. by removing the main
13568   axis rect), the corresponding pointer becomes \c nullptr.
13569   
13570   If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
13571   axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
13572   the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
13573   is added after the main legend was removed before.
13574 */
13575 
13576 /* end of documentation of public members */
13577 
13578 /*!
13579   Constructs a QCustomPlot and sets reasonable default values.
13580 */
13581 QCustomPlot::QCustomPlot(QWidget *parent) :
13582   QWidget(parent),
13583   xAxis(nullptr),
13584   yAxis(nullptr),
13585   xAxis2(nullptr),
13586   yAxis2(nullptr),
13587   legend(nullptr),
13588   mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
13589   mPlotLayout(nullptr),
13590   mAutoAddPlottableToLegend(true),
13591   mAntialiasedElements(QCP::aeNone),
13592   mNotAntialiasedElements(QCP::aeNone),
13593   mInteractions(QCP::iNone),
13594   mSelectionTolerance(8),
13595   mNoAntialiasingOnDrag(false),
13596   mBackgroundBrush(Qt::white, Qt::SolidPattern),
13597   mBackgroundScaled(true),
13598   mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
13599   mCurrentLayer(nullptr),
13600   mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
13601   mMultiSelectModifier(Qt::ControlModifier),
13602   mSelectionRectMode(QCP::srmNone),
13603   mSelectionRect(nullptr),
13604   mOpenGl(false),
13605   mMouseHasMoved(false),
13606   mMouseEventLayerable(nullptr),
13607   mMouseSignalLayerable(nullptr),
13608   mReplotting(false),
13609   mReplotQueued(false),
13610   mReplotTime(0),
13611   mReplotTimeAverage(0),
13612   mOpenGlMultisamples(16),
13613   mOpenGlAntialiasedElementsBackup(QCP::aeNone),
13614   mOpenGlCacheLabelsBackup(true)
13615 {
13616   setAttribute(Qt::WA_NoMousePropagation);
13617   setAttribute(Qt::WA_OpaquePaintEvent);
13618   setAttribute( Qt::WA_AcceptTouchEvents );
13619   grabGesture( Qt::PinchGesture );
13620   setFocusPolicy(Qt::ClickFocus);
13621   setMouseTracking(true);
13622   QLocale currentLocale = locale();
13623   currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
13624   setLocale(currentLocale);
13625 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
13626 #  ifdef QCP_DEVICEPIXELRATIO_FLOAT
13627   setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
13628 #  else
13629   setBufferDevicePixelRatio(QWidget::devicePixelRatio());
13630 #  endif
13631 #endif
13632   
13633   mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
13634   mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
13635   // create initial layers:
13636   mLayers.append(new QCPLayer(this, QLatin1String("background")));
13637   mLayers.append(new QCPLayer(this, QLatin1String("grid")));
13638   mLayers.append(new QCPLayer(this, QLatin1String("main")));
13639   mLayers.append(new QCPLayer(this, QLatin1String("axes")));
13640   mLayers.append(new QCPLayer(this, QLatin1String("legend")));
13641   mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
13642   updateLayerIndices();
13643   setCurrentLayer(QLatin1String("main"));
13644   layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
13645   
13646   // create initial layout, axis rect and legend:
13647   mPlotLayout = new QCPLayoutGrid;
13648   mPlotLayout->initializeParentPlot(this);
13649   mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
13650   mPlotLayout->setLayer(QLatin1String("main"));
13651   QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
13652   mPlotLayout->addElement(0, 0, defaultAxisRect);
13653   xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
13654   yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
13655   xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
13656   yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
13657   legend = new QCPLegend;
13658   legend->setVisible(false);
13659   defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
13660   defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
13661   
13662   defaultAxisRect->setLayer(QLatin1String("background"));
13663   xAxis->setLayer(QLatin1String("axes"));
13664   yAxis->setLayer(QLatin1String("axes"));
13665   xAxis2->setLayer(QLatin1String("axes"));
13666   yAxis2->setLayer(QLatin1String("axes"));
13667   xAxis->grid()->setLayer(QLatin1String("grid"));
13668   yAxis->grid()->setLayer(QLatin1String("grid"));
13669   xAxis2->grid()->setLayer(QLatin1String("grid"));
13670   yAxis2->grid()->setLayer(QLatin1String("grid"));
13671   legend->setLayer(QLatin1String("legend"));
13672   
13673   // create selection rect instance:
13674   mSelectionRect = new QCPSelectionRect(this);
13675   mSelectionRect->setLayer(QLatin1String("overlay"));
13676   
13677   setViewport(rect()); // needs to be called after mPlotLayout has been created
13678   
13679   replot(rpQueuedReplot);
13680 }
13681 
13682 QCustomPlot::~QCustomPlot()
13683 {
13684   clearPlottables();
13685   clearItems();
13686 
13687   if (mPlotLayout)
13688   {
13689     delete mPlotLayout;
13690     mPlotLayout = nullptr;
13691   }
13692   
13693   mCurrentLayer = nullptr;
13694   qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
13695   mLayers.clear();
13696 }
13697 
13698 /*!
13699   Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
13700   
13701   This overrides the antialiasing settings for whole element groups, normally controlled with the
13702   \a setAntialiasing function on the individual elements. If an element is neither specified in
13703   \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
13704   each individual element instance is used.
13705   
13706   For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
13707   drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
13708   to.
13709   
13710   if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
13711   removed from there.
13712   
13713   \see setNotAntialiasedElements
13714 */
13715 void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
13716 {
13717   mAntialiasedElements = antialiasedElements;
13718   
13719   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
13720   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
13721     mNotAntialiasedElements |= ~mAntialiasedElements;
13722 }
13723 
13724 /*!
13725   Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
13726   
13727   See \ref setAntialiasedElements for details.
13728   
13729   \see setNotAntialiasedElement
13730 */
13731 void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
13732 {
13733   if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
13734     mAntialiasedElements &= ~antialiasedElement;
13735   else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
13736     mAntialiasedElements |= antialiasedElement;
13737   
13738   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
13739   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
13740     mNotAntialiasedElements |= ~mAntialiasedElements;
13741 }
13742 
13743 /*!
13744   Sets which elements are forcibly drawn not antialiased as an \a or combination of
13745   QCP::AntialiasedElement.
13746   
13747   This overrides the antialiasing settings for whole element groups, normally controlled with the
13748   \a setAntialiasing function on the individual elements. If an element is neither specified in
13749   \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
13750   each individual element instance is used.
13751   
13752   For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
13753   drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
13754   to.
13755   
13756   if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
13757   removed from there.
13758   
13759   \see setAntialiasedElements
13760 */
13761 void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
13762 {
13763   mNotAntialiasedElements = notAntialiasedElements;
13764   
13765   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
13766   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
13767     mAntialiasedElements |= ~mNotAntialiasedElements;
13768 }
13769 
13770 /*!
13771   Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
13772   
13773   See \ref setNotAntialiasedElements for details.
13774   
13775   \see setAntialiasedElement
13776 */
13777 void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
13778 {
13779   if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
13780     mNotAntialiasedElements &= ~notAntialiasedElement;
13781   else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
13782     mNotAntialiasedElements |= notAntialiasedElement;
13783   
13784   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
13785   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
13786     mAntialiasedElements |= ~mNotAntialiasedElements;
13787 }
13788 
13789 /*!
13790   If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
13791   plottable to the legend (QCustomPlot::legend).
13792   
13793   \see addGraph, QCPLegend::addItem
13794 */
13795 void QCustomPlot::setAutoAddPlottableToLegend(bool on)
13796 {
13797   mAutoAddPlottableToLegend = on;
13798 }
13799 
13800 /*!
13801   Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
13802   enums. There are the following types of interactions:
13803   
13804   <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
13805   respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
13806   For details how to control which axes the user may drag/zoom and in what orientations, see \ref
13807   QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
13808   \ref QCPAxisRect::setRangeZoomAxes.
13809   
13810   <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
13811   QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
13812   their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
13813   user can actually select a plottable and its data can further be restricted with the \ref
13814   QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
13815   special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
13816   currently selected plottables, call \ref selectedPlottables. If you're only interested in
13817   QCPGraphs, you may use the convenience function \ref selectedGraphs.
13818   
13819   <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
13820   may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
13821   out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
13822   all currently selected items, call \ref selectedItems.
13823   
13824   <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
13825   may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
13826   labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
13827   each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
13828   selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
13829   
13830   <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
13831   select the legend itself or individual items by clicking on them. What parts exactly are
13832   selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
13833   legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
13834   find out which child items are selected, call \ref QCPLegend::selectedItems.
13835   
13836   <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
13837   QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
13838   user may select those objects by clicking on them. To find out which are currently selected, you
13839   need to check their selected state explicitly.
13840   
13841   If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
13842   emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
13843   their selection state has changed, i.e. not only by user interaction.
13844   
13845   To allow multiple objects to be selected by holding the selection modifier (\ref
13846   setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
13847   
13848   \note In addition to the selection mechanism presented here, QCustomPlot always emits
13849   corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
13850   \ref plottableDoubleClick for example.
13851   
13852   \see setInteraction, setSelectionTolerance
13853 */
13854 void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
13855 {
13856   mInteractions = interactions;
13857 }
13858 
13859 /*!
13860   Sets the single \a interaction of this QCustomPlot to \a enabled.
13861   
13862   For details about the interaction system, see \ref setInteractions.
13863   
13864   \see setInteractions
13865 */
13866 void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
13867 {
13868   if (!enabled && mInteractions.testFlag(interaction))
13869     mInteractions &= ~interaction;
13870   else if (enabled && !mInteractions.testFlag(interaction))
13871     mInteractions |= interaction;
13872 }
13873 
13874 /*!
13875   Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
13876   not.
13877   
13878   If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
13879   potential selection when the minimum distance between the click position and the graph line is
13880   smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
13881   directly inside the area and ignore this selection tolerance. In other words, it only has meaning
13882   for parts of objects that are too thin to exactly hit with a click and thus need such a
13883   tolerance.
13884   
13885   \see setInteractions, QCPLayerable::selectTest
13886 */
13887 void QCustomPlot::setSelectionTolerance(int pixels)
13888 {
13889   mSelectionTolerance = pixels;
13890 }
13891 
13892 /*!
13893   Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
13894   ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
13895   performance during dragging. Thus it creates a more responsive user experience. As soon as the
13896   user stops dragging, the last replot is done with normal antialiasing, to restore high image
13897   quality.
13898   
13899   \see setAntialiasedElements, setNotAntialiasedElements
13900 */
13901 void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
13902 {
13903   mNoAntialiasingOnDrag = enabled;
13904 }
13905 
13906 /*!
13907   Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
13908   
13909   \see setPlottingHint
13910 */
13911 void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
13912 {
13913   mPlottingHints = hints;
13914 }
13915 
13916 /*!
13917   Sets the specified plotting \a hint to \a enabled.
13918   
13919   \see setPlottingHints
13920 */
13921 void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
13922 {
13923   QCP::PlottingHints newHints = mPlottingHints;
13924   if (!enabled)
13925     newHints &= ~hint;
13926   else
13927     newHints |= hint;
13928   
13929   if (newHints != mPlottingHints)
13930     setPlottingHints(newHints);
13931 }
13932 
13933 /*!
13934   Sets the keyboard modifier that will be recognized as multi-select-modifier.
13935   
13936   If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
13937   objects (or data points) by clicking on them one after the other while holding down \a modifier.
13938   
13939   By default the multi-select-modifier is set to Qt::ControlModifier.
13940   
13941   \see setInteractions
13942 */
13943 void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
13944 {
13945   mMultiSelectModifier = modifier;
13946 }
13947 
13948 /*!
13949   Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
13950 
13951   If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
13952   example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
13953   QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
13954   selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
13955   
13956   If you wish to provide your user both with axis range dragging and data selection/range zooming,
13957   use this method to switch between the modes just before the interaction is processed, e.g. in
13958   reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
13959   the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
13960   
13961   If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
13962   interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
13963   will keep the selection rect active. Upon completion of the interaction, the behaviour is as
13964   defined by the currently set \a mode, not the mode that was set when the interaction started.
13965   
13966   \see setInteractions, setSelectionRect, QCPSelectionRect
13967 */
13968 void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
13969 {
13970   if (mSelectionRect)
13971   {
13972     if (mode == QCP::srmNone)
13973       mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
13974     
13975     // disconnect old connections:
13976     if (mSelectionRectMode == QCP::srmSelect)
13977       disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
13978     else if (mSelectionRectMode == QCP::srmZoom)
13979       disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
13980     
13981     // establish new ones:
13982     if (mode == QCP::srmSelect)
13983       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
13984     else if (mode == QCP::srmZoom)
13985       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
13986   }
13987   
13988   mSelectionRectMode = mode;
13989 }
13990 
13991 /*!
13992   Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
13993   QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
13994   the passed \a selectionRect. It can be accessed later via \ref selectionRect.
13995   
13996   This method is useful if you wish to replace the default QCPSelectionRect instance with an
13997   instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
13998   
13999   \see setSelectionRectMode
14000 */
14001 void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
14002 {
14003   delete mSelectionRect;
14004   
14005   mSelectionRect = selectionRect;
14006   
14007   if (mSelectionRect)
14008   {
14009     // establish connections with new selection rect:
14010     if (mSelectionRectMode == QCP::srmSelect)
14011       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
14012     else if (mSelectionRectMode == QCP::srmZoom)
14013       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
14014   }
14015 }
14016 
14017 /*!
14018   \warning This is still an experimental feature and its performance depends on the system that it
14019   runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
14020   might cause context conflicts on some systems.
14021   
14022   This method allows to enable OpenGL plot rendering, for increased plotting performance of
14023   graphically demanding plots (thick lines, translucent fills, etc.).
14024 
14025   If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
14026   continue plotting with hardware acceleration. The parameter \a multisampling controls how many
14027   samples will be used per pixel, it essentially controls the antialiasing quality. If \a
14028   multisampling is set too high for the current graphics hardware, the maximum allowed value will
14029   be used.
14030 
14031   You can test whether switching to OpenGL rendering was successful by checking whether the
14032   according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
14033   rendering continues with the regular software rasterizer, and an according qDebug output is
14034   generated.
14035 
14036   If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
14037   "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
14038   for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
14039   higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
14040   OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
14041   controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
14042   settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
14043   meantime.
14044 
14045   \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
14046   defined. This define must be set before including the QCustomPlot header both during compilation
14047   of the QCustomPlot library as well as when compiling your application. It is best to just include
14048   the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
14049   \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
14050   QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
14051   newer OpenGL interface which is already in the "gui" module.
14052 */
14053 void QCustomPlot::setOpenGl(bool enabled, int multisampling)
14054 {
14055   mOpenGlMultisamples = qMax(0, multisampling);
14056 #ifdef QCUSTOMPLOT_USE_OPENGL
14057   mOpenGl = enabled;
14058   if (mOpenGl)
14059   {
14060     if (setupOpenGl())
14061     {
14062       // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
14063       mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
14064       mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
14065       // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
14066       setAntialiasedElements(QCP::aeAll);
14067       setPlottingHint(QCP::phCacheLabels, false);
14068     } else
14069     {
14070       qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
14071       mOpenGl = false;
14072     }
14073   } else
14074   {
14075     // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
14076     if (mAntialiasedElements == QCP::aeAll)
14077       setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
14078     if (!mPlottingHints.testFlag(QCP::phCacheLabels))
14079       setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
14080     freeOpenGl();
14081   }
14082   // recreate all paint buffers:
14083   mPaintBuffers.clear();
14084   setupPaintBuffers();
14085 #else
14086   Q_UNUSED(enabled)
14087   qDebug() << Q_FUNC_INFO << "QCustomPlot can't use OpenGL because QCUSTOMPLOT_USE_OPENGL was not defined during compilation (add 'DEFINES += QCUSTOMPLOT_USE_OPENGL' to your qmake .pro file)";
14088 #endif
14089 }
14090 
14091 /*!
14092   Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
14093   viewport manually.
14094 
14095   The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
14096   the viewport to be the outer border of the plot. The viewport normally is the rect() of the
14097   QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
14098 
14099   Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
14100   an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
14101   and contains also the axes themselves, their tick numbers, their labels, or even additional axis
14102   rects, color scales and other layout elements.
14103 
14104   This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
14105   savePdf, etc. by temporarily changing the viewport size.
14106 */
14107 void QCustomPlot::setViewport(const QRect &rect)
14108 {
14109   mViewport = rect;
14110   if (mPlotLayout)
14111     mPlotLayout->setOuterRect(mViewport);
14112 }
14113 
14114 /*!
14115   Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
14116 
14117   Normally, this doesn't need to be set manually, because it is initialized with the regular \a
14118   QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
14119   displays, 2 for High-DPI displays).
14120 
14121   Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
14122   when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
14123   leaves the internal buffer device pixel ratio at 1.0.
14124 */
14125 void QCustomPlot::setBufferDevicePixelRatio(double ratio)
14126 {
14127   if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
14128   {
14129 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
14130     mBufferDevicePixelRatio = ratio;
14131     foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
14132       buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
14133     // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
14134 #else
14135     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
14136     mBufferDevicePixelRatio = 1.0;
14137 #endif
14138   }
14139 }
14140 
14141 /*!
14142   Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
14143   below all other objects in the plot.
14144 
14145   For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
14146   enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
14147   preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
14148   consider using the overloaded version of this function.
14149   
14150   If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
14151   first be filled with that brush, before drawing the background pixmap. This can be useful for
14152   background pixmaps with translucent areas.
14153 
14154   \see setBackgroundScaled, setBackgroundScaledMode
14155 */
14156 void QCustomPlot::setBackground(const QPixmap &pm)
14157 {
14158   mBackgroundPixmap = pm;
14159   mScaledBackgroundPixmap = QPixmap();
14160 }
14161 
14162 /*!
14163   Sets the background brush of the viewport (see \ref setViewport).
14164 
14165   Before drawing everything else, the background is filled with \a brush. If a background pixmap
14166   was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
14167   before the background pixmap is drawn. This can be useful for background pixmaps with translucent
14168   areas.
14169   
14170   Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
14171   useful for exporting to image formats which support transparency, e.g. \ref savePng.
14172 
14173   \see setBackgroundScaled, setBackgroundScaledMode
14174 */
14175 void QCustomPlot::setBackground(const QBrush &brush)
14176 {
14177   mBackgroundBrush = brush;
14178 }
14179 
14180 /*! \overload
14181   
14182   Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
14183   shall be scaled in one call.
14184 
14185   \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
14186 */
14187 void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
14188 {
14189   mBackgroundPixmap = pm;
14190   mScaledBackgroundPixmap = QPixmap();
14191   mBackgroundScaled = scaled;
14192   mBackgroundScaledMode = mode;
14193 }
14194 
14195 /*!
14196   Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
14197   set to true, control whether and how the aspect ratio of the original pixmap is preserved with
14198   \ref setBackgroundScaledMode.
14199   
14200   Note that the scaled version of the original pixmap is buffered, so there is no performance
14201   penalty on replots. (Except when the viewport dimensions are changed continuously.)
14202   
14203   \see setBackground, setBackgroundScaledMode
14204 */
14205 void QCustomPlot::setBackgroundScaled(bool scaled)
14206 {
14207   mBackgroundScaled = scaled;
14208 }
14209 
14210 /*!
14211   If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
14212   function to define whether and how the aspect ratio of the original pixmap is preserved.
14213   
14214   \see setBackground, setBackgroundScaled
14215 */
14216 void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
14217 {
14218   mBackgroundScaledMode = mode;
14219 }
14220 
14221 /*!
14222   Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
14223   
14224   There is an overloaded version of this function with no parameter which returns the last added
14225   plottable, see QCustomPlot::plottable()
14226   
14227   \see plottableCount
14228 */
14229 QCPAbstractPlottable *QCustomPlot::plottable(int index)
14230 {
14231   if (index >= 0 && index < mPlottables.size())
14232   {
14233     return mPlottables.at(index);
14234   } else
14235   {
14236     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14237     return nullptr;
14238   }
14239 }
14240 
14241 /*! \overload
14242   
14243   Returns the last plottable that was added to the plot. If there are no plottables in the plot,
14244   returns \c nullptr.
14245   
14246   \see plottableCount
14247 */
14248 QCPAbstractPlottable *QCustomPlot::plottable()
14249 {
14250   if (!mPlottables.isEmpty())
14251   {
14252     return mPlottables.last();
14253   } else
14254     return nullptr;
14255 }
14256 
14257 /*!
14258   Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
14259   legend item is also removed from the default legend (QCustomPlot::legend).
14260   
14261   Returns true on success.
14262   
14263   \see clearPlottables
14264 */
14265 bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
14266 {
14267   if (!mPlottables.contains(plottable))
14268   {
14269     qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
14270     return false;
14271   }
14272   
14273   // remove plottable from legend:
14274   plottable->removeFromLegend();
14275   // special handling for QCPGraphs to maintain the simple graph interface:
14276   if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
14277     mGraphs.removeOne(graph);
14278   // remove plottable:
14279   delete plottable;
14280   mPlottables.removeOne(plottable);
14281   return true;
14282 }
14283 
14284 /*! \overload
14285   
14286   Removes and deletes the plottable by its \a index.
14287 */
14288 bool QCustomPlot::removePlottable(int index)
14289 {
14290   if (index >= 0 && index < mPlottables.size())
14291     return removePlottable(mPlottables[index]);
14292   else
14293   {
14294     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14295     return false;
14296   }
14297 }
14298 
14299 /*!
14300   Removes all plottables from the plot and deletes them. Corresponding legend items are also
14301   removed from the default legend (QCustomPlot::legend).
14302   
14303   Returns the number of plottables removed.
14304   
14305   \see removePlottable
14306 */
14307 int QCustomPlot::clearPlottables()
14308 {
14309   int c = mPlottables.size();
14310   for (int i=c-1; i >= 0; --i)
14311     removePlottable(mPlottables[i]);
14312   return c;
14313 }
14314 
14315 /*!
14316   Returns the number of currently existing plottables in the plot
14317   
14318   \see plottable
14319 */
14320 int QCustomPlot::plottableCount() const
14321 {
14322   return mPlottables.size();
14323 }
14324 
14325 /*!
14326   Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
14327   
14328   There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
14329   
14330   \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
14331 */
14332 QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
14333 {
14334   QList<QCPAbstractPlottable*> result;
14335   foreach (QCPAbstractPlottable *plottable, mPlottables)
14336   {
14337     if (plottable->selected())
14338       result.append(plottable);
14339   }
14340   return result;
14341 }
14342 
14343 /*!
14344   Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
14345   return type is the abstract base class of all plottables, QCPAbstractPlottable.
14346   
14347   For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
14348   template method plottableAt<PlottableType>()
14349   
14350   \see plottableAt<PlottableType>(), itemAt, layoutElementAt
14351 */
14352 QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
14353 {
14354   return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
14355 }
14356 
14357 /*!
14358   Returns whether this QCustomPlot instance contains the \a plottable.
14359 */
14360 bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
14361 {
14362   return mPlottables.contains(plottable);
14363 }
14364 
14365 /*!
14366   Returns the graph with \a index. If the index is invalid, returns \c nullptr.
14367   
14368   There is an overloaded version of this function with no parameter which returns the last created
14369   graph, see QCustomPlot::graph()
14370   
14371   \see graphCount, addGraph
14372 */
14373 QCPGraph *QCustomPlot::graph(int index) const
14374 {
14375   if (index >= 0 && index < mGraphs.size())
14376   {
14377     return mGraphs.at(index);
14378   } else
14379   {
14380     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14381     return nullptr;
14382   }
14383 }
14384 
14385 /*! \overload
14386   
14387   Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
14388   returns \c nullptr.
14389   
14390   \see graphCount, addGraph
14391 */
14392 QCPGraph *QCustomPlot::graph() const
14393 {
14394   if (!mGraphs.isEmpty())
14395   {
14396     return mGraphs.last();
14397   } else
14398     return nullptr;
14399 }
14400 
14401 /*!
14402   Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
14403   bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
14404   keyAxis and \a valueAxis must reside in this QCustomPlot.
14405   
14406   \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
14407   "y") for the graph.
14408   
14409   Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
14410   
14411   \see graph, graphCount, removeGraph, clearGraphs
14412 */
14413 QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
14414 {
14415   if (!keyAxis) keyAxis = xAxis;
14416   if (!valueAxis) valueAxis = yAxis;
14417   if (!keyAxis || !valueAxis)
14418   {
14419     qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
14420     return nullptr;
14421   }
14422   if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
14423   {
14424     qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
14425     return nullptr;
14426   }
14427   
14428   QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
14429   newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
14430   return newGraph;
14431 }
14432 
14433 /*!
14434   Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
14435   legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
14436   the plot have a channel fill set towards the removed graph, the channel fill property of those
14437   graphs is reset to \c nullptr (no channel fill).
14438   
14439   Returns true on success.
14440   
14441   \see clearGraphs
14442 */
14443 bool QCustomPlot::removeGraph(QCPGraph *graph)
14444 {
14445   return removePlottable(graph);
14446 }
14447 
14448 /*! \overload
14449   
14450   Removes and deletes the graph by its \a index.
14451 */
14452 bool QCustomPlot::removeGraph(int index)
14453 {
14454   if (index >= 0 && index < mGraphs.size())
14455     return removeGraph(mGraphs[index]);
14456   else
14457     return false;
14458 }
14459 
14460 /*!
14461   Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
14462   from the default legend (QCustomPlot::legend).
14463 
14464   Returns the number of graphs removed.
14465   
14466   \see removeGraph
14467 */
14468 int QCustomPlot::clearGraphs()
14469 {
14470   int c = mGraphs.size();
14471   for (int i=c-1; i >= 0; --i)
14472     removeGraph(mGraphs[i]);
14473   return c;
14474 }
14475 
14476 /*!
14477   Returns the number of currently existing graphs in the plot
14478   
14479   \see graph, addGraph
14480 */
14481 int QCustomPlot::graphCount() const
14482 {
14483   return mGraphs.size();
14484 }
14485 
14486 /*!
14487   Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
14488   
14489   If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
14490   etc., use \ref selectedPlottables.
14491   
14492   \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
14493 */
14494 QList<QCPGraph*> QCustomPlot::selectedGraphs() const
14495 {
14496   QList<QCPGraph*> result;
14497   foreach (QCPGraph *graph, mGraphs)
14498   {
14499     if (graph->selected())
14500       result.append(graph);
14501   }
14502   return result;
14503 }
14504 
14505 /*!
14506   Returns the item with \a index. If the index is invalid, returns \c nullptr.
14507   
14508   There is an overloaded version of this function with no parameter which returns the last added
14509   item, see QCustomPlot::item()
14510   
14511   \see itemCount
14512 */
14513 QCPAbstractItem *QCustomPlot::item(int index) const
14514 {
14515   if (index >= 0 && index < mItems.size())
14516   {
14517     return mItems.at(index);
14518   } else
14519   {
14520     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14521     return nullptr;
14522   }
14523 }
14524 
14525 /*! \overload
14526   
14527   Returns the last item that was added to this plot. If there are no items in the plot,
14528   returns \c nullptr.
14529   
14530   \see itemCount
14531 */
14532 QCPAbstractItem *QCustomPlot::item() const
14533 {
14534   if (!mItems.isEmpty())
14535   {
14536     return mItems.last();
14537   } else
14538     return nullptr;
14539 }
14540 
14541 /*!
14542   Removes the specified item from the plot and deletes it.
14543   
14544   Returns true on success.
14545   
14546   \see clearItems
14547 */
14548 bool QCustomPlot::removeItem(QCPAbstractItem *item)
14549 {
14550   if (mItems.contains(item))
14551   {
14552     delete item;
14553     mItems.removeOne(item);
14554     return true;
14555   } else
14556   {
14557     qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
14558     return false;
14559   }
14560 }
14561 
14562 /*! \overload
14563   
14564   Removes and deletes the item by its \a index.
14565 */
14566 bool QCustomPlot::removeItem(int index)
14567 {
14568   if (index >= 0 && index < mItems.size())
14569     return removeItem(mItems[index]);
14570   else
14571   {
14572     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14573     return false;
14574   }
14575 }
14576 
14577 /*!
14578   Removes all items from the plot and deletes them.
14579   
14580   Returns the number of items removed.
14581   
14582   \see removeItem
14583 */
14584 int QCustomPlot::clearItems()
14585 {
14586   int c = mItems.size();
14587   for (int i=c-1; i >= 0; --i)
14588     removeItem(mItems[i]);
14589   return c;
14590 }
14591 
14592 /*!
14593   Returns the number of currently existing items in the plot
14594   
14595   \see item
14596 */
14597 int QCustomPlot::itemCount() const
14598 {
14599   return mItems.size();
14600 }
14601 
14602 /*!
14603   Returns a list of the selected items. If no items are currently selected, the list is empty.
14604   
14605   \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
14606 */
14607 QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
14608 {
14609   QList<QCPAbstractItem*> result;
14610   foreach (QCPAbstractItem *item, mItems)
14611   {
14612     if (item->selected())
14613       result.append(item);
14614   }
14615   return result;
14616 }
14617 
14618 /*!
14619   Returns the item at the pixel position \a pos. Since it can capture all items, the
14620   return type is the abstract base class of all items, QCPAbstractItem.
14621   
14622   For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
14623   template method itemAt<ItemType>()
14624   
14625   \see itemAt<ItemType>(), plottableAt, layoutElementAt
14626 */
14627 QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
14628 {
14629   return itemAt<QCPAbstractItem>(pos, onlySelectable);
14630 }
14631 
14632 /*!
14633   Returns whether this QCustomPlot contains the \a item.
14634   
14635   \see item
14636 */
14637 bool QCustomPlot::hasItem(QCPAbstractItem *item) const
14638 {
14639   return mItems.contains(item);
14640 }
14641 
14642 /*!
14643   Returns the layer with the specified \a name. If there is no layer with the specified name, \c
14644   nullptr is returned.
14645   
14646   Layer names are case-sensitive.
14647   
14648   \see addLayer, moveLayer, removeLayer
14649 */
14650 QCPLayer *QCustomPlot::layer(const QString &name) const
14651 {
14652   foreach (QCPLayer *layer, mLayers)
14653   {
14654     if (layer->name() == name)
14655       return layer;
14656   }
14657   return nullptr;
14658 }
14659 
14660 /*! \overload
14661   
14662   Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
14663   
14664   \see addLayer, moveLayer, removeLayer
14665 */
14666 QCPLayer *QCustomPlot::layer(int index) const
14667 {
14668   if (index >= 0 && index < mLayers.size())
14669   {
14670     return mLayers.at(index);
14671   } else
14672   {
14673     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
14674     return nullptr;
14675   }
14676 }
14677 
14678 /*!
14679   Returns the layer that is set as current layer (see \ref setCurrentLayer).
14680 */
14681 QCPLayer *QCustomPlot::currentLayer() const
14682 {
14683   return mCurrentLayer;
14684 }
14685 
14686 /*!
14687   Sets the layer with the specified \a name to be the current layer. All layerables (\ref
14688   QCPLayerable), e.g. plottables and items, are created on the current layer.
14689   
14690   Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
14691   
14692   Layer names are case-sensitive.
14693   
14694   \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
14695 */
14696 bool QCustomPlot::setCurrentLayer(const QString &name)
14697 {
14698   if (QCPLayer *newCurrentLayer = layer(name))
14699   {
14700     return setCurrentLayer(newCurrentLayer);
14701   } else
14702   {
14703     qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
14704     return false;
14705   }
14706 }
14707 
14708 /*! \overload
14709   
14710   Sets the provided \a layer to be the current layer.
14711   
14712   Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
14713   
14714   \see addLayer, moveLayer, removeLayer
14715 */
14716 bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
14717 {
14718   if (!mLayers.contains(layer))
14719   {
14720     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
14721     return false;
14722   }
14723   
14724   mCurrentLayer = layer;
14725   return true;
14726 }
14727 
14728 /*!
14729   Returns the number of currently existing layers in the plot
14730   
14731   \see layer, addLayer
14732 */
14733 int QCustomPlot::layerCount() const
14734 {
14735   return mLayers.size();
14736 }
14737 
14738 /*!
14739   Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
14740   must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
14741   
14742   Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
14743   valid layer inside this QCustomPlot.
14744   
14745   If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
14746   
14747   For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
14748   
14749   \see layer, moveLayer, removeLayer
14750 */
14751 bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
14752 {
14753   if (!otherLayer)
14754     otherLayer = mLayers.last();
14755   if (!mLayers.contains(otherLayer))
14756   {
14757     qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
14758     return false;
14759   }
14760   if (layer(name))
14761   {
14762     qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
14763     return false;
14764   }
14765     
14766   QCPLayer *newLayer = new QCPLayer(this, name);
14767   mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
14768   updateLayerIndices();
14769   setupPaintBuffers(); // associates new layer with the appropriate paint buffer
14770   return true;
14771 }
14772 
14773 /*!
14774   Removes the specified \a layer and returns true on success.
14775   
14776   All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
14777   \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
14778   cases, the total rendering order of all layerables in the QCustomPlot is preserved.
14779   
14780   If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
14781   layer) becomes the new current layer.
14782   
14783   It is not possible to remove the last layer of the plot.
14784   
14785   \see layer, addLayer, moveLayer
14786 */
14787 bool QCustomPlot::removeLayer(QCPLayer *layer)
14788 {
14789   if (!mLayers.contains(layer))
14790   {
14791     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
14792     return false;
14793   }
14794   if (mLayers.size() < 2)
14795   {
14796     qDebug() << Q_FUNC_INFO << "can't remove last layer";
14797     return false;
14798   }
14799   
14800   // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
14801   int removedIndex = layer->index();
14802   bool isFirstLayer = removedIndex==0;
14803   QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
14804   QList<QCPLayerable*> children = layer->children();
14805   if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
14806     std::reverse(children.begin(), children.end());
14807   foreach (QCPLayerable *child, children)
14808     child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
14809   
14810   // if removed layer is current layer, change current layer to layer below/above:
14811   if (layer == mCurrentLayer)
14812     setCurrentLayer(targetLayer);
14813   
14814   // invalidate the paint buffer that was responsible for this layer:
14815   if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
14816     pb->setInvalidated();
14817   
14818   // remove layer:
14819   delete layer;
14820   mLayers.removeOne(layer);
14821   updateLayerIndices();
14822   return true;
14823 }
14824 
14825 /*!
14826   Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
14827   below is controlled with \a insertMode.
14828   
14829   Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
14830   QCustomPlot.
14831   
14832   \see layer, addLayer, moveLayer
14833 */
14834 bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
14835 {
14836   if (!mLayers.contains(layer))
14837   {
14838     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
14839     return false;
14840   }
14841   if (!mLayers.contains(otherLayer))
14842   {
14843     qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
14844     return false;
14845   }
14846   
14847   if (layer->index() > otherLayer->index())
14848     mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
14849   else if (layer->index() < otherLayer->index())
14850     mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
14851   
14852   // invalidate the paint buffers that are responsible for the layers:
14853   if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
14854     pb->setInvalidated();
14855   if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
14856     pb->setInvalidated();
14857   
14858   updateLayerIndices();
14859   return true;
14860 }
14861 
14862 /*!
14863   Returns the number of axis rects in the plot.
14864   
14865   All axis rects can be accessed via QCustomPlot::axisRect().
14866   
14867   Initially, only one axis rect exists in the plot.
14868   
14869   \see axisRect, axisRects
14870 */
14871 int QCustomPlot::axisRectCount() const
14872 {
14873   return axisRects().size();
14874 }
14875 
14876 /*!
14877   Returns the axis rect with \a index.
14878   
14879   Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
14880   added, all of them may be accessed with this function in a linear fashion (even when they are
14881   nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
14882   
14883   The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
14884   them. For example, if the axis rects are in the top level grid layout (accessible via \ref
14885   QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
14886   default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
14887   "foColumnsFirst" wasn't changed.
14888   
14889   If you want to access axis rects by their row and column index, use the layout interface. For
14890   example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
14891   returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
14892   
14893   \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
14894 */
14895 QCPAxisRect *QCustomPlot::axisRect(int index) const
14896 {
14897   const QList<QCPAxisRect*> rectList = axisRects();
14898   if (index >= 0 && index < rectList.size())
14899   {
14900     return rectList.at(index);
14901   } else
14902   {
14903     qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
14904     return nullptr;
14905   }
14906 }
14907 
14908 /*!
14909   Returns all axis rects in the plot.
14910   
14911   The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
14912   them. For example, if the axis rects are in the top level grid layout (accessible via \ref
14913   QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
14914   default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
14915   "foColumnsFirst" wasn't changed.
14916   
14917   \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
14918 */
14919 QList<QCPAxisRect*> QCustomPlot::axisRects() const
14920 {
14921   QList<QCPAxisRect*> result;
14922   QStack<QCPLayoutElement*> elementStack;
14923   if (mPlotLayout)
14924     elementStack.push(mPlotLayout);
14925   
14926   while (!elementStack.isEmpty())
14927   {
14928     foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
14929     {
14930       if (element)
14931       {
14932         elementStack.push(element);
14933         if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
14934           result.append(ar);
14935       }
14936     }
14937   }
14938   
14939   return result;
14940 }
14941 
14942 /*!
14943   Returns the layout element at pixel position \a pos. If there is no element at that position,
14944   returns \c nullptr.
14945   
14946   Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
14947   any of its parent elements is set to false, it will not be considered.
14948   
14949   \see itemAt, plottableAt
14950 */
14951 QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
14952 {
14953   QCPLayoutElement *currentElement = mPlotLayout;
14954   bool searchSubElements = true;
14955   while (searchSubElements && currentElement)
14956   {
14957     searchSubElements = false;
14958     foreach (QCPLayoutElement *subElement, currentElement->elements(false))
14959     {
14960       if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
14961       {
14962         currentElement = subElement;
14963         searchSubElements = true;
14964         break;
14965       }
14966     }
14967   }
14968   return currentElement;
14969 }
14970 
14971 /*!
14972   Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
14973   other layout elements even if they are visually in front of the axis rect (e.g. a \ref
14974   QCPLegend). If there is no axis rect at that position, returns \c nullptr.
14975 
14976   Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
14977   on any of its parent elements is set to false, it will not be considered.
14978 
14979   \see layoutElementAt
14980 */
14981 QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
14982 {
14983   QCPAxisRect *result = nullptr;
14984   QCPLayoutElement *currentElement = mPlotLayout;
14985   bool searchSubElements = true;
14986   while (searchSubElements && currentElement)
14987   {
14988     searchSubElements = false;
14989     foreach (QCPLayoutElement *subElement, currentElement->elements(false))
14990     {
14991       if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
14992       {
14993         currentElement = subElement;
14994         searchSubElements = true;
14995         if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
14996           result = ar;
14997         break;
14998       }
14999     }
15000   }
15001   return result;
15002 }
15003 
15004 /*!
15005   Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
15006   QCPAxis::spNone.
15007   
15008   \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
15009   QCPAxis::setSelectableParts
15010 */
15011 QList<QCPAxis*> QCustomPlot::selectedAxes() const
15012 {
15013   QList<QCPAxis*> result, allAxes;
15014   foreach (QCPAxisRect *rect, axisRects())
15015     allAxes << rect->axes();
15016   
15017   foreach (QCPAxis *axis, allAxes)
15018   {
15019     if (axis->selectedParts() != QCPAxis::spNone)
15020       result.append(axis);
15021   }
15022   
15023   return result;
15024 }
15025 
15026 /*!
15027   Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
15028   QCPLegend::spNone.
15029   
15030   \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
15031   QCPLegend::setSelectableParts, QCPLegend::selectedItems
15032 */
15033 QList<QCPLegend*> QCustomPlot::selectedLegends() const
15034 {
15035   QList<QCPLegend*> result;
15036   
15037   QStack<QCPLayoutElement*> elementStack;
15038   if (mPlotLayout)
15039     elementStack.push(mPlotLayout);
15040   
15041   while (!elementStack.isEmpty())
15042   {
15043     foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
15044     {
15045       if (subElement)
15046       {
15047         elementStack.push(subElement);
15048         if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
15049         {
15050           if (leg->selectedParts() != QCPLegend::spNone)
15051             result.append(leg);
15052         }
15053       }
15054     }
15055   }
15056   
15057   return result;
15058 }
15059 
15060 /*!
15061   Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
15062   
15063   Since calling this function is not a user interaction, this does not emit the \ref
15064   selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
15065   objects were previously selected.
15066   
15067   \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
15068 */
15069 void QCustomPlot::deselectAll()
15070 {
15071   foreach (QCPLayer *layer, mLayers)
15072   {
15073     foreach (QCPLayerable *layerable, layer->children())
15074       layerable->deselectEvent(nullptr);
15075   }
15076 }
15077 
15078 /*!
15079   Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
15080   refreshed with the new buffer contents. This is the method that must be called to make changes to
15081   the plot, e.g. on the axis ranges or data points of graphs, visible.
15082 
15083   The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
15084   if your application calls \ref replot very quickly in succession (e.g. multiple independent
15085   functions change some aspects of the plot and each wants to make sure the change gets replotted),
15086   it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
15087   actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
15088   replot with this priority will only cause a single replot, avoiding redundant replots and
15089   improving performance.
15090 
15091   Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
15092   QCustomPlot widget and user interactions (object selection and range dragging/zooming).
15093 
15094   Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
15095   afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
15096   signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
15097   recursion.
15098 
15099   If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
15100   replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
15101   details.
15102   
15103   \see replotTime
15104 */
15105 void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
15106 {
15107   if (refreshPriority == QCustomPlot::rpQueuedReplot)
15108   {
15109     if (!mReplotQueued)
15110     {
15111       mReplotQueued = true;
15112       QTimer::singleShot(0, this, SLOT(replot()));
15113     }
15114     return;
15115   }
15116   
15117   if (mReplotting) // incase signals loop back to replot slot
15118     return;
15119   mReplotting = true;
15120   mReplotQueued = false;
15121   emit beforeReplot();
15122   
15123 # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
15124   QTime replotTimer;
15125   replotTimer.start();
15126 # else
15127   QElapsedTimer replotTimer;
15128   replotTimer.start();
15129 # endif
15130   
15131   updateLayout();
15132   // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
15133   setupPaintBuffers();
15134   foreach (QCPLayer *layer, mLayers)
15135     layer->drawToPaintBuffer();
15136   foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
15137     buffer->setInvalidated(false);
15138   
15139   if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
15140     repaint();
15141   else
15142     update();
15143   
15144 # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
15145   mReplotTime = replotTimer.elapsed();
15146 # else
15147   mReplotTime = replotTimer.nsecsElapsed()*1e-6;
15148 # endif
15149   if (!qFuzzyIsNull(mReplotTimeAverage))
15150     mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
15151   else
15152     mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
15153   
15154   emit afterReplot();
15155   mReplotting = false;
15156 }
15157 
15158 /*!
15159   Returns the time in milliseconds that the last replot took. If \a average is set to true, an
15160   exponential moving average over the last couple of replots is returned.
15161   
15162   \see replot
15163 */
15164 double QCustomPlot::replotTime(bool average) const
15165 {
15166   return average ? mReplotTimeAverage : mReplotTime;
15167 }
15168 
15169 /*!
15170   Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
15171   
15172   if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
15173   (QCPLayerable::setVisible), will be used to rescale the axes.
15174   
15175   \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
15176 */
15177 void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
15178 {
15179   QList<QCPAxis*> allAxes;
15180   foreach (QCPAxisRect *rect, axisRects())
15181     allAxes << rect->axes();
15182   
15183   foreach (QCPAxis *axis, allAxes)
15184     axis->rescale(onlyVisiblePlottables);
15185 }
15186 
15187 /*!
15188   Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
15189   of texts and lines will be derived from the specified \a width and \a height. This means, the
15190   output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
15191   pixel width and height. If either \a width or \a height is zero, the exported image will have the
15192   same dimensions as the QCustomPlot widget currently has.
15193 
15194   Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
15195   drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
15196   a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
15197   about cosmetic pens, see the QPainter and QPen documentation.
15198 
15199   The objects of the plot will appear in the current selection state. If you don't want any
15200   selected objects to be painted in their selected look, deselect everything with \ref deselectAll
15201   before calling this function.
15202 
15203   Returns true on success.
15204 
15205   \warning
15206   \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
15207   is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
15208   (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
15209   \li If calling this function inside the constructor of the parent of the QCustomPlot widget
15210   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
15211   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
15212   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
15213   aren't defined yet inside the constructor, so you would get an image that has strange
15214   widths/heights.
15215 
15216   \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
15217   PDF file.
15218 
15219   \note On Android systems, this method does nothing and issues an according qDebug warning
15220   message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
15221 
15222   \see savePng, saveBmp, saveJpg, saveRastered
15223 */
15224 bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
15225 {
15226   bool success = false;
15227 #ifdef QT_NO_PRINTER
15228   Q_UNUSED(fileName)
15229   Q_UNUSED(exportPen)
15230   Q_UNUSED(width)
15231   Q_UNUSED(height)
15232   Q_UNUSED(pdfCreator)
15233   Q_UNUSED(pdfTitle)
15234   qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
15235 #else
15236   int newWidth, newHeight;
15237   if (width == 0 || height == 0)
15238   {
15239     newWidth = this->width();
15240     newHeight = this->height();
15241   } else
15242   {
15243     newWidth = width;
15244     newHeight = height;
15245   }
15246   
15247   QPrinter printer(QPrinter::ScreenResolution);
15248   printer.setOutputFileName(fileName);
15249   printer.setOutputFormat(QPrinter::PdfFormat);
15250   printer.setColorMode(QPrinter::Color);
15251   printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
15252   printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
15253   QRect oldViewport = viewport();
15254   setViewport(QRect(0, 0, newWidth, newHeight));
15255 #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
15256   printer.setFullPage(true);
15257   printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
15258 #else
15259   QPageLayout pageLayout;
15260   pageLayout.setMode(QPageLayout::FullPageMode);
15261   pageLayout.setOrientation(QPageLayout::Portrait);
15262   pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
15263   pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
15264   printer.setPageLayout(pageLayout);
15265 #endif
15266   QCPPainter printpainter;
15267   if (printpainter.begin(&printer))
15268   {
15269     printpainter.setMode(QCPPainter::pmVectorized);
15270     printpainter.setMode(QCPPainter::pmNoCaching);
15271     printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
15272     printpainter.setWindow(mViewport);
15273     if (mBackgroundBrush.style() != Qt::NoBrush &&
15274         mBackgroundBrush.color() != Qt::white &&
15275         mBackgroundBrush.color() != Qt::transparent &&
15276         mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
15277       printpainter.fillRect(viewport(), mBackgroundBrush);
15278     draw(&printpainter);
15279     printpainter.end();
15280     success = true;
15281   }
15282   setViewport(oldViewport);
15283 #endif // QT_NO_PRINTER
15284   return success;
15285 }
15286 
15287 /*!
15288   Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
15289   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
15290   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
15291   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
15292   parameter.
15293 
15294   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
15295   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
15296   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
15297   200*200 pixel resolution.
15298 
15299   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
15300   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
15301   QCustomPlot to place objects with sub-pixel accuracy.
15302 
15303   image compression can be controlled with the \a quality parameter which must be between 0 and 100
15304   or -1 to use the default setting.
15305 
15306   The \a resolution will be written to the image file header and has no direct consequence for the
15307   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
15308   it will be able to scale the image to match either a given size in real units of length (inch,
15309   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
15310   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
15311   resolution unit internally.
15312 
15313   Returns true on success. If this function fails, most likely the PNG format isn't supported by
15314   the system, see Qt docs about QImageWriter::supportedImageFormats().
15315 
15316   The objects of the plot will appear in the current selection state. If you don't want any selected
15317   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
15318   this function.
15319 
15320   If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
15321   with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
15322 
15323   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
15324   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
15325   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
15326   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
15327   aren't defined yet inside the constructor, so you would get an image that has strange
15328   widths/heights.
15329 
15330   \see savePdf, saveBmp, saveJpg, saveRastered
15331 */
15332 bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
15333 {
15334   return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
15335 }
15336 
15337 /*!
15338   Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
15339   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
15340   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
15341   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
15342   parameter.
15343 
15344   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
15345   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
15346   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
15347   200*200 pixel resolution.
15348 
15349   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
15350   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
15351   QCustomPlot to place objects with sub-pixel accuracy.
15352 
15353   image compression can be controlled with the \a quality parameter which must be between 0 and 100
15354   or -1 to use the default setting.
15355 
15356   The \a resolution will be written to the image file header and has no direct consequence for the
15357   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
15358   it will be able to scale the image to match either a given size in real units of length (inch,
15359   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
15360   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
15361   resolution unit internally.
15362 
15363   Returns true on success. If this function fails, most likely the JPEG format isn't supported by
15364   the system, see Qt docs about QImageWriter::supportedImageFormats().
15365 
15366   The objects of the plot will appear in the current selection state. If you don't want any selected
15367   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
15368   this function.
15369 
15370   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
15371   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
15372   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
15373   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
15374   aren't defined yet inside the constructor, so you would get an image that has strange
15375   widths/heights.
15376 
15377   \see savePdf, savePng, saveBmp, saveRastered
15378 */
15379 bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
15380 {
15381   return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
15382 }
15383 
15384 /*!
15385   Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
15386   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
15387   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
15388   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
15389   parameter.
15390 
15391   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
15392   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
15393   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
15394   200*200 pixel resolution.
15395 
15396   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
15397   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
15398   QCustomPlot to place objects with sub-pixel accuracy.
15399 
15400   The \a resolution will be written to the image file header and has no direct consequence for the
15401   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
15402   it will be able to scale the image to match either a given size in real units of length (inch,
15403   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
15404   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
15405   resolution unit internally.
15406 
15407   Returns true on success. If this function fails, most likely the BMP format isn't supported by
15408   the system, see Qt docs about QImageWriter::supportedImageFormats().
15409 
15410   The objects of the plot will appear in the current selection state. If you don't want any selected
15411   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
15412   this function.
15413 
15414   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
15415   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
15416   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
15417   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
15418   aren't defined yet inside the constructor, so you would get an image that has strange
15419   widths/heights.
15420 
15421   \see savePdf, savePng, saveJpg, saveRastered
15422 */
15423 bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
15424 {
15425   return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
15426 }
15427 
15428 /*! \internal
15429   
15430   Returns a minimum size hint that corresponds to the minimum size of the top level layout
15431   (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
15432   size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
15433   This is especially important, when placed in a QLayout where other components try to take in as
15434   much space as possible (e.g. QMdiArea).
15435 */
15436 QSize QCustomPlot::minimumSizeHint() const
15437 {
15438   return mPlotLayout->minimumOuterSizeHint();
15439 }
15440 
15441 /*! \internal
15442   
15443   Returns a size hint that is the same as \ref minimumSizeHint.
15444   
15445 */
15446 QSize QCustomPlot::sizeHint() const
15447 {
15448   return mPlotLayout->minimumOuterSizeHint();
15449 }
15450 
15451 /*! \internal
15452   
15453   Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
15454   draws the internal buffer on the widget surface.
15455 */
15456 void QCustomPlot::paintEvent(QPaintEvent *event)
15457 {
15458   Q_UNUSED(event)
15459   QCPPainter painter(this);
15460   if (painter.isActive())
15461   {
15462 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
15463   painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
15464 #endif
15465     if (mBackgroundBrush.style() != Qt::NoBrush)
15466       painter.fillRect(mViewport, mBackgroundBrush);
15467     drawBackground(&painter);
15468     foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
15469       buffer->draw(&painter);
15470   }
15471 }
15472 
15473 /*! \internal
15474   
15475   Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
15476   of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
15477 */
15478 void QCustomPlot::resizeEvent(QResizeEvent *event)
15479 {
15480   Q_UNUSED(event)
15481   // resize and repaint the buffer:
15482   setViewport(rect());
15483   replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
15484 }
15485 
15486 bool QCustomPlot::event( QEvent *event ){
15487     switch( event->type() ){
15488         case QEvent::Gesture: {
15489             QGestureEvent *gestureEve = static_cast<QGestureEvent*>(event);
15490             if( QGesture *pinch = gestureEve->gesture(Qt::PinchGesture) ){
15491                 QPinchGesture *pinchEve = static_cast<QPinchGesture *>(pinch);
15492                 qreal scaleFactor = pinchEve->totalScaleFactor( );
15493                 if( scaleFactor > 1.0 ){
15494                     scaleFactor *= 5;
15495                 }else{
15496                     scaleFactor *= -15;
15497                 }
15498                 QWheelEvent *wheelEve = new QWheelEvent(this->mapFromGlobal(QCursor::pos()), scaleFactor, Qt::NoButton, Qt::NoModifier, Qt::Vertical );
15499                 this->wheelEvent( wheelEve );
15500             }
15501             return true;
15502         }
15503         default: {
15504             break;
15505         }
15506     }
15507 
15508     return QWidget::event( event );
15509 }
15510 
15511 /*! \internal
15512   
15513  Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
15514  determines the layerable under the cursor and forwards the event to it. Finally, emits the
15515  specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
15516  axisDoubleClick, etc.).
15517  
15518  \see mousePressEvent, mouseReleaseEvent
15519 */
15520 void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
15521 {
15522   emit mouseDoubleClick(event);
15523   mMouseHasMoved = false;
15524   mMousePressPos = event->pos();
15525   
15526   // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
15527   QList<QVariant> details;
15528   QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
15529   for (int i=0; i<candidates.size(); ++i)
15530   {
15531     event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
15532     candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
15533     if (event->isAccepted())
15534     {
15535       mMouseEventLayerable = candidates.at(i);
15536       mMouseEventLayerableDetails = details.at(i);
15537       break;
15538     }
15539   }
15540   
15541   // emit specialized object double click signals:
15542   if (!candidates.isEmpty())
15543   {
15544     if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
15545     {
15546       int dataIndex = 0;
15547       if (!details.first().value<QCPDataSelection>().isEmpty())
15548         dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
15549       emit plottableDoubleClick(ap, dataIndex, event);
15550     } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
15551       emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
15552     else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
15553       emit itemDoubleClick(ai, event);
15554     else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
15555       emit legendDoubleClick(lg, nullptr, event);
15556     else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
15557       emit legendDoubleClick(li->parentLegend(), li, event);
15558   }
15559   
15560   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
15561 }
15562 
15563 /*! \internal
15564   
15565   Event handler for when a mouse button is pressed. Emits the mousePress signal.
15566 
15567   If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
15568   selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
15569   
15570   \see mouseMoveEvent, mouseReleaseEvent
15571 */
15572 void QCustomPlot::mousePressEvent(QMouseEvent *event)
15573 {
15574   emit mousePress(event);
15575   // save some state to tell in releaseEvent whether it was a click:
15576   mMouseHasMoved = false;
15577   mMousePressPos = event->pos();
15578   
15579   if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
15580   {
15581     if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
15582       mSelectionRect->startSelection(event);
15583   } else
15584   {
15585     // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
15586     QList<QVariant> details;
15587     QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
15588     if (!candidates.isEmpty())
15589     {
15590       mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
15591       mMouseSignalLayerableDetails = details.first();
15592     }
15593     // forward event to topmost candidate which accepts the event:
15594     for (int i=0; i<candidates.size(); ++i)
15595     {
15596       event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
15597       candidates.at(i)->mousePressEvent(event, details.at(i));
15598       if (event->isAccepted())
15599       {
15600         mMouseEventLayerable = candidates.at(i);
15601         mMouseEventLayerableDetails = details.at(i);
15602         break;
15603       }
15604     }
15605   }
15606   
15607   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
15608 }
15609 
15610 /*! \internal
15611   
15612   Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
15613 
15614   If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
15615   in order to update the rect geometry.
15616   
15617   Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
15618   layout element before), the mouseMoveEvent is forwarded to that element.
15619   
15620   \see mousePressEvent, mouseReleaseEvent
15621 */
15622 void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
15623 {
15624   emit mouseMove(event);
15625   
15626   if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
15627     mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
15628   
15629   if (mSelectionRect && mSelectionRect->isActive())
15630     mSelectionRect->moveSelection(event);
15631   else if (mMouseEventLayerable) // call event of affected layerable:
15632     mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
15633   
15634   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
15635 }
15636 
15637 /*! \internal
15638 
15639   Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
15640 
15641   If the mouse was moved less than a certain threshold in any direction since the \ref
15642   mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
15643   \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
15644   click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
15645 
15646   If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
15647   before), the \ref mouseReleaseEvent is forwarded to that element.
15648 
15649   \see mousePressEvent, mouseMoveEvent
15650 */
15651 void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
15652 {
15653   emit mouseRelease(event);
15654   
15655   if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
15656   {
15657     if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
15658       mSelectionRect->cancel();
15659     if (event->button() == Qt::LeftButton)
15660       processPointSelection(event);
15661     
15662     // emit specialized click signals of QCustomPlot instance:
15663     if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
15664     {
15665       int dataIndex = 0;
15666       if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
15667         dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
15668       emit plottableClick(ap, dataIndex, event);
15669     } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
15670       emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
15671     else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
15672       emit itemClick(ai, event);
15673     else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
15674       emit legendClick(lg, nullptr, event);
15675     else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
15676       emit legendClick(li->parentLegend(), li, event);
15677     mMouseSignalLayerable = nullptr;
15678   }
15679   
15680   if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
15681   {
15682     // finish selection rect, the appropriate action will be taken via signal-slot connection:
15683     mSelectionRect->endSelection(event);
15684   } else
15685   {
15686     // call event of affected layerable:
15687     if (mMouseEventLayerable)
15688     {
15689       mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
15690       mMouseEventLayerable = nullptr;
15691     }
15692   }
15693   
15694   if (noAntialiasingOnDrag())
15695     replot(rpQueuedReplot);
15696   
15697   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
15698 }
15699 
15700 /*! \internal
15701 
15702   Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
15703   determines the affected layerable and forwards the event to it.
15704 */
15705 void QCustomPlot::wheelEvent(QWheelEvent *event)
15706 {
15707   emit mouseWheel(event);
15708   
15709 #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
15710   const QPointF pos = event->pos();
15711 #else
15712   const QPointF pos = event->position();
15713 #endif
15714   
15715   // forward event to layerable under cursor:
15716   foreach (QCPLayerable *candidate, layerableListAt(pos, false))
15717   {
15718     event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
15719     candidate->wheelEvent(event);
15720     if (event->isAccepted())
15721       break;
15722   }
15723   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
15724 }
15725 
15726 /*! \internal
15727   
15728   This function draws the entire plot, including background pixmap, with the specified \a painter.
15729   It does not make use of the paint buffers like \ref replot, so this is the function typically
15730   used by saving/exporting methods such as \ref savePdf or \ref toPainter.
15731 
15732   Note that it does not fill the background with the background brush (as the user may specify with
15733   \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
15734   method.
15735 */
15736 void QCustomPlot::draw(QCPPainter *painter)
15737 {
15738   updateLayout();
15739   
15740   // draw viewport background pixmap:
15741   drawBackground(painter);
15742 
15743   // draw all layered objects (grid, axes, plottables, items, legend,...):
15744   foreach (QCPLayer *layer, mLayers)
15745     layer->draw(painter);
15746   
15747   /* Debug code to draw all layout element rects
15748   foreach (QCPLayoutElement *el, findChildren<QCPLayoutElement*>())
15749   {
15750     painter->setBrush(Qt::NoBrush);
15751     painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
15752     painter->drawRect(el->rect());
15753     painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
15754     painter->drawRect(el->outerRect());
15755   }
15756   */
15757 }
15758 
15759 /*! \internal
15760 
15761   Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
15762   QCPLayoutElement::update on the main plot layout.
15763 
15764   Here, the layout elements calculate their positions and margins, and prepare for the following
15765   draw call.
15766 */
15767 void QCustomPlot::updateLayout()
15768 {
15769   // run through layout phases:
15770   mPlotLayout->update(QCPLayoutElement::upPreparation);
15771   mPlotLayout->update(QCPLayoutElement::upMargins);
15772   mPlotLayout->update(QCPLayoutElement::upLayout);
15773 
15774   emit afterLayout();
15775 }
15776 
15777 /*! \internal
15778   
15779   Draws the viewport background pixmap of the plot.
15780   
15781   If a pixmap was provided via \ref setBackground, this function buffers the scaled version
15782   depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
15783   the viewport with the provided \a painter. The scaled version is buffered in
15784   mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
15785   the axis rect has changed in a way that requires a rescale of the background pixmap (this is
15786   dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
15787   set.
15788   
15789   Note that this function does not draw a fill with the background brush
15790   (\ref setBackground(const QBrush &brush)) beneath the pixmap.
15791   
15792   \see setBackground, setBackgroundScaled, setBackgroundScaledMode
15793 */
15794 void QCustomPlot::drawBackground(QCPPainter *painter)
15795 {
15796   // Note: background color is handled in individual replot/save functions
15797 
15798   // draw background pixmap (on top of fill, if brush specified):
15799   if (!mBackgroundPixmap.isNull())
15800   {
15801     if (mBackgroundScaled)
15802     {
15803       // check whether mScaledBackground needs to be updated:
15804       QSize scaledSize(mBackgroundPixmap.size());
15805       scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
15806       if (mScaledBackgroundPixmap.size() != scaledSize)
15807         mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
15808       painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
15809     } else
15810     {
15811       painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
15812     }
15813   }
15814 }
15815 
15816 /*! \internal
15817 
15818   Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
15819   paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
15820   Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
15821   associates the paint buffers with the layers, so they draw themselves into the right buffer when
15822   \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
15823   QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
15824   layers in \ref QCPLayer::lmBuffered mode.
15825 
15826   This method uses \ref createPaintBuffer to create new paint buffers.
15827 
15828   After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
15829   (so an attempt to replot only a single buffered layer causes a full replot).
15830 
15831   This method is called in every \ref replot call, prior to actually drawing the layers (into their
15832   associated paint buffer). If the paint buffers don't need changing/reallocating, this method
15833   basically leaves them alone and thus finishes very fast.
15834 */
15835 void QCustomPlot::setupPaintBuffers()
15836 {
15837   int bufferIndex = 0;
15838   if (mPaintBuffers.isEmpty())
15839     mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
15840   
15841   for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
15842   {
15843     QCPLayer *layer = mLayers.at(layerIndex);
15844     if (layer->mode() == QCPLayer::lmLogical)
15845     {
15846       layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
15847     } else if (layer->mode() == QCPLayer::lmBuffered)
15848     {
15849       ++bufferIndex;
15850       if (bufferIndex >= mPaintBuffers.size())
15851         mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
15852       layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
15853       if (layerIndex < mLayers.size()-1 && mLayers.at(layerIndex+1)->mode() == QCPLayer::lmLogical) // not last layer, and next one is logical, so prepare another buffer for next layerables
15854       {
15855         ++bufferIndex;
15856         if (bufferIndex >= mPaintBuffers.size())
15857           mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
15858       }
15859     }
15860   }
15861   // remove unneeded buffers:
15862   while (mPaintBuffers.size()-1 > bufferIndex)
15863     mPaintBuffers.removeLast();
15864   // resize buffers to viewport size and clear contents:
15865   foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
15866   {
15867     buffer->setSize(viewport().size()); // won't do anything if already correct size
15868     buffer->clear(Qt::transparent);
15869     buffer->setInvalidated();
15870   }
15871 }
15872 
15873 /*! \internal
15874 
15875   This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
15876 
15877   Depending on the current setting of \ref setOpenGl, and the current Qt version, different
15878   backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
15879   size and device pixel ratio, and returned.
15880 */
15881 QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
15882 {
15883   if (mOpenGl)
15884   {
15885 #if defined(QCP_OPENGL_FBO)
15886     return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
15887 #elif defined(QCP_OPENGL_PBUFFER)
15888     return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
15889 #else
15890     qDebug() << Q_FUNC_INFO << "OpenGL enabled even though no support for it compiled in, this shouldn't have happened. Falling back to pixmap paint buffer.";
15891     return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
15892 #endif
15893   } else
15894     return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
15895 }
15896 
15897 /*!
15898   This method returns whether any of the paint buffers held by this QCustomPlot instance are
15899   invalidated.
15900 
15901   If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
15902   causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
15903   the layer order has changed, new layers were added or removed, layer modes were changed (\ref
15904   QCPLayer::setMode), or layerables were added or removed.
15905 
15906   \see QCPAbstractPaintBuffer::setInvalidated
15907 */
15908 bool QCustomPlot::hasInvalidatedPaintBuffers()
15909 {
15910   foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
15911   {
15912     if (buffer->invalidated())
15913       return true;
15914   }
15915   return false;
15916 }
15917 
15918 /*! \internal
15919 
15920   When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
15921   surface, paint device).
15922 
15923   Returns true on success.
15924 
15925   If this method is successful, all paint buffers should be deleted and then reallocated by calling
15926   \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
15927   QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
15928 
15929   \see freeOpenGl
15930 */
15931 bool QCustomPlot::setupOpenGl()
15932 {
15933 #ifdef QCP_OPENGL_FBO
15934   freeOpenGl();
15935   QSurfaceFormat proposedSurfaceFormat;
15936   proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
15937 #ifdef QCP_OPENGL_OFFSCREENSURFACE
15938   QOffscreenSurface *surface = new QOffscreenSurface;
15939 #else
15940   QWindow *surface = new QWindow;
15941   surface->setSurfaceType(QSurface::OpenGLSurface);
15942 #endif
15943   surface->setFormat(proposedSurfaceFormat);
15944   surface->create();
15945   mGlSurface = QSharedPointer<QSurface>(surface);
15946   mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
15947   mGlContext->setFormat(mGlSurface->format());
15948   if (!mGlContext->create())
15949   {
15950     qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
15951     mGlContext.clear();
15952     mGlSurface.clear();
15953     return false;
15954   }
15955   if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
15956   {
15957     qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
15958     mGlContext.clear();
15959     mGlSurface.clear();
15960     return false;
15961   }
15962   if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
15963   {
15964     qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
15965     mGlContext.clear();
15966     mGlSurface.clear();
15967     return false;
15968   }
15969   mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
15970   return true;
15971 #elif defined(QCP_OPENGL_PBUFFER)
15972   return QGLFormat::hasOpenGL();
15973 #else
15974   return false;
15975 #endif
15976 }
15977 
15978 /*! \internal
15979 
15980   When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
15981   context and frees resources).
15982 
15983   After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
15984   \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
15985   QCPPaintBufferPixmap) is used for subsequent replots.
15986 
15987   \see setupOpenGl
15988 */
15989 void QCustomPlot::freeOpenGl()
15990 {
15991 #ifdef QCP_OPENGL_FBO
15992   mGlPaintDevice.clear();
15993   mGlContext.clear();
15994   mGlSurface.clear();
15995 #endif
15996 }
15997 
15998 /*! \internal
15999   
16000   This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
16001   so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
16002 */
16003 void QCustomPlot::axisRemoved(QCPAxis *axis)
16004 {
16005   if (xAxis == axis)
16006     xAxis = nullptr;
16007   if (xAxis2 == axis)
16008     xAxis2 = nullptr;
16009   if (yAxis == axis)
16010     yAxis = nullptr;
16011   if (yAxis2 == axis)
16012     yAxis2 = nullptr;
16013   
16014   // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
16015 }
16016 
16017 /*! \internal
16018   
16019   This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
16020   it may clear its QCustomPlot::legend member accordingly.
16021 */
16022 void QCustomPlot::legendRemoved(QCPLegend *legend)
16023 {
16024   if (this->legend == legend)
16025     this->legend = nullptr;
16026 }
16027 
16028 /*! \internal
16029   
16030   This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
16031   setSelectionRectMode is set to \ref QCP::srmSelect.
16032 
16033   First, it determines which axis rect was the origin of the selection rect judging by the starting
16034   point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
16035   precise) associated with that axis rect and finds the data points that are in \a rect. It does
16036   this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
16037   
16038   Then, the actual selection is done by calling the plottables' \ref
16039   QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
16040   parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
16041   rect receive a \ref QCPAbstractPlottable::deselectEvent.
16042   
16043   \see processRectZoom
16044 */
16045 void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
16046 {
16047   typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
16048   typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
16049   
16050   bool selectionStateChanged = false;
16051   
16052   if (mInteractions.testFlag(QCP::iSelectPlottables))
16053   {
16054     SelectionCandidates potentialSelections;
16055     QRectF rectF(rect.normalized());
16056     if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
16057     {
16058       // determine plottables that were hit by the rect and thus are candidates for selection:
16059       foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
16060       {
16061         if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
16062         {
16063           QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
16064           if (!dataSel.isEmpty())
16065             potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
16066         }
16067       }
16068       
16069       if (!mInteractions.testFlag(QCP::iMultiSelect))
16070       {
16071         // only leave plottable with most selected points in map, since we will only select a single plottable:
16072         if (!potentialSelections.isEmpty())
16073         {
16074           SelectionCandidates::iterator it = potentialSelections.begin();
16075           while (it != std::prev(potentialSelections.end())) // erase all except last element
16076             it = potentialSelections.erase(it);
16077         }
16078       }
16079       
16080       bool additive = event->modifiers().testFlag(mMultiSelectModifier);
16081       // deselect all other layerables if not additive selection:
16082       if (!additive)
16083       {
16084         // emit deselection except to those plottables who will be selected afterwards:
16085         foreach (QCPLayer *layer, mLayers)
16086         {
16087           foreach (QCPLayerable *layerable, layer->children())
16088           {
16089             if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
16090             {
16091               bool selChanged = false;
16092               layerable->deselectEvent(&selChanged);
16093               selectionStateChanged |= selChanged;
16094             }
16095           }
16096         }
16097       }
16098       
16099       // go through selections in reverse (largest selection first) and emit select events:
16100       SelectionCandidates::const_iterator it = potentialSelections.constEnd();
16101       while (it != potentialSelections.constBegin())
16102       {
16103         --it;
16104         if (mInteractions.testFlag(it.value().first->selectionCategory()))
16105         {
16106           bool selChanged = false;
16107           it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
16108           selectionStateChanged |= selChanged;
16109         }
16110       }
16111     }
16112   }
16113   
16114   if (selectionStateChanged)
16115   {
16116     emit selectionChangedByUser();
16117     replot(rpQueuedReplot);
16118   } else if (mSelectionRect)
16119     mSelectionRect->layer()->replot();
16120 }
16121 
16122 /*! \internal
16123   
16124   This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
16125   setSelectionRectMode is set to \ref QCP::srmZoom.
16126 
16127   It determines which axis rect was the origin of the selection rect judging by the starting point
16128   of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
16129   provided \a rect (see \ref QCPAxisRect::zoom).
16130   
16131   \see processRectSelection
16132 */
16133 void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
16134 {
16135   Q_UNUSED(event)
16136   if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
16137   {
16138     QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
16139     affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
16140     axisRect->zoom(QRectF(rect), affectedAxes);
16141   }
16142   replot(rpQueuedReplot); // always replot to make selection rect disappear
16143 }
16144 
16145 /*! \internal
16146 
16147   This method is called when a simple left mouse click was detected on the QCustomPlot surface.
16148 
16149   It first determines the layerable that was hit by the click, and then calls its \ref
16150   QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
16151   multi-select modifier was pressed, see \ref setMultiSelectModifier).
16152 
16153   In this method the hit layerable is determined a second time using \ref layerableAt (after the
16154   one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
16155   implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
16156   clicked layerable determined here. For example, if a non-selectable layerable is in front of a
16157   selectable layerable at the click position, the front layerable will receive mouse events but the
16158   selectable one in the back will receive the \ref QCPLayerable::selectEvent.
16159 
16160   \see processRectSelection, QCPLayerable::selectTest
16161 */
16162 void QCustomPlot::processPointSelection(QMouseEvent *event)
16163 {
16164   QVariant details;
16165   QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
16166   bool selectionStateChanged = false;
16167   bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
16168   // deselect all other layerables if not additive selection:
16169   if (!additive)
16170   {
16171     foreach (QCPLayer *layer, mLayers)
16172     {
16173       foreach (QCPLayerable *layerable, layer->children())
16174       {
16175         if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
16176         {
16177           bool selChanged = false;
16178           layerable->deselectEvent(&selChanged);
16179           selectionStateChanged |= selChanged;
16180         }
16181       }
16182     }
16183   }
16184   if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
16185   {
16186     // a layerable was actually clicked, call its selectEvent:
16187     bool selChanged = false;
16188     clickedLayerable->selectEvent(event, additive, details, &selChanged);
16189     selectionStateChanged |= selChanged;
16190   }
16191   if (selectionStateChanged)
16192   {
16193     emit selectionChangedByUser();
16194     replot(rpQueuedReplot);
16195   }
16196 }
16197 
16198 /*! \internal
16199   
16200   Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
16201   is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
16202   plottable.
16203   
16204   Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
16205   \a plottable is this QCustomPlot.
16206   
16207   This method is called automatically in the QCPAbstractPlottable base class constructor.
16208 */
16209 bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
16210 {
16211   if (mPlottables.contains(plottable))
16212   {
16213     qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
16214     return false;
16215   }
16216   if (plottable->parentPlot() != this)
16217   {
16218     qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
16219     return false;
16220   }
16221   
16222   mPlottables.append(plottable);
16223   // possibly add plottable to legend:
16224   if (mAutoAddPlottableToLegend)
16225     plottable->addToLegend();
16226   if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
16227     plottable->setLayer(currentLayer());
16228   return true;
16229 }
16230 
16231 /*! \internal
16232   
16233   In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
16234   QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
16235   on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
16236   
16237   This graph specific registration happens in addition to the call to \ref registerPlottable by the
16238   QCPAbstractPlottable base class.
16239 */
16240 bool QCustomPlot::registerGraph(QCPGraph *graph)
16241 {
16242   if (!graph)
16243   {
16244     qDebug() << Q_FUNC_INFO << "passed graph is zero";
16245     return false;
16246   }
16247   if (mGraphs.contains(graph))
16248   {
16249     qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
16250     return false;
16251   }
16252   
16253   mGraphs.append(graph);
16254   return true;
16255 }
16256 
16257 
16258 /*! \internal
16259 
16260   Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
16261   
16262   Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
16263   item is this QCustomPlot.
16264   
16265   This method is called automatically in the QCPAbstractItem base class constructor.
16266 */
16267 bool QCustomPlot::registerItem(QCPAbstractItem *item)
16268 {
16269   if (mItems.contains(item))
16270   {
16271     qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
16272     return false;
16273   }
16274   if (item->parentPlot() != this)
16275   {
16276     qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
16277     return false;
16278   }
16279   
16280   mItems.append(item);
16281   if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
16282     item->setLayer(currentLayer());
16283   return true;
16284 }
16285 
16286 /*! \internal
16287   
16288   Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
16289   after every operation that changes the layer indices, like layer removal, layer creation, layer
16290   moving.
16291 */
16292 void QCustomPlot::updateLayerIndices() const
16293 {
16294   for (int i=0; i<mLayers.size(); ++i)
16295     mLayers.at(i)->mIndex = i;
16296 }
16297 
16298 /*! \internal
16299 
16300   Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
16301   only those layerables that are selectable will be considered. (Layerable subclasses communicate
16302   their selectability via the QCPLayerable::selectTest method, by returning -1.)
16303 
16304   \a selectionDetails is an output parameter that contains selection specifics of the affected
16305   layerable. This is useful if the respective layerable shall be given a subsequent
16306   QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
16307   information about which part of the layerable was hit, in multi-part layerables (e.g.
16308   QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
16309   QCPDataSelection instance with the single data point which is closest to \a pos.
16310   
16311   \see layerableListAt, layoutElementAt, axisRectAt
16312 */
16313 QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
16314 {
16315   QList<QVariant> details;
16316   QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
16317   if (selectionDetails && !details.isEmpty())
16318     *selectionDetails = details.first();
16319   if (!candidates.isEmpty())
16320     return candidates.first();
16321   else
16322     return nullptr;
16323 }
16324 
16325 /*! \internal
16326 
16327   Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
16328   layerables that are selectable will be considered. (Layerable subclasses communicate their
16329   selectability via the QCPLayerable::selectTest method, by returning -1.)
16330 
16331   The returned list is sorted by the layerable/drawing order such that the layerable that appears
16332   on top in the plot is at index 0 of the returned list. If you only need to know the top
16333   layerable, rather use \ref layerableAt.
16334 
16335   \a selectionDetails is an output parameter that contains selection specifics of the affected
16336   layerable. This is useful if the respective layerable shall be given a subsequent
16337   QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
16338   information about which part of the layerable was hit, in multi-part layerables (e.g.
16339   QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
16340   QCPDataSelection instance with the single data point which is closest to \a pos.
16341   
16342   \see layerableAt, layoutElementAt, axisRectAt
16343 */
16344 QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
16345 {
16346   QList<QCPLayerable*> result;
16347   for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
16348   {
16349     const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
16350     for (int i=layerables.size()-1; i>=0; --i)
16351     {
16352       if (!layerables.at(i)->realVisibility())
16353         continue;
16354       QVariant details;
16355       double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
16356       if (dist >= 0 && dist < selectionTolerance())
16357       {
16358         result.append(layerables.at(i));
16359         if (selectionDetails)
16360           selectionDetails->append(details);
16361       }
16362     }
16363   }
16364   return result;
16365 }
16366 
16367 /*!
16368   Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
16369   sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
16370   to a full resolution file with width 200.) If the \a format supports compression, \a quality may
16371   be between 0 and 100 to control it.
16372 
16373   Returns true on success. If this function fails, most likely the given \a format isn't supported
16374   by the system, see Qt docs about QImageWriter::supportedImageFormats().
16375 
16376   The \a resolution will be written to the image file header (if the file format supports this) and
16377   has no direct consequence for the quality or the pixel size. However, if opening the image with a
16378   tool which respects the metadata, it will be able to scale the image to match either a given size
16379   in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
16380   which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
16381   to the format's expected resolution unit internally.
16382 
16383   \see saveBmp, saveJpg, savePng, savePdf
16384 */
16385 bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
16386 {
16387   QImage buffer = toPixmap(width, height, scale).toImage();
16388   
16389   int dotsPerMeter = 0;
16390   switch (resolutionUnit)
16391   {
16392     case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
16393     case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
16394     case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
16395   }
16396   buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
16397   buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
16398   if (!buffer.isNull())
16399     return buffer.save(fileName, format, quality);
16400   else
16401     return false;
16402 }
16403 
16404 /*!
16405   Renders the plot to a pixmap and returns it.
16406   
16407   The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
16408   scale 2.0 lead to a full resolution pixmap with width 200.)
16409   
16410   \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
16411 */
16412 QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
16413 {
16414   // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
16415   int newWidth, newHeight;
16416   if (width == 0 || height == 0)
16417   {
16418     newWidth = this->width();
16419     newHeight = this->height();
16420   } else
16421   {
16422     newWidth = width;
16423     newHeight = height;
16424   }
16425   int scaledWidth = qRound(scale*newWidth);
16426   int scaledHeight = qRound(scale*newHeight);
16427 
16428   QPixmap result(scaledWidth, scaledHeight);
16429   result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
16430   QCPPainter painter;
16431   painter.begin(&result);
16432   if (painter.isActive())
16433   {
16434     QRect oldViewport = viewport();
16435     setViewport(QRect(0, 0, newWidth, newHeight));
16436     painter.setMode(QCPPainter::pmNoCaching);
16437     if (!qFuzzyCompare(scale, 1.0))
16438     {
16439       if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
16440         painter.setMode(QCPPainter::pmNonCosmetic);
16441       painter.scale(scale, scale);
16442     }
16443     if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
16444       painter.fillRect(mViewport, mBackgroundBrush);
16445     draw(&painter);
16446     setViewport(oldViewport);
16447     painter.end();
16448   } else // might happen if pixmap has width or height zero
16449   {
16450     qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
16451     return QPixmap();
16452   }
16453   return result;
16454 }
16455 
16456 /*!
16457   Renders the plot using the passed \a painter.
16458   
16459   The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
16460   appear scaled accordingly.
16461   
16462   \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
16463   on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
16464   the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
16465   
16466   \see toPixmap
16467 */
16468 void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
16469 {
16470   // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
16471   int newWidth, newHeight;
16472   if (width == 0 || height == 0)
16473   {
16474     newWidth = this->width();
16475     newHeight = this->height();
16476   } else
16477   {
16478     newWidth = width;
16479     newHeight = height;
16480   }
16481 
16482   if (painter->isActive())
16483   {
16484     QRect oldViewport = viewport();
16485     setViewport(QRect(0, 0, newWidth, newHeight));
16486     painter->setMode(QCPPainter::pmNoCaching);
16487     if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here
16488       painter->fillRect(mViewport, mBackgroundBrush);
16489     draw(painter);
16490     setViewport(oldViewport);
16491   } else
16492     qDebug() << Q_FUNC_INFO << "Passed painter is not active";
16493 }
16494 /* end of 'src/core.cpp' */
16495 
16496 
16497 /* including file 'src/colorgradient.cpp'   */
16498 /* modified 2021-03-29T02:30:44, size 25278 */
16499 
16500 
16501 ////////////////////////////////////////////////////////////////////////////////////////////////////
16502 //////////////////// QCPColorGradient
16503 ////////////////////////////////////////////////////////////////////////////////////////////////////
16504 
16505 /*! \class QCPColorGradient
16506   \brief Defines a color gradient for use with e.g. \ref QCPColorMap
16507   
16508   This class describes a color gradient which can be used to encode data with color. For example,
16509   QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
16510   take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
16511   with a \a position from 0 to 1. In between these defined color positions, the
16512   color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
16513 
16514   Alternatively, load one of the preset color gradients shown in the image below, with \ref
16515   loadPreset, or by directly specifying the preset in the constructor.
16516   
16517   Apart from red, green and blue components, the gradient also interpolates the alpha values of the
16518   configured color stops. This allows to display some portions of the data range as transparent in
16519   the plot.
16520   
16521   How NaN values are interpreted can be configured with \ref setNanHandling.
16522   
16523   \image html QCPColorGradient.png
16524   
16525   The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
16526   GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
16527   to all the \a setGradient methods, e.g.:
16528   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
16529   
16530   The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
16531   color gradient shall be applied periodically (wrapping around) to data values that lie outside
16532   the data range specified on the plottable instance can be controlled with \ref setPeriodic.
16533 */
16534 
16535 /*!
16536   Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
16537   stops with \ref setColorStopAt.
16538 
16539   The color level count is initialized to 350.
16540 */
16541 QCPColorGradient::QCPColorGradient() :
16542   mLevelCount(350),
16543   mColorInterpolation(ciRGB),
16544   mNanHandling(nhNone),
16545   mNanColor(Qt::black),
16546   mPeriodic(false),
16547   mColorBufferInvalidated(true)
16548 {
16549   mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
16550 }
16551 
16552 /*!
16553   Constructs a new QCPColorGradient initialized with the colors and color interpolation according
16554   to \a preset.
16555 
16556   The color level count is initialized to 350.
16557 */
16558 QCPColorGradient::QCPColorGradient(GradientPreset preset) :
16559   mLevelCount(350),
16560   mColorInterpolation(ciRGB),
16561   mNanHandling(nhNone),
16562   mNanColor(Qt::black),
16563   mPeriodic(false),
16564   mColorBufferInvalidated(true)
16565 {
16566   mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
16567   loadPreset(preset);
16568 }
16569 
16570 /* undocumented operator */
16571 bool QCPColorGradient::operator==(const QCPColorGradient &other) const
16572 {
16573   return ((other.mLevelCount == this->mLevelCount) &&
16574           (other.mColorInterpolation == this->mColorInterpolation) &&
16575           (other.mNanHandling == this ->mNanHandling) &&
16576           (other.mNanColor == this->mNanColor) &&
16577           (other.mPeriodic == this->mPeriodic) &&
16578           (other.mColorStops == this->mColorStops));
16579 }
16580 
16581 /*!
16582   Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
16583   is typically enough to create a smooth appearance. The minimum number of levels is 2.
16584 
16585   \image html QCPColorGradient-levelcount.png
16586 */
16587 void QCPColorGradient::setLevelCount(int n)
16588 {
16589   if (n < 2)
16590   {
16591     qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
16592     n = 2;
16593   }
16594   if (n != mLevelCount)
16595   {
16596     mLevelCount = n;
16597     mColorBufferInvalidated = true;
16598   }
16599 }
16600 
16601 /*!
16602   Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
16603   colors are the values of the passed QMap \a colorStops. In between these color stops, the color
16604   is interpolated according to \ref setColorInterpolation.
16605   
16606   A more convenient way to create a custom gradient may be to clear all color stops with \ref
16607   clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
16608   \ref setColorStopAt.
16609   
16610   \see clearColorStops
16611 */
16612 void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
16613 {
16614   mColorStops = colorStops;
16615   mColorBufferInvalidated = true;
16616 }
16617 
16618 /*!
16619   Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
16620   these color stops, the color is interpolated according to \ref setColorInterpolation.
16621   
16622   \see setColorStops, clearColorStops
16623 */
16624 void QCPColorGradient::setColorStopAt(double position, const QColor &color)
16625 {
16626   mColorStops.insert(position, color);
16627   mColorBufferInvalidated = true;
16628 }
16629 
16630 /*!
16631   Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
16632   interpolated linearly in RGB or in HSV color space.
16633   
16634   For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
16635   whereas in HSV space the intermediate color is yellow.
16636 */
16637 void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
16638 {
16639   if (interpolation != mColorInterpolation)
16640   {
16641     mColorInterpolation = interpolation;
16642     mColorBufferInvalidated = true;
16643   }
16644 }
16645 
16646 /*!
16647   Sets how NaNs in the data are displayed in the plot.
16648   
16649   \see setNanColor
16650 */
16651 void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
16652 {
16653   mNanHandling = handling;
16654 }
16655 
16656 /*!
16657   Sets the color that NaN data is represented by, if \ref setNanHandling is set
16658   to ref nhNanColor.
16659   
16660   \see setNanHandling
16661 */
16662 void QCPColorGradient::setNanColor(const QColor &color)
16663 {
16664   mNanColor = color;
16665 }
16666 
16667 /*!
16668   Sets whether data points that are outside the configured data range (e.g. \ref
16669   QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
16670   they all have the same color, corresponding to the respective gradient boundary color.
16671   
16672   \image html QCPColorGradient-periodic.png
16673   
16674   As shown in the image above, gradients that have the same start and end color are especially
16675   suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
16676   the color map. A preset that has this property is \ref gpHues.
16677   
16678   In practice, using periodic color gradients makes sense when the data corresponds to a periodic
16679   dimension, such as an angle or a phase. If this is not the case, the color encoding might become
16680   ambiguous, because multiple different data values are shown as the same color.
16681 */
16682 void QCPColorGradient::setPeriodic(bool enabled)
16683 {
16684   mPeriodic = enabled;
16685 }
16686 
16687 /*! \overload
16688   
16689   This method is used to quickly convert a \a data array to colors. The colors will be output in
16690   the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
16691   function. The data range that shall be used for mapping the data value to the gradient is passed
16692   in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
16693   logarithmically.
16694 
16695   if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
16696   set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
16697   array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
16698   is addressed <tt>data[i*dataIndexFactor]</tt>.
16699   
16700   Use the overloaded method to additionally provide alpha map data.
16701 
16702   The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
16703   with alpha (see QImage::Format_ARGB32_Premultiplied).
16704 */
16705 void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
16706 {
16707   // If you change something here, make sure to also adapt color() and the other colorize() overload
16708   if (!data)
16709   {
16710     qDebug() << Q_FUNC_INFO << "null pointer given as data";
16711     return;
16712   }
16713   if (!scanLine)
16714   {
16715     qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
16716     return;
16717   }
16718   if (mColorBufferInvalidated)
16719     updateColorBuffer();
16720   
16721   const bool skipNanCheck = mNanHandling == nhNone;
16722   const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
16723   for (int i=0; i<n; ++i)
16724   {
16725     const double value = data[dataIndexFactor*i];
16726     if (skipNanCheck || !std::isnan(value))
16727     {
16728       int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
16729       if (!mPeriodic)
16730       {
16731         index = qBound(0, index, mLevelCount-1);
16732       } else
16733       {
16734         index %= mLevelCount;
16735         if (index < 0)
16736           index += mLevelCount;
16737       }
16738       scanLine[i] = mColorBuffer.at(index);
16739     } else
16740     {
16741       switch(mNanHandling)
16742       {
16743       case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
16744       case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
16745       case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
16746       case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
16747       case nhNone: break; // shouldn't happen
16748       }
16749     }
16750   }
16751 }
16752 
16753 /*! \overload
16754 
16755   Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
16756   has the same size and structure as \a data and encodes the alpha information per data point.
16757 
16758   The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
16759   with alpha (see QImage::Format_ARGB32_Premultiplied).
16760 */
16761 void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
16762 {
16763   // If you change something here, make sure to also adapt color() and the other colorize() overload
16764   if (!data)
16765   {
16766     qDebug() << Q_FUNC_INFO << "null pointer given as data";
16767     return;
16768   }
16769   if (!alpha)
16770   {
16771     qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
16772     return;
16773   }
16774   if (!scanLine)
16775   {
16776     qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
16777     return;
16778   }
16779   if (mColorBufferInvalidated)
16780     updateColorBuffer();
16781   
16782   const bool skipNanCheck = mNanHandling == nhNone;
16783   const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
16784   for (int i=0; i<n; ++i)
16785   {
16786     const double value = data[dataIndexFactor*i];
16787     if (skipNanCheck || !std::isnan(value))
16788     {
16789       int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
16790       if (!mPeriodic)
16791       {
16792         index = qBound(0, index, mLevelCount-1);
16793       } else
16794       {
16795         index %= mLevelCount;
16796         if (index < 0)
16797           index += mLevelCount;
16798       }
16799       if (alpha[dataIndexFactor*i] == 255)
16800       {
16801         scanLine[i] = mColorBuffer.at(index);
16802       } else
16803       {
16804         const QRgb rgb = mColorBuffer.at(index);
16805         const float alphaF = alpha[dataIndexFactor*i]/255.0f;
16806         scanLine[i] = qRgba(int(qRed(rgb)*alphaF), int(qGreen(rgb)*alphaF), int(qBlue(rgb)*alphaF), int(qAlpha(rgb)*alphaF)); // also multiply r,g,b with alpha, to conform to Format_ARGB32_Premultiplied
16807       }
16808     } else
16809     {
16810       switch(mNanHandling)
16811       {
16812       case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
16813       case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
16814       case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
16815       case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
16816       case nhNone: break; // shouldn't happen
16817       }
16818     }
16819   }
16820 }
16821 
16822 /*! \internal
16823 
16824   This method is used to colorize a single data value given in \a position, to colors. The data
16825   range that shall be used for mapping the data value to the gradient is passed in \a range. \a
16826   logarithmic indicates whether the data value shall be mapped to a color logarithmically.
16827 
16828   If an entire array of data values shall be converted, rather use \ref colorize, for better
16829   performance.
16830 
16831   The returned QRgb has its r, g and b components premultiplied with alpha (see
16832   QImage::Format_ARGB32_Premultiplied).
16833 */
16834 QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
16835 {
16836   // If you change something here, make sure to also adapt ::colorize()
16837   if (mColorBufferInvalidated)
16838     updateColorBuffer();
16839   
16840   const bool skipNanCheck = mNanHandling == nhNone;
16841   if (!skipNanCheck && std::isnan(position))
16842   {
16843     switch(mNanHandling)
16844     {
16845     case nhLowestColor: return mColorBuffer.first();
16846     case nhHighestColor: return mColorBuffer.last();
16847     case nhTransparent: return qRgba(0, 0, 0, 0);
16848     case nhNanColor: return mNanColor.rgba();
16849     case nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
16850     }
16851   }
16852   
16853   const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
16854   int index = int((!logarithmic ? position-range.lower : qLn(position/range.lower)) * posToIndexFactor);
16855   if (!mPeriodic)
16856   {
16857     index = qBound(0, index, mLevelCount-1);
16858   } else
16859   {
16860     index %= mLevelCount;
16861     if (index < 0)
16862       index += mLevelCount;
16863   }
16864   return mColorBuffer.at(index);
16865 }
16866 
16867 /*!
16868   Clears the current color stops and loads the specified \a preset. A preset consists of predefined
16869   color stops and the corresponding color interpolation method.
16870   
16871   The available presets are:
16872   \image html QCPColorGradient.png
16873 */
16874 void QCPColorGradient::loadPreset(GradientPreset preset)
16875 {
16876   clearColorStops();
16877   switch (preset)
16878   {
16879     case gpGrayscale:
16880       setColorInterpolation(ciRGB);
16881       setColorStopAt(0, Qt::black);
16882       setColorStopAt(1, Qt::white);
16883       break;
16884     case gpHot:
16885       setColorInterpolation(ciRGB);
16886       setColorStopAt(0, QColor(50, 0, 0));
16887       setColorStopAt(0.2, QColor(180, 10, 0));
16888       setColorStopAt(0.4, QColor(245, 50, 0));
16889       setColorStopAt(0.6, QColor(255, 150, 10));
16890       setColorStopAt(0.8, QColor(255, 255, 50));
16891       setColorStopAt(1, QColor(255, 255, 255));
16892       break;
16893     case gpCold:
16894       setColorInterpolation(ciRGB);
16895       setColorStopAt(0, QColor(0, 0, 50));
16896       setColorStopAt(0.2, QColor(0, 10, 180));
16897       setColorStopAt(0.4, QColor(0, 50, 245));
16898       setColorStopAt(0.6, QColor(10, 150, 255));
16899       setColorStopAt(0.8, QColor(50, 255, 255));
16900       setColorStopAt(1, QColor(255, 255, 255));
16901       break;
16902     case gpNight:
16903       setColorInterpolation(ciHSV);
16904       setColorStopAt(0, QColor(10, 20, 30));
16905       setColorStopAt(1, QColor(250, 255, 250));
16906       break;
16907     case gpCandy:
16908       setColorInterpolation(ciHSV);
16909       setColorStopAt(0, QColor(0, 0, 255));
16910       setColorStopAt(1, QColor(255, 250, 250));
16911       break;
16912     case gpGeography:
16913       setColorInterpolation(ciRGB);
16914       setColorStopAt(0, QColor(70, 170, 210));
16915       setColorStopAt(0.20, QColor(90, 160, 180));
16916       setColorStopAt(0.25, QColor(45, 130, 175));
16917       setColorStopAt(0.30, QColor(100, 140, 125));
16918       setColorStopAt(0.5, QColor(100, 140, 100));
16919       setColorStopAt(0.6, QColor(130, 145, 120));
16920       setColorStopAt(0.7, QColor(140, 130, 120));
16921       setColorStopAt(0.9, QColor(180, 190, 190));
16922       setColorStopAt(1, QColor(210, 210, 230));
16923       break;
16924     case gpIon:
16925       setColorInterpolation(ciHSV);
16926       setColorStopAt(0, QColor(50, 10, 10));
16927       setColorStopAt(0.45, QColor(0, 0, 255));
16928       setColorStopAt(0.8, QColor(0, 255, 255));
16929       setColorStopAt(1, QColor(0, 255, 0));
16930       break;
16931     case gpThermal:
16932       setColorInterpolation(ciRGB);
16933       setColorStopAt(0, QColor(0, 0, 50));
16934       setColorStopAt(0.15, QColor(20, 0, 120));
16935       setColorStopAt(0.33, QColor(200, 30, 140));
16936       setColorStopAt(0.6, QColor(255, 100, 0));
16937       setColorStopAt(0.85, QColor(255, 255, 40));
16938       setColorStopAt(1, QColor(255, 255, 255));
16939       break;
16940     case gpPolar:
16941       setColorInterpolation(ciRGB);
16942       setColorStopAt(0, QColor(50, 255, 255));
16943       setColorStopAt(0.18, QColor(10, 70, 255));
16944       setColorStopAt(0.28, QColor(10, 10, 190));
16945       setColorStopAt(0.5, QColor(0, 0, 0));
16946       setColorStopAt(0.72, QColor(190, 10, 10));
16947       setColorStopAt(0.82, QColor(255, 70, 10));
16948       setColorStopAt(1, QColor(255, 255, 50));
16949       break;
16950     case gpSpectrum:
16951       setColorInterpolation(ciHSV);
16952       setColorStopAt(0, QColor(50, 0, 50));
16953       setColorStopAt(0.15, QColor(0, 0, 255));
16954       setColorStopAt(0.35, QColor(0, 255, 255));
16955       setColorStopAt(0.6, QColor(255, 255, 0));
16956       setColorStopAt(0.75, QColor(255, 30, 0));
16957       setColorStopAt(1, QColor(50, 0, 0));
16958       break;
16959     case gpJet:
16960       setColorInterpolation(ciRGB);
16961       setColorStopAt(0, QColor(0, 0, 100));
16962       setColorStopAt(0.15, QColor(0, 50, 255));
16963       setColorStopAt(0.35, QColor(0, 255, 255));
16964       setColorStopAt(0.65, QColor(255, 255, 0));
16965       setColorStopAt(0.85, QColor(255, 30, 0));
16966       setColorStopAt(1, QColor(100, 0, 0));
16967       break;
16968     case gpHues:
16969       setColorInterpolation(ciHSV);
16970       setColorStopAt(0, QColor(255, 0, 0));
16971       setColorStopAt(1.0/3.0, QColor(0, 0, 255));
16972       setColorStopAt(2.0/3.0, QColor(0, 255, 0));
16973       setColorStopAt(1, QColor(255, 0, 0));
16974       break;
16975   }
16976 }
16977 
16978 /*!
16979   Clears all color stops.
16980   
16981   \see setColorStops, setColorStopAt
16982 */
16983 void QCPColorGradient::clearColorStops()
16984 {
16985   mColorStops.clear();
16986   mColorBufferInvalidated = true;
16987 }
16988 
16989 /*!
16990   Returns an inverted gradient. The inverted gradient has all properties as this \ref
16991   QCPColorGradient, but the order of the color stops is inverted.
16992   
16993   \see setColorStops, setColorStopAt
16994 */
16995 QCPColorGradient QCPColorGradient::inverted() const
16996 {
16997   QCPColorGradient result(*this);
16998   result.clearColorStops();
16999   for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
17000     result.setColorStopAt(1.0-it.key(), it.value());
17001   return result;
17002 }
17003 
17004 /*! \internal
17005   
17006   Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
17007   has an alpha value below 255.
17008 */
17009 bool QCPColorGradient::stopsUseAlpha() const
17010 {
17011   for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
17012   {
17013     if (it.value().alpha() < 255)
17014       return true;
17015   }
17016   return false;
17017 }
17018 
17019 /*! \internal
17020   
17021   Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
17022   convert positions to colors. This is where the interpolation between color stops is calculated.
17023 */
17024 void QCPColorGradient::updateColorBuffer()
17025 {
17026   if (mColorBuffer.size() != mLevelCount)
17027     mColorBuffer.resize(mLevelCount);
17028   if (mColorStops.size() > 1)
17029   {
17030     double indexToPosFactor = 1.0/double(mLevelCount-1);
17031     const bool useAlpha = stopsUseAlpha();
17032     for (int i=0; i<mLevelCount; ++i)
17033     {
17034       double position = i*indexToPosFactor;
17035       QMap<double, QColor>::const_iterator it = const_cast<const QMap<double, QColor> &>(mColorStops).lowerBound(position);
17036       if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
17037       {
17038         if (useAlpha)
17039         {
17040           const QColor col = std::prev(it).value();
17041           const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
17042           mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
17043                                   int(col.green()*alphaPremultiplier),
17044                                   int(col.blue()*alphaPremultiplier),
17045                                   col.alpha());
17046         } else
17047           mColorBuffer[i] = std::prev(it).value().rgba();
17048       } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
17049       {
17050         if (useAlpha)
17051         {
17052           const QColor &col = it.value();
17053           const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
17054           mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
17055                                   int(col.green()*alphaPremultiplier),
17056                                   int(col.blue()*alphaPremultiplier),
17057                                   col.alpha());
17058         } else
17059           mColorBuffer[i] = it.value().rgba();
17060       } else // position is in between stops (or on an intermediate stop), interpolate color
17061       {
17062         QMap<double, QColor>::const_iterator high = it;
17063         QMap<double, QColor>::const_iterator low = std::prev(it);
17064         double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
17065         switch (mColorInterpolation)
17066         {
17067           case ciRGB:
17068           {
17069             if (useAlpha)
17070             {
17071               const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
17072               const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
17073               mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
17074                                       int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
17075                                       int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
17076                                       alpha);
17077             } else
17078             {
17079               mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
17080                                      int( ((1-t)*low.value().green() + t*high.value().green()) ),
17081                                      int( ((1-t)*low.value().blue() + t*high.value().blue())) );
17082             }
17083             break;
17084           }
17085           case ciHSV:
17086           {
17087             QColor lowHsv = low.value().toHsv();
17088             QColor highHsv = high.value().toHsv();
17089             double hue = 0;
17090             double hueDiff = highHsv.hueF()-lowHsv.hueF();
17091             if (hueDiff > 0.5)
17092               hue = lowHsv.hueF() - t*(1.0-hueDiff);
17093             else if (hueDiff < -0.5)
17094               hue = lowHsv.hueF() + t*(1.0+hueDiff);
17095             else
17096               hue = lowHsv.hueF() + t*hueDiff;
17097             if (hue < 0) hue += 1.0;
17098             else if (hue >= 1.0) hue -= 1.0;
17099             if (useAlpha)
17100             {
17101               const QRgb rgb = QColor::fromHsvF(hue,
17102                                                 (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
17103                                                 (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
17104               const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
17105               mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
17106             }
17107             else
17108             {
17109               mColorBuffer[i] = QColor::fromHsvF(hue,
17110                                                  (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
17111                                                  (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
17112             }
17113             break;
17114           }
17115         }
17116       }
17117     }
17118   } else if (mColorStops.size() == 1)
17119   {
17120     const QRgb rgb = mColorStops.constBegin().value().rgb();
17121     const double alpha = mColorStops.constBegin().value().alphaF();
17122     mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
17123   } else // mColorStops is empty, fill color buffer with black
17124   {
17125     mColorBuffer.fill(qRgb(0, 0, 0));
17126   }
17127   mColorBufferInvalidated = false;
17128 }
17129 /* end of 'src/colorgradient.cpp' */
17130 
17131 
17132 /* including file 'src/selectiondecorator-bracket.cpp' */
17133 /* modified 2021-03-29T02:30:44, size 12308            */
17134 
17135 ////////////////////////////////////////////////////////////////////////////////////////////////////
17136 //////////////////// QCPSelectionDecoratorBracket
17137 ////////////////////////////////////////////////////////////////////////////////////////////////////
17138 
17139 /*! \class QCPSelectionDecoratorBracket
17140   \brief A selection decorator which draws brackets around each selected data segment
17141   
17142   Additionally to the regular highlighting of selected segments via color, fill and scatter style,
17143   this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
17144   segment of the plottable.
17145   
17146   The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
17147   \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
17148   setBracketBrush.
17149   
17150   To introduce custom bracket styles, it is only necessary to sublcass \ref
17151   QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
17152   base class.
17153 */
17154 
17155 /*!
17156   Creates a new QCPSelectionDecoratorBracket instance with default values.
17157 */
17158 QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
17159   mBracketPen(QPen(Qt::black)),
17160   mBracketBrush(Qt::NoBrush),
17161   mBracketWidth(5),
17162   mBracketHeight(50),
17163   mBracketStyle(bsSquareBracket),
17164   mTangentToData(false),
17165   mTangentAverage(2)
17166 {
17167   
17168 }
17169 
17170 QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
17171 {
17172 }
17173 
17174 /*!
17175   Sets the pen that will be used to draw the brackets at the beginning and end of each selected
17176   data segment.
17177 */
17178 void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
17179 {
17180   mBracketPen = pen;
17181 }
17182 
17183 /*!
17184   Sets the brush that will be used to draw the brackets at the beginning and end of each selected
17185   data segment.
17186 */
17187 void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
17188 {
17189   mBracketBrush = brush;
17190 }
17191 
17192 /*!
17193   Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
17194   the data, or the tangent direction of the current data slope, if \ref setTangentToData is
17195   enabled.
17196 */
17197 void QCPSelectionDecoratorBracket::setBracketWidth(int width)
17198 {
17199   mBracketWidth = width;
17200 }
17201 
17202 /*!
17203   Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
17204   of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
17205   enabled.
17206 */
17207 void QCPSelectionDecoratorBracket::setBracketHeight(int height)
17208 {
17209   mBracketHeight = height;
17210 }
17211 
17212 /*!
17213   Sets the shape that the bracket/marker will have.
17214   
17215   \see setBracketWidth, setBracketHeight
17216 */
17217 void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
17218 {
17219   mBracketStyle = style;
17220 }
17221 
17222 /*!
17223   Sets whether the brackets will be rotated such that they align with the slope of the data at the
17224   position that they appear in.
17225   
17226   For noisy data, it might be more visually appealing to average the slope over multiple data
17227   points. This can be configured via \ref setTangentAverage.
17228 */
17229 void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
17230 {
17231   mTangentToData = enabled;
17232 }
17233 
17234 /*!
17235   Controls over how many data points the slope shall be averaged, when brackets shall be aligned
17236   with the data (if \ref setTangentToData is true).
17237   
17238   From the position of the bracket, \a pointCount points towards the selected data range will be
17239   taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
17240   disabling \ref setTangentToData.
17241 */
17242 void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
17243 {
17244   mTangentAverage = pointCount;
17245   if (mTangentAverage < 1)
17246     mTangentAverage = 1;
17247 }
17248 
17249 /*!
17250   Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
17251   indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
17252   bracket, respectively).
17253   
17254   The passed \a painter already contains all transformations that are necessary to position and
17255   rotate the bracket appropriately. Painting operations can be performed as if drawing upright
17256   brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
17257   
17258   If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
17259   shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
17260   reimplement.
17261 */
17262 void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
17263 {
17264   switch (mBracketStyle)
17265   {
17266     case bsSquareBracket:
17267     {
17268       painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
17269       painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
17270       painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
17271       break;
17272     }
17273     case bsHalfEllipse:
17274     {
17275       painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
17276       break;
17277     }
17278     case bsEllipse:
17279     {
17280       painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
17281       break;
17282     }
17283     case bsPlus:
17284     {
17285       painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
17286       painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
17287       break;
17288     }
17289     default:
17290     {
17291       qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
17292       break;
17293     }
17294   }
17295 }
17296 
17297 /*!
17298   Draws the bracket decoration on the data points at the begin and end of each selected data
17299   segment given in \a seletion.
17300   
17301   It uses the method \ref drawBracket to actually draw the shapes.
17302   
17303   \seebaseclassmethod
17304 */
17305 void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
17306 {
17307   if (!mPlottable || selection.isEmpty()) return;
17308   
17309   if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
17310   {
17311     foreach (const QCPDataRange &dataRange, selection.dataRanges())
17312     {
17313       // determine position and (if tangent mode is enabled) angle of brackets:
17314       int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
17315       int closeBracketDir = -openBracketDir;
17316       QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
17317       QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
17318       double openBracketAngle = 0;
17319       double closeBracketAngle = 0;
17320       if (mTangentToData)
17321       {
17322         openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
17323         closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
17324       }
17325       // draw opening bracket:
17326       QTransform oldTransform = painter->transform();
17327       painter->setPen(mBracketPen);
17328       painter->setBrush(mBracketBrush);
17329       painter->translate(openBracketPos);
17330       painter->rotate(openBracketAngle/M_PI*180.0);
17331       drawBracket(painter, openBracketDir);
17332       painter->setTransform(oldTransform);
17333       // draw closing bracket:
17334       painter->setPen(mBracketPen);
17335       painter->setBrush(mBracketBrush);
17336       painter->translate(closeBracketPos);
17337       painter->rotate(closeBracketAngle/M_PI*180.0);
17338       drawBracket(painter, closeBracketDir);
17339       painter->setTransform(oldTransform);
17340     }
17341   }
17342 }
17343 
17344 /*! \internal
17345   
17346   If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
17347   This method returns the angle in radians by which a bracket at the given \a dataIndex must be
17348   rotated.
17349   
17350   The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
17351   or closing bracket. Since for slope calculation multiple data points are required, this defines
17352   the direction in which the algorithm walks, starting at \a dataIndex, to average those data
17353   points. (see \ref setTangentToData and \ref setTangentAverage)
17354   
17355   \a interface1d is the interface to the plottable's data which is used to query data coordinates.
17356 */
17357 double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
17358 {
17359   if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
17360     return 0;
17361   direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
17362   
17363   // how many steps we can actually go from index in the given direction without exceeding data bounds:
17364   int averageCount;
17365   if (direction < 0)
17366     averageCount = qMin(mTangentAverage, dataIndex);
17367   else
17368     averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
17369   qDebug() << averageCount;
17370   // calculate point average of averageCount points:
17371   QVector<QPointF> points(averageCount);
17372   QPointF pointsAverage;
17373   int currentIndex = dataIndex;
17374   for (int i=0; i<averageCount; ++i)
17375   {
17376     points[i] = getPixelCoordinates(interface1d, currentIndex);
17377     pointsAverage += points[i];
17378     currentIndex += direction;
17379   }
17380   pointsAverage /= double(averageCount);
17381   
17382   // calculate slope of linear regression through points:
17383   double numSum = 0;
17384   double denomSum = 0;
17385   for (int i=0; i<averageCount; ++i)
17386   {
17387     const double dx = points.at(i).x()-pointsAverage.x();
17388     const double dy = points.at(i).y()-pointsAverage.y();
17389     numSum += dx*dy;
17390     denomSum += dx*dx;
17391   }
17392   if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
17393   {
17394     return qAtan2(numSum, denomSum);
17395   } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
17396     return 0;
17397 }
17398 
17399 /*! \internal
17400   
17401   Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
17402   the data points.
17403 */
17404 QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
17405 {
17406   QCPAxis *keyAxis = mPlottable->keyAxis();
17407   QCPAxis *valueAxis = mPlottable->valueAxis();
17408   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
17409   
17410   if (keyAxis->orientation() == Qt::Horizontal)
17411     return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
17412   else
17413     return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
17414 }
17415 /* end of 'src/selectiondecorator-bracket.cpp' */
17416 
17417 
17418 /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
17419 /* modified 2021-03-29T02:30:44, size 47193                       */
17420 
17421 
17422 ////////////////////////////////////////////////////////////////////////////////////////////////////
17423 //////////////////// QCPAxisRect
17424 ////////////////////////////////////////////////////////////////////////////////////////////////////
17425 
17426 /*! \class QCPAxisRect
17427   \brief Holds multiple axes and arranges them in a rectangular shape.
17428   
17429   This class represents an axis rect, a rectangular area that is bounded on all sides with an
17430   arbitrary number of axes.
17431   
17432   Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
17433   layout system allows to have multiple axis rects, e.g. arranged in a grid layout
17434   (QCustomPlot::plotLayout).
17435   
17436   By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
17437   accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
17438   If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
17439   invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
17440   addAxes. To remove an axis, use \ref removeAxis.
17441   
17442   The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
17443   setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
17444   explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
17445   placed on other layers, independently of the axis rect.
17446   
17447   Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
17448   insetLayout and can be used to have other layout elements (or even other layouts with multiple
17449   elements) hovering inside the axis rect.
17450   
17451   If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
17452   behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
17453   is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
17454   via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
17455   only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
17456   QCP::iRangeZoom.
17457   
17458   \image html AxisRectSpacingOverview.png
17459   <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
17460   line on the far left indicates the viewport/widget border.</center>
17461 */
17462 
17463 /* start documentation of inline functions */
17464 
17465 /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
17466   
17467   Returns the inset layout of this axis rect. It can be used to place other layout elements (or
17468   even layouts with multiple other elements) inside/on top of an axis rect.
17469   
17470   \see QCPLayoutInset
17471 */
17472 
17473 /*! \fn int QCPAxisRect::left() const
17474   
17475   Returns the pixel position of the left border of this axis rect. Margins are not taken into
17476   account here, so the returned value is with respect to the inner \ref rect.
17477 */
17478 
17479 /*! \fn int QCPAxisRect::right() const
17480   
17481   Returns the pixel position of the right border of this axis rect. Margins are not taken into
17482   account here, so the returned value is with respect to the inner \ref rect.
17483 */
17484 
17485 /*! \fn int QCPAxisRect::top() const
17486   
17487   Returns the pixel position of the top border of this axis rect. Margins are not taken into
17488   account here, so the returned value is with respect to the inner \ref rect.
17489 */
17490 
17491 /*! \fn int QCPAxisRect::bottom() const
17492   
17493   Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
17494   account here, so the returned value is with respect to the inner \ref rect.
17495 */
17496 
17497 /*! \fn int QCPAxisRect::width() const
17498   
17499   Returns the pixel width of this axis rect. Margins are not taken into account here, so the
17500   returned value is with respect to the inner \ref rect.
17501 */
17502 
17503 /*! \fn int QCPAxisRect::height() const
17504   
17505   Returns the pixel height of this axis rect. Margins are not taken into account here, so the
17506   returned value is with respect to the inner \ref rect.
17507 */
17508 
17509 /*! \fn QSize QCPAxisRect::size() const
17510   
17511   Returns the pixel size of this axis rect. Margins are not taken into account here, so the
17512   returned value is with respect to the inner \ref rect.
17513 */
17514 
17515 /*! \fn QPoint QCPAxisRect::topLeft() const
17516   
17517   Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
17518   so the returned value is with respect to the inner \ref rect.
17519 */
17520 
17521 /*! \fn QPoint QCPAxisRect::topRight() const
17522   
17523   Returns the top right corner of this axis rect in pixels. Margins are not taken into account
17524   here, so the returned value is with respect to the inner \ref rect.
17525 */
17526 
17527 /*! \fn QPoint QCPAxisRect::bottomLeft() const
17528   
17529   Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
17530   here, so the returned value is with respect to the inner \ref rect.
17531 */
17532 
17533 /*! \fn QPoint QCPAxisRect::bottomRight() const
17534   
17535   Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
17536   here, so the returned value is with respect to the inner \ref rect.
17537 */
17538 
17539 /*! \fn QPoint QCPAxisRect::center() const
17540   
17541   Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
17542   returned value is with respect to the inner \ref rect.
17543 */
17544 
17545 /* end documentation of inline functions */
17546 
17547 /*!
17548   Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
17549   sides, the top and right axes are set invisible initially.
17550 */
17551 QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
17552   QCPLayoutElement(parentPlot),
17553   mBackgroundBrush(Qt::NoBrush),
17554   mBackgroundScaled(true),
17555   mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
17556   mInsetLayout(new QCPLayoutInset),
17557   mRangeDrag(Qt::Horizontal|Qt::Vertical),
17558   mRangeZoom(Qt::Horizontal|Qt::Vertical),
17559   mRangeZoomFactorHorz(0.85),
17560   mRangeZoomFactorVert(0.85),
17561   mDragging(false)
17562 {
17563   mInsetLayout->initializeParentPlot(mParentPlot);
17564   mInsetLayout->setParentLayerable(this);
17565   mInsetLayout->setParent(this);
17566   
17567   setMinimumSize(50, 50);
17568   setMinimumMargins(QMargins(15, 15, 15, 15));
17569   mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
17570   mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
17571   mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
17572   mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
17573   
17574   if (setupDefaultAxes)
17575   {
17576     QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
17577     QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
17578     QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
17579     QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
17580     setRangeDragAxes(xAxis, yAxis);
17581     setRangeZoomAxes(xAxis, yAxis);
17582     xAxis2->setVisible(false);
17583     yAxis2->setVisible(false);
17584     xAxis->grid()->setVisible(true);
17585     yAxis->grid()->setVisible(true);
17586     xAxis2->grid()->setVisible(false);
17587     yAxis2->grid()->setVisible(false);
17588     xAxis2->grid()->setZeroLinePen(Qt::NoPen);
17589     yAxis2->grid()->setZeroLinePen(Qt::NoPen);
17590     xAxis2->grid()->setVisible(false);
17591     yAxis2->grid()->setVisible(false);
17592   }
17593 }
17594 
17595 QCPAxisRect::~QCPAxisRect()
17596 {
17597   delete mInsetLayout;
17598   mInsetLayout = nullptr;
17599   
17600   foreach (QCPAxis *axis, axes())
17601     removeAxis(axis);
17602 }
17603 
17604 /*!
17605   Returns the number of axes on the axis rect side specified with \a type.
17606   
17607   \see axis
17608 */
17609 int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
17610 {
17611   return mAxes.value(type).size();
17612 }
17613 
17614 /*!
17615   Returns the axis with the given \a index on the axis rect side specified with \a type.
17616   
17617   \see axisCount, axes
17618 */
17619 QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
17620 {
17621   QList<QCPAxis*> ax(mAxes.value(type));
17622   if (index >= 0 && index < ax.size())
17623   {
17624     return ax.at(index);
17625   } else
17626   {
17627     qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
17628     return nullptr;
17629   }
17630 }
17631 
17632 /*!
17633   Returns all axes on the axis rect sides specified with \a types.
17634   
17635   \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
17636   multiple sides.
17637   
17638   \see axis
17639 */
17640 QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
17641 {
17642   QList<QCPAxis*> result;
17643   if (types.testFlag(QCPAxis::atLeft))
17644     result << mAxes.value(QCPAxis::atLeft);
17645   if (types.testFlag(QCPAxis::atRight))
17646     result << mAxes.value(QCPAxis::atRight);
17647   if (types.testFlag(QCPAxis::atTop))
17648     result << mAxes.value(QCPAxis::atTop);
17649   if (types.testFlag(QCPAxis::atBottom))
17650     result << mAxes.value(QCPAxis::atBottom);
17651   return result;
17652 }
17653 
17654 /*! \overload
17655   
17656   Returns all axes of this axis rect.
17657 */
17658 QList<QCPAxis*> QCPAxisRect::axes() const
17659 {
17660   QList<QCPAxis*> result;
17661   QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
17662   while (it.hasNext())
17663   {
17664     it.next();
17665     result << it.value();
17666   }
17667   return result;
17668 }
17669 
17670 /*!
17671   Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
17672   new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
17673   remove an axis, use \ref removeAxis instead of deleting it manually.
17674 
17675   You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
17676   previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
17677   of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
17678   with this axis rect as parent and with the same axis type as specified in \a type. If this is not
17679   the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
17680 
17681   This method can not be used to move \a axis between axis rects. The same \a axis instance must
17682   not be added multiple times to the same or different axis rects.
17683 
17684   If an axis rect side already contains one or more axes, the lower and upper endings of the new
17685   axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
17686   QCPLineEnding::esHalfBar.
17687 
17688   \see addAxes, setupFullAxesBox
17689 */
17690 QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
17691 {
17692   QCPAxis *newAxis = axis;
17693   if (!newAxis)
17694   {
17695     newAxis = new QCPAxis(this, type);
17696   } else // user provided existing axis instance, do some sanity checks
17697   {
17698     if (newAxis->axisType() != type)
17699     {
17700       qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
17701       return nullptr;
17702     }
17703     if (newAxis->axisRect() != this)
17704     {
17705       qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
17706       return nullptr;
17707     }
17708     if (axes().contains(newAxis))
17709     {
17710       qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
17711       return nullptr;
17712     }
17713   }
17714   if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
17715   {
17716     bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
17717     newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
17718     newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
17719   }
17720   mAxes[type].append(newAxis);
17721   
17722   // reset convenience axis pointers on parent QCustomPlot if they are unset:
17723   if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
17724   {
17725     switch (type)
17726     {
17727       case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
17728       case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
17729       case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
17730       case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
17731     }
17732   }
17733   
17734   return newAxis;
17735 }
17736 
17737 /*!
17738   Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
17739   <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
17740   
17741   Returns a list of the added axes.
17742   
17743   \see addAxis, setupFullAxesBox
17744 */
17745 QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
17746 {
17747   QList<QCPAxis*> result;
17748   if (types.testFlag(QCPAxis::atLeft))
17749     result << addAxis(QCPAxis::atLeft);
17750   if (types.testFlag(QCPAxis::atRight))
17751     result << addAxis(QCPAxis::atRight);
17752   if (types.testFlag(QCPAxis::atTop))
17753     result << addAxis(QCPAxis::atTop);
17754   if (types.testFlag(QCPAxis::atBottom))
17755     result << addAxis(QCPAxis::atBottom);
17756   return result;
17757 }
17758 
17759 /*!
17760   Removes the specified \a axis from the axis rect and deletes it.
17761   
17762   Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
17763   
17764   \see addAxis
17765 */
17766 bool QCPAxisRect::removeAxis(QCPAxis *axis)
17767 {
17768   // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
17769   QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
17770   while (it.hasNext())
17771   {
17772     it.next();
17773     if (it.value().contains(axis))
17774     {
17775       if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists)
17776         it.value()[1]->setOffset(axis->offset());
17777       mAxes[it.key()].removeOne(axis);
17778       if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
17779         parentPlot()->axisRemoved(axis);
17780       delete axis;
17781       return true;
17782     }
17783   }
17784   qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
17785   return false;
17786 }
17787 
17788 /*!
17789   Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
17790 
17791   All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
17792   specific axes, use the overloaded version of this method.
17793   
17794   \see QCustomPlot::setSelectionRectMode
17795 */
17796 void QCPAxisRect::zoom(const QRectF &pixelRect)
17797 {
17798   zoom(pixelRect, axes());
17799 }
17800 
17801 /*! \overload
17802   
17803   Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
17804   
17805   Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
17806   
17807   \see QCustomPlot::setSelectionRectMode
17808 */
17809 void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
17810 {
17811   foreach (QCPAxis *axis, affectedAxes)
17812   {
17813     if (!axis)
17814     {
17815       qDebug() << Q_FUNC_INFO << "a passed axis was zero";
17816       continue;
17817     }
17818     QCPRange pixelRange;
17819     if (axis->orientation() == Qt::Horizontal)
17820       pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
17821     else
17822       pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
17823     axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
17824   }
17825 }
17826 
17827 /*!
17828   Convenience function to create an axis on each side that doesn't have any axes yet and set their
17829   visibility to true. Further, the top/right axes are assigned the following properties of the
17830   bottom/left axes:
17831 
17832   \li range (\ref QCPAxis::setRange)
17833   \li range reversed (\ref QCPAxis::setRangeReversed)
17834   \li scale type (\ref QCPAxis::setScaleType)
17835   \li tick visibility (\ref QCPAxis::setTicks)
17836   \li number format (\ref QCPAxis::setNumberFormat)
17837   \li number precision (\ref QCPAxis::setNumberPrecision)
17838   \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
17839   \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
17840 
17841   Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
17842 
17843   If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
17844   and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
17845 */
17846 void QCPAxisRect::setupFullAxesBox(bool connectRanges)
17847 {
17848   QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
17849   if (axisCount(QCPAxis::atBottom) == 0)
17850     xAxis = addAxis(QCPAxis::atBottom);
17851   else
17852     xAxis = axis(QCPAxis::atBottom);
17853   
17854   if (axisCount(QCPAxis::atLeft) == 0)
17855     yAxis = addAxis(QCPAxis::atLeft);
17856   else
17857     yAxis = axis(QCPAxis::atLeft);
17858   
17859   if (axisCount(QCPAxis::atTop) == 0)
17860     xAxis2 = addAxis(QCPAxis::atTop);
17861   else
17862     xAxis2 = axis(QCPAxis::atTop);
17863   
17864   if (axisCount(QCPAxis::atRight) == 0)
17865     yAxis2 = addAxis(QCPAxis::atRight);
17866   else
17867     yAxis2 = axis(QCPAxis::atRight);
17868   
17869   xAxis->setVisible(true);
17870   yAxis->setVisible(true);
17871   xAxis2->setVisible(true);
17872   yAxis2->setVisible(true);
17873   xAxis2->setTickLabels(false);
17874   yAxis2->setTickLabels(false);
17875   
17876   xAxis2->setRange(xAxis->range());
17877   xAxis2->setRangeReversed(xAxis->rangeReversed());
17878   xAxis2->setScaleType(xAxis->scaleType());
17879   xAxis2->setTicks(xAxis->ticks());
17880   xAxis2->setNumberFormat(xAxis->numberFormat());
17881   xAxis2->setNumberPrecision(xAxis->numberPrecision());
17882   xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
17883   xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
17884   
17885   yAxis2->setRange(yAxis->range());
17886   yAxis2->setRangeReversed(yAxis->rangeReversed());
17887   yAxis2->setScaleType(yAxis->scaleType());
17888   yAxis2->setTicks(yAxis->ticks());
17889   yAxis2->setNumberFormat(yAxis->numberFormat());
17890   yAxis2->setNumberPrecision(yAxis->numberPrecision());
17891   yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
17892   yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
17893   
17894   if (connectRanges)
17895   {
17896     connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
17897     connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
17898   }
17899 }
17900 
17901 /*!
17902   Returns a list of all the plottables that are associated with this axis rect.
17903   
17904   A plottable is considered associated with an axis rect if its key or value axis (or both) is in
17905   this axis rect.
17906   
17907   \see graphs, items
17908 */
17909 QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
17910 {
17911   // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
17912   QList<QCPAbstractPlottable*> result;
17913   foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
17914   {
17915     if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
17916       result.append(plottable);
17917   }
17918   return result;
17919 }
17920 
17921 /*!
17922   Returns a list of all the graphs that are associated with this axis rect.
17923   
17924   A graph is considered associated with an axis rect if its key or value axis (or both) is in
17925   this axis rect.
17926   
17927   \see plottables, items
17928 */
17929 QList<QCPGraph*> QCPAxisRect::graphs() const
17930 {
17931   // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
17932   QList<QCPGraph*> result;
17933   foreach (QCPGraph *graph, mParentPlot->mGraphs)
17934   {
17935     if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
17936       result.append(graph);
17937   }
17938   return result;
17939 }
17940 
17941 /*!
17942   Returns a list of all the items that are associated with this axis rect.
17943   
17944   An item is considered associated with an axis rect if any of its positions has key or value axis
17945   set to an axis that is in this axis rect, or if any of its positions has \ref
17946   QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
17947   QCPAbstractItem::setClipAxisRect) is set to this axis rect.
17948   
17949   \see plottables, graphs
17950 */
17951 QList<QCPAbstractItem *> QCPAxisRect::items() const
17952 {
17953   // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
17954   //       and miss those items that have this axis rect as clipAxisRect.
17955   QList<QCPAbstractItem*> result;
17956   foreach (QCPAbstractItem *item, mParentPlot->mItems)
17957   {
17958     if (item->clipAxisRect() == this)
17959     {
17960       result.append(item);
17961       continue;
17962     }
17963     foreach (QCPItemPosition *position, item->positions())
17964     {
17965       if (position->axisRect() == this ||
17966           position->keyAxis()->axisRect() == this ||
17967           position->valueAxis()->axisRect() == this)
17968       {
17969         result.append(item);
17970         break;
17971       }
17972     }
17973   }
17974   return result;
17975 }
17976 
17977 /*!
17978   This method is called automatically upon replot and doesn't need to be called by users of
17979   QCPAxisRect.
17980   
17981   Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
17982   and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
17983   QCPInsetLayout::update function.
17984   
17985   \seebaseclassmethod
17986 */
17987 void QCPAxisRect::update(UpdatePhase phase)
17988 {
17989   QCPLayoutElement::update(phase);
17990   
17991   switch (phase)
17992   {
17993     case upPreparation:
17994     {
17995       foreach (QCPAxis *axis, axes())
17996         axis->setupTickVectors();
17997       break;
17998     }
17999     case upLayout:
18000     {
18001       mInsetLayout->setOuterRect(rect());
18002       break;
18003     }
18004     default: break;
18005   }
18006   
18007   // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
18008   mInsetLayout->update(phase);
18009 }
18010 
18011 /* inherits documentation from base class */
18012 QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
18013 {
18014   QList<QCPLayoutElement*> result;
18015   if (mInsetLayout)
18016   {
18017     result << mInsetLayout;
18018     if (recursive)
18019       result << mInsetLayout->elements(recursive);
18020   }
18021   return result;
18022 }
18023 
18024 /* inherits documentation from base class */
18025 void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
18026 {
18027   painter->setAntialiasing(false);
18028 }
18029 
18030 /* inherits documentation from base class */
18031 void QCPAxisRect::draw(QCPPainter *painter)
18032 {
18033   drawBackground(painter);
18034 }
18035 
18036 /*!
18037   Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
18038   axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
18039   backgrounds are usually drawn below everything else.
18040 
18041   For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
18042   enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
18043   is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
18044   consider using the overloaded version of this function.
18045 
18046   Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
18047   setBackground(const QBrush &brush).
18048   
18049   \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
18050 */
18051 void QCPAxisRect::setBackground(const QPixmap &pm)
18052 {
18053   mBackgroundPixmap = pm;
18054   mScaledBackgroundPixmap = QPixmap();
18055 }
18056 
18057 /*! \overload
18058   
18059   Sets \a brush as the background brush. The axis rect background will be filled with this brush.
18060   Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
18061   are usually drawn below everything else.
18062 
18063   The brush will be drawn before (under) any background pixmap, which may be specified with \ref
18064   setBackground(const QPixmap &pm).
18065 
18066   To disable drawing of a background brush, set \a brush to Qt::NoBrush.
18067   
18068   \see setBackground(const QPixmap &pm)
18069 */
18070 void QCPAxisRect::setBackground(const QBrush &brush)
18071 {
18072   mBackgroundBrush = brush;
18073 }
18074 
18075 /*! \overload
18076   
18077   Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
18078   shall be scaled in one call.
18079 
18080   \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
18081 */
18082 void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
18083 {
18084   mBackgroundPixmap = pm;
18085   mScaledBackgroundPixmap = QPixmap();
18086   mBackgroundScaled = scaled;
18087   mBackgroundScaledMode = mode;
18088 }
18089 
18090 /*!
18091   Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
18092   is set to true, you may control whether and how the aspect ratio of the original pixmap is
18093   preserved with \ref setBackgroundScaledMode.
18094   
18095   Note that the scaled version of the original pixmap is buffered, so there is no performance
18096   penalty on replots. (Except when the axis rect dimensions are changed continuously.)
18097   
18098   \see setBackground, setBackgroundScaledMode
18099 */
18100 void QCPAxisRect::setBackgroundScaled(bool scaled)
18101 {
18102   mBackgroundScaled = scaled;
18103 }
18104 
18105 /*!
18106   If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
18107   define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
18108   \see setBackground, setBackgroundScaled
18109 */
18110 void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
18111 {
18112   mBackgroundScaledMode = mode;
18113 }
18114 
18115 /*!
18116   Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
18117   the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
18118 
18119   \see setRangeDragAxes
18120 */
18121 QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
18122 {
18123   if (orientation == Qt::Horizontal)
18124     return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
18125   else
18126     return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
18127 }
18128 
18129 /*!
18130   Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
18131   the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
18132 
18133   \see setRangeZoomAxes
18134 */
18135 QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
18136 {
18137   if (orientation == Qt::Horizontal)
18138     return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
18139   else
18140     return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
18141 }
18142 
18143 /*!
18144   Returns all range drag axes of the \a orientation provided.
18145 
18146   \see rangeZoomAxis, setRangeZoomAxes
18147 */
18148 QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
18149 {
18150   QList<QCPAxis*> result;
18151   if (orientation == Qt::Horizontal)
18152   {
18153     foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
18154     {
18155       if (!axis.isNull())
18156         result.append(axis.data());
18157     }
18158   } else
18159   {
18160     foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
18161     {
18162       if (!axis.isNull())
18163         result.append(axis.data());
18164     }
18165   }
18166   return result;
18167 }
18168 
18169 /*!
18170   Returns all range zoom axes of the \a orientation provided.
18171 
18172   \see rangeDragAxis, setRangeDragAxes
18173 */
18174 QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
18175 {
18176   QList<QCPAxis*> result;
18177   if (orientation == Qt::Horizontal)
18178   {
18179     foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
18180     {
18181       if (!axis.isNull())
18182         result.append(axis.data());
18183     }
18184   } else
18185   {
18186     foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
18187     {
18188       if (!axis.isNull())
18189         result.append(axis.data());
18190     }
18191   }
18192   return result;
18193 }
18194 
18195 /*!
18196   Returns the range zoom factor of the \a orientation provided.
18197   
18198   \see setRangeZoomFactor
18199 */
18200 double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
18201 {
18202   return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
18203 }
18204 
18205 /*!
18206   Sets which axis orientation may be range dragged by the user with mouse interaction.
18207   What orientation corresponds to which specific axis can be set with
18208   \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
18209   default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
18210   is the left axis (yAxis).
18211   
18212   To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
18213   QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
18214   directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
18215   
18216   In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
18217   contains \ref QCP::iRangeDrag to enable the range dragging interaction.
18218   
18219   \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
18220 */
18221 void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
18222 {
18223   mRangeDrag = orientations;
18224 }
18225 
18226 /*!
18227   Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
18228   corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
18229   QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
18230   axis is the left axis (yAxis).
18231 
18232   To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
18233   QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
18234   directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
18235   
18236   In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
18237   contains \ref QCP::iRangeZoom to enable the range zooming interaction.
18238   
18239   \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
18240 */
18241 void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
18242 {
18243   mRangeZoom = orientations;
18244 }
18245 
18246 /*! \overload
18247   
18248   Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
18249   the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
18250   orientation.
18251 
18252   Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
18253   react to dragging interactions.
18254 
18255   \see setRangeZoomAxes
18256 */
18257 void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
18258 {
18259   QList<QCPAxis*> horz, vert;
18260   if (horizontal)
18261     horz.append(horizontal);
18262   if (vertical)
18263     vert.append(vertical);
18264   setRangeDragAxes(horz, vert);
18265 }
18266 
18267 /*! \overload
18268 
18269   This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
18270   orientation that the respective axis will react to is deduced from its orientation (\ref
18271   QCPAxis::orientation).
18272 
18273   In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
18274   motion, use the overload taking two separate lists for horizontal and vertical dragging.
18275 */
18276 void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
18277 {
18278   QList<QCPAxis*> horz, vert;
18279   foreach (QCPAxis *ax, axes)
18280   {
18281     if (ax->orientation() == Qt::Horizontal)
18282       horz.append(ax);
18283     else
18284       vert.append(ax);
18285   }
18286   setRangeDragAxes(horz, vert);
18287 }
18288 
18289 /*! \overload
18290 
18291   This method allows to set multiple axes up to react to horizontal and vertical dragging, and
18292   define specifically which axis reacts to which drag orientation (irrespective of the axis
18293   orientation).
18294 */
18295 void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
18296 {
18297   mRangeDragHorzAxis.clear();
18298   foreach (QCPAxis *ax, horizontal)
18299   {
18300     QPointer<QCPAxis> axPointer(ax);
18301     if (!axPointer.isNull())
18302       mRangeDragHorzAxis.append(axPointer);
18303     else
18304       qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
18305   }
18306   mRangeDragVertAxis.clear();
18307   foreach (QCPAxis *ax, vertical)
18308   {
18309     QPointer<QCPAxis> axPointer(ax);
18310     if (!axPointer.isNull())
18311       mRangeDragVertAxis.append(axPointer);
18312     else
18313       qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
18314   }
18315 }
18316 
18317 /*!
18318   Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
18319   the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
18320 
18321   The two axes can be zoomed with different strengths, when different factors are passed to \ref
18322   setRangeZoomFactor(double horizontalFactor, double verticalFactor).
18323 
18324   Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
18325   react to zooming interactions.
18326 
18327   \see setRangeDragAxes
18328 */
18329 void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
18330 {
18331   QList<QCPAxis*> horz, vert;
18332   if (horizontal)
18333     horz.append(horizontal);
18334   if (vertical)
18335     vert.append(vertical);
18336   setRangeZoomAxes(horz, vert);
18337 }
18338 
18339 /*! \overload
18340 
18341   This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
18342   zoom orientation that the respective axis will react to is deduced from its orientation (\ref
18343   QCPAxis::orientation).
18344 
18345   In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
18346   interaction, use the overload taking two separate lists for horizontal and vertical zooming.
18347 */
18348 void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
18349 {
18350   QList<QCPAxis*> horz, vert;
18351   foreach (QCPAxis *ax, axes)
18352   {
18353     if (ax->orientation() == Qt::Horizontal)
18354       horz.append(ax);
18355     else
18356       vert.append(ax);
18357   }
18358   setRangeZoomAxes(horz, vert);
18359 }
18360 
18361 /*! \overload
18362 
18363   This method allows to set multiple axes up to react to horizontal and vertical zooming, and
18364   define specifically which axis reacts to which zoom orientation (irrespective of the axis
18365   orientation).
18366 */
18367 void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
18368 {
18369   mRangeZoomHorzAxis.clear();
18370   foreach (QCPAxis *ax, horizontal)
18371   {
18372     QPointer<QCPAxis> axPointer(ax);
18373     if (!axPointer.isNull())
18374       mRangeZoomHorzAxis.append(axPointer);
18375     else
18376       qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
18377   }
18378   mRangeZoomVertAxis.clear();
18379   foreach (QCPAxis *ax, vertical)
18380   {
18381     QPointer<QCPAxis> axPointer(ax);
18382     if (!axPointer.isNull())
18383       mRangeZoomVertAxis.append(axPointer);
18384     else
18385       qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
18386   }
18387 }
18388 
18389 /*!
18390   Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
18391   \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
18392   let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
18393   and which is vertical, can be set with \ref setRangeZoomAxes.
18394 
18395   When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
18396   will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
18397   same scrolling direction will zoom out.
18398 */
18399 void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
18400 {
18401   mRangeZoomFactorHorz = horizontalFactor;
18402   mRangeZoomFactorVert = verticalFactor;
18403 }
18404 
18405 /*! \overload
18406   
18407   Sets both the horizontal and vertical zoom \a factor.
18408 */
18409 void QCPAxisRect::setRangeZoomFactor(double factor)
18410 {
18411   mRangeZoomFactorHorz = factor;
18412   mRangeZoomFactorVert = factor;
18413 }
18414 
18415 /*! \internal
18416   
18417   Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
18418   pixmap.
18419   
18420   If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
18421   according filling inside the axis rect with the provided \a painter.
18422   
18423   Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
18424   depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
18425   the axis rect with the provided \a painter. The scaled version is buffered in
18426   mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
18427   the axis rect has changed in a way that requires a rescale of the background pixmap (this is
18428   dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
18429   set.
18430   
18431   \see setBackground, setBackgroundScaled, setBackgroundScaledMode
18432 */
18433 void QCPAxisRect::drawBackground(QCPPainter *painter)
18434 {
18435   // draw background fill:
18436   if (mBackgroundBrush != Qt::NoBrush)
18437     painter->fillRect(mRect, mBackgroundBrush);
18438   
18439   // draw background pixmap (on top of fill, if brush specified):
18440   if (!mBackgroundPixmap.isNull())
18441   {
18442     if (mBackgroundScaled)
18443     {
18444       // check whether mScaledBackground needs to be updated:
18445       QSize scaledSize(mBackgroundPixmap.size());
18446       scaledSize.scale(mRect.size(), mBackgroundScaledMode);
18447       if (mScaledBackgroundPixmap.size() != scaledSize)
18448         mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
18449       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
18450     } else
18451     {
18452       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
18453     }
18454   }
18455 }
18456 
18457 /*! \internal
18458   
18459   This function makes sure multiple axes on the side specified with \a type don't collide, but are
18460   distributed according to their respective space requirement (QCPAxis::calculateMargin).
18461   
18462   It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
18463   one with index zero.
18464   
18465   This function is called by \ref calculateAutoMargin.
18466 */
18467 void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
18468 {
18469   const QList<QCPAxis*> axesList = mAxes.value(type);
18470   if (axesList.isEmpty())
18471     return;
18472   
18473   bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false
18474   for (int i=1; i<axesList.size(); ++i)
18475   {
18476     int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
18477     if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible)
18478     {
18479       if (!isFirstVisible)
18480         offset += axesList.at(i)->tickLengthIn();
18481       isFirstVisible = false;
18482     }
18483     axesList.at(i)->setOffset(offset);
18484   }
18485 }
18486 
18487 /* inherits documentation from base class */
18488 int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
18489 {
18490   if (!mAutoMargins.testFlag(side))
18491     qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
18492   
18493   updateAxesOffset(QCPAxis::marginSideToAxisType(side));
18494   
18495   // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
18496   const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
18497   if (!axesList.isEmpty())
18498     return axesList.last()->offset() + axesList.last()->calculateMargin();
18499   else
18500     return 0;
18501 }
18502 
18503 /*! \internal
18504   
18505   Reacts to a change in layout to potentially set the convenience axis pointers \ref
18506   QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
18507   axes of this axis rect. This is only done if the respective convenience pointer is currently zero
18508   and if there is no QCPAxisRect at position (0, 0) of the plot layout.
18509   
18510   This automation makes it simpler to replace the main axis rect with a newly created one, without
18511   the need to manually reset the convenience pointers.
18512 */
18513 void QCPAxisRect::layoutChanged()
18514 {
18515   if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
18516   {
18517     if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
18518       mParentPlot->xAxis = axis(QCPAxis::atBottom);
18519     if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
18520       mParentPlot->yAxis = axis(QCPAxis::atLeft);
18521     if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
18522       mParentPlot->xAxis2 = axis(QCPAxis::atTop);
18523     if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
18524       mParentPlot->yAxis2 = axis(QCPAxis::atRight);
18525   }
18526 }
18527 
18528 /*! \internal
18529   
18530   Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
18531   pressed, the range dragging interaction is initialized (the actual range manipulation happens in
18532   the \ref mouseMoveEvent).
18533 
18534   The mDragging flag is set to true and some anchor points are set that are needed to determine the
18535   distance the mouse was dragged in the mouse move/release events later.
18536   
18537   \see mouseMoveEvent, mouseReleaseEvent
18538 */
18539 void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
18540 {
18541   Q_UNUSED(details)
18542   if (event->buttons() & Qt::LeftButton)
18543   {
18544     mDragging = true;
18545     // initialize antialiasing backup in case we start dragging:
18546     if (mParentPlot->noAntialiasingOnDrag())
18547     {
18548       mAADragBackup = mParentPlot->antialiasedElements();
18549       mNotAADragBackup = mParentPlot->notAntialiasedElements();
18550     }
18551     // Mouse range dragging interaction:
18552     if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
18553     {
18554       mDragStartHorzRange.clear();
18555       foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
18556         mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
18557       mDragStartVertRange.clear();
18558       foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
18559         mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
18560     }
18561   }
18562 }
18563 
18564 /*! \internal
18565   
18566   Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
18567   preceding \ref mousePressEvent, the range is moved accordingly.
18568   
18569   \see mousePressEvent, mouseReleaseEvent
18570 */
18571 void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
18572 {
18573   Q_UNUSED(startPos)
18574   // Mouse range dragging interaction:
18575   if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
18576   {
18577     
18578     if (mRangeDrag.testFlag(Qt::Horizontal))
18579     {
18580       for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
18581       {
18582         QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
18583         if (!ax)
18584           continue;
18585         if (i >= mDragStartHorzRange.size())
18586           break;
18587         if (ax->mScaleType == QCPAxis::stLinear)
18588         {
18589           double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
18590           ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
18591         } else if (ax->mScaleType == QCPAxis::stLogarithmic)
18592         {
18593           double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
18594           ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
18595         }
18596       }
18597     }
18598     
18599     if (mRangeDrag.testFlag(Qt::Vertical))
18600     {
18601       for (int i=0; i<mRangeDragVertAxis.size(); ++i)
18602       {
18603         QCPAxis *ax = mRangeDragVertAxis.at(i).data();
18604         if (!ax)
18605           continue;
18606         if (i >= mDragStartVertRange.size())
18607           break;
18608         if (ax->mScaleType == QCPAxis::stLinear)
18609         {
18610           double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
18611           ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
18612         } else if (ax->mScaleType == QCPAxis::stLogarithmic)
18613         {
18614           double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
18615           ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
18616         }
18617       }
18618     }
18619     
18620     if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
18621     {
18622       if (mParentPlot->noAntialiasingOnDrag())
18623         mParentPlot->setNotAntialiasedElements(QCP::aeAll);
18624       mParentPlot->replot(QCustomPlot::rpQueuedReplot);
18625     }
18626     
18627   }
18628 }
18629 
18630 /* inherits documentation from base class */
18631 void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
18632 {
18633   Q_UNUSED(event)
18634   Q_UNUSED(startPos)
18635   mDragging = false;
18636   if (mParentPlot->noAntialiasingOnDrag())
18637   {
18638     mParentPlot->setAntialiasedElements(mAADragBackup);
18639     mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
18640   }
18641 }
18642 
18643 /*! \internal
18644   
18645   Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
18646   ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
18647   the scaling operation is the current cursor position inside the axis rect. The scaling factor is
18648   dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
18649   zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
18650   
18651   Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
18652   wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
18653   of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
18654   the range zoom factor. This takes care of the wheel direction automatically, by inverting the
18655   factor, when the wheel step is negative (f^-1 = 1/f).
18656 */
18657 void QCPAxisRect::wheelEvent(QWheelEvent *event)
18658 {
18659 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
18660   const double delta = event->delta();
18661 #else
18662   const double delta = event->angleDelta().y();
18663 #endif
18664   
18665 #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
18666   const QPointF pos = event->pos();
18667 #else
18668   const QPointF pos = event->position();
18669 #endif
18670   
18671   // Mouse range zooming interaction:
18672   if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
18673   {
18674     if (mRangeZoom != 0)
18675     {
18676       double factor;
18677       double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
18678       if (mRangeZoom.testFlag(Qt::Horizontal))
18679       {
18680         factor = qPow(mRangeZoomFactorHorz, wheelSteps);
18681         foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
18682         {
18683           if (!axis.isNull())
18684             axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
18685         }
18686       }
18687       if (mRangeZoom.testFlag(Qt::Vertical))
18688       {
18689         factor = qPow(mRangeZoomFactorVert, wheelSteps);
18690         foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
18691         {
18692           if (!axis.isNull())
18693             axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
18694         }
18695       }
18696       mParentPlot->replot();
18697     }
18698   }
18699 }
18700 /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
18701 
18702 
18703 /* including file 'src/layoutelements/layoutelement-legend.cpp' */
18704 /* modified 2021-03-29T02:30:44, size 31762                     */
18705 
18706 ////////////////////////////////////////////////////////////////////////////////////////////////////
18707 //////////////////// QCPAbstractLegendItem
18708 ////////////////////////////////////////////////////////////////////////////////////////////////////
18709 
18710 /*! \class QCPAbstractLegendItem
18711   \brief The abstract base class for all entries in a QCPLegend.
18712   
18713   It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
18714   legend, the subclass \ref QCPPlottableLegendItem is more suitable.
18715   
18716   Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
18717   that's not even associated with a plottable).
18718 
18719   You must implement the following pure virtual functions:
18720   \li \ref draw (from QCPLayerable)
18721   
18722   You inherit the following members you may use:
18723   <table>
18724     <tr>
18725       <td>QCPLegend *\b mParentLegend</td>
18726       <td>A pointer to the parent QCPLegend.</td>
18727     </tr><tr>
18728       <td>QFont \b mFont</td>
18729       <td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
18730     </tr>
18731   </table>
18732 */
18733 
18734 /* start of documentation of signals */
18735 
18736 /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
18737   
18738   This signal is emitted when the selection state of this legend item has changed, either by user
18739   interaction or by a direct call to \ref setSelected.
18740 */
18741 
18742 /* end of documentation of signals */
18743 
18744 /*!
18745   Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
18746   cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
18747 */
18748 QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
18749   QCPLayoutElement(parent->parentPlot()),
18750   mParentLegend(parent),
18751   mFont(parent->font()),
18752   mTextColor(parent->textColor()),
18753   mSelectedFont(parent->selectedFont()),
18754   mSelectedTextColor(parent->selectedTextColor()),
18755   mSelectable(true),
18756   mSelected(false)
18757 {
18758   setLayer(QLatin1String("legend"));
18759   setMargins(QMargins(0, 0, 0, 0));
18760 }
18761 
18762 /*!
18763   Sets the default font of this specific legend item to \a font.
18764   
18765   \see setTextColor, QCPLegend::setFont
18766 */
18767 void QCPAbstractLegendItem::setFont(const QFont &font)
18768 {
18769   mFont = font;
18770 }
18771 
18772 /*!
18773   Sets the default text color of this specific legend item to \a color.
18774   
18775   \see setFont, QCPLegend::setTextColor
18776 */
18777 void QCPAbstractLegendItem::setTextColor(const QColor &color)
18778 {
18779   mTextColor = color;
18780 }
18781 
18782 /*!
18783   When this legend item is selected, \a font is used to draw generic text, instead of the normal
18784   font set with \ref setFont.
18785   
18786   \see setFont, QCPLegend::setSelectedFont
18787 */
18788 void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
18789 {
18790   mSelectedFont = font;
18791 }
18792 
18793 /*!
18794   When this legend item is selected, \a color is used to draw generic text, instead of the normal
18795   color set with \ref setTextColor.
18796   
18797   \see setTextColor, QCPLegend::setSelectedTextColor
18798 */
18799 void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
18800 {
18801   mSelectedTextColor = color;
18802 }
18803 
18804 /*!
18805   Sets whether this specific legend item is selectable.
18806   
18807   \see setSelectedParts, QCustomPlot::setInteractions
18808 */
18809 void QCPAbstractLegendItem::setSelectable(bool selectable)
18810 {
18811   if (mSelectable != selectable)
18812   {
18813     mSelectable = selectable;
18814     emit selectableChanged(mSelectable);
18815   }
18816 }
18817 
18818 /*!
18819   Sets whether this specific legend item is selected.
18820   
18821   It is possible to set the selection state of this item by calling this function directly, even if
18822   setSelectable is set to false.
18823   
18824   \see setSelectableParts, QCustomPlot::setInteractions
18825 */
18826 void QCPAbstractLegendItem::setSelected(bool selected)
18827 {
18828   if (mSelected != selected)
18829   {
18830     mSelected = selected;
18831     emit selectionChanged(mSelected);
18832   }
18833 }
18834 
18835 /* inherits documentation from base class */
18836 double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
18837 {
18838   Q_UNUSED(details)
18839   if (!mParentPlot) return -1;
18840   if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
18841     return -1;
18842   
18843   if (mRect.contains(pos.toPoint()))
18844     return mParentPlot->selectionTolerance()*0.99;
18845   else
18846     return -1;
18847 }
18848 
18849 /* inherits documentation from base class */
18850 void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
18851 {
18852   applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
18853 }
18854 
18855 /* inherits documentation from base class */
18856 QRect QCPAbstractLegendItem::clipRect() const
18857 {
18858   return mOuterRect;
18859 }
18860 
18861 /* inherits documentation from base class */
18862 void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
18863 {
18864   Q_UNUSED(event)
18865   Q_UNUSED(details)
18866   if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
18867   {
18868     bool selBefore = mSelected;
18869     setSelected(additive ? !mSelected : true);
18870     if (selectionStateChanged)
18871       *selectionStateChanged = mSelected != selBefore;
18872   }
18873 }
18874 
18875 /* inherits documentation from base class */
18876 void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
18877 {
18878   if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
18879   {
18880     bool selBefore = mSelected;
18881     setSelected(false);
18882     if (selectionStateChanged)
18883       *selectionStateChanged = mSelected != selBefore;
18884   }
18885 }
18886 
18887 ////////////////////////////////////////////////////////////////////////////////////////////////////
18888 //////////////////// QCPPlottableLegendItem
18889 ////////////////////////////////////////////////////////////////////////////////////////////////////
18890 
18891 /*! \class QCPPlottableLegendItem
18892   \brief A legend item representing a plottable with an icon and the plottable name.
18893   
18894   This is the standard legend item for plottables. It displays an icon of the plottable next to the
18895   plottable name. The icon is drawn by the respective plottable itself (\ref
18896   QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
18897   For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
18898   middle.
18899   
18900   Legend items of this type are always associated with one plottable (retrievable via the
18901   plottable() function and settable with the constructor). You may change the font of the plottable
18902   name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
18903   QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
18904 
18905   The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
18906   creates/removes legend items of this type.
18907   
18908   Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
18909   QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
18910   interface, QCPLegend has specialized functions for handling legend items conveniently, see the
18911   documentation of \ref QCPLegend.
18912 */
18913 
18914 /*!
18915   Creates a new legend item associated with \a plottable.
18916   
18917   Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
18918   
18919   A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
18920   QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
18921 */
18922 QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
18923   QCPAbstractLegendItem(parent),
18924   mPlottable(plottable)
18925 {
18926   setAntialiased(false);
18927 }
18928 
18929 /*! \internal
18930   
18931   Returns the pen that shall be used to draw the icon border, taking into account the selection
18932   state of this item.
18933 */
18934 QPen QCPPlottableLegendItem::getIconBorderPen() const
18935 {
18936   return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
18937 }
18938 
18939 /*! \internal
18940   
18941   Returns the text color that shall be used to draw text, taking into account the selection state
18942   of this item.
18943 */
18944 QColor QCPPlottableLegendItem::getTextColor() const
18945 {
18946   return mSelected ? mSelectedTextColor : mTextColor;
18947 }
18948 
18949 /*! \internal
18950   
18951   Returns the font that shall be used to draw text, taking into account the selection state of this
18952   item.
18953 */
18954 QFont QCPPlottableLegendItem::getFont() const
18955 {
18956   return mSelected ? mSelectedFont : mFont;
18957 }
18958 
18959 /*! \internal
18960   
18961   Draws the item with \a painter. The size and position of the drawn legend item is defined by the
18962   parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
18963   maximumOuterSizeHint of this legend item.
18964 */
18965 void QCPPlottableLegendItem::draw(QCPPainter *painter)
18966 {
18967   if (!mPlottable) return;
18968   painter->setFont(getFont());
18969   painter->setPen(QPen(getTextColor()));
18970   QSize iconSize = mParentLegend->iconSize();
18971   QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
18972   QRect iconRect(mRect.topLeft(), iconSize);
18973   int textHeight = qMax(textRect.height(), iconSize.height());  // if text has smaller height than icon, center text vertically in icon height, else align tops
18974   painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
18975   // draw icon:
18976   painter->save();
18977   painter->setClipRect(iconRect, Qt::IntersectClip);
18978   mPlottable->drawLegendIcon(painter, iconRect);
18979   painter->restore();
18980   // draw icon border:
18981   if (getIconBorderPen().style() != Qt::NoPen)
18982   {
18983     painter->setPen(getIconBorderPen());
18984     painter->setBrush(Qt::NoBrush);
18985     int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
18986     painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
18987     painter->drawRect(iconRect);
18988   }
18989 }
18990 
18991 /*! \internal
18992   
18993   Calculates and returns the size of this item. This includes the icon, the text and the padding in
18994   between.
18995   
18996   \seebaseclassmethod
18997 */
18998 QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
18999 {
19000   if (!mPlottable) return {};
19001   QSize result(0, 0);
19002   QRect textRect;
19003   QFontMetrics fontMetrics(getFont());
19004   QSize iconSize = mParentLegend->iconSize();
19005   textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
19006   result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
19007   result.setHeight(qMax(textRect.height(), iconSize.height()));
19008   result.rwidth() += mMargins.left()+mMargins.right();
19009   result.rheight() += mMargins.top()+mMargins.bottom();
19010   return result;
19011 }
19012 
19013 
19014 ////////////////////////////////////////////////////////////////////////////////////////////////////
19015 //////////////////// QCPLegend
19016 ////////////////////////////////////////////////////////////////////////////////////////////////////
19017 
19018 /*! \class QCPLegend
19019   \brief Manages a legend inside a QCustomPlot.
19020 
19021   A legend is a small box somewhere in the plot which lists plottables with their name and icon.
19022 
19023   A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
19024   plottable, for which a legend item shall be created. In the case of the main legend (\ref
19025   QCustomPlot::legend), simply adding plottables to the plot while \ref
19026   QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
19027   legend items. The legend item associated with a certain plottable can be removed with \ref
19028   QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
19029   manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
19030   addItem, \ref removeItem, etc.
19031 
19032   Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
19033   QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
19034   "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
19035   an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
19036   mentioned above. In principle, any other layout elements may also be added to a legend via the
19037   normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
19038   System\endlink for examples on how to add other elements to the legend and move it outside the axis
19039   rect.
19040 
19041   Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
19042   in which order (column first or row first) the legend is filled up when calling \ref addItem, and
19043   at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
19044 
19045   By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
19046   inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
19047   position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
19048   outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
19049   interface.
19050 */
19051 
19052 /* start of documentation of signals */
19053 
19054 /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
19055 
19056   This signal is emitted when the selection state of this legend has changed.
19057   
19058   \see setSelectedParts, setSelectableParts
19059 */
19060 
19061 /* end of documentation of signals */
19062 
19063 /*!
19064   Constructs a new QCPLegend instance with default values.
19065   
19066   Note that by default, QCustomPlot already contains a legend ready to be used as \ref
19067   QCustomPlot::legend
19068 */
19069 QCPLegend::QCPLegend() :
19070   mIconTextPadding{}
19071 {
19072   setFillOrder(QCPLayoutGrid::foRowsFirst);
19073   setWrap(0);
19074   
19075   setRowSpacing(3);
19076   setColumnSpacing(8);
19077   setMargins(QMargins(7, 5, 7, 4));
19078   setAntialiased(false);
19079   setIconSize(32, 18);
19080   
19081   setIconTextPadding(7);
19082   
19083   setSelectableParts(spLegendBox | spItems);
19084   setSelectedParts(spNone);
19085   
19086   setBorderPen(QPen(Qt::black, 0));
19087   setSelectedBorderPen(QPen(Qt::blue, 2));
19088   setIconBorderPen(Qt::NoPen);
19089   setSelectedIconBorderPen(QPen(Qt::blue, 2));
19090   setBrush(Qt::white);
19091   setSelectedBrush(Qt::white);
19092   setTextColor(Qt::black);
19093   setSelectedTextColor(Qt::blue);
19094 }
19095 
19096 QCPLegend::~QCPLegend()
19097 {
19098   clearItems();
19099   if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot)
19100     mParentPlot->legendRemoved(this);
19101 }
19102 
19103 /* no doc for getter, see setSelectedParts */
19104 QCPLegend::SelectableParts QCPLegend::selectedParts() const
19105 {
19106   // check whether any legend elements selected, if yes, add spItems to return value
19107   bool hasSelectedItems = false;
19108   for (int i=0; i<itemCount(); ++i)
19109   {
19110     if (item(i) && item(i)->selected())
19111     {
19112       hasSelectedItems = true;
19113       break;
19114     }
19115   }
19116   if (hasSelectedItems)
19117     return mSelectedParts | spItems;
19118   else
19119     return mSelectedParts & ~spItems;
19120 }
19121 
19122 /*!
19123   Sets the pen, the border of the entire legend is drawn with.
19124 */
19125 void QCPLegend::setBorderPen(const QPen &pen)
19126 {
19127   mBorderPen = pen;
19128 }
19129 
19130 /*!
19131   Sets the brush of the legend background.
19132 */
19133 void QCPLegend::setBrush(const QBrush &brush)
19134 {
19135   mBrush = brush;
19136 }
19137 
19138 /*!
19139   Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
19140   use this font by default. However, a different font can be specified on a per-item-basis by
19141   accessing the specific legend item.
19142   
19143   This function will also set \a font on all already existing legend items.
19144   
19145   \see QCPAbstractLegendItem::setFont
19146 */
19147 void QCPLegend::setFont(const QFont &font)
19148 {
19149   mFont = font;
19150   for (int i=0; i<itemCount(); ++i)
19151   {
19152     if (item(i))
19153       item(i)->setFont(mFont);
19154   }
19155 }
19156 
19157 /*!
19158   Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
19159   will use this color by default. However, a different colors can be specified on a per-item-basis
19160   by accessing the specific legend item.
19161   
19162   This function will also set \a color on all already existing legend items.
19163   
19164   \see QCPAbstractLegendItem::setTextColor
19165 */
19166 void QCPLegend::setTextColor(const QColor &color)
19167 {
19168   mTextColor = color;
19169   for (int i=0; i<itemCount(); ++i)
19170   {
19171     if (item(i))
19172       item(i)->setTextColor(color);
19173   }
19174 }
19175 
19176 /*!
19177   Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
19178   representation of the graph) will use this size by default.
19179 */
19180 void QCPLegend::setIconSize(const QSize &size)
19181 {
19182   mIconSize = size;
19183 }
19184 
19185 /*! \overload
19186 */
19187 void QCPLegend::setIconSize(int width, int height)
19188 {
19189   mIconSize.setWidth(width);
19190   mIconSize.setHeight(height);
19191 }
19192 
19193 /*!
19194   Sets the horizontal space in pixels between the legend icon and the text next to it.
19195   Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
19196   name of the graph) will use this space by default.
19197 */
19198 void QCPLegend::setIconTextPadding(int padding)
19199 {
19200   mIconTextPadding = padding;
19201 }
19202 
19203 /*!
19204   Sets the pen used to draw a border around each legend icon. Legend items that draw an
19205   icon (e.g. a visual representation of the graph) will use this pen by default.
19206   
19207   If no border is wanted, set this to \a Qt::NoPen.
19208 */
19209 void QCPLegend::setIconBorderPen(const QPen &pen)
19210 {
19211   mIconBorderPen = pen;
19212 }
19213 
19214 /*!
19215   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
19216   (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
19217   
19218   However, even when \a selectable is set to a value not allowing the selection of a specific part,
19219   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
19220   directly.
19221   
19222   \see SelectablePart, setSelectedParts
19223 */
19224 void QCPLegend::setSelectableParts(const SelectableParts &selectable)
19225 {
19226   if (mSelectableParts != selectable)
19227   {
19228     mSelectableParts = selectable;
19229     emit selectableChanged(mSelectableParts);
19230   }
19231 }
19232 
19233 /*!
19234   Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
19235   is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
19236   doesn't contain \ref spItems, those items become deselected.
19237   
19238   The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
19239   contains iSelectLegend. You only need to call this function when you wish to change the selection
19240   state manually.
19241   
19242   This function can change the selection state of a part even when \ref setSelectableParts was set to a
19243   value that actually excludes the part.
19244   
19245   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
19246   
19247   Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
19248   before, because there's no way to specify which exact items to newly select. Do this by calling
19249   \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
19250   
19251   \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
19252   setSelectedFont
19253 */
19254 void QCPLegend::setSelectedParts(const SelectableParts &selected)
19255 {
19256   SelectableParts newSelected = selected;
19257   mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
19258 
19259   if (mSelectedParts != newSelected)
19260   {
19261     if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
19262     {
19263       qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
19264       newSelected &= ~spItems;
19265     }
19266     if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
19267     {
19268       for (int i=0; i<itemCount(); ++i)
19269       {
19270         if (item(i))
19271           item(i)->setSelected(false);
19272       }
19273     }
19274     mSelectedParts = newSelected;
19275     emit selectionChanged(mSelectedParts);
19276   }
19277 }
19278 
19279 /*!
19280   When the legend box is selected, this pen is used to draw the border instead of the normal pen
19281   set via \ref setBorderPen.
19282 
19283   \see setSelectedParts, setSelectableParts, setSelectedBrush
19284 */
19285 void QCPLegend::setSelectedBorderPen(const QPen &pen)
19286 {
19287   mSelectedBorderPen = pen;
19288 }
19289 
19290 /*!
19291   Sets the pen legend items will use to draw their icon borders, when they are selected.
19292 
19293   \see setSelectedParts, setSelectableParts, setSelectedFont
19294 */
19295 void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
19296 {
19297   mSelectedIconBorderPen = pen;
19298 }
19299 
19300 /*!
19301   When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
19302   set via \ref setBrush.
19303 
19304   \see setSelectedParts, setSelectableParts, setSelectedBorderPen
19305 */
19306 void QCPLegend::setSelectedBrush(const QBrush &brush)
19307 {
19308   mSelectedBrush = brush;
19309 }
19310 
19311 /*!
19312   Sets the default font that is used by legend items when they are selected.
19313   
19314   This function will also set \a font on all already existing legend items.
19315 
19316   \see setFont, QCPAbstractLegendItem::setSelectedFont
19317 */
19318 void QCPLegend::setSelectedFont(const QFont &font)
19319 {
19320   mSelectedFont = font;
19321   for (int i=0; i<itemCount(); ++i)
19322   {
19323     if (item(i))
19324       item(i)->setSelectedFont(font);
19325   }
19326 }
19327 
19328 /*!
19329   Sets the default text color that is used by legend items when they are selected.
19330   
19331   This function will also set \a color on all already existing legend items.
19332 
19333   \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
19334 */
19335 void QCPLegend::setSelectedTextColor(const QColor &color)
19336 {
19337   mSelectedTextColor = color;
19338   for (int i=0; i<itemCount(); ++i)
19339   {
19340     if (item(i))
19341       item(i)->setSelectedTextColor(color);
19342   }
19343 }
19344 
19345 /*!
19346   Returns the item with index \a i. If non-legend items were added to the legend, and the element
19347   at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
19348 
19349   Note that the linear index depends on the current fill order (\ref setFillOrder).
19350 
19351   \see itemCount, addItem, itemWithPlottable
19352 */
19353 QCPAbstractLegendItem *QCPLegend::item(int index) const
19354 {
19355   return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
19356 }
19357 
19358 /*!
19359   Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
19360   If such an item isn't in the legend, returns \c nullptr.
19361   
19362   \see hasItemWithPlottable
19363 */
19364 QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
19365 {
19366   for (int i=0; i<itemCount(); ++i)
19367   {
19368     if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
19369     {
19370       if (pli->plottable() == plottable)
19371         return pli;
19372     }
19373   }
19374   return nullptr;
19375 }
19376 
19377 /*!
19378   Returns the number of items currently in the legend. It is identical to the base class
19379   QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
19380   doesn't only address elements which can be cast to QCPAbstractLegendItem.
19381 
19382   Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
19383   base class which allows creating empty cells), they are included in the returned count.
19384 
19385   \see item
19386 */
19387 int QCPLegend::itemCount() const
19388 {
19389   return elementCount();
19390 }
19391 
19392 /*!
19393   Returns whether the legend contains \a item.
19394   
19395   \see hasItemWithPlottable
19396 */
19397 bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
19398 {
19399   for (int i=0; i<itemCount(); ++i)
19400   {
19401     if (item == this->item(i))
19402         return true;
19403   }
19404   return false;
19405 }
19406 
19407 /*!
19408   Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
19409   If such an item isn't in the legend, returns false.
19410   
19411   \see itemWithPlottable
19412 */
19413 bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
19414 {
19415   return itemWithPlottable(plottable);
19416 }
19417 
19418 /*!
19419   Adds \a item to the legend, if it's not present already. The element is arranged according to the
19420   current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
19421 
19422   Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
19423 
19424   The legend takes ownership of the item.
19425 
19426   \see removeItem, item, hasItem
19427 */
19428 bool QCPLegend::addItem(QCPAbstractLegendItem *item)
19429 {
19430   return addElement(item);
19431 }
19432 
19433 /*! \overload
19434 
19435   Removes the item with the specified \a index from the legend and deletes it.
19436 
19437   After successful removal, the legend is reordered according to the current fill order (\ref
19438   setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
19439   was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
19440 
19441   Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
19442   elements derived from \ref QCPAbstractLegendItem.
19443 
19444   \see itemCount, clearItems
19445 */
19446 bool QCPLegend::removeItem(int index)
19447 {
19448   if (QCPAbstractLegendItem *ali = item(index))
19449   {
19450     bool success = remove(ali);
19451     if (success)
19452       setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
19453     return success;
19454   } else
19455     return false;
19456 }
19457 
19458 /*! \overload
19459 
19460   Removes \a item from the legend and deletes it.
19461 
19462   After successful removal, the legend is reordered according to the current fill order (\ref
19463   setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
19464   was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
19465 
19466   Returns true, if successful.
19467 
19468   \see clearItems
19469 */
19470 bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
19471 {
19472   bool success = remove(item);
19473   if (success)
19474     setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
19475   return success;
19476 }
19477 
19478 /*!
19479   Removes all items from the legend.
19480 */
19481 void QCPLegend::clearItems()
19482 {
19483   for (int i=elementCount()-1; i>=0; --i)
19484   {
19485     if (item(i))
19486       removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
19487   }
19488   setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
19489 }
19490 
19491 /*!
19492   Returns the legend items that are currently selected. If no items are selected,
19493   the list is empty.
19494   
19495   \see QCPAbstractLegendItem::setSelected, setSelectable
19496 */
19497 QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
19498 {
19499   QList<QCPAbstractLegendItem*> result;
19500   for (int i=0; i<itemCount(); ++i)
19501   {
19502     if (QCPAbstractLegendItem *ali = item(i))
19503     {
19504       if (ali->selected())
19505         result.append(ali);
19506     }
19507   }
19508   return result;
19509 }
19510 
19511 /*! \internal
19512 
19513   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
19514   before drawing main legend elements.
19515 
19516   This is the antialiasing state the painter passed to the \ref draw method is in by default.
19517   
19518   This function takes into account the local setting of the antialiasing flag as well as the
19519   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
19520   QCustomPlot::setNotAntialiasedElements.
19521   
19522   \seebaseclassmethod
19523   
19524   \see setAntialiased
19525 */
19526 void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
19527 {
19528   applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
19529 }
19530 
19531 /*! \internal
19532   
19533   Returns the pen used to paint the border of the legend, taking into account the selection state
19534   of the legend box.
19535 */
19536 QPen QCPLegend::getBorderPen() const
19537 {
19538   return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
19539 }
19540 
19541 /*! \internal
19542   
19543   Returns the brush used to paint the background of the legend, taking into account the selection
19544   state of the legend box.
19545 */
19546 QBrush QCPLegend::getBrush() const
19547 {
19548   return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
19549 }
19550 
19551 /*! \internal
19552   
19553   Draws the legend box with the provided \a painter. The individual legend items are layerables
19554   themselves, thus are drawn independently.
19555 */
19556 void QCPLegend::draw(QCPPainter *painter)
19557 {
19558   // draw background rect:
19559   painter->setBrush(getBrush());
19560   painter->setPen(getBorderPen());
19561   painter->drawRect(mOuterRect);
19562 }
19563 
19564 /* inherits documentation from base class */
19565 double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
19566 {
19567   if (!mParentPlot) return -1;
19568   if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
19569     return -1;
19570   
19571   if (mOuterRect.contains(pos.toPoint()))
19572   {
19573     if (details) details->setValue(spLegendBox);
19574     return mParentPlot->selectionTolerance()*0.99;
19575   }
19576   return -1;
19577 }
19578 
19579 /* inherits documentation from base class */
19580 void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
19581 {
19582   Q_UNUSED(event)
19583   mSelectedParts = selectedParts(); // in case item selection has changed
19584   if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
19585   {
19586     SelectableParts selBefore = mSelectedParts;
19587     setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
19588     if (selectionStateChanged)
19589       *selectionStateChanged = mSelectedParts != selBefore;
19590   }
19591 }
19592 
19593 /* inherits documentation from base class */
19594 void QCPLegend::deselectEvent(bool *selectionStateChanged)
19595 {
19596   mSelectedParts = selectedParts(); // in case item selection has changed
19597   if (mSelectableParts.testFlag(spLegendBox))
19598   {
19599     SelectableParts selBefore = mSelectedParts;
19600     setSelectedParts(selectedParts() & ~spLegendBox);
19601     if (selectionStateChanged)
19602       *selectionStateChanged = mSelectedParts != selBefore;
19603   }
19604 }
19605 
19606 /* inherits documentation from base class */
19607 QCP::Interaction QCPLegend::selectionCategory() const
19608 {
19609   return QCP::iSelectLegend;
19610 }
19611 
19612 /* inherits documentation from base class */
19613 QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
19614 {
19615   return QCP::iSelectLegend;
19616 }
19617 
19618 /* inherits documentation from base class */
19619 void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
19620 {
19621   if (parentPlot && !parentPlot->legend)
19622     parentPlot->legend = this;
19623 }
19624 /* end of 'src/layoutelements/layoutelement-legend.cpp' */
19625 
19626 
19627 /* including file 'src/layoutelements/layoutelement-textelement.cpp' */
19628 /* modified 2021-03-29T02:30:44, size 12925                          */
19629 
19630 ////////////////////////////////////////////////////////////////////////////////////////////////////
19631 //////////////////// QCPTextElement
19632 ////////////////////////////////////////////////////////////////////////////////////////////////////
19633 
19634 /*! \class QCPTextElement
19635   \brief A layout element displaying a text
19636 
19637   The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
19638   \ref setTextColor, and \ref setTextFlags.
19639 
19640   A text element can be added as follows:
19641   \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
19642 */
19643 
19644 /* start documentation of signals */
19645 
19646 /*! \fn void QCPTextElement::selectionChanged(bool selected)
19647   
19648   This signal is emitted when the selection state has changed to \a selected, either by user
19649   interaction or by a direct call to \ref setSelected.
19650   
19651   \see setSelected, setSelectable
19652 */
19653 
19654 /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
19655 
19656   This signal is emitted when the text element is clicked.
19657 
19658   \see doubleClicked, selectTest
19659 */
19660 
19661 /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
19662 
19663   This signal is emitted when the text element is double clicked.
19664 
19665   \see clicked, selectTest
19666 */
19667 
19668 /* end documentation of signals */
19669 
19670 /*! \overload
19671   
19672   Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
19673   setText).
19674 */
19675 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
19676   QCPLayoutElement(parentPlot),
19677   mText(),
19678   mTextFlags(Qt::AlignCenter),
19679   mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
19680   mTextColor(Qt::black),
19681   mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
19682   mSelectedTextColor(Qt::blue),
19683   mSelectable(false),
19684   mSelected(false)
19685 {
19686   if (parentPlot)
19687   {
19688     mFont = parentPlot->font();
19689     mSelectedFont = parentPlot->font();
19690   }
19691   setMargins(QMargins(2, 2, 2, 2));
19692 }
19693 
19694 /*! \overload
19695   
19696   Creates a new QCPTextElement instance and sets default values.
19697 
19698   The initial text is set to \a text.
19699 */
19700 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
19701   QCPLayoutElement(parentPlot),
19702   mText(text),
19703   mTextFlags(Qt::AlignCenter),
19704   mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
19705   mTextColor(Qt::black),
19706   mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
19707   mSelectedTextColor(Qt::blue),
19708   mSelectable(false),
19709   mSelected(false)
19710 {
19711   if (parentPlot)
19712   {
19713     mFont = parentPlot->font();
19714     mSelectedFont = parentPlot->font();
19715   }
19716   setMargins(QMargins(2, 2, 2, 2));
19717 }
19718 
19719 /*! \overload
19720   
19721   Creates a new QCPTextElement instance and sets default values.
19722 
19723   The initial text is set to \a text with \a pointSize.
19724 */
19725 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
19726   QCPLayoutElement(parentPlot),
19727   mText(text),
19728   mTextFlags(Qt::AlignCenter),
19729   mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
19730   mTextColor(Qt::black),
19731   mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
19732   mSelectedTextColor(Qt::blue),
19733   mSelectable(false),
19734   mSelected(false)
19735 {
19736   mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
19737   if (parentPlot)
19738   {
19739     mFont = parentPlot->font();
19740     mFont.setPointSizeF(pointSize);
19741     mSelectedFont = parentPlot->font();
19742     mSelectedFont.setPointSizeF(pointSize);
19743   }
19744   setMargins(QMargins(2, 2, 2, 2));
19745 }
19746 
19747 /*! \overload
19748   
19749   Creates a new QCPTextElement instance and sets default values.
19750 
19751   The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
19752 */
19753 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
19754   QCPLayoutElement(parentPlot),
19755   mText(text),
19756   mTextFlags(Qt::AlignCenter),
19757   mFont(QFont(fontFamily, int(pointSize))),
19758   mTextColor(Qt::black),
19759   mSelectedFont(QFont(fontFamily, int(pointSize))),
19760   mSelectedTextColor(Qt::blue),
19761   mSelectable(false),
19762   mSelected(false)
19763 {
19764   mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
19765   setMargins(QMargins(2, 2, 2, 2));
19766 }
19767 
19768 /*! \overload
19769   
19770   Creates a new QCPTextElement instance and sets default values.
19771 
19772   The initial text is set to \a text with the specified \a font.
19773 */
19774 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
19775   QCPLayoutElement(parentPlot),
19776   mText(text),
19777   mTextFlags(Qt::AlignCenter),
19778   mFont(font),
19779   mTextColor(Qt::black),
19780   mSelectedFont(font),
19781   mSelectedTextColor(Qt::blue),
19782   mSelectable(false),
19783   mSelected(false)
19784 {
19785   setMargins(QMargins(2, 2, 2, 2));
19786 }
19787 
19788 /*!
19789   Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
19790   
19791   \see setFont, setTextColor, setTextFlags
19792 */
19793 void QCPTextElement::setText(const QString &text)
19794 {
19795   mText = text;
19796 }
19797 
19798 /*!
19799   Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
19800   \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
19801   
19802   Possible enums are:
19803   - Qt::AlignLeft
19804   - Qt::AlignRight
19805   - Qt::AlignHCenter
19806   - Qt::AlignJustify
19807   - Qt::AlignTop
19808   - Qt::AlignBottom
19809   - Qt::AlignVCenter
19810   - Qt::AlignCenter
19811   - Qt::TextDontClip
19812   - Qt::TextSingleLine
19813   - Qt::TextExpandTabs
19814   - Qt::TextShowMnemonic
19815   - Qt::TextWordWrap
19816   - Qt::TextIncludeTrailingSpaces
19817 */
19818 void QCPTextElement::setTextFlags(int flags)
19819 {
19820   mTextFlags = flags;
19821 }
19822 
19823 /*!
19824   Sets the \a font of the text.
19825   
19826   \see setTextColor, setSelectedFont
19827 */
19828 void QCPTextElement::setFont(const QFont &font)
19829 {
19830   mFont = font;
19831 }
19832 
19833 /*!
19834   Sets the \a color of the text.
19835   
19836   \see setFont, setSelectedTextColor
19837 */
19838 void QCPTextElement::setTextColor(const QColor &color)
19839 {
19840   mTextColor = color;
19841 }
19842 
19843 /*!
19844   Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
19845   
19846   \see setFont
19847 */
19848 void QCPTextElement::setSelectedFont(const QFont &font)
19849 {
19850   mSelectedFont = font;
19851 }
19852 
19853 /*!
19854   Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
19855   
19856   \see setTextColor
19857 */
19858 void QCPTextElement::setSelectedTextColor(const QColor &color)
19859 {
19860   mSelectedTextColor = color;
19861 }
19862 
19863 /*!
19864   Sets whether the user may select this text element.
19865 
19866   Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
19867   programmatically via \ref setSelected.
19868 */
19869 void QCPTextElement::setSelectable(bool selectable)
19870 {
19871   if (mSelectable != selectable)
19872   {
19873     mSelectable = selectable;
19874     emit selectableChanged(mSelectable);
19875   }
19876 }
19877 
19878 /*!
19879   Sets the selection state of this text element to \a selected. If the selection has changed, \ref
19880   selectionChanged is emitted.
19881   
19882   Note that this function can change the selection state independently of the current \ref
19883   setSelectable state.
19884 */
19885 void QCPTextElement::setSelected(bool selected)
19886 {
19887   if (mSelected != selected)
19888   {
19889     mSelected = selected;
19890     emit selectionChanged(mSelected);
19891   }
19892 }
19893 
19894 /* inherits documentation from base class */
19895 void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
19896 {
19897   applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
19898 }
19899 
19900 /* inherits documentation from base class */
19901 void QCPTextElement::draw(QCPPainter *painter)
19902 {
19903   painter->setFont(mainFont());
19904   painter->setPen(QPen(mainTextColor()));
19905   painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
19906 }
19907 
19908 /* inherits documentation from base class */
19909 QSize QCPTextElement::minimumOuterSizeHint() const
19910 {
19911   QFontMetrics metrics(mFont);
19912   QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
19913   result.rwidth() += mMargins.left()+mMargins.right();
19914   result.rheight() += mMargins.top()+mMargins.bottom();
19915   return result;
19916 }
19917 
19918 /* inherits documentation from base class */
19919 QSize QCPTextElement::maximumOuterSizeHint() const
19920 {
19921   QFontMetrics metrics(mFont);
19922   QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
19923   result.setWidth(QWIDGETSIZE_MAX);
19924   result.rheight() += mMargins.top()+mMargins.bottom();
19925   return result;
19926 }
19927 
19928 /* inherits documentation from base class */
19929 void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
19930 {
19931   Q_UNUSED(event)
19932   Q_UNUSED(details)
19933   if (mSelectable)
19934   {
19935     bool selBefore = mSelected;
19936     setSelected(additive ? !mSelected : true);
19937     if (selectionStateChanged)
19938       *selectionStateChanged = mSelected != selBefore;
19939   }
19940 }
19941 
19942 /* inherits documentation from base class */
19943 void QCPTextElement::deselectEvent(bool *selectionStateChanged)
19944 {
19945   if (mSelectable)
19946   {
19947     bool selBefore = mSelected;
19948     setSelected(false);
19949     if (selectionStateChanged)
19950       *selectionStateChanged = mSelected != selBefore;
19951   }
19952 }
19953 
19954 /*!
19955   Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
19956   within the bounding box of the text element's text. Note that this bounding box is updated in the
19957   draw call.
19958 
19959   If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
19960   element is not selectable (\ref setSelectable), returns -1.
19961 
19962   \seebaseclassmethod
19963 */
19964 double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
19965 {
19966   Q_UNUSED(details)
19967   if (onlySelectable && !mSelectable)
19968     return -1;
19969   
19970   if (mTextBoundingRect.contains(pos.toPoint()))
19971     return mParentPlot->selectionTolerance()*0.99;
19972   else
19973     return -1;
19974 }
19975 
19976 /*!
19977   Accepts the mouse event in order to emit the according click signal in the \ref
19978   mouseReleaseEvent.
19979 
19980   \seebaseclassmethod
19981 */
19982 void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
19983 {
19984   Q_UNUSED(details)
19985   event->accept();
19986 }
19987 
19988 /*!
19989   Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
19990   mousePressEvent.
19991 
19992   \seebaseclassmethod
19993 */
19994 void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
19995 {
19996   if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
19997     emit clicked(event);
19998 }
19999 
20000 /*!
20001   Emits the \ref doubleClicked signal.
20002 
20003   \seebaseclassmethod
20004 */
20005 void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
20006 {
20007   Q_UNUSED(details)
20008   emit doubleClicked(event);
20009 }
20010 
20011 /*! \internal
20012   
20013   Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
20014   <tt>true</tt>, else mFont is returned.
20015 */
20016 QFont QCPTextElement::mainFont() const
20017 {
20018   return mSelected ? mSelectedFont : mFont;
20019 }
20020 
20021 /*! \internal
20022   
20023   Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
20024   <tt>true</tt>, else mTextColor is returned.
20025 */
20026 QColor QCPTextElement::mainTextColor() const
20027 {
20028   return mSelected ? mSelectedTextColor : mTextColor;
20029 }
20030 /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
20031 
20032 
20033 /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
20034 /* modified 2021-03-29T02:30:44, size 26531                         */
20035 
20036 
20037 ////////////////////////////////////////////////////////////////////////////////////////////////////
20038 //////////////////// QCPColorScale
20039 ////////////////////////////////////////////////////////////////////////////////////////////////////
20040 
20041 /*! \class QCPColorScale
20042   \brief A color scale for use with color coding data such as QCPColorMap
20043   
20044   This layout element can be placed on the plot to correlate a color gradient with data values. It
20045   is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
20046 
20047   \image html QCPColorScale.png
20048   
20049   The color scale can be either horizontal or vertical, as shown in the image above. The
20050   orientation and the side where the numbers appear is controlled with \ref setType.
20051   
20052   Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
20053   connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
20054   setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
20055   scale, to make them all synchronize these properties.
20056   
20057   To have finer control over the number display and axis behaviour, you can directly access the
20058   \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
20059   you want to change the number of automatically generated ticks, call
20060   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
20061   
20062   Placing a color scale next to the main axis rect works like with any other layout element:
20063   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
20064   In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
20065   call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
20066   scale can be set with \ref setLabel.
20067   
20068   For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
20069   the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
20070   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
20071   
20072   Color scales are initialized with a non-zero minimum top and bottom margin (\ref
20073   setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
20074   margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
20075   horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
20076   might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
20077 */
20078 
20079 /* start documentation of inline functions */
20080 
20081 /*! \fn QCPAxis *QCPColorScale::axis() const
20082   
20083   Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
20084   appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
20085   interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
20086   setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
20087   QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
20088   the QCPColorScale or on its QCPAxis.
20089   
20090   If the type of the color scale is changed with \ref setType, the axis returned by this method
20091   will change, too, to either the left, right, bottom or top axis, depending on which type was set.
20092 */
20093 
20094 /* end documentation of signals */
20095 /* start documentation of signals */
20096 
20097 /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
20098   
20099   This signal is emitted when the data range changes.
20100   
20101   \see setDataRange
20102 */
20103 
20104 /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
20105   
20106   This signal is emitted when the data scale type changes.
20107   
20108   \see setDataScaleType
20109 */
20110 
20111 /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
20112   
20113   This signal is emitted when the gradient changes.
20114   
20115   \see setGradient
20116 */
20117 
20118 /* end documentation of signals */
20119 
20120 /*!
20121   Constructs a new QCPColorScale.
20122 */
20123 QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
20124   QCPLayoutElement(parentPlot),
20125   mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
20126   mDataScaleType(QCPAxis::stLinear),
20127   mGradient(QCPColorGradient::gpCold),
20128   mBarWidth(20),
20129   mAxisRect(new QCPColorScaleAxisRectPrivate(this))
20130 {
20131   setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used)
20132   setType(QCPAxis::atRight);
20133   setDataRange(QCPRange(0, 6));
20134 }
20135 
20136 QCPColorScale::~QCPColorScale()
20137 {
20138   delete mAxisRect;
20139 }
20140 
20141 /* undocumented getter */
20142 QString QCPColorScale::label() const
20143 {
20144   if (!mColorAxis)
20145   {
20146     qDebug() << Q_FUNC_INFO << "internal color axis undefined";
20147     return QString();
20148   }
20149   
20150   return mColorAxis.data()->label();
20151 }
20152 
20153 /* undocumented getter */
20154 bool QCPColorScale::rangeDrag() const
20155 {
20156   if (!mAxisRect)
20157   {
20158     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20159     return false;
20160   }
20161   
20162   return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
20163       mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
20164       mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
20165 }
20166 
20167 /* undocumented getter */
20168 bool QCPColorScale::rangeZoom() const
20169 {
20170   if (!mAxisRect)
20171   {
20172     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20173     return false;
20174   }
20175   
20176   return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
20177       mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
20178       mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
20179 }
20180 
20181 /*!
20182   Sets at which side of the color scale the axis is placed, and thus also its orientation.
20183   
20184   Note that after setting \a type to a different value, the axis returned by \ref axis() will
20185   be a different one. The new axis will adopt the following properties from the previous axis: The
20186   range, scale type, label and ticker (the latter will be shared and not copied).
20187 */
20188 void QCPColorScale::setType(QCPAxis::AxisType type)
20189 {
20190   if (!mAxisRect)
20191   {
20192     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20193     return;
20194   }
20195   if (mType != type)
20196   {
20197     mType = type;
20198     QCPRange rangeTransfer(0, 6);
20199     QString labelTransfer;
20200     QSharedPointer<QCPAxisTicker> tickerTransfer;
20201     // transfer/revert some settings on old axis if it exists:
20202     bool doTransfer = !mColorAxis.isNull();
20203     if (doTransfer)
20204     {
20205       rangeTransfer = mColorAxis.data()->range();
20206       labelTransfer = mColorAxis.data()->label();
20207       tickerTransfer = mColorAxis.data()->ticker();
20208       mColorAxis.data()->setLabel(QString());
20209       disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
20210       disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
20211     }
20212     const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
20213     foreach (QCPAxis::AxisType atype, allAxisTypes)
20214     {
20215       mAxisRect.data()->axis(atype)->setTicks(atype == mType);
20216       mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
20217     }
20218     // set new mColorAxis pointer:
20219     mColorAxis = mAxisRect.data()->axis(mType);
20220     // transfer settings to new axis:
20221     if (doTransfer)
20222     {
20223       mColorAxis.data()->setRange(rangeTransfer); // range transfer necessary if axis changes from vertical to horizontal or vice versa (axes with same orientation are synchronized via signals)
20224       mColorAxis.data()->setLabel(labelTransfer);
20225       mColorAxis.data()->setTicker(tickerTransfer);
20226     }
20227     connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
20228     connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
20229     mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
20230   }
20231 }
20232 
20233 /*!
20234   Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
20235   
20236   It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
20237   also equivalent to directly accessing the \ref axis and setting its range with \ref
20238   QCPAxis::setRange.
20239   
20240   \see setDataScaleType, setGradient, rescaleDataRange
20241 */
20242 void QCPColorScale::setDataRange(const QCPRange &dataRange)
20243 {
20244   if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
20245   {
20246     mDataRange = dataRange;
20247     if (mColorAxis)
20248       mColorAxis.data()->setRange(mDataRange);
20249     emit dataRangeChanged(mDataRange);
20250   }
20251 }
20252 
20253 /*!
20254   Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
20255   or logarithmically.
20256   
20257   It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
20258   also equivalent to directly accessing the \ref axis and setting its scale type with \ref
20259   QCPAxis::setScaleType.
20260   
20261   Note that this method controls the coordinate transformation. For logarithmic scales, you will
20262   likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
20263   the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
20264   
20265   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
20266   
20267   See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
20268   creation.
20269   
20270   \see setDataRange, setGradient
20271 */
20272 void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
20273 {
20274   if (mDataScaleType != scaleType)
20275   {
20276     mDataScaleType = scaleType;
20277     if (mColorAxis)
20278       mColorAxis.data()->setScaleType(mDataScaleType);
20279     if (mDataScaleType == QCPAxis::stLogarithmic)
20280       setDataRange(mDataRange.sanitizedForLogScale());
20281     emit dataScaleTypeChanged(mDataScaleType);
20282   }
20283 }
20284 
20285 /*!
20286   Sets the color gradient that will be used to represent data values.
20287   
20288   It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
20289   
20290   \see setDataRange, setDataScaleType
20291 */
20292 void QCPColorScale::setGradient(const QCPColorGradient &gradient)
20293 {
20294   if (mGradient != gradient)
20295   {
20296     mGradient = gradient;
20297     if (mAxisRect)
20298       mAxisRect.data()->mGradientImageInvalidated = true;
20299     emit gradientChanged(mGradient);
20300   }
20301 }
20302 
20303 /*!
20304   Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
20305   the internal \ref axis.
20306 */
20307 void QCPColorScale::setLabel(const QString &str)
20308 {
20309   if (!mColorAxis)
20310   {
20311     qDebug() << Q_FUNC_INFO << "internal color axis undefined";
20312     return;
20313   }
20314   
20315   mColorAxis.data()->setLabel(str);
20316 }
20317 
20318 /*!
20319   Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
20320   will have.
20321 */
20322 void QCPColorScale::setBarWidth(int width)
20323 {
20324   mBarWidth = width;
20325 }
20326 
20327 /*!
20328   Sets whether the user can drag the data range (\ref setDataRange).
20329   
20330   Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
20331   QCustomPlot::setInteractions) to allow range dragging.
20332 */
20333 void QCPColorScale::setRangeDrag(bool enabled)
20334 {
20335   if (!mAxisRect)
20336   {
20337     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20338     return;
20339   }
20340   
20341   if (enabled)
20342   {
20343     mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
20344   } else
20345   {
20346 #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
20347     mAxisRect.data()->setRangeDrag(nullptr);
20348 #else
20349     mAxisRect.data()->setRangeDrag({});
20350 #endif
20351   }
20352 }
20353 
20354 /*!
20355   Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
20356   
20357   Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
20358   QCustomPlot::setInteractions) to allow range dragging.
20359 */
20360 void QCPColorScale::setRangeZoom(bool enabled)
20361 {
20362   if (!mAxisRect)
20363   {
20364     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20365     return;
20366   }
20367   
20368   if (enabled)
20369   {
20370     mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
20371   } else
20372   {
20373 #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
20374     mAxisRect.data()->setRangeDrag(nullptr);
20375 #else
20376     mAxisRect.data()->setRangeZoom({});
20377 #endif
20378   }
20379 }
20380 
20381 /*!
20382   Returns a list of all the color maps associated with this color scale.
20383 */
20384 QList<QCPColorMap*> QCPColorScale::colorMaps() const
20385 {
20386   QList<QCPColorMap*> result;
20387   for (int i=0; i<mParentPlot->plottableCount(); ++i)
20388   {
20389     if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
20390       if (cm->colorScale() == this)
20391         result.append(cm);
20392   }
20393   return result;
20394 }
20395 
20396 /*!
20397   Changes the data range such that all color maps associated with this color scale are fully mapped
20398   to the gradient in the data dimension.
20399   
20400   \see setDataRange
20401 */
20402 void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
20403 {
20404   QList<QCPColorMap*> maps = colorMaps();
20405   QCPRange newRange;
20406   bool haveRange = false;
20407   QCP::SignDomain sign = QCP::sdBoth;
20408   if (mDataScaleType == QCPAxis::stLogarithmic)
20409     sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
20410   foreach (QCPColorMap *map, maps)
20411   {
20412     if (!map->realVisibility() && onlyVisibleMaps)
20413       continue;
20414     QCPRange mapRange;
20415     if (map->colorScale() == this)
20416     {
20417       bool currentFoundRange = true;
20418       mapRange = map->data()->dataBounds();
20419       if (sign == QCP::sdPositive)
20420       {
20421         if (mapRange.lower <= 0 && mapRange.upper > 0)
20422           mapRange.lower = mapRange.upper*1e-3;
20423         else if (mapRange.lower <= 0 && mapRange.upper <= 0)
20424           currentFoundRange = false;
20425       } else if (sign == QCP::sdNegative)
20426       {
20427         if (mapRange.upper >= 0 && mapRange.lower < 0)
20428           mapRange.upper = mapRange.lower*1e-3;
20429         else if (mapRange.upper >= 0 && mapRange.lower >= 0)
20430           currentFoundRange = false;
20431       }
20432       if (currentFoundRange)
20433       {
20434         if (!haveRange)
20435           newRange = mapRange;
20436         else
20437           newRange.expand(mapRange);
20438         haveRange = true;
20439       }
20440     }
20441   }
20442   if (haveRange)
20443   {
20444     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data
20445     {
20446       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
20447       if (mDataScaleType == QCPAxis::stLinear)
20448       {
20449         newRange.lower = center-mDataRange.size()/2.0;
20450         newRange.upper = center+mDataRange.size()/2.0;
20451       } else // mScaleType == stLogarithmic
20452       {
20453         newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
20454         newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
20455       }
20456     }
20457     setDataRange(newRange);
20458   }
20459 }
20460 
20461 /* inherits documentation from base class */
20462 void QCPColorScale::update(UpdatePhase phase)
20463 {
20464   QCPLayoutElement::update(phase);
20465   if (!mAxisRect)
20466   {
20467     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20468     return;
20469   }
20470   
20471   mAxisRect.data()->update(phase);
20472   
20473   switch (phase)
20474   {
20475     case upMargins:
20476     {
20477       if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
20478       {
20479         setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
20480         setMinimumSize(0,               mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
20481       } else
20482       {
20483         setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
20484         setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
20485       }
20486       break;
20487     }
20488     case upLayout:
20489     {
20490       mAxisRect.data()->setOuterRect(rect());
20491       break;
20492     }
20493     default: break;
20494   }
20495 }
20496 
20497 /* inherits documentation from base class */
20498 void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
20499 {
20500   painter->setAntialiasing(false);
20501 }
20502 
20503 /* inherits documentation from base class */
20504 void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
20505 {
20506   if (!mAxisRect)
20507   {
20508     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20509     return;
20510   }
20511   mAxisRect.data()->mousePressEvent(event, details);
20512 }
20513 
20514 /* inherits documentation from base class */
20515 void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
20516 {
20517   if (!mAxisRect)
20518   {
20519     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20520     return;
20521   }
20522   mAxisRect.data()->mouseMoveEvent(event, startPos);
20523 }
20524 
20525 /* inherits documentation from base class */
20526 void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
20527 {
20528   if (!mAxisRect)
20529   {
20530     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20531     return;
20532   }
20533   mAxisRect.data()->mouseReleaseEvent(event, startPos);
20534 }
20535 
20536 /* inherits documentation from base class */
20537 void QCPColorScale::wheelEvent(QWheelEvent *event)
20538 {
20539   if (!mAxisRect)
20540   {
20541     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
20542     return;
20543   }
20544   mAxisRect.data()->wheelEvent(event);
20545 }
20546 
20547 ////////////////////////////////////////////////////////////////////////////////////////////////////
20548 //////////////////// QCPColorScaleAxisRectPrivate
20549 ////////////////////////////////////////////////////////////////////////////////////////////////////
20550 
20551 /*! \class QCPColorScaleAxisRectPrivate
20552 
20553   \internal
20554   \brief An axis rect subclass for use in a QCPColorScale
20555   
20556   This is a private class and not part of the public QCustomPlot interface.
20557   
20558   It provides the axis rect functionality for the QCPColorScale class.
20559 */
20560 
20561 
20562 /*!
20563   Creates a new instance, as a child of \a parentColorScale.
20564 */
20565 QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
20566   QCPAxisRect(parentColorScale->parentPlot(), true),
20567   mParentColorScale(parentColorScale),
20568   mGradientImageInvalidated(true)
20569 {
20570   setParentLayerable(parentColorScale);
20571   setMinimumMargins(QMargins(0, 0, 0, 0));
20572   const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
20573   foreach (QCPAxis::AxisType type, allAxisTypes)
20574   {
20575     axis(type)->setVisible(true);
20576     axis(type)->grid()->setVisible(false);
20577     axis(type)->setPadding(0);
20578     connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
20579     connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
20580   }
20581 
20582   connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
20583   connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
20584   connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
20585   connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
20586   connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
20587   connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
20588   connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
20589   connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
20590   
20591   // make layer transfers of color scale transfer to axis rect and axes
20592   // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
20593   connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
20594   foreach (QCPAxis::AxisType type, allAxisTypes)
20595     connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
20596 }
20597 
20598 /*! \internal
20599   
20600   Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
20601   it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
20602   
20603   \seebaseclassmethod
20604 */
20605 void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
20606 {
20607   if (mGradientImageInvalidated)
20608     updateGradientImage();
20609   
20610   bool mirrorHorz = false;
20611   bool mirrorVert = false;
20612   if (mParentColorScale->mColorAxis)
20613   {
20614     mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
20615     mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
20616   }
20617   
20618   painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
20619   QCPAxisRect::draw(painter);
20620 }
20621 
20622 /*! \internal
20623 
20624   Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
20625   generate a gradient image. This gradient image will be used in the \ref draw method.
20626 */
20627 void QCPColorScaleAxisRectPrivate::updateGradientImage()
20628 {
20629   if (rect().isEmpty())
20630     return;
20631   
20632   const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
20633   int n = mParentColorScale->mGradient.levelCount();
20634   int w, h;
20635   QVector<double> data(n);
20636   for (int i=0; i<n; ++i)
20637     data[i] = i;
20638   if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
20639   {
20640     w = n;
20641     h = rect().height();
20642     mGradientImage = QImage(w, h, format);
20643     QVector<QRgb*> pixels;
20644     for (int y=0; y<h; ++y)
20645       pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
20646     mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
20647     for (int y=1; y<h; ++y)
20648       memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
20649   } else
20650   {
20651     w = rect().width();
20652     h = n;
20653     mGradientImage = QImage(w, h, format);
20654     for (int y=0; y<h; ++y)
20655     {
20656       QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
20657       const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
20658       for (int x=0; x<w; ++x)
20659         pixels[x] = lineColor;
20660     }
20661   }
20662   mGradientImageInvalidated = false;
20663 }
20664 
20665 /*! \internal
20666 
20667   This slot is connected to the selectionChanged signals of the four axes in the constructor. It
20668   synchronizes the selection state of the axes.
20669 */
20670 void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
20671 {
20672   // axis bases of four axes shall always (de-)selected synchronously:
20673   const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
20674   foreach (QCPAxis::AxisType type, allAxisTypes)
20675   {
20676     if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
20677       if (senderAxis->axisType() == type)
20678         continue;
20679     
20680     if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
20681     {
20682       if (selectedParts.testFlag(QCPAxis::spAxis))
20683         axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
20684       else
20685         axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
20686     }
20687   }
20688 }
20689 
20690 /*! \internal
20691 
20692   This slot is connected to the selectableChanged signals of the four axes in the constructor. It
20693   synchronizes the selectability of the axes.
20694 */
20695 void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
20696 {
20697   // synchronize axis base selectability:
20698   const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
20699   foreach (QCPAxis::AxisType type, allAxisTypes)
20700   {
20701     if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
20702       if (senderAxis->axisType() == type)
20703         continue;
20704     
20705     if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
20706     {
20707       if (selectableParts.testFlag(QCPAxis::spAxis))
20708         axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
20709       else
20710         axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
20711     }
20712   }
20713 }
20714 /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
20715 
20716 
20717 /* including file 'src/plottables/plottable-graph.cpp' */
20718 /* modified 2021-03-29T02:30:44, size 74518            */
20719 
20720 ////////////////////////////////////////////////////////////////////////////////////////////////////
20721 //////////////////// QCPGraphData
20722 ////////////////////////////////////////////////////////////////////////////////////////////////////
20723 
20724 /*! \class QCPGraphData
20725   \brief Holds the data of one single data point for QCPGraph.
20726   
20727   The stored data is:
20728   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
20729   \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
20730   
20731   The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
20732   \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
20733   documentation there for an explanation regarding the data type's generic methods.
20734   
20735   \see QCPGraphDataContainer
20736 */
20737 
20738 /* start documentation of inline functions */
20739 
20740 /*! \fn double QCPGraphData::sortKey() const
20741   
20742   Returns the \a key member of this data point.
20743   
20744   For a general explanation of what this method is good for in the context of the data container,
20745   see the documentation of \ref QCPDataContainer.
20746 */
20747 
20748 /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
20749   
20750   Returns a data point with the specified \a sortKey. All other members are set to zero.
20751   
20752   For a general explanation of what this method is good for in the context of the data container,
20753   see the documentation of \ref QCPDataContainer.
20754 */
20755 
20756 /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
20757   
20758   Since the member \a key is both the data point key coordinate and the data ordering parameter,
20759   this method returns true.
20760   
20761   For a general explanation of what this method is good for in the context of the data container,
20762   see the documentation of \ref QCPDataContainer.
20763 */
20764 
20765 /*! \fn double QCPGraphData::mainKey() const
20766   
20767   Returns the \a key member of this data point.
20768   
20769   For a general explanation of what this method is good for in the context of the data container,
20770   see the documentation of \ref QCPDataContainer.
20771 */
20772 
20773 /*! \fn double QCPGraphData::mainValue() const
20774   
20775   Returns the \a value member of this data point.
20776   
20777   For a general explanation of what this method is good for in the context of the data container,
20778   see the documentation of \ref QCPDataContainer.
20779 */
20780 
20781 /*! \fn QCPRange QCPGraphData::valueRange() const
20782   
20783   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
20784   
20785   For a general explanation of what this method is good for in the context of the data container,
20786   see the documentation of \ref QCPDataContainer.
20787 */
20788 
20789 /* end documentation of inline functions */
20790 
20791 /*!
20792   Constructs a data point with key and value set to zero.
20793 */
20794 QCPGraphData::QCPGraphData() :
20795   key(0),
20796   value(0)
20797 {
20798 }
20799 
20800 /*!
20801   Constructs a data point with the specified \a key and \a value.
20802 */
20803 QCPGraphData::QCPGraphData(double key, double value) :
20804   key(key),
20805   value(value)
20806 {
20807 }
20808 
20809 
20810 ////////////////////////////////////////////////////////////////////////////////////////////////////
20811 //////////////////// QCPGraph
20812 ////////////////////////////////////////////////////////////////////////////////////////////////////
20813 
20814 /*! \class QCPGraph
20815   \brief A plottable representing a graph in a plot.
20816 
20817   \image html QCPGraph.png
20818   
20819   Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
20820   accessed via QCustomPlot::graph.
20821 
20822   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
20823   also access and modify the data via the \ref data method, which returns a pointer to the internal
20824   \ref QCPGraphDataContainer.
20825   
20826   Graphs are used to display single-valued data. Single-valued means that there should only be one
20827   data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
20828   want to plot non-single-valued curves, rather use the QCPCurve plottable.
20829   
20830   Gaps in the graph line can be created by adding data points with NaN as value
20831   (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
20832   separated.
20833   
20834   \section qcpgraph-appearance Changing the appearance
20835   
20836   The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
20837   of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
20838   
20839   \subsection filling Filling under or between graphs
20840   
20841   QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
20842   the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
20843   just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
20844   
20845   By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
20846   between this graph and another one, call \ref setChannelFillGraph with the other graph as
20847   parameter.
20848 
20849   \see QCustomPlot::addGraph, QCustomPlot::graph
20850 */
20851 
20852 /* start of documentation of inline functions */
20853 
20854 /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
20855   
20856   Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
20857   use it to directly manipulate the data, which may be more convenient and faster than using the
20858   regular \ref setData or \ref addData methods.
20859 */
20860 
20861 /* end of documentation of inline functions */
20862 
20863 /*!
20864   Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
20865   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
20866   the same orientation. If either of these restrictions is violated, a corresponding message is
20867   printed to the debug output (qDebug), the construction is not aborted, though.
20868   
20869   The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
20870   keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
20871   but use QCustomPlot::removePlottable() instead.
20872   
20873   To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
20874 */
20875 QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
20876   QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
20877   mLineStyle{},
20878   mScatterSkip{},
20879   mAdaptiveSampling{}
20880 {
20881   // special handling for QCPGraphs to maintain the simple graph interface:
20882   mParentPlot->registerGraph(this);
20883 
20884   setPen(QPen(Qt::blue, 0));
20885   setBrush(Qt::NoBrush);
20886   
20887   setLineStyle(lsLine);
20888   setScatterSkip(0);
20889   setChannelFillGraph(nullptr);
20890   setAdaptiveSampling(true);
20891 }
20892 
20893 QCPGraph::~QCPGraph()
20894 {
20895 }
20896 
20897 /*! \overload
20898   
20899   Replaces the current data container with the provided \a data container.
20900   
20901   Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
20902   Modifying the data in the container will then affect all graphs that share the container. Sharing
20903   can be achieved by simply exchanging the data containers wrapped in shared pointers:
20904   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
20905   
20906   If you do not wish to share containers, but create a copy from an existing container, rather use
20907   the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
20908   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
20909   
20910   \see addData
20911 */
20912 void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
20913 {
20914   mDataContainer = data;
20915 }
20916 
20917 /*! \overload
20918   
20919   Replaces the current data with the provided points in \a keys and \a values. The provided
20920   vectors should have equal length. Else, the number of added points will be the size of the
20921   smallest vector.
20922   
20923   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
20924   can set \a alreadySorted to true, to improve performance by saving a sorting run.
20925   
20926   \see addData
20927 */
20928 void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
20929 {
20930   mDataContainer->clear();
20931   addData(keys, values, alreadySorted);
20932 }
20933 
20934 /*!
20935   Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
20936   \ref lsNone and \ref setScatterStyle to the desired scatter style.
20937   
20938   \see setScatterStyle
20939 */
20940 void QCPGraph::setLineStyle(LineStyle ls)
20941 {
20942   mLineStyle = ls;
20943 }
20944 
20945 /*!
20946   Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
20947   are drawn (e.g. for line-only-plots with appropriate line style).
20948   
20949   \see QCPScatterStyle, setLineStyle
20950 */
20951 void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
20952 {
20953   mScatterStyle = style;
20954 }
20955 
20956 /*!
20957   If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
20958   scatter points are skipped/not drawn after every drawn scatter point.
20959 
20960   This can be used to make the data appear sparser while for example still having a smooth line,
20961   and to improve performance for very high density plots.
20962 
20963   If \a skip is set to 0 (default), all scatter points are drawn.
20964 
20965   \see setScatterStyle
20966 */
20967 void QCPGraph::setScatterSkip(int skip)
20968 {
20969   mScatterSkip = qMax(0, skip);
20970 }
20971 
20972 /*!
20973   Sets the target graph for filling the area between this graph and \a targetGraph with the current
20974   brush (\ref setBrush).
20975   
20976   When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
20977   disable any filling, set the brush to Qt::NoBrush.
20978 
20979   \see setBrush
20980 */
20981 void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
20982 {
20983   // prevent setting channel target to this graph itself:
20984   if (targetGraph == this)
20985   {
20986     qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
20987     mChannelFillGraph = nullptr;
20988     return;
20989   }
20990   // prevent setting channel target to a graph not in the plot:
20991   if (targetGraph && targetGraph->mParentPlot != mParentPlot)
20992   {
20993     qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
20994     mChannelFillGraph = nullptr;
20995     return;
20996   }
20997   
20998   mChannelFillGraph = targetGraph;
20999 }
21000 
21001 /*!
21002   Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
21003   sampling technique can drastically improve the replot performance for graphs with a larger number
21004   of points (e.g. above 10,000), without notably changing the appearance of the graph.
21005   
21006   By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
21007   sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
21008   disadvantage in almost all cases.
21009   
21010   \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
21011   
21012   As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
21013   reproduced reliably, as well as the overall shape of the data set. The replot time reduces
21014   dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
21015   
21016   \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
21017   
21018   Care must be taken when using high-density scatter plots in combination with adaptive sampling.
21019   The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
21020   gives a significant reduction of replot times, but not quite as much as for line plots. This is
21021   because scatter plots inherently need more data points to be preserved in order to still resemble
21022   the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
21023   identical, as banding occurs for the outer data points. This is in fact intentional, such that
21024   the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
21025   depends on the point density, i.e. the number of points in the plot.
21026   
21027   For some situations with scatter plots it might thus be desirable to manually turn adaptive
21028   sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
21029   enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
21030   back to true afterwards.
21031 */
21032 void QCPGraph::setAdaptiveSampling(bool enabled)
21033 {
21034   mAdaptiveSampling = enabled;
21035 }
21036 
21037 /*! \overload
21038   
21039   Adds the provided points in \a keys and \a values to the current data. The provided vectors
21040   should have equal length. Else, the number of added points will be the size of the smallest
21041   vector.
21042   
21043   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
21044   can set \a alreadySorted to true, to improve performance by saving a sorting run.
21045   
21046   Alternatively, you can also access and modify the data directly via the \ref data method, which
21047   returns a pointer to the internal data container.
21048 */
21049 void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
21050 {
21051   if (keys.size() != values.size())
21052     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
21053   const int n = qMin(keys.size(), values.size());
21054   QVector<QCPGraphData> tempData(n);
21055   QVector<QCPGraphData>::iterator it = tempData.begin();
21056   const QVector<QCPGraphData>::iterator itEnd = tempData.end();
21057   int i = 0;
21058   while (it != itEnd)
21059   {
21060     it->key = keys[i];
21061     it->value = values[i];
21062     ++it;
21063     ++i;
21064   }
21065   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
21066 }
21067 
21068 /*! \overload
21069   
21070   Adds the provided data point as \a key and \a value to the current data.
21071   
21072   Alternatively, you can also access and modify the data directly via the \ref data method, which
21073   returns a pointer to the internal data container.
21074 */
21075 void QCPGraph::addData(double key, double value)
21076 {
21077   mDataContainer->add(QCPGraphData(key, value));
21078 }
21079 
21080 /*!
21081   Implements a selectTest specific to this plottable's point geometry.
21082 
21083   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
21084   point to \a pos.
21085   
21086   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
21087 */
21088 double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
21089 {
21090   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
21091     return -1;
21092   if (!mKeyAxis || !mValueAxis)
21093     return -1;
21094   
21095   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
21096   {
21097     QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
21098     double result = pointDistance(pos, closestDataPoint);
21099     if (details)
21100     {
21101       int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
21102       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
21103     }
21104     return result;
21105   } else
21106     return -1;
21107 }
21108 
21109 /* inherits documentation from base class */
21110 QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
21111 {
21112   return mDataContainer->keyRange(foundRange, inSignDomain);
21113 }
21114 
21115 /* inherits documentation from base class */
21116 QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
21117 {
21118   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
21119 }
21120 
21121 /* inherits documentation from base class */
21122 void QCPGraph::draw(QCPPainter *painter)
21123 {
21124   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
21125   if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
21126   if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
21127   
21128   QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
21129   
21130   // loop over and draw segments of unselected/selected data:
21131   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
21132   getDataSegments(selectedSegments, unselectedSegments);
21133   allSegments << unselectedSegments << selectedSegments;
21134   for (int i=0; i<allSegments.size(); ++i)
21135   {
21136     bool isSelectedSegment = i >= unselectedSegments.size();
21137     // get line pixel points appropriate to line style:
21138     QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
21139     getLines(&lines, lineDataRange);
21140     
21141     // check data validity if flag set:
21142 #ifdef QCUSTOMPLOT_CHECK_DATA
21143     QCPGraphDataContainer::const_iterator it;
21144     for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
21145     {
21146       if (QCP::isInvalidData(it->key, it->value))
21147         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
21148     }
21149 #endif
21150     
21151     // draw fill of graph:
21152     if (isSelectedSegment && mSelectionDecorator)
21153       mSelectionDecorator->applyBrush(painter);
21154     else
21155       painter->setBrush(mBrush);
21156     painter->setPen(Qt::NoPen);
21157     drawFill(painter, &lines);
21158     
21159     // draw line:
21160     if (mLineStyle != lsNone)
21161     {
21162       if (isSelectedSegment && mSelectionDecorator)
21163         mSelectionDecorator->applyPen(painter);
21164       else
21165         painter->setPen(mPen);
21166       painter->setBrush(Qt::NoBrush);
21167       if (mLineStyle == lsImpulse)
21168         drawImpulsePlot(painter, lines);
21169       else
21170         drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
21171     }
21172     
21173     // draw scatters:
21174     QCPScatterStyle finalScatterStyle = mScatterStyle;
21175     if (isSelectedSegment && mSelectionDecorator)
21176       finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
21177     if (!finalScatterStyle.isNone())
21178     {
21179       getScatters(&scatters, allSegments.at(i));
21180       drawScatterPlot(painter, scatters, finalScatterStyle);
21181     }
21182   }
21183   
21184   // draw other selection decoration that isn't just line/scatter pens and brushes:
21185   if (mSelectionDecorator)
21186     mSelectionDecorator->drawDecoration(painter, selection());
21187 }
21188 
21189 /* inherits documentation from base class */
21190 void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
21191 {
21192   // draw fill:
21193   if (mBrush.style() != Qt::NoBrush)
21194   {
21195     applyFillAntialiasingHint(painter);
21196     painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
21197   }
21198   // draw line vertically centered:
21199   if (mLineStyle != lsNone)
21200   {
21201     applyDefaultAntialiasingHint(painter);
21202     painter->setPen(mPen);
21203     painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
21204   }
21205   // draw scatter symbol:
21206   if (!mScatterStyle.isNone())
21207   {
21208     applyScattersAntialiasingHint(painter);
21209     // scale scatter pixmap if it's too large to fit in legend icon rect:
21210     if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
21211     {
21212       QCPScatterStyle scaledStyle(mScatterStyle);
21213       scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
21214       scaledStyle.applyTo(painter, mPen);
21215       scaledStyle.drawShape(painter, QRectF(rect).center());
21216     } else
21217     {
21218       mScatterStyle.applyTo(painter, mPen);
21219       mScatterStyle.drawShape(painter, QRectF(rect).center());
21220     }
21221   }
21222 }
21223 
21224 /*! \internal
21225 
21226   This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
21227   out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
21228   according to the line style of the graph.
21229 
21230   \a lines will be filled with points in pixel coordinates, that can be drawn with the according
21231   draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
21232   aren't necessarily the original data points. For example, step line styles require additional
21233   points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
21234   lines vector will be empty.
21235 
21236   \a dataRange specifies the beginning and ending data indices that will be taken into account for
21237   conversion. In this function, the specified range may exceed the total data bounds without harm:
21238   a correspondingly trimmed data range will be used. This takes the burden off the user of this
21239   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
21240   getDataSegments.
21241 
21242   \see getScatters
21243 */
21244 void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
21245 {
21246   if (!lines) return;
21247   QCPGraphDataContainer::const_iterator begin, end;
21248   getVisibleDataBounds(begin, end, dataRange);
21249   if (begin == end)
21250   {
21251     lines->clear();
21252     return;
21253   }
21254   
21255   QVector<QCPGraphData> lineData;
21256   if (mLineStyle != lsNone)
21257     getOptimizedLineData(&lineData, begin, end);
21258   
21259   if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
21260     std::reverse(lineData.begin(), lineData.end());
21261 
21262   switch (mLineStyle)
21263   {
21264     case lsNone: lines->clear(); break;
21265     case lsLine: *lines = dataToLines(lineData); break;
21266     case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
21267     case lsStepRight: *lines = dataToStepRightLines(lineData); break;
21268     case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
21269     case lsImpulse: *lines = dataToImpulseLines(lineData); break;
21270   }
21271 }
21272 
21273 /*! \internal
21274 
21275   This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
21276   converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
21277   passed to \ref drawScatterPlot.
21278 
21279   \a dataRange specifies the beginning and ending data indices that will be taken into account for
21280   conversion. In this function, the specified range may exceed the total data bounds without harm:
21281   a correspondingly trimmed data range will be used. This takes the burden off the user of this
21282   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
21283   getDataSegments.
21284 */
21285 void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
21286 {
21287   if (!scatters) return;
21288   QCPAxis *keyAxis = mKeyAxis.data();
21289   QCPAxis *valueAxis = mValueAxis.data();
21290   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
21291   
21292   QCPGraphDataContainer::const_iterator begin, end;
21293   getVisibleDataBounds(begin, end, dataRange);
21294   if (begin == end)
21295   {
21296     scatters->clear();
21297     return;
21298   }
21299   
21300   QVector<QCPGraphData> data;
21301   getOptimizedScatterData(&data, begin, end);
21302   
21303   if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
21304     std::reverse(data.begin(), data.end());
21305   
21306   scatters->resize(data.size());
21307   if (keyAxis->orientation() == Qt::Vertical)
21308   {
21309     for (int i=0; i<data.size(); ++i)
21310     {
21311       if (!qIsNaN(data.at(i).value))
21312       {
21313         (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
21314         (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
21315       }
21316     }
21317   } else
21318   {
21319     for (int i=0; i<data.size(); ++i)
21320     {
21321       if (!qIsNaN(data.at(i).value))
21322       {
21323         (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
21324         (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
21325       }
21326     }
21327   }
21328 }
21329 
21330 /*! \internal
21331 
21332   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
21333   coordinate points which are suitable for drawing the line style \ref lsLine.
21334   
21335   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
21336   getLines if the line style is set accordingly.
21337 
21338   \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
21339 */
21340 QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
21341 {
21342   QVector<QPointF> result;
21343   QCPAxis *keyAxis = mKeyAxis.data();
21344   QCPAxis *valueAxis = mValueAxis.data();
21345   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
21346 
21347   result.resize(data.size());
21348   
21349   // transform data points to pixels:
21350   if (keyAxis->orientation() == Qt::Vertical)
21351   {
21352     for (int i=0; i<data.size(); ++i)
21353     {
21354       result[i].setX(valueAxis->coordToPixel(data.at(i).value));
21355       result[i].setY(keyAxis->coordToPixel(data.at(i).key));
21356     }
21357   } else // key axis is horizontal
21358   {
21359     for (int i=0; i<data.size(); ++i)
21360     {
21361       result[i].setX(keyAxis->coordToPixel(data.at(i).key));
21362       result[i].setY(valueAxis->coordToPixel(data.at(i).value));
21363     }
21364   }
21365   return result;
21366 }
21367 
21368 /*! \internal
21369 
21370   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
21371   coordinate points which are suitable for drawing the line style \ref lsStepLeft.
21372   
21373   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
21374   getLines if the line style is set accordingly.
21375 
21376   \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
21377 */
21378 QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
21379 {
21380   QVector<QPointF> result;
21381   QCPAxis *keyAxis = mKeyAxis.data();
21382   QCPAxis *valueAxis = mValueAxis.data();
21383   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
21384   
21385   result.resize(data.size()*2);
21386   
21387   // calculate steps from data and transform to pixel coordinates:
21388   if (keyAxis->orientation() == Qt::Vertical)
21389   {
21390     double lastValue = valueAxis->coordToPixel(data.first().value);
21391     for (int i=0; i<data.size(); ++i)
21392     {
21393       const double key = keyAxis->coordToPixel(data.at(i).key);
21394       result[i*2+0].setX(lastValue);
21395       result[i*2+0].setY(key);
21396       lastValue = valueAxis->coordToPixel(data.at(i).value);
21397       result[i*2+1].setX(lastValue);
21398       result[i*2+1].setY(key);
21399     }
21400   } else // key axis is horizontal
21401   {
21402     double lastValue = valueAxis->coordToPixel(data.first().value);
21403     for (int i=0; i<data.size(); ++i)
21404     {
21405       const double key = keyAxis->coordToPixel(data.at(i).key);
21406       result[i*2+0].setX(key);
21407       result[i*2+0].setY(lastValue);
21408       lastValue = valueAxis->coordToPixel(data.at(i).value);
21409       result[i*2+1].setX(key);
21410       result[i*2+1].setY(lastValue);
21411     }
21412   }
21413   return result;
21414 }
21415 
21416 /*! \internal
21417 
21418   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
21419   coordinate points which are suitable for drawing the line style \ref lsStepRight.
21420   
21421   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
21422   getLines if the line style is set accordingly.
21423 
21424   \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
21425 */
21426 QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
21427 {
21428   QVector<QPointF> result;
21429   QCPAxis *keyAxis = mKeyAxis.data();
21430   QCPAxis *valueAxis = mValueAxis.data();
21431   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
21432   
21433   result.resize(data.size()*2);
21434   
21435   // calculate steps from data and transform to pixel coordinates:
21436   if (keyAxis->orientation() == Qt::Vertical)
21437   {
21438     double lastKey = keyAxis->coordToPixel(data.first().key);
21439     for (int i=0; i<data.size(); ++i)
21440     {
21441       const double value = valueAxis->coordToPixel(data.at(i).value);
21442       result[i*2+0].setX(value);
21443       result[i*2+0].setY(lastKey);
21444       lastKey = keyAxis->coordToPixel(data.at(i).key);
21445       result[i*2+1].setX(value);
21446       result[i*2+1].setY(lastKey);
21447     }
21448   } else // key axis is horizontal
21449   {
21450     double lastKey = keyAxis->coordToPixel(data.first().key);
21451     for (int i=0; i<data.size(); ++i)
21452     {
21453       const double value = valueAxis->coordToPixel(data.at(i).value);
21454       result[i*2+0].setX(lastKey);
21455       result[i*2+0].setY(value);
21456       lastKey = keyAxis->coordToPixel(data.at(i).key);
21457       result[i*2+1].setX(lastKey);
21458       result[i*2+1].setY(value);
21459     }
21460   }
21461   return result;
21462 }
21463 
21464 /*! \internal
21465 
21466   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
21467   coordinate points which are suitable for drawing the line style \ref lsStepCenter.
21468   
21469   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
21470   getLines if the line style is set accordingly.
21471 
21472   \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
21473 */
21474 QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
21475 {
21476   QVector<QPointF> result;
21477   QCPAxis *keyAxis = mKeyAxis.data();
21478   QCPAxis *valueAxis = mValueAxis.data();
21479   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
21480   
21481   result.resize(data.size()*2);
21482   
21483   // calculate steps from data and transform to pixel coordinates:
21484   if (keyAxis->orientation() == Qt::Vertical)
21485   {
21486     double lastKey = keyAxis->coordToPixel(data.first().key);
21487     double lastValue = valueAxis->coordToPixel(data.first().value);
21488     result[0].setX(lastValue);
21489     result[0].setY(lastKey);
21490     for (int i=1; i<data.size(); ++i)
21491     {
21492       const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
21493       result[i*2-1].setX(lastValue);
21494       result[i*2-1].setY(key);
21495       lastValue = valueAxis->coordToPixel(data.at(i).value);
21496       lastKey = keyAxis->coordToPixel(data.at(i).key);
21497       result[i*2+0].setX(lastValue);
21498       result[i*2+0].setY(key);
21499     }
21500     result[data.size()*2-1].setX(lastValue);
21501     result[data.size()*2-1].setY(lastKey);
21502   } else // key axis is horizontal
21503   {
21504     double lastKey = keyAxis->coordToPixel(data.first().key);
21505     double lastValue = valueAxis->coordToPixel(data.first().value);
21506     result[0].setX(lastKey);
21507     result[0].setY(lastValue);
21508     for (int i=1; i<data.size(); ++i)
21509     {
21510       const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
21511       result[i*2-1].setX(key);
21512       result[i*2-1].setY(lastValue);
21513       lastValue = valueAxis->coordToPixel(data.at(i).value);
21514       lastKey = keyAxis->coordToPixel(data.at(i).key);
21515       result[i*2+0].setX(key);
21516       result[i*2+0].setY(lastValue);
21517     }
21518     result[data.size()*2-1].setX(lastKey);
21519     result[data.size()*2-1].setY(lastValue);
21520   }
21521   return result;
21522 }
21523 
21524 /*! \internal
21525 
21526   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
21527   coordinate points which are suitable for drawing the line style \ref lsImpulse.
21528   
21529   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
21530   getLines if the line style is set accordingly.
21531 
21532   \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
21533 */
21534 QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
21535 {
21536   QVector<QPointF> result;
21537   QCPAxis *keyAxis = mKeyAxis.data();
21538   QCPAxis *valueAxis = mValueAxis.data();
21539   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
21540   
21541   result.resize(data.size()*2);
21542   
21543   // transform data points to pixels:
21544   if (keyAxis->orientation() == Qt::Vertical)
21545   {
21546     for (int i=0; i<data.size(); ++i)
21547     {
21548       const double key = keyAxis->coordToPixel(data.at(i).key);
21549       result[i*2+0].setX(valueAxis->coordToPixel(0));
21550       result[i*2+0].setY(key);
21551       result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
21552       result[i*2+1].setY(key);
21553     }
21554   } else // key axis is horizontal
21555   {
21556     for (int i=0; i<data.size(); ++i)
21557     {
21558       const double key = keyAxis->coordToPixel(data.at(i).key);
21559       result[i*2+0].setX(key);
21560       result[i*2+0].setY(valueAxis->coordToPixel(0));
21561       result[i*2+1].setX(key);
21562       result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
21563     }
21564   }
21565   return result;
21566 }
21567 
21568 /*! \internal
21569   
21570   Draws the fill of the graph using the specified \a painter, with the currently set brush.
21571   
21572   Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
21573   getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
21574   
21575   In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
21576   this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
21577   operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
21578   segments of the two involved graphs, before passing the overlapping pairs to \ref
21579   getChannelFillPolygon.
21580   
21581   Pass the points of this graph's line as \a lines, in pixel coordinates.
21582 
21583   \see drawLinePlot, drawImpulsePlot, drawScatterPlot
21584 */
21585 void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
21586 {
21587   if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
21588   if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
21589   
21590   applyFillAntialiasingHint(painter);
21591   const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
21592   if (!mChannelFillGraph)
21593   {
21594     // draw base fill under graph, fill goes all the way to the zero-value-line:
21595     foreach (QCPDataRange segment, segments)
21596       painter->drawPolygon(getFillPolygon(lines, segment));
21597   } else
21598   {
21599     // draw fill between this graph and mChannelFillGraph:
21600     QVector<QPointF> otherLines;
21601     mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
21602     if (!otherLines.isEmpty())
21603     {
21604       QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
21605       QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
21606       for (int i=0; i<segmentPairs.size(); ++i)
21607         painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
21608     }
21609   }
21610 }
21611 
21612 /*! \internal
21613 
21614   Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
21615   scatters will be drawn with \a painter and have the appearance as specified in \a style.
21616 
21617   \see drawLinePlot, drawImpulsePlot
21618 */
21619 void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
21620 {
21621   applyScattersAntialiasingHint(painter);
21622   style.applyTo(painter, mPen);
21623   foreach (const QPointF &scatter, scatters)
21624     style.drawShape(painter, scatter.x(), scatter.y());
21625 }
21626 
21627 /*!  \internal
21628   
21629   Draws lines between the points in \a lines, given in pixel coordinates.
21630   
21631   \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
21632 */
21633 void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
21634 {
21635   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
21636   {
21637     applyDefaultAntialiasingHint(painter);
21638     drawPolyline(painter, lines);
21639   }
21640 }
21641 
21642 /*! \internal
21643 
21644   Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
21645   pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
21646   from the regular graph data points.
21647 
21648   \see drawLinePlot, drawScatterPlot
21649 */
21650 void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
21651 {
21652   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
21653   {
21654     applyDefaultAntialiasingHint(painter);
21655     QPen oldPen = painter->pen();
21656     QPen newPen = painter->pen();
21657     newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
21658     painter->setPen(newPen);
21659     painter->drawLines(lines);
21660     painter->setPen(oldPen);
21661   }
21662 }
21663 
21664 /*! \internal
21665 
21666   Returns via \a lineData the data points that need to be visualized for this graph when plotting
21667   graph lines, taking into consideration the currently visible axis ranges and, if \ref
21668   setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
21669   further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
21670   getDataSegments).
21671 
21672   This method is used by \ref getLines to retrieve the basic working set of data.
21673 
21674   \see getOptimizedScatterData
21675 */
21676 void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
21677 {
21678   if (!lineData) return;
21679   QCPAxis *keyAxis = mKeyAxis.data();
21680   QCPAxis *valueAxis = mValueAxis.data();
21681   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
21682   if (begin == end) return;
21683   
21684   int dataCount = int(end-begin);
21685   int maxCount = (std::numeric_limits<int>::max)();
21686   if (mAdaptiveSampling)
21687   {
21688     double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
21689     if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
21690       maxCount = int(2*keyPixelSpan+2);
21691   }
21692   
21693   if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
21694   {
21695     QCPGraphDataContainer::const_iterator it = begin;
21696     double minValue = it->value;
21697     double maxValue = it->value;
21698     QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
21699     int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
21700     int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
21701     double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
21702     double lastIntervalEndKey = currentIntervalStartKey;
21703     double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
21704     bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
21705     int intervalDataCount = 1;
21706     ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
21707     while (it != end)
21708     {
21709       if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
21710       {
21711         if (it->value < minValue)
21712           minValue = it->value;
21713         else if (it->value > maxValue)
21714           maxValue = it->value;
21715         ++intervalDataCount;
21716       } else // new pixel interval started
21717       {
21718         if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
21719         {
21720           if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
21721             lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
21722           lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
21723           lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
21724           if (it->key > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point
21725             lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
21726         } else
21727           lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
21728         lastIntervalEndKey = (it-1)->key;
21729         minValue = it->value;
21730         maxValue = it->value;
21731         currentIntervalFirstPoint = it;
21732         currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
21733         if (keyEpsilonVariable)
21734           keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
21735         intervalDataCount = 1;
21736       }
21737       ++it;
21738     }
21739     // handle last interval:
21740     if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
21741     {
21742       if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
21743         lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
21744       lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
21745       lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
21746     } else
21747       lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
21748     
21749   } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
21750   {
21751     lineData->resize(dataCount);
21752     std::copy(begin, end, lineData->begin());
21753   }
21754 }
21755 
21756 /*! \internal
21757 
21758   Returns via \a scatterData the data points that need to be visualized for this graph when
21759   plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
21760   setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
21761   further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
21762   getDataSegments).
21763 
21764   This method is used by \ref getScatters to retrieve the basic working set of data.
21765 
21766   \see getOptimizedLineData
21767 */
21768 void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
21769 {
21770   if (!scatterData) return;
21771   QCPAxis *keyAxis = mKeyAxis.data();
21772   QCPAxis *valueAxis = mValueAxis.data();
21773   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
21774   
21775   const int scatterModulo = mScatterSkip+1;
21776   const bool doScatterSkip = mScatterSkip > 0;
21777   int beginIndex = int(begin-mDataContainer->constBegin());
21778   int endIndex = int(end-mDataContainer->constBegin());
21779   while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
21780   {
21781     ++beginIndex;
21782     ++begin;
21783   }
21784   if (begin == end) return;
21785   int dataCount = int(end-begin);
21786   int maxCount = (std::numeric_limits<int>::max)();
21787   if (mAdaptiveSampling)
21788   {
21789     int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
21790     maxCount = 2*keyPixelSpan+2;
21791   }
21792   
21793   if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
21794   {
21795     double valueMaxRange = valueAxis->range().upper;
21796     double valueMinRange = valueAxis->range().lower;
21797     QCPGraphDataContainer::const_iterator it = begin;
21798     int itIndex = int(beginIndex);
21799     double minValue = it->value;
21800     double maxValue = it->value;
21801     QCPGraphDataContainer::const_iterator minValueIt = it;
21802     QCPGraphDataContainer::const_iterator maxValueIt = it;
21803     QCPGraphDataContainer::const_iterator currentIntervalStart = it;
21804     int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
21805     int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
21806     double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
21807     double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
21808     bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
21809     int intervalDataCount = 1;
21810     // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
21811     if (!doScatterSkip)
21812       ++it;
21813     else
21814     {
21815       itIndex += scatterModulo;
21816       if (itIndex < endIndex) // make sure we didn't jump over end
21817         it += scatterModulo;
21818       else
21819       {
21820         it = end;
21821         itIndex = endIndex;
21822       }
21823     }
21824     // main loop over data points:
21825     while (it != end)
21826     {
21827       if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
21828       {
21829         if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
21830         {
21831           minValue = it->value;
21832           minValueIt = it;
21833         } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
21834         {
21835           maxValue = it->value;
21836           maxValueIt = it;
21837         }
21838         ++intervalDataCount;
21839       } else // new pixel started
21840       {
21841         if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
21842         {
21843           // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
21844           double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
21845           int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
21846           QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
21847           int c = 0;
21848           while (intervalIt != it)
21849           {
21850             if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
21851               scatterData->append(*intervalIt);
21852             ++c;
21853             if (!doScatterSkip)
21854               ++intervalIt;
21855             else
21856               intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
21857           }
21858         } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
21859           scatterData->append(*currentIntervalStart);
21860         minValue = it->value;
21861         maxValue = it->value;
21862         currentIntervalStart = it;
21863         currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
21864         if (keyEpsilonVariable)
21865           keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
21866         intervalDataCount = 1;
21867       }
21868       // advance to next data point:
21869       if (!doScatterSkip)
21870         ++it;
21871       else
21872       {
21873         itIndex += scatterModulo;
21874         if (itIndex < endIndex) // make sure we didn't jump over end
21875           it += scatterModulo;
21876         else
21877         {
21878           it = end;
21879           itIndex = endIndex;
21880         }
21881       }
21882     }
21883     // handle last interval:
21884     if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
21885     {
21886       // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
21887       double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
21888       int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
21889       QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
21890       int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
21891       int c = 0;
21892       while (intervalIt != it)
21893       {
21894         if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
21895           scatterData->append(*intervalIt);
21896         ++c;
21897         if (!doScatterSkip)
21898           ++intervalIt;
21899         else // here we can't guarantee that adding scatterModulo doesn't exceed "it" (because "it" is equal to "end" here, and "end" isn't scatterModulo-aligned), so check via index comparison:
21900         {
21901           intervalItIndex += scatterModulo;
21902           if (intervalItIndex < itIndex)
21903             intervalIt += scatterModulo;
21904           else
21905           {
21906             intervalIt = it;
21907             intervalItIndex = itIndex;
21908           }
21909         }
21910       }
21911     } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
21912       scatterData->append(*currentIntervalStart);
21913     
21914   } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
21915   {
21916     QCPGraphDataContainer::const_iterator it = begin;
21917     int itIndex = beginIndex;
21918     scatterData->reserve(dataCount);
21919     while (it != end)
21920     {
21921       scatterData->append(*it);
21922       // advance to next data point:
21923       if (!doScatterSkip)
21924         ++it;
21925       else
21926       {
21927         itIndex += scatterModulo;
21928         if (itIndex < endIndex)
21929           it += scatterModulo;
21930         else
21931         {
21932           it = end;
21933           itIndex = endIndex;
21934         }
21935       }
21936     }
21937   }
21938 }
21939 
21940 /*!
21941   This method outputs the currently visible data range via \a begin and \a end. The returned range
21942   will also never exceed \a rangeRestriction.
21943 
21944   This method takes into account that the drawing of data lines at the axis rect border always
21945   requires the points just outside the visible axis range. So \a begin and \a end may actually
21946   indicate a range that contains one additional data point to the left and right of the visible
21947   axis range.
21948 */
21949 void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
21950 {
21951   if (rangeRestriction.isEmpty())
21952   {
21953     end = mDataContainer->constEnd();
21954     begin = end;
21955   } else
21956   {
21957     QCPAxis *keyAxis = mKeyAxis.data();
21958     QCPAxis *valueAxis = mValueAxis.data();
21959     if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
21960     // get visible data range:
21961     begin = mDataContainer->findBegin(keyAxis->range().lower);
21962     end = mDataContainer->findEnd(keyAxis->range().upper);
21963     // limit lower/upperEnd to rangeRestriction:
21964     mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
21965   }
21966 }
21967 
21968 /*!  \internal
21969   
21970   This method goes through the passed points in \a lineData and returns a list of the segments
21971   which don't contain NaN data points.
21972   
21973   \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
21974   for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
21975   Qt::Vertical, the \a x member is checked.
21976   
21977   \see getOverlappingSegments, drawFill
21978 */
21979 QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
21980 {
21981   QVector<QCPDataRange> result;
21982   const int n = lineData->size();
21983   
21984   QCPDataRange currentSegment(-1, -1);
21985   int i = 0;
21986   
21987   if (keyOrientation == Qt::Horizontal)
21988   {
21989     while (i < n)
21990     {
21991       while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
21992         ++i;
21993       if (i == n)
21994         break;
21995       currentSegment.setBegin(i++);
21996       while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
21997         ++i;
21998       currentSegment.setEnd(i++);
21999       result.append(currentSegment);
22000     }
22001   } else // keyOrientation == Qt::Vertical
22002   {
22003     while (i < n)
22004     {
22005       while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
22006         ++i;
22007       if (i == n)
22008         break;
22009       currentSegment.setBegin(i++);
22010       while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
22011         ++i;
22012       currentSegment.setEnd(i++);
22013       result.append(currentSegment);
22014     }
22015   }
22016   return result;
22017 }
22018 
22019 /*!  \internal
22020   
22021   This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
22022   \a otherSegments, and their associated point data \a thisData and \a otherData.
22023 
22024   It returns all pairs of segments (the first from \a thisSegments, the second from \a
22025   otherSegments), which overlap in plot coordinates.
22026   
22027   This method is useful in the case of a channel fill between two graphs, when only those non-NaN
22028   segments which actually overlap in their key coordinate shall be considered for drawing a channel
22029   fill polygon.
22030   
22031   It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
22032   that the segments don't overlap themselves. The same is assumed for the segments in \a
22033   otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
22034   
22035   \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
22036 */
22037 QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
22038 {
22039   QVector<QPair<QCPDataRange, QCPDataRange> > result;
22040   if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
22041     return result;
22042   
22043   int thisIndex = 0;
22044   int otherIndex = 0;
22045   const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
22046   while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
22047   {
22048     if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
22049     {
22050       ++thisIndex;
22051       continue;
22052     }
22053     if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
22054     {
22055       ++otherIndex;
22056       continue;
22057     }
22058     double thisLower, thisUpper, otherLower, otherUpper;
22059     if (!verticalKey)
22060     {
22061       thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
22062       thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
22063       otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
22064       otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
22065     } else
22066     {
22067       thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
22068       thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
22069       otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
22070       otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
22071     }
22072     
22073     int bPrecedence;
22074     if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
22075       result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
22076     
22077     if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
22078       ++otherIndex;
22079     else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
22080       ++thisIndex;
22081   }
22082   
22083   return result;
22084 }
22085 
22086 /*!  \internal
22087   
22088   Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
22089   have overlap.
22090   
22091   The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
22092   \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
22093   coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
22094   both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
22095   
22096   It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
22097   
22098   \see getOverlappingSegments
22099 */
22100 bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
22101 {
22102   bPrecedence = 0;
22103   if (aLower > bUpper)
22104   {
22105     bPrecedence = -1;
22106     return false;
22107   } else if (bLower > aUpper)
22108   {
22109     bPrecedence = 1;
22110     return false;
22111   } else
22112   {
22113     if (aUpper > bUpper)
22114       bPrecedence = -1;
22115     else if (aUpper < bUpper)
22116       bPrecedence = 1;
22117     
22118     return true;
22119   }
22120 }
22121 
22122 /*! \internal
22123   
22124   Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
22125   The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
22126   is in positive or negative infinity. So this case is handled separately by just closing the fill
22127   polygon on the axis which lies in the direction towards the zero value.
22128 
22129   \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
22130   the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
22131   y value of the returned point, respectively.
22132 */
22133 QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
22134 {
22135   QCPAxis *keyAxis = mKeyAxis.data();
22136   QCPAxis *valueAxis = mValueAxis.data();
22137   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
22138   
22139   QPointF result;
22140   if (valueAxis->scaleType() == QCPAxis::stLinear)
22141   {
22142     if (keyAxis->orientation() == Qt::Horizontal)
22143     {
22144       result.setX(matchingDataPoint.x());
22145       result.setY(valueAxis->coordToPixel(0));
22146     } else // keyAxis->orientation() == Qt::Vertical
22147     {
22148       result.setX(valueAxis->coordToPixel(0));
22149       result.setY(matchingDataPoint.y());
22150     }
22151   } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
22152   {
22153     // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
22154     // to the axis which is in the direction towards 0
22155     if (keyAxis->orientation() == Qt::Vertical)
22156     {
22157       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
22158           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
22159         result.setX(keyAxis->axisRect()->right());
22160       else
22161         result.setX(keyAxis->axisRect()->left());
22162       result.setY(matchingDataPoint.y());
22163     } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
22164     {
22165       result.setX(matchingDataPoint.x());
22166       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
22167           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
22168         result.setY(keyAxis->axisRect()->top());
22169       else
22170         result.setY(keyAxis->axisRect()->bottom());
22171     }
22172   }
22173   return result;
22174 }
22175 
22176 /*! \internal
22177   
22178   Returns the polygon needed for drawing normal fills between this graph and the key axis.
22179   
22180   Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
22181   which shall be used for the fill. The collection of \a lineData points described by \a segment
22182   must not contain NaN data points (see \ref getNonNanSegments).
22183   
22184   The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
22185   axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
22186   side (see \ref getFillBasePoint).
22187 
22188   For increased performance (due to implicit sharing), keep the returned QPolygonF const.
22189   
22190   \see drawFill, getNonNanSegments
22191 */
22192 const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
22193 {
22194   if (segment.size() < 2)
22195     return QPolygonF();
22196   QPolygonF result(segment.size()+2);
22197   
22198   result[0] = getFillBasePoint(lineData->at(segment.begin()));
22199   std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
22200   result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
22201   
22202   return result;
22203 }
22204 
22205 /*! \internal
22206   
22207   Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
22208   specified by \ref setChannelFillGraph.
22209   
22210   The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
22211   other graph as \a otherData. The returned polygon will be calculated for the specified data
22212   segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
22213   otherData, respectively.
22214   
22215   The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
22216   \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
22217   need to be processed here.
22218   
22219   For increased performance due to implicit sharing, keep the returned QPolygonF const.
22220   
22221   \see drawFill, getOverlappingSegments, getNonNanSegments
22222 */
22223 const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
22224 {
22225   if (!mChannelFillGraph)
22226     return QPolygonF();
22227   
22228   QCPAxis *keyAxis = mKeyAxis.data();
22229   QCPAxis *valueAxis = mValueAxis.data();
22230   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
22231   if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
22232   
22233   if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
22234     return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
22235   
22236   if (thisData->isEmpty()) return QPolygonF();
22237   QVector<QPointF> thisSegmentData(thisSegment.size());
22238   QVector<QPointF> otherSegmentData(otherSegment.size());
22239   std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
22240   std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
22241   // pointers to be able to swap them, depending which data range needs cropping:
22242   QVector<QPointF> *staticData = &thisSegmentData;
22243   QVector<QPointF> *croppedData = &otherSegmentData;
22244   
22245   // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
22246   if (keyAxis->orientation() == Qt::Horizontal)
22247   {
22248     // x is key
22249     // crop lower bound:
22250     if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
22251       qSwap(staticData, croppedData);
22252     const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
22253     if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
22254     croppedData->remove(0, lowBound);
22255     // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
22256     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
22257     double slope;
22258     if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
22259       slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
22260     else
22261       slope = 0;
22262     (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
22263     (*croppedData)[0].setX(staticData->first().x());
22264     
22265     // crop upper bound:
22266     if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
22267       qSwap(staticData, croppedData);
22268     int highBound = findIndexAboveX(croppedData, staticData->last().x());
22269     if (highBound == -1) return QPolygonF(); // key ranges have no overlap
22270     croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
22271     // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
22272     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
22273     const int li = croppedData->size()-1; // last index
22274     if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
22275       slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
22276     else
22277       slope = 0;
22278     (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
22279     (*croppedData)[li].setX(staticData->last().x());
22280   } else // mKeyAxis->orientation() == Qt::Vertical
22281   {
22282     // y is key
22283     // crop lower bound:
22284     if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
22285       qSwap(staticData, croppedData);
22286     int lowBound = findIndexBelowY(croppedData, staticData->first().y());
22287     if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
22288     croppedData->remove(0, lowBound);
22289     // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
22290     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
22291     double slope;
22292     if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
22293       slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
22294     else
22295       slope = 0;
22296     (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
22297     (*croppedData)[0].setY(staticData->first().y());
22298     
22299     // crop upper bound:
22300     if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
22301       qSwap(staticData, croppedData);
22302     int highBound = findIndexAboveY(croppedData, staticData->last().y());
22303     if (highBound == -1) return QPolygonF(); // key ranges have no overlap
22304     croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
22305     // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
22306     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
22307     int li = croppedData->size()-1; // last index
22308     if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
22309       slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
22310     else
22311       slope = 0;
22312     (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
22313     (*croppedData)[li].setY(staticData->last().y());
22314   }
22315   
22316   // return joined:
22317   for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
22318     thisSegmentData << otherSegmentData.at(i);
22319   return QPolygonF(thisSegmentData);
22320 }
22321 
22322 /*! \internal
22323   
22324   Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
22325   \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
22326   axis is horizontal.
22327 
22328   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
22329 */
22330 int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
22331 {
22332   for (int i=data->size()-1; i>=0; --i)
22333   {
22334     if (data->at(i).x() < x)
22335     {
22336       if (i<data->size()-1)
22337         return i+1;
22338       else
22339         return data->size()-1;
22340     }
22341   }
22342   return -1;
22343 }
22344 
22345 /*! \internal
22346   
22347   Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
22348   \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
22349   axis is horizontal.
22350   
22351   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
22352 */
22353 int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
22354 {
22355   for (int i=0; i<data->size(); ++i)
22356   {
22357     if (data->at(i).x() > x)
22358     {
22359       if (i>0)
22360         return i-1;
22361       else
22362         return 0;
22363     }
22364   }
22365   return -1;
22366 }
22367 
22368 /*! \internal
22369   
22370   Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
22371   \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
22372   axis is vertical.
22373   
22374   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
22375 */
22376 int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
22377 {
22378   for (int i=data->size()-1; i>=0; --i)
22379   {
22380     if (data->at(i).y() < y)
22381     {
22382       if (i<data->size()-1)
22383         return i+1;
22384       else
22385         return data->size()-1;
22386     }
22387   }
22388   return -1;
22389 }
22390 
22391 /*! \internal
22392   
22393   Calculates the minimum distance in pixels the graph's representation has from the given \a
22394   pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
22395   selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
22396   the graph has a line representation, the returned distance may be smaller than the distance to
22397   the \a closestData point, since the distance to the graph line is also taken into account.
22398   
22399   If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
22400   is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
22401 */
22402 double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
22403 {
22404   closestData = mDataContainer->constEnd();
22405   if (mDataContainer->isEmpty())
22406     return -1.0;
22407   if (mLineStyle == lsNone && mScatterStyle.isNone())
22408     return -1.0;
22409   
22410   // calculate minimum distances to graph data points and find closestData iterator:
22411   double minDistSqr = (std::numeric_limits<double>::max)();
22412   // determine which key range comes into question, taking selection tolerance around pos into account:
22413   double posKeyMin, posKeyMax, dummy;
22414   pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
22415   pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
22416   if (posKeyMin > posKeyMax)
22417     qSwap(posKeyMin, posKeyMax);
22418   // iterate over found data points and then choose the one with the shortest distance to pos:
22419   QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
22420   QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
22421   for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
22422   {
22423     const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
22424     if (currentDistSqr < minDistSqr)
22425     {
22426       minDistSqr = currentDistSqr;
22427       closestData = it;
22428     }
22429   }
22430     
22431   // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
22432   if (mLineStyle != lsNone)
22433   {
22434     // line displayed, calculate distance to line segments:
22435     QVector<QPointF> lineData;
22436     getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate
22437     QCPVector2D p(pixelPoint);
22438     const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
22439     for (int i=0; i<lineData.size()-1; i+=step)
22440     {
22441       const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
22442       if (currentDistSqr < minDistSqr)
22443         minDistSqr = currentDistSqr;
22444     }
22445   }
22446   
22447   return qSqrt(minDistSqr);
22448 }
22449 
22450 /*! \internal
22451   
22452   Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
22453   \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
22454   axis is vertical.
22455 
22456   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
22457 */
22458 int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
22459 {
22460   for (int i=0; i<data->size(); ++i)
22461   {
22462     if (data->at(i).y() > y)
22463     {
22464       if (i>0)
22465         return i-1;
22466       else
22467         return 0;
22468     }
22469   }
22470   return -1;
22471 }
22472 /* end of 'src/plottables/plottable-graph.cpp' */
22473 
22474 
22475 /* including file 'src/plottables/plottable-curve.cpp' */
22476 /* modified 2021-03-29T02:30:44, size 63851            */
22477 
22478 ////////////////////////////////////////////////////////////////////////////////////////////////////
22479 //////////////////// QCPCurveData
22480 ////////////////////////////////////////////////////////////////////////////////////////////////////
22481 
22482 /*! \class QCPCurveData
22483   \brief Holds the data of one single data point for QCPCurve.
22484   
22485   The stored data is:
22486   \li \a t: the free ordering parameter of this curve point, like in the mathematical vector <em>(x(t), y(t))</em>. (This is the \a sortKey)
22487   \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
22488   \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
22489   
22490   The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
22491   \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
22492   documentation there for an explanation regarding the data type's generic methods.
22493   
22494   \see QCPCurveDataContainer
22495 */
22496 
22497 /* start documentation of inline functions */
22498 
22499 /*! \fn double QCPCurveData::sortKey() const
22500   
22501   Returns the \a t member of this data point.
22502   
22503   For a general explanation of what this method is good for in the context of the data container,
22504   see the documentation of \ref QCPDataContainer.
22505 */
22506 
22507 /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
22508   
22509   Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
22510   All other members are set to zero.
22511   
22512   For a general explanation of what this method is good for in the context of the data container,
22513   see the documentation of \ref QCPDataContainer.
22514 */
22515 
22516 /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
22517   
22518   Since the member \a key is the data point key coordinate and the member \a t is the data ordering
22519   parameter, this method returns false.
22520   
22521   For a general explanation of what this method is good for in the context of the data container,
22522   see the documentation of \ref QCPDataContainer.
22523 */
22524 
22525 /*! \fn double QCPCurveData::mainKey() const
22526   
22527   Returns the \a key member of this data point.
22528   
22529   For a general explanation of what this method is good for in the context of the data container,
22530   see the documentation of \ref QCPDataContainer.
22531 */
22532 
22533 /*! \fn double QCPCurveData::mainValue() const
22534   
22535   Returns the \a value member of this data point.
22536   
22537   For a general explanation of what this method is good for in the context of the data container,
22538   see the documentation of \ref QCPDataContainer.
22539 */
22540 
22541 /*! \fn QCPRange QCPCurveData::valueRange() const
22542   
22543   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
22544   
22545   For a general explanation of what this method is good for in the context of the data container,
22546   see the documentation of \ref QCPDataContainer.
22547 */
22548 
22549 /* end documentation of inline functions */
22550 
22551 /*!
22552   Constructs a curve data point with t, key and value set to zero.
22553 */
22554 QCPCurveData::QCPCurveData() :
22555   t(0),
22556   key(0),
22557   value(0)
22558 {
22559 }
22560 
22561 /*!
22562   Constructs a curve data point with the specified \a t, \a key and \a value.
22563 */
22564 QCPCurveData::QCPCurveData(double t, double key, double value) :
22565   t(t),
22566   key(key),
22567   value(value)
22568 {
22569 }
22570 
22571 
22572 ////////////////////////////////////////////////////////////////////////////////////////////////////
22573 //////////////////// QCPCurve
22574 ////////////////////////////////////////////////////////////////////////////////////////////////////
22575 
22576 /*! \class QCPCurve
22577   \brief A plottable representing a parametric curve in a plot.
22578   
22579   \image html QCPCurve.png
22580   
22581   Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
22582   so their visual representation can have \a loops. This is realized by introducing a third
22583   coordinate \a t, which defines the order of the points described by the other two coordinates \a
22584   x and \a y.
22585 
22586   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
22587   also access and modify the curve's data via the \ref data method, which returns a pointer to the
22588   internal \ref QCPCurveDataContainer.
22589   
22590   Gaps in the curve can be created by adding data points with NaN as key and value
22591   (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
22592   separated.
22593   
22594   \section qcpcurve-appearance Changing the appearance
22595   
22596   The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
22597   
22598   \section qcpcurve-usage Usage
22599   
22600   Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
22601   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
22602   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
22603   
22604   Usually, you first create an instance:
22605   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
22606   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
22607   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
22608   The newly created plottable can be modified, e.g.:
22609   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
22610 */
22611 
22612 /* start of documentation of inline functions */
22613 
22614 /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
22615   
22616   Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
22617   use it to directly manipulate the data, which may be more convenient and faster than using the
22618   regular \ref setData or \ref addData methods.
22619 */
22620 
22621 /* end of documentation of inline functions */
22622 
22623 /*!
22624   Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
22625   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
22626   the same orientation. If either of these restrictions is violated, a corresponding message is
22627   printed to the debug output (qDebug), the construction is not aborted, though.
22628   
22629   The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
22630   keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
22631   but use QCustomPlot::removePlottable() instead.
22632 */
22633 QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
22634   QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
22635   mScatterSkip{},
22636   mLineStyle{}
22637 {
22638   // modify inherited properties from abstract plottable:
22639   setPen(QPen(Qt::blue, 0));
22640   setBrush(Qt::NoBrush);
22641   
22642   setScatterStyle(QCPScatterStyle());
22643   setLineStyle(lsLine);
22644   setScatterSkip(0);
22645 }
22646 
22647 QCPCurve::~QCPCurve()
22648 {
22649 }
22650 
22651 /*! \overload
22652   
22653   Replaces the current data container with the provided \a data container.
22654   
22655   Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
22656   Modifying the data in the container will then affect all curves that share the container. Sharing
22657   can be achieved by simply exchanging the data containers wrapped in shared pointers:
22658   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
22659   
22660   If you do not wish to share containers, but create a copy from an existing container, rather use
22661   the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
22662   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
22663   
22664   \see addData
22665 */
22666 void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
22667 {
22668   mDataContainer = data;
22669 }
22670 
22671 /*! \overload
22672   
22673   Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
22674   vectors should have equal length. Else, the number of added points will be the size of the
22675   smallest vector.
22676   
22677   If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
22678   set \a alreadySorted to true, to improve performance by saving a sorting run.
22679   
22680   \see addData
22681 */
22682 void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
22683 {
22684   mDataContainer->clear();
22685   addData(t, keys, values, alreadySorted);
22686 }
22687 
22688 
22689 /*! \overload
22690   
22691   Replaces the current data with the provided points in \a keys and \a values. The provided vectors
22692   should have equal length. Else, the number of added points will be the size of the smallest
22693   vector.
22694   
22695   The t parameter of each data point will be set to the integer index of the respective key/value
22696   pair.
22697   
22698   \see addData
22699 */
22700 void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
22701 {
22702   mDataContainer->clear();
22703   addData(keys, values);
22704 }
22705 
22706 /*!
22707   Sets the visual appearance of single data points in the plot. If set to \ref
22708   QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
22709   line style).
22710   
22711   \see QCPScatterStyle, setLineStyle
22712 */
22713 void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
22714 {
22715   mScatterStyle = style;
22716 }
22717 
22718 /*!
22719   If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
22720   scatter points are skipped/not drawn after every drawn scatter point.
22721 
22722   This can be used to make the data appear sparser while for example still having a smooth line,
22723   and to improve performance for very high density plots.
22724 
22725   If \a skip is set to 0 (default), all scatter points are drawn.
22726 
22727   \see setScatterStyle
22728 */
22729 void QCPCurve::setScatterSkip(int skip)
22730 {
22731   mScatterSkip = qMax(0, skip);
22732 }
22733 
22734 /*!
22735   Sets how the single data points are connected in the plot or how they are represented visually
22736   apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
22737   setScatterStyle to the desired scatter style.
22738   
22739   \see setScatterStyle
22740 */
22741 void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
22742 {
22743   mLineStyle = style;
22744 }
22745 
22746 /*! \overload
22747   
22748   Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
22749   should have equal length. Else, the number of added points will be the size of the smallest
22750   vector.
22751   
22752   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
22753   can set \a alreadySorted to true, to improve performance by saving a sorting run.
22754   
22755   Alternatively, you can also access and modify the data directly via the \ref data method, which
22756   returns a pointer to the internal data container.
22757 */
22758 void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
22759 {
22760   if (t.size() != keys.size() || t.size() != values.size())
22761     qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
22762   const int n = qMin(qMin(t.size(), keys.size()), values.size());
22763   QVector<QCPCurveData> tempData(n);
22764   QVector<QCPCurveData>::iterator it = tempData.begin();
22765   const QVector<QCPCurveData>::iterator itEnd = tempData.end();
22766   int i = 0;
22767   while (it != itEnd)
22768   {
22769     it->t = t[i];
22770     it->key = keys[i];
22771     it->value = values[i];
22772     ++it;
22773     ++i;
22774   }
22775   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
22776 }
22777 
22778 /*! \overload
22779   
22780   Adds the provided points in \a keys and \a values to the current data. The provided vectors
22781   should have equal length. Else, the number of added points will be the size of the smallest
22782   vector.
22783   
22784   The t parameter of each data point will be set to the integer index of the respective key/value
22785   pair.
22786   
22787   Alternatively, you can also access and modify the data directly via the \ref data method, which
22788   returns a pointer to the internal data container.
22789 */
22790 void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
22791 {
22792   if (keys.size() != values.size())
22793     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
22794   const int n = qMin(keys.size(), values.size());
22795   double tStart;
22796   if (!mDataContainer->isEmpty())
22797     tStart = (mDataContainer->constEnd()-1)->t + 1.0;
22798   else
22799     tStart = 0;
22800   QVector<QCPCurveData> tempData(n);
22801   QVector<QCPCurveData>::iterator it = tempData.begin();
22802   const QVector<QCPCurveData>::iterator itEnd = tempData.end();
22803   int i = 0;
22804   while (it != itEnd)
22805   {
22806     it->t = tStart + i;
22807     it->key = keys[i];
22808     it->value = values[i];
22809     ++it;
22810     ++i;
22811   }
22812   mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
22813 }
22814 
22815 /*! \overload
22816   Adds the provided data point as \a t, \a key and \a value to the current data.
22817   
22818   Alternatively, you can also access and modify the data directly via the \ref data method, which
22819   returns a pointer to the internal data container.
22820 */
22821 void QCPCurve::addData(double t, double key, double value)
22822 {
22823   mDataContainer->add(QCPCurveData(t, key, value));
22824 }
22825 
22826 /*! \overload
22827   
22828   Adds the provided data point as \a key and \a value to the current data.
22829   
22830   The t parameter is generated automatically by increments of 1 for each point, starting at the
22831   highest t of previously existing data or 0, if the curve data is empty.
22832   
22833   Alternatively, you can also access and modify the data directly via the \ref data method, which
22834   returns a pointer to the internal data container.
22835 */
22836 void QCPCurve::addData(double key, double value)
22837 {
22838   if (!mDataContainer->isEmpty())
22839     mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
22840   else
22841     mDataContainer->add(QCPCurveData(0.0, key, value));
22842 }
22843 
22844 /*!
22845   Implements a selectTest specific to this plottable's point geometry.
22846 
22847   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
22848   point to \a pos.
22849   
22850   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
22851 */
22852 double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
22853 {
22854   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
22855     return -1;
22856   if (!mKeyAxis || !mValueAxis)
22857     return -1;
22858   
22859   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
22860   {
22861     QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
22862     double result = pointDistance(pos, closestDataPoint);
22863     if (details)
22864     {
22865       int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
22866       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
22867     }
22868     return result;
22869   } else
22870     return -1;
22871 }
22872 
22873 /* inherits documentation from base class */
22874 QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
22875 {
22876   return mDataContainer->keyRange(foundRange, inSignDomain);
22877 }
22878 
22879 /* inherits documentation from base class */
22880 QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
22881 {
22882   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
22883 }
22884 
22885 /* inherits documentation from base class */
22886 void QCPCurve::draw(QCPPainter *painter)
22887 {
22888   if (mDataContainer->isEmpty()) return;
22889   
22890   // allocate line vector:
22891   QVector<QPointF> lines, scatters;
22892   
22893   // loop over and draw segments of unselected/selected data:
22894   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
22895   getDataSegments(selectedSegments, unselectedSegments);
22896   allSegments << unselectedSegments << selectedSegments;
22897   for (int i=0; i<allSegments.size(); ++i)
22898   {
22899     bool isSelectedSegment = i >= unselectedSegments.size();
22900     
22901     // fill with curve data:
22902     QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
22903     if (isSelectedSegment && mSelectionDecorator)
22904       finalCurvePen = mSelectionDecorator->pen();
22905     
22906     QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care)
22907     getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
22908     
22909     // check data validity if flag set:
22910   #ifdef QCUSTOMPLOT_CHECK_DATA
22911     for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
22912     {
22913       if (QCP::isInvalidData(it->t) ||
22914           QCP::isInvalidData(it->key, it->value))
22915         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
22916     }
22917   #endif
22918     
22919     // draw curve fill:
22920     applyFillAntialiasingHint(painter);
22921     if (isSelectedSegment && mSelectionDecorator)
22922       mSelectionDecorator->applyBrush(painter);
22923     else
22924       painter->setBrush(mBrush);
22925     painter->setPen(Qt::NoPen);
22926     if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
22927       painter->drawPolygon(QPolygonF(lines));
22928     
22929     // draw curve line:
22930     if (mLineStyle != lsNone)
22931     {
22932       painter->setPen(finalCurvePen);
22933       painter->setBrush(Qt::NoBrush);
22934       drawCurveLine(painter, lines);
22935     }
22936     
22937     // draw scatters:
22938     QCPScatterStyle finalScatterStyle = mScatterStyle;
22939     if (isSelectedSegment && mSelectionDecorator)
22940       finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
22941     if (!finalScatterStyle.isNone())
22942     {
22943       getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
22944       drawScatterPlot(painter, scatters, finalScatterStyle);
22945     }
22946   }
22947   
22948   // draw other selection decoration that isn't just line/scatter pens and brushes:
22949   if (mSelectionDecorator)
22950     mSelectionDecorator->drawDecoration(painter, selection());
22951 }
22952 
22953 /* inherits documentation from base class */
22954 void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
22955 {
22956   // draw fill:
22957   if (mBrush.style() != Qt::NoBrush)
22958   {
22959     applyFillAntialiasingHint(painter);
22960     painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
22961   }
22962   // draw line vertically centered:
22963   if (mLineStyle != lsNone)
22964   {
22965     applyDefaultAntialiasingHint(painter);
22966     painter->setPen(mPen);
22967     painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
22968   }
22969   // draw scatter symbol:
22970   if (!mScatterStyle.isNone())
22971   {
22972     applyScattersAntialiasingHint(painter);
22973     // scale scatter pixmap if it's too large to fit in legend icon rect:
22974     if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
22975     {
22976       QCPScatterStyle scaledStyle(mScatterStyle);
22977       scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
22978       scaledStyle.applyTo(painter, mPen);
22979       scaledStyle.drawShape(painter, QRectF(rect).center());
22980     } else
22981     {
22982       mScatterStyle.applyTo(painter, mPen);
22983       mScatterStyle.drawShape(painter, QRectF(rect).center());
22984     }
22985   }
22986 }
22987 
22988 /*!  \internal
22989 
22990   Draws lines between the points in \a lines, given in pixel coordinates.
22991 
22992   \see drawScatterPlot, getCurveLines
22993 */
22994 void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
22995 {
22996   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
22997   {
22998     applyDefaultAntialiasingHint(painter);
22999     drawPolyline(painter, lines);
23000   }
23001 }
23002 
23003 /*! \internal
23004 
23005   Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
23006   scatters will be drawn with \a painter and have the appearance as specified in \a style.
23007 
23008   \see drawCurveLine, getCurveLines
23009 */
23010 void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
23011 {
23012   // draw scatter point symbols:
23013   applyScattersAntialiasingHint(painter);
23014   style.applyTo(painter, mPen);
23015   foreach (const QPointF &point, points)
23016     if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
23017       style.drawShape(painter,  point);
23018 }
23019 
23020 /*! \internal
23021 
23022   Called by \ref draw to generate points in pixel coordinates which represent the line of the
23023   curve.
23024 
23025   Line segments that aren't visible in the current axis rect are handled in an optimized way. They
23026   are projected onto a rectangle slightly larger than the visible axis rect and simplified
23027   regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
23028   the visible axis rect by generating new temporary points on the outer rect if necessary.
23029 
23030   \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
23031   drawCurveLine.
23032 
23033   \a dataRange specifies the beginning and ending data indices that will be taken into account for
23034   conversion. In this function, the specified range may exceed the total data bounds without harm:
23035   a correspondingly trimmed data range will be used. This takes the burden off the user of this
23036   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
23037   getDataSegments.
23038 
23039   \a penWidth specifies the pen width that will be used to later draw the lines generated by this
23040   function. This is needed here to calculate an accordingly wider margin around the axis rect when
23041   performing the line optimization.
23042 
23043   Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
23044   getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
23045 
23046   \see drawCurveLine, drawScatterPlot
23047 */
23048 void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
23049 {
23050   if (!lines) return;
23051   lines->clear();
23052   QCPAxis *keyAxis = mKeyAxis.data();
23053   QCPAxis *valueAxis = mValueAxis.data();
23054   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
23055   
23056   // add margins to rect to compensate for stroke width
23057   const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
23058   const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
23059   const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
23060   const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
23061   const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
23062   QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
23063   QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
23064   mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
23065   if (itBegin == itEnd)
23066     return;
23067   QCPCurveDataContainer::const_iterator it = itBegin;
23068   QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
23069   int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
23070   QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right)
23071   while (it != itEnd)
23072   {
23073     const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
23074     if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
23075     {
23076       if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
23077       {
23078         QPointF crossA, crossB;
23079         if (prevRegion == 5) // we're coming from R, so add this point optimized
23080         {
23081           lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
23082           // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point
23083           *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
23084         } else if (mayTraverse(prevRegion, currentRegion) &&
23085                    getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
23086         {
23087           // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
23088           QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
23089           getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
23090           if (it != itBegin)
23091           {
23092             *lines << beforeTraverseCornerPoints;
23093             lines->append(crossA);
23094             lines->append(crossB);
23095             *lines << afterTraverseCornerPoints;
23096           } else
23097           {
23098             lines->append(crossB);
23099             *lines << afterTraverseCornerPoints;
23100             trailingPoints << beforeTraverseCornerPoints << crossA ;
23101           }
23102         } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s)
23103         {
23104           *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
23105         }
23106       } else // segment does end in R, so we add previous point optimized and this point at original position
23107       {
23108         if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
23109           trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
23110         else
23111           lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
23112         lines->append(coordsToPixels(it->key, it->value));
23113       }
23114     } else // region didn't change
23115     {
23116       if (currentRegion == 5) // still in R, keep adding original points
23117       {
23118         lines->append(coordsToPixels(it->key, it->value));
23119       } else // still outside R, no need to add anything
23120       {
23121         // see how this is not doing anything? That's the main optimization...
23122       }
23123     }
23124     prevIt = it;
23125     prevRegion = currentRegion;
23126     ++it;
23127   }
23128   *lines << trailingPoints;
23129 }
23130 
23131 /*! \internal
23132 
23133   Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
23134   curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
23135   sparser.
23136 
23137   Scatters that aren't visible in the current axis rect are optimized away.
23138 
23139   \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
23140   drawScatterPlot.
23141 
23142   \a dataRange specifies the beginning and ending data indices that will be taken into account for
23143   conversion.
23144 
23145   \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
23146   coordinates generated by this function. This is needed here to calculate an accordingly wider
23147   margin around the axis rect when performing the data point reduction.
23148 
23149   \see draw, drawScatterPlot
23150 */
23151 void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
23152 {
23153   if (!scatters) return;
23154   scatters->clear();
23155   QCPAxis *keyAxis = mKeyAxis.data();
23156   QCPAxis *valueAxis = mValueAxis.data();
23157   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
23158   
23159   QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
23160   QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
23161   mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
23162   if (begin == end)
23163     return;
23164   const int scatterModulo = mScatterSkip+1;
23165   const bool doScatterSkip = mScatterSkip > 0;
23166   int endIndex = int( end-mDataContainer->constBegin() );
23167   
23168   QCPRange keyRange = keyAxis->range();
23169   QCPRange valueRange = valueAxis->range();
23170   // extend range to include width of scatter symbols:
23171   keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
23172   keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
23173   valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
23174   valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
23175   
23176   QCPCurveDataContainer::const_iterator it = begin;
23177   int itIndex = int( begin-mDataContainer->constBegin() );
23178   while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
23179   {
23180     ++itIndex;
23181     ++it;
23182   }
23183   if (keyAxis->orientation() == Qt::Vertical)
23184   {
23185     while (it != end)
23186     {
23187       if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
23188         scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
23189       
23190       // advance iterator to next (non-skipped) data point:
23191       if (!doScatterSkip)
23192         ++it;
23193       else
23194       {
23195         itIndex += scatterModulo;
23196         if (itIndex < endIndex) // make sure we didn't jump over end
23197           it += scatterModulo;
23198         else
23199         {
23200           it = end;
23201           itIndex = endIndex;
23202         }
23203       }
23204     }
23205   } else
23206   {
23207     while (it != end)
23208     {
23209       if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
23210         scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
23211       
23212       // advance iterator to next (non-skipped) data point:
23213       if (!doScatterSkip)
23214         ++it;
23215       else
23216       {
23217         itIndex += scatterModulo;
23218         if (itIndex < endIndex) // make sure we didn't jump over end
23219           it += scatterModulo;
23220         else
23221         {
23222           it = end;
23223           itIndex = endIndex;
23224         }
23225       }
23226     }
23227   }
23228 }
23229 
23230 /*! \internal
23231 
23232   This function is part of the curve optimization algorithm of \ref getCurveLines.
23233 
23234   It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
23235   by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
23236 
23237   The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
23238   keyMin to \a keyMax):
23239 
23240   <table style="width:10em; text-align:center">
23241     <tr><td>1</td><td>4</td><td>7</td></tr>
23242     <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
23243     <tr><td>3</td><td>6</td><td>9</td></tr>
23244   </table>
23245 
23246   With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
23247   curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
23248 */
23249 int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
23250 {
23251   if (key < keyMin) // region 123
23252   {
23253     if (value > valueMax)
23254       return 1;
23255     else if (value < valueMin)
23256       return 3;
23257     else
23258       return 2;
23259   } else if (key > keyMax) // region 789
23260   {
23261     if (value > valueMax)
23262       return 7;
23263     else if (value < valueMin)
23264       return 9;
23265     else
23266       return 8;
23267   } else // region 456
23268   {
23269     if (value > valueMax)
23270       return 4;
23271     else if (value < valueMin)
23272       return 6;
23273     else
23274       return 5;
23275   }
23276 }
23277 
23278 /*! \internal
23279   
23280   This function is part of the curve optimization algorithm of \ref getCurveLines.
23281   
23282   This method is used in case the current segment passes from inside the visible rect (region 5,
23283   see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
23284   the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
23285   
23286   It returns the intersection point of the segment with the border of region 5.
23287   
23288   For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
23289   whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
23290   leaving it. It is important though that \a otherRegion correctly identifies the other region not
23291   equal to 5.
23292 */
23293 QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
23294 {
23295   // The intersection point interpolation here is done in pixel coordinates, so we don't need to
23296   // differentiate between different axis scale types. Note that the nomenclature
23297   // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
23298   // different in pixel coordinates (horz/vert key axes, reversed ranges)
23299   
23300   const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
23301   const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
23302   const double valueMinPx = mValueAxis->coordToPixel(valueMin);
23303   const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
23304   const double otherValuePx = mValueAxis->coordToPixel(otherValue);
23305   const double valuePx = mValueAxis->coordToPixel(value);
23306   const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
23307   const double keyPx = mKeyAxis->coordToPixel(key);
23308   double intersectKeyPx = keyMinPx; // initial key just a fail-safe
23309   double intersectValuePx = valueMinPx; // initial value just a fail-safe
23310   switch (otherRegion)
23311   {
23312     case 1: // top and left edge
23313     {
23314       intersectValuePx = valueMaxPx;
23315       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23316       if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
23317       {
23318         intersectKeyPx = keyMinPx;
23319         intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23320       }
23321       break;
23322     }
23323     case 2: // left edge
23324     {
23325       intersectKeyPx = keyMinPx;
23326       intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23327       break;
23328     }
23329     case 3: // bottom and left edge
23330     {
23331       intersectValuePx = valueMinPx;
23332       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23333       if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
23334       {
23335         intersectKeyPx = keyMinPx;
23336         intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23337       }
23338       break;
23339     }
23340     case 4: // top edge
23341     {
23342       intersectValuePx = valueMaxPx;
23343       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23344       break;
23345     }
23346     case 5:
23347     {
23348       break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
23349     }
23350     case 6: // bottom edge
23351     {
23352       intersectValuePx = valueMinPx;
23353       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23354       break;
23355     }
23356     case 7: // top and right edge
23357     {
23358       intersectValuePx = valueMaxPx;
23359       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23360       if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
23361       {
23362         intersectKeyPx = keyMaxPx;
23363         intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23364       }
23365       break;
23366     }
23367     case 8: // right edge
23368     {
23369       intersectKeyPx = keyMaxPx;
23370       intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23371       break;
23372     }
23373     case 9: // bottom and right edge
23374     {
23375       intersectValuePx = valueMinPx;
23376       intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
23377       if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
23378       {
23379         intersectKeyPx = keyMaxPx;
23380         intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
23381       }
23382       break;
23383     }
23384   }
23385   if (mKeyAxis->orientation() == Qt::Horizontal)
23386     return {intersectKeyPx, intersectValuePx};
23387   else
23388     return {intersectValuePx, intersectKeyPx};
23389 }
23390 
23391 /*! \internal
23392   
23393   This function is part of the curve optimization algorithm of \ref getCurveLines.
23394   
23395   In situations where a single segment skips over multiple regions it might become necessary to add
23396   extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
23397   doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
23398   This method provides these points that must be added, assuming the original segment doesn't
23399   start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
23400   \ref getTraverseCornerPoints.)
23401   
23402   For example, consider a segment which directly goes from region 4 to 2 but originally is far out
23403   to the top left such that it doesn't cross region 5. Naively optimizing these points by
23404   projecting them on the top and left borders of region 5 will create a segment that surely crosses
23405   5, creating a visual artifact in the plot. This method prevents this by providing extra points at
23406   the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
23407   traversing 5.
23408 */
23409 QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
23410 {
23411   QVector<QPointF> result;
23412   switch (prevRegion)
23413   {
23414     case 1:
23415     {
23416       switch (currentRegion)
23417       {
23418         case 2: { result << coordsToPixels(keyMin, valueMax); break; }
23419         case 4: { result << coordsToPixels(keyMin, valueMax); break; }
23420         case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
23421         case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
23422         case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
23423         case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
23424         case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
23425           if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
23426           { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
23427           else
23428           { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
23429           break;
23430         }
23431       }
23432       break;
23433     }
23434     case 2:
23435     {
23436       switch (currentRegion)
23437       {
23438         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
23439         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
23440         case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
23441         case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
23442         case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
23443         case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
23444       }
23445       break;
23446     }
23447     case 3:
23448     {
23449       switch (currentRegion)
23450       {
23451         case 2: { result << coordsToPixels(keyMin, valueMin); break; }
23452         case 6: { result << coordsToPixels(keyMin, valueMin); break; }
23453         case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
23454         case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
23455         case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
23456         case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
23457         case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
23458           if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
23459           { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
23460           else
23461           { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
23462           break;
23463         }
23464       }
23465       break;
23466     }
23467     case 4:
23468     {
23469       switch (currentRegion)
23470       {
23471         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
23472         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
23473         case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
23474         case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
23475         case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
23476         case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
23477       }
23478       break;
23479     }
23480     case 5:
23481     {
23482       switch (currentRegion)
23483       {
23484         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
23485         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
23486         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
23487         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
23488       }
23489       break;
23490     }
23491     case 6:
23492     {
23493       switch (currentRegion)
23494       {
23495         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
23496         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
23497         case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
23498         case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
23499         case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
23500         case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
23501       }
23502       break;
23503     }
23504     case 7:
23505     {
23506       switch (currentRegion)
23507       {
23508         case 4: { result << coordsToPixels(keyMax, valueMax); break; }
23509         case 8: { result << coordsToPixels(keyMax, valueMax); break; }
23510         case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
23511         case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
23512         case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
23513         case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
23514         case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
23515           if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
23516           { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
23517           else
23518           { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
23519           break;
23520         }
23521       }
23522       break;
23523     }
23524     case 8:
23525     {
23526       switch (currentRegion)
23527       {
23528         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
23529         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
23530         case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
23531         case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
23532         case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
23533         case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
23534       }
23535       break;
23536     }
23537     case 9:
23538     {
23539       switch (currentRegion)
23540       {
23541         case 6: { result << coordsToPixels(keyMax, valueMin); break; }
23542         case 8: { result << coordsToPixels(keyMax, valueMin); break; }
23543         case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
23544         case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
23545         case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
23546         case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
23547         case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
23548           if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
23549           { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
23550           else
23551           { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
23552           break;
23553         }
23554       }
23555       break;
23556     }
23557   }
23558   return result;
23559 }
23560 
23561 /*! \internal
23562   
23563   This function is part of the curve optimization algorithm of \ref getCurveLines.
23564   
23565   This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
23566   getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
23567   nor \a currentRegion is 5 itself.
23568   
23569   If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
23570   segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
23571   getTraverse).
23572 */
23573 bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
23574 {
23575   switch (prevRegion)
23576   {
23577     case 1:
23578     {
23579       switch (currentRegion)
23580       {
23581         case 4:
23582         case 7:
23583         case 2:
23584         case 3: return false;
23585         default: return true;
23586       }
23587     }
23588     case 2:
23589     {
23590       switch (currentRegion)
23591       {
23592         case 1:
23593         case 3: return false;
23594         default: return true;
23595       }
23596     }
23597     case 3:
23598     {
23599       switch (currentRegion)
23600       {
23601         case 1:
23602         case 2:
23603         case 6:
23604         case 9: return false;
23605         default: return true;
23606       }
23607     }
23608     case 4:
23609     {
23610       switch (currentRegion)
23611       {
23612         case 1:
23613         case 7: return false;
23614         default: return true;
23615       }
23616     }
23617     case 5: return false; // should never occur
23618     case 6:
23619     {
23620       switch (currentRegion)
23621       {
23622         case 3:
23623         case 9: return false;
23624         default: return true;
23625       }
23626     }
23627     case 7:
23628     {
23629       switch (currentRegion)
23630       {
23631         case 1:
23632         case 4:
23633         case 8:
23634         case 9: return false;
23635         default: return true;
23636       }
23637     }
23638     case 8:
23639     {
23640       switch (currentRegion)
23641       {
23642         case 7:
23643         case 9: return false;
23644         default: return true;
23645       }
23646     }
23647     case 9:
23648     {
23649       switch (currentRegion)
23650       {
23651         case 3:
23652         case 6:
23653         case 8:
23654         case 7: return false;
23655         default: return true;
23656       }
23657     }
23658     default: return true;
23659   }
23660 }
23661 
23662 
23663 /*! \internal
23664   
23665   This function is part of the curve optimization algorithm of \ref getCurveLines.
23666   
23667   This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
23668   segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
23669   region 5.
23670   
23671   The return value of this method indicates whether the segment actually traverses region 5 or not.
23672   
23673   If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
23674   exit points of region 5. They will become the optimized points for that segment.
23675 */
23676 bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
23677 {
23678   // The intersection point interpolation here is done in pixel coordinates, so we don't need to
23679   // differentiate between different axis scale types. Note that the nomenclature
23680   // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
23681   // different in pixel coordinates (horz/vert key axes, reversed ranges)
23682   
23683   QList<QPointF> intersections;
23684   const double valueMinPx = mValueAxis->coordToPixel(valueMin);
23685   const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
23686   const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
23687   const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
23688   const double keyPx = mKeyAxis->coordToPixel(key);
23689   const double valuePx = mValueAxis->coordToPixel(value);
23690   const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
23691   const double prevValuePx = mValueAxis->coordToPixel(prevValue);
23692   if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
23693   {
23694     // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
23695     intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
23696     intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
23697   } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
23698   {
23699     // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
23700     intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
23701     intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
23702   } else // line is skewed
23703   {
23704     double gamma;
23705     double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
23706     // check top of rect:
23707     gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
23708     if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
23709       intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
23710     // check bottom of rect:
23711     gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
23712     if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
23713       intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
23714     const double valuePerKeyPx = 1.0/keyPerValuePx;
23715     // check left of rect:
23716     gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
23717     if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
23718       intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
23719     // check right of rect:
23720     gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
23721     if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
23722       intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
23723   }
23724   
23725   // handle cases where found points isn't exactly 2:
23726   if (intersections.size() > 2)
23727   {
23728     // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
23729     double distSqrMax = 0;
23730     QPointF pv1, pv2;
23731     for (int i=0; i<intersections.size()-1; ++i)
23732     {
23733       for (int k=i+1; k<intersections.size(); ++k)
23734       {
23735         QPointF distPoint = intersections.at(i)-intersections.at(k);
23736         double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
23737         if (distSqr > distSqrMax)
23738         {
23739           pv1 = intersections.at(i);
23740           pv2 = intersections.at(k);
23741           distSqrMax = distSqr;
23742         }
23743       }
23744     }
23745     intersections = QList<QPointF>() << pv1 << pv2;
23746   } else if (intersections.size() != 2)
23747   {
23748     // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
23749     return false;
23750   }
23751   
23752   // possibly re-sort points so optimized point segment has same direction as original segment:
23753   double xDelta = keyPx-prevKeyPx;
23754   double yDelta = valuePx-prevValuePx;
23755   if (mKeyAxis->orientation() != Qt::Horizontal)
23756     qSwap(xDelta, yDelta);
23757   if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction
23758     intersections.move(0, 1);
23759   crossA = intersections.at(0);
23760   crossB = intersections.at(1);
23761   return true;
23762 }
23763 
23764 /*! \internal
23765   
23766   This function is part of the curve optimization algorithm of \ref getCurveLines.
23767   
23768   This method assumes that the \ref getTraverse test has returned true, so the segment definitely
23769   traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
23770   
23771   In certain situations it is not sufficient to merely generate the entry and exit points of the
23772   segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
23773   addition to traversing region 5, skips another region outside of region 5, which makes it
23774   necessary to add an optimized corner point there (very similar to the job \ref
23775   getOptimizedCornerPoints does for segments that are completely in outside regions and don't
23776   traverse 5).
23777   
23778   As an example, consider a segment going from region 1 to region 6, traversing the lower left
23779   corner of region 5. In this configuration, the segment additionally crosses the border between
23780   region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
23781   the top left corner, before adding the optimized traverse points. So in this case, the output
23782   parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
23783   empty.
23784   
23785   In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
23786   corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
23787   return the respective corner points.
23788 */
23789 void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
23790 {
23791   switch (prevRegion)
23792   {
23793     case 1:
23794     {
23795       switch (currentRegion)
23796       {
23797         case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
23798         case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
23799         case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
23800       }
23801       break;
23802     }
23803     case 2:
23804     {
23805       switch (currentRegion)
23806       {
23807         case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
23808         case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
23809       }
23810       break;
23811     }
23812     case 3:
23813     {
23814       switch (currentRegion)
23815       {
23816         case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
23817         case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
23818         case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
23819       }
23820       break;
23821     }
23822     case 4:
23823     {
23824       switch (currentRegion)
23825       {
23826         case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
23827         case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
23828       }
23829       break;
23830     }
23831     case 5: { break; } // shouldn't happen because this method only handles full traverses
23832     case 6:
23833     {
23834       switch (currentRegion)
23835       {
23836         case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
23837         case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
23838       }
23839       break;
23840     }
23841     case 7:
23842     {
23843       switch (currentRegion)
23844       {
23845         case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
23846         case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
23847         case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
23848       }
23849       break;
23850     }
23851     case 8:
23852     {
23853       switch (currentRegion)
23854       {
23855         case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
23856         case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
23857       }
23858       break;
23859     }
23860     case 9:
23861     {
23862       switch (currentRegion)
23863       {
23864         case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
23865         case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
23866         case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
23867       }
23868       break;
23869     }
23870   }
23871 }
23872 
23873 /*! \internal
23874   
23875   Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
23876   pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
23877   \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
23878   if the curve has a line representation, the returned distance may be smaller than the distance to
23879   the \a closestData point, since the distance to the curve line is also taken into account.
23880   
23881   If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
23882   is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
23883   -1.0.
23884 */
23885 double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
23886 {
23887   closestData = mDataContainer->constEnd();
23888   if (mDataContainer->isEmpty())
23889     return -1.0;
23890   if (mLineStyle == lsNone && mScatterStyle.isNone())
23891     return -1.0;
23892   
23893   if (mDataContainer->size() == 1)
23894   {
23895     QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
23896     closestData = mDataContainer->constBegin();
23897     return QCPVector2D(dataPoint-pixelPoint).length();
23898   }
23899   
23900   // calculate minimum distances to curve data points and find closestData iterator:
23901   double minDistSqr = (std::numeric_limits<double>::max)();
23902   // iterate over found data points and then choose the one with the shortest distance to pos:
23903   QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
23904   QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
23905   for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
23906   {
23907     const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
23908     if (currentDistSqr < minDistSqr)
23909     {
23910       minDistSqr = currentDistSqr;
23911       closestData = it;
23912     }
23913   }
23914   
23915   // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
23916   if (mLineStyle != lsNone)
23917   {
23918     QVector<QPointF> lines;
23919     getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width
23920     for (int i=0; i<lines.size()-1; ++i)
23921     {
23922       double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
23923       if (currentDistSqr < minDistSqr)
23924         minDistSqr = currentDistSqr;
23925     }
23926   }
23927   
23928   return qSqrt(minDistSqr);
23929 }
23930 /* end of 'src/plottables/plottable-curve.cpp' */
23931 
23932 
23933 /* including file 'src/plottables/plottable-bars.cpp' */
23934 /* modified 2021-03-29T02:30:44, size 43907           */
23935 
23936 
23937 ////////////////////////////////////////////////////////////////////////////////////////////////////
23938 //////////////////// QCPBarsGroup
23939 ////////////////////////////////////////////////////////////////////////////////////////////////////
23940 
23941 /*! \class QCPBarsGroup
23942   \brief Groups multiple QCPBars together so they appear side by side
23943   
23944   \image html QCPBarsGroup.png
23945   
23946   When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
23947   to have them appearing next to each other at each key. This is what adding the respective QCPBars
23948   plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
23949   other, see \ref QCPBars::moveAbove.)
23950   
23951   \section qcpbarsgroup-usage Usage
23952   
23953   To add a QCPBars plottable to the group, create a new group and then add the respective bars
23954   intances:
23955   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
23956   Alternatively to appending to the group like shown above, you can also set the group on the
23957   QCPBars plottable via \ref QCPBars::setBarsGroup.
23958   
23959   The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
23960   bars in this group appear in the plot in the order they were appended. To insert a bars plottable
23961   at a certain index position, or to reposition a bars plottable which is already in the group, use
23962   \ref insert.
23963   
23964   To remove specific bars from the group, use either \ref remove or call \ref
23965   QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
23966   
23967   To clear the entire group, call \ref clear, or simply delete the group.
23968   
23969   \section qcpbarsgroup-example Example
23970   
23971   The image above is generated with the following code:
23972   \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
23973 */
23974 
23975 /* start of documentation of inline functions */
23976 
23977 /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
23978   
23979   Returns all bars currently in this group.
23980   
23981   \see bars(int index)
23982 */
23983 
23984 /*! \fn int QCPBarsGroup::size() const
23985   
23986   Returns the number of QCPBars plottables that are part of this group.
23987   
23988 */
23989 
23990 /*! \fn bool QCPBarsGroup::isEmpty() const
23991   
23992   Returns whether this bars group is empty.
23993   
23994   \see size
23995 */
23996 
23997 /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
23998   
23999   Returns whether the specified \a bars plottable is part of this group.
24000   
24001 */
24002 
24003 /* end of documentation of inline functions */
24004 
24005 /*!
24006   Constructs a new bars group for the specified QCustomPlot instance.
24007 */
24008 QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
24009   QObject(parentPlot),
24010   mParentPlot(parentPlot),
24011   mSpacingType(stAbsolute),
24012   mSpacing(4)
24013 {
24014 }
24015 
24016 QCPBarsGroup::~QCPBarsGroup()
24017 {
24018   clear();
24019 }
24020 
24021 /*!
24022   Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
24023   
24024   The actual spacing can then be specified with \ref setSpacing.
24025 
24026   \see setSpacing
24027 */
24028 void QCPBarsGroup::setSpacingType(SpacingType spacingType)
24029 {
24030   mSpacingType = spacingType;
24031 }
24032 
24033 /*!
24034   Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
24035   defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
24036 
24037   \see setSpacingType
24038 */
24039 void QCPBarsGroup::setSpacing(double spacing)
24040 {
24041   mSpacing = spacing;
24042 }
24043 
24044 /*!
24045   Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
24046   exists, returns \c nullptr.
24047 
24048   \see bars(), size
24049 */
24050 QCPBars *QCPBarsGroup::bars(int index) const
24051 {
24052   if (index >= 0 && index < mBars.size())
24053   {
24054     return mBars.at(index);
24055   } else
24056   {
24057     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
24058     return nullptr;
24059   }
24060 }
24061 
24062 /*!
24063   Removes all QCPBars plottables from this group.
24064 
24065   \see isEmpty
24066 */
24067 void QCPBarsGroup::clear()
24068 {
24069   const QList<QCPBars*> oldBars = mBars;
24070   foreach (QCPBars *bars, oldBars)
24071     bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
24072 }
24073 
24074 /*!
24075   Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
24076   QCPBars::setBarsGroup on the \a bars instance.
24077 
24078   \see insert, remove
24079 */
24080 void QCPBarsGroup::append(QCPBars *bars)
24081 {
24082   if (!bars)
24083   {
24084     qDebug() << Q_FUNC_INFO << "bars is 0";
24085     return;
24086   }
24087     
24088   if (!mBars.contains(bars))
24089     bars->setBarsGroup(this);
24090   else
24091     qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
24092 }
24093 
24094 /*!
24095   Inserts the specified \a bars plottable into this group at the specified index position \a i.
24096   This gives you full control over the ordering of the bars.
24097   
24098   \a bars may already be part of this group. In that case, \a bars is just moved to the new index
24099   position.
24100 
24101   \see append, remove
24102 */
24103 void QCPBarsGroup::insert(int i, QCPBars *bars)
24104 {
24105   if (!bars)
24106   {
24107     qDebug() << Q_FUNC_INFO << "bars is 0";
24108     return;
24109   }
24110   
24111   // first append to bars list normally:
24112   if (!mBars.contains(bars))
24113     bars->setBarsGroup(this);
24114   // then move to according position:
24115   mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
24116 }
24117 
24118 /*!
24119   Removes the specified \a bars plottable from this group.
24120   
24121   \see contains, clear
24122 */
24123 void QCPBarsGroup::remove(QCPBars *bars)
24124 {
24125   if (!bars)
24126   {
24127     qDebug() << Q_FUNC_INFO << "bars is 0";
24128     return;
24129   }
24130   
24131   if (mBars.contains(bars))
24132     bars->setBarsGroup(nullptr);
24133   else
24134     qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
24135 }
24136 
24137 /*! \internal
24138   
24139   Adds the specified \a bars to the internal mBars list of bars. This method does not change the
24140   barsGroup property on \a bars.
24141   
24142   \see unregisterBars
24143 */
24144 void QCPBarsGroup::registerBars(QCPBars *bars)
24145 {
24146   if (!mBars.contains(bars))
24147     mBars.append(bars);
24148 }
24149 
24150 /*! \internal
24151   
24152   Removes the specified \a bars from the internal mBars list of bars. This method does not change
24153   the barsGroup property on \a bars.
24154   
24155   \see registerBars
24156 */
24157 void QCPBarsGroup::unregisterBars(QCPBars *bars)
24158 {
24159   mBars.removeOne(bars);
24160 }
24161 
24162 /*! \internal
24163   
24164   Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
24165   given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
24166   coordinate \a keyCoord.
24167 */
24168 double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
24169 {
24170   // find list of all base bars in case some mBars are stacked:
24171   QList<const QCPBars*> baseBars;
24172   foreach (const QCPBars *b, mBars)
24173   {
24174     while (b->barBelow())
24175       b = b->barBelow();
24176     if (!baseBars.contains(b))
24177       baseBars.append(b);
24178   }
24179   // find base bar this "bars" is stacked on:
24180   const QCPBars *thisBase = bars;
24181   while (thisBase->barBelow())
24182     thisBase = thisBase->barBelow();
24183   
24184   // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
24185   double result = 0;
24186   int index = baseBars.indexOf(thisBase);
24187   if (index >= 0)
24188   {
24189     if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
24190     {
24191       return result;
24192     } else
24193     {
24194       double lowerPixelWidth, upperPixelWidth;
24195       int startIndex;
24196       int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
24197       if (baseBars.size() % 2 == 0) // even number of bars
24198       {
24199         startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
24200         result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
24201       } else // uneven number of bars
24202       {
24203         startIndex = (baseBars.size()-1)/2+dir;
24204         baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
24205         result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
24206         result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
24207       }
24208       for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
24209       {
24210         baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
24211         result += qAbs(upperPixelWidth-lowerPixelWidth);
24212         result += getPixelSpacing(baseBars.at(i), keyCoord);
24213       }
24214       // finally half of our bars width:
24215       baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
24216       result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
24217       // correct sign of result depending on orientation and direction of key axis:
24218       result *= dir*thisBase->keyAxis()->pixelOrientation();
24219     }
24220   }
24221   return result;
24222 }
24223 
24224 /*! \internal
24225   
24226   Returns the spacing in pixels which is between this \a bars and the following one, both at the
24227   key coordinate \a keyCoord.
24228   
24229   \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
24230   needed to get access to the key axis transformation and axis rect for the modes \ref
24231   stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
24232   \ref stPlotCoords on a logarithmic axis.
24233 */
24234 double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
24235 {
24236   switch (mSpacingType)
24237   {
24238     case stAbsolute:
24239     {
24240       return mSpacing;
24241     }
24242     case stAxisRectRatio:
24243     {
24244       if (bars->keyAxis()->orientation() == Qt::Horizontal)
24245         return bars->keyAxis()->axisRect()->width()*mSpacing;
24246       else
24247         return bars->keyAxis()->axisRect()->height()*mSpacing;
24248     }
24249     case stPlotCoords:
24250     {
24251       double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
24252       return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
24253     }
24254   }
24255   return 0;
24256 }
24257 
24258 
24259 ////////////////////////////////////////////////////////////////////////////////////////////////////
24260 //////////////////// QCPBarsData
24261 ////////////////////////////////////////////////////////////////////////////////////////////////////
24262 
24263 /*! \class QCPBarsData
24264   \brief Holds the data of one single data point (one bar) for QCPBars.
24265   
24266   The stored data is:
24267   \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
24268   \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
24269   
24270   The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
24271   \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
24272   documentation there for an explanation regarding the data type's generic methods.
24273   
24274   \see QCPBarsDataContainer
24275 */
24276 
24277 /* start documentation of inline functions */
24278 
24279 /*! \fn double QCPBarsData::sortKey() const
24280   
24281   Returns the \a key member of this data point.
24282   
24283   For a general explanation of what this method is good for in the context of the data container,
24284   see the documentation of \ref QCPDataContainer.
24285 */
24286 
24287 /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
24288   
24289   Returns a data point with the specified \a sortKey. All other members are set to zero.
24290   
24291   For a general explanation of what this method is good for in the context of the data container,
24292   see the documentation of \ref QCPDataContainer.
24293 */
24294 
24295 /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
24296   
24297   Since the member \a key is both the data point key coordinate and the data ordering parameter,
24298   this method returns true.
24299   
24300   For a general explanation of what this method is good for in the context of the data container,
24301   see the documentation of \ref QCPDataContainer.
24302 */
24303 
24304 /*! \fn double QCPBarsData::mainKey() const
24305   
24306   Returns the \a key member of this data point.
24307   
24308   For a general explanation of what this method is good for in the context of the data container,
24309   see the documentation of \ref QCPDataContainer.
24310 */
24311 
24312 /*! \fn double QCPBarsData::mainValue() const
24313   
24314   Returns the \a value member of this data point.
24315   
24316   For a general explanation of what this method is good for in the context of the data container,
24317   see the documentation of \ref QCPDataContainer.
24318 */
24319 
24320 /*! \fn QCPRange QCPBarsData::valueRange() const
24321   
24322   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
24323   
24324   For a general explanation of what this method is good for in the context of the data container,
24325   see the documentation of \ref QCPDataContainer.
24326 */
24327 
24328 /* end documentation of inline functions */
24329 
24330 /*!
24331   Constructs a bar data point with key and value set to zero.
24332 */
24333 QCPBarsData::QCPBarsData() :
24334   key(0),
24335   value(0)
24336 {
24337 }
24338 
24339 /*!
24340   Constructs a bar data point with the specified \a key and \a value.
24341 */
24342 QCPBarsData::QCPBarsData(double key, double value) :
24343   key(key),
24344   value(value)
24345 {
24346 }
24347 
24348 
24349 ////////////////////////////////////////////////////////////////////////////////////////////////////
24350 //////////////////// QCPBars
24351 ////////////////////////////////////////////////////////////////////////////////////////////////////
24352 
24353 /*! \class QCPBars
24354   \brief A plottable representing a bar chart in a plot.
24355 
24356   \image html QCPBars.png
24357   
24358   To plot data, assign it with the \ref setData or \ref addData functions.
24359   
24360   \section qcpbars-appearance Changing the appearance
24361   
24362   The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
24363   The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
24364   
24365   Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
24366   (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
24367   stacked.
24368   
24369   If you would like to group multiple QCPBars plottables together so they appear side by side as
24370   shown below, use QCPBarsGroup.
24371   
24372   \image html QCPBarsGroup.png
24373   
24374   \section qcpbars-usage Usage
24375   
24376   Like all data representing objects in QCustomPlot, the QCPBars is a plottable
24377   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
24378   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
24379   
24380   Usually, you first create an instance:
24381   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
24382   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
24383   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
24384   The newly created plottable can be modified, e.g.:
24385   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
24386 */
24387 
24388 /* start of documentation of inline functions */
24389 
24390 /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
24391   
24392   Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
24393   use it to directly manipulate the data, which may be more convenient and faster than using the
24394   regular \ref setData or \ref addData methods.
24395 */
24396 
24397 /*! \fn QCPBars *QCPBars::barBelow() const
24398   Returns the bars plottable that is directly below this bars plottable.
24399   If there is no such plottable, returns \c nullptr.
24400   
24401   \see barAbove, moveBelow, moveAbove
24402 */
24403 
24404 /*! \fn QCPBars *QCPBars::barAbove() const
24405   Returns the bars plottable that is directly above this bars plottable.
24406   If there is no such plottable, returns \c nullptr.
24407   
24408   \see barBelow, moveBelow, moveAbove
24409 */
24410 
24411 /* end of documentation of inline functions */
24412 
24413 /*!
24414   Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
24415   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
24416   the same orientation. If either of these restrictions is violated, a corresponding message is
24417   printed to the debug output (qDebug), the construction is not aborted, though.
24418   
24419   The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
24420   keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
24421   but use QCustomPlot::removePlottable() instead.
24422 */
24423 QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
24424   QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
24425   mWidth(0.75),
24426   mWidthType(wtPlotCoords),
24427   mBarsGroup(nullptr),
24428   mBaseValue(0),
24429   mStackingGap(1)
24430 {
24431   // modify inherited properties from abstract plottable:
24432   mPen.setColor(Qt::blue);
24433   mPen.setStyle(Qt::SolidLine);
24434   mBrush.setColor(QColor(40, 50, 255, 30));
24435   mBrush.setStyle(Qt::SolidPattern);
24436   mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
24437 }
24438 
24439 QCPBars::~QCPBars()
24440 {
24441   setBarsGroup(nullptr);
24442   if (mBarBelow || mBarAbove)
24443     connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
24444 }
24445 
24446 /*! \overload
24447   
24448   Replaces the current data container with the provided \a data container.
24449   
24450   Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
24451   Modifying the data in the container will then affect all bars that share the container. Sharing
24452   can be achieved by simply exchanging the data containers wrapped in shared pointers:
24453   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
24454   
24455   If you do not wish to share containers, but create a copy from an existing container, rather use
24456   the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
24457   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
24458   
24459   \see addData
24460 */
24461 void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
24462 {
24463   mDataContainer = data;
24464 }
24465 
24466 /*! \overload
24467   
24468   Replaces the current data with the provided points in \a keys and \a values. The provided
24469   vectors should have equal length. Else, the number of added points will be the size of the
24470   smallest vector.
24471   
24472   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
24473   can set \a alreadySorted to true, to improve performance by saving a sorting run.
24474   
24475   \see addData
24476 */
24477 void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
24478 {
24479   mDataContainer->clear();
24480   addData(keys, values, alreadySorted);
24481 }
24482 
24483 /*!
24484   Sets the width of the bars.
24485 
24486   How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
24487   depends on the currently set width type, see \ref setWidthType and \ref WidthType.
24488 */
24489 void QCPBars::setWidth(double width)
24490 {
24491   mWidth = width;
24492 }
24493 
24494 /*!
24495   Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
24496   explanation of the possible values for \a widthType.
24497   
24498   The default value is \ref wtPlotCoords.
24499   
24500   \see setWidth
24501 */
24502 void QCPBars::setWidthType(QCPBars::WidthType widthType)
24503 {
24504   mWidthType = widthType;
24505 }
24506 
24507 /*!
24508   Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
24509   QCPBarsGroup::append.
24510   
24511   To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
24512 */
24513 void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
24514 {
24515   // deregister at old group:
24516   if (mBarsGroup)
24517     mBarsGroup->unregisterBars(this);
24518   mBarsGroup = barsGroup;
24519   // register at new group:
24520   if (mBarsGroup)
24521     mBarsGroup->registerBars(this);
24522 }
24523 
24524 /*!
24525   Sets the base value of this bars plottable.
24526 
24527   The base value defines where on the value coordinate the bars start. How far the bars extend from
24528   the base value is given by their individual value data. For example, if the base value is set to
24529   1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
24530   3.
24531   
24532   For stacked bars, only the base value of the bottom-most QCPBars has meaning.
24533   
24534   The default base value is 0.
24535 */
24536 void QCPBars::setBaseValue(double baseValue)
24537 {
24538   mBaseValue = baseValue;
24539 }
24540 
24541 /*!
24542   If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
24543   allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
24544   the bars below it.
24545 */
24546 void QCPBars::setStackingGap(double pixels)
24547 {
24548   mStackingGap = pixels;
24549 }
24550 
24551 /*! \overload
24552   
24553   Adds the provided points in \a keys and \a values to the current data. The provided vectors
24554   should have equal length. Else, the number of added points will be the size of the smallest
24555   vector.
24556   
24557   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
24558   can set \a alreadySorted to true, to improve performance by saving a sorting run.
24559   
24560   Alternatively, you can also access and modify the data directly via the \ref data method, which
24561   returns a pointer to the internal data container.
24562 */
24563 void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
24564 {
24565   if (keys.size() != values.size())
24566     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
24567   const int n = qMin(keys.size(), values.size());
24568   QVector<QCPBarsData> tempData(n);
24569   QVector<QCPBarsData>::iterator it = tempData.begin();
24570   const QVector<QCPBarsData>::iterator itEnd = tempData.end();
24571   int i = 0;
24572   while (it != itEnd)
24573   {
24574     it->key = keys[i];
24575     it->value = values[i];
24576     ++it;
24577     ++i;
24578   }
24579   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
24580 }
24581 
24582 /*! \overload
24583   Adds the provided data point as \a key and \a value to the current data.
24584   
24585   Alternatively, you can also access and modify the data directly via the \ref data method, which
24586   returns a pointer to the internal data container.
24587 */
24588 void QCPBars::addData(double key, double value)
24589 {
24590   mDataContainer->add(QCPBarsData(key, value));
24591 }
24592 
24593 /*!
24594   Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
24595   below the bars of \a bars. The move target \a bars must use the same key and value axis as this
24596   plottable.
24597   
24598   Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
24599   has a bars object below itself, this bars object is inserted between the two. If this bars object
24600   is already between two other bars, the two other bars will be stacked on top of each other after
24601   the operation.
24602   
24603   To remove this bars plottable from any stacking, set \a bars to \c nullptr.
24604   
24605   \see moveBelow, barAbove, barBelow
24606 */
24607 void QCPBars::moveBelow(QCPBars *bars)
24608 {
24609   if (bars == this) return;
24610   if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
24611   {
24612     qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
24613     return;
24614   }
24615   // remove from stacking:
24616   connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
24617   // if new bar given, insert this bar below it:
24618   if (bars)
24619   {
24620     if (bars->mBarBelow)
24621       connectBars(bars->mBarBelow.data(), this);
24622     connectBars(this, bars);
24623   }
24624 }
24625 
24626 /*!
24627   Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
24628   above the bars of \a bars. The move target \a bars must use the same key and value axis as this
24629   plottable.
24630   
24631   Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
24632   has a bars object above itself, this bars object is inserted between the two. If this bars object
24633   is already between two other bars, the two other bars will be stacked on top of each other after
24634   the operation.
24635   
24636   To remove this bars plottable from any stacking, set \a bars to \c nullptr.
24637   
24638   \see moveBelow, barBelow, barAbove
24639 */
24640 void QCPBars::moveAbove(QCPBars *bars)
24641 {
24642   if (bars == this) return;
24643   if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
24644   {
24645     qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
24646     return;
24647   }
24648   // remove from stacking:
24649   connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
24650   // if new bar given, insert this bar above it:
24651   if (bars)
24652   {
24653     if (bars->mBarAbove)
24654       connectBars(this, bars->mBarAbove.data());
24655     connectBars(bars, this);
24656   }
24657 }
24658 
24659 /*!
24660   \copydoc QCPPlottableInterface1D::selectTestRect
24661 */
24662 QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
24663 {
24664   QCPDataSelection result;
24665   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
24666     return result;
24667   if (!mKeyAxis || !mValueAxis)
24668     return result;
24669   
24670   QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
24671   getVisibleDataBounds(visibleBegin, visibleEnd);
24672   
24673   for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
24674   {
24675     if (rect.intersects(getBarRect(it->key, it->value)))
24676       result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
24677   }
24678   result.simplify();
24679   return result;
24680 }
24681 
24682 /*!
24683   Implements a selectTest specific to this plottable's point geometry.
24684 
24685   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
24686   point to \a pos.
24687   
24688   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
24689 */
24690 double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
24691 {
24692   Q_UNUSED(details)
24693   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
24694     return -1;
24695   if (!mKeyAxis || !mValueAxis)
24696     return -1;
24697   
24698   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
24699   {
24700     // get visible data range:
24701     QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
24702     getVisibleDataBounds(visibleBegin, visibleEnd);
24703     for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
24704     {
24705       if (getBarRect(it->key, it->value).contains(pos))
24706       {
24707         if (details)
24708         {
24709           int pointIndex = int(it-mDataContainer->constBegin());
24710           details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
24711         }
24712         return mParentPlot->selectionTolerance()*0.99;
24713       }
24714     }
24715   }
24716   return -1;
24717 }
24718 
24719 /* inherits documentation from base class */
24720 QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
24721 {
24722   /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
24723   absolute pixels), using this method to adapt the key axis range to fit the bars into the
24724   currently visible axis range will not work perfectly. Because in the moment the axis range is
24725   changed to the new range, the fixed pixel widths/spacings will represent different coordinate
24726   spans than before, which in turn would require a different key range to perfectly fit, and so on.
24727   The only solution would be to iteratively approach the perfect fitting axis range, but the
24728   mismatch isn't large enough in most applications, to warrant this here. If a user does need a
24729   better fit, he should call the corresponding axis rescale multiple times in a row.
24730   */
24731   QCPRange range;
24732   range = mDataContainer->keyRange(foundRange, inSignDomain);
24733   
24734   // determine exact range of bars by including bar width and barsgroup offset:
24735   if (foundRange && mKeyAxis)
24736   {
24737     double lowerPixelWidth, upperPixelWidth, keyPixel;
24738     // lower range bound:
24739     getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
24740     keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
24741     if (mBarsGroup)
24742       keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
24743     const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
24744     if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
24745       range.lower = lowerCorrected;
24746     // upper range bound:
24747     getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
24748     keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
24749     if (mBarsGroup)
24750       keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
24751     const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
24752     if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
24753       range.upper = upperCorrected;
24754   }
24755   return range;
24756 }
24757 
24758 /* inherits documentation from base class */
24759 QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
24760 {
24761   // Note: can't simply use mDataContainer->valueRange here because we need to
24762   // take into account bar base value and possible stacking of multiple bars
24763   QCPRange range;
24764   range.lower = mBaseValue;
24765   range.upper = mBaseValue;
24766   bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
24767   bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
24768   QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
24769   QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
24770   if (inKeyRange != QCPRange())
24771   {
24772     itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
24773     itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
24774   }
24775   for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
24776   {
24777     const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
24778     if (qIsNaN(current)) continue;
24779     if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
24780     {
24781       if (current < range.lower || !haveLower)
24782       {
24783         range.lower = current;
24784         haveLower = true;
24785       }
24786       if (current > range.upper || !haveUpper)
24787       {
24788         range.upper = current;
24789         haveUpper = true;
24790       }
24791     }
24792   }
24793   
24794   foundRange = true; // return true because bar charts always have the 0-line visible
24795   return range;
24796 }
24797 
24798 /* inherits documentation from base class */
24799 QPointF QCPBars::dataPixelPosition(int index) const
24800 {
24801   if (index >= 0 && index < mDataContainer->size())
24802   {
24803     QCPAxis *keyAxis = mKeyAxis.data();
24804     QCPAxis *valueAxis = mValueAxis.data();
24805     if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
24806     
24807     const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
24808     const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
24809     const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
24810     if (keyAxis->orientation() == Qt::Horizontal)
24811       return {keyPixel, valuePixel};
24812     else
24813       return {valuePixel, keyPixel};
24814   } else
24815   {
24816     qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
24817     return {};
24818   }
24819 }
24820 
24821 /* inherits documentation from base class */
24822 void QCPBars::draw(QCPPainter *painter)
24823 {
24824   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
24825   if (mDataContainer->isEmpty()) return;
24826   
24827   QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
24828   getVisibleDataBounds(visibleBegin, visibleEnd);
24829   
24830   // loop over and draw segments of unselected/selected data:
24831   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
24832   getDataSegments(selectedSegments, unselectedSegments);
24833   allSegments << unselectedSegments << selectedSegments;
24834   for (int i=0; i<allSegments.size(); ++i)
24835   {
24836     bool isSelectedSegment = i >= unselectedSegments.size();
24837     QCPBarsDataContainer::const_iterator begin = visibleBegin;
24838     QCPBarsDataContainer::const_iterator end = visibleEnd;
24839     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
24840     if (begin == end)
24841       continue;
24842     
24843     for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
24844     {
24845       // check data validity if flag set:
24846 #ifdef QCUSTOMPLOT_CHECK_DATA
24847       if (QCP::isInvalidData(it->key, it->value))
24848         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
24849 #endif
24850       // draw bar:
24851       if (isSelectedSegment && mSelectionDecorator)
24852       {
24853         mSelectionDecorator->applyBrush(painter);
24854         mSelectionDecorator->applyPen(painter);
24855       } else
24856       {
24857         painter->setBrush(mBrush);
24858         painter->setPen(mPen);
24859       }
24860       applyDefaultAntialiasingHint(painter);
24861       painter->drawPolygon(getBarRect(it->key, it->value));
24862     }
24863   }
24864   
24865   // draw other selection decoration that isn't just line/scatter pens and brushes:
24866   if (mSelectionDecorator)
24867     mSelectionDecorator->drawDecoration(painter, selection());
24868 }
24869 
24870 /* inherits documentation from base class */
24871 void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
24872 {
24873   // draw filled rect:
24874   applyDefaultAntialiasingHint(painter);
24875   painter->setBrush(mBrush);
24876   painter->setPen(mPen);
24877   QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
24878   r.moveCenter(rect.center());
24879   painter->drawRect(r);
24880 }
24881 
24882 /*!  \internal
24883   
24884   called by \ref draw to determine which data (key) range is visible at the current key axis range
24885   setting, so only that needs to be processed. It also takes into account the bar width.
24886   
24887   \a begin returns an iterator to the lowest data point that needs to be taken into account when
24888   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
24889   lower may still be just outside the visible range.
24890   
24891   \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
24892   may also lie just outside of the visible range.
24893   
24894   if the plottable contains no data, both \a begin and \a end point to constEnd.
24895 */
24896 void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
24897 {
24898   if (!mKeyAxis)
24899   {
24900     qDebug() << Q_FUNC_INFO << "invalid key axis";
24901     begin = mDataContainer->constEnd();
24902     end = mDataContainer->constEnd();
24903     return;
24904   }
24905   if (mDataContainer->isEmpty())
24906   {
24907     begin = mDataContainer->constEnd();
24908     end = mDataContainer->constEnd();
24909     return;
24910   }
24911   
24912   // get visible data range as QMap iterators
24913   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
24914   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
24915   double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
24916   double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
24917   bool isVisible = false;
24918   // walk left from begin to find lower bar that actually is completely outside visible pixel range:
24919   QCPBarsDataContainer::const_iterator it = begin;
24920   while (it != mDataContainer->constBegin())
24921   {
24922     --it;
24923     const QRectF barRect = getBarRect(it->key, it->value);
24924     if (mKeyAxis.data()->orientation() == Qt::Horizontal)
24925       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
24926     else // keyaxis is vertical
24927       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
24928     if (isVisible)
24929       begin = it;
24930     else
24931       break;
24932   }
24933   // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
24934   it = end;
24935   while (it != mDataContainer->constEnd())
24936   {
24937     const QRectF barRect = getBarRect(it->key, it->value);
24938     if (mKeyAxis.data()->orientation() == Qt::Horizontal)
24939       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
24940     else // keyaxis is vertical
24941       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
24942     if (isVisible)
24943       end = it+1;
24944     else
24945       break;
24946     ++it;
24947   }
24948 }
24949 
24950 /*! \internal
24951   
24952   Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
24953   rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
24954   setBaseValue), and to have non-overlapping border lines with the bars stacked below.
24955 */
24956 QRectF QCPBars::getBarRect(double key, double value) const
24957 {
24958   QCPAxis *keyAxis = mKeyAxis.data();
24959   QCPAxis *valueAxis = mValueAxis.data();
24960   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
24961   
24962   double lowerPixelWidth, upperPixelWidth;
24963   getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
24964   double base = getStackedBaseValue(key, value >= 0);
24965   double basePixel = valueAxis->coordToPixel(base);
24966   double valuePixel = valueAxis->coordToPixel(base+value);
24967   double keyPixel = keyAxis->coordToPixel(key);
24968   if (mBarsGroup)
24969     keyPixel += mBarsGroup->keyPixelOffset(this, key);
24970   double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
24971   bottomOffset += mBarBelow ? mStackingGap : 0;
24972   bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
24973   if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
24974     bottomOffset = valuePixel-basePixel;
24975   if (keyAxis->orientation() == Qt::Horizontal)
24976   {
24977     return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
24978   } else
24979   {
24980     return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
24981   }
24982 }
24983 
24984 /*! \internal
24985   
24986   This function is used to determine the width of the bar at coordinate \a key, according to the
24987   specified width (\ref setWidth) and width type (\ref setWidthType).
24988   
24989   The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
24990   and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
24991   lower is negative and \a upper positive).
24992 */
24993 void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
24994 {
24995   lower = 0;
24996   upper = 0;
24997   switch (mWidthType)
24998   {
24999     case wtAbsolute:
25000     {
25001       upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
25002       lower = -upper;
25003       break;
25004     }
25005     case wtAxisRectRatio:
25006     {
25007       if (mKeyAxis && mKeyAxis.data()->axisRect())
25008       {
25009         if (mKeyAxis.data()->orientation() == Qt::Horizontal)
25010           upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
25011         else
25012           upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
25013         lower = -upper;
25014       } else
25015         qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
25016       break;
25017     }
25018     case wtPlotCoords:
25019     {
25020       if (mKeyAxis)
25021       {
25022         double keyPixel = mKeyAxis.data()->coordToPixel(key);
25023         upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
25024         lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
25025         // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
25026         // coordinate transform which includes range direction
25027       } else
25028         qDebug() << Q_FUNC_INFO << "No key axis defined";
25029       break;
25030     }
25031   }
25032 }
25033 
25034 /*! \internal
25035   
25036   This function is called to find at which value to start drawing the base of a bar at \a key, when
25037   it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
25038   
25039   positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
25040   negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
25041   bar for which we need the base value is negative, set \a positive to false.
25042 */
25043 double QCPBars::getStackedBaseValue(double key, bool positive) const
25044 {
25045   if (mBarBelow)
25046   {
25047     double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
25048     // find bars of mBarBelow that are approximately at key and find largest one:
25049     double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
25050     if (key == 0)
25051       epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
25052     QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
25053     QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
25054     while (it != itEnd)
25055     {
25056       if (it->key > key-epsilon && it->key < key+epsilon)
25057       {
25058         if ((positive && it->value > max) ||
25059             (!positive && it->value < max))
25060           max = it->value;
25061       }
25062       ++it;
25063     }
25064     // recurse down the bar-stack to find the total height:
25065     return max + mBarBelow.data()->getStackedBaseValue(key, positive);
25066   } else
25067     return mBaseValue;
25068 }
25069 
25070 /*! \internal
25071 
25072   Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
25073   currently above lower and below upper will become disconnected to lower/upper.
25074   
25075   If lower is zero, upper will be disconnected at the bottom.
25076   If upper is zero, lower will be disconnected at the top.
25077 */
25078 void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
25079 {
25080   if (!lower && !upper) return;
25081   
25082   if (!lower) // disconnect upper at bottom
25083   {
25084     // disconnect old bar below upper:
25085     if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
25086       upper->mBarBelow.data()->mBarAbove = nullptr;
25087     upper->mBarBelow = nullptr;
25088   } else if (!upper) // disconnect lower at top
25089   {
25090     // disconnect old bar above lower:
25091     if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
25092       lower->mBarAbove.data()->mBarBelow = nullptr;
25093     lower->mBarAbove = nullptr;
25094   } else // connect lower and upper
25095   {
25096     // disconnect old bar above lower:
25097     if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
25098       lower->mBarAbove.data()->mBarBelow = nullptr;
25099     // disconnect old bar below upper:
25100     if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
25101       upper->mBarBelow.data()->mBarAbove = nullptr;
25102     lower->mBarAbove = upper;
25103     upper->mBarBelow = lower;
25104   }
25105 }
25106 /* end of 'src/plottables/plottable-bars.cpp' */
25107 
25108 
25109 /* including file 'src/plottables/plottable-statisticalbox.cpp' */
25110 /* modified 2021-03-29T02:30:44, size 28951                     */
25111 
25112 ////////////////////////////////////////////////////////////////////////////////////////////////////
25113 //////////////////// QCPStatisticalBoxData
25114 ////////////////////////////////////////////////////////////////////////////////////////////////////
25115 
25116 /*! \class QCPStatisticalBoxData
25117   \brief Holds the data of one single data point for QCPStatisticalBox.
25118   
25119   The stored data is:
25120   
25121   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
25122   
25123   \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
25124   sample that's not considered an outlier.
25125   
25126   \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
25127   statistical quartiles around the median of the sample, they should contain 50% of the sample
25128   data.
25129   
25130   \li \a median: the value of the median mark inside the quartile box. The median separates the
25131   sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
25132   
25133   \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
25134   statistical quartiles around the median of the sample, they should contain 50% of the sample
25135   data.
25136   
25137   \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
25138   sample that's not considered an outlier.
25139   
25140   \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
25141   coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
25142   
25143   The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
25144   typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
25145   parameter. See the documentation there for an explanation regarding the data type's generic
25146   methods.
25147   
25148   \see QCPStatisticalBoxDataContainer
25149 */
25150 
25151 /* start documentation of inline functions */
25152 
25153 /*! \fn double QCPStatisticalBoxData::sortKey() const
25154   
25155   Returns the \a key member of this data point.
25156   
25157   For a general explanation of what this method is good for in the context of the data container,
25158   see the documentation of \ref QCPDataContainer.
25159 */
25160 
25161 /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
25162   
25163   Returns a data point with the specified \a sortKey. All other members are set to zero.
25164   
25165   For a general explanation of what this method is good for in the context of the data container,
25166   see the documentation of \ref QCPDataContainer.
25167 */
25168 
25169 /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
25170   
25171   Since the member \a key is both the data point key coordinate and the data ordering parameter,
25172   this method returns true.
25173   
25174   For a general explanation of what this method is good for in the context of the data container,
25175   see the documentation of \ref QCPDataContainer.
25176 */
25177 
25178 /*! \fn double QCPStatisticalBoxData::mainKey() const
25179   
25180   Returns the \a key member of this data point.
25181   
25182   For a general explanation of what this method is good for in the context of the data container,
25183   see the documentation of \ref QCPDataContainer.
25184 */
25185 
25186 /*! \fn double QCPStatisticalBoxData::mainValue() const
25187   
25188   Returns the \a median member of this data point.
25189   
25190   For a general explanation of what this method is good for in the context of the data container,
25191   see the documentation of \ref QCPDataContainer.
25192 */
25193 
25194 /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
25195   
25196   Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
25197   data point, possibly further expanded by outliers.
25198   
25199   For a general explanation of what this method is good for in the context of the data container,
25200   see the documentation of \ref QCPDataContainer.
25201 */
25202 
25203 /* end documentation of inline functions */
25204 
25205 /*!
25206   Constructs a data point with key and all values set to zero.
25207 */
25208 QCPStatisticalBoxData::QCPStatisticalBoxData() :
25209   key(0),
25210   minimum(0),
25211   lowerQuartile(0),
25212   median(0),
25213   upperQuartile(0),
25214   maximum(0)
25215 {
25216 }
25217 
25218 /*!
25219   Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
25220   upperQuartile, \a maximum and optionally a number of \a outliers.
25221 */
25222 QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
25223   key(key),
25224   minimum(minimum),
25225   lowerQuartile(lowerQuartile),
25226   median(median),
25227   upperQuartile(upperQuartile),
25228   maximum(maximum),
25229   outliers(outliers)
25230 {
25231 }
25232 
25233 
25234 ////////////////////////////////////////////////////////////////////////////////////////////////////
25235 //////////////////// QCPStatisticalBox
25236 ////////////////////////////////////////////////////////////////////////////////////////////////////
25237 
25238 /*! \class QCPStatisticalBox
25239   \brief A plottable representing a single statistical box in a plot.
25240 
25241   \image html QCPStatisticalBox.png
25242   
25243   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
25244   also access and modify the data via the \ref data method, which returns a pointer to the internal
25245   \ref QCPStatisticalBoxDataContainer.
25246   
25247   Additionally each data point can itself have a list of outliers, drawn as scatter points at the
25248   key coordinate of the respective statistical box data point. They can either be set by using the
25249   respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
25250   "addData" method or accessing the individual data points through \ref data, and setting the
25251   <tt>QVector<double> outliers</tt> of the data points directly.
25252   
25253   \section qcpstatisticalbox-appearance Changing the appearance
25254   
25255   The appearance of each data point box, ranging from the lower to the upper quartile, is
25256   controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
25257   setWidth in plot coordinates.
25258 
25259   Each data point's visual representation also consists of two whiskers. Whiskers are the lines
25260   which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
25261   The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
25262   \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
25263   the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
25264   the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
25265   few pixels due to the pen cap being not perfectly flat.
25266   
25267   The median indicator line inside the box has its own pen, \ref setMedianPen.
25268   
25269   The outlier data points are drawn as normal scatter points. Their look can be controlled with
25270   \ref setOutlierStyle
25271   
25272   \section qcpstatisticalbox-usage Usage
25273   
25274   Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
25275   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
25276   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
25277   
25278   Usually, you first create an instance:
25279   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
25280   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
25281   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
25282   The newly created plottable can be modified, e.g.:
25283   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
25284 */
25285 
25286 /* start documentation of inline functions */
25287 
25288 /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
25289   
25290   Returns a shared pointer to the internal data storage of type \ref
25291   QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
25292   convenient and faster than using the regular \ref setData or \ref addData methods.
25293 */
25294 
25295 /* end documentation of inline functions */
25296 
25297 /*!
25298   Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
25299   value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
25300   not have the same orientation. If either of these restrictions is violated, a corresponding
25301   message is printed to the debug output (qDebug), the construction is not aborted, though.
25302   
25303   The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
25304   from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
25305   delete it manually but use QCustomPlot::removePlottable() instead.
25306 */
25307 QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
25308   QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
25309   mWidth(0.5),
25310   mWhiskerWidth(0.2),
25311   mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
25312   mWhiskerBarPen(Qt::black),
25313   mWhiskerAntialiased(false),
25314   mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
25315   mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
25316 {
25317   setPen(QPen(Qt::black));
25318   setBrush(Qt::NoBrush);
25319 }
25320 
25321 /*! \overload
25322   
25323   Replaces the current data container with the provided \a data container.
25324   
25325   Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
25326   safely. Modifying the data in the container will then affect all statistical boxes that share the
25327   container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
25328   pointers:
25329   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
25330   
25331   If you do not wish to share containers, but create a copy from an existing container, rather use
25332   the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
25333   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
25334   
25335   \see addData
25336 */
25337 void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
25338 {
25339   mDataContainer = data;
25340 }
25341 /*! \overload
25342   
25343   Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
25344   median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
25345   number of added points will be the size of the smallest vector.
25346   
25347   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
25348   can set \a alreadySorted to true, to improve performance by saving a sorting run.
25349   
25350   \see addData
25351 */
25352 void QCPStatisticalBox::setData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
25353 {
25354   mDataContainer->clear();
25355   addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
25356 }
25357 
25358 /*!
25359   Sets the width of the boxes in key coordinates.
25360   
25361   \see setWhiskerWidth
25362 */
25363 void QCPStatisticalBox::setWidth(double width)
25364 {
25365   mWidth = width;
25366 }
25367 
25368 /*!
25369   Sets the width of the whiskers in key coordinates.
25370   
25371   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
25372   quartile to the minimum.
25373   
25374   \see setWidth
25375 */
25376 void QCPStatisticalBox::setWhiskerWidth(double width)
25377 {
25378   mWhiskerWidth = width;
25379 }
25380 
25381 /*!
25382   Sets the pen used for drawing the whisker backbone.
25383   
25384   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
25385   quartile to the minimum.
25386   
25387   Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
25388   line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
25389   
25390   \see setWhiskerBarPen
25391 */
25392 void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
25393 {
25394   mWhiskerPen = pen;
25395 }
25396 
25397 /*!
25398   Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
25399   each end of the whisker backbone.
25400   
25401   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
25402   quartile to the minimum.
25403   
25404   \see setWhiskerPen
25405 */
25406 void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
25407 {
25408   mWhiskerBarPen = pen;
25409 }
25410 
25411 /*!
25412   Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
25413 
25414   Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
25415   QCustomPlot::setNotAntialiasedElements.
25416 */
25417 void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
25418 {
25419   mWhiskerAntialiased = enabled;
25420 }
25421 
25422 /*!
25423   Sets the pen used for drawing the median indicator line inside the statistical boxes.
25424 */
25425 void QCPStatisticalBox::setMedianPen(const QPen &pen)
25426 {
25427   mMedianPen = pen;
25428 }
25429 
25430 /*!
25431   Sets the appearance of the outlier data points.
25432 
25433   Outliers can be specified with the method
25434   \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
25435 */
25436 void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
25437 {
25438   mOutlierStyle = style;
25439 }
25440 
25441 /*! \overload
25442    
25443   Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
25444   \a maximum to the current data. The provided vectors should have equal length. Else, the number
25445   of added points will be the size of the smallest vector.
25446    
25447   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
25448   can set \a alreadySorted to true, to improve performance by saving a sorting run.
25449    
25450   Alternatively, you can also access and modify the data directly via the \ref data method, which
25451   returns a pointer to the internal data container.
25452 */
25453 void QCPStatisticalBox::addData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
25454 {
25455   if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
25456       median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
25457     qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
25458              << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
25459   const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
25460   QVector<QCPStatisticalBoxData> tempData(n);
25461   QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
25462   const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
25463   int i = 0;
25464   while (it != itEnd)
25465   {
25466     it->key = keys[i];
25467     it->minimum = minimum[i];
25468     it->lowerQuartile = lowerQuartile[i];
25469     it->median = median[i];
25470     it->upperQuartile = upperQuartile[i];
25471     it->maximum = maximum[i];
25472     ++it;
25473     ++i;
25474   }
25475   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
25476 }
25477 
25478 /*! \overload
25479   
25480   Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
25481   and \a maximum to the current data.
25482   
25483   Alternatively, you can also access and modify the data directly via the \ref data method, which
25484   returns a pointer to the internal data container.
25485 */
25486 void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
25487 {
25488   mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
25489 }
25490 
25491 /*!
25492   \copydoc QCPPlottableInterface1D::selectTestRect
25493 */
25494 QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
25495 {
25496   QCPDataSelection result;
25497   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
25498     return result;
25499   if (!mKeyAxis || !mValueAxis)
25500     return result;
25501   
25502   QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
25503   getVisibleDataBounds(visibleBegin, visibleEnd);
25504   
25505   for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
25506   {
25507     if (rect.intersects(getQuartileBox(it)))
25508       result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
25509   }
25510   result.simplify();
25511   return result;
25512 }
25513 
25514 /*!
25515   Implements a selectTest specific to this plottable's point geometry.
25516 
25517   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
25518   point to \a pos.
25519   
25520   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
25521 */
25522 double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
25523 {
25524   Q_UNUSED(details)
25525   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
25526     return -1;
25527   if (!mKeyAxis || !mValueAxis)
25528     return -1;
25529   
25530   if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
25531   {
25532     // get visible data range:
25533     QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
25534     QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
25535     getVisibleDataBounds(visibleBegin, visibleEnd);
25536     double minDistSqr = (std::numeric_limits<double>::max)();
25537     for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
25538     {
25539       if (getQuartileBox(it).contains(pos)) // quartile box
25540       {
25541         double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
25542         if (currentDistSqr < minDistSqr)
25543         {
25544           minDistSqr = currentDistSqr;
25545           closestDataPoint = it;
25546         }
25547       } else // whiskers
25548       {
25549         const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
25550         const QCPVector2D posVec(pos);
25551         foreach (const QLineF &backbone, whiskerBackbones)
25552         {
25553           double currentDistSqr = posVec.distanceSquaredToLine(backbone);
25554           if (currentDistSqr < minDistSqr)
25555           {
25556             minDistSqr = currentDistSqr;
25557             closestDataPoint = it;
25558           }
25559         }
25560       }
25561     }
25562     if (details)
25563     {
25564       int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
25565       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
25566     }
25567     return qSqrt(minDistSqr);
25568   }
25569   return -1;
25570 }
25571 
25572 /* inherits documentation from base class */
25573 QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
25574 {
25575   QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
25576   // determine exact range by including width of bars/flags:
25577   if (foundRange)
25578   {
25579     if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
25580       range.lower -= mWidth*0.5;
25581     if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
25582       range.upper += mWidth*0.5;
25583   }
25584   return range;
25585 }
25586 
25587 /* inherits documentation from base class */
25588 QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
25589 {
25590   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
25591 }
25592 
25593 /* inherits documentation from base class */
25594 void QCPStatisticalBox::draw(QCPPainter *painter)
25595 {
25596   if (mDataContainer->isEmpty()) return;
25597   QCPAxis *keyAxis = mKeyAxis.data();
25598   QCPAxis *valueAxis = mValueAxis.data();
25599   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
25600   
25601   QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
25602   getVisibleDataBounds(visibleBegin, visibleEnd);
25603   
25604   // loop over and draw segments of unselected/selected data:
25605   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
25606   getDataSegments(selectedSegments, unselectedSegments);
25607   allSegments << unselectedSegments << selectedSegments;
25608   for (int i=0; i<allSegments.size(); ++i)
25609   {
25610     bool isSelectedSegment = i >= unselectedSegments.size();
25611     QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
25612     QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
25613     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
25614     if (begin == end)
25615       continue;
25616     
25617     for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
25618     {
25619       // check data validity if flag set:
25620 # ifdef QCUSTOMPLOT_CHECK_DATA
25621       if (QCP::isInvalidData(it->key, it->minimum) ||
25622           QCP::isInvalidData(it->lowerQuartile, it->median) ||
25623           QCP::isInvalidData(it->upperQuartile, it->maximum))
25624         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
25625       for (int i=0; i<it->outliers.size(); ++i)
25626         if (QCP::isInvalidData(it->outliers.at(i)))
25627           qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
25628 # endif
25629       
25630       if (isSelectedSegment && mSelectionDecorator)
25631       {
25632         mSelectionDecorator->applyPen(painter);
25633         mSelectionDecorator->applyBrush(painter);
25634       } else
25635       {
25636         painter->setPen(mPen);
25637         painter->setBrush(mBrush);
25638       }
25639       QCPScatterStyle finalOutlierStyle = mOutlierStyle;
25640       if (isSelectedSegment && mSelectionDecorator)
25641         finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
25642       drawStatisticalBox(painter, it, finalOutlierStyle);
25643     }
25644   }
25645   
25646   // draw other selection decoration that isn't just line/scatter pens and brushes:
25647   if (mSelectionDecorator)
25648     mSelectionDecorator->drawDecoration(painter, selection());
25649 }
25650 
25651 /* inherits documentation from base class */
25652 void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
25653 {
25654   // draw filled rect:
25655   applyDefaultAntialiasingHint(painter);
25656   painter->setPen(mPen);
25657   painter->setBrush(mBrush);
25658   QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
25659   r.moveCenter(rect.center());
25660   painter->drawRect(r);
25661 }
25662 
25663 /*!
25664   Draws the graphical representation of a single statistical box with the data given by the
25665   iterator \a it with the provided \a painter.
25666 
25667   If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
25668 
25669   \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
25670 */
25671 void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
25672 {
25673   // draw quartile box:
25674   applyDefaultAntialiasingHint(painter);
25675   const QRectF quartileBox = getQuartileBox(it);
25676   painter->drawRect(quartileBox);
25677   // draw median line with cliprect set to quartile box:
25678   painter->save();
25679   painter->setClipRect(quartileBox, Qt::IntersectClip);
25680   painter->setPen(mMedianPen);
25681   painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
25682   painter->restore();
25683   // draw whisker lines:
25684   applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
25685   painter->setPen(mWhiskerPen);
25686   painter->drawLines(getWhiskerBackboneLines(it));
25687   painter->setPen(mWhiskerBarPen);
25688   painter->drawLines(getWhiskerBarLines(it));
25689   // draw outliers:
25690   applyScattersAntialiasingHint(painter);
25691   outlierStyle.applyTo(painter, mPen);
25692   for (int i=0; i<it->outliers.size(); ++i)
25693     outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
25694 }
25695 
25696 /*!  \internal
25697   
25698   called by \ref draw to determine which data (key) range is visible at the current key axis range
25699   setting, so only that needs to be processed. It also takes into account the bar width.
25700   
25701   \a begin returns an iterator to the lowest data point that needs to be taken into account when
25702   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
25703   lower may still be just outside the visible range.
25704   
25705   \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
25706   may also lie just outside of the visible range.
25707   
25708   if the plottable contains no data, both \a begin and \a end point to constEnd.
25709 */
25710 void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
25711 {
25712   if (!mKeyAxis)
25713   {
25714     qDebug() << Q_FUNC_INFO << "invalid key axis";
25715     begin = mDataContainer->constEnd();
25716     end = mDataContainer->constEnd();
25717     return;
25718   }
25719   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
25720   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
25721 }
25722 
25723 /*!  \internal
25724 
25725   Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
25726   value range from the lower to the upper quartile, of the data given by \a it.
25727 
25728   \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
25729 */
25730 QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
25731 {
25732   QRectF result;
25733   result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
25734   result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
25735   return result;
25736 }
25737 
25738 /*!  \internal
25739 
25740   Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
25741   range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
25742   data given by \a it.
25743 
25744   \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
25745 */
25746 QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
25747 {
25748   QVector<QLineF> result(2);
25749   result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
25750   result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
25751   return result;
25752 }
25753 
25754 /*!  \internal
25755 
25756   Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
25757   end of the whisker backbones, at the minimum and maximum of the data given by \a it.
25758 
25759   \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
25760 */
25761 QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
25762 {
25763   QVector<QLineF> result(2);
25764   result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
25765   result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
25766   return result;
25767 }
25768 /* end of 'src/plottables/plottable-statisticalbox.cpp' */
25769 
25770 
25771 /* including file 'src/plottables/plottable-colormap.cpp' */
25772 /* modified 2021-03-29T02:30:44, size 48149               */
25773 
25774 ////////////////////////////////////////////////////////////////////////////////////////////////////
25775 //////////////////// QCPColorMapData
25776 ////////////////////////////////////////////////////////////////////////////////////////////////////
25777 
25778 /*! \class QCPColorMapData
25779   \brief Holds the two-dimensional data of a QCPColorMap plottable.
25780   
25781   This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
25782   QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
25783   color, depending on the value.
25784   
25785   The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
25786   Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
25787   setKeyRange, \ref setValueRange).
25788   
25789   The data cells can be accessed in two ways: They can be directly addressed by an integer index
25790   with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
25791   coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
25792   provided by the functions \ref coordToCell and \ref cellToCoord.
25793   
25794   A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
25795   allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
25796   fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
25797   the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
25798   
25799   This class also buffers the minimum and maximum values that are in the data set, to provide
25800   QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
25801   that is greater than the current maximum increases this maximum to the new value. However,
25802   setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
25803   maximum again, because finding the true new maximum would require going through the entire data
25804   array, which might be time consuming. The same holds for the data minimum. This functionality is
25805   given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
25806   true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
25807   parameter \a recalculateDataBounds which may be set to true to automatically call \ref
25808   recalculateDataBounds internally.
25809 */
25810 
25811 /* start of documentation of inline functions */
25812 
25813 /*! \fn bool QCPColorMapData::isEmpty() const
25814   
25815   Returns whether this instance carries no data. This is equivalent to having a size where at least
25816   one of the dimensions is 0 (see \ref setSize).
25817 */
25818 
25819 /* end of documentation of inline functions */
25820 
25821 /*!
25822   Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
25823   and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
25824   at the coordinates \a keyRange and \a valueRange.
25825   
25826   \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
25827 */
25828 QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
25829   mKeySize(0),
25830   mValueSize(0),
25831   mKeyRange(keyRange),
25832   mValueRange(valueRange),
25833   mIsEmpty(true),
25834   mData(nullptr),
25835   mAlpha(nullptr),
25836   mDataModified(true)
25837 {
25838   setSize(keySize, valueSize);
25839   fill(0);
25840 }
25841 
25842 QCPColorMapData::~QCPColorMapData()
25843 {
25844   delete[] mData;
25845   delete[] mAlpha;
25846 }
25847 
25848 /*!
25849   Constructs a new QCPColorMapData instance copying the data and range of \a other.
25850 */
25851 QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
25852   mKeySize(0),
25853   mValueSize(0),
25854   mIsEmpty(true),
25855   mData(nullptr),
25856   mAlpha(nullptr),
25857   mDataModified(true)
25858 {
25859   *this = other;
25860 }
25861 
25862 /*!
25863   Overwrites this color map data instance with the data stored in \a other. The alpha map state is
25864   transferred, too.
25865 */
25866 QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
25867 {
25868   if (&other != this)
25869   {
25870     const int keySize = other.keySize();
25871     const int valueSize = other.valueSize();
25872     if (!other.mAlpha && mAlpha)
25873       clearAlpha();
25874     setSize(keySize, valueSize);
25875     if (other.mAlpha && !mAlpha)
25876       createAlpha(false);
25877     setRange(other.keyRange(), other.valueRange());
25878     if (!isEmpty())
25879     {
25880       memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize));
25881       if (mAlpha)
25882         memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize));
25883     }
25884     mDataBounds = other.mDataBounds;
25885     mDataModified = true;
25886   }
25887   return *this;
25888 }
25889 
25890 /* undocumented getter */
25891 double QCPColorMapData::data(double key, double value)
25892 {
25893   int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
25894   int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
25895   if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
25896     return mData[valueCell*mKeySize + keyCell];
25897   else
25898     return 0;
25899 }
25900 
25901 /* undocumented getter */
25902 double QCPColorMapData::cell(int keyIndex, int valueIndex)
25903 {
25904   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
25905     return mData[valueIndex*mKeySize + keyIndex];
25906   else
25907     return 0;
25908 }
25909 
25910 /*!
25911   Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
25912 
25913   If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
25914   creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
25915 
25916   \see setAlpha
25917 */
25918 unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
25919 {
25920   if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
25921     return mAlpha[valueIndex*mKeySize + keyIndex];
25922   else
25923     return 255;
25924 }
25925 
25926 /*!
25927   Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
25928   the value dimension.
25929 
25930   The current data is discarded and the map cells are set to 0, unless the map had already the
25931   requested size.
25932   
25933   Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
25934   isEmpty returns true.
25935 
25936   \see setRange, setKeySize, setValueSize
25937 */
25938 void QCPColorMapData::setSize(int keySize, int valueSize)
25939 {
25940   if (keySize != mKeySize || valueSize != mValueSize)
25941   {
25942     mKeySize = keySize;
25943     mValueSize = valueSize;
25944     delete[] mData;
25945     mIsEmpty = mKeySize == 0 || mValueSize == 0;
25946     if (!mIsEmpty)
25947     {
25948 #ifdef __EXCEPTIONS
25949       try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
25950 #endif
25951       mData = new double[size_t(mKeySize*mValueSize)];
25952 #ifdef __EXCEPTIONS
25953       } catch (...) { mData = nullptr; }
25954 #endif
25955       if (mData)
25956         fill(0);
25957       else
25958         qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
25959     } else
25960       mData = nullptr;
25961     
25962     if (mAlpha) // if we had an alpha map, recreate it with new size
25963       createAlpha();
25964     
25965     mDataModified = true;
25966   }
25967 }
25968 
25969 /*!
25970   Resizes the data array to have \a keySize cells in the key dimension.
25971 
25972   The current data is discarded and the map cells are set to 0, unless the map had already the
25973   requested size.
25974   
25975   Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
25976 
25977   \see setKeyRange, setSize, setValueSize
25978 */
25979 void QCPColorMapData::setKeySize(int keySize)
25980 {
25981   setSize(keySize, mValueSize);
25982 }
25983 
25984 /*!
25985   Resizes the data array to have \a valueSize cells in the value dimension.
25986 
25987   The current data is discarded and the map cells are set to 0, unless the map had already the
25988   requested size.
25989   
25990   Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
25991 
25992   \see setValueRange, setSize, setKeySize
25993 */
25994 void QCPColorMapData::setValueSize(int valueSize)
25995 {
25996   setSize(mKeySize, valueSize);
25997 }
25998 
25999 /*!
26000   Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
26001   covered by the color map in plot coordinates.
26002   
26003   The outer cells will be centered on the range boundaries given to this function. For example, if
26004   the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
26005   be cells centered on the key coordinates 2, 2.5 and 3.
26006  
26007   \see setSize
26008 */
26009 void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
26010 {
26011   setKeyRange(keyRange);
26012   setValueRange(valueRange);
26013 }
26014 
26015 /*!
26016   Sets the coordinate range the data shall be distributed over in the key dimension. Together with
26017   the value range, This defines the rectangular area covered by the color map in plot coordinates.
26018   
26019   The outer cells will be centered on the range boundaries given to this function. For example, if
26020   the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
26021   be cells centered on the key coordinates 2, 2.5 and 3.
26022  
26023   \see setRange, setValueRange, setSize
26024 */
26025 void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
26026 {
26027   mKeyRange = keyRange;
26028 }
26029 
26030 /*!
26031   Sets the coordinate range the data shall be distributed over in the value dimension. Together with
26032   the key range, This defines the rectangular area covered by the color map in plot coordinates.
26033   
26034   The outer cells will be centered on the range boundaries given to this function. For example, if
26035   the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
26036   will be cells centered on the value coordinates 2, 2.5 and 3.
26037  
26038   \see setRange, setKeyRange, setSize
26039 */
26040 void QCPColorMapData::setValueRange(const QCPRange &valueRange)
26041 {
26042   mValueRange = valueRange;
26043 }
26044 
26045 /*!
26046   Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
26047   z.
26048   
26049   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
26050   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
26051   you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
26052   determine the cell index. Rather directly access the cell index with \ref
26053   QCPColorMapData::setCell.
26054  
26055   \see setCell, setRange
26056 */
26057 void QCPColorMapData::setData(double key, double value, double z)
26058 {
26059   int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
26060   int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
26061   if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
26062   {
26063     mData[valueCell*mKeySize + keyCell] = z;
26064     if (z < mDataBounds.lower)
26065       mDataBounds.lower = z;
26066     if (z > mDataBounds.upper)
26067       mDataBounds.upper = z;
26068      mDataModified = true;
26069   }
26070 }
26071 
26072 /*!
26073   Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
26074   enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
26075   \ref setSize).
26076   
26077   In the standard plot configuration (horizontal key axis and vertical value axis, both not
26078   range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
26079   indices (keySize-1, valueSize-1) is in the top right corner of the color map.
26080   
26081   \see setData, setSize
26082 */
26083 void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
26084 {
26085   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
26086   {
26087     mData[valueIndex*mKeySize + keyIndex] = z;
26088     if (z < mDataBounds.lower)
26089       mDataBounds.lower = z;
26090     if (z > mDataBounds.upper)
26091       mDataBounds.upper = z;
26092      mDataModified = true;
26093   } else
26094     qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
26095 }
26096 
26097 /*!
26098   Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
26099   of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
26100   opaque cell.
26101 
26102   If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
26103   to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
26104 
26105   Note that the cell-wise alpha which can be configured here is independent of any alpha configured
26106   in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
26107   and gradient alpha, the alpha values will be blended accordingly during rendering of the color
26108   map.
26109 
26110   \see fillAlpha, clearAlpha
26111 */
26112 void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
26113 {
26114   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
26115   {
26116     if (mAlpha || createAlpha())
26117     {
26118       mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
26119       mDataModified = true;
26120     }
26121   } else
26122     qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
26123 }
26124 
26125 /*!
26126   Goes through the data and updates the buffered minimum and maximum data values.
26127   
26128   Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
26129   and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
26130   with a smaller or larger value respectively, since the buffered maximum/minimum values have been
26131   updated the last time. Why this is the case is explained in the class description (\ref
26132   QCPColorMapData).
26133   
26134   Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
26135   recalculateDataBounds for convenience. Setting this to true will call this method for you, before
26136   doing the rescale.
26137 */
26138 void QCPColorMapData::recalculateDataBounds()
26139 {
26140   if (mKeySize > 0 && mValueSize > 0)
26141   {
26142     double minHeight = mData[0];
26143     double maxHeight = mData[0];
26144     const int dataCount = mValueSize*mKeySize;
26145     for (int i=0; i<dataCount; ++i)
26146     {
26147       if (mData[i] > maxHeight)
26148         maxHeight = mData[i];
26149       if (mData[i] < minHeight)
26150         minHeight = mData[i];
26151     }
26152     mDataBounds.lower = minHeight;
26153     mDataBounds.upper = maxHeight;
26154   }
26155 }
26156 
26157 /*!
26158   Frees the internal data memory.
26159   
26160   This is equivalent to calling \ref setSize "setSize(0, 0)".
26161 */
26162 void QCPColorMapData::clear()
26163 {
26164   setSize(0, 0);
26165 }
26166 
26167 /*!
26168   Frees the internal alpha map. The color map will have full opacity again.
26169 */
26170 void QCPColorMapData::clearAlpha()
26171 {
26172   if (mAlpha)
26173   {
26174     delete[] mAlpha;
26175     mAlpha = nullptr;
26176     mDataModified = true;
26177   }
26178 }
26179 
26180 /*!
26181   Sets all cells to the value \a z.
26182 */
26183 void QCPColorMapData::fill(double z)
26184 {
26185   const int dataCount = mValueSize*mKeySize;
26186   for (int i=0; i<dataCount; ++i)
26187     mData[i] = z;
26188   mDataBounds = QCPRange(z, z);
26189   mDataModified = true;
26190 }
26191 
26192 /*!
26193   Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
26194   transparent color map, and a value of 255 results in a fully opaque color map.
26195 
26196   If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
26197   \ref clearAlpha.
26198 
26199   \see setAlpha
26200 */
26201 void QCPColorMapData::fillAlpha(unsigned char alpha)
26202 {
26203   if (mAlpha || createAlpha(false))
26204   {
26205     const int dataCount = mValueSize*mKeySize;
26206     for (int i=0; i<dataCount; ++i)
26207       mAlpha[i] = alpha;
26208     mDataModified = true;
26209   }
26210 }
26211 
26212 /*!
26213   Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
26214   instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
26215   valueIndex.
26216   
26217   The retrieved key/value cell indices can then be used for example with \ref setCell.
26218   
26219   If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
26220   \a keyIndex.
26221   
26222   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
26223   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
26224   you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
26225   determine the cell index.
26226   
26227   \see cellToCoord, QCPAxis::coordToPixel
26228 */
26229 void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
26230 {
26231   if (keyIndex)
26232     *keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
26233   if (valueIndex)
26234     *valueIndex = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
26235 }
26236 
26237 /*!
26238   Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
26239   instance. The resulting coordinates are returned via the output parameters \a key and \a
26240   value.
26241   
26242   If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
26243   value.
26244   
26245   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
26246   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
26247   you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
26248   determine the cell index.
26249   
26250   \see coordToCell, QCPAxis::pixelToCoord
26251 */
26252 void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
26253 {
26254   if (key)
26255     *key = keyIndex/double(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
26256   if (value)
26257     *value = valueIndex/double(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
26258 }
26259 
26260 /*! \internal
26261 
26262   Allocates the internal alpha map with the current data map key/value size and, if \a
26263   initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
26264   values are not initialized at all. In this case, the alpha map should be initialized manually,
26265   e.g. with \ref fillAlpha.
26266 
26267   If an alpha map exists already, it is deleted first. If this color map is empty (has either key
26268   or value size zero, see \ref isEmpty), the alpha map is cleared.
26269 
26270   The return value indicates the existence of the alpha map after the call. So this method returns
26271   true if the data map isn't empty and an alpha map was successfully allocated.
26272 */
26273 bool QCPColorMapData::createAlpha(bool initializeOpaque)
26274 {
26275   clearAlpha();
26276   if (isEmpty())
26277     return false;
26278   
26279 #ifdef __EXCEPTIONS
26280   try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
26281 #endif
26282     mAlpha = new unsigned char[size_t(mKeySize*mValueSize)];
26283 #ifdef __EXCEPTIONS
26284   } catch (...) { mAlpha = nullptr; }
26285 #endif
26286   if (mAlpha)
26287   {
26288     if (initializeOpaque)
26289       fillAlpha(255);
26290     return true;
26291   } else
26292   {
26293     qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
26294     return false;
26295   }
26296 }
26297 
26298 
26299 ////////////////////////////////////////////////////////////////////////////////////////////////////
26300 //////////////////// QCPColorMap
26301 ////////////////////////////////////////////////////////////////////////////////////////////////////
26302 
26303 /*! \class QCPColorMap
26304   \brief A plottable representing a two-dimensional color map in a plot.
26305 
26306   \image html QCPColorMap.png
26307   
26308   The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
26309   method.
26310   
26311   A color map has three dimensions to represent a data point: The \a key dimension, the \a value
26312   dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
26313   correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
26314   constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
26315   value).
26316 
26317   Set the number of points (or \a cells) in the key/value dimension via \ref
26318   QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
26319   specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
26320   boundary and the last cell will be centered on the upper range boundary. The data can be set by
26321   either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
26322   their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
26323   setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
26324   better.
26325   
26326   The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
26327   key and value axes.
26328   
26329   To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
26330   typically placed to the right of the axis rect. See the documentation there for details on how to
26331   add and use a color scale.
26332   
26333   \section qcpcolormap-appearance Changing the appearance
26334   
26335   Most important to the appearance is the color gradient, which can be specified via \ref
26336   setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
26337   gradient.
26338   
26339   The \a data range that is mapped to the colors of the gradient can be specified with \ref
26340   setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
26341   rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
26342   to define how they are displayed.
26343   
26344   \section qcpcolormap-transparency Transparency
26345   
26346   Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
26347   values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
26348   cause the color map data which gets mapped to colors around those color stops to appear with the
26349   accordingly interpolated transparency.
26350   
26351   On the other hand you can also directly apply an alpha value to each cell independent of its
26352   data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
26353   QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
26354   
26355   The two transparencies will be joined together in the plot and otherwise not interfere with each
26356   other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
26357   simultaneously, will result in a total transparency of 25% (64/255).
26358   
26359   \section qcpcolormap-usage Usage
26360   
26361   Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
26362   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
26363   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
26364   
26365   Usually, you first create an instance:
26366   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
26367   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
26368   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
26369   The newly created plottable can be modified, e.g.:
26370   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
26371   
26372   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
26373   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
26374   you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
26375   determine the cell index. Rather directly access the cell index with \ref
26376   QCPColorMapData::setCell.
26377 */
26378 
26379 /* start documentation of inline functions */
26380 
26381 /*! \fn QCPColorMapData *QCPColorMap::data() const
26382   
26383   Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
26384   modify data points (cells) and the color map key/value range.
26385   
26386   \see setData
26387 */
26388 
26389 /* end documentation of inline functions */
26390 
26391 /* start documentation of signals */
26392 
26393 /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
26394   
26395   This signal is emitted when the data range changes.
26396   
26397   \see setDataRange
26398 */
26399 
26400 /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
26401   
26402   This signal is emitted when the data scale type changes.
26403   
26404   \see setDataScaleType
26405 */
26406 
26407 /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
26408   
26409   This signal is emitted when the gradient changes.
26410   
26411   \see setGradient
26412 */
26413 
26414 /* end documentation of signals */
26415 
26416 /*!
26417   Constructs a color map with the specified \a keyAxis and \a valueAxis.
26418   
26419   The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
26420   \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
26421   manually but use QCustomPlot::removePlottable() instead.
26422 */
26423 QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
26424   QCPAbstractPlottable(keyAxis, valueAxis),
26425   mDataScaleType(QCPAxis::stLinear),
26426   mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
26427   mGradient(QCPColorGradient::gpCold),
26428   mInterpolate(true),
26429   mTightBoundary(false),
26430   mMapImageInvalidated(true)
26431 {
26432 }
26433 
26434 QCPColorMap::~QCPColorMap()
26435 {
26436   delete mMapData;
26437 }
26438 
26439 /*!
26440   Replaces the current \ref data with the provided \a data.
26441   
26442   If \a copy is set to true, the \a data object will only be copied. if false, the color map
26443   takes ownership of the passed data and replaces the internal data pointer with it. This is
26444   significantly faster than copying for large datasets.
26445 */
26446 void QCPColorMap::setData(QCPColorMapData *data, bool copy)
26447 {
26448   if (mMapData == data)
26449   {
26450     qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
26451     return;
26452   }
26453   if (copy)
26454   {
26455     *mMapData = *data;
26456   } else
26457   {
26458     delete mMapData;
26459     mMapData = data;
26460   }
26461   mMapImageInvalidated = true;
26462 }
26463 
26464 /*!
26465   Sets the data range of this color map to \a dataRange. The data range defines which data values
26466   are mapped to the color gradient.
26467   
26468   To make the data range span the full range of the data set, use \ref rescaleDataRange.
26469   
26470   \see QCPColorScale::setDataRange
26471 */
26472 void QCPColorMap::setDataRange(const QCPRange &dataRange)
26473 {
26474   if (!QCPRange::validRange(dataRange)) return;
26475   if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
26476   {
26477     if (mDataScaleType == QCPAxis::stLogarithmic)
26478       mDataRange = dataRange.sanitizedForLogScale();
26479     else
26480       mDataRange = dataRange.sanitizedForLinScale();
26481     mMapImageInvalidated = true;
26482     emit dataRangeChanged(mDataRange);
26483   }
26484 }
26485 
26486 /*!
26487   Sets whether the data is correlated with the color gradient linearly or logarithmically.
26488   
26489   \see QCPColorScale::setDataScaleType
26490 */
26491 void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
26492 {
26493   if (mDataScaleType != scaleType)
26494   {
26495     mDataScaleType = scaleType;
26496     mMapImageInvalidated = true;
26497     emit dataScaleTypeChanged(mDataScaleType);
26498     if (mDataScaleType == QCPAxis::stLogarithmic)
26499       setDataRange(mDataRange.sanitizedForLogScale());
26500   }
26501 }
26502 
26503 /*!
26504   Sets the color gradient that is used to represent the data. For more details on how to create an
26505   own gradient or use one of the preset gradients, see \ref QCPColorGradient.
26506   
26507   The colors defined by the gradient will be used to represent data values in the currently set
26508   data range, see \ref setDataRange. Data points that are outside this data range will either be
26509   colored uniformly with the respective gradient boundary color, or the gradient will repeat,
26510   depending on \ref QCPColorGradient::setPeriodic.
26511   
26512   \see QCPColorScale::setGradient
26513 */
26514 void QCPColorMap::setGradient(const QCPColorGradient &gradient)
26515 {
26516   if (mGradient != gradient)
26517   {
26518     mGradient = gradient;
26519     mMapImageInvalidated = true;
26520     emit gradientChanged(mGradient);
26521   }
26522 }
26523 
26524 /*!
26525   Sets whether the color map image shall use bicubic interpolation when displaying the color map
26526   shrinked or expanded, and not at a 1:1 pixel-to-data scale.
26527   
26528   \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
26529 */
26530 void QCPColorMap::setInterpolate(bool enabled)
26531 {
26532   mInterpolate = enabled;
26533   mMapImageInvalidated = true; // because oversampling factors might need to change
26534 }
26535 
26536 /*!
26537   Sets whether the outer most data rows and columns are clipped to the specified key and value
26538   range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
26539   
26540   if \a enabled is set to false, the data points at the border of the color map are drawn with the
26541   same width and height as all other data points. Since the data points are represented by
26542   rectangles of one color centered on the data coordinate, this means that the shown color map
26543   extends by half a data point over the specified key/value range in each direction.
26544   
26545   \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
26546 */
26547 void QCPColorMap::setTightBoundary(bool enabled)
26548 {
26549   mTightBoundary = enabled;
26550 }
26551 
26552 /*!
26553   Associates the color scale \a colorScale with this color map.
26554   
26555   This means that both the color scale and the color map synchronize their gradient, data range and
26556   data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
26557   can be associated with one single color scale. This causes the color maps to also synchronize
26558   those properties, via the mutual color scale.
26559   
26560   This function causes the color map to adopt the current color gradient, data range and data scale
26561   type of \a colorScale. After this call, you may change these properties at either the color map
26562   or the color scale, and the setting will be applied to both.
26563   
26564   Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
26565 */
26566 void QCPColorMap::setColorScale(QCPColorScale *colorScale)
26567 {
26568   if (mColorScale) // unconnect signals from old color scale
26569   {
26570     disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
26571     disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
26572     disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
26573     disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
26574     disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
26575     disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
26576   }
26577   mColorScale = colorScale;
26578   if (mColorScale) // connect signals to new color scale
26579   {
26580     setGradient(mColorScale.data()->gradient());
26581     setDataRange(mColorScale.data()->dataRange());
26582     setDataScaleType(mColorScale.data()->dataScaleType());
26583     connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
26584     connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
26585     connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
26586     connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
26587     connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
26588     connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
26589   }
26590 }
26591 
26592 /*!
26593   Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
26594   current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
26595   only for the third data dimension of the color map.
26596   
26597   The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
26598   instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
26599   QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
26600   performance reasons, however, they are only updated in an expanding fashion. So the buffered
26601   maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
26602   the data that actually lower the maximum of the data set (by overwriting the cell holding the
26603   current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
26604   the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
26605   true minimum and maximum by explicitly looking at each cell, the method
26606   QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
26607   recalculateDataBounds calls this method before setting the data range to the buffered minimum and
26608   maximum.
26609   
26610   \see setDataRange
26611 */
26612 void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
26613 {
26614   if (recalculateDataBounds)
26615     mMapData->recalculateDataBounds();
26616   setDataRange(mMapData->dataBounds());
26617 }
26618 
26619 /*!
26620   Takes the current appearance of the color map and updates the legend icon, which is used to
26621   represent this color map in the legend (see \ref QCPLegend).
26622   
26623   The \a transformMode specifies whether the rescaling is done by a faster, low quality image
26624   scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
26625   (Qt::SmoothTransformation).
26626   
26627   The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
26628   the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
26629   legend icon size, the thumb will be rescaled during drawing of the legend item.
26630   
26631   \see setDataRange
26632 */
26633 void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
26634 {
26635   if (mMapImage.isNull() && !data()->isEmpty())
26636     updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
26637   
26638   if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
26639   {
26640     bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
26641     bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
26642     mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
26643   }
26644 }
26645 
26646 /* inherits documentation from base class */
26647 double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
26648 {
26649   Q_UNUSED(details)
26650   if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
26651     return -1;
26652   if (!mKeyAxis || !mValueAxis)
26653     return -1;
26654   
26655   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
26656   {
26657     double posKey, posValue;
26658     pixelsToCoords(pos, posKey, posValue);
26659     if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
26660     {
26661       if (details)
26662         details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
26663       return mParentPlot->selectionTolerance()*0.99;
26664     }
26665   }
26666   return -1;
26667 }
26668 
26669 /* inherits documentation from base class */
26670 QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
26671 {
26672   foundRange = true;
26673   QCPRange result = mMapData->keyRange();
26674   result.normalize();
26675   if (inSignDomain == QCP::sdPositive)
26676   {
26677     if (result.lower <= 0 && result.upper > 0)
26678       result.lower = result.upper*1e-3;
26679     else if (result.lower <= 0 && result.upper <= 0)
26680       foundRange = false;
26681   } else if (inSignDomain == QCP::sdNegative)
26682   {
26683     if (result.upper >= 0 && result.lower < 0)
26684       result.upper = result.lower*1e-3;
26685     else if (result.upper >= 0 && result.lower >= 0)
26686       foundRange = false;
26687   }
26688   return result;
26689 }
26690 
26691 /* inherits documentation from base class */
26692 QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
26693 {
26694   if (inKeyRange != QCPRange())
26695   {
26696     if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
26697     {
26698       foundRange = false;
26699       return {};
26700     }
26701   }
26702   
26703   foundRange = true;
26704   QCPRange result = mMapData->valueRange();
26705   result.normalize();
26706   if (inSignDomain == QCP::sdPositive)
26707   {
26708     if (result.lower <= 0 && result.upper > 0)
26709       result.lower = result.upper*1e-3;
26710     else if (result.lower <= 0 && result.upper <= 0)
26711       foundRange = false;
26712   } else if (inSignDomain == QCP::sdNegative)
26713   {
26714     if (result.upper >= 0 && result.lower < 0)
26715       result.upper = result.lower*1e-3;
26716     else if (result.upper >= 0 && result.lower >= 0)
26717       foundRange = false;
26718   }
26719   return result;
26720 }
26721 
26722 /*! \internal
26723   
26724   Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
26725   turning the data values into color pixels with \ref QCPColorGradient::colorize.
26726   
26727   This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
26728   has been invalidated for a different reason (e.g. a change of the data range with \ref
26729   setDataRange).
26730   
26731   If the map cell count is low, the image created will be oversampled in order to avoid a
26732   QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
26733   without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
26734   setInterpolate is true.
26735 */
26736 void QCPColorMap::updateMapImage()
26737 {
26738   QCPAxis *keyAxis = mKeyAxis.data();
26739   if (!keyAxis) return;
26740   if (mMapData->isEmpty()) return;
26741   
26742   const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
26743   const int keySize = mMapData->keySize();
26744   const int valueSize = mMapData->valueSize();
26745   int keyOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(keySize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
26746   int valueOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
26747   
26748   // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
26749   if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
26750     mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
26751   else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
26752     mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
26753   
26754   if (mMapImage.isNull())
26755   {
26756     qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
26757     mMapImage = QImage(QSize(10, 10), format);
26758     mMapImage.fill(Qt::black);
26759   } else
26760   {
26761     QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
26762     if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
26763     {
26764       // resize undersampled map image to actual key/value cell sizes:
26765       if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
26766         mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
26767       else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
26768         mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
26769       localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
26770     } else if (!mUndersampledMapImage.isNull())
26771       mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
26772     
26773     const double *rawData = mMapData->mData;
26774     const unsigned char *rawAlpha = mMapData->mAlpha;
26775     if (keyAxis->orientation() == Qt::Horizontal)
26776     {
26777       const int lineCount = valueSize;
26778       const int rowCount = keySize;
26779       for (int line=0; line<lineCount; ++line)
26780       {
26781         QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
26782         if (rawAlpha)
26783           mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
26784         else
26785           mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
26786       }
26787     } else // keyAxis->orientation() == Qt::Vertical
26788     {
26789       const int lineCount = keySize;
26790       const int rowCount = valueSize;
26791       for (int line=0; line<lineCount; ++line)
26792       {
26793         QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
26794         if (rawAlpha)
26795           mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
26796         else
26797           mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
26798       }
26799     }
26800     
26801     if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
26802     {
26803       if (keyAxis->orientation() == Qt::Horizontal)
26804         mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
26805       else
26806         mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
26807     }
26808   }
26809   mMapData->mDataModified = false;
26810   mMapImageInvalidated = false;
26811 }
26812 
26813 /* inherits documentation from base class */
26814 void QCPColorMap::draw(QCPPainter *painter)
26815 {
26816   if (mMapData->isEmpty()) return;
26817   if (!mKeyAxis || !mValueAxis) return;
26818   applyDefaultAntialiasingHint(painter);
26819   
26820   if (mMapData->mDataModified || mMapImageInvalidated)
26821     updateMapImage();
26822   
26823   // use buffer if painting vectorized (PDF):
26824   const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
26825   QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
26826   QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
26827   QPixmap mapBuffer;
26828   if (useBuffer)
26829   {
26830     const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
26831     mapBufferTarget = painter->clipRegion().boundingRect();
26832     mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
26833     mapBuffer.fill(Qt::transparent);
26834     localPainter = new QCPPainter(&mapBuffer);
26835     localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
26836     localPainter->translate(-mapBufferTarget.topLeft());
26837   }
26838   
26839   QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
26840                             coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
26841   // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
26842   double halfCellWidth = 0; // in pixels
26843   double halfCellHeight = 0; // in pixels
26844   if (keyAxis()->orientation() == Qt::Horizontal)
26845   {
26846     if (mMapData->keySize() > 1)
26847       halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1);
26848     if (mMapData->valueSize() > 1)
26849       halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1);
26850   } else // keyAxis orientation is Qt::Vertical
26851   {
26852     if (mMapData->keySize() > 1)
26853       halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1);
26854     if (mMapData->valueSize() > 1)
26855       halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1);
26856   }
26857   imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
26858   const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
26859   const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
26860   const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
26861   localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
26862   QRegion clipBackup;
26863   if (mTightBoundary)
26864   {
26865     clipBackup = localPainter->clipRegion();
26866     QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
26867                                   coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
26868     localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
26869   }
26870   localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
26871   if (mTightBoundary)
26872     localPainter->setClipRegion(clipBackup);
26873   localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
26874   
26875   if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
26876   {
26877     delete localPainter;
26878     painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
26879   }
26880 }
26881 
26882 /* inherits documentation from base class */
26883 void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
26884 {
26885   applyDefaultAntialiasingHint(painter);
26886   // draw map thumbnail:
26887   if (!mLegendIcon.isNull())
26888   {
26889     QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
26890     QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
26891     iconRect.moveCenter(rect.center());
26892     painter->drawPixmap(iconRect.topLeft(), scaledIcon);
26893   }
26894   /*
26895   // draw frame:
26896   painter->setBrush(Qt::NoBrush);
26897   painter->setPen(Qt::black);
26898   painter->drawRect(rect.adjusted(1, 1, 0, 0));
26899   */
26900 }
26901 /* end of 'src/plottables/plottable-colormap.cpp' */
26902 
26903 
26904 /* including file 'src/plottables/plottable-financial.cpp' */
26905 /* modified 2021-03-29T02:30:44, size 42914                */
26906 
26907 ////////////////////////////////////////////////////////////////////////////////////////////////////
26908 //////////////////// QCPFinancialData
26909 ////////////////////////////////////////////////////////////////////////////////////////////////////
26910 
26911 /*! \class QCPFinancialData
26912   \brief Holds the data of one single data point for QCPFinancial.
26913   
26914   The stored data is:
26915   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
26916   \li \a open: The opening value at the data point (this is the \a mainValue)
26917   \li \a high: The high/maximum value at the data point
26918   \li \a low: The low/minimum value at the data point
26919   \li \a close: The closing value at the data point
26920   
26921   The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
26922   for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
26923   documentation there for an explanation regarding the data type's generic methods.
26924   
26925   \see QCPFinancialDataContainer
26926 */
26927 
26928 /* start documentation of inline functions */
26929 
26930 /*! \fn double QCPFinancialData::sortKey() const
26931   
26932   Returns the \a key member of this data point.
26933   
26934   For a general explanation of what this method is good for in the context of the data container,
26935   see the documentation of \ref QCPDataContainer.
26936 */
26937 
26938 /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
26939   
26940   Returns a data point with the specified \a sortKey. All other members are set to zero.
26941   
26942   For a general explanation of what this method is good for in the context of the data container,
26943   see the documentation of \ref QCPDataContainer.
26944 */
26945 
26946 /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
26947   
26948   Since the member \a key is both the data point key coordinate and the data ordering parameter,
26949   this method returns true.
26950   
26951   For a general explanation of what this method is good for in the context of the data container,
26952   see the documentation of \ref QCPDataContainer.
26953 */
26954 
26955 /*! \fn double QCPFinancialData::mainKey() const
26956   
26957   Returns the \a key member of this data point.
26958   
26959   For a general explanation of what this method is good for in the context of the data container,
26960   see the documentation of \ref QCPDataContainer.
26961 */
26962 
26963 /*! \fn double QCPFinancialData::mainValue() const
26964   
26965   Returns the \a open member of this data point.
26966   
26967   For a general explanation of what this method is good for in the context of the data container,
26968   see the documentation of \ref QCPDataContainer.
26969 */
26970 
26971 /*! \fn QCPRange QCPFinancialData::valueRange() const
26972   
26973   Returns a QCPRange spanning from the \a low to the \a high value of this data point.
26974   
26975   For a general explanation of what this method is good for in the context of the data container,
26976   see the documentation of \ref QCPDataContainer.
26977 */
26978 
26979 /* end documentation of inline functions */
26980 
26981 /*!
26982   Constructs a data point with key and all values set to zero.
26983 */
26984 QCPFinancialData::QCPFinancialData() :
26985   key(0),
26986   open(0),
26987   high(0),
26988   low(0),
26989   close(0)
26990 {
26991 }
26992 
26993 /*!
26994   Constructs a data point with the specified \a key and OHLC values.
26995 */
26996 QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
26997   key(key),
26998   open(open),
26999   high(high),
27000   low(low),
27001   close(close)
27002 {
27003 }
27004 
27005 
27006 ////////////////////////////////////////////////////////////////////////////////////////////////////
27007 //////////////////// QCPFinancial
27008 ////////////////////////////////////////////////////////////////////////////////////////////////////
27009 
27010 /*! \class QCPFinancial
27011   \brief A plottable representing a financial stock chart
27012 
27013   \image html QCPFinancial.png
27014 
27015   This plottable represents time series data binned to certain intervals, mainly used for stock
27016   charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
27017   set via \ref setChartStyle.
27018 
27019   The data is passed via \ref setData as a set of open/high/low/close values at certain keys
27020   (typically times). This means the data must be already binned appropriately. If data is only
27021   available as a series of values (e.g. \a price against \a time), you can use the static
27022   convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
27023   to \ref setData.
27024 
27025   The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
27026   setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
27027   the width to (or slightly less than) one time bin interval width.
27028 
27029   \section qcpfinancial-appearance Changing the appearance
27030 
27031   Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
27032   lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
27033 
27034   If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
27035   represented with a different pen and brush than negative changes (\a close < \a open). These can
27036   be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
27037   setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
27038   however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
27039   irrespective of whether the chart is single- or two-colored.
27040 
27041   \section qcpfinancial-usage Usage
27042 
27043   Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
27044   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
27045   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
27046 
27047   Usually, you first create an instance:
27048 
27049   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
27050   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
27051   instance takes ownership of the plottable, so do not delete it manually but use
27052   QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
27053 
27054   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
27055   Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
27056   series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
27057 */
27058 
27059 /* start of documentation of inline functions */
27060 
27061 /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
27062   
27063   Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
27064   use it to directly manipulate the data, which may be more convenient and faster than using the
27065   regular \ref setData or \ref addData methods, in certain situations.
27066 */
27067 
27068 /* end of documentation of inline functions */
27069 
27070 /*!
27071   Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
27072   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
27073   the same orientation. If either of these restrictions is violated, a corresponding message is
27074   printed to the debug output (qDebug), the construction is not aborted, though.
27075   
27076   The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
27077   keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
27078   but use QCustomPlot::removePlottable() instead.
27079 */
27080 QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
27081   QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
27082   mChartStyle(csCandlestick),
27083   mWidth(0.5),
27084   mWidthType(wtPlotCoords),
27085   mTwoColored(true),
27086   mBrushPositive(QBrush(QColor(50, 160, 0))),
27087   mBrushNegative(QBrush(QColor(180, 0, 15))),
27088   mPenPositive(QPen(QColor(40, 150, 0))),
27089   mPenNegative(QPen(QColor(170, 5, 5)))
27090 {
27091   mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
27092 }
27093 
27094 QCPFinancial::~QCPFinancial()
27095 {
27096 }
27097 
27098 /*! \overload
27099   
27100   Replaces the current data container with the provided \a data container.
27101   
27102   Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
27103   Modifying the data in the container will then affect all financials that share the container.
27104   Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
27105   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
27106   
27107   If you do not wish to share containers, but create a copy from an existing container, rather use
27108   the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
27109   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
27110   
27111   \see addData, timeSeriesToOhlc
27112 */
27113 void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
27114 {
27115   mDataContainer = data;
27116 }
27117 
27118 /*! \overload
27119   
27120   Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
27121   close. The provided vectors should have equal length. Else, the number of added points will be
27122   the size of the smallest vector.
27123   
27124   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
27125   can set \a alreadySorted to true, to improve performance by saving a sorting run.
27126   
27127   \see addData, timeSeriesToOhlc
27128 */
27129 void QCPFinancial::setData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
27130 {
27131   mDataContainer->clear();
27132   addData(keys, open, high, low, close, alreadySorted);
27133 }
27134 
27135 /*!
27136   Sets which representation style shall be used to display the OHLC data.
27137 */
27138 void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
27139 {
27140   mChartStyle = style;
27141 }
27142 
27143 /*!
27144   Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
27145   
27146   A typical choice is to set it to (or slightly less than) one bin interval width.
27147 */
27148 void QCPFinancial::setWidth(double width)
27149 {
27150   mWidth = width;
27151 }
27152 
27153 /*!
27154   Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
27155   an explanation of the possible values for \a widthType.
27156 
27157   The default value is \ref wtPlotCoords.
27158 
27159   \see setWidth
27160 */
27161 void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
27162 {
27163   mWidthType = widthType;
27164 }
27165 
27166 /*!
27167   Sets whether this chart shall contrast positive from negative trends per data point by using two
27168   separate colors to draw the respective bars/candlesticks.
27169   
27170   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
27171   setBrush).
27172   
27173   \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
27174 */
27175 void QCPFinancial::setTwoColored(bool twoColored)
27176 {
27177   mTwoColored = twoColored;
27178 }
27179 
27180 /*!
27181   If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
27182   of data points with a positive trend (i.e. bars/candlesticks with close >= open).
27183   
27184   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
27185   setBrush).
27186   
27187   \see setBrushNegative, setPenPositive, setPenNegative
27188 */
27189 void QCPFinancial::setBrushPositive(const QBrush &brush)
27190 {
27191   mBrushPositive = brush;
27192 }
27193 
27194 /*!
27195   If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
27196   of data points with a negative trend (i.e. bars/candlesticks with close < open).
27197   
27198   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
27199   setBrush).
27200   
27201   \see setBrushPositive, setPenNegative, setPenPositive
27202 */
27203 void QCPFinancial::setBrushNegative(const QBrush &brush)
27204 {
27205   mBrushNegative = brush;
27206 }
27207 
27208 /*!
27209   If \ref setTwoColored is set to true, this function controls the pen that is used to draw
27210   outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
27211   
27212   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
27213   setBrush).
27214   
27215   \see setPenNegative, setBrushPositive, setBrushNegative
27216 */
27217 void QCPFinancial::setPenPositive(const QPen &pen)
27218 {
27219   mPenPositive = pen;
27220 }
27221 
27222 /*!
27223   If \ref setTwoColored is set to true, this function controls the pen that is used to draw
27224   outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
27225   
27226   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
27227   setBrush).
27228   
27229   \see setPenPositive, setBrushNegative, setBrushPositive
27230 */
27231 void QCPFinancial::setPenNegative(const QPen &pen)
27232 {
27233   mPenNegative = pen;
27234 }
27235 
27236 /*! \overload
27237   
27238   Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
27239   The provided vectors should have equal length. Else, the number of added points will be the size
27240   of the smallest vector.
27241   
27242   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
27243   can set \a alreadySorted to true, to improve performance by saving a sorting run.
27244   
27245   Alternatively, you can also access and modify the data directly via the \ref data method, which
27246   returns a pointer to the internal data container.
27247   
27248   \see timeSeriesToOhlc
27249 */
27250 void QCPFinancial::addData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
27251 {
27252   if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
27253     qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
27254   const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
27255   QVector<QCPFinancialData> tempData(n);
27256   QVector<QCPFinancialData>::iterator it = tempData.begin();
27257   const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
27258   int i = 0;
27259   while (it != itEnd)
27260   {
27261     it->key = keys[i];
27262     it->open = open[i];
27263     it->high = high[i];
27264     it->low = low[i];
27265     it->close = close[i];
27266     ++it;
27267     ++i;
27268   }
27269   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
27270 }
27271 
27272 /*! \overload
27273   
27274   Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
27275   data.
27276   
27277   Alternatively, you can also access and modify the data directly via the \ref data method, which
27278   returns a pointer to the internal data container.
27279   
27280   \see timeSeriesToOhlc
27281 */
27282 void QCPFinancial::addData(double key, double open, double high, double low, double close)
27283 {
27284   mDataContainer->add(QCPFinancialData(key, open, high, low, close));
27285 }
27286 
27287 /*!
27288   \copydoc QCPPlottableInterface1D::selectTestRect
27289 */
27290 QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
27291 {
27292   QCPDataSelection result;
27293   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
27294     return result;
27295   if (!mKeyAxis || !mValueAxis)
27296     return result;
27297   
27298   QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
27299   getVisibleDataBounds(visibleBegin, visibleEnd);
27300   
27301   for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
27302   {
27303     if (rect.intersects(selectionHitBox(it)))
27304       result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
27305   }
27306   result.simplify();
27307   return result;
27308 }
27309 
27310 /*!
27311   Implements a selectTest specific to this plottable's point geometry.
27312 
27313   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
27314   point to \a pos.
27315   
27316   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
27317 */
27318 double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
27319 {
27320   Q_UNUSED(details)
27321   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
27322     return -1;
27323   if (!mKeyAxis || !mValueAxis)
27324     return -1;
27325   
27326   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
27327   {
27328     // get visible data range:
27329     QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
27330     QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
27331     getVisibleDataBounds(visibleBegin, visibleEnd);
27332     // perform select test according to configured style:
27333     double result = -1;
27334     switch (mChartStyle)
27335     {
27336       case QCPFinancial::csOhlc:
27337         result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
27338       case QCPFinancial::csCandlestick:
27339         result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
27340     }
27341     if (details)
27342     {
27343       int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
27344       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
27345     }
27346     return result;
27347   }
27348   
27349   return -1;
27350 }
27351 
27352 /* inherits documentation from base class */
27353 QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
27354 {
27355   QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
27356   // determine exact range by including width of bars/flags:
27357   if (foundRange)
27358   {
27359     if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
27360       range.lower -= mWidth*0.5;
27361     if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
27362       range.upper += mWidth*0.5;
27363   }
27364   return range;
27365 }
27366 
27367 /* inherits documentation from base class */
27368 QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
27369 {
27370   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
27371 }
27372 
27373 /*!
27374   A convenience function that converts time series data (\a value against \a time) to OHLC binned
27375   data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
27376   QCPFinancialDataContainer&).
27377   
27378   The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
27379   For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
27380   each, set \a timeBinSize to 3600.
27381   
27382   \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
27383   value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
27384   It merely defines the mathematical offset/phase of the bins that will be used to process the
27385   data.
27386 */
27387 QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
27388 {
27389   QCPFinancialDataContainer data;
27390   int count = qMin(time.size(), value.size());
27391   if (count == 0)
27392     return QCPFinancialDataContainer();
27393   
27394   QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
27395   int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
27396   for (int i=0; i<count; ++i)
27397   {
27398     int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
27399     if (currentBinIndex == index) // data point still in current bin, extend high/low:
27400     {
27401       if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
27402       if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
27403       if (i == count-1) // last data point is in current bin, finalize bin:
27404       {
27405         currentBinData.close = value.at(i);
27406         currentBinData.key = timeBinOffset+(index)*timeBinSize;
27407         data.add(currentBinData);
27408       }
27409     } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
27410     {
27411       // finalize current bin:
27412       currentBinData.close = value.at(i-1);
27413       currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
27414       data.add(currentBinData);
27415       // start next bin:
27416       currentBinIndex = index;
27417       currentBinData.open = value.at(i);
27418       currentBinData.high = value.at(i);
27419       currentBinData.low = value.at(i);
27420     }
27421   }
27422   
27423   return data;
27424 }
27425 
27426 /* inherits documentation from base class */
27427 void QCPFinancial::draw(QCPPainter *painter)
27428 {
27429   // get visible data range:
27430   QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
27431   getVisibleDataBounds(visibleBegin, visibleEnd);
27432   
27433   // loop over and draw segments of unselected/selected data:
27434   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
27435   getDataSegments(selectedSegments, unselectedSegments);
27436   allSegments << unselectedSegments << selectedSegments;
27437   for (int i=0; i<allSegments.size(); ++i)
27438   {
27439     bool isSelectedSegment = i >= unselectedSegments.size();
27440     QCPFinancialDataContainer::const_iterator begin = visibleBegin;
27441     QCPFinancialDataContainer::const_iterator end = visibleEnd;
27442     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
27443     if (begin == end)
27444       continue;
27445     
27446     // draw data segment according to configured style:
27447     switch (mChartStyle)
27448     {
27449       case QCPFinancial::csOhlc:
27450         drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
27451       case QCPFinancial::csCandlestick:
27452         drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
27453     }
27454   }
27455   
27456   // draw other selection decoration that isn't just line/scatter pens and brushes:
27457   if (mSelectionDecorator)
27458     mSelectionDecorator->drawDecoration(painter, selection());
27459 }
27460 
27461 /* inherits documentation from base class */
27462 void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
27463 {
27464   painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
27465   if (mChartStyle == csOhlc)
27466   {
27467     if (mTwoColored)
27468     {
27469       // draw upper left half icon with positive color:
27470       painter->setBrush(mBrushPositive);
27471       painter->setPen(mPenPositive);
27472       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
27473       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27474       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
27475       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
27476       // draw bottom right half icon with negative color:
27477       painter->setBrush(mBrushNegative);
27478       painter->setPen(mPenNegative);
27479       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
27480       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27481       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
27482       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
27483     } else
27484     {
27485       painter->setBrush(mBrush);
27486       painter->setPen(mPen);
27487       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27488       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
27489       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
27490     }
27491   } else if (mChartStyle == csCandlestick)
27492   {
27493     if (mTwoColored)
27494     {
27495       // draw upper left half icon with positive color:
27496       painter->setBrush(mBrushPositive);
27497       painter->setPen(mPenPositive);
27498       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
27499       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
27500       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27501       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
27502       // draw bottom right half icon with negative color:
27503       painter->setBrush(mBrushNegative);
27504       painter->setPen(mPenNegative);
27505       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
27506       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
27507       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27508       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
27509     } else
27510     {
27511       painter->setBrush(mBrush);
27512       painter->setPen(mPen);
27513       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
27514       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
27515       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
27516     }
27517   }
27518 }
27519 
27520 /*! \internal
27521   
27522   Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
27523 
27524   This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
27525 */
27526 void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
27527 {
27528   QCPAxis *keyAxis = mKeyAxis.data();
27529   QCPAxis *valueAxis = mValueAxis.data();
27530   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
27531   
27532   if (keyAxis->orientation() == Qt::Horizontal)
27533   {
27534     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
27535     {
27536       if (isSelected && mSelectionDecorator)
27537         mSelectionDecorator->applyPen(painter);
27538       else if (mTwoColored)
27539         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
27540       else
27541         painter->setPen(mPen);
27542       double keyPixel = keyAxis->coordToPixel(it->key);
27543       double openPixel = valueAxis->coordToPixel(it->open);
27544       double closePixel = valueAxis->coordToPixel(it->close);
27545       // draw backbone:
27546       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
27547       // draw open:
27548       double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
27549       painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
27550       // draw close:
27551       painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
27552     }
27553   } else
27554   {
27555     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
27556     {
27557       if (isSelected && mSelectionDecorator)
27558         mSelectionDecorator->applyPen(painter);
27559       else if (mTwoColored)
27560         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
27561       else
27562         painter->setPen(mPen);
27563       double keyPixel = keyAxis->coordToPixel(it->key);
27564       double openPixel = valueAxis->coordToPixel(it->open);
27565       double closePixel = valueAxis->coordToPixel(it->close);
27566       // draw backbone:
27567       painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
27568       // draw open:
27569       double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
27570       painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
27571       // draw close:
27572       painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
27573     }
27574   }
27575 }
27576 
27577 /*! \internal
27578   
27579   Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
27580 
27581   This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
27582 */
27583 void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
27584 {
27585   QCPAxis *keyAxis = mKeyAxis.data();
27586   QCPAxis *valueAxis = mValueAxis.data();
27587   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
27588   
27589   if (keyAxis->orientation() == Qt::Horizontal)
27590   {
27591     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
27592     {
27593       if (isSelected && mSelectionDecorator)
27594       {
27595         mSelectionDecorator->applyPen(painter);
27596         mSelectionDecorator->applyBrush(painter);
27597       } else if (mTwoColored)
27598       {
27599         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
27600         painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
27601       } else
27602       {
27603         painter->setPen(mPen);
27604         painter->setBrush(mBrush);
27605       }
27606       double keyPixel = keyAxis->coordToPixel(it->key);
27607       double openPixel = valueAxis->coordToPixel(it->open);
27608       double closePixel = valueAxis->coordToPixel(it->close);
27609       // draw high:
27610       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
27611       // draw low:
27612       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
27613       // draw open-close box:
27614       double pixelWidth = getPixelWidth(it->key, keyPixel);
27615       painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
27616     }
27617   } else // keyAxis->orientation() == Qt::Vertical
27618   {
27619     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
27620     {
27621       if (isSelected && mSelectionDecorator)
27622       {
27623         mSelectionDecorator->applyPen(painter);
27624         mSelectionDecorator->applyBrush(painter);
27625       } else if (mTwoColored)
27626       {
27627         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
27628         painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
27629       } else
27630       {
27631         painter->setPen(mPen);
27632         painter->setBrush(mBrush);
27633       }
27634       double keyPixel = keyAxis->coordToPixel(it->key);
27635       double openPixel = valueAxis->coordToPixel(it->open);
27636       double closePixel = valueAxis->coordToPixel(it->close);
27637       // draw high:
27638       painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
27639       // draw low:
27640       painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
27641       // draw open-close box:
27642       double pixelWidth = getPixelWidth(it->key, keyPixel);
27643       painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
27644     }
27645   }
27646 }
27647 
27648 /*! \internal
27649 
27650   This function is used to determine the width of the bar at coordinate \a key, according to the
27651   specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
27652   \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
27653   when this function is called).
27654 
27655   It returns the number of pixels the bar extends to higher keys, relative to the \a key
27656   coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
27657   horizontal axis, the return value is negative. This is important so the open/close flags on the
27658   \ref csOhlc bar are drawn to the correct side.
27659 */
27660 double QCPFinancial::getPixelWidth(double key, double keyPixel) const
27661 {
27662   double result = 0;
27663   switch (mWidthType)
27664   {
27665     case wtAbsolute:
27666     {
27667       if (mKeyAxis)
27668         result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
27669       break;
27670     }
27671     case wtAxisRectRatio:
27672     {
27673       if (mKeyAxis && mKeyAxis.data()->axisRect())
27674       {
27675         if (mKeyAxis.data()->orientation() == Qt::Horizontal)
27676           result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
27677         else
27678           result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
27679       } else
27680         qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
27681       break;
27682     }
27683     case wtPlotCoords:
27684     {
27685       if (mKeyAxis)
27686         result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
27687       else
27688         qDebug() << Q_FUNC_INFO << "No key axis defined";
27689       break;
27690     }
27691   }
27692   return result;
27693 }
27694 
27695 /*! \internal
27696 
27697   This method is a helper function for \ref selectTest. It is used to test for selection when the
27698   chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
27699   
27700   Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
27701   representation of the plottable, and \a closestDataPoint will point to the respective data point.
27702 */
27703 double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
27704 {
27705   closestDataPoint = mDataContainer->constEnd();
27706   QCPAxis *keyAxis = mKeyAxis.data();
27707   QCPAxis *valueAxis = mValueAxis.data();
27708   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
27709 
27710   double minDistSqr = (std::numeric_limits<double>::max)();
27711   if (keyAxis->orientation() == Qt::Horizontal)
27712   {
27713     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
27714     {
27715       double keyPixel = keyAxis->coordToPixel(it->key);
27716       // calculate distance to backbone:
27717       double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
27718       if (currentDistSqr < minDistSqr)
27719       {
27720         minDistSqr = currentDistSqr;
27721         closestDataPoint = it;
27722       }
27723     }
27724   } else // keyAxis->orientation() == Qt::Vertical
27725   {
27726     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
27727     {
27728       double keyPixel = keyAxis->coordToPixel(it->key);
27729       // calculate distance to backbone:
27730       double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
27731       if (currentDistSqr < minDistSqr)
27732       {
27733         minDistSqr = currentDistSqr;
27734         closestDataPoint = it;
27735       }
27736     }
27737   }
27738   return qSqrt(minDistSqr);
27739 }
27740 
27741 /*! \internal
27742   
27743   This method is a helper function for \ref selectTest. It is used to test for selection when the
27744   chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
27745   end.
27746   
27747   Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
27748   representation of the plottable, and \a closestDataPoint will point to the respective data point.
27749 */
27750 double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
27751 {
27752   closestDataPoint = mDataContainer->constEnd();
27753   QCPAxis *keyAxis = mKeyAxis.data();
27754   QCPAxis *valueAxis = mValueAxis.data();
27755   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
27756 
27757   double minDistSqr = (std::numeric_limits<double>::max)();
27758   if (keyAxis->orientation() == Qt::Horizontal)
27759   {
27760     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
27761     {
27762       double currentDistSqr;
27763       // determine whether pos is in open-close-box:
27764       QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
27765       QCPRange boxValueRange(it->close, it->open);
27766       double posKey, posValue;
27767       pixelsToCoords(pos, posKey, posValue);
27768       if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
27769       {
27770         currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
27771       } else
27772       {
27773         // calculate distance to high/low lines:
27774         double keyPixel = keyAxis->coordToPixel(it->key);
27775         double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
27776         double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
27777         currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
27778       }
27779       if (currentDistSqr < minDistSqr)
27780       {
27781         minDistSqr = currentDistSqr;
27782         closestDataPoint = it;
27783       }
27784     }
27785   } else // keyAxis->orientation() == Qt::Vertical
27786   {
27787     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
27788     {
27789       double currentDistSqr;
27790       // determine whether pos is in open-close-box:
27791       QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
27792       QCPRange boxValueRange(it->close, it->open);
27793       double posKey, posValue;
27794       pixelsToCoords(pos, posKey, posValue);
27795       if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
27796       {
27797         currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
27798       } else
27799       {
27800         // calculate distance to high/low lines:
27801         double keyPixel = keyAxis->coordToPixel(it->key);
27802         double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
27803         double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
27804         currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
27805       }
27806       if (currentDistSqr < minDistSqr)
27807       {
27808         minDistSqr = currentDistSqr;
27809         closestDataPoint = it;
27810       }
27811     }
27812   }
27813   return qSqrt(minDistSqr);
27814 }
27815 
27816 /*! \internal
27817   
27818   called by the drawing methods to determine which data (key) range is visible at the current key
27819   axis range setting, so only that needs to be processed.
27820   
27821   \a begin returns an iterator to the lowest data point that needs to be taken into account when
27822   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
27823   begin may still be just outside the visible range.
27824   
27825   \a end returns the iterator just above the highest data point that needs to be taken into
27826   account. Same as before, \a end may also lie just outside of the visible range
27827   
27828   if the plottable contains no data, both \a begin and \a end point to \c constEnd.
27829 */
27830 void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
27831 {
27832   if (!mKeyAxis)
27833   {
27834     qDebug() << Q_FUNC_INFO << "invalid key axis";
27835     begin = mDataContainer->constEnd();
27836     end = mDataContainer->constEnd();
27837     return;
27838   }
27839   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
27840   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
27841 }
27842 
27843 /*!  \internal
27844 
27845   Returns the hit box in pixel coordinates that will be used for data selection with the selection
27846   rect (\ref selectTestRect), of the data point given by \a it.
27847 */
27848 QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
27849 {
27850   QCPAxis *keyAxis = mKeyAxis.data();
27851   QCPAxis *valueAxis = mValueAxis.data();
27852   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
27853   
27854   double keyPixel = keyAxis->coordToPixel(it->key);
27855   double highPixel = valueAxis->coordToPixel(it->high);
27856   double lowPixel = valueAxis->coordToPixel(it->low);
27857   double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
27858   if (keyAxis->orientation() == Qt::Horizontal)
27859     return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
27860   else
27861     return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
27862 }
27863 /* end of 'src/plottables/plottable-financial.cpp' */
27864 
27865 
27866 /* including file 'src/plottables/plottable-errorbar.cpp' */
27867 /* modified 2021-03-29T02:30:44, size 37679               */
27868 
27869 ////////////////////////////////////////////////////////////////////////////////////////////////////
27870 //////////////////// QCPErrorBarsData
27871 ////////////////////////////////////////////////////////////////////////////////////////////////////
27872 
27873 /*! \class QCPErrorBarsData
27874   \brief Holds the data of one single error bar for QCPErrorBars.
27875 
27876   The stored data is:
27877   \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
27878   point position
27879   \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
27880   position
27881 
27882   The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
27883   typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
27884 
27885   \see QCPErrorBarsDataContainer
27886 */
27887 
27888 /*!
27889   Constructs an error bar with errors set to zero.
27890 */
27891 QCPErrorBarsData::QCPErrorBarsData() :
27892   errorMinus(0),
27893   errorPlus(0)
27894 {
27895 }
27896 
27897 /*!
27898   Constructs an error bar with equal \a error in both negative and positive direction.
27899 */
27900 QCPErrorBarsData::QCPErrorBarsData(double error) :
27901   errorMinus(error),
27902   errorPlus(error)
27903 {
27904 }
27905 
27906 /*!
27907   Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
27908   respectively.
27909 */
27910 QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
27911   errorMinus(errorMinus),
27912   errorPlus(errorPlus)
27913 {
27914 }
27915 
27916 
27917 ////////////////////////////////////////////////////////////////////////////////////////////////////
27918 //////////////////// QCPErrorBars
27919 ////////////////////////////////////////////////////////////////////////////////////////////////////
27920 
27921 /*! \class QCPErrorBars
27922   \brief A plottable that adds a set of error bars to other plottables.
27923 
27924   \image html QCPErrorBars.png
27925 
27926   The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
27927   QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
27928 
27929   Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
27930   error bars. The orientation of the error bars can be controlled with \ref setErrorType.
27931 
27932   By using \ref setData, you can supply the actual error data, either as symmetric error or
27933   plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
27934   key/value position of each error bar will be adopted from the configured data plottable. The
27935   error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
27936   of the data plottable. You can directly access and manipulate the error bar data via \ref data.
27937 
27938   Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
27939   <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
27940   that index.
27941 
27942   \section qcperrorbars-appearance Changing the appearance
27943 
27944   The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
27945   whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
27946   point center to prevent that error bars are drawn too close to or even through scatter points.
27947   This gap size can be controlled via \ref setSymbolGap.
27948 */
27949 
27950 /* start of documentation of inline functions */
27951 
27952 /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
27953 
27954   Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
27955   may use it to directly manipulate the error values, which may be more convenient and faster than
27956   using the regular \ref setData methods.
27957 */
27958 
27959 /* end of documentation of inline functions */
27960 
27961 /*!
27962   Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
27963   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
27964   the same orientation. If either of these restrictions is violated, a corresponding message is
27965   printed to the debug output (qDebug), the construction is not aborted, though.
27966 
27967   It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
27968   plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
27969 
27970   The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
27971   from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
27972   delete it manually but use \ref QCustomPlot::removePlottable() instead.
27973 */
27974 QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
27975   QCPAbstractPlottable(keyAxis, valueAxis),
27976   mDataContainer(new QVector<QCPErrorBarsData>),
27977   mErrorType(etValueError),
27978   mWhiskerWidth(9),
27979   mSymbolGap(10)
27980 {
27981   setPen(QPen(Qt::black, 0));
27982   setBrush(Qt::NoBrush);
27983 }
27984 
27985 QCPErrorBars::~QCPErrorBars()
27986 {
27987 }
27988 
27989 /*! \overload
27990 
27991   Replaces the current data container with the provided \a data container.
27992 
27993   Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
27994   container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
27995   instances that share the container. Sharing can be achieved by simply exchanging the data
27996   containers wrapped in shared pointers:
27997   \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
27998 
27999   If you do not wish to share containers, but create a copy from an existing container, assign the
28000   data containers directly:
28001   \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
28002   (This uses different notation compared with other plottables, because the \ref QCPErrorBars
28003   uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
28004 
28005   \see addData
28006 */
28007 void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
28008 {
28009   mDataContainer = data;
28010 }
28011 
28012 /*! \overload
28013 
28014   Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
28015   by the data point index to the associated data plottable (\ref setDataPlottable).
28016 
28017   You can directly access and manipulate the error bar data via \ref data.
28018 
28019   \see addData
28020 */
28021 void QCPErrorBars::setData(const QVector<double> &error)
28022 {
28023   mDataContainer->clear();
28024   addData(error);
28025 }
28026 
28027 /*! \overload
28028 
28029   Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
28030   associated one-to-one by the data point index to the associated data plottable (\ref
28031   setDataPlottable).
28032 
28033   You can directly access and manipulate the error bar data via \ref data.
28034 
28035   \see addData
28036 */
28037 void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
28038 {
28039   mDataContainer->clear();
28040   addData(errorMinus, errorPlus);
28041 }
28042 
28043 /*!
28044   Sets the data plottable to which the error bars will be applied. The error values specified e.g.
28045   via \ref setData will be associated one-to-one by the data point index to the data points of \a
28046   plottable. This means that the error bars will adopt the key/value coordinates of the data point
28047   with the same index.
28048 
28049   The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
28050   QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
28051   of these restrictions is violated, a corresponding qDebug output is generated, and the data
28052   plottable of this \ref QCPErrorBars instance is set to zero.
28053 
28054   For proper display, care must also be taken that the key and value axes of the \a plottable match
28055   those configured for this \ref QCPErrorBars instance.
28056 */
28057 void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
28058 {
28059   if (plottable && qobject_cast<QCPErrorBars*>(plottable))
28060   {
28061     mDataPlottable = nullptr;
28062     qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
28063     return;
28064   }
28065   if (plottable && !plottable->interface1D())
28066   {
28067     mDataPlottable = nullptr;
28068     qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
28069     return;
28070   }
28071   
28072   mDataPlottable = plottable;
28073 }
28074 
28075 /*!
28076   Sets in which orientation the error bars shall appear on the data points. If your data needs both
28077   error dimensions, create two \ref QCPErrorBars with different \a type.
28078 */
28079 void QCPErrorBars::setErrorType(ErrorType type)
28080 {
28081   mErrorType = type;
28082 }
28083 
28084 /*!
28085   Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
28086   \a pixels.
28087 */
28088 void QCPErrorBars::setWhiskerWidth(double pixels)
28089 {
28090   mWhiskerWidth = pixels;
28091 }
28092 
28093 /*!
28094   Sets the gap diameter around the data points that will be left out when drawing the error bar
28095   backbones. This gap prevents that error bars are drawn too close to or even through scatter
28096   points.
28097 */
28098 void QCPErrorBars::setSymbolGap(double pixels)
28099 {
28100   mSymbolGap = pixels;
28101 }
28102 
28103 /*! \overload
28104 
28105   Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
28106   by the data point index to the associated data plottable (\ref setDataPlottable).
28107 
28108   You can directly access and manipulate the error bar data via \ref data.
28109 
28110   \see setData
28111 */
28112 void QCPErrorBars::addData(const QVector<double> &error)
28113 {
28114   addData(error, error);
28115 }
28116 
28117 /*! \overload
28118 
28119   Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
28120   associated one-to-one by the data point index to the associated data plottable (\ref
28121   setDataPlottable).
28122 
28123   You can directly access and manipulate the error bar data via \ref data.
28124 
28125   \see setData
28126 */
28127 void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
28128 {
28129   if (errorMinus.size() != errorPlus.size())
28130     qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
28131   const int n = qMin(errorMinus.size(), errorPlus.size());
28132   mDataContainer->reserve(n);
28133   for (int i=0; i<n; ++i)
28134     mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
28135 }
28136 
28137 /*! \overload
28138 
28139   Adds a single symmetrical error bar as specified in \a error. The errors will be associated
28140   one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
28141 
28142   You can directly access and manipulate the error bar data via \ref data.
28143 
28144   \see setData
28145 */
28146 void QCPErrorBars::addData(double error)
28147 {
28148   mDataContainer->append(QCPErrorBarsData(error));
28149 }
28150 
28151 /*! \overload
28152 
28153   Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
28154   will be associated one-to-one by the data point index to the associated data plottable (\ref
28155   setDataPlottable).
28156 
28157   You can directly access and manipulate the error bar data via \ref data.
28158 
28159   \see setData
28160 */
28161 void QCPErrorBars::addData(double errorMinus, double errorPlus)
28162 {
28163   mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
28164 }
28165 
28166 /* inherits documentation from base class */
28167 int QCPErrorBars::dataCount() const
28168 {
28169   return mDataContainer->size();
28170 }
28171 
28172 /* inherits documentation from base class */
28173 double QCPErrorBars::dataMainKey(int index) const
28174 {
28175   if (mDataPlottable)
28176     return mDataPlottable->interface1D()->dataMainKey(index);
28177   else
28178     qDebug() << Q_FUNC_INFO << "no data plottable set";
28179   return 0;
28180 }
28181 
28182 /* inherits documentation from base class */
28183 double QCPErrorBars::dataSortKey(int index) const
28184 {
28185   if (mDataPlottable)
28186     return mDataPlottable->interface1D()->dataSortKey(index);
28187   else
28188     qDebug() << Q_FUNC_INFO << "no data plottable set";
28189   return 0;
28190 }
28191 
28192 /* inherits documentation from base class */
28193 double QCPErrorBars::dataMainValue(int index) const
28194 {
28195   if (mDataPlottable)
28196     return mDataPlottable->interface1D()->dataMainValue(index);
28197   else
28198     qDebug() << Q_FUNC_INFO << "no data plottable set";
28199   return 0;
28200 }
28201 
28202 /* inherits documentation from base class */
28203 QCPRange QCPErrorBars::dataValueRange(int index) const
28204 {
28205   if (mDataPlottable)
28206   {
28207     const double value = mDataPlottable->interface1D()->dataMainValue(index);
28208     if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
28209       return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
28210     else
28211       return {value, value};
28212   } else
28213   {
28214     qDebug() << Q_FUNC_INFO << "no data plottable set";
28215     return {};
28216   }
28217 }
28218 
28219 /* inherits documentation from base class */
28220 QPointF QCPErrorBars::dataPixelPosition(int index) const
28221 {
28222   if (mDataPlottable)
28223     return mDataPlottable->interface1D()->dataPixelPosition(index);
28224   else
28225     qDebug() << Q_FUNC_INFO << "no data plottable set";
28226   return {};
28227 }
28228 
28229 /* inherits documentation from base class */
28230 bool QCPErrorBars::sortKeyIsMainKey() const
28231 {
28232   if (mDataPlottable)
28233   {
28234     return mDataPlottable->interface1D()->sortKeyIsMainKey();
28235   } else
28236   {
28237     qDebug() << Q_FUNC_INFO << "no data plottable set";
28238     return true;
28239   }
28240 }
28241 
28242 /*!
28243   \copydoc QCPPlottableInterface1D::selectTestRect
28244 */
28245 QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
28246 {
28247   QCPDataSelection result;
28248   if (!mDataPlottable)
28249     return result;
28250   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
28251     return result;
28252   if (!mKeyAxis || !mValueAxis)
28253     return result;
28254   
28255   QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
28256   getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
28257   
28258   QVector<QLineF> backbones, whiskers;
28259   for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
28260   {
28261     backbones.clear();
28262     whiskers.clear();
28263     getErrorBarLines(it, backbones, whiskers);
28264     foreach (const QLineF &backbone, backbones)
28265     {
28266       if (rectIntersectsLine(rect, backbone))
28267       {
28268         result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
28269         break;
28270       }
28271     }
28272   }
28273   result.simplify();
28274   return result;
28275 }
28276 
28277 /* inherits documentation from base class */
28278 int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
28279 {
28280   if (mDataPlottable)
28281   {
28282     if (mDataContainer->isEmpty())
28283       return 0;
28284     int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
28285     if (beginIndex >= mDataContainer->size())
28286       beginIndex = mDataContainer->size()-1;
28287     return beginIndex;
28288   } else
28289     qDebug() << Q_FUNC_INFO << "no data plottable set";
28290   return 0;
28291 }
28292 
28293 /* inherits documentation from base class */
28294 int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
28295 {
28296   if (mDataPlottable)
28297   {
28298     if (mDataContainer->isEmpty())
28299       return 0;
28300     int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
28301     if (endIndex > mDataContainer->size())
28302       endIndex = mDataContainer->size();
28303     return endIndex;
28304   } else
28305     qDebug() << Q_FUNC_INFO << "no data plottable set";
28306   return 0;
28307 }
28308 
28309 /*!
28310   Implements a selectTest specific to this plottable's point geometry.
28311 
28312   If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
28313   point to \a pos.
28314   
28315   \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
28316 */
28317 double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28318 {
28319   if (!mDataPlottable) return -1;
28320   
28321   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
28322     return -1;
28323   if (!mKeyAxis || !mValueAxis)
28324     return -1;
28325   
28326   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
28327   {
28328     QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
28329     double result = pointDistance(pos, closestDataPoint);
28330     if (details)
28331     {
28332       int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
28333       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
28334     }
28335     return result;
28336   } else
28337     return -1;
28338 }
28339 
28340 /* inherits documentation from base class */
28341 void QCPErrorBars::draw(QCPPainter *painter)
28342 {
28343   if (!mDataPlottable) return;
28344   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
28345   if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
28346   
28347   // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
28348   // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
28349   bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
28350       
28351     // check data validity if flag set:
28352 #ifdef QCUSTOMPLOT_CHECK_DATA
28353   QCPErrorBarsDataContainer::const_iterator it;
28354   for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
28355   {
28356     if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
28357       qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
28358   }
28359 #endif
28360   
28361   applyDefaultAntialiasingHint(painter);
28362   painter->setBrush(Qt::NoBrush);
28363   // loop over and draw segments of unselected/selected data:
28364   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
28365   getDataSegments(selectedSegments, unselectedSegments);
28366   allSegments << unselectedSegments << selectedSegments;
28367   QVector<QLineF> backbones, whiskers;
28368   for (int i=0; i<allSegments.size(); ++i)
28369   {
28370     QCPErrorBarsDataContainer::const_iterator begin, end;
28371     getVisibleDataBounds(begin, end, allSegments.at(i));
28372     if (begin == end)
28373       continue;
28374     
28375     bool isSelectedSegment = i >= unselectedSegments.size();
28376     if (isSelectedSegment && mSelectionDecorator)
28377       mSelectionDecorator->applyPen(painter);
28378     else
28379       painter->setPen(mPen);
28380     if (painter->pen().capStyle() == Qt::SquareCap)
28381     {
28382       QPen capFixPen(painter->pen());
28383       capFixPen.setCapStyle(Qt::FlatCap);
28384       painter->setPen(capFixPen);
28385     }
28386     backbones.clear();
28387     whiskers.clear();
28388     for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
28389     {
28390       if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
28391         getErrorBarLines(it, backbones, whiskers);
28392     }
28393     painter->drawLines(backbones);
28394     painter->drawLines(whiskers);
28395   }
28396   
28397   // draw other selection decoration that isn't just line/scatter pens and brushes:
28398   if (mSelectionDecorator)
28399     mSelectionDecorator->drawDecoration(painter, selection());
28400 }
28401 
28402 /* inherits documentation from base class */
28403 void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
28404 {
28405   applyDefaultAntialiasingHint(painter);
28406   painter->setPen(mPen);
28407   if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
28408   {
28409     painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
28410     painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
28411     painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
28412   } else
28413   {
28414     painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
28415     painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
28416     painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
28417   }
28418 }
28419 
28420 /* inherits documentation from base class */
28421 QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
28422 {
28423   if (!mDataPlottable)
28424   {
28425     foundRange = false;
28426     return {};
28427   }
28428   
28429   QCPRange range;
28430   bool haveLower = false;
28431   bool haveUpper = false;
28432   QCPErrorBarsDataContainer::const_iterator it;
28433   for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
28434   {
28435     if (mErrorType == etValueError)
28436     {
28437       // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
28438       const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
28439       if (qIsNaN(current)) continue;
28440       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28441       {
28442         if (current < range.lower || !haveLower)
28443         {
28444           range.lower = current;
28445           haveLower = true;
28446         }
28447         if (current > range.upper || !haveUpper)
28448         {
28449           range.upper = current;
28450           haveUpper = true;
28451         }
28452       }
28453     } else // mErrorType == etKeyError
28454     {
28455       const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
28456       if (qIsNaN(dataKey)) continue;
28457       // plus error:
28458       double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
28459       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28460       {
28461         if (current > range.upper || !haveUpper)
28462         {
28463           range.upper = current;
28464           haveUpper = true;
28465         }
28466       }
28467       // minus error:
28468       current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
28469       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28470       {
28471         if (current < range.lower || !haveLower)
28472         {
28473           range.lower = current;
28474           haveLower = true;
28475         }
28476       }
28477     }
28478   }
28479   
28480   if (haveUpper && !haveLower)
28481   {
28482     range.lower = range.upper;
28483     haveLower = true;
28484   } else if (haveLower && !haveUpper)
28485   {
28486     range.upper = range.lower;
28487     haveUpper = true;
28488   }
28489   
28490   foundRange = haveLower && haveUpper;
28491   return range;
28492 }
28493 
28494 /* inherits documentation from base class */
28495 QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
28496 {
28497   if (!mDataPlottable)
28498   {
28499     foundRange = false;
28500     return {};
28501   }
28502   
28503   QCPRange range;
28504   const bool restrictKeyRange = inKeyRange != QCPRange();
28505   bool haveLower = false;
28506   bool haveUpper = false;
28507   QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
28508   QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
28509   if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
28510   {
28511     itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
28512     itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
28513   }
28514   for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
28515   {
28516     if (restrictKeyRange)
28517     {
28518       const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
28519       if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
28520         continue;
28521     }
28522     if (mErrorType == etValueError)
28523     {
28524       const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
28525       if (qIsNaN(dataValue)) continue;
28526       // plus error:
28527       double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
28528       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28529       {
28530         if (current > range.upper || !haveUpper)
28531         {
28532           range.upper = current;
28533           haveUpper = true;
28534         }
28535       }
28536       // minus error:
28537       current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
28538       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28539       {
28540         if (current < range.lower || !haveLower)
28541         {
28542           range.lower = current;
28543           haveLower = true;
28544         }
28545       }
28546     } else // mErrorType == etKeyError
28547     {
28548       // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
28549       const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
28550       if (qIsNaN(current)) continue;
28551       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
28552       {
28553         if (current < range.lower || !haveLower)
28554         {
28555           range.lower = current;
28556           haveLower = true;
28557         }
28558         if (current > range.upper || !haveUpper)
28559         {
28560           range.upper = current;
28561           haveUpper = true;
28562         }
28563       }
28564     }
28565   }
28566   
28567   if (haveUpper && !haveLower)
28568   {
28569     range.lower = range.upper;
28570     haveLower = true;
28571   } else if (haveLower && !haveUpper)
28572   {
28573     range.upper = range.lower;
28574     haveUpper = true;
28575   }
28576   
28577   foundRange = haveLower && haveUpper;
28578   return range;
28579 }
28580 
28581 /*! \internal
28582 
28583   Calculates the lines that make up the error bar belonging to the data point \a it.
28584 
28585   The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
28586   calling this method with different \a it but the same \a backbones and \a whiskers allows to
28587   accumulate lines for multiple data points.
28588 
28589   This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
28590   instance and within the bounds of the associated data plottable.
28591 */
28592 void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
28593 {
28594   if (!mDataPlottable) return;
28595   
28596   int index = int(it-mDataContainer->constBegin());
28597   QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
28598   if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
28599     return;
28600   QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
28601   QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
28602   const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
28603   const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
28604   const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
28605   const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
28606   // plus error:
28607   double errorStart, errorEnd;
28608   if (!qIsNaN(it->errorPlus))
28609   {
28610     errorStart = centerErrorAxisPixel+symbolGap;
28611     errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
28612     if (errorAxis->orientation() == Qt::Vertical)
28613     {
28614       if ((errorStart > errorEnd) != errorAxis->rangeReversed())
28615         backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
28616       whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
28617     } else
28618     {
28619       if ((errorStart < errorEnd) != errorAxis->rangeReversed())
28620         backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
28621       whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
28622     }
28623   }
28624   // minus error:
28625   if (!qIsNaN(it->errorMinus))
28626   {
28627     errorStart = centerErrorAxisPixel-symbolGap;
28628     errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
28629     if (errorAxis->orientation() == Qt::Vertical)
28630     {
28631       if ((errorStart < errorEnd) != errorAxis->rangeReversed())
28632         backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
28633       whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
28634     } else
28635     {
28636       if ((errorStart > errorEnd) != errorAxis->rangeReversed())
28637         backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
28638       whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
28639     }
28640   }
28641 }
28642 
28643 /*! \internal
28644 
28645   This method outputs the currently visible data range via \a begin and \a end. The returned range
28646   will also never exceed \a rangeRestriction.
28647 
28648   Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
28649   coordinates relative to their data point key, this method checks all outer error bars whether
28650   they truly don't reach into the visible portion of the axis rect, by calling \ref
28651   errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
28652   with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
28653   "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
28654   error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
28655   QCPPlottableInterface1D::findEnd).
28656 
28657   If the plottable's sort key is not equal to the main key, this method returns the full data
28658   range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
28659   point-by-point basis in the \ref draw method.
28660 */
28661 void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
28662 {
28663   QCPAxis *keyAxis = mKeyAxis.data();
28664   QCPAxis *valueAxis = mValueAxis.data();
28665   if (!keyAxis || !valueAxis)
28666   {
28667     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
28668     end = mDataContainer->constEnd();
28669     begin = end;
28670     return;
28671   }
28672   if (!mDataPlottable || rangeRestriction.isEmpty())
28673   {
28674     end = mDataContainer->constEnd();
28675     begin = end;
28676     return;
28677   }
28678   if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
28679   {
28680     // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
28681     // data points, so this method then only applies the range restriction and otherwise returns
28682     // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
28683     QCPDataRange dataRange(0, mDataContainer->size());
28684     dataRange = dataRange.bounded(rangeRestriction);
28685     begin = mDataContainer->constBegin()+dataRange.begin();
28686     end = mDataContainer->constBegin()+dataRange.end();
28687     return;
28688   }
28689   
28690   // get visible data range via interface from data plottable, and then restrict to available error data points:
28691   const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
28692   int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
28693   int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
28694   int i = beginIndex;
28695   while (i > 0 && i < n && i > rangeRestriction.begin())
28696   {
28697     if (errorBarVisible(i))
28698       beginIndex = i;
28699     --i;
28700   }
28701   i = endIndex;
28702   while (i >= 0 && i < n && i < rangeRestriction.end())
28703   {
28704     if (errorBarVisible(i))
28705       endIndex = i+1;
28706     ++i;
28707   }
28708   QCPDataRange dataRange(beginIndex, endIndex);
28709   dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
28710   begin = mDataContainer->constBegin()+dataRange.begin();
28711   end = mDataContainer->constBegin()+dataRange.end();
28712 }
28713 
28714 /*! \internal
28715 
28716   Calculates the minimum distance in pixels the error bars' representation has from the given \a
28717   pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
28718   selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
28719 */
28720 double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
28721 {
28722   closestData = mDataContainer->constEnd();
28723   if (!mDataPlottable || mDataContainer->isEmpty())
28724     return -1.0;
28725   if (!mKeyAxis || !mValueAxis)
28726   {
28727     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
28728     return -1.0;
28729   }
28730   
28731   QCPErrorBarsDataContainer::const_iterator begin, end;
28732   getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
28733   
28734   // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
28735   double minDistSqr = (std::numeric_limits<double>::max)();
28736   QVector<QLineF> backbones, whiskers;
28737   for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
28738   {
28739     getErrorBarLines(it, backbones, whiskers);
28740     foreach (const QLineF &backbone, backbones)
28741     {
28742       const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
28743       if (currentDistSqr < minDistSqr)
28744       {
28745         minDistSqr = currentDistSqr;
28746         closestData = it;
28747       }
28748     }
28749   }
28750   return qSqrt(minDistSqr);
28751 }
28752 
28753 /*! \internal
28754 
28755   \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
28756   reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
28757   own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
28758   documentation there for details.
28759 */
28760 void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
28761 {
28762   selectedSegments.clear();
28763   unselectedSegments.clear();
28764   if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
28765   {
28766     if (selected())
28767       selectedSegments << QCPDataRange(0, dataCount());
28768     else
28769       unselectedSegments << QCPDataRange(0, dataCount());
28770   } else
28771   {
28772     QCPDataSelection sel(selection());
28773     sel.simplify();
28774     selectedSegments = sel.dataRanges();
28775     unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
28776   }
28777 }
28778 
28779 /*! \internal
28780 
28781   Returns whether the error bar at the specified \a index is visible within the current key axis
28782   range.
28783 
28784   This method assumes for performance reasons without checking that the key axis, the value axis,
28785   and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
28786   valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
28787 */
28788 bool QCPErrorBars::errorBarVisible(int index) const
28789 {
28790   QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
28791   const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
28792   if (qIsNaN(centerKeyPixel))
28793     return false;
28794   
28795   double keyMin, keyMax;
28796   if (mErrorType == etKeyError)
28797   {
28798     const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
28799     const double errorPlus = mDataContainer->at(index).errorPlus;
28800     const double errorMinus = mDataContainer->at(index).errorMinus;
28801     keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
28802     keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
28803   } else // mErrorType == etValueError
28804   {
28805     keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
28806     keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
28807   }
28808   return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
28809 }
28810 
28811 /*! \internal
28812 
28813   Returns whether \a line intersects (or is contained in) \a pixelRect.
28814 
28815   \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
28816   error bar lines.
28817 */
28818 bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
28819 {
28820   if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
28821     return false;
28822   else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
28823     return false;
28824   else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
28825     return false;
28826   else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
28827     return false;
28828   else
28829     return true;
28830 }
28831 /* end of 'src/plottables/plottable-errorbar.cpp' */
28832 
28833 
28834 /* including file 'src/items/item-straightline.cpp' */
28835 /* modified 2021-03-29T02:30:44, size 7596          */
28836 
28837 ////////////////////////////////////////////////////////////////////////////////////////////////////
28838 //////////////////// QCPItemStraightLine
28839 ////////////////////////////////////////////////////////////////////////////////////////////////////
28840 
28841 /*! \class QCPItemStraightLine
28842   \brief A straight line that spans infinitely in both directions
28843 
28844   \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
28845 
28846   It has two positions, \a point1 and \a point2, which define the straight line.
28847 */
28848 
28849 /*!
28850   Creates a straight line item and sets default values.
28851   
28852   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28853   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28854 */
28855 QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
28856   QCPAbstractItem(parentPlot),
28857   point1(createPosition(QLatin1String("point1"))),
28858   point2(createPosition(QLatin1String("point2")))
28859 {
28860   point1->setCoords(0, 0);
28861   point2->setCoords(1, 1);
28862   
28863   setPen(QPen(Qt::black));
28864   setSelectedPen(QPen(Qt::blue,2));
28865 }
28866 
28867 QCPItemStraightLine::~QCPItemStraightLine()
28868 {
28869 }
28870 
28871 /*!
28872   Sets the pen that will be used to draw the line
28873   
28874   \see setSelectedPen
28875 */
28876 void QCPItemStraightLine::setPen(const QPen &pen)
28877 {
28878   mPen = pen;
28879 }
28880 
28881 /*!
28882   Sets the pen that will be used to draw the line when selected
28883   
28884   \see setPen, setSelected
28885 */
28886 void QCPItemStraightLine::setSelectedPen(const QPen &pen)
28887 {
28888   mSelectedPen = pen;
28889 }
28890 
28891 /* inherits documentation from base class */
28892 double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28893 {
28894   Q_UNUSED(details)
28895   if (onlySelectable && !mSelectable)
28896     return -1;
28897   
28898   return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
28899 }
28900 
28901 /* inherits documentation from base class */
28902 void QCPItemStraightLine::draw(QCPPainter *painter)
28903 {
28904   QCPVector2D start(point1->pixelPosition());
28905   QCPVector2D end(point2->pixelPosition());
28906   // get visible segment of straight line inside clipRect:
28907   int clipPad = qCeil(mainPen().widthF());
28908   QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
28909   // paint visible segment, if existent:
28910   if (!line.isNull())
28911   {
28912     painter->setPen(mainPen());
28913     painter->drawLine(line);
28914   }
28915 }
28916 
28917 /*! \internal
28918 
28919   Returns the section of the straight line defined by \a base and direction vector \a
28920   vec, that is visible in the specified \a rect.
28921   
28922   This is a helper function for \ref draw.
28923 */
28924 QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
28925 {
28926   double bx, by;
28927   double gamma;
28928   QLineF result;
28929   if (vec.x() == 0 && vec.y() == 0)
28930     return result;
28931   if (qFuzzyIsNull(vec.x())) // line is vertical
28932   {
28933     // check top of rect:
28934     bx = rect.left();
28935     by = rect.top();
28936     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
28937     if (gamma >= 0 && gamma <= rect.width())
28938       result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
28939   } else if (qFuzzyIsNull(vec.y())) // line is horizontal
28940   {
28941     // check left of rect:
28942     bx = rect.left();
28943     by = rect.top();
28944     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
28945     if (gamma >= 0 && gamma <= rect.height())
28946       result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
28947   } else // line is skewed
28948   {
28949     QList<QCPVector2D> pointVectors;
28950     // check top of rect:
28951     bx = rect.left();
28952     by = rect.top();
28953     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
28954     if (gamma >= 0 && gamma <= rect.width())
28955       pointVectors.append(QCPVector2D(bx+gamma, by));
28956     // check bottom of rect:
28957     bx = rect.left();
28958     by = rect.bottom();
28959     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
28960     if (gamma >= 0 && gamma <= rect.width())
28961       pointVectors.append(QCPVector2D(bx+gamma, by));
28962     // check left of rect:
28963     bx = rect.left();
28964     by = rect.top();
28965     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
28966     if (gamma >= 0 && gamma <= rect.height())
28967       pointVectors.append(QCPVector2D(bx, by+gamma));
28968     // check right of rect:
28969     bx = rect.right();
28970     by = rect.top();
28971     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
28972     if (gamma >= 0 && gamma <= rect.height())
28973       pointVectors.append(QCPVector2D(bx, by+gamma));
28974     
28975     // evaluate points:
28976     if (pointVectors.size() == 2)
28977     {
28978       result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
28979     } else if (pointVectors.size() > 2)
28980     {
28981       // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
28982       double distSqrMax = 0;
28983       QCPVector2D pv1, pv2;
28984       for (int i=0; i<pointVectors.size()-1; ++i)
28985       {
28986         for (int k=i+1; k<pointVectors.size(); ++k)
28987         {
28988           double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
28989           if (distSqr > distSqrMax)
28990           {
28991             pv1 = pointVectors.at(i);
28992             pv2 = pointVectors.at(k);
28993             distSqrMax = distSqr;
28994           }
28995         }
28996       }
28997       result.setPoints(pv1.toPointF(), pv2.toPointF());
28998     }
28999   }
29000   return result;
29001 }
29002 
29003 /*! \internal
29004 
29005   Returns the pen that should be used for drawing lines. Returns mPen when the
29006   item is not selected and mSelectedPen when it is.
29007 */
29008 QPen QCPItemStraightLine::mainPen() const
29009 {
29010   return mSelected ? mSelectedPen : mPen;
29011 }
29012 /* end of 'src/items/item-straightline.cpp' */
29013 
29014 
29015 /* including file 'src/items/item-line.cpp' */
29016 /* modified 2021-03-29T02:30:44, size 8525  */
29017 
29018 ////////////////////////////////////////////////////////////////////////////////////////////////////
29019 //////////////////// QCPItemLine
29020 ////////////////////////////////////////////////////////////////////////////////////////////////////
29021 
29022 /*! \class QCPItemLine
29023   \brief A line from one point to another
29024 
29025   \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
29026 
29027   It has two positions, \a start and \a end, which define the end points of the line.
29028   
29029   With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
29030 */
29031 
29032 /*!
29033   Creates a line item and sets default values.
29034   
29035   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29036   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29037 */
29038 QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
29039   QCPAbstractItem(parentPlot),
29040   start(createPosition(QLatin1String("start"))),
29041   end(createPosition(QLatin1String("end")))
29042 {
29043   start->setCoords(0, 0);
29044   end->setCoords(1, 1);
29045   
29046   setPen(QPen(Qt::black));
29047   setSelectedPen(QPen(Qt::blue,2));
29048 }
29049 
29050 QCPItemLine::~QCPItemLine()
29051 {
29052 }
29053 
29054 /*!
29055   Sets the pen that will be used to draw the line
29056   
29057   \see setSelectedPen
29058 */
29059 void QCPItemLine::setPen(const QPen &pen)
29060 {
29061   mPen = pen;
29062 }
29063 
29064 /*!
29065   Sets the pen that will be used to draw the line when selected
29066   
29067   \see setPen, setSelected
29068 */
29069 void QCPItemLine::setSelectedPen(const QPen &pen)
29070 {
29071   mSelectedPen = pen;
29072 }
29073 
29074 /*!
29075   Sets the line ending style of the head. The head corresponds to the \a end position.
29076   
29077   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
29078   a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
29079   
29080   \see setTail
29081 */
29082 void QCPItemLine::setHead(const QCPLineEnding &head)
29083 {
29084   mHead = head;
29085 }
29086 
29087 /*!
29088   Sets the line ending style of the tail. The tail corresponds to the \a start position.
29089   
29090   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
29091   a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
29092   
29093   \see setHead
29094 */
29095 void QCPItemLine::setTail(const QCPLineEnding &tail)
29096 {
29097   mTail = tail;
29098 }
29099 
29100 /* inherits documentation from base class */
29101 double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29102 {
29103   Q_UNUSED(details)
29104   if (onlySelectable && !mSelectable)
29105     return -1;
29106   
29107   return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
29108 }
29109 
29110 /* inherits documentation from base class */
29111 void QCPItemLine::draw(QCPPainter *painter)
29112 {
29113   QCPVector2D startVec(start->pixelPosition());
29114   QCPVector2D endVec(end->pixelPosition());
29115   if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
29116     return;
29117   // get visible segment of straight line inside clipRect:
29118   int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance()));
29119   clipPad = qMax(clipPad, qCeil(mainPen().widthF()));
29120   QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
29121   // paint visible segment, if existent:
29122   if (!line.isNull())
29123   {
29124     painter->setPen(mainPen());
29125     painter->drawLine(line);
29126     painter->setBrush(Qt::SolidPattern);
29127     if (mTail.style() != QCPLineEnding::esNone)
29128       mTail.draw(painter, startVec, startVec-endVec);
29129     if (mHead.style() != QCPLineEnding::esNone)
29130       mHead.draw(painter, endVec, endVec-startVec);
29131   }
29132 }
29133 
29134 /*! \internal
29135 
29136   Returns the section of the line defined by \a start and \a end, that is visible in the specified
29137   \a rect.
29138   
29139   This is a helper function for \ref draw.
29140 */
29141 QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
29142 {
29143   bool containsStart = rect.contains(qRound(start.x()), qRound(start.y()));
29144   bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y()));
29145   if (containsStart && containsEnd)
29146     return {start.toPointF(), end.toPointF()};
29147   
29148   QCPVector2D base = start;
29149   QCPVector2D vec = end-start;
29150   double bx, by;
29151   double gamma, mu;
29152   QLineF result;
29153   QList<QCPVector2D> pointVectors;
29154 
29155   if (!qFuzzyIsNull(vec.y())) // line is not horizontal
29156   {
29157     // check top of rect:
29158     bx = rect.left();
29159     by = rect.top();
29160     mu = (by-base.y())/vec.y();
29161     if (mu >= 0 && mu <= 1)
29162     {
29163       gamma = base.x()-bx + mu*vec.x();
29164       if (gamma >= 0 && gamma <= rect.width())
29165         pointVectors.append(QCPVector2D(bx+gamma, by));
29166     }
29167     // check bottom of rect:
29168     bx = rect.left();
29169     by = rect.bottom();
29170     mu = (by-base.y())/vec.y();
29171     if (mu >= 0 && mu <= 1)
29172     {
29173       gamma = base.x()-bx + mu*vec.x();
29174       if (gamma >= 0 && gamma <= rect.width())
29175         pointVectors.append(QCPVector2D(bx+gamma, by));
29176     }
29177   }
29178   if (!qFuzzyIsNull(vec.x())) // line is not vertical
29179   {
29180     // check left of rect:
29181     bx = rect.left();
29182     by = rect.top();
29183     mu = (bx-base.x())/vec.x();
29184     if (mu >= 0 && mu <= 1)
29185     {
29186       gamma = base.y()-by + mu*vec.y();
29187       if (gamma >= 0 && gamma <= rect.height())
29188         pointVectors.append(QCPVector2D(bx, by+gamma));
29189     }
29190     // check right of rect:
29191     bx = rect.right();
29192     by = rect.top();
29193     mu = (bx-base.x())/vec.x();
29194     if (mu >= 0 && mu <= 1)
29195     {
29196       gamma = base.y()-by + mu*vec.y();
29197       if (gamma >= 0 && gamma <= rect.height())
29198         pointVectors.append(QCPVector2D(bx, by+gamma));
29199     }
29200   }
29201   
29202   if (containsStart)
29203     pointVectors.append(start);
29204   if (containsEnd)
29205     pointVectors.append(end);
29206   
29207   // evaluate points:
29208   if (pointVectors.size() == 2)
29209   {
29210     result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
29211   } else if (pointVectors.size() > 2)
29212   {
29213     // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
29214     double distSqrMax = 0;
29215     QCPVector2D pv1, pv2;
29216     for (int i=0; i<pointVectors.size()-1; ++i)
29217     {
29218       for (int k=i+1; k<pointVectors.size(); ++k)
29219       {
29220         double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
29221         if (distSqr > distSqrMax)
29222         {
29223           pv1 = pointVectors.at(i);
29224           pv2 = pointVectors.at(k);
29225           distSqrMax = distSqr;
29226         }
29227       }
29228     }
29229     result.setPoints(pv1.toPointF(), pv2.toPointF());
29230   }
29231   return result;
29232 }
29233 
29234 /*! \internal
29235 
29236   Returns the pen that should be used for drawing lines. Returns mPen when the
29237   item is not selected and mSelectedPen when it is.
29238 */
29239 QPen QCPItemLine::mainPen() const
29240 {
29241   return mSelected ? mSelectedPen : mPen;
29242 }
29243 /* end of 'src/items/item-line.cpp' */
29244 
29245 
29246 /* including file 'src/items/item-curve.cpp' */
29247 /* modified 2021-03-29T02:30:44, size 7273   */
29248 
29249 ////////////////////////////////////////////////////////////////////////////////////////////////////
29250 //////////////////// QCPItemCurve
29251 ////////////////////////////////////////////////////////////////////////////////////////////////////
29252 
29253 /*! \class QCPItemCurve
29254   \brief A curved line from one point to another
29255 
29256   \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
29257 
29258   It has four positions, \a start and \a end, which define the end points of the line, and two
29259   control points which define the direction the line exits from the start and the direction from
29260   which it approaches the end: \a startDir and \a endDir.
29261   
29262   With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
29263   arrow.
29264   
29265   Often it is desirable for the control points to stay at fixed relative positions to the start/end
29266   point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
29267   and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
29268 */
29269 
29270 /*!
29271   Creates a curve item and sets default values.
29272   
29273   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29274   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29275 */
29276 QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
29277   QCPAbstractItem(parentPlot),
29278   start(createPosition(QLatin1String("start"))),
29279   startDir(createPosition(QLatin1String("startDir"))),
29280   endDir(createPosition(QLatin1String("endDir"))),
29281   end(createPosition(QLatin1String("end")))
29282 {
29283   start->setCoords(0, 0);
29284   startDir->setCoords(0.5, 0);
29285   endDir->setCoords(0, 0.5);
29286   end->setCoords(1, 1);
29287   
29288   setPen(QPen(Qt::black));
29289   setSelectedPen(QPen(Qt::blue,2));
29290 }
29291 
29292 QCPItemCurve::~QCPItemCurve()
29293 {
29294 }
29295 
29296 /*!
29297   Sets the pen that will be used to draw the line
29298   
29299   \see setSelectedPen
29300 */
29301 void QCPItemCurve::setPen(const QPen &pen)
29302 {
29303   mPen = pen;
29304 }
29305 
29306 /*!
29307   Sets the pen that will be used to draw the line when selected
29308   
29309   \see setPen, setSelected
29310 */
29311 void QCPItemCurve::setSelectedPen(const QPen &pen)
29312 {
29313   mSelectedPen = pen;
29314 }
29315 
29316 /*!
29317   Sets the line ending style of the head. The head corresponds to the \a end position.
29318   
29319   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
29320   a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
29321   
29322   \see setTail
29323 */
29324 void QCPItemCurve::setHead(const QCPLineEnding &head)
29325 {
29326   mHead = head;
29327 }
29328 
29329 /*!
29330   Sets the line ending style of the tail. The tail corresponds to the \a start position.
29331   
29332   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
29333   a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
29334   
29335   \see setHead
29336 */
29337 void QCPItemCurve::setTail(const QCPLineEnding &tail)
29338 {
29339   mTail = tail;
29340 }
29341 
29342 /* inherits documentation from base class */
29343 double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29344 {
29345   Q_UNUSED(details)
29346   if (onlySelectable && !mSelectable)
29347     return -1;
29348   
29349   QPointF startVec(start->pixelPosition());
29350   QPointF startDirVec(startDir->pixelPosition());
29351   QPointF endDirVec(endDir->pixelPosition());
29352   QPointF endVec(end->pixelPosition());
29353 
29354   QPainterPath cubicPath(startVec);
29355   cubicPath.cubicTo(startDirVec, endDirVec, endVec);
29356   
29357   QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
29358   if (polygons.isEmpty())
29359     return -1;
29360   const QPolygonF polygon = polygons.first();
29361   QCPVector2D p(pos);
29362   double minDistSqr = (std::numeric_limits<double>::max)();
29363   for (int i=1; i<polygon.size(); ++i)
29364   {
29365     double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
29366     if (distSqr < minDistSqr)
29367       minDistSqr = distSqr;
29368   }
29369   return qSqrt(minDistSqr);
29370 }
29371 
29372 /* inherits documentation from base class */
29373 void QCPItemCurve::draw(QCPPainter *painter)
29374 {
29375   QCPVector2D startVec(start->pixelPosition());
29376   QCPVector2D startDirVec(startDir->pixelPosition());
29377   QCPVector2D endDirVec(endDir->pixelPosition());
29378   QCPVector2D endVec(end->pixelPosition());
29379   if ((endVec-startVec).length() > 1e10) // too large curves cause crash
29380     return;
29381 
29382   QPainterPath cubicPath(startVec.toPointF());
29383   cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
29384 
29385   // paint visible segment, if existent:
29386   const int clipEnlarge = qCeil(mainPen().widthF());
29387   QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
29388   QRect cubicRect = cubicPath.controlPointRect().toRect();
29389   if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
29390     cubicRect.adjust(0, 0, 1, 1);
29391   if (clip.intersects(cubicRect))
29392   {
29393     painter->setPen(mainPen());
29394     painter->drawPath(cubicPath);
29395     painter->setBrush(Qt::SolidPattern);
29396     if (mTail.style() != QCPLineEnding::esNone)
29397       mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
29398     if (mHead.style() != QCPLineEnding::esNone)
29399       mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
29400   }
29401 }
29402 
29403 /*! \internal
29404 
29405   Returns the pen that should be used for drawing lines. Returns mPen when the
29406   item is not selected and mSelectedPen when it is.
29407 */
29408 QPen QCPItemCurve::mainPen() const
29409 {
29410   return mSelected ? mSelectedPen : mPen;
29411 }
29412 /* end of 'src/items/item-curve.cpp' */
29413 
29414 
29415 /* including file 'src/items/item-rect.cpp' */
29416 /* modified 2021-03-29T02:30:44, size 6472  */
29417 
29418 ////////////////////////////////////////////////////////////////////////////////////////////////////
29419 //////////////////// QCPItemRect
29420 ////////////////////////////////////////////////////////////////////////////////////////////////////
29421 
29422 /*! \class QCPItemRect
29423   \brief A rectangle
29424 
29425   \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
29426 
29427   It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
29428 */
29429 
29430 /*!
29431   Creates a rectangle item and sets default values.
29432   
29433   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29434   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29435 */
29436 QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
29437   QCPAbstractItem(parentPlot),
29438   topLeft(createPosition(QLatin1String("topLeft"))),
29439   bottomRight(createPosition(QLatin1String("bottomRight"))),
29440   top(createAnchor(QLatin1String("top"), aiTop)),
29441   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
29442   right(createAnchor(QLatin1String("right"), aiRight)),
29443   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
29444   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
29445   left(createAnchor(QLatin1String("left"), aiLeft))
29446 {
29447   topLeft->setCoords(0, 1);
29448   bottomRight->setCoords(1, 0);
29449   
29450   setPen(QPen(Qt::black));
29451   setSelectedPen(QPen(Qt::blue,2));
29452   setBrush(Qt::NoBrush);
29453   setSelectedBrush(Qt::NoBrush);
29454 }
29455 
29456 QCPItemRect::~QCPItemRect()
29457 {
29458 }
29459 
29460 /*!
29461   Sets the pen that will be used to draw the line of the rectangle
29462   
29463   \see setSelectedPen, setBrush
29464 */
29465 void QCPItemRect::setPen(const QPen &pen)
29466 {
29467   mPen = pen;
29468 }
29469 
29470 /*!
29471   Sets the pen that will be used to draw the line of the rectangle when selected
29472   
29473   \see setPen, setSelected
29474 */
29475 void QCPItemRect::setSelectedPen(const QPen &pen)
29476 {
29477   mSelectedPen = pen;
29478 }
29479 
29480 /*!
29481   Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
29482   Qt::NoBrush.
29483   
29484   \see setSelectedBrush, setPen
29485 */
29486 void QCPItemRect::setBrush(const QBrush &brush)
29487 {
29488   mBrush = brush;
29489 }
29490 
29491 /*!
29492   Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
29493   brush to Qt::NoBrush.
29494   
29495   \see setBrush
29496 */
29497 void QCPItemRect::setSelectedBrush(const QBrush &brush)
29498 {
29499   mSelectedBrush = brush;
29500 }
29501 
29502 /* inherits documentation from base class */
29503 double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29504 {
29505   Q_UNUSED(details)
29506   if (onlySelectable && !mSelectable)
29507     return -1;
29508   
29509   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
29510   bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
29511   return rectDistance(rect, pos, filledRect);
29512 }
29513 
29514 /* inherits documentation from base class */
29515 void QCPItemRect::draw(QCPPainter *painter)
29516 {
29517   QPointF p1 = topLeft->pixelPosition();
29518   QPointF p2 = bottomRight->pixelPosition();
29519   if (p1.toPoint() == p2.toPoint())
29520     return;
29521   QRectF rect = QRectF(p1, p2).normalized();
29522   double clipPad = mainPen().widthF();
29523   QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
29524   if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
29525   {
29526     painter->setPen(mainPen());
29527     painter->setBrush(mainBrush());
29528     painter->drawRect(rect);
29529   }
29530 }
29531 
29532 /* inherits documentation from base class */
29533 QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
29534 {
29535   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
29536   switch (anchorId)
29537   {
29538     case aiTop:         return (rect.topLeft()+rect.topRight())*0.5;
29539     case aiTopRight:    return rect.topRight();
29540     case aiRight:       return (rect.topRight()+rect.bottomRight())*0.5;
29541     case aiBottom:      return (rect.bottomLeft()+rect.bottomRight())*0.5;
29542     case aiBottomLeft:  return rect.bottomLeft();
29543     case aiLeft:        return (rect.topLeft()+rect.bottomLeft())*0.5;
29544   }
29545   
29546   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
29547   return {};
29548 }
29549 
29550 /*! \internal
29551 
29552   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
29553   and mSelectedPen when it is.
29554 */
29555 QPen QCPItemRect::mainPen() const
29556 {
29557   return mSelected ? mSelectedPen : mPen;
29558 }
29559 
29560 /*! \internal
29561 
29562   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
29563   is not selected and mSelectedBrush when it is.
29564 */
29565 QBrush QCPItemRect::mainBrush() const
29566 {
29567   return mSelected ? mSelectedBrush : mBrush;
29568 }
29569 /* end of 'src/items/item-rect.cpp' */
29570 
29571 
29572 /* including file 'src/items/item-text.cpp' */
29573 /* modified 2021-03-29T02:30:44, size 13335 */
29574 
29575 ////////////////////////////////////////////////////////////////////////////////////////////////////
29576 //////////////////// QCPItemText
29577 ////////////////////////////////////////////////////////////////////////////////////////////////////
29578 
29579 /*! \class QCPItemText
29580   \brief A text label
29581 
29582   \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
29583 
29584   Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
29585   The latter controls which part of the text rect shall be aligned with \a position.
29586   
29587   The text alignment itself (i.e. left, center, right) can be controlled with \ref
29588   setTextAlignment.
29589   
29590   The text may be rotated around the \a position point with \ref setRotation.
29591 */
29592 
29593 /*!
29594   Creates a text item and sets default values.
29595   
29596   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29597   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29598 */
29599 QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
29600   QCPAbstractItem(parentPlot),
29601   position(createPosition(QLatin1String("position"))),
29602   topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
29603   top(createAnchor(QLatin1String("top"), aiTop)),
29604   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
29605   right(createAnchor(QLatin1String("right"), aiRight)),
29606   bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
29607   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
29608   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
29609   left(createAnchor(QLatin1String("left"), aiLeft)),
29610   mText(QLatin1String("text")),
29611   mPositionAlignment(Qt::AlignCenter),
29612   mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
29613   mRotation(0)
29614 {
29615   position->setCoords(0, 0);
29616   
29617   setPen(Qt::NoPen);
29618   setSelectedPen(Qt::NoPen);
29619   setBrush(Qt::NoBrush);
29620   setSelectedBrush(Qt::NoBrush);
29621   setColor(Qt::black);
29622   setSelectedColor(Qt::blue);
29623 }
29624 
29625 QCPItemText::~QCPItemText()
29626 {
29627 }
29628 
29629 /*!
29630   Sets the color of the text.
29631 */
29632 void QCPItemText::setColor(const QColor &color)
29633 {
29634   mColor = color;
29635 }
29636 
29637 /*!
29638   Sets the color of the text that will be used when the item is selected.
29639 */
29640 void QCPItemText::setSelectedColor(const QColor &color)
29641 {
29642   mSelectedColor = color;
29643 }
29644 
29645 /*!
29646   Sets the pen that will be used do draw a rectangular border around the text. To disable the
29647   border, set \a pen to Qt::NoPen.
29648   
29649   \see setSelectedPen, setBrush, setPadding
29650 */
29651 void QCPItemText::setPen(const QPen &pen)
29652 {
29653   mPen = pen;
29654 }
29655 
29656 /*!
29657   Sets the pen that will be used do draw a rectangular border around the text, when the item is
29658   selected. To disable the border, set \a pen to Qt::NoPen.
29659   
29660   \see setPen
29661 */
29662 void QCPItemText::setSelectedPen(const QPen &pen)
29663 {
29664   mSelectedPen = pen;
29665 }
29666 
29667 /*!
29668   Sets the brush that will be used do fill the background of the text. To disable the
29669   background, set \a brush to Qt::NoBrush.
29670   
29671   \see setSelectedBrush, setPen, setPadding
29672 */
29673 void QCPItemText::setBrush(const QBrush &brush)
29674 {
29675   mBrush = brush;
29676 }
29677 
29678 /*!
29679   Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
29680   background, set \a brush to Qt::NoBrush.
29681   
29682   \see setBrush
29683 */
29684 void QCPItemText::setSelectedBrush(const QBrush &brush)
29685 {
29686   mSelectedBrush = brush;
29687 }
29688 
29689 /*!
29690   Sets the font of the text.
29691   
29692   \see setSelectedFont, setColor
29693 */
29694 void QCPItemText::setFont(const QFont &font)
29695 {
29696   mFont = font;
29697 }
29698 
29699 /*!
29700   Sets the font of the text that will be used when the item is selected.
29701   
29702   \see setFont
29703 */
29704 void QCPItemText::setSelectedFont(const QFont &font)
29705 {
29706   mSelectedFont = font;
29707 }
29708 
29709 /*!
29710   Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
29711   character, e.g. '\n'.
29712   
29713   \see setFont, setColor, setTextAlignment
29714 */
29715 void QCPItemText::setText(const QString &text)
29716 {
29717   mText = text;
29718 }
29719 
29720 /*!
29721   Sets which point of the text rect shall be aligned with \a position.
29722   
29723   Examples:
29724   \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
29725   that the top of the text rect will be horizontally centered on \a position.
29726   \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
29727   bottom left corner of the text rect.
29728   
29729   If you want to control the alignment of (multi-lined) text within the text rect, use \ref
29730   setTextAlignment.
29731 */
29732 void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
29733 {
29734   mPositionAlignment = alignment;
29735 }
29736 
29737 /*!
29738   Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
29739 */
29740 void QCPItemText::setTextAlignment(Qt::Alignment alignment)
29741 {
29742   mTextAlignment = alignment;
29743 }
29744 
29745 /*!
29746   Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
29747   around \a position.
29748 */
29749 void QCPItemText::setRotation(double degrees)
29750 {
29751   mRotation = degrees;
29752 }
29753 
29754 /*!
29755   Sets the distance between the border of the text rectangle and the text. The appearance (and
29756   visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
29757 */
29758 void QCPItemText::setPadding(const QMargins &padding)
29759 {
29760   mPadding = padding;
29761 }
29762 
29763 /* inherits documentation from base class */
29764 double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29765 {
29766   Q_UNUSED(details)
29767   if (onlySelectable && !mSelectable)
29768     return -1;
29769   
29770   // The rect may be rotated, so we transform the actual clicked pos to the rotated
29771   // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
29772   QPointF positionPixels(position->pixelPosition());
29773   QTransform inputTransform;
29774   inputTransform.translate(positionPixels.x(), positionPixels.y());
29775   inputTransform.rotate(-mRotation);
29776   inputTransform.translate(-positionPixels.x(), -positionPixels.y());
29777   QPointF rotatedPos = inputTransform.map(pos);
29778   QFontMetrics fontMetrics(mFont);
29779   QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
29780   QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
29781   QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
29782   textBoxRect.moveTopLeft(textPos.toPoint());
29783 
29784   return rectDistance(textBoxRect, rotatedPos, true);
29785 }
29786 
29787 /* inherits documentation from base class */
29788 void QCPItemText::draw(QCPPainter *painter)
29789 {
29790   QPointF pos(position->pixelPosition());
29791   QTransform transform = painter->transform();
29792   transform.translate(pos.x(), pos.y());
29793   if (!qFuzzyIsNull(mRotation))
29794     transform.rotate(mRotation);
29795   painter->setFont(mainFont());
29796   QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
29797   QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
29798   QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
29799   textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
29800   textBoxRect.moveTopLeft(textPos.toPoint());
29801   int clipPad = qCeil(mainPen().widthF());
29802   QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
29803   if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
29804   {
29805     painter->setTransform(transform);
29806     if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
29807         (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
29808     {
29809       painter->setPen(mainPen());
29810       painter->setBrush(mainBrush());
29811       painter->drawRect(textBoxRect);
29812     }
29813     painter->setBrush(Qt::NoBrush);
29814     painter->setPen(QPen(mainColor()));
29815     painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
29816   }
29817 }
29818 
29819 /* inherits documentation from base class */
29820 QPointF QCPItemText::anchorPixelPosition(int anchorId) const
29821 {
29822   // get actual rect points (pretty much copied from draw function):
29823   QPointF pos(position->pixelPosition());
29824   QTransform transform;
29825   transform.translate(pos.x(), pos.y());
29826   if (!qFuzzyIsNull(mRotation))
29827     transform.rotate(mRotation);
29828   QFontMetrics fontMetrics(mainFont());
29829   QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
29830   QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
29831   QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
29832   textBoxRect.moveTopLeft(textPos.toPoint());
29833   QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
29834   
29835   switch (anchorId)
29836   {
29837     case aiTopLeft:     return rectPoly.at(0);
29838     case aiTop:         return (rectPoly.at(0)+rectPoly.at(1))*0.5;
29839     case aiTopRight:    return rectPoly.at(1);
29840     case aiRight:       return (rectPoly.at(1)+rectPoly.at(2))*0.5;
29841     case aiBottomRight: return rectPoly.at(2);
29842     case aiBottom:      return (rectPoly.at(2)+rectPoly.at(3))*0.5;
29843     case aiBottomLeft:  return rectPoly.at(3);
29844     case aiLeft:        return (rectPoly.at(3)+rectPoly.at(0))*0.5;
29845   }
29846   
29847   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
29848   return {};
29849 }
29850 
29851 /*! \internal
29852   
29853   Returns the point that must be given to the QPainter::drawText function (which expects the top
29854   left point of the text rect), according to the position \a pos, the text bounding box \a rect and
29855   the requested \a positionAlignment.
29856   
29857   For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
29858   will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
29859   drawn at that point, the lower left corner of the resulting text rect is at \a pos.
29860 */
29861 QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
29862 {
29863   if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
29864     return pos;
29865   
29866   QPointF result = pos; // start at top left
29867   if (positionAlignment.testFlag(Qt::AlignHCenter))
29868     result.rx() -= rect.width()/2.0;
29869   else if (positionAlignment.testFlag(Qt::AlignRight))
29870     result.rx() -= rect.width();
29871   if (positionAlignment.testFlag(Qt::AlignVCenter))
29872     result.ry() -= rect.height()/2.0;
29873   else if (positionAlignment.testFlag(Qt::AlignBottom))
29874     result.ry() -= rect.height();
29875   return result;
29876 }
29877 
29878 /*! \internal
29879 
29880   Returns the font that should be used for drawing text. Returns mFont when the item is not selected
29881   and mSelectedFont when it is.
29882 */
29883 QFont QCPItemText::mainFont() const
29884 {
29885   return mSelected ? mSelectedFont : mFont;
29886 }
29887 
29888 /*! \internal
29889 
29890   Returns the color that should be used for drawing text. Returns mColor when the item is not
29891   selected and mSelectedColor when it is.
29892 */
29893 QColor QCPItemText::mainColor() const
29894 {
29895   return mSelected ? mSelectedColor : mColor;
29896 }
29897 
29898 /*! \internal
29899 
29900   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
29901   and mSelectedPen when it is.
29902 */
29903 QPen QCPItemText::mainPen() const
29904 {
29905   return mSelected ? mSelectedPen : mPen;
29906 }
29907 
29908 /*! \internal
29909 
29910   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
29911   is not selected and mSelectedBrush when it is.
29912 */
29913 QBrush QCPItemText::mainBrush() const
29914 {
29915   return mSelected ? mSelectedBrush : mBrush;
29916 }
29917 /* end of 'src/items/item-text.cpp' */
29918 
29919 
29920 /* including file 'src/items/item-ellipse.cpp' */
29921 /* modified 2021-03-29T02:30:44, size 7881     */
29922 
29923 ////////////////////////////////////////////////////////////////////////////////////////////////////
29924 //////////////////// QCPItemEllipse
29925 ////////////////////////////////////////////////////////////////////////////////////////////////////
29926 
29927 /*! \class QCPItemEllipse
29928   \brief An ellipse
29929 
29930   \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
29931 
29932   It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
29933 */
29934 
29935 /*!
29936   Creates an ellipse item and sets default values.
29937   
29938   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29939   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29940 */
29941 QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
29942   QCPAbstractItem(parentPlot),
29943   topLeft(createPosition(QLatin1String("topLeft"))),
29944   bottomRight(createPosition(QLatin1String("bottomRight"))),
29945   topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
29946   top(createAnchor(QLatin1String("top"), aiTop)),
29947   topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
29948   right(createAnchor(QLatin1String("right"), aiRight)),
29949   bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
29950   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
29951   bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
29952   left(createAnchor(QLatin1String("left"), aiLeft)),
29953   center(createAnchor(QLatin1String("center"), aiCenter))
29954 {
29955   topLeft->setCoords(0, 1);
29956   bottomRight->setCoords(1, 0);
29957   
29958   setPen(QPen(Qt::black));
29959   setSelectedPen(QPen(Qt::blue, 2));
29960   setBrush(Qt::NoBrush);
29961   setSelectedBrush(Qt::NoBrush);
29962 }
29963 
29964 QCPItemEllipse::~QCPItemEllipse()
29965 {
29966 }
29967 
29968 /*!
29969   Sets the pen that will be used to draw the line of the ellipse
29970   
29971   \see setSelectedPen, setBrush
29972 */
29973 void QCPItemEllipse::setPen(const QPen &pen)
29974 {
29975   mPen = pen;
29976 }
29977 
29978 /*!
29979   Sets the pen that will be used to draw the line of the ellipse when selected
29980   
29981   \see setPen, setSelected
29982 */
29983 void QCPItemEllipse::setSelectedPen(const QPen &pen)
29984 {
29985   mSelectedPen = pen;
29986 }
29987 
29988 /*!
29989   Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
29990   Qt::NoBrush.
29991   
29992   \see setSelectedBrush, setPen
29993 */
29994 void QCPItemEllipse::setBrush(const QBrush &brush)
29995 {
29996   mBrush = brush;
29997 }
29998 
29999 /*!
30000   Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
30001   brush to Qt::NoBrush.
30002   
30003   \see setBrush
30004 */
30005 void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
30006 {
30007   mSelectedBrush = brush;
30008 }
30009 
30010 /* inherits documentation from base class */
30011 double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
30012 {
30013   Q_UNUSED(details)
30014   if (onlySelectable && !mSelectable)
30015     return -1;
30016   
30017   QPointF p1 = topLeft->pixelPosition();
30018   QPointF p2 = bottomRight->pixelPosition();
30019   QPointF center((p1+p2)/2.0);
30020   double a = qAbs(p1.x()-p2.x())/2.0;
30021   double b = qAbs(p1.y()-p2.y())/2.0;
30022   double x = pos.x()-center.x();
30023   double y = pos.y()-center.y();
30024   
30025   // distance to border:
30026   double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
30027   double result = qAbs(c-1)*qSqrt(x*x+y*y);
30028   // filled ellipse, allow click inside to count as hit:
30029   if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
30030   {
30031     if (x*x/(a*a) + y*y/(b*b) <= 1)
30032       result = mParentPlot->selectionTolerance()*0.99;
30033   }
30034   return result;
30035 }
30036 
30037 /* inherits documentation from base class */
30038 void QCPItemEllipse::draw(QCPPainter *painter)
30039 {
30040   QPointF p1 = topLeft->pixelPosition();
30041   QPointF p2 = bottomRight->pixelPosition();
30042   if (p1.toPoint() == p2.toPoint())
30043     return;
30044   QRectF ellipseRect = QRectF(p1, p2).normalized();
30045   const int clipEnlarge = qCeil(mainPen().widthF());
30046   QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
30047   if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
30048   {
30049     painter->setPen(mainPen());
30050     painter->setBrush(mainBrush());
30051 #ifdef __EXCEPTIONS
30052     try // drawEllipse sometimes throws exceptions if ellipse is too big
30053     {
30054 #endif
30055       painter->drawEllipse(ellipseRect);
30056 #ifdef __EXCEPTIONS
30057     } catch (...)
30058     {
30059       qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
30060       setVisible(false);
30061     }
30062 #endif
30063   }
30064 }
30065 
30066 /* inherits documentation from base class */
30067 QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
30068 {
30069   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
30070   switch (anchorId)
30071   {
30072     case aiTopLeftRim:     return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
30073     case aiTop:            return (rect.topLeft()+rect.topRight())*0.5;
30074     case aiTopRightRim:    return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
30075     case aiRight:          return (rect.topRight()+rect.bottomRight())*0.5;
30076     case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
30077     case aiBottom:         return (rect.bottomLeft()+rect.bottomRight())*0.5;
30078     case aiBottomLeftRim:  return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
30079     case aiLeft:           return (rect.topLeft()+rect.bottomLeft())*0.5;
30080     case aiCenter:         return (rect.topLeft()+rect.bottomRight())*0.5;
30081   }
30082   
30083   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
30084   return {};
30085 }
30086 
30087 /*! \internal
30088 
30089   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
30090   and mSelectedPen when it is.
30091 */
30092 QPen QCPItemEllipse::mainPen() const
30093 {
30094   return mSelected ? mSelectedPen : mPen;
30095 }
30096 
30097 /*! \internal
30098 
30099   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
30100   is not selected and mSelectedBrush when it is.
30101 */
30102 QBrush QCPItemEllipse::mainBrush() const
30103 {
30104   return mSelected ? mSelectedBrush : mBrush;
30105 }
30106 /* end of 'src/items/item-ellipse.cpp' */
30107 
30108 
30109 /* including file 'src/items/item-pixmap.cpp' */
30110 /* modified 2021-03-29T02:30:44, size 10622   */
30111 
30112 ////////////////////////////////////////////////////////////////////////////////////////////////////
30113 //////////////////// QCPItemPixmap
30114 ////////////////////////////////////////////////////////////////////////////////////////////////////
30115 
30116 /*! \class QCPItemPixmap
30117   \brief An arbitrary pixmap
30118 
30119   \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
30120 
30121   It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
30122   be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
30123   fit the rectangle or be drawn aligned to the topLeft position.
30124   
30125   If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
30126   on the right side of the example image), the pixmap will be flipped in the respective
30127   orientations.
30128 */
30129 
30130 /*!
30131   Creates a rectangle item and sets default values.
30132   
30133   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
30134   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
30135 */
30136 QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
30137   QCPAbstractItem(parentPlot),
30138   topLeft(createPosition(QLatin1String("topLeft"))),
30139   bottomRight(createPosition(QLatin1String("bottomRight"))),
30140   top(createAnchor(QLatin1String("top"), aiTop)),
30141   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
30142   right(createAnchor(QLatin1String("right"), aiRight)),
30143   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
30144   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
30145   left(createAnchor(QLatin1String("left"), aiLeft)),
30146   mScaled(false),
30147   mScaledPixmapInvalidated(true),
30148   mAspectRatioMode(Qt::KeepAspectRatio),
30149   mTransformationMode(Qt::SmoothTransformation)
30150 {
30151   topLeft->setCoords(0, 1);
30152   bottomRight->setCoords(1, 0);
30153   
30154   setPen(Qt::NoPen);
30155   setSelectedPen(QPen(Qt::blue));
30156 }
30157 
30158 QCPItemPixmap::~QCPItemPixmap()
30159 {
30160 }
30161 
30162 /*!
30163   Sets the pixmap that will be displayed.
30164 */
30165 void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
30166 {
30167   mPixmap = pixmap;
30168   mScaledPixmapInvalidated = true;
30169   if (mPixmap.isNull())
30170     qDebug() << Q_FUNC_INFO << "pixmap is null";
30171 }
30172 
30173 /*!
30174   Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
30175   bottomRight positions.
30176 */
30177 void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
30178 {
30179   mScaled = scaled;
30180   mAspectRatioMode = aspectRatioMode;
30181   mTransformationMode = transformationMode;
30182   mScaledPixmapInvalidated = true;
30183 }
30184 
30185 /*!
30186   Sets the pen that will be used to draw a border around the pixmap.
30187   
30188   \see setSelectedPen, setBrush
30189 */
30190 void QCPItemPixmap::setPen(const QPen &pen)
30191 {
30192   mPen = pen;
30193 }
30194 
30195 /*!
30196   Sets the pen that will be used to draw a border around the pixmap when selected
30197   
30198   \see setPen, setSelected
30199 */
30200 void QCPItemPixmap::setSelectedPen(const QPen &pen)
30201 {
30202   mSelectedPen = pen;
30203 }
30204 
30205 /* inherits documentation from base class */
30206 double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
30207 {
30208   Q_UNUSED(details)
30209   if (onlySelectable && !mSelectable)
30210     return -1;
30211   
30212   return rectDistance(getFinalRect(), pos, true);
30213 }
30214 
30215 /* inherits documentation from base class */
30216 void QCPItemPixmap::draw(QCPPainter *painter)
30217 {
30218   bool flipHorz = false;
30219   bool flipVert = false;
30220   QRect rect = getFinalRect(&flipHorz, &flipVert);
30221   int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF());
30222   QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
30223   if (boundingRect.intersects(clipRect()))
30224   {
30225     updateScaledPixmap(rect, flipHorz, flipVert);
30226     painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
30227     QPen pen = mainPen();
30228     if (pen.style() != Qt::NoPen)
30229     {
30230       painter->setPen(pen);
30231       painter->setBrush(Qt::NoBrush);
30232       painter->drawRect(rect);
30233     }
30234   }
30235 }
30236 
30237 /* inherits documentation from base class */
30238 QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
30239 {
30240   bool flipHorz = false;
30241   bool flipVert = false;
30242   QRect rect = getFinalRect(&flipHorz, &flipVert);
30243   // we actually want denormal rects (negative width/height) here, so restore
30244   // the flipped state:
30245   if (flipHorz)
30246     rect.adjust(rect.width(), 0, -rect.width(), 0);
30247   if (flipVert)
30248     rect.adjust(0, rect.height(), 0, -rect.height());
30249   
30250   switch (anchorId)
30251   {
30252     case aiTop:         return (rect.topLeft()+rect.topRight())*0.5;
30253     case aiTopRight:    return rect.topRight();
30254     case aiRight:       return (rect.topRight()+rect.bottomRight())*0.5;
30255     case aiBottom:      return (rect.bottomLeft()+rect.bottomRight())*0.5;
30256     case aiBottomLeft:  return rect.bottomLeft();
30257     case aiLeft:        return (rect.topLeft()+rect.bottomLeft())*0.5;
30258   }
30259   
30260   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
30261   return {};
30262 }
30263 
30264 /*! \internal
30265   
30266   Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
30267   parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
30268   horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
30269   bottomRight.)
30270   
30271   This function only creates the scaled pixmap when the buffered pixmap has a different size than
30272   the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
30273   not cause expensive rescaling every time.
30274   
30275   If scaling is disabled, sets mScaledPixmap to a null QPixmap.
30276 */
30277 void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
30278 {
30279   if (mPixmap.isNull())
30280     return;
30281   
30282   if (mScaled)
30283   {
30284 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
30285     double devicePixelRatio = mPixmap.devicePixelRatio();
30286 #else
30287     double devicePixelRatio = 1.0;
30288 #endif
30289     if (finalRect.isNull())
30290       finalRect = getFinalRect(&flipHorz, &flipVert);
30291     if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
30292     {
30293       mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
30294       if (flipHorz || flipVert)
30295         mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
30296 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
30297       mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
30298 #endif
30299     }
30300   } else if (!mScaledPixmap.isNull())
30301     mScaledPixmap = QPixmap();
30302   mScaledPixmapInvalidated = false;
30303 }
30304 
30305 /*! \internal
30306   
30307   Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
30308   and scaling settings.
30309   
30310   The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
30311   flipped horizontally or vertically in the returned rect. (The returned rect itself is always
30312   normalized, i.e. the top left corner of the rect is actually further to the top/left than the
30313   bottom right corner). This is the case when the item position \a topLeft is further to the
30314   bottom/right than \a bottomRight.
30315   
30316   If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
30317   aligned with the item position \a topLeft. The position \a bottomRight is ignored.
30318 */
30319 QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
30320 {
30321   QRect result;
30322   bool flipHorz = false;
30323   bool flipVert = false;
30324   QPoint p1 = topLeft->pixelPosition().toPoint();
30325   QPoint p2 = bottomRight->pixelPosition().toPoint();
30326   if (p1 == p2)
30327     return {p1, QSize(0, 0)};
30328   if (mScaled)
30329   {
30330     QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
30331     QPoint topLeft = p1;
30332     if (newSize.width() < 0)
30333     {
30334       flipHorz = true;
30335       newSize.rwidth() *= -1;
30336       topLeft.setX(p2.x());
30337     }
30338     if (newSize.height() < 0)
30339     {
30340       flipVert = true;
30341       newSize.rheight() *= -1;
30342       topLeft.setY(p2.y());
30343     }
30344     QSize scaledSize = mPixmap.size();
30345 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
30346     scaledSize /= mPixmap.devicePixelRatio();
30347     scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
30348 #else
30349     scaledSize.scale(newSize, mAspectRatioMode);
30350 #endif
30351     result = QRect(topLeft, scaledSize);
30352   } else
30353   {
30354 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
30355     result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
30356 #else
30357     result = QRect(p1, mPixmap.size());
30358 #endif
30359   }
30360   if (flippedHorz)
30361     *flippedHorz = flipHorz;
30362   if (flippedVert)
30363     *flippedVert = flipVert;
30364   return result;
30365 }
30366 
30367 /*! \internal
30368 
30369   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
30370   and mSelectedPen when it is.
30371 */
30372 QPen QCPItemPixmap::mainPen() const
30373 {
30374   return mSelected ? mSelectedPen : mPen;
30375 }
30376 /* end of 'src/items/item-pixmap.cpp' */
30377 
30378 
30379 /* including file 'src/items/item-tracer.cpp' */
30380 /* modified 2021-03-29T02:30:44, size 14645   */
30381 
30382 ////////////////////////////////////////////////////////////////////////////////////////////////////
30383 //////////////////// QCPItemTracer
30384 ////////////////////////////////////////////////////////////////////////////////////////////////////
30385 
30386 /*! \class QCPItemTracer
30387   \brief Item that sticks to QCPGraph data points
30388 
30389   \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
30390 
30391   The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
30392   the coordinate axes of the graph and update its \a position to be on the graph's data. This means
30393   the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
30394   QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
30395   position will have no effect because they will be overriden in the next redraw (this is when the
30396   coordinate update happens).
30397   
30398   If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
30399   stay at the corresponding end of the graph.
30400   
30401   With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
30402   points or whether it interpolates data points linearly, if given a key that lies between two data
30403   points of the graph.
30404   
30405   The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
30406   have no own visual appearance (set the style to \ref tsNone), and just connect other item
30407   positions to the tracer \a position (used as an anchor) via \ref
30408   QCPItemPosition::setParentAnchor.
30409   
30410   \note The tracer position is only automatically updated upon redraws. So when the data of the
30411   graph changes and immediately afterwards (without a redraw) the position coordinates of the
30412   tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
30413   updatePosition must be called manually, prior to reading the tracer coordinates.
30414 */
30415 
30416 /*!
30417   Creates a tracer item and sets default values.
30418   
30419   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
30420   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
30421 */
30422 QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
30423   QCPAbstractItem(parentPlot),
30424   position(createPosition(QLatin1String("position"))),
30425   mSize(6),
30426   mStyle(tsCrosshair),
30427   mGraph(nullptr),
30428   mGraphKey(0),
30429   mInterpolating(false)
30430 {
30431   position->setCoords(0, 0);
30432 
30433   setBrush(Qt::NoBrush);
30434   setSelectedBrush(Qt::NoBrush);
30435   setPen(QPen(Qt::black));
30436   setSelectedPen(QPen(Qt::blue, 2));
30437 }
30438 
30439 QCPItemTracer::~QCPItemTracer()
30440 {
30441 }
30442 
30443 /*!
30444   Sets the pen that will be used to draw the line of the tracer
30445   
30446   \see setSelectedPen, setBrush
30447 */
30448 void QCPItemTracer::setPen(const QPen &pen)
30449 {
30450   mPen = pen;
30451 }
30452 
30453 /*!
30454   Sets the pen that will be used to draw the line of the tracer when selected
30455   
30456   \see setPen, setSelected
30457 */
30458 void QCPItemTracer::setSelectedPen(const QPen &pen)
30459 {
30460   mSelectedPen = pen;
30461 }
30462 
30463 /*!
30464   Sets the brush that will be used to draw any fills of the tracer
30465   
30466   \see setSelectedBrush, setPen
30467 */
30468 void QCPItemTracer::setBrush(const QBrush &brush)
30469 {
30470   mBrush = brush;
30471 }
30472 
30473 /*!
30474   Sets the brush that will be used to draw any fills of the tracer, when selected.
30475   
30476   \see setBrush, setSelected
30477 */
30478 void QCPItemTracer::setSelectedBrush(const QBrush &brush)
30479 {
30480   mSelectedBrush = brush;
30481 }
30482 
30483 /*!
30484   Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
30485   does, \ref tsCrosshair does not).
30486 */
30487 void QCPItemTracer::setSize(double size)
30488 {
30489   mSize = size;
30490 }
30491 
30492 /*!
30493   Sets the style/visual appearance of the tracer.
30494   
30495   If you only want to use the tracer \a position as an anchor for other items, set \a style to
30496   \ref tsNone.
30497 */
30498 void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
30499 {
30500   mStyle = style;
30501 }
30502 
30503 /*!
30504   Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
30505   QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
30506   
30507   To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
30508   placed freely like any other item position. This is the state the tracer will assume when its
30509   graph gets deleted while still attached to it.
30510   
30511   \see setGraphKey
30512 */
30513 void QCPItemTracer::setGraph(QCPGraph *graph)
30514 {
30515   if (graph)
30516   {
30517     if (graph->parentPlot() == mParentPlot)
30518     {
30519       position->setType(QCPItemPosition::ptPlotCoords);
30520       position->setAxes(graph->keyAxis(), graph->valueAxis());
30521       mGraph = graph;
30522       updatePosition();
30523     } else
30524       qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
30525   } else
30526   {
30527     mGraph = nullptr;
30528   }
30529 }
30530 
30531 /*!
30532   Sets the key of the graph's data point the tracer will be positioned at. This is the only free
30533   coordinate of a tracer when attached to a graph.
30534   
30535   Depending on \ref setInterpolating, the tracer will be either positioned on the data point
30536   closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
30537   
30538   \see setGraph, setInterpolating
30539 */
30540 void QCPItemTracer::setGraphKey(double key)
30541 {
30542   mGraphKey = key;
30543 }
30544 
30545 /*!
30546   Sets whether the value of the graph's data points shall be interpolated, when positioning the
30547   tracer.
30548   
30549   If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
30550   the data point of the graph which is closest to the key, but which is not necessarily exactly
30551   there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
30552   the appropriate value will be interpolated from the graph's data points linearly.
30553   
30554   \see setGraph, setGraphKey
30555 */
30556 void QCPItemTracer::setInterpolating(bool enabled)
30557 {
30558   mInterpolating = enabled;
30559 }
30560 
30561 /* inherits documentation from base class */
30562 double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
30563 {
30564   Q_UNUSED(details)
30565   if (onlySelectable && !mSelectable)
30566     return -1;
30567 
30568   QPointF center(position->pixelPosition());
30569   double w = mSize/2.0;
30570   QRect clip = clipRect();
30571   switch (mStyle)
30572   {
30573     case tsNone: return -1;
30574     case tsPlus:
30575     {
30576       if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30577         return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
30578                           QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
30579       break;
30580     }
30581     case tsCrosshair:
30582     {
30583       return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
30584                         QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
30585     }
30586     case tsCircle:
30587     {
30588       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30589       {
30590         // distance to border:
30591         double centerDist = QCPVector2D(center-pos).length();
30592         double circleLine = w;
30593         double result = qAbs(centerDist-circleLine);
30594         // filled ellipse, allow click inside to count as hit:
30595         if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
30596         {
30597           if (centerDist <= circleLine)
30598             result = mParentPlot->selectionTolerance()*0.99;
30599         }
30600         return result;
30601       }
30602       break;
30603     }
30604     case tsSquare:
30605     {
30606       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30607       {
30608         QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
30609         bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
30610         return rectDistance(rect, pos, filledRect);
30611       }
30612       break;
30613     }
30614   }
30615   return -1;
30616 }
30617 
30618 /* inherits documentation from base class */
30619 void QCPItemTracer::draw(QCPPainter *painter)
30620 {
30621   updatePosition();
30622   if (mStyle == tsNone)
30623     return;
30624 
30625   painter->setPen(mainPen());
30626   painter->setBrush(mainBrush());
30627   QPointF center(position->pixelPosition());
30628   double w = mSize/2.0;
30629   QRect clip = clipRect();
30630   switch (mStyle)
30631   {
30632     case tsNone: return;
30633     case tsPlus:
30634     {
30635       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30636       {
30637         painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
30638         painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
30639       }
30640       break;
30641     }
30642     case tsCrosshair:
30643     {
30644       if (center.y() > clip.top() && center.y() < clip.bottom())
30645         painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
30646       if (center.x() > clip.left() && center.x() < clip.right())
30647         painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
30648       break;
30649     }
30650     case tsCircle:
30651     {
30652       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30653         painter->drawEllipse(center, w, w);
30654       break;
30655     }
30656     case tsSquare:
30657     {
30658       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
30659         painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
30660       break;
30661     }
30662   }
30663 }
30664 
30665 /*!
30666   If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
30667   position to reside on the graph data, depending on the configured key (\ref setGraphKey).
30668   
30669   It is called automatically on every redraw and normally doesn't need to be called manually. One
30670   exception is when you want to read the tracer coordinates via \a position and are not sure that
30671   the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
30672   In that situation, call this function before accessing \a position, to make sure you don't get
30673   out-of-date coordinates.
30674   
30675   If there is no graph set on this tracer, this function does nothing.
30676 */
30677 void QCPItemTracer::updatePosition()
30678 {
30679   if (mGraph)
30680   {
30681     if (mParentPlot->hasPlottable(mGraph))
30682     {
30683       if (mGraph->data()->size() > 1)
30684       {
30685         QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
30686         QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
30687         if (mGraphKey <= first->key)
30688           position->setCoords(first->key, first->value);
30689         else if (mGraphKey >= last->key)
30690           position->setCoords(last->key, last->value);
30691         else
30692         {
30693           QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
30694           if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
30695           {
30696             QCPGraphDataContainer::const_iterator prevIt = it;
30697             ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
30698             if (mInterpolating)
30699             {
30700               // interpolate between iterators around mGraphKey:
30701               double slope = 0;
30702               if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
30703                 slope = (it->value-prevIt->value)/(it->key-prevIt->key);
30704               position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
30705             } else
30706             {
30707               // find iterator with key closest to mGraphKey:
30708               if (mGraphKey < (prevIt->key+it->key)*0.5)
30709                 position->setCoords(prevIt->key, prevIt->value);
30710               else
30711                 position->setCoords(it->key, it->value);
30712             }
30713           } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
30714             position->setCoords(it->key, it->value);
30715         }
30716       } else if (mGraph->data()->size() == 1)
30717       {
30718         QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
30719         position->setCoords(it->key, it->value);
30720       } else
30721         qDebug() << Q_FUNC_INFO << "graph has no data";
30722     } else
30723       qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
30724   }
30725 }
30726 
30727 /*! \internal
30728 
30729   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
30730   and mSelectedPen when it is.
30731 */
30732 QPen QCPItemTracer::mainPen() const
30733 {
30734   return mSelected ? mSelectedPen : mPen;
30735 }
30736 
30737 /*! \internal
30738 
30739   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
30740   is not selected and mSelectedBrush when it is.
30741 */
30742 QBrush QCPItemTracer::mainBrush() const
30743 {
30744   return mSelected ? mSelectedBrush : mBrush;
30745 }
30746 /* end of 'src/items/item-tracer.cpp' */
30747 
30748 
30749 /* including file 'src/items/item-bracket.cpp' */
30750 /* modified 2021-03-29T02:30:44, size 10705    */
30751 
30752 ////////////////////////////////////////////////////////////////////////////////////////////////////
30753 //////////////////// QCPItemBracket
30754 ////////////////////////////////////////////////////////////////////////////////////////////////////
30755 
30756 /*! \class QCPItemBracket
30757   \brief A bracket for referencing/highlighting certain parts in the plot.
30758 
30759   \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
30760 
30761   It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
30762   actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
30763   example image.
30764   
30765   The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
30766   stretches away from the embraced span, can be controlled with \ref setLength.
30767   
30768   \image html QCPItemBracket-length.png
30769   <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
30770   bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
30771   
30772   It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
30773   or QCPItemCurve) or a text label (QCPItemText), to the bracket.
30774 */
30775 
30776 /*!
30777   Creates a bracket item and sets default values.
30778   
30779   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
30780   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
30781 */
30782 QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
30783   QCPAbstractItem(parentPlot),
30784   left(createPosition(QLatin1String("left"))),
30785   right(createPosition(QLatin1String("right"))),
30786   center(createAnchor(QLatin1String("center"), aiCenter)),
30787   mLength(8),
30788   mStyle(bsCalligraphic)
30789 {
30790   left->setCoords(0, 0);
30791   right->setCoords(1, 1);
30792   
30793   setPen(QPen(Qt::black));
30794   setSelectedPen(QPen(Qt::blue, 2));
30795 }
30796 
30797 QCPItemBracket::~QCPItemBracket()
30798 {
30799 }
30800 
30801 /*!
30802   Sets the pen that will be used to draw the bracket.
30803   
30804   Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
30805   stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
30806   \ref setLength, which has a similar effect.
30807   
30808   \see setSelectedPen
30809 */
30810 void QCPItemBracket::setPen(const QPen &pen)
30811 {
30812   mPen = pen;
30813 }
30814 
30815 /*!
30816   Sets the pen that will be used to draw the bracket when selected
30817   
30818   \see setPen, setSelected
30819 */
30820 void QCPItemBracket::setSelectedPen(const QPen &pen)
30821 {
30822   mSelectedPen = pen;
30823 }
30824 
30825 /*!
30826   Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
30827   span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
30828   
30829   \image html QCPItemBracket-length.png
30830   <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
30831   bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
30832 */
30833 void QCPItemBracket::setLength(double length)
30834 {
30835   mLength = length;
30836 }
30837 
30838 /*!
30839   Sets the style of the bracket, i.e. the shape/visual appearance.
30840   
30841   \see setPen
30842 */
30843 void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
30844 {
30845   mStyle = style;
30846 }
30847 
30848 /* inherits documentation from base class */
30849 double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
30850 {
30851   Q_UNUSED(details)
30852   if (onlySelectable && !mSelectable)
30853     return -1;
30854   
30855   QCPVector2D p(pos);
30856   QCPVector2D leftVec(left->pixelPosition());
30857   QCPVector2D rightVec(right->pixelPosition());
30858   if (leftVec.toPoint() == rightVec.toPoint())
30859     return -1;
30860   
30861   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
30862   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
30863   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
30864   
30865   switch (mStyle)
30866   {
30867     case QCPItemBracket::bsSquare:
30868     case QCPItemBracket::bsRound:
30869     {
30870       double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
30871       double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
30872       double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
30873       return qSqrt(qMin(qMin(a, b), c));
30874     }
30875     case QCPItemBracket::bsCurly:
30876     case QCPItemBracket::bsCalligraphic:
30877     {
30878       double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
30879       double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
30880       double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
30881       double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
30882       return qSqrt(qMin(qMin(a, b), qMin(c, d)));
30883     }
30884   }
30885   return -1;
30886 }
30887 
30888 /* inherits documentation from base class */
30889 void QCPItemBracket::draw(QCPPainter *painter)
30890 {
30891   QCPVector2D leftVec(left->pixelPosition());
30892   QCPVector2D rightVec(right->pixelPosition());
30893   if (leftVec.toPoint() == rightVec.toPoint())
30894     return;
30895   
30896   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
30897   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
30898   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
30899 
30900   QPolygon boundingPoly;
30901   boundingPoly << leftVec.toPoint() << rightVec.toPoint()
30902                << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
30903   const int clipEnlarge = qCeil(mainPen().widthF());
30904   QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
30905   if (clip.intersects(boundingPoly.boundingRect()))
30906   {
30907     painter->setPen(mainPen());
30908     switch (mStyle)
30909     {
30910       case bsSquare:
30911       {
30912         painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
30913         painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
30914         painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
30915         break;
30916       }
30917       case bsRound:
30918       {
30919         painter->setBrush(Qt::NoBrush);
30920         QPainterPath path;
30921         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
30922         path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
30923         path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
30924         painter->drawPath(path);
30925         break;
30926       }
30927       case bsCurly:
30928       {
30929         painter->setBrush(Qt::NoBrush);
30930         QPainterPath path;
30931         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
30932         path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
30933         path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
30934         painter->drawPath(path);
30935         break;
30936       }
30937       case bsCalligraphic:
30938       {
30939         painter->setPen(Qt::NoPen);
30940         painter->setBrush(QBrush(mainPen().color()));
30941         QPainterPath path;
30942         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
30943         
30944         path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
30945         path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
30946         
30947         path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
30948         path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
30949         
30950         painter->drawPath(path);
30951         break;
30952       }
30953     }
30954   }
30955 }
30956 
30957 /* inherits documentation from base class */
30958 QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
30959 {
30960   QCPVector2D leftVec(left->pixelPosition());
30961   QCPVector2D rightVec(right->pixelPosition());
30962   if (leftVec.toPoint() == rightVec.toPoint())
30963     return leftVec.toPointF();
30964   
30965   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
30966   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
30967   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
30968   
30969   switch (anchorId)
30970   {
30971     case aiCenter:
30972       return centerVec.toPointF();
30973   }
30974   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
30975   return {};
30976 }
30977 
30978 /*! \internal
30979 
30980   Returns the pen that should be used for drawing lines. Returns mPen when the
30981   item is not selected and mSelectedPen when it is.
30982 */
30983 QPen QCPItemBracket::mainPen() const
30984 {
30985     return mSelected ? mSelectedPen : mPen;
30986 }
30987 /* end of 'src/items/item-bracket.cpp' */
30988 
30989 
30990 /* including file 'src/polar/radialaxis.cpp' */
30991 /* modified 2021-03-29T02:30:44, size 49415  */
30992 
30993 
30994 
30995 ////////////////////////////////////////////////////////////////////////////////////////////////////
30996 //////////////////// QCPPolarAxisRadial
30997 ////////////////////////////////////////////////////////////////////////////////////////////////////
30998 
30999 /*! \class QCPPolarAxisRadial
31000   \brief The radial axis inside a radial plot
31001   
31002   \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
31003   functionality to be incomplete, as well as changing public interfaces in the future.
31004   
31005   Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
31006   tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
31007   the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
31008   documentation of QCPAxisTicker.
31009 */
31010 
31011 /* start of documentation of inline functions */
31012 
31013 /*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
31014 
31015   Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
31016   responsible for generating the tick positions and tick labels of this axis. You can access the
31017   \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
31018   (\ref QCPAxisTicker::setTickCount).
31019 
31020   You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
31021   the documentation there. A new axis ticker can be set with \ref setTicker.
31022 
31023   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
31024   ticker simply by passing the same shared pointer to multiple axes.
31025 
31026   \see setTicker
31027 */
31028 
31029 /* end of documentation of inline functions */
31030 /* start of documentation of signals */
31031 
31032 /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
31033 
31034   This signal is emitted when the range of this axis has changed. You can connect it to the \ref
31035   setRange slot of another axis to communicate the new range to the other axis, in order for it to
31036   be synchronized.
31037   
31038   You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
31039   This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
31040   range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
31041   slot would limit the x axis to ranges between 0 and 10:
31042   \code
31043   customPlot->xAxis->setRange(newRange.bounded(0, 10))
31044   \endcode
31045 */
31046 
31047 /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
31048   \overload
31049   
31050   Additionally to the new range, this signal also provides the previous range held by the axis as
31051   \a oldRange.
31052 */
31053 
31054 /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
31055   
31056   This signal is emitted when the scale type changes, by calls to \ref setScaleType
31057 */
31058 
31059 /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
31060   
31061   This signal is emitted when the selection state of this axis has changed, either by user interaction
31062   or by a direct call to \ref setSelectedParts.
31063 */
31064 
31065 /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
31066   
31067   This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
31068 */
31069 
31070 /* end of documentation of signals */
31071 
31072 /*!
31073   Constructs an Axis instance of Type \a type for the axis rect \a parent.
31074   
31075   Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
31076   them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
31077   create them manually and then inject them also via \ref QCPAxisRect::addAxis.
31078 */
31079 QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
31080   QCPLayerable(parent->parentPlot(), QString(), parent),
31081   mRangeDrag(true),
31082   mRangeZoom(true),
31083   mRangeZoomFactor(0.85),
31084   // axis base:
31085   mAngularAxis(parent),
31086   mAngle(45),
31087   mAngleReference(arAngularAxis),
31088   mSelectableParts(spAxis | spTickLabels | spAxisLabel),
31089   mSelectedParts(spNone),
31090   mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
31091   mSelectedBasePen(QPen(Qt::blue, 2)),
31092   // axis label:
31093   mLabelPadding(0),
31094   mLabel(),
31095   mLabelFont(mParentPlot->font()),
31096   mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
31097   mLabelColor(Qt::black),
31098   mSelectedLabelColor(Qt::blue),
31099   // tick labels:
31100   // mTickLabelPadding(0), in label painter
31101   mTickLabels(true),
31102   // mTickLabelRotation(0), in label painter
31103   mTickLabelFont(mParentPlot->font()),
31104   mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
31105   mTickLabelColor(Qt::black),
31106   mSelectedTickLabelColor(Qt::blue),
31107   mNumberPrecision(6),
31108   mNumberFormatChar('g'),
31109   mNumberBeautifulPowers(true),
31110   mNumberMultiplyCross(false),
31111   // ticks and subticks:
31112   mTicks(true),
31113   mSubTicks(true),
31114   mTickLengthIn(5),
31115   mTickLengthOut(0),
31116   mSubTickLengthIn(2),
31117   mSubTickLengthOut(0),
31118   mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
31119   mSelectedTickPen(QPen(Qt::blue, 2)),
31120   mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
31121   mSelectedSubTickPen(QPen(Qt::blue, 2)),
31122   // scale and range:
31123   mRange(0, 5),
31124   mRangeReversed(false),
31125   mScaleType(stLinear),
31126   // internal members:
31127   mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
31128   mTicker(new QCPAxisTicker),
31129   mLabelPainter(mParentPlot)
31130 {
31131   setParent(parent);
31132   setAntialiased(true);
31133   
31134   setTickLabelPadding(5);
31135   setTickLabelRotation(0);
31136   setTickLabelMode(lmUpright);
31137   mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent);
31138   mLabelPainter.setAbbreviateDecimalPowers(false);
31139 }
31140 
31141 QCPPolarAxisRadial::~QCPPolarAxisRadial()
31142 {
31143 }
31144 
31145 QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
31146 {
31147   switch (mLabelPainter.anchorMode())
31148   {
31149     case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
31150     case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
31151     default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
31152   }
31153   return lmUpright;
31154 }
31155 
31156 /* No documentation as it is a property getter */
31157 QString QCPPolarAxisRadial::numberFormat() const
31158 {
31159   QString result;
31160   result.append(mNumberFormatChar);
31161   if (mNumberBeautifulPowers)
31162   {
31163     result.append(QLatin1Char('b'));
31164     if (mNumberMultiplyCross)
31165       result.append(QLatin1Char('c'));
31166   }
31167   return result;
31168 }
31169 
31170 /* No documentation as it is a property getter */
31171 int QCPPolarAxisRadial::tickLengthIn() const
31172 {
31173   return mTickLengthIn;
31174 }
31175 
31176 /* No documentation as it is a property getter */
31177 int QCPPolarAxisRadial::tickLengthOut() const
31178 {
31179   return mTickLengthOut;
31180 }
31181 
31182 /* No documentation as it is a property getter */
31183 int QCPPolarAxisRadial::subTickLengthIn() const
31184 {
31185   return mSubTickLengthIn;
31186 }
31187 
31188 /* No documentation as it is a property getter */
31189 int QCPPolarAxisRadial::subTickLengthOut() const
31190 {
31191   return mSubTickLengthOut;
31192 }
31193 
31194 /* No documentation as it is a property getter */
31195 int QCPPolarAxisRadial::labelPadding() const
31196 {
31197   return mLabelPadding;
31198 }
31199 
31200 void QCPPolarAxisRadial::setRangeDrag(bool enabled)
31201 {
31202   mRangeDrag = enabled;
31203 }
31204 
31205 void QCPPolarAxisRadial::setRangeZoom(bool enabled)
31206 {
31207   mRangeZoom = enabled;
31208 }
31209 
31210 void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
31211 {
31212   mRangeZoomFactor = factor;
31213 }
31214 
31215 /*!
31216   Sets whether the axis uses a linear scale or a logarithmic scale.
31217   
31218   Note that this method controls the coordinate transformation. For logarithmic scales, you will
31219   likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
31220   the axis ticker to an instance of \ref QCPAxisTickerLog :
31221   
31222   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
31223   
31224   See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
31225   creation.
31226   
31227   \ref setNumberPrecision
31228 */
31229 void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
31230 {
31231   if (mScaleType != type)
31232   {
31233     mScaleType = type;
31234     if (mScaleType == stLogarithmic)
31235       setRange(mRange.sanitizedForLogScale());
31236     //mCachedMarginValid = false;
31237     emit scaleTypeChanged(mScaleType);
31238   }
31239 }
31240 
31241 /*!
31242   Sets the range of the axis.
31243   
31244   This slot may be connected with the \ref rangeChanged signal of another axis so this axis
31245   is always synchronized with the other axis range, when it changes.
31246   
31247   To invert the direction of an axis, use \ref setRangeReversed.
31248 */
31249 void QCPPolarAxisRadial::setRange(const QCPRange &range)
31250 {
31251   if (range.lower == mRange.lower && range.upper == mRange.upper)
31252     return;
31253   
31254   if (!QCPRange::validRange(range)) return;
31255   QCPRange oldRange = mRange;
31256   if (mScaleType == stLogarithmic)
31257   {
31258     mRange = range.sanitizedForLogScale();
31259   } else
31260   {
31261     mRange = range.sanitizedForLinScale();
31262   }
31263   emit rangeChanged(mRange);
31264   emit rangeChanged(mRange, oldRange);
31265 }
31266 
31267 /*!
31268   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
31269   (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
31270   
31271   However, even when \a selectable is set to a value not allowing the selection of a specific part,
31272   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
31273   directly.
31274   
31275   \see SelectablePart, setSelectedParts
31276 */
31277 void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
31278 {
31279   if (mSelectableParts != selectable)
31280   {
31281     mSelectableParts = selectable;
31282     emit selectableChanged(mSelectableParts);
31283   }
31284 }
31285 
31286 /*!
31287   Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
31288   is selected, it uses a different pen/font.
31289   
31290   The entire selection mechanism for axes is handled automatically when \ref
31291   QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
31292   wish to change the selection state manually.
31293   
31294   This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
31295   
31296   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
31297   
31298   \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
31299   setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
31300 */
31301 void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
31302 {
31303   if (mSelectedParts != selected)
31304   {
31305     mSelectedParts = selected;
31306     emit selectionChanged(mSelectedParts);
31307   }
31308 }
31309 
31310 /*!
31311   \overload
31312   
31313   Sets the lower and upper bound of the axis range.
31314   
31315   To invert the direction of an axis, use \ref setRangeReversed.
31316   
31317   There is also a slot to set a range, see \ref setRange(const QCPRange &range).
31318 */
31319 void QCPPolarAxisRadial::setRange(double lower, double upper)
31320 {
31321   if (lower == mRange.lower && upper == mRange.upper)
31322     return;
31323   
31324   if (!QCPRange::validRange(lower, upper)) return;
31325   QCPRange oldRange = mRange;
31326   mRange.lower = lower;
31327   mRange.upper = upper;
31328   if (mScaleType == stLogarithmic)
31329   {
31330     mRange = mRange.sanitizedForLogScale();
31331   } else
31332   {
31333     mRange = mRange.sanitizedForLinScale();
31334   }
31335   emit rangeChanged(mRange);
31336   emit rangeChanged(mRange, oldRange);
31337 }
31338 
31339 /*!
31340   \overload
31341   
31342   Sets the range of the axis.
31343   
31344   The \a position coordinate indicates together with the \a alignment parameter, where the new
31345   range will be positioned. \a size defines the size of the new axis range. \a alignment may be
31346   Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
31347   or center of the range to be aligned with \a position. Any other values of \a alignment will
31348   default to Qt::AlignCenter.
31349 */
31350 void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
31351 {
31352   if (alignment == Qt::AlignLeft)
31353     setRange(position, position+size);
31354   else if (alignment == Qt::AlignRight)
31355     setRange(position-size, position);
31356   else // alignment == Qt::AlignCenter
31357     setRange(position-size/2.0, position+size/2.0);
31358 }
31359 
31360 /*!
31361   Sets the lower bound of the axis range. The upper bound is not changed.
31362   \see setRange
31363 */
31364 void QCPPolarAxisRadial::setRangeLower(double lower)
31365 {
31366   if (mRange.lower == lower)
31367     return;
31368   
31369   QCPRange oldRange = mRange;
31370   mRange.lower = lower;
31371   if (mScaleType == stLogarithmic)
31372   {
31373     mRange = mRange.sanitizedForLogScale();
31374   } else
31375   {
31376     mRange = mRange.sanitizedForLinScale();
31377   }
31378   emit rangeChanged(mRange);
31379   emit rangeChanged(mRange, oldRange);
31380 }
31381 
31382 /*!
31383   Sets the upper bound of the axis range. The lower bound is not changed.
31384   \see setRange
31385 */
31386 void QCPPolarAxisRadial::setRangeUpper(double upper)
31387 {
31388   if (mRange.upper == upper)
31389     return;
31390   
31391   QCPRange oldRange = mRange;
31392   mRange.upper = upper;
31393   if (mScaleType == stLogarithmic)
31394   {
31395     mRange = mRange.sanitizedForLogScale();
31396   } else
31397   {
31398     mRange = mRange.sanitizedForLinScale();
31399   }
31400   emit rangeChanged(mRange);
31401   emit rangeChanged(mRange, oldRange);
31402 }
31403 
31404 /*!
31405   Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
31406   axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
31407   direction of increasing values is inverted.
31408 
31409   Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
31410   of the \ref setRange interface will still reference the mathematically smaller number than the \a
31411   upper part.
31412 */
31413 void QCPPolarAxisRadial::setRangeReversed(bool reversed)
31414 {
31415   mRangeReversed = reversed;
31416 }
31417 
31418 void QCPPolarAxisRadial::setAngle(double degrees)
31419 {
31420   mAngle = degrees;
31421 }
31422 
31423 void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
31424 {
31425   mAngleReference = reference;
31426 }
31427 
31428 /*!
31429   The axis ticker is responsible for generating the tick positions and tick labels. See the
31430   documentation of QCPAxisTicker for details on how to work with axis tickers.
31431   
31432   You can change the tick positioning/labeling behaviour of this axis by setting a different
31433   QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
31434   ticker, access it via \ref ticker.
31435   
31436   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
31437   ticker simply by passing the same shared pointer to multiple axes.
31438   
31439   \see ticker
31440 */
31441 void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
31442 {
31443   if (ticker)
31444     mTicker = ticker;
31445   else
31446     qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
31447   // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
31448 }
31449 
31450 /*!
31451   Sets whether tick marks are displayed.
31452 
31453   Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
31454   that, see \ref setTickLabels.
31455   
31456   \see setSubTicks
31457 */
31458 void QCPPolarAxisRadial::setTicks(bool show)
31459 {
31460   if (mTicks != show)
31461   {
31462     mTicks = show;
31463     //mCachedMarginValid = false;
31464   }
31465 }
31466 
31467 /*!
31468   Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
31469 */
31470 void QCPPolarAxisRadial::setTickLabels(bool show)
31471 {
31472   if (mTickLabels != show)
31473   {
31474     mTickLabels = show;
31475     //mCachedMarginValid = false;
31476     if (!mTickLabels)
31477       mTickVectorLabels.clear();
31478   }
31479 }
31480 
31481 /*!
31482   Sets the distance between the axis base line (including any outward ticks) and the tick labels.
31483   \see setLabelPadding, setPadding
31484 */
31485 void QCPPolarAxisRadial::setTickLabelPadding(int padding)
31486 {
31487   mLabelPainter.setPadding(padding);
31488 }
31489 
31490 /*!
31491   Sets the font of the tick labels.
31492   
31493   \see setTickLabels, setTickLabelColor
31494 */
31495 void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
31496 {
31497   if (font != mTickLabelFont)
31498   {
31499     mTickLabelFont = font;
31500     //mCachedMarginValid = false;
31501   }
31502 }
31503 
31504 /*!
31505   Sets the color of the tick labels.
31506   
31507   \see setTickLabels, setTickLabelFont
31508 */
31509 void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
31510 {
31511   mTickLabelColor = color;
31512 }
31513 
31514 /*!
31515   Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
31516   the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
31517   from -90 to 90 degrees.
31518   
31519   If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
31520   other angles, the label is drawn with an offset such that it seems to point toward or away from
31521   the tick mark.
31522 */
31523 void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
31524 {
31525   mLabelPainter.setRotation(degrees);
31526 }
31527 
31528 void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
31529 {
31530   switch (mode)
31531   {
31532     case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
31533     case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
31534   }
31535 }
31536 
31537 /*!
31538   Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
31539   of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
31540   that, see the "Argument Formats" section in the detailed description of the QString class.
31541   
31542   \a formatCode is a string of one, two or three characters. The first character is identical to
31543   the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
31544   format, 'g'/'G' scientific or fixed, whichever is shorter.
31545   
31546   The second and third characters are optional and specific to QCustomPlot:\n
31547   If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
31548   "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
31549   "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
31550   [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
31551   If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
31552   be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
31553   cross and 183 (0xB7) for the dot.
31554   
31555   Examples for \a formatCode:
31556   \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
31557   normal scientific format is used
31558   \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
31559   beautifully typeset decimal powers and a dot as multiplication sign
31560   \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
31561   multiplication sign
31562   \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
31563   powers. Format code will be reduced to 'f'.
31564   \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
31565   code will not be changed.
31566 */
31567 void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
31568 {
31569   if (formatCode.isEmpty())
31570   {
31571     qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
31572     return;
31573   }
31574   //mCachedMarginValid = false;
31575   
31576   // interpret first char as number format char:
31577   QString allowedFormatChars(QLatin1String("eEfgG"));
31578   if (allowedFormatChars.contains(formatCode.at(0)))
31579   {
31580     mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
31581   } else
31582   {
31583     qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
31584     return;
31585   }
31586   
31587   if (formatCode.length() < 2)
31588   {
31589     mNumberBeautifulPowers = false;
31590     mNumberMultiplyCross = false;
31591   } else
31592   {
31593     // interpret second char as indicator for beautiful decimal powers:
31594     if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
31595       mNumberBeautifulPowers = true;
31596     else
31597       qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
31598     
31599     if (formatCode.length() < 3)
31600     {
31601       mNumberMultiplyCross = false;
31602     } else
31603     {
31604       // interpret third char as indicator for dot or cross multiplication symbol:
31605       if (formatCode.at(2) == QLatin1Char('c'))
31606         mNumberMultiplyCross = true;
31607       else if (formatCode.at(2) == QLatin1Char('d'))
31608         mNumberMultiplyCross = false;
31609       else
31610         qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
31611     }
31612   }
31613   mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
31614   mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
31615 }
31616 
31617 /*!
31618   Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
31619   for details. The effect of precisions are most notably for number Formats starting with 'e', see
31620   \ref setNumberFormat
31621 */
31622 void QCPPolarAxisRadial::setNumberPrecision(int precision)
31623 {
31624   if (mNumberPrecision != precision)
31625   {
31626     mNumberPrecision = precision;
31627     //mCachedMarginValid = false;
31628   }
31629 }
31630 
31631 /*!
31632   Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
31633   plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
31634   zero, the tick labels and axis label will increase their distance to the axis accordingly, so
31635   they won't collide with the ticks.
31636   
31637   \see setSubTickLength, setTickLengthIn, setTickLengthOut
31638 */
31639 void QCPPolarAxisRadial::setTickLength(int inside, int outside)
31640 {
31641   setTickLengthIn(inside);
31642   setTickLengthOut(outside);
31643 }
31644 
31645 /*!
31646   Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
31647   inside the plot.
31648   
31649   \see setTickLengthOut, setTickLength, setSubTickLength
31650 */
31651 void QCPPolarAxisRadial::setTickLengthIn(int inside)
31652 {
31653   if (mTickLengthIn != inside)
31654   {
31655     mTickLengthIn = inside;
31656   }
31657 }
31658 
31659 /*!
31660   Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
31661   outside the plot. If \a outside is greater than zero, the tick labels and axis label will
31662   increase their distance to the axis accordingly, so they won't collide with the ticks.
31663   
31664   \see setTickLengthIn, setTickLength, setSubTickLength
31665 */
31666 void QCPPolarAxisRadial::setTickLengthOut(int outside)
31667 {
31668   if (mTickLengthOut != outside)
31669   {
31670     mTickLengthOut = outside;
31671     //mCachedMarginValid = false; // only outside tick length can change margin
31672   }
31673 }
31674 
31675 /*!
31676   Sets whether sub tick marks are displayed.
31677   
31678   Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
31679   
31680   \see setTicks
31681 */
31682 void QCPPolarAxisRadial::setSubTicks(bool show)
31683 {
31684   if (mSubTicks != show)
31685   {
31686     mSubTicks = show;
31687     //mCachedMarginValid = false;
31688   }
31689 }
31690 
31691 /*!
31692   Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
31693   the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
31694   than zero, the tick labels and axis label will increase their distance to the axis accordingly,
31695   so they won't collide with the ticks.
31696   
31697   \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
31698 */
31699 void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
31700 {
31701   setSubTickLengthIn(inside);
31702   setSubTickLengthOut(outside);
31703 }
31704 
31705 /*!
31706   Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
31707   the plot.
31708   
31709   \see setSubTickLengthOut, setSubTickLength, setTickLength
31710 */
31711 void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
31712 {
31713   if (mSubTickLengthIn != inside)
31714   {
31715     mSubTickLengthIn = inside;
31716   }
31717 }
31718 
31719 /*!
31720   Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
31721   outside the plot. If \a outside is greater than zero, the tick labels will increase their
31722   distance to the axis accordingly, so they won't collide with the ticks.
31723   
31724   \see setSubTickLengthIn, setSubTickLength, setTickLength
31725 */
31726 void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
31727 {
31728   if (mSubTickLengthOut != outside)
31729   {
31730     mSubTickLengthOut = outside;
31731     //mCachedMarginValid = false; // only outside tick length can change margin
31732   }
31733 }
31734 
31735 /*!
31736   Sets the pen, the axis base line is drawn with.
31737   
31738   \see setTickPen, setSubTickPen
31739 */
31740 void QCPPolarAxisRadial::setBasePen(const QPen &pen)
31741 {
31742   mBasePen = pen;
31743 }
31744 
31745 /*!
31746   Sets the pen, tick marks will be drawn with.
31747   
31748   \see setTickLength, setBasePen
31749 */
31750 void QCPPolarAxisRadial::setTickPen(const QPen &pen)
31751 {
31752   mTickPen = pen;
31753 }
31754 
31755 /*!
31756   Sets the pen, subtick marks will be drawn with.
31757   
31758   \see setSubTickCount, setSubTickLength, setBasePen
31759 */
31760 void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
31761 {
31762   mSubTickPen = pen;
31763 }
31764 
31765 /*!
31766   Sets the font of the axis label.
31767   
31768   \see setLabelColor
31769 */
31770 void QCPPolarAxisRadial::setLabelFont(const QFont &font)
31771 {
31772   if (mLabelFont != font)
31773   {
31774     mLabelFont = font;
31775     //mCachedMarginValid = false;
31776   }
31777 }
31778 
31779 /*!
31780   Sets the color of the axis label.
31781   
31782   \see setLabelFont
31783 */
31784 void QCPPolarAxisRadial::setLabelColor(const QColor &color)
31785 {
31786   mLabelColor = color;
31787 }
31788 
31789 /*!
31790   Sets the text of the axis label that will be shown below/above or next to the axis, depending on
31791   its orientation. To disable axis labels, pass an empty string as \a str.
31792 */
31793 void QCPPolarAxisRadial::setLabel(const QString &str)
31794 {
31795   if (mLabel != str)
31796   {
31797     mLabel = str;
31798     //mCachedMarginValid = false;
31799   }
31800 }
31801 
31802 /*!
31803   Sets the distance between the tick labels and the axis label.
31804   
31805   \see setTickLabelPadding, setPadding
31806 */
31807 void QCPPolarAxisRadial::setLabelPadding(int padding)
31808 {
31809   if (mLabelPadding != padding)
31810   {
31811     mLabelPadding = padding;
31812     //mCachedMarginValid = false;
31813   }
31814 }
31815 
31816 /*!
31817   Sets the font that is used for tick labels when they are selected.
31818   
31819   \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31820 */
31821 void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
31822 {
31823   if (font != mSelectedTickLabelFont)
31824   {
31825     mSelectedTickLabelFont = font;
31826     // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
31827   }
31828 }
31829 
31830 /*!
31831   Sets the font that is used for the axis label when it is selected.
31832   
31833   \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31834 */
31835 void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
31836 {
31837   mSelectedLabelFont = font;
31838   // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
31839 }
31840 
31841 /*!
31842   Sets the color that is used for tick labels when they are selected.
31843   
31844   \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31845 */
31846 void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
31847 {
31848   if (color != mSelectedTickLabelColor)
31849   {
31850     mSelectedTickLabelColor = color;
31851   }
31852 }
31853 
31854 /*!
31855   Sets the color that is used for the axis label when it is selected.
31856   
31857   \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31858 */
31859 void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
31860 {
31861   mSelectedLabelColor = color;
31862 }
31863 
31864 /*!
31865   Sets the pen that is used to draw the axis base line when selected.
31866   
31867   \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31868 */
31869 void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
31870 {
31871   mSelectedBasePen = pen;
31872 }
31873 
31874 /*!
31875   Sets the pen that is used to draw the (major) ticks when selected.
31876   
31877   \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31878 */
31879 void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
31880 {
31881   mSelectedTickPen = pen;
31882 }
31883 
31884 /*!
31885   Sets the pen that is used to draw the subticks when selected.
31886   
31887   \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
31888 */
31889 void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
31890 {
31891   mSelectedSubTickPen = pen;
31892 }
31893 
31894 /*!
31895   If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
31896   bounds of the range. The range is simply moved by \a diff.
31897   
31898   If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
31899   corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
31900 */
31901 void QCPPolarAxisRadial::moveRange(double diff)
31902 {
31903   QCPRange oldRange = mRange;
31904   if (mScaleType == stLinear)
31905   {
31906     mRange.lower += diff;
31907     mRange.upper += diff;
31908   } else // mScaleType == stLogarithmic
31909   {
31910     mRange.lower *= diff;
31911     mRange.upper *= diff;
31912   }
31913   emit rangeChanged(mRange);
31914   emit rangeChanged(mRange, oldRange);
31915 }
31916 
31917 /*!
31918   Scales the range of this axis by \a factor around the center of the current axis range. For
31919   example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
31920   range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
31921   the center will have moved symmetrically closer).
31922 
31923   If you wish to scale around a different coordinate than the current axis range center, use the
31924   overload \ref scaleRange(double factor, double center).
31925 */
31926 void QCPPolarAxisRadial::scaleRange(double factor)
31927 {
31928   scaleRange(factor, range().center());
31929 }
31930 
31931 /*! \overload
31932 
31933   Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
31934   factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
31935   coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
31936   around 1.0 will have moved symmetrically closer to 1.0).
31937 
31938   \see scaleRange(double factor)
31939 */
31940 void QCPPolarAxisRadial::scaleRange(double factor, double center)
31941 {
31942   QCPRange oldRange = mRange;
31943   if (mScaleType == stLinear)
31944   {
31945     QCPRange newRange;
31946     newRange.lower = (mRange.lower-center)*factor + center;
31947     newRange.upper = (mRange.upper-center)*factor + center;
31948     if (QCPRange::validRange(newRange))
31949       mRange = newRange.sanitizedForLinScale();
31950   } else // mScaleType == stLogarithmic
31951   {
31952     if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
31953     {
31954       QCPRange newRange;
31955       newRange.lower = qPow(mRange.lower/center, factor)*center;
31956       newRange.upper = qPow(mRange.upper/center, factor)*center;
31957       if (QCPRange::validRange(newRange))
31958         mRange = newRange.sanitizedForLogScale();
31959     } else
31960       qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
31961   }
31962   emit rangeChanged(mRange);
31963   emit rangeChanged(mRange, oldRange);
31964 }
31965 
31966 /*!
31967   Changes the axis range such that all plottables associated with this axis are fully visible in
31968   that dimension.
31969   
31970   \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
31971 */
31972 void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
31973 {
31974   Q_UNUSED(onlyVisiblePlottables)
31975   /* TODO
31976   QList<QCPAbstractPlottable*> p = plottables();
31977   QCPRange newRange;
31978   bool haveRange = false;
31979   for (int i=0; i<p.size(); ++i)
31980   {
31981     if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
31982       continue;
31983     QCPRange plottableRange;
31984     bool currentFoundRange;
31985     QCP::SignDomain signDomain = QCP::sdBoth;
31986     if (mScaleType == stLogarithmic)
31987       signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
31988     if (p.at(i)->keyAxis() == this)
31989       plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
31990     else
31991       plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
31992     if (currentFoundRange)
31993     {
31994       if (!haveRange)
31995         newRange = plottableRange;
31996       else
31997         newRange.expand(plottableRange);
31998       haveRange = true;
31999     }
32000   }
32001   if (haveRange)
32002   {
32003     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
32004     {
32005       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
32006       if (mScaleType == stLinear)
32007       {
32008         newRange.lower = center-mRange.size()/2.0;
32009         newRange.upper = center+mRange.size()/2.0;
32010       } else // mScaleType == stLogarithmic
32011       {
32012         newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
32013         newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
32014       }
32015     }
32016     setRange(newRange);
32017   }
32018   */
32019 }
32020 
32021 /*!
32022   Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
32023 */
32024 void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
32025 {
32026   QCPVector2D posVector(pixelPos-mCenter);
32027   radiusCoord = radiusToCoord(posVector.length());
32028   angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
32029 }
32030 
32031 /*!
32032   Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
32033 */
32034 QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
32035 {
32036   const double radiusPixel = coordToRadius(radiusCoord);
32037   const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
32038   return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
32039 }
32040 
32041 double QCPPolarAxisRadial::coordToRadius(double coord) const
32042 {
32043   if (mScaleType == stLinear)
32044   {
32045     if (!mRangeReversed)
32046       return (coord-mRange.lower)/mRange.size()*mRadius;
32047     else
32048       return (mRange.upper-coord)/mRange.size()*mRadius;
32049   } else // mScaleType == stLogarithmic
32050   {
32051     if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range
32052       return !mRangeReversed ? mRadius+200 : mRadius-200;
32053     else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
32054       return !mRangeReversed ? mRadius-200 :mRadius+200;
32055     else
32056     {
32057       if (!mRangeReversed)
32058         return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
32059       else
32060         return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
32061     }
32062   }
32063 }
32064 
32065 double QCPPolarAxisRadial::radiusToCoord(double radius) const
32066 {
32067   if (mScaleType == stLinear)
32068   {
32069     if (!mRangeReversed)
32070       return (radius)/mRadius*mRange.size()+mRange.lower;
32071     else
32072       return -(radius)/mRadius*mRange.size()+mRange.upper;
32073   } else // mScaleType == stLogarithmic
32074   {
32075     if (!mRangeReversed)
32076       return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
32077     else
32078       return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
32079   }
32080 }
32081 
32082 
32083 /*!
32084   Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
32085   is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
32086   function does not change the current selection state of the axis.
32087   
32088   If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
32089   
32090   \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
32091 */
32092 QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
32093 {
32094   Q_UNUSED(pos) // TODO remove later
32095   if (!mVisible)
32096     return spNone;
32097   
32098   /*
32099     TODO:
32100   if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
32101     return spAxis;
32102   else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
32103     return spTickLabels;
32104   else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
32105     return spAxisLabel;
32106   else */
32107     return spNone;
32108 }
32109 
32110 /* inherits documentation from base class */
32111 double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
32112 {
32113   if (!mParentPlot) return -1;
32114   SelectablePart part = getPartAt(pos);
32115   if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
32116     return -1;
32117   
32118   if (details)
32119     details->setValue(part);
32120   return mParentPlot->selectionTolerance()*0.99;
32121 }
32122 
32123 /* inherits documentation from base class */
32124 void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
32125 {
32126   Q_UNUSED(event)
32127   SelectablePart part = details.value<SelectablePart>();
32128   if (mSelectableParts.testFlag(part))
32129   {
32130     SelectableParts selBefore = mSelectedParts;
32131     setSelectedParts(additive ? mSelectedParts^part : part);
32132     if (selectionStateChanged)
32133       *selectionStateChanged = mSelectedParts != selBefore;
32134   }
32135 }
32136 
32137 /* inherits documentation from base class */
32138 void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
32139 {
32140   SelectableParts selBefore = mSelectedParts;
32141   setSelectedParts(mSelectedParts & ~mSelectableParts);
32142   if (selectionStateChanged)
32143     *selectionStateChanged = mSelectedParts != selBefore;
32144 }
32145 
32146 /*! \internal
32147   
32148   This mouse event reimplementation provides the functionality to let the user drag individual axes
32149   exclusively, by startig the drag on top of the axis.
32150 
32151   For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
32152   must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
32153   (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
32154   QCPAxisRect::setRangeDragAxes)
32155   
32156   \seebaseclassmethod
32157   
32158   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
32159   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
32160 */
32161 void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
32162 {
32163   Q_UNUSED(details)
32164   if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
32165   {
32166     event->ignore();
32167     return;
32168   }
32169   
32170   if (event->buttons() & Qt::LeftButton)
32171   {
32172     mDragging = true;
32173     // initialize antialiasing backup in case we start dragging:
32174     if (mParentPlot->noAntialiasingOnDrag())
32175     {
32176       mAADragBackup = mParentPlot->antialiasedElements();
32177       mNotAADragBackup = mParentPlot->notAntialiasedElements();
32178     }
32179     // Mouse range dragging interaction:
32180     if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
32181       mDragStartRange = mRange;
32182   }
32183 }
32184 
32185 /*! \internal
32186   
32187   This mouse event reimplementation provides the functionality to let the user drag individual axes
32188   exclusively, by startig the drag on top of the axis.
32189   
32190   \seebaseclassmethod
32191   
32192   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
32193   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
32194   
32195   \see QCPAxis::mousePressEvent
32196 */
32197 void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
32198 {
32199   Q_UNUSED(event) // TODO remove later
32200   Q_UNUSED(startPos) // TODO remove later
32201   if (mDragging)
32202   {
32203     /* TODO
32204     const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
32205     const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
32206     if (mScaleType == QCPPolarAxisRadial::stLinear)
32207     {
32208       const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
32209       setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
32210     } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
32211     {
32212       const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
32213       setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
32214     }
32215     */
32216     
32217     if (mParentPlot->noAntialiasingOnDrag())
32218       mParentPlot->setNotAntialiasedElements(QCP::aeAll);
32219     mParentPlot->replot(QCustomPlot::rpQueuedReplot);
32220   }
32221 }
32222 
32223 /*! \internal
32224   
32225   This mouse event reimplementation provides the functionality to let the user drag individual axes
32226   exclusively, by startig the drag on top of the axis.
32227   
32228   \seebaseclassmethod
32229   
32230   \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
32231   rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
32232   
32233   \see QCPAxis::mousePressEvent
32234 */
32235 void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
32236 {
32237   Q_UNUSED(event)
32238   Q_UNUSED(startPos)
32239   mDragging = false;
32240   if (mParentPlot->noAntialiasingOnDrag())
32241   {
32242     mParentPlot->setAntialiasedElements(mAADragBackup);
32243     mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
32244   }
32245 }
32246 
32247 /*! \internal
32248   
32249   This mouse event reimplementation provides the functionality to let the user zoom individual axes
32250   exclusively, by performing the wheel event on top of the axis.
32251 
32252   For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
32253   must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
32254   (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
32255   QCPAxisRect::setRangeZoomAxes)
32256   
32257   \seebaseclassmethod
32258   
32259   \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
32260   axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
32261 */
32262 void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
32263 {
32264   // Mouse range zooming interaction:
32265   if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
32266   {
32267     event->ignore();
32268     return;
32269   }
32270   
32271   // TODO:
32272   //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
32273   //const double factor = qPow(mRangeZoomFactor, wheelSteps);
32274   //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
32275   mParentPlot->replot();
32276 }
32277 
32278 void QCPPolarAxisRadial::updateGeometry(const QPointF &center, double radius)
32279 {
32280   mCenter = center;
32281   mRadius = radius;
32282   if (mRadius < 1) mRadius = 1;
32283 }
32284 
32285 /*! \internal
32286 
32287   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
32288   before drawing axis lines.
32289 
32290   This is the antialiasing state the painter passed to the \ref draw method is in by default.
32291   
32292   This function takes into account the local setting of the antialiasing flag as well as the
32293   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
32294   QCustomPlot::setNotAntialiasedElements.
32295   
32296   \seebaseclassmethod
32297   
32298   \see setAntialiased
32299 */
32300 void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
32301 {
32302   applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
32303 }
32304 
32305 /*! \internal
32306   
32307   Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
32308 
32309   \seebaseclassmethod
32310 */
32311 void QCPPolarAxisRadial::draw(QCPPainter *painter)
32312 {
32313   const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
32314   const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
32315   const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
32316   
32317   // draw baseline:
32318   painter->setPen(getBasePen());
32319   painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
32320   
32321   // draw subticks:
32322   if (!mSubTickVector.isEmpty())
32323   {
32324     painter->setPen(getSubTickPen());
32325     for (int i=0; i<mSubTickVector.size(); ++i)
32326     {
32327       const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
32328       painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
32329     }
32330   }
32331   
32332   // draw ticks and labels:
32333   if (!mTickVector.isEmpty())
32334   {
32335     mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
32336     mLabelPainter.setFont(getTickLabelFont());
32337     mLabelPainter.setColor(getTickLabelColor());
32338     const QPen ticksPen = getTickPen();
32339     painter->setPen(ticksPen);
32340     for (int i=0; i<mTickVector.size(); ++i)
32341     {
32342       const double r = coordToRadius(mTickVector.at(i));
32343       const QPointF tickPosition = mCenter+axisVector*r;
32344       painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
32345       // possibly draw tick labels:
32346       if (!mTickVectorLabels.isEmpty())
32347       {
32348         if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
32349             (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
32350           mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
32351       }
32352     }
32353   }
32354 }
32355 
32356 /*! \internal
32357   
32358   Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
32359   QCPAxisTicker::generate on the currently installed ticker.
32360   
32361   If a change in the label text/count is detected, the cached axis margin is invalidated to make
32362   sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
32363 */
32364 void QCPPolarAxisRadial::setupTickVectors()
32365 {
32366   if (!mParentPlot) return;
32367   if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
32368   
32369   mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
32370 }
32371 
32372 /*! \internal
32373   
32374   Returns the pen that is used to draw the axis base line. Depending on the selection state, this
32375   is either mSelectedBasePen or mBasePen.
32376 */
32377 QPen QCPPolarAxisRadial::getBasePen() const
32378 {
32379   return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
32380 }
32381 
32382 /*! \internal
32383   
32384   Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
32385   is either mSelectedTickPen or mTickPen.
32386 */
32387 QPen QCPPolarAxisRadial::getTickPen() const
32388 {
32389   return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
32390 }
32391 
32392 /*! \internal
32393   
32394   Returns the pen that is used to draw the subticks. Depending on the selection state, this
32395   is either mSelectedSubTickPen or mSubTickPen.
32396 */
32397 QPen QCPPolarAxisRadial::getSubTickPen() const
32398 {
32399   return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
32400 }
32401 
32402 /*! \internal
32403   
32404   Returns the font that is used to draw the tick labels. Depending on the selection state, this
32405   is either mSelectedTickLabelFont or mTickLabelFont.
32406 */
32407 QFont QCPPolarAxisRadial::getTickLabelFont() const
32408 {
32409   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
32410 }
32411 
32412 /*! \internal
32413   
32414   Returns the font that is used to draw the axis label. Depending on the selection state, this
32415   is either mSelectedLabelFont or mLabelFont.
32416 */
32417 QFont QCPPolarAxisRadial::getLabelFont() const
32418 {
32419   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
32420 }
32421 
32422 /*! \internal
32423   
32424   Returns the color that is used to draw the tick labels. Depending on the selection state, this
32425   is either mSelectedTickLabelColor or mTickLabelColor.
32426 */
32427 QColor QCPPolarAxisRadial::getTickLabelColor() const
32428 {
32429   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
32430 }
32431 
32432 /*! \internal
32433   
32434   Returns the color that is used to draw the axis label. Depending on the selection state, this
32435   is either mSelectedLabelColor or mLabelColor.
32436 */
32437 QColor QCPPolarAxisRadial::getLabelColor() const
32438 {
32439   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
32440 }
32441 
32442 
32443 /* inherits documentation from base class */
32444 QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
32445 {
32446   return QCP::iSelectAxes;
32447 }
32448 /* end of 'src/polar/radialaxis.cpp' */
32449 
32450 
32451 /* including file 'src/polar/layoutelement-angularaxis.cpp' */
32452 /* modified 2021-03-29T02:30:44, size 57266                 */
32453 
32454 
32455 ////////////////////////////////////////////////////////////////////////////////////////////////////
32456 //////////////////// QCPPolarAxisAngular
32457 ////////////////////////////////////////////////////////////////////////////////////////////////////
32458 
32459 /*! \class QCPPolarAxisAngular
32460   \brief The main container for polar plots, representing the angular axis as a circle
32461 
32462   \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
32463   functionality to be incomplete, as well as changing public interfaces in the future.
32464 */
32465 
32466 /* start documentation of inline functions */
32467 
32468 /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
32469   
32470   Returns the inset layout of this axis rect. It can be used to place other layout elements (or
32471   even layouts with multiple other elements) inside/on top of an axis rect.
32472   
32473   \see QCPLayoutInset
32474 */
32475 
32476 /*! \fn int QCPPolarAxisAngular::left() const
32477   
32478   Returns the pixel position of the left border of this axis rect. Margins are not taken into
32479   account here, so the returned value is with respect to the inner \ref rect.
32480 */
32481 
32482 /*! \fn int QCPPolarAxisAngular::right() const
32483   
32484   Returns the pixel position of the right border of this axis rect. Margins are not taken into
32485   account here, so the returned value is with respect to the inner \ref rect.
32486 */
32487 
32488 /*! \fn int QCPPolarAxisAngular::top() const
32489   
32490   Returns the pixel position of the top border of this axis rect. Margins are not taken into
32491   account here, so the returned value is with respect to the inner \ref rect.
32492 */
32493 
32494 /*! \fn int QCPPolarAxisAngular::bottom() const
32495   
32496   Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
32497   account here, so the returned value is with respect to the inner \ref rect.
32498 */
32499 
32500 /*! \fn int QCPPolarAxisAngular::width() const
32501   
32502   Returns the pixel width of this axis rect. Margins are not taken into account here, so the
32503   returned value is with respect to the inner \ref rect.
32504 */
32505 
32506 /*! \fn int QCPPolarAxisAngular::height() const
32507   
32508   Returns the pixel height of this axis rect. Margins are not taken into account here, so the
32509   returned value is with respect to the inner \ref rect.
32510 */
32511 
32512 /*! \fn QSize QCPPolarAxisAngular::size() const
32513   
32514   Returns the pixel size of this axis rect. Margins are not taken into account here, so the
32515   returned value is with respect to the inner \ref rect.
32516 */
32517 
32518 /*! \fn QPoint QCPPolarAxisAngular::topLeft() const
32519   
32520   Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
32521   so the returned value is with respect to the inner \ref rect.
32522 */
32523 
32524 /*! \fn QPoint QCPPolarAxisAngular::topRight() const
32525   
32526   Returns the top right corner of this axis rect in pixels. Margins are not taken into account
32527   here, so the returned value is with respect to the inner \ref rect.
32528 */
32529 
32530 /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
32531   
32532   Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
32533   here, so the returned value is with respect to the inner \ref rect.
32534 */
32535 
32536 /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
32537   
32538   Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
32539   here, so the returned value is with respect to the inner \ref rect.
32540 */
32541 
32542 /*! \fn QPoint QCPPolarAxisAngular::center() const
32543   
32544   Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
32545   returned value is with respect to the inner \ref rect.
32546 */
32547 
32548 /* end documentation of inline functions */
32549 
32550 /*!
32551   Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
32552   sides, the top and right axes are set invisible initially.
32553 */
32554 QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
32555   QCPLayoutElement(parentPlot),
32556   mBackgroundBrush(Qt::NoBrush),
32557   mBackgroundScaled(true),
32558   mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
32559   mInsetLayout(new QCPLayoutInset),
32560   mRangeDrag(false),
32561   mRangeZoom(false),
32562   mRangeZoomFactor(0.85),
32563   // axis base:
32564   mAngle(-90),
32565   mAngleRad(mAngle/180.0*M_PI),
32566   mSelectableParts(spAxis | spTickLabels | spAxisLabel),
32567   mSelectedParts(spNone),
32568   mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
32569   mSelectedBasePen(QPen(Qt::blue, 2)),
32570   // axis label:
32571   mLabelPadding(0),
32572   mLabel(),
32573   mLabelFont(mParentPlot->font()),
32574   mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
32575   mLabelColor(Qt::black),
32576   mSelectedLabelColor(Qt::blue),
32577   // tick labels:
32578   //mTickLabelPadding(0), in label painter
32579   mTickLabels(true),
32580   //mTickLabelRotation(0), in label painter
32581   mTickLabelFont(mParentPlot->font()),
32582   mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
32583   mTickLabelColor(Qt::black),
32584   mSelectedTickLabelColor(Qt::blue),
32585   mNumberPrecision(6),
32586   mNumberFormatChar('g'),
32587   mNumberBeautifulPowers(true),
32588   mNumberMultiplyCross(false),
32589   // ticks and subticks:
32590   mTicks(true),
32591   mSubTicks(true),
32592   mTickLengthIn(5),
32593   mTickLengthOut(0),
32594   mSubTickLengthIn(2),
32595   mSubTickLengthOut(0),
32596   mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
32597   mSelectedTickPen(QPen(Qt::blue, 2)),
32598   mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
32599   mSelectedSubTickPen(QPen(Qt::blue, 2)),
32600   // scale and range:
32601   mRange(0, 360),
32602   mRangeReversed(false),
32603   // internal members:
32604   mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
32605   mGrid(new QCPPolarGrid(this)),
32606   mTicker(new QCPAxisTickerFixed),
32607   mDragging(false),
32608   mLabelPainter(parentPlot)
32609 {
32610   // TODO:
32611   //mInsetLayout->initializeParentPlot(mParentPlot);
32612   //mInsetLayout->setParentLayerable(this);
32613   //mInsetLayout->setParent(this);
32614  
32615   if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
32616   {
32617     fixedTicker->setTickStep(30);
32618   }
32619   setAntialiased(true);
32620   setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
32621   
32622   setTickLabelPadding(5);
32623   setTickLabelRotation(0);
32624   setTickLabelMode(lmUpright);
32625   mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal);
32626   mLabelPainter.setAbbreviateDecimalPowers(false);
32627   mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
32628   
32629   setMinimumSize(50, 50);
32630   setMinimumMargins(QMargins(30, 30, 30, 30));
32631   
32632   addRadialAxis();
32633   mGrid->setRadialAxis(radialAxis());
32634 }
32635 
32636 QCPPolarAxisAngular::~QCPPolarAxisAngular()
32637 {
32638   delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
32639   mGrid = 0;
32640   
32641   delete mInsetLayout;
32642   mInsetLayout = 0;
32643   
32644   QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
32645   for (int i=0; i<radialAxesList.size(); ++i)
32646     removeRadialAxis(radialAxesList.at(i));
32647 }
32648 
32649 QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
32650 {
32651   switch (mLabelPainter.anchorMode())
32652   {
32653     case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
32654     case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
32655     default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
32656   }
32657   return lmUpright;
32658 }
32659 
32660 /* No documentation as it is a property getter */
32661 QString QCPPolarAxisAngular::numberFormat() const
32662 {
32663   QString result;
32664   result.append(mNumberFormatChar);
32665   if (mNumberBeautifulPowers)
32666   {
32667     result.append(QLatin1Char('b'));
32668     if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
32669       result.append(QLatin1Char('c'));
32670   }
32671   return result;
32672 }
32673 
32674 /*!
32675   Returns the number of axes on the axis rect side specified with \a type.
32676   
32677   \see axis
32678 */
32679 int QCPPolarAxisAngular::radialAxisCount() const
32680 {
32681   return mRadialAxes.size();
32682 }
32683 
32684 /*!
32685   Returns the axis with the given \a index on the axis rect side specified with \a type.
32686   
32687   \see axisCount, axes
32688 */
32689 QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
32690 {
32691   if (index >= 0 && index < mRadialAxes.size())
32692   {
32693     return mRadialAxes.at(index);
32694   } else
32695   {
32696     qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
32697     return 0;
32698   }
32699 }
32700 
32701 /*!
32702   Returns all axes on the axis rect sides specified with \a types.
32703   
32704   \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
32705   multiple sides.
32706   
32707   \see axis
32708 */
32709 QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
32710 {
32711   return mRadialAxes;
32712 }
32713 
32714 
32715 /*!
32716   Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
32717   new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
32718   remove an axis, use \ref removeAxis instead of deleting it manually.
32719 
32720   You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
32721   previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
32722   of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
32723   with this axis rect as parent and with the same axis type as specified in \a type. If this is not
32724   the case, a debug output is generated, the axis is not added, and the method returns 0.
32725 
32726   This method can not be used to move \a axis between axis rects. The same \a axis instance must
32727   not be added multiple times to the same or different axis rects.
32728 
32729   If an axis rect side already contains one or more axes, the lower and upper endings of the new
32730   axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
32731   QCPLineEnding::esHalfBar.
32732 
32733   \see addAxes, setupFullAxesBox
32734 */
32735 QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
32736 {
32737   QCPPolarAxisRadial *newAxis = axis;
32738   if (!newAxis)
32739   {
32740     newAxis = new QCPPolarAxisRadial(this);
32741   } else // user provided existing axis instance, do some sanity checks
32742   {
32743     if (newAxis->angularAxis() != this)
32744     {
32745       qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
32746       return 0;
32747     }
32748     if (radialAxes().contains(newAxis))
32749     {
32750       qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
32751       return 0;
32752     }
32753   }
32754   mRadialAxes.append(newAxis);
32755   return newAxis;
32756 }
32757 
32758 /*!
32759   Removes the specified \a axis from the axis rect and deletes it.
32760   
32761   Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
32762   
32763   \see addAxis
32764 */
32765 bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
32766 {
32767   if (mRadialAxes.contains(radialAxis))
32768   {
32769     mRadialAxes.removeOne(radialAxis);
32770     delete radialAxis;
32771     return true;
32772   } else
32773   {
32774     qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
32775     return false;
32776   }
32777 }
32778 
32779 QRegion QCPPolarAxisAngular::exactClipRegion() const
32780 {
32781   return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
32782 }
32783 
32784 /*!
32785   If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
32786   bounds of the range. The range is simply moved by \a diff.
32787   
32788   If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
32789   corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
32790 */
32791 void QCPPolarAxisAngular::moveRange(double diff)
32792 {
32793   QCPRange oldRange = mRange;
32794   mRange.lower += diff;
32795   mRange.upper += diff;
32796   emit rangeChanged(mRange);
32797   emit rangeChanged(mRange, oldRange);
32798 }
32799 
32800 /*!
32801   Scales the range of this axis by \a factor around the center of the current axis range. For
32802   example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
32803   range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
32804   the center will have moved symmetrically closer).
32805 
32806   If you wish to scale around a different coordinate than the current axis range center, use the
32807   overload \ref scaleRange(double factor, double center).
32808 */
32809 void QCPPolarAxisAngular::scaleRange(double factor)
32810 {
32811   scaleRange(factor, range().center());
32812 }
32813 
32814 /*! \overload
32815 
32816   Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
32817   factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
32818   coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
32819   around 1.0 will have moved symmetrically closer to 1.0).
32820 
32821   \see scaleRange(double factor)
32822 */
32823 void QCPPolarAxisAngular::scaleRange(double factor, double center)
32824 {
32825   QCPRange oldRange = mRange;
32826   QCPRange newRange;
32827   newRange.lower = (mRange.lower-center)*factor + center;
32828   newRange.upper = (mRange.upper-center)*factor + center;
32829   if (QCPRange::validRange(newRange))
32830     mRange = newRange.sanitizedForLinScale();
32831   emit rangeChanged(mRange);
32832   emit rangeChanged(mRange, oldRange);
32833 }
32834 
32835 /*!
32836   Changes the axis range such that all plottables associated with this axis are fully visible in
32837   that dimension.
32838   
32839   \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
32840 */
32841 void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
32842 {
32843   QCPRange newRange;
32844   bool haveRange = false;
32845   for (int i=0; i<mGraphs.size(); ++i)
32846   {
32847     if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
32848       continue;
32849     QCPRange range;
32850     bool currentFoundRange;
32851     if (mGraphs.at(i)->keyAxis() == this)
32852       range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth);
32853     else
32854       range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth);
32855     if (currentFoundRange)
32856     {
32857       if (!haveRange)
32858         newRange = range;
32859       else
32860         newRange.expand(range);
32861       haveRange = true;
32862     }
32863   }
32864   if (haveRange)
32865   {
32866     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
32867     {
32868       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
32869       newRange.lower = center-mRange.size()/2.0;
32870       newRange.upper = center+mRange.size()/2.0;
32871     }
32872     setRange(newRange);
32873   }
32874 }
32875 
32876 /*!
32877   Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
32878 */
32879 void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
32880 {
32881   if (!mRadialAxes.isEmpty())
32882     mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
32883   else
32884     qDebug() << Q_FUNC_INFO << "no radial axis configured";
32885 }
32886 
32887 /*!
32888   Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
32889 */
32890 QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
32891 {
32892   if (!mRadialAxes.isEmpty())
32893   {
32894     return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
32895   } else
32896   {
32897     qDebug() << Q_FUNC_INFO << "no radial axis configured";
32898     return QPointF();
32899   }
32900 }
32901 
32902 /*!
32903   Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
32904   is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
32905   function does not change the current selection state of the axis.
32906   
32907   If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
32908   
32909   \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
32910 */
32911 QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
32912 {
32913   Q_UNUSED(pos) // TODO remove later
32914   
32915   if (!mVisible)
32916     return spNone;
32917   
32918   /*
32919     TODO:
32920   if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
32921     return spAxis;
32922   else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
32923     return spTickLabels;
32924   else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
32925     return spAxisLabel;
32926   else */
32927     return spNone;
32928 }
32929 
32930 /* inherits documentation from base class */
32931 double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
32932 {
32933   /*
32934   if (!mParentPlot) return -1;
32935   SelectablePart part = getPartAt(pos);
32936   if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
32937     return -1;
32938   
32939   if (details)
32940     details->setValue(part);
32941   return mParentPlot->selectionTolerance()*0.99;
32942   */
32943   
32944   Q_UNUSED(details)
32945   
32946   if (onlySelectable)
32947     return -1;
32948   
32949   if (QRectF(mOuterRect).contains(pos))
32950   {
32951     if (mParentPlot)
32952       return mParentPlot->selectionTolerance()*0.99;
32953     else
32954     {
32955       qDebug() << Q_FUNC_INFO << "parent plot not defined";
32956       return -1;
32957     }
32958   } else
32959     return -1;
32960 }
32961 
32962 /*!
32963   This method is called automatically upon replot and doesn't need to be called by users of
32964   QCPPolarAxisAngular.
32965   
32966   Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
32967   and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
32968   QCPInsetLayout::update function.
32969   
32970   \seebaseclassmethod
32971 */
32972 void QCPPolarAxisAngular::update(UpdatePhase phase)
32973 {
32974   QCPLayoutElement::update(phase);
32975   
32976   switch (phase)
32977   {
32978     case upPreparation:
32979     {
32980       setupTickVectors();
32981       for (int i=0; i<mRadialAxes.size(); ++i)
32982         mRadialAxes.at(i)->setupTickVectors();
32983       break;
32984     }
32985     case upLayout:
32986     {
32987       mCenter = mRect.center();
32988       mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
32989       if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
32990       for (int i=0; i<mRadialAxes.size(); ++i)
32991         mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
32992       
32993       mInsetLayout->setOuterRect(rect());
32994       break;
32995     }
32996     default: break;
32997   }
32998   
32999   // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
33000   mInsetLayout->update(phase);
33001 }
33002 
33003 /* inherits documentation from base class */
33004 QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
33005 {
33006   QList<QCPLayoutElement*> result;
33007   if (mInsetLayout)
33008   {
33009     result << mInsetLayout;
33010     if (recursive)
33011       result << mInsetLayout->elements(recursive);
33012   }
33013   return result;
33014 }
33015 
33016 bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
33017 {
33018   if (!mGraphs.contains(graph))
33019   {
33020     qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
33021     return false;
33022   }
33023   
33024   // remove plottable from legend:
33025   graph->removeFromLegend();
33026   // remove plottable:
33027   delete graph;
33028   mGraphs.removeOne(graph);
33029   return true;
33030 }
33031 
33032 /* inherits documentation from base class */
33033 void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
33034 {
33035   applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
33036 }
33037 
33038 /* inherits documentation from base class */
33039 void QCPPolarAxisAngular::draw(QCPPainter *painter)
33040 {
33041   drawBackground(painter, mCenter, mRadius);
33042   
33043   // draw baseline circle:
33044   painter->setPen(getBasePen());
33045   painter->drawEllipse(mCenter, mRadius, mRadius);
33046   
33047   // draw subticks:
33048   if (!mSubTickVector.isEmpty())
33049   {
33050     painter->setPen(getSubTickPen());
33051     for (int i=0; i<mSubTickVector.size(); ++i)
33052     {
33053       painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
33054                         mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
33055     }
33056   }
33057   
33058   // draw ticks and labels:
33059   if (!mTickVector.isEmpty())
33060   {
33061     mLabelPainter.setAnchorReference(mCenter);
33062     mLabelPainter.setFont(getTickLabelFont());
33063     mLabelPainter.setColor(getTickLabelColor());
33064     const QPen ticksPen = getTickPen();
33065     painter->setPen(ticksPen);
33066     for (int i=0; i<mTickVector.size(); ++i)
33067     {
33068       const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
33069       painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
33070       // draw tick labels:
33071       if (!mTickVectorLabels.isEmpty())
33072       {
33073         if (i < mTickVectorLabels.count()-1 || (mTickVectorCosSin.at(i)-mTickVectorCosSin.first()).manhattanLength() > 5/180.0*M_PI) // skip last label if it's closer than approx 5 degrees to first
33074           mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
33075       }
33076     }
33077   }
33078 }
33079 
33080 /* inherits documentation from base class */
33081 QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
33082 {
33083   return QCP::iSelectAxes;
33084 }
33085 
33086 
33087 /*!
33088   Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
33089   axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
33090   backgrounds are usually drawn below everything else.
33091 
33092   For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
33093   enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
33094   is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
33095   consider using the overloaded version of this function.
33096 
33097   Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
33098   setBackground(const QBrush &brush).
33099   
33100   \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
33101 */
33102 void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
33103 {
33104   mBackgroundPixmap = pm;
33105   mScaledBackgroundPixmap = QPixmap();
33106 }
33107 
33108 /*! \overload
33109   
33110   Sets \a brush as the background brush. The axis rect background will be filled with this brush.
33111   Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
33112   are usually drawn below everything else.
33113 
33114   The brush will be drawn before (under) any background pixmap, which may be specified with \ref
33115   setBackground(const QPixmap &pm).
33116 
33117   To disable drawing of a background brush, set \a brush to Qt::NoBrush.
33118   
33119   \see setBackground(const QPixmap &pm)
33120 */
33121 void QCPPolarAxisAngular::setBackground(const QBrush &brush)
33122 {
33123   mBackgroundBrush = brush;
33124 }
33125 
33126 /*! \overload
33127   
33128   Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
33129   shall be scaled in one call.
33130 
33131   \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
33132 */
33133 void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
33134 {
33135   mBackgroundPixmap = pm;
33136   mScaledBackgroundPixmap = QPixmap();
33137   mBackgroundScaled = scaled;
33138   mBackgroundScaledMode = mode;
33139 }
33140 
33141 /*!
33142   Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
33143   is set to true, you may control whether and how the aspect ratio of the original pixmap is
33144   preserved with \ref setBackgroundScaledMode.
33145   
33146   Note that the scaled version of the original pixmap is buffered, so there is no performance
33147   penalty on replots. (Except when the axis rect dimensions are changed continuously.)
33148   
33149   \see setBackground, setBackgroundScaledMode
33150 */
33151 void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
33152 {
33153   mBackgroundScaled = scaled;
33154 }
33155 
33156 /*!
33157   If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
33158   define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
33159   \see setBackground, setBackgroundScaled
33160 */
33161 void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
33162 {
33163   mBackgroundScaledMode = mode;
33164 }
33165 
33166 void QCPPolarAxisAngular::setRangeDrag(bool enabled)
33167 {
33168   mRangeDrag = enabled;
33169 }
33170 
33171 void QCPPolarAxisAngular::setRangeZoom(bool enabled)
33172 {
33173   mRangeZoom = enabled;
33174 }
33175 
33176 void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
33177 {
33178   mRangeZoomFactor = factor;
33179 }
33180 
33181 
33182 
33183 
33184 
33185 
33186 
33187 /*!
33188   Sets the range of the axis.
33189   
33190   This slot may be connected with the \ref rangeChanged signal of another axis so this axis
33191   is always synchronized with the other axis range, when it changes.
33192   
33193   To invert the direction of an axis, use \ref setRangeReversed.
33194 */
33195 void QCPPolarAxisAngular::setRange(const QCPRange &range)
33196 {
33197   if (range.lower == mRange.lower && range.upper == mRange.upper)
33198     return;
33199   
33200   if (!QCPRange::validRange(range)) return;
33201   QCPRange oldRange = mRange;
33202   mRange = range.sanitizedForLinScale();
33203   emit rangeChanged(mRange);
33204   emit rangeChanged(mRange, oldRange);
33205 }
33206 
33207 /*!
33208   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
33209   (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
33210   
33211   However, even when \a selectable is set to a value not allowing the selection of a specific part,
33212   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
33213   directly.
33214   
33215   \see SelectablePart, setSelectedParts
33216 */
33217 void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
33218 {
33219   if (mSelectableParts != selectable)
33220   {
33221     mSelectableParts = selectable;
33222     emit selectableChanged(mSelectableParts);
33223   }
33224 }
33225 
33226 /*!
33227   Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
33228   is selected, it uses a different pen/font.
33229   
33230   The entire selection mechanism for axes is handled automatically when \ref
33231   QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
33232   wish to change the selection state manually.
33233   
33234   This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
33235   
33236   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
33237   
33238   \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
33239   setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
33240 */
33241 void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
33242 {
33243   if (mSelectedParts != selected)
33244   {
33245     mSelectedParts = selected;
33246     emit selectionChanged(mSelectedParts);
33247   }
33248 }
33249 
33250 /*!
33251   \overload
33252   
33253   Sets the lower and upper bound of the axis range.
33254   
33255   To invert the direction of an axis, use \ref setRangeReversed.
33256   
33257   There is also a slot to set a range, see \ref setRange(const QCPRange &range).
33258 */
33259 void QCPPolarAxisAngular::setRange(double lower, double upper)
33260 {
33261   if (lower == mRange.lower && upper == mRange.upper)
33262     return;
33263   
33264   if (!QCPRange::validRange(lower, upper)) return;
33265   QCPRange oldRange = mRange;
33266   mRange.lower = lower;
33267   mRange.upper = upper;
33268   mRange = mRange.sanitizedForLinScale();
33269   emit rangeChanged(mRange);
33270   emit rangeChanged(mRange, oldRange);
33271 }
33272 
33273 /*!
33274   \overload
33275   
33276   Sets the range of the axis.
33277   
33278   The \a position coordinate indicates together with the \a alignment parameter, where the new
33279   range will be positioned. \a size defines the size of the new axis range. \a alignment may be
33280   Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
33281   or center of the range to be aligned with \a position. Any other values of \a alignment will
33282   default to Qt::AlignCenter.
33283 */
33284 void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
33285 {
33286   if (alignment == Qt::AlignLeft)
33287     setRange(position, position+size);
33288   else if (alignment == Qt::AlignRight)
33289     setRange(position-size, position);
33290   else // alignment == Qt::AlignCenter
33291     setRange(position-size/2.0, position+size/2.0);
33292 }
33293 
33294 /*!
33295   Sets the lower bound of the axis range. The upper bound is not changed.
33296   \see setRange
33297 */
33298 void QCPPolarAxisAngular::setRangeLower(double lower)
33299 {
33300   if (mRange.lower == lower)
33301     return;
33302   
33303   QCPRange oldRange = mRange;
33304   mRange.lower = lower;
33305   mRange = mRange.sanitizedForLinScale();
33306   emit rangeChanged(mRange);
33307   emit rangeChanged(mRange, oldRange);
33308 }
33309 
33310 /*!
33311   Sets the upper bound of the axis range. The lower bound is not changed.
33312   \see setRange
33313 */
33314 void QCPPolarAxisAngular::setRangeUpper(double upper)
33315 {
33316   if (mRange.upper == upper)
33317     return;
33318   
33319   QCPRange oldRange = mRange;
33320   mRange.upper = upper;
33321   mRange = mRange.sanitizedForLinScale();
33322   emit rangeChanged(mRange);
33323   emit rangeChanged(mRange, oldRange);
33324 }
33325 
33326 /*!
33327   Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
33328   axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
33329   direction of increasing values is inverted.
33330 
33331   Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
33332   of the \ref setRange interface will still reference the mathematically smaller number than the \a
33333   upper part.
33334 */
33335 void QCPPolarAxisAngular::setRangeReversed(bool reversed)
33336 {
33337   mRangeReversed = reversed;
33338 }
33339 
33340 void QCPPolarAxisAngular::setAngle(double degrees)
33341 {
33342   mAngle = degrees;
33343   mAngleRad = mAngle/180.0*M_PI;
33344 }
33345 
33346 /*!
33347   The axis ticker is responsible for generating the tick positions and tick labels. See the
33348   documentation of QCPAxisTicker for details on how to work with axis tickers.
33349   
33350   You can change the tick positioning/labeling behaviour of this axis by setting a different
33351   QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
33352   ticker, access it via \ref ticker.
33353   
33354   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
33355   ticker simply by passing the same shared pointer to multiple axes.
33356   
33357   \see ticker
33358 */
33359 void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
33360 {
33361   if (ticker)
33362     mTicker = ticker;
33363   else
33364     qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
33365   // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
33366 }
33367 
33368 /*!
33369   Sets whether tick marks are displayed.
33370 
33371   Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
33372   that, see \ref setTickLabels.
33373   
33374   \see setSubTicks
33375 */
33376 void QCPPolarAxisAngular::setTicks(bool show)
33377 {
33378   if (mTicks != show)
33379   {
33380     mTicks = show;
33381     //mCachedMarginValid = false;
33382   }
33383 }
33384 
33385 /*!
33386   Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
33387 */
33388 void QCPPolarAxisAngular::setTickLabels(bool show)
33389 {
33390   if (mTickLabels != show)
33391   {
33392     mTickLabels = show;
33393     //mCachedMarginValid = false;
33394     if (!mTickLabels)
33395       mTickVectorLabels.clear();
33396   }
33397 }
33398 
33399 /*!
33400   Sets the distance between the axis base line (including any outward ticks) and the tick labels.
33401   \see setLabelPadding, setPadding
33402 */
33403 void QCPPolarAxisAngular::setTickLabelPadding(int padding)
33404 {
33405   mLabelPainter.setPadding(padding);
33406 }
33407 
33408 /*!
33409   Sets the font of the tick labels.
33410   
33411   \see setTickLabels, setTickLabelColor
33412 */
33413 void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
33414 {
33415   mTickLabelFont = font;
33416 }
33417 
33418 /*!
33419   Sets the color of the tick labels.
33420   
33421   \see setTickLabels, setTickLabelFont
33422 */
33423 void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
33424 {
33425   mTickLabelColor = color;
33426 }
33427 
33428 /*!
33429   Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
33430   the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
33431   from -90 to 90 degrees.
33432   
33433   If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
33434   other angles, the label is drawn with an offset such that it seems to point toward or away from
33435   the tick mark.
33436 */
33437 void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
33438 {
33439   mLabelPainter.setRotation(degrees);
33440 }
33441 
33442 void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
33443 {
33444   switch (mode)
33445   {
33446     case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
33447     case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
33448   }
33449 }
33450 
33451 /*!
33452   Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
33453   of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
33454   that, see the "Argument Formats" section in the detailed description of the QString class.
33455   
33456   \a formatCode is a string of one, two or three characters. The first character is identical to
33457   the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
33458   format, 'g'/'G' scientific or fixed, whichever is shorter.
33459   
33460   The second and third characters are optional and specific to QCustomPlot:\n If the first char was
33461   'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
33462   visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
33463   "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
33464   [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
33465   If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
33466   be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
33467   cross and 183 (0xB7) for the dot.
33468   
33469   Examples for \a formatCode:
33470   \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
33471   normal scientific format is used
33472   \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
33473   beautifully typeset decimal powers and a dot as multiplication sign
33474   \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
33475   multiplication sign
33476   \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
33477   powers. Format code will be reduced to 'f'.
33478   \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
33479   code will not be changed.
33480 */
33481 void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
33482 {
33483   if (formatCode.isEmpty())
33484   {
33485     qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
33486     return;
33487   }
33488   //mCachedMarginValid = false;
33489   
33490   // interpret first char as number format char:
33491   QString allowedFormatChars(QLatin1String("eEfgG"));
33492   if (allowedFormatChars.contains(formatCode.at(0)))
33493   {
33494     mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
33495   } else
33496   {
33497     qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
33498     return;
33499   }
33500   
33501   if (formatCode.length() < 2)
33502   {
33503     mNumberBeautifulPowers = false;
33504     mNumberMultiplyCross = false;
33505   } else
33506   {
33507     // interpret second char as indicator for beautiful decimal powers:
33508     if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
33509       mNumberBeautifulPowers = true;
33510     else
33511       qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
33512     
33513     if (formatCode.length() < 3)
33514     {
33515       mNumberMultiplyCross = false;
33516     } else
33517     {
33518       // interpret third char as indicator for dot or cross multiplication symbol:
33519       if (formatCode.at(2) == QLatin1Char('c'))
33520         mNumberMultiplyCross = true;
33521       else if (formatCode.at(2) == QLatin1Char('d'))
33522         mNumberMultiplyCross = false;
33523       else
33524         qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
33525     }
33526   }
33527   mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
33528   mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
33529 }
33530 
33531 /*!
33532   Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
33533   for details. The effect of precisions are most notably for number Formats starting with 'e', see
33534   \ref setNumberFormat
33535 */
33536 void QCPPolarAxisAngular::setNumberPrecision(int precision)
33537 {
33538   if (mNumberPrecision != precision)
33539   {
33540     mNumberPrecision = precision;
33541     //mCachedMarginValid = false;
33542   }
33543 }
33544 
33545 /*!
33546   Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
33547   plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
33548   zero, the tick labels and axis label will increase their distance to the axis accordingly, so
33549   they won't collide with the ticks.
33550   
33551   \see setSubTickLength, setTickLengthIn, setTickLengthOut
33552 */
33553 void QCPPolarAxisAngular::setTickLength(int inside, int outside)
33554 {
33555   setTickLengthIn(inside);
33556   setTickLengthOut(outside);
33557 }
33558 
33559 /*!
33560   Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
33561   inside the plot.
33562   
33563   \see setTickLengthOut, setTickLength, setSubTickLength
33564 */
33565 void QCPPolarAxisAngular::setTickLengthIn(int inside)
33566 {
33567   if (mTickLengthIn != inside)
33568   {
33569     mTickLengthIn = inside;
33570   }
33571 }
33572 
33573 /*!
33574   Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
33575   outside the plot. If \a outside is greater than zero, the tick labels and axis label will
33576   increase their distance to the axis accordingly, so they won't collide with the ticks.
33577   
33578   \see setTickLengthIn, setTickLength, setSubTickLength
33579 */
33580 void QCPPolarAxisAngular::setTickLengthOut(int outside)
33581 {
33582   if (mTickLengthOut != outside)
33583   {
33584     mTickLengthOut = outside;
33585     //mCachedMarginValid = false; // only outside tick length can change margin
33586   }
33587 }
33588 
33589 /*!
33590   Sets whether sub tick marks are displayed.
33591   
33592   Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
33593   
33594   \see setTicks
33595 */
33596 void QCPPolarAxisAngular::setSubTicks(bool show)
33597 {
33598   if (mSubTicks != show)
33599   {
33600     mSubTicks = show;
33601     //mCachedMarginValid = false;
33602   }
33603 }
33604 
33605 /*!
33606   Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
33607   the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
33608   than zero, the tick labels and axis label will increase their distance to the axis accordingly,
33609   so they won't collide with the ticks.
33610   
33611   \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
33612 */
33613 void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
33614 {
33615   setSubTickLengthIn(inside);
33616   setSubTickLengthOut(outside);
33617 }
33618 
33619 /*!
33620   Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
33621   the plot.
33622   
33623   \see setSubTickLengthOut, setSubTickLength, setTickLength
33624 */
33625 void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
33626 {
33627   if (mSubTickLengthIn != inside)
33628   {
33629     mSubTickLengthIn = inside;
33630   }
33631 }
33632 
33633 /*!
33634   Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
33635   outside the plot. If \a outside is greater than zero, the tick labels will increase their
33636   distance to the axis accordingly, so they won't collide with the ticks.
33637   
33638   \see setSubTickLengthIn, setSubTickLength, setTickLength
33639 */
33640 void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
33641 {
33642   if (mSubTickLengthOut != outside)
33643   {
33644     mSubTickLengthOut = outside;
33645     //mCachedMarginValid = false; // only outside tick length can change margin
33646   }
33647 }
33648 
33649 /*!
33650   Sets the pen, the axis base line is drawn with.
33651   
33652   \see setTickPen, setSubTickPen
33653 */
33654 void QCPPolarAxisAngular::setBasePen(const QPen &pen)
33655 {
33656   mBasePen = pen;
33657 }
33658 
33659 /*!
33660   Sets the pen, tick marks will be drawn with.
33661   
33662   \see setTickLength, setBasePen
33663 */
33664 void QCPPolarAxisAngular::setTickPen(const QPen &pen)
33665 {
33666   mTickPen = pen;
33667 }
33668 
33669 /*!
33670   Sets the pen, subtick marks will be drawn with.
33671   
33672   \see setSubTickCount, setSubTickLength, setBasePen
33673 */
33674 void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
33675 {
33676   mSubTickPen = pen;
33677 }
33678 
33679 /*!
33680   Sets the font of the axis label.
33681   
33682   \see setLabelColor
33683 */
33684 void QCPPolarAxisAngular::setLabelFont(const QFont &font)
33685 {
33686   if (mLabelFont != font)
33687   {
33688     mLabelFont = font;
33689     //mCachedMarginValid = false;
33690   }
33691 }
33692 
33693 /*!
33694   Sets the color of the axis label.
33695   
33696   \see setLabelFont
33697 */
33698 void QCPPolarAxisAngular::setLabelColor(const QColor &color)
33699 {
33700   mLabelColor = color;
33701 }
33702 
33703 /*!
33704   Sets the text of the axis label that will be shown below/above or next to the axis, depending on
33705   its orientation. To disable axis labels, pass an empty string as \a str.
33706 */
33707 void QCPPolarAxisAngular::setLabel(const QString &str)
33708 {
33709   if (mLabel != str)
33710   {
33711     mLabel = str;
33712     //mCachedMarginValid = false;
33713   }
33714 }
33715 
33716 /*!
33717   Sets the distance between the tick labels and the axis label.
33718   
33719   \see setTickLabelPadding, setPadding
33720 */
33721 void QCPPolarAxisAngular::setLabelPadding(int padding)
33722 {
33723   if (mLabelPadding != padding)
33724   {
33725     mLabelPadding = padding;
33726     //mCachedMarginValid = false;
33727   }
33728 }
33729 
33730 /*!
33731   Sets the font that is used for tick labels when they are selected.
33732   
33733   \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33734 */
33735 void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
33736 {
33737   if (font != mSelectedTickLabelFont)
33738   {
33739     mSelectedTickLabelFont = font;
33740     // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
33741   }
33742 }
33743 
33744 /*!
33745   Sets the font that is used for the axis label when it is selected.
33746   
33747   \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33748 */
33749 void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
33750 {
33751   mSelectedLabelFont = font;
33752   // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
33753 }
33754 
33755 /*!
33756   Sets the color that is used for tick labels when they are selected.
33757   
33758   \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33759 */
33760 void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
33761 {
33762   if (color != mSelectedTickLabelColor)
33763   {
33764     mSelectedTickLabelColor = color;
33765   }
33766 }
33767 
33768 /*!
33769   Sets the color that is used for the axis label when it is selected.
33770   
33771   \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33772 */
33773 void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
33774 {
33775   mSelectedLabelColor = color;
33776 }
33777 
33778 /*!
33779   Sets the pen that is used to draw the axis base line when selected.
33780   
33781   \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33782 */
33783 void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
33784 {
33785   mSelectedBasePen = pen;
33786 }
33787 
33788 /*!
33789   Sets the pen that is used to draw the (major) ticks when selected.
33790   
33791   \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33792 */
33793 void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
33794 {
33795   mSelectedTickPen = pen;
33796 }
33797 
33798 /*!
33799   Sets the pen that is used to draw the subticks when selected.
33800   
33801   \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
33802 */
33803 void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
33804 {
33805   mSelectedSubTickPen = pen;
33806 }
33807 
33808 /*! \internal
33809   
33810   Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
33811   pixmap.
33812   
33813   If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
33814   according filling inside the axis rect with the provided \a painter.
33815   
33816   Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
33817   depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
33818   the axis rect with the provided \a painter. The scaled version is buffered in
33819   mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
33820   the axis rect has changed in a way that requires a rescale of the background pixmap (this is
33821   dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
33822   set.
33823   
33824   \see setBackground, setBackgroundScaled, setBackgroundScaledMode
33825 */
33826 void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF &center, double radius)
33827 {
33828   // draw background fill (don't use circular clip, looks bad):
33829   if (mBackgroundBrush != Qt::NoBrush)
33830   {
33831     QPainterPath ellipsePath;
33832     ellipsePath.addEllipse(center, radius, radius);
33833     painter->fillPath(ellipsePath, mBackgroundBrush);
33834   }
33835   
33836   // draw background pixmap (on top of fill, if brush specified):
33837   if (!mBackgroundPixmap.isNull())
33838   {
33839     QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
33840     QRegion originalClip = painter->clipRegion();
33841     painter->setClipRegion(clipCircle);
33842     if (mBackgroundScaled)
33843     {
33844       // check whether mScaledBackground needs to be updated:
33845       QSize scaledSize(mBackgroundPixmap.size());
33846       scaledSize.scale(mRect.size(), mBackgroundScaledMode);
33847       if (mScaledBackgroundPixmap.size() != scaledSize)
33848         mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
33849       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
33850     } else
33851     {
33852       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
33853     }
33854     painter->setClipRegion(originalClip);
33855   }
33856 }
33857 
33858 /*! \internal
33859   
33860   Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
33861   QCPAxisTicker::generate on the currently installed ticker.
33862   
33863   If a change in the label text/count is detected, the cached axis margin is invalidated to make
33864   sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
33865 */
33866 void QCPPolarAxisAngular::setupTickVectors()
33867 {
33868   if (!mParentPlot) return;
33869   if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
33870   
33871   mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
33872   mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
33873   
33874   // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
33875   mTickVectorCosSin.resize(mTickVector.size());
33876   for (int i=0; i<mTickVector.size(); ++i)
33877   {
33878     const double theta = coordToAngleRad(mTickVector.at(i));
33879     mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
33880   }
33881   mSubTickVectorCosSin.resize(mSubTickVector.size());
33882   for (int i=0; i<mSubTickVector.size(); ++i)
33883   {
33884     const double theta = coordToAngleRad(mSubTickVector.at(i));
33885     mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
33886   }
33887 }
33888 
33889 /*! \internal
33890   
33891   Returns the pen that is used to draw the axis base line. Depending on the selection state, this
33892   is either mSelectedBasePen or mBasePen.
33893 */
33894 QPen QCPPolarAxisAngular::getBasePen() const
33895 {
33896   return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
33897 }
33898 
33899 /*! \internal
33900   
33901   Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
33902   is either mSelectedTickPen or mTickPen.
33903 */
33904 QPen QCPPolarAxisAngular::getTickPen() const
33905 {
33906   return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
33907 }
33908 
33909 /*! \internal
33910   
33911   Returns the pen that is used to draw the subticks. Depending on the selection state, this
33912   is either mSelectedSubTickPen or mSubTickPen.
33913 */
33914 QPen QCPPolarAxisAngular::getSubTickPen() const
33915 {
33916   return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
33917 }
33918 
33919 /*! \internal
33920   
33921   Returns the font that is used to draw the tick labels. Depending on the selection state, this
33922   is either mSelectedTickLabelFont or mTickLabelFont.
33923 */
33924 QFont QCPPolarAxisAngular::getTickLabelFont() const
33925 {
33926   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
33927 }
33928 
33929 /*! \internal
33930   
33931   Returns the font that is used to draw the axis label. Depending on the selection state, this
33932   is either mSelectedLabelFont or mLabelFont.
33933 */
33934 QFont QCPPolarAxisAngular::getLabelFont() const
33935 {
33936   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
33937 }
33938 
33939 /*! \internal
33940   
33941   Returns the color that is used to draw the tick labels. Depending on the selection state, this
33942   is either mSelectedTickLabelColor or mTickLabelColor.
33943 */
33944 QColor QCPPolarAxisAngular::getTickLabelColor() const
33945 {
33946   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
33947 }
33948 
33949 /*! \internal
33950   
33951   Returns the color that is used to draw the axis label. Depending on the selection state, this
33952   is either mSelectedLabelColor or mLabelColor.
33953 */
33954 QColor QCPPolarAxisAngular::getLabelColor() const
33955 {
33956   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
33957 }
33958 
33959 /*! \internal
33960   
33961   Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
33962   pressed, the range dragging interaction is initialized (the actual range manipulation happens in
33963   the \ref mouseMoveEvent).
33964 
33965   The mDragging flag is set to true and some anchor points are set that are needed to determine the
33966   distance the mouse was dragged in the mouse move/release events later.
33967   
33968   \see mouseMoveEvent, mouseReleaseEvent
33969 */
33970 void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
33971 {
33972   Q_UNUSED(details)
33973   if (event->buttons() & Qt::LeftButton)
33974   {
33975     mDragging = true;
33976     // initialize antialiasing backup in case we start dragging:
33977     if (mParentPlot->noAntialiasingOnDrag())
33978     {
33979       mAADragBackup = mParentPlot->antialiasedElements();
33980       mNotAADragBackup = mParentPlot->notAntialiasedElements();
33981     }
33982     // Mouse range dragging interaction:
33983     if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
33984     {
33985       mDragAngularStart = range();
33986       mDragRadialStart.clear();
33987       for (int i=0; i<mRadialAxes.size(); ++i)
33988         mDragRadialStart.append(mRadialAxes.at(i)->range());
33989     }
33990   }
33991 }
33992 
33993 /*! \internal
33994   
33995   Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
33996   preceding \ref mousePressEvent, the range is moved accordingly.
33997   
33998   \see mousePressEvent, mouseReleaseEvent
33999 */
34000 void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
34001 {
34002   Q_UNUSED(startPos)
34003   bool doReplot = false;
34004   // Mouse range dragging interaction:
34005   if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
34006   {
34007     if (mRangeDrag)
34008     {
34009       doReplot = true;
34010       double angleCoordStart, radiusCoordStart;
34011       double angleCoord, radiusCoord;
34012       pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
34013       pixelToCoord(event->pos(), angleCoord, radiusCoord);
34014       double diff = angleCoordStart - angleCoord;
34015       setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
34016     }
34017     
34018     for (int i=0; i<mRadialAxes.size(); ++i)
34019     {
34020       QCPPolarAxisRadial *ax = mRadialAxes.at(i);
34021       if (!ax->rangeDrag())
34022         continue;
34023       doReplot = true;
34024       double angleCoordStart, radiusCoordStart;
34025       double angleCoord, radiusCoord;
34026       ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
34027       ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
34028       if (ax->scaleType() == QCPPolarAxisRadial::stLinear)
34029       {
34030         double diff = radiusCoordStart - radiusCoord;
34031         ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
34032       } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic)
34033       {
34034         if (radiusCoord != 0)
34035         {
34036           double diff = radiusCoordStart/radiusCoord;
34037           ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
34038         }
34039       }
34040     }
34041     
34042     if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
34043     {
34044       if (mParentPlot->noAntialiasingOnDrag())
34045         mParentPlot->setNotAntialiasedElements(QCP::aeAll);
34046       mParentPlot->replot(QCustomPlot::rpQueuedReplot);
34047     }
34048   }
34049 }
34050 
34051 /* inherits documentation from base class */
34052 void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
34053 {
34054   Q_UNUSED(event)
34055   Q_UNUSED(startPos)
34056   mDragging = false;
34057   if (mParentPlot->noAntialiasingOnDrag())
34058   {
34059     mParentPlot->setAntialiasedElements(mAADragBackup);
34060     mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
34061   }
34062 }
34063 
34064 /*! \internal
34065   
34066   Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
34067   ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
34068   the scaling operation is the current cursor position inside the axis rect. The scaling factor is
34069   dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
34070   zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
34071   
34072   Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
34073   wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
34074   multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
34075   exponent of the range zoom factor. This takes care of the wheel direction automatically, by
34076   inverting the factor, when the wheel step is negative (f^-1 = 1/f).
34077 */
34078 void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
34079 {
34080   bool doReplot = false;
34081   // Mouse range zooming interaction:
34082   if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
34083   {
34084 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
34085     const double delta = event->delta();
34086 #else
34087     const double delta = event->angleDelta().y();
34088 #endif
34089 
34090 #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
34091     const QPointF pos = event->pos();
34092 #else
34093     const QPointF pos = event->position();
34094 #endif
34095     const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
34096     if (mRangeZoom)
34097     {
34098       double angleCoord, radiusCoord;
34099       pixelToCoord(pos, angleCoord, radiusCoord);
34100       scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
34101     }
34102 
34103     for (int i=0; i<mRadialAxes.size(); ++i)
34104     {
34105       QCPPolarAxisRadial *ax = mRadialAxes.at(i);
34106       if (!ax->rangeZoom())
34107         continue;
34108       doReplot = true;
34109       double angleCoord, radiusCoord;
34110       ax->pixelToCoord(pos, angleCoord, radiusCoord);
34111       ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
34112     }
34113   }
34114   if (doReplot)
34115     mParentPlot->replot();
34116 }
34117 
34118 bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
34119 {
34120   if (mGraphs.contains(graph))
34121   {
34122     qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
34123     return false;
34124   }
34125   if (graph->keyAxis() != this)
34126   {
34127     qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
34128     return false;
34129   }
34130   
34131   mGraphs.append(graph);
34132   // possibly add plottable to legend:
34133   if (mParentPlot->autoAddPlottableToLegend())
34134     graph->addToLegend();
34135   if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
34136     graph->setLayer(mParentPlot->currentLayer());
34137   return true;
34138 }
34139 /* end of 'src/polar/layoutelement-angularaxis.cpp' */
34140 
34141 
34142 /* including file 'src/polar/polargrid.cpp' */
34143 /* modified 2021-03-29T02:30:44, size 7493  */
34144 
34145 
34146 ////////////////////////////////////////////////////////////////////////////////////////////////////
34147 //////////////////// QCPPolarGrid
34148 ////////////////////////////////////////////////////////////////////////////////////////////////////
34149 
34150 /*! \class QCPPolarGrid
34151   \brief The grid in both angular and radial dimensions for polar plots
34152 
34153   \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
34154   functionality to be incomplete, as well as changing public interfaces in the future.
34155 */
34156 
34157 /*!
34158   Creates a QCPPolarGrid instance and sets default values.
34159   
34160   You shouldn't instantiate grids on their own, since every axis brings its own grid.
34161 */
34162 QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
34163   QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
34164   mType(gtNone),
34165   mSubGridType(gtNone),
34166   mAntialiasedSubGrid(true),
34167   mAntialiasedZeroLine(true),
34168   mParentAxis(parentAxis)
34169 {
34170   // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
34171   setParent(parentAxis);
34172   setType(gtAll);
34173   setSubGridType(gtNone);
34174   
34175   setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
34176   setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
34177   
34178   setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
34179   setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
34180   setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
34181   
34182   setAntialiased(true);
34183 }
34184 
34185 void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
34186 {
34187   mRadialAxis = axis;
34188 }
34189 
34190 void QCPPolarGrid::setType(GridTypes type)
34191 {
34192   mType = type;
34193 }
34194 
34195 void QCPPolarGrid::setSubGridType(GridTypes type)
34196 {
34197   mSubGridType = type;
34198 }
34199 
34200 /*!
34201   Sets whether sub grid lines are drawn antialiased.
34202 */
34203 void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
34204 {
34205   mAntialiasedSubGrid = enabled;
34206 }
34207 
34208 /*!
34209   Sets whether zero lines are drawn antialiased.
34210 */
34211 void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
34212 {
34213   mAntialiasedZeroLine = enabled;
34214 }
34215 
34216 /*!
34217   Sets the pen with which (major) grid lines are drawn.
34218 */
34219 void QCPPolarGrid::setAngularPen(const QPen &pen)
34220 {
34221   mAngularPen = pen;
34222 }
34223 
34224 /*!
34225   Sets the pen with which sub grid lines are drawn.
34226 */
34227 void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
34228 {
34229   mAngularSubGridPen = pen;
34230 }
34231 
34232 void QCPPolarGrid::setRadialPen(const QPen &pen)
34233 {
34234   mRadialPen = pen;
34235 }
34236 
34237 void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
34238 {
34239   mRadialSubGridPen = pen;
34240 }
34241 
34242 void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
34243 {
34244   mRadialZeroLinePen = pen;
34245 }
34246 
34247 /*! \internal
34248 
34249   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
34250   before drawing the major grid lines.
34251 
34252   This is the antialiasing state the painter passed to the \ref draw method is in by default.
34253   
34254   This function takes into account the local setting of the antialiasing flag as well as the
34255   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
34256   QCustomPlot::setNotAntialiasedElements.
34257   
34258   \see setAntialiased
34259 */
34260 void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
34261 {
34262   applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
34263 }
34264 
34265 /*! \internal
34266   
34267   Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
34268   over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
34269 */
34270 void QCPPolarGrid::draw(QCPPainter *painter)
34271 {
34272   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
34273   
34274   const QPointF center = mParentAxis->mCenter;
34275   const double radius = mParentAxis->mRadius;
34276   
34277   painter->setBrush(Qt::NoBrush);
34278   // draw main angular grid:
34279   if (mType.testFlag(gtAngular))
34280     drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
34281   // draw main radial grid:
34282   if (mType.testFlag(gtRadial) && mRadialAxis)
34283     drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
34284   
34285   applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
34286   // draw sub angular grid:
34287   if (mSubGridType.testFlag(gtAngular))
34288     drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
34289   // draw sub radial grid:
34290   if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
34291     drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
34292 }
34293 
34294 void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF &center, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
34295 {
34296   if (!mRadialAxis) return;
34297   if (coords.isEmpty()) return;
34298   const bool drawZeroLine = zeroPen != Qt::NoPen;
34299   const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
34300   
34301   painter->setPen(pen);
34302   for (int i=0; i<coords.size(); ++i)
34303   {
34304     const double r = mRadialAxis->coordToRadius(coords.at(i));
34305     if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
34306     {
34307       applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
34308       painter->setPen(zeroPen);
34309       painter->drawEllipse(center, r, r);
34310       painter->setPen(pen);
34311       applyDefaultAntialiasingHint(painter);
34312     } else
34313     {
34314       painter->drawEllipse(center, r, r);
34315     }
34316   }
34317 }
34318 
34319 void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF &center, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
34320 {
34321   if (ticksCosSin.isEmpty()) return;
34322   
34323   painter->setPen(pen);
34324   for (int i=0; i<ticksCosSin.size(); ++i)
34325     painter->drawLine(center, center+ticksCosSin.at(i)*radius);
34326 }
34327 /* end of 'src/polar/polargrid.cpp' */
34328 
34329 
34330 /* including file 'src/polar/polargraph.cpp' */
34331 /* modified 2021-03-29T02:30:44, size 44035  */
34332 
34333 
34334 ////////////////////////////////////////////////////////////////////////////////////////////////////
34335 //////////////////// QCPPolarLegendItem
34336 ////////////////////////////////////////////////////////////////////////////////////////////////////
34337 
34338 /*! \class QCPPolarLegendItem
34339   \brief A legend item for polar plots
34340 
34341   \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
34342   functionality to be incomplete, as well as changing public interfaces in the future.
34343 */
34344 QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
34345   QCPAbstractLegendItem(parent),
34346   mPolarGraph(graph)
34347 {
34348   setAntialiased(false);
34349 }
34350 
34351 void QCPPolarLegendItem::draw(QCPPainter *painter)
34352 {
34353   if (!mPolarGraph) return;
34354   painter->setFont(getFont());
34355   painter->setPen(QPen(getTextColor()));
34356   QSizeF iconSize = mParentLegend->iconSize();
34357   QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
34358   QRectF iconRect(mRect.topLeft(), iconSize);
34359   int textHeight = qMax(textRect.height(), iconSize.height());  // if text has smaller height than icon, center text vertically in icon height, else align tops
34360   painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
34361   // draw icon:
34362   painter->save();
34363   painter->setClipRect(iconRect, Qt::IntersectClip);
34364   mPolarGraph->drawLegendIcon(painter, iconRect);
34365   painter->restore();
34366   // draw icon border:
34367   if (getIconBorderPen().style() != Qt::NoPen)
34368   {
34369     painter->setPen(getIconBorderPen());
34370     painter->setBrush(Qt::NoBrush);
34371     int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
34372     painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
34373     painter->drawRect(iconRect);
34374   }
34375 }
34376 
34377 QSize QCPPolarLegendItem::minimumOuterSizeHint() const
34378 {
34379   if (!mPolarGraph) return QSize();
34380   QSize result(0, 0);
34381   QRect textRect;
34382   QFontMetrics fontMetrics(getFont());
34383   QSize iconSize = mParentLegend->iconSize();
34384   textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
34385   result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
34386   result.setHeight(qMax(textRect.height(), iconSize.height()));
34387   result.rwidth() += mMargins.left()+mMargins.right();
34388   result.rheight() += mMargins.top()+mMargins.bottom();
34389   return result;
34390 }
34391 
34392 QPen QCPPolarLegendItem::getIconBorderPen() const
34393 {
34394   return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
34395 }
34396 
34397 QColor QCPPolarLegendItem::getTextColor() const
34398 {
34399   return mSelected ? mSelectedTextColor : mTextColor;
34400 }
34401 
34402 QFont QCPPolarLegendItem::getFont() const
34403 {
34404   return mSelected ? mSelectedFont : mFont;
34405 }
34406 
34407 
34408 ////////////////////////////////////////////////////////////////////////////////////////////////////
34409 //////////////////// QCPPolarGraph
34410 ////////////////////////////////////////////////////////////////////////////////////////////////////
34411 
34412 /*! \class QCPPolarGraph
34413   \brief A radial graph used to display data in polar plots
34414 
34415   \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
34416   functionality to be incomplete, as well as changing public interfaces in the future.
34417 */
34418 
34419 /* start of documentation of inline functions */
34420 
34421 // TODO
34422 
34423 /* end of documentation of inline functions */
34424 
34425 /*!
34426   Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
34427   keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
34428   associated with the angular axis. If either of these restrictions is violated, a corresponding
34429   message is printed to the debug output (qDebug), the construction is not aborted, though.
34430 
34431   The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
34432   \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
34433   manually but use QCPPolarAxisAngular::removeGraph() instead.
34434 
34435   To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
34436   method.
34437 */
34438 QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
34439   QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
34440   mDataContainer(new QCPGraphDataContainer),
34441   mName(),
34442   mAntialiasedFill(true),
34443   mAntialiasedScatters(true),
34444   mPen(Qt::black),
34445   mBrush(Qt::NoBrush),
34446   mPeriodic(true),
34447   mKeyAxis(keyAxis),
34448   mValueAxis(valueAxis),
34449   mSelectable(QCP::stWhole)
34450   //mSelectionDecorator(0) // TODO
34451 {
34452   if (keyAxis->parentPlot() != valueAxis->parentPlot())
34453     qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
34454   
34455   mKeyAxis->registerPolarGraph(this);
34456   
34457   //setSelectionDecorator(new QCPSelectionDecorator); // TODO
34458   
34459   setPen(QPen(Qt::blue, 0));
34460   setBrush(Qt::NoBrush);
34461   setLineStyle(lsLine);
34462 }
34463 
34464 QCPPolarGraph::~QCPPolarGraph()
34465 {
34466   /* TODO
34467   if (mSelectionDecorator)
34468   {
34469     delete mSelectionDecorator;
34470     mSelectionDecorator = 0;
34471   }
34472   */
34473 }
34474 
34475 /*!
34476    The name is the textual representation of this plottable as it is displayed in the legend
34477    (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
34478 */
34479 void QCPPolarGraph::setName(const QString &name)
34480 {
34481   mName = name;
34482 }
34483 
34484 /*!
34485   Sets whether fills of this plottable are drawn antialiased or not.
34486   
34487   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
34488   QCustomPlot::setNotAntialiasedElements.
34489 */
34490 void QCPPolarGraph::setAntialiasedFill(bool enabled)
34491 {
34492   mAntialiasedFill = enabled;
34493 }
34494 
34495 /*!
34496   Sets whether the scatter symbols of this plottable are drawn antialiased or not.
34497   
34498   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
34499   QCustomPlot::setNotAntialiasedElements.
34500 */
34501 void QCPPolarGraph::setAntialiasedScatters(bool enabled)
34502 {
34503   mAntialiasedScatters = enabled;
34504 }
34505 
34506 /*!
34507   The pen is used to draw basic lines that make up the plottable representation in the
34508   plot.
34509   
34510   For example, the \ref QCPGraph subclass draws its graph lines with this pen.
34511 
34512   \see setBrush
34513 */
34514 void QCPPolarGraph::setPen(const QPen &pen)
34515 {
34516   mPen = pen;
34517 }
34518 
34519 /*!
34520   The brush is used to draw basic fills of the plottable representation in the
34521   plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
34522   
34523   For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
34524   it's not set to Qt::NoBrush.
34525 
34526   \see setPen
34527 */
34528 void QCPPolarGraph::setBrush(const QBrush &brush)
34529 {
34530   mBrush = brush;
34531 }
34532 
34533 void QCPPolarGraph::setPeriodic(bool enabled)
34534 {
34535   mPeriodic = enabled;
34536 }
34537 
34538 /*!
34539   The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
34540   to the plottable's value axis. This function performs no checks to make sure this is the case.
34541   The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
34542   y-axis (QCustomPlot::yAxis) as value axis.
34543   
34544   Normally, the key and value axes are set in the constructor of the plottable (or \ref
34545   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
34546 
34547   \see setValueAxis
34548 */
34549 void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
34550 {
34551   mKeyAxis = axis;
34552 }
34553 
34554 /*!
34555   The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
34556   orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
34557   case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
34558   the y-axis (QCustomPlot::yAxis) as value axis.
34559 
34560   Normally, the key and value axes are set in the constructor of the plottable (or \ref
34561   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
34562   
34563   \see setKeyAxis
34564 */
34565 void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
34566 {
34567   mValueAxis = axis;
34568 }
34569 
34570 /*!
34571   Sets whether and to which granularity this plottable can be selected.
34572 
34573   A selection can happen by clicking on the QCustomPlot surface (When \ref
34574   QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
34575   (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
34576   calling \ref setSelection.
34577   
34578   \see setSelection, QCP::SelectionType
34579 */
34580 void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
34581 {
34582   if (mSelectable != selectable)
34583   {
34584     mSelectable = selectable;
34585     QCPDataSelection oldSelection = mSelection;
34586     mSelection.enforceType(mSelectable);
34587     emit selectableChanged(mSelectable);
34588     if (mSelection != oldSelection)
34589     {
34590       emit selectionChanged(selected());
34591       emit selectionChanged(mSelection);
34592     }
34593   }
34594 }
34595 
34596 /*!
34597   Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
34598   (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
34599   selectionDecorator).
34600   
34601   The entire selection mechanism for plottables is handled automatically when \ref
34602   QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
34603   you wish to change the selection state programmatically.
34604   
34605   Using \ref setSelectable you can further specify for each plottable whether and to which
34606   granularity it is selectable. If \a selection is not compatible with the current \ref
34607   QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
34608   accordingly (see \ref QCPDataSelection::enforceType).
34609   
34610   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
34611   
34612   \see setSelectable, selectTest
34613 */
34614 void QCPPolarGraph::setSelection(QCPDataSelection selection)
34615 {
34616   selection.enforceType(mSelectable);
34617   if (mSelection != selection)
34618   {
34619     mSelection = selection;
34620     emit selectionChanged(selected());
34621     emit selectionChanged(mSelection);
34622   }
34623 }
34624 
34625 /*! \overload
34626   
34627   Replaces the current data container with the provided \a data container.
34628   
34629   Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
34630   Modifying the data in the container will then affect all graphs that share the container. Sharing
34631   can be achieved by simply exchanging the data containers wrapped in shared pointers:
34632   \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
34633   
34634   If you do not wish to share containers, but create a copy from an existing container, rather use
34635   the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
34636   \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
34637   
34638   \see addData
34639 */
34640 void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
34641 {
34642   mDataContainer = data;
34643 }
34644 
34645 /*! \overload
34646   
34647   Replaces the current data with the provided points in \a keys and \a values. The provided
34648   vectors should have equal length. Else, the number of added points will be the size of the
34649   smallest vector.
34650   
34651   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
34652   can set \a alreadySorted to true, to improve performance by saving a sorting run.
34653   
34654   \see addData
34655 */
34656 void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
34657 {
34658   mDataContainer->clear();
34659   addData(keys, values, alreadySorted);
34660 }
34661 
34662 /*!
34663   Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
34664   \ref lsNone and \ref setScatterStyle to the desired scatter style.
34665   
34666   \see setScatterStyle
34667 */
34668 void QCPPolarGraph::setLineStyle(LineStyle ls)
34669 {
34670   mLineStyle = ls;
34671 }
34672 
34673 /*!
34674   Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
34675   are drawn (e.g. for line-only-plots with appropriate line style).
34676   
34677   \see QCPScatterStyle, setLineStyle
34678 */
34679 void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
34680 {
34681   mScatterStyle = style;
34682 }
34683 
34684 void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
34685 {
34686   if (keys.size() != values.size())
34687     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
34688   const int n = qMin(keys.size(), values.size());
34689   QVector<QCPGraphData> tempData(n);
34690   QVector<QCPGraphData>::iterator it = tempData.begin();
34691   const QVector<QCPGraphData>::iterator itEnd = tempData.end();
34692   int i = 0;
34693   while (it != itEnd)
34694   {
34695     it->key = keys[i];
34696     it->value = values[i];
34697     ++it;
34698     ++i;
34699   }
34700   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
34701 }
34702 
34703 void QCPPolarGraph::addData(double key, double value)
34704 {
34705   mDataContainer->add(QCPGraphData(key, value));
34706 }
34707 
34708 /*!
34709   Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
34710   customize the visual representation of selected data ranges further than by using the default
34711   QCPSelectionDecorator.
34712   
34713   The plottable takes ownership of the \a decorator.
34714   
34715   The currently set decorator can be accessed via \ref selectionDecorator.
34716 */
34717 /*
34718 void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
34719 {
34720   if (decorator)
34721   {
34722     if (decorator->registerWithPlottable(this))
34723     {
34724       if (mSelectionDecorator) // delete old decorator if necessary
34725         delete mSelectionDecorator;
34726       mSelectionDecorator = decorator;
34727     }
34728   } else if (mSelectionDecorator) // just clear decorator
34729   {
34730     delete mSelectionDecorator;
34731     mSelectionDecorator = 0;
34732   }
34733 }
34734 */
34735 
34736 void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
34737 {
34738   if (mValueAxis)
34739   {
34740     const QPointF point = mValueAxis->coordToPixel(key, value);
34741     x = point.x();
34742     y = point.y();
34743   } else
34744   {
34745     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
34746   }
34747 }
34748 
34749 const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
34750 {
34751   if (mValueAxis)
34752   {
34753     return mValueAxis->coordToPixel(key, value);
34754   } else
34755   {
34756     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
34757     return QPointF();
34758   }
34759 }
34760 
34761 void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
34762 {
34763   if (mValueAxis)
34764   {
34765     mValueAxis->pixelToCoord(QPointF(x, y), key, value);
34766   } else
34767   {
34768     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
34769   }
34770 }
34771 
34772 void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
34773 {
34774   if (mValueAxis)
34775   {
34776     mValueAxis->pixelToCoord(pixelPos, key, value);
34777   } else
34778   {
34779     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
34780   }
34781 }
34782 
34783 void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
34784 {
34785   rescaleKeyAxis(onlyEnlarge);
34786   rescaleValueAxis(onlyEnlarge);
34787 }
34788 
34789 void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
34790 {
34791   QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
34792   if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
34793   
34794   bool foundRange;
34795   QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth);
34796   if (foundRange)
34797   {
34798     if (onlyEnlarge)
34799       newRange.expand(keyAxis->range());
34800     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
34801     {
34802       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
34803       newRange.lower = center-keyAxis->range().size()/2.0;
34804       newRange.upper = center+keyAxis->range().size()/2.0;
34805     }
34806     keyAxis->setRange(newRange);
34807   }
34808 }
34809 
34810 void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
34811 {
34812   QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
34813   QCPPolarAxisRadial *valueAxis = mValueAxis.data();
34814   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
34815   
34816   QCP::SignDomain signDomain = QCP::sdBoth;
34817   if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic)
34818     signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
34819   
34820   bool foundRange;
34821   QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
34822   if (foundRange)
34823   {
34824     if (onlyEnlarge)
34825       newRange.expand(valueAxis->range());
34826     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
34827     {
34828       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
34829       if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear)
34830       {
34831         newRange.lower = center-valueAxis->range().size()/2.0;
34832         newRange.upper = center+valueAxis->range().size()/2.0;
34833       } else // scaleType() == stLogarithmic
34834       {
34835         newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
34836         newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
34837       }
34838     }
34839     valueAxis->setRange(newRange);
34840   }
34841 }
34842 
34843 bool QCPPolarGraph::addToLegend(QCPLegend *legend)
34844 {
34845   if (!legend)
34846   {
34847     qDebug() << Q_FUNC_INFO << "passed legend is null";
34848     return false;
34849   }
34850   if (legend->parentPlot() != mParentPlot)
34851   {
34852     qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
34853     return false;
34854   }
34855   
34856   //if (!legend->hasItemWithPlottable(this)) // TODO
34857   //{
34858     legend->addItem(new QCPPolarLegendItem(legend, this));
34859     return true;
34860   //} else
34861   //  return false;
34862 }
34863 
34864 bool QCPPolarGraph::addToLegend()
34865 {
34866   if (!mParentPlot || !mParentPlot->legend)
34867     return false;
34868   else
34869     return addToLegend(mParentPlot->legend);
34870 }
34871 
34872 bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
34873 {
34874   if (!legend)
34875   {
34876     qDebug() << Q_FUNC_INFO << "passed legend is null";
34877     return false;
34878   }
34879   
34880   
34881   QCPPolarLegendItem *removableItem = 0;
34882   for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
34883   {
34884     if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
34885     {
34886       if (pli->polarGraph() == this)
34887       {
34888         removableItem = pli;
34889         break;
34890       }
34891     }
34892   }
34893   
34894   if (removableItem)
34895     return legend->removeItem(removableItem);
34896   else
34897     return false;
34898 }
34899 
34900 bool QCPPolarGraph::removeFromLegend() const
34901 {
34902   if (!mParentPlot || !mParentPlot->legend)
34903     return false;
34904   else
34905     return removeFromLegend(mParentPlot->legend);
34906 }
34907 
34908 double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
34909 {
34910   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
34911     return -1;
34912   if (!mKeyAxis || !mValueAxis)
34913     return -1;
34914   
34915   if (mKeyAxis->rect().contains(pos.toPoint()))
34916   {
34917     QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
34918     double result = pointDistance(pos, closestDataPoint);
34919     if (details)
34920     {
34921       int pointIndex = closestDataPoint-mDataContainer->constBegin();
34922       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
34923     }
34924     return result;
34925   } else
34926     return -1;
34927 }
34928 
34929 /* inherits documentation from base class */
34930 QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
34931 {
34932   return mDataContainer->keyRange(foundRange, inSignDomain);
34933 }
34934 
34935 /* inherits documentation from base class */
34936 QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
34937 {
34938   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
34939 }
34940 
34941 /* inherits documentation from base class */
34942 QRect QCPPolarGraph::clipRect() const
34943 {
34944   if (mKeyAxis)
34945     return mKeyAxis.data()->rect();
34946   else
34947     return QRect();
34948 }
34949 
34950 void QCPPolarGraph::draw(QCPPainter *painter)
34951 {
34952   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
34953   if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
34954   if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
34955   
34956   painter->setClipRegion(mKeyAxis->exactClipRegion());
34957   
34958   QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
34959   
34960   // loop over and draw segments of unselected/selected data:
34961   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
34962   getDataSegments(selectedSegments, unselectedSegments);
34963   allSegments << unselectedSegments << selectedSegments;
34964   for (int i=0; i<allSegments.size(); ++i)
34965   {
34966     bool isSelectedSegment = i >= unselectedSegments.size();
34967     // get line pixel points appropriate to line style:
34968     QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
34969     getLines(&lines, lineDataRange);
34970     
34971     // check data validity if flag set:
34972 #ifdef QCUSTOMPLOT_CHECK_DATA
34973     QCPGraphDataContainer::const_iterator it;
34974     for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
34975     {
34976       if (QCP::isInvalidData(it->key, it->value))
34977         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
34978     }
34979 #endif
34980     
34981     // draw fill of graph:
34982     //if (isSelectedSegment && mSelectionDecorator)
34983     //  mSelectionDecorator->applyBrush(painter);
34984     //else
34985       painter->setBrush(mBrush);
34986     painter->setPen(Qt::NoPen);
34987     drawFill(painter, &lines);
34988     
34989     
34990     // draw line:
34991     if (mLineStyle != lsNone)
34992     {
34993       //if (isSelectedSegment && mSelectionDecorator)
34994       //  mSelectionDecorator->applyPen(painter);
34995       //else
34996         painter->setPen(mPen);
34997       painter->setBrush(Qt::NoBrush);
34998       drawLinePlot(painter, lines);
34999     }
35000     
35001     // draw scatters:
35002     
35003     QCPScatterStyle finalScatterStyle = mScatterStyle;
35004     //if (isSelectedSegment && mSelectionDecorator)
35005     //  finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
35006     if (!finalScatterStyle.isNone())
35007     {
35008       getScatters(&scatters, allSegments.at(i));
35009       drawScatterPlot(painter, scatters, finalScatterStyle);
35010     }
35011   }
35012   
35013   // draw other selection decoration that isn't just line/scatter pens and brushes:
35014   //if (mSelectionDecorator)
35015   //  mSelectionDecorator->drawDecoration(painter, selection());
35016 }
35017 
35018 QCP::Interaction QCPPolarGraph::selectionCategory() const
35019 {
35020   return QCP::iSelectPlottables;
35021 }
35022 
35023 void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
35024 {
35025   applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
35026 }
35027 
35028 /* inherits documentation from base class */
35029 void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
35030 {
35031   Q_UNUSED(event)
35032   
35033   if (mSelectable != QCP::stNone)
35034   {
35035     QCPDataSelection newSelection = details.value<QCPDataSelection>();
35036     QCPDataSelection selectionBefore = mSelection;
35037     if (additive)
35038     {
35039       if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
35040       {
35041         if (selected())
35042           setSelection(QCPDataSelection());
35043         else
35044           setSelection(newSelection);
35045       } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
35046       {
35047         if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
35048           setSelection(mSelection-newSelection);
35049         else
35050           setSelection(mSelection+newSelection);
35051       }
35052     } else
35053       setSelection(newSelection);
35054     if (selectionStateChanged)
35055       *selectionStateChanged = mSelection != selectionBefore;
35056   }
35057 }
35058 
35059 /* inherits documentation from base class */
35060 void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
35061 {
35062   if (mSelectable != QCP::stNone)
35063   {
35064     QCPDataSelection selectionBefore = mSelection;
35065     setSelection(QCPDataSelection());
35066     if (selectionStateChanged)
35067       *selectionStateChanged = mSelection != selectionBefore;
35068   }
35069 }
35070 
35071 /*!  \internal
35072   
35073   Draws lines between the points in \a lines, given in pixel coordinates.
35074   
35075   \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
35076 */
35077 void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
35078 {
35079   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
35080   {
35081     applyDefaultAntialiasingHint(painter);
35082     drawPolyline(painter, lines);
35083   }
35084 }
35085 
35086 /*! \internal
35087   
35088   Draws the fill of the graph using the specified \a painter, with the currently set brush.
35089   
35090   Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
35091   getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
35092   
35093   In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
35094   this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
35095   operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
35096   segments of the two involved graphs, before passing the overlapping pairs to \ref
35097   getChannelFillPolygon.
35098   
35099   Pass the points of this graph's line as \a lines, in pixel coordinates.
35100 
35101   \see drawLinePlot, drawImpulsePlot, drawScatterPlot
35102 */
35103 void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
35104 {
35105   applyFillAntialiasingHint(painter);
35106   if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
35107     painter->drawPolygon(QPolygonF(*lines));
35108 }
35109 
35110 /*! \internal
35111 
35112   Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
35113   scatters will be drawn with \a painter and have the appearance as specified in \a style.
35114 
35115   \see drawLinePlot, drawImpulsePlot
35116 */
35117 void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
35118 {
35119   applyScattersAntialiasingHint(painter);
35120   style.applyTo(painter, mPen);
35121   for (int i=0; i<scatters.size(); ++i)
35122     style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
35123 }
35124 
35125 void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
35126 {
35127   // draw fill:
35128   if (mBrush.style() != Qt::NoBrush)
35129   {
35130     applyFillAntialiasingHint(painter);
35131     painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
35132   }
35133   // draw line vertically centered:
35134   if (mLineStyle != lsNone)
35135   {
35136     applyDefaultAntialiasingHint(painter);
35137     painter->setPen(mPen);
35138     painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
35139   }
35140   // draw scatter symbol:
35141   if (!mScatterStyle.isNone())
35142   {
35143     applyScattersAntialiasingHint(painter);
35144     // scale scatter pixmap if it's too large to fit in legend icon rect:
35145     if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
35146     {
35147       QCPScatterStyle scaledStyle(mScatterStyle);
35148       scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
35149       scaledStyle.applyTo(painter, mPen);
35150       scaledStyle.drawShape(painter, QRectF(rect).center());
35151     } else
35152     {
35153       mScatterStyle.applyTo(painter, mPen);
35154       mScatterStyle.drawShape(painter, QRectF(rect).center());
35155     }
35156   }
35157 }
35158 
35159 void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
35160 {
35161   applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
35162 }
35163 
35164 void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
35165 {
35166   applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
35167 }
35168 
35169 double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
35170 {
35171   closestData = mDataContainer->constEnd();
35172   if (mDataContainer->isEmpty())
35173     return -1.0;
35174   if (mLineStyle == lsNone && mScatterStyle.isNone())
35175     return -1.0;
35176   
35177   // calculate minimum distances to graph data points and find closestData iterator:
35178   double minDistSqr = (std::numeric_limits<double>::max)();
35179   // determine which key range comes into question, taking selection tolerance around pos into account:
35180   double posKeyMin, posKeyMax, dummy;
35181   pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
35182   pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
35183   if (posKeyMin > posKeyMax)
35184     qSwap(posKeyMin, posKeyMax);
35185   // iterate over found data points and then choose the one with the shortest distance to pos:
35186   QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
35187   QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
35188   for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
35189   {
35190     const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
35191     if (currentDistSqr < minDistSqr)
35192     {
35193       minDistSqr = currentDistSqr;
35194       closestData = it;
35195     }
35196   }
35197     
35198   // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
35199   if (mLineStyle != lsNone)
35200   {
35201     // line displayed, calculate distance to line segments:
35202     QVector<QPointF> lineData;
35203     getLines(&lineData, QCPDataRange(0, dataCount()));
35204     QCPVector2D p(pixelPoint);
35205     for (int i=0; i<lineData.size()-1; ++i)
35206     {
35207       const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
35208       if (currentDistSqr < minDistSqr)
35209         minDistSqr = currentDistSqr;
35210     }
35211   }
35212   
35213   return qSqrt(minDistSqr);
35214 }
35215 
35216 int QCPPolarGraph::dataCount() const
35217 {
35218   return mDataContainer->size();
35219 }
35220 
35221 void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
35222 {
35223   selectedSegments.clear();
35224   unselectedSegments.clear();
35225   if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
35226   {
35227     if (selected())
35228       selectedSegments << QCPDataRange(0, dataCount());
35229     else
35230       unselectedSegments << QCPDataRange(0, dataCount());
35231   } else
35232   {
35233     QCPDataSelection sel(selection());
35234     sel.simplify();
35235     selectedSegments = sel.dataRanges();
35236     unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
35237   }
35238 }
35239 
35240 void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
35241 {
35242   // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
35243   if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
35244       painter->pen().style() == Qt::SolidLine &&
35245       !painter->modes().testFlag(QCPPainter::pmVectorized) &&
35246       !painter->modes().testFlag(QCPPainter::pmNoCaching))
35247   {
35248     int i = 0;
35249     bool lastIsNan = false;
35250     const int lineDataSize = lineData.size();
35251     while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
35252       ++i;
35253     ++i; // because drawing works in 1 point retrospect
35254     while (i < lineDataSize)
35255     {
35256       if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
35257       {
35258         if (!lastIsNan)
35259           painter->drawLine(lineData.at(i-1), lineData.at(i));
35260         else
35261           lastIsNan = false;
35262       } else
35263         lastIsNan = true;
35264       ++i;
35265     }
35266   } else
35267   {
35268     int segmentStart = 0;
35269     int i = 0;
35270     const int lineDataSize = lineData.size();
35271     while (i < lineDataSize)
35272     {
35273       if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block
35274       {
35275         painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
35276         segmentStart = i+1;
35277       }
35278       ++i;
35279     }
35280     // draw last segment:
35281     painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
35282   }
35283 }
35284 
35285 void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
35286 {
35287   if (rangeRestriction.isEmpty())
35288   {
35289     end = mDataContainer->constEnd();
35290     begin = end;
35291   } else
35292   {
35293     QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
35294     QCPPolarAxisRadial *valueAxis = mValueAxis.data();
35295     if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
35296     // get visible data range:
35297     if (mPeriodic)
35298     {
35299       begin = mDataContainer->constBegin();
35300       end = mDataContainer->constEnd();
35301     } else
35302     {
35303       begin = mDataContainer->findBegin(keyAxis->range().lower);
35304       end = mDataContainer->findEnd(keyAxis->range().upper);
35305     }
35306     // limit lower/upperEnd to rangeRestriction:
35307     mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
35308   }
35309 }
35310 
35311 /*! \internal
35312 
35313   This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
35314   out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
35315   according to the line style of the graph.
35316 
35317   \a lines will be filled with points in pixel coordinates, that can be drawn with the according
35318   draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
35319   aren't necessarily the original data points. For example, step line styles require additional
35320   points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
35321   lines vector will be empty.
35322 
35323   \a dataRange specifies the beginning and ending data indices that will be taken into account for
35324   conversion. In this function, the specified range may exceed the total data bounds without harm:
35325   a correspondingly trimmed data range will be used. This takes the burden off the user of this
35326   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
35327   getDataSegments.
35328 
35329   \see getScatters
35330 */
35331 void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
35332 {
35333   if (!lines) return;
35334   QCPGraphDataContainer::const_iterator begin, end;
35335   getVisibleDataBounds(begin, end, dataRange);
35336   if (begin == end)
35337   {
35338     lines->clear();
35339     return;
35340   }
35341   
35342   QVector<QCPGraphData> lineData;
35343   if (mLineStyle != lsNone)
35344     getOptimizedLineData(&lineData, begin, end);
35345 
35346   switch (mLineStyle)
35347   {
35348     case lsNone: lines->clear(); break;
35349     case lsLine: *lines = dataToLines(lineData); break;
35350   }
35351 }
35352 
35353 void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
35354 {
35355   QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
35356   QCPPolarAxisRadial *valueAxis = mValueAxis.data();
35357   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
35358   
35359   if (!scatters) return;
35360   QCPGraphDataContainer::const_iterator begin, end;
35361   getVisibleDataBounds(begin, end, dataRange);
35362   if (begin == end)
35363   {
35364     scatters->clear();
35365     return;
35366   }
35367   
35368   QVector<QCPGraphData> data;
35369   getOptimizedScatterData(&data, begin, end);
35370   
35371   scatters->resize(data.size());
35372   for (int i=0; i<data.size(); ++i)
35373   {
35374     if (!qIsNaN(data.at(i).value))
35375       (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
35376   }
35377 }
35378 
35379 void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
35380 {
35381   lineData->clear();
35382   
35383   // TODO: fix for log axes and thick line style
35384   
35385   const QCPRange range = mValueAxis->range();
35386   bool reversed = mValueAxis->rangeReversed();
35387   const double clipMargin = range.size()*0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents
35388   const double upperClipValue = range.upper + (reversed ? 0 : range.size()*0.05+clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
35389   const double lowerClipValue = range.lower - (reversed ? range.size()*0.05+clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
35390   const double maxKeySkip = qAsin(qSqrt(clipMargin*(clipMargin+2*range.size()))/(range.size()+clipMargin))/M_PI*mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue)
35391   double skipBegin = 0;
35392   bool belowRange = false;
35393   bool aboveRange = false;
35394   QCPGraphDataContainer::const_iterator it = begin;
35395   while (it != end)
35396   {
35397     if (it->value < lowerClipValue)
35398     {
35399       if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
35400       {
35401         aboveRange = false;
35402         if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
35403           lineData->append(*(it-1));
35404       }
35405       if (!belowRange)
35406       {
35407         skipBegin = it->key;
35408         lineData->append(QCPGraphData(it->key, lowerClipValue));
35409         belowRange = true;
35410       }
35411       if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
35412       {
35413         skipBegin += maxKeySkip;
35414         lineData->append(QCPGraphData(skipBegin, lowerClipValue));
35415       }
35416     } else if (it->value > upperClipValue)
35417     {
35418       if (belowRange) // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis)
35419       {
35420         belowRange = false;
35421         if (reversed)
35422           lineData->append(*(it-1));
35423       }
35424       if (!aboveRange)
35425       {
35426         skipBegin = it->key;
35427         lineData->append(QCPGraphData(it->key, upperClipValue));
35428         aboveRange = true;
35429       }
35430       if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
35431       {
35432         skipBegin += maxKeySkip;
35433         lineData->append(QCPGraphData(skipBegin, upperClipValue));
35434       }
35435     } else // value within bounds where we don't optimize away points
35436     {
35437       if (aboveRange)
35438       {
35439         aboveRange = false;
35440         if (!reversed)
35441           lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
35442       }
35443       if (belowRange)
35444       {
35445         belowRange = false;
35446         if (reversed)
35447           lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
35448       }
35449       lineData->append(*it); // inside visible circle, add point normally
35450     }
35451     ++it;
35452   }
35453   // to make fill not erratic, add last point normally if it was outside visible circle:
35454   if (aboveRange)
35455   {
35456     aboveRange = false;
35457     if (!reversed)
35458       lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
35459   }
35460   if (belowRange)
35461   {
35462     belowRange = false;
35463     if (reversed)
35464       lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
35465   }
35466 }
35467 
35468 void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
35469 {
35470   scatterData->clear();
35471   
35472   const QCPRange range = mValueAxis->range();
35473   bool reversed = mValueAxis->rangeReversed();
35474   const double clipMargin = range.size()*0.05;
35475   const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
35476   const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
35477   QCPGraphDataContainer::const_iterator it = begin;
35478   while (it != end)
35479   {
35480     if (it->value > lowerClipValue && it->value < upperClipValue)
35481       scatterData->append(*it);
35482     ++it;
35483   }
35484 }
35485 
35486 /*! \internal
35487 
35488   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
35489   coordinate points which are suitable for drawing the line style \ref lsLine.
35490   
35491   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
35492   getLines if the line style is set accordingly.
35493 
35494   \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
35495 */
35496 QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
35497 {
35498   QVector<QPointF> result;
35499   QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
35500   QCPPolarAxisRadial *valueAxis = mValueAxis.data();
35501   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
35502 
35503   // transform data points to pixels:
35504   result.resize(data.size());
35505   for (int i=0; i<data.size(); ++i)
35506     result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
35507   return result;
35508 }
35509 /* end of 'src/polar/polargraph.cpp' */
35510 
35511