qwt_picker.cpp 33.8 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
 * Qwt Widget Library
 * Copyright (C) 1997   Josef Wilgen
 * Copyright (C) 2002   Uwe Rathmann
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the Qwt License, Version 1.0
 *****************************************************************************/

#include <qapplication.h>
#include <qevent.h>
#include <qpainter.h>
#include <qframe.h>
#include <qcursor.h>
#include <qbitmap.h>
#include "qwt_math.h"
#include "qwt_painter.h"
#include "qwt_picker_machine.h"
#include "qwt_picker.h"
#if QT_VERSION < 0x040000
#include <qguardedptr.h>
#else
#include <qpointer.h>
#include <qpaintengine.h>
#endif

class QwtPicker::PickerWidget: public QWidget
{
public:
30
    enum Type {
pixhawk's avatar
pixhawk committed
31 32 33 34 35 36 37 38
        RubberBand,
        Text
    };

    PickerWidget(QwtPicker *, QWidget *, Type);
    virtual void updateMask();

    /*
39
       For a tracker text with a background we can use the background
pixhawk's avatar
pixhawk committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
       rect as mask. Also for "regular" Qt widgets >= 4.3.0 we
       don't need to mask the text anymore.
     */
    bool d_hasTextMask;

protected:
    virtual void paintEvent(QPaintEvent *);

    QwtPicker *d_picker;
    Type d_type;
};

class QwtPicker::PrivateData
{
public:
    bool enabled;

    QwtPickerMachine *stateMachine;

    int selectionFlags;
    QwtPicker::ResizeMode resizeMode;

    QwtPicker::RubberBand rubberBand;
    QPen rubberBandPen;

    QwtPicker::DisplayMode trackerMode;
    QPen trackerPen;
    QFont trackerFont;

    QwtPolygon selection;
    bool isActive;
    QPoint trackerPosition;

    bool mouseTracking; // used to save previous value

    /*
      On X11 the widget below the picker widgets gets paint events
      with a region that is the bounding rect of the mask, if it is complex.
      In case of (f.e) a CrossRubberBand and a text this creates complete
      repaints of the widget. So we better use two different widgets.
     */
81

pixhawk's avatar
pixhawk committed
82 83 84 85 86 87 88 89 90 91
#if QT_VERSION < 0x040000
    QGuardedPtr<PickerWidget> rubberBandWidget;
    QGuardedPtr<PickerWidget> trackerWidget;
#else
    QPointer<PickerWidget> rubberBandWidget;
    QPointer<PickerWidget> trackerWidget;
#endif
};

QwtPicker::PickerWidget::PickerWidget(
92
    QwtPicker *picker, QWidget *parent, Type type):
pixhawk's avatar
pixhawk committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    QWidget(parent),
    d_hasTextMask(false),
    d_picker(picker),
    d_type(type)
{
#if QT_VERSION >= 0x040000
    setAttribute(Qt::WA_TransparentForMouseEvents);
    setAttribute(Qt::WA_NoSystemBackground);
    setFocusPolicy(Qt::NoFocus);
#else
    setBackgroundMode(Qt::NoBackground);
    setFocusPolicy(QWidget::NoFocus);
    setMouseTracking(true);
#endif
    hide();
}

void QwtPicker::PickerWidget::updateMask()
{
    QRegion mask;

114
    if ( d_type == RubberBand ) {
pixhawk's avatar
pixhawk committed
115 116 117 118 119 120 121 122 123 124 125 126
        QBitmap bm(width(), height());
        bm.fill(Qt::color0);

        QPainter painter(&bm);
        QPen pen = d_picker->rubberBandPen();
        pen.setColor(Qt::color1);
        painter.setPen(pen);

        d_picker->drawRubberBand(&painter);

        mask = QRegion(bm);
    }
127
    if ( d_type == Text ) {
pixhawk's avatar
pixhawk committed
128 129
        d_hasTextMask = true;
#if QT_VERSION >= 0x040300
130
        if ( !parentWidget()->testAttribute(Qt::WA_PaintOnScreen) ) {
pixhawk's avatar
pixhawk committed
131 132 133 134 135
#if 0
            if ( parentWidget()->paintEngine()->type() != QPaintEngine::OpenGL )
#endif
            {
                // With Qt >= 4.3 drawing of the tracker can be implemented in an
136
                // easier way, using the textRect as mask.
pixhawk's avatar
pixhawk committed
137 138 139 140 141

                d_hasTextMask = false;
            }
        }
#endif
142 143

        if ( d_hasTextMask ) {
pixhawk's avatar
pixhawk committed
144
            const QwtText label = d_picker->trackerText(
145
                                      d_picker->trackerPosition());
pixhawk's avatar
pixhawk committed
146
            if ( label.testPaintAttribute(QwtText::PaintBackground)
147
                    && label.backgroundBrush().style() != Qt::NoBrush ) {
pixhawk's avatar
pixhawk committed
148 149 150
#if QT_VERSION >= 0x040300
                if ( label.backgroundBrush().color().alpha() > 0 )
#endif
151 152
                    // We don't need a text mask, when we have a background
                    d_hasTextMask = false;
pixhawk's avatar
pixhawk committed
153 154 155
            }
        }

156
        if ( d_hasTextMask ) {
pixhawk's avatar
pixhawk committed
157 158 159 160 161 162 163 164 165 166 167 168 169
            QBitmap bm(width(), height());
            bm.fill(Qt::color0);

            QPainter painter(&bm);
            painter.setFont(font());

            QPen pen = d_picker->trackerPen();
            pen.setColor(Qt::color1);
            painter.setPen(pen);

            d_picker->drawTracker(&painter);

            mask = QRegion(bm);
170
        } else {
pixhawk's avatar
pixhawk committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            mask = d_picker->trackerRect(font());
        }
    }

#if QT_VERSION < 0x040000
    QWidget *w = parentWidget();
    const bool doUpdate = w->isUpdatesEnabled();
    const Qt::BackgroundMode bgMode = w->backgroundMode();
    w->setUpdatesEnabled(false);
    if ( bgMode != Qt::NoBackground )
        w->setBackgroundMode(Qt::NoBackground);
#endif

    setMask(mask);

#if QT_VERSION < 0x040000
    if ( bgMode != Qt::NoBackground )
        w->setBackgroundMode(bgMode);

    w->setUpdatesEnabled(doUpdate);
#endif

    setShown(!mask.isEmpty());
}

void QwtPicker::PickerWidget::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    painter.setClipRegion(e->region());

201
    if ( d_type == RubberBand ) {
pixhawk's avatar
pixhawk committed
202 203 204 205
        painter.setPen(d_picker->rubberBandPen());
        d_picker->drawRubberBand(&painter);
    }

206
    if ( d_type == Text ) {
pixhawk's avatar
pixhawk committed
207 208 209 210 211 212
        /*
           If we have a text mask we simply fill the region of
           the mask. This gives better results for antialiased fonts.
         */
        bool doDrawTracker = !d_hasTextMask;
#if QT_VERSION < 0x040000
213
        if ( !doDrawTracker && QPainter::redirect(this) ) {
pixhawk's avatar
pixhawk committed
214 215 216 217
            // setMask + painter redirection doesn't work
            doDrawTracker = true;
        }
#endif
218
        if ( doDrawTracker ) {
pixhawk's avatar
pixhawk committed
219 220
            painter.setPen(d_picker->trackerPen());
            d_picker->drawTracker(&painter);
221
        } else
pixhawk's avatar
pixhawk committed
222 223 224 225 226 227 228 229 230
            painter.fillRect(e->rect(), QBrush(d_picker->trackerPen().color()));
    }
}

/*!
  Constructor

  Creates an picker that is enabled, but where selection flag
  is set to NoSelection, rubberband and tracker are disabled.
231

pixhawk's avatar
pixhawk committed
232 233 234 235 236 237 238 239 240 241 242 243
  \param parent Parent widget, that will be observed
 */

QwtPicker::QwtPicker(QWidget *parent):
    QObject(parent)
{
    init(parent, NoSelection, NoRubberBand, AlwaysOff);
}

/*!
  Constructor

244
  \param selectionFlags Or'd value of SelectionType, RectSelectionType and
pixhawk's avatar
pixhawk committed
245 246 247 248 249 250
                        SelectionMode
  \param rubberBand Rubberband style
  \param trackerMode Tracker mode
  \param parent Parent widget, that will be observed
 */
QwtPicker::QwtPicker(int selectionFlags, RubberBand rubberBand,
251
                     DisplayMode trackerMode, QWidget *parent):
pixhawk's avatar
pixhawk committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    QObject(parent)
{
    init(parent, selectionFlags, rubberBand, trackerMode);
}

//! Destructor
QwtPicker::~QwtPicker()
{
    setMouseTracking(false);
    delete d_data->stateMachine;
    delete d_data->rubberBandWidget;
    delete d_data->trackerWidget;
    delete d_data;
}

//! Init the picker, used by the constructors
268 269
void QwtPicker::init(QWidget *parent, int selectionFlags,
                     RubberBand rubberBand, DisplayMode trackerMode)
pixhawk's avatar
pixhawk committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
{
    d_data = new PrivateData;

    d_data->rubberBandWidget = NULL;
    d_data->trackerWidget = NULL;

    d_data->rubberBand = rubberBand;
    d_data->enabled = false;
    d_data->resizeMode = Stretch;
    d_data->trackerMode = AlwaysOff;
    d_data->isActive = false;
    d_data->trackerPosition = QPoint(-1, -1);
    d_data->mouseTracking = false;

    d_data->stateMachine = NULL;
    setSelectionFlags(selectionFlags);

287
    if ( parent ) {
pixhawk's avatar
pixhawk committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
#if QT_VERSION >= 0x040000
        if ( parent->focusPolicy() == Qt::NoFocus )
            parent->setFocusPolicy(Qt::WheelFocus);
#else
        if ( parent->focusPolicy() == QWidget::NoFocus )
            parent->setFocusPolicy(QWidget::WheelFocus);
#endif

        d_data->trackerFont = parent->font();
        d_data->mouseTracking = parent->hasMouseTracking();
        setEnabled(true);
    }
    setTrackerMode(trackerMode);
}

/*!
   Set a state machine and delete the previous one
*/
void QwtPicker::setStateMachine(QwtPickerMachine *stateMachine)
{
308
    if ( d_data->stateMachine != stateMachine ) {
pixhawk's avatar
pixhawk committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        reset();

        delete d_data->stateMachine;
        d_data->stateMachine = stateMachine;

        if ( d_data->stateMachine )
            d_data->stateMachine->reset();
    }
}

/*!
   Create a state machine depending on the selection flags.

   - PointSelection | ClickSelection\n
     QwtPickerClickPointMachine()
   - PointSelection | DragSelection\n
     QwtPickerDragPointMachine()
   - RectSelection | ClickSelection\n
     QwtPickerClickRectMachine()
   - RectSelection | DragSelection\n
     QwtPickerDragRectMachine()
   - PolygonSelection\n
     QwtPickerPolygonMachine()

   \sa setSelectionFlags()
*/
QwtPickerMachine *QwtPicker::stateMachine(int flags) const
{
337
    if ( flags & PointSelection ) {
pixhawk's avatar
pixhawk committed
338 339 340 341 342
        if ( flags & ClickSelection )
            return new QwtPickerClickPointMachine;
        else
            return new QwtPickerDragPointMachine;
    }
343
    if ( flags & RectSelection ) {
pixhawk's avatar
pixhawk committed
344 345 346 347 348
        if ( flags & ClickSelection )
            return new QwtPickerClickRectMachine;
        else
            return new QwtPickerDragRectMachine;
    }
349
    if ( flags & PolygonSelection ) {
pixhawk's avatar
pixhawk committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
        return new QwtPickerPolygonMachine();
    }
    return NULL;
}

//! Return the parent widget, where the selection happens
QWidget *QwtPicker::parentWidget()
{
    QObject *obj = parent();
    if ( obj && obj->isWidgetType() )
        return (QWidget *)obj;

    return NULL;
}

//! Return the parent widget, where the selection happens
const QWidget *QwtPicker::parentWidget() const
{
    QObject *obj = parent();
    if ( obj && obj->isWidgetType() )
        return (QWidget *)obj;

    return NULL;
}

/*!
  Set the selection flags

378
  \param flags Or'd value of SelectionType, RectSelectionType and
pixhawk's avatar
pixhawk committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
               SelectionMode. The default value is NoSelection.

  \sa selectionFlags(), SelectionType, RectSelectionType, SelectionMode
*/

void QwtPicker::setSelectionFlags(int flags)
{
    d_data->selectionFlags = flags;
    setStateMachine(stateMachine(flags));
}

/*!
  \return Selection flags, an Or'd value of SelectionType, RectSelectionType and
          SelectionMode.
  \sa setSelectionFlags(), SelectionType, RectSelectionType, SelectionMode
*/
int QwtPicker::selectionFlags() const
{
    return d_data->selectionFlags;
}

/*!
401
  Set the rubberband style
pixhawk's avatar
pixhawk committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

  \param rubberBand Rubberband style
         The default value is NoRubberBand.

  \sa rubberBand(), RubberBand, setRubberBandPen()
*/
void QwtPicker::setRubberBand(RubberBand rubberBand)
{
    d_data->rubberBand = rubberBand;
}

/*!
  \return Rubberband style
  \sa setRubberBand(), RubberBand, rubberBandPen()
*/
QwtPicker::RubberBand QwtPicker::rubberBand() const
{
    return d_data->rubberBand;
}

/*!
  \brief Set the display mode of the tracker.

  A tracker displays information about current position of
  the cursor as a string. The display mode controls
  if the tracker has to be displayed whenever the observed
  widget has focus and cursor (AlwaysOn), never (AlwaysOff), or
  only when the selection is active (ActiveOnly).
430

pixhawk's avatar
pixhawk committed
431 432 433 434 435 436 437 438
  \param mode Tracker display mode

  \warning In case of AlwaysOn, mouseTracking will be enabled
           for the observed widget.
  \sa trackerMode(), DisplayMode
*/

void QwtPicker::setTrackerMode(DisplayMode mode)
439 440
{
    if ( d_data->trackerMode != mode ) {
pixhawk's avatar
pixhawk committed
441 442 443
        d_data->trackerMode = mode;
        setMouseTracking(d_data->trackerMode == AlwaysOn);
    }
444
}
pixhawk's avatar
pixhawk committed
445 446 447 448 449 450

/*!
  \return Tracker display mode
  \sa setTrackerMode(), DisplayMode
*/
QwtPicker::DisplayMode QwtPicker::trackerMode() const
451
{
pixhawk's avatar
pixhawk committed
452
    return d_data->trackerMode;
453
}
pixhawk's avatar
pixhawk committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

/*!
  \brief Set the resize mode.

  The resize mode controls what to do with the selected points of an active
  selection when the observed widget is resized.

  Stretch means the points are scaled according to the new
  size, KeepSize means the points remain unchanged.

  The default mode is Stretch.

  \param mode Resize mode
  \sa resizeMode(), ResizeMode
*/
void QwtPicker::setResizeMode(ResizeMode mode)
{
    d_data->resizeMode = mode;
472
}
pixhawk's avatar
pixhawk committed
473 474 475 476 477 478 479

/*!
  \return Resize mode
  \sa setResizeMode(), ResizeMode
*/

QwtPicker::ResizeMode QwtPicker::resizeMode() const
480
{
pixhawk's avatar
pixhawk committed
481 482 483 484 485 486 487 488 489 490 491 492 493 494
    return d_data->resizeMode;
}

/*!
  \brief En/disable the picker

  When enabled is true an event filter is installed for
  the observed widget, otherwise the event filter is removed.

  \param enabled true or false
  \sa isEnabled(), eventFilter()
*/
void QwtPicker::setEnabled(bool enabled)
{
495
    if ( d_data->enabled != enabled ) {
pixhawk's avatar
pixhawk committed
496 497 498
        d_data->enabled = enabled;

        QWidget *w = parentWidget();
499
        if ( w ) {
pixhawk's avatar
pixhawk committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
            if ( enabled )
                w->installEventFilter(this);
            else
                w->removeEventFilter(this);
        }

        updateDisplay();
    }
}

/*!
  \return true when enabled, false otherwise
  \sa setEnabled, eventFilter()
*/

bool QwtPicker::isEnabled() const
{
    return d_data->enabled;
}

/*!
  Set the font for the tracker

  \param font Tracker font
  \sa trackerFont(), setTrackerMode(), setTrackerPen()
*/
void QwtPicker::setTrackerFont(const QFont &font)
{
528
    if ( font != d_data->trackerFont ) {
pixhawk's avatar
pixhawk committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
        d_data->trackerFont = font;
        updateDisplay();
    }
}

/*!
  \return Tracker font
  \sa setTrackerFont(), trackerMode(), trackerPen()
*/

QFont QwtPicker::trackerFont() const
{
    return d_data->trackerFont;
}

/*!
  Set the pen for the tracker

  \param pen Tracker pen
  \sa trackerPen(), setTrackerMode(), setTrackerFont()
*/
void QwtPicker::setTrackerPen(const QPen &pen)
{
552
    if ( pen != d_data->trackerPen ) {
pixhawk's avatar
pixhawk committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        d_data->trackerPen = pen;
        updateDisplay();
    }
}

/*!
  \return Tracker pen
  \sa setTrackerPen(), trackerMode(), trackerFont()
*/
QPen QwtPicker::trackerPen() const
{
    return d_data->trackerPen;
}

/*!
  Set the pen for the rubberband

  \param pen Rubberband pen
  \sa rubberBandPen(), setRubberBand()
*/
void QwtPicker::setRubberBandPen(const QPen &pen)
{
575
    if ( pen != d_data->rubberBandPen ) {
pixhawk's avatar
pixhawk committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        d_data->rubberBandPen = pen;
        updateDisplay();
    }
}

/*!
  \return Rubberband pen
  \sa setRubberBandPen(), rubberBand()
*/
QPen QwtPicker::rubberBandPen() const
{
    return d_data->rubberBandPen;
}

/*!
   \brief Return the label for a position

   In case of HLineRubberBand the label is the value of the
   y position, in case of VLineRubberBand the value of the x position.
   Otherwise the label contains x and y position separated by a ',' .

   The format for the string conversion is "%d".

   \param pos Position
   \return Converted position as string
*/

QwtText QwtPicker::trackerText(const QPoint &pos) const
{
    QString label;

607 608 609 610 611 612 613 614 615
    switch(rubberBand()) {
    case HLineRubberBand:
        label.sprintf("%d", pos.y());
        break;
    case VLineRubberBand:
        label.sprintf("%d", pos.x());
        break;
    default:
        label.sprintf("%d, %d", pos.x(), pos.y());
pixhawk's avatar
pixhawk committed
616 617 618 619 620 621 622
    }
    return label;
}

/*!
   Draw a rubberband , depending on rubberBand() and selectionFlags()

623
   \param painter Painter, initialized with clip rect
pixhawk's avatar
pixhawk committed
624 625 626 627 628 629

   \sa rubberBand(), RubberBand, selectionFlags()
*/

void QwtPicker::drawRubberBand(QPainter *painter) const
{
630 631
    if ( !isActive() || rubberBand() == NoRubberBand ||
            rubberBandPen().style() == Qt::NoPen ) {
pixhawk's avatar
pixhawk committed
632 633 634 635 636 637
        return;
    }

    const QRect &pRect = pickRect();
    const QwtPolygon &pa = d_data->selection;

638
    if ( selectionFlags() & PointSelection ) {
pixhawk's avatar
pixhawk committed
639 640 641 642 643
        if ( pa.count() < 1 )
            return;

        const QPoint pos = pa[0];

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        switch(rubberBand()) {
        case VLineRubberBand:
            QwtPainter::drawLine(painter, pos.x(),
                                 pRect.top(), pos.x(), pRect.bottom());
            break;

        case HLineRubberBand:
            QwtPainter::drawLine(painter, pRect.left(),
                                 pos.y(), pRect.right(), pos.y());
            break;

        case CrossRubberBand:
            QwtPainter::drawLine(painter, pos.x(),
                                 pRect.top(), pos.x(), pRect.bottom());
            QwtPainter::drawLine(painter, pRect.left(),
                                 pos.y(), pRect.right(), pos.y());
            break;
        default:
            break;
pixhawk's avatar
pixhawk committed
663 664 665
        }
    }

666
    else if ( selectionFlags() & RectSelection ) {
pixhawk's avatar
pixhawk committed
667 668 669 670 671 672
        if ( pa.count() < 2 )
            return;

        QPoint p1 = pa[0];
        QPoint p2 = pa[int(pa.count() - 1)];

673
        if ( selectionFlags() & CenterToCorner ) {
pixhawk's avatar
pixhawk committed
674 675
            p1.setX(p1.x() - (p2.x() - p1.x()));
            p1.setY(p1.y() - (p2.y() - p1.y()));
676 677 678
        } else if ( selectionFlags() & CenterToRadius ) {
            const int radius = qwtMax(qwtAbs(p2.x() - p1.x()),
                                      qwtAbs(p2.y() - p1.y()));
pixhawk's avatar
pixhawk committed
679 680 681 682 683 684 685 686 687 688 689
            p2.setX(p1.x() + radius);
            p2.setY(p1.y() + radius);
            p1.setX(p1.x() - radius);
            p1.setY(p1.y() - radius);
        }

#if QT_VERSION < 0x040000
        const QRect rect = QRect(p1, p2).normalize();
#else
        const QRect rect = QRect(p1, p2).normalized();
#endif
690 691 692 693 694 695 696 697 698
        switch(rubberBand()) {
        case EllipseRubberBand:
            QwtPainter::drawEllipse(painter, rect);
            break;
        case RectRubberBand:
            QwtPainter::drawRect(painter, rect);
            break;
        default:
            break;
pixhawk's avatar
pixhawk committed
699
        }
700
    } else if ( selectionFlags() & PolygonSelection ) {
pixhawk's avatar
pixhawk committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
        if ( rubberBand() == PolygonRubberBand )
            painter->drawPolyline(pa);
    }
}

/*!
   Draw the tracker

   \param painter Painter
   \sa trackerRect(), trackerText()
*/

void QwtPicker::drawTracker(QPainter *painter) const
{
    const QRect textRect = trackerRect(painter->font());
716
    if ( !textRect.isEmpty() ) {
pixhawk's avatar
pixhawk committed
717
        QwtText label = trackerText(d_data->trackerPosition);
718
        if ( !label.isEmpty() ) {
pixhawk's avatar
pixhawk committed
719 720 721 722
            painter->save();

#if defined(Q_WS_MAC)
            // Antialiased fonts are broken on the Mac.
723
#if QT_VERSION >= 0x040000
pixhawk's avatar
pixhawk committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737
            painter->setRenderHint(QPainter::TextAntialiasing, false);
#else
            QFont fnt = label.usedFont(painter->font());
            fnt.setStyleStrategy(QFont::NoAntialias);
            label.setFont(fnt);
#endif
#endif
            label.draw(painter, textRect);

            painter->restore();
        }
    }
}

738
QPoint QwtPicker::trackerPosition() const
pixhawk's avatar
pixhawk committed
739 740 741 742 743 744
{
    return d_data->trackerPosition;
}

QRect QwtPicker::trackerRect(const QFont &font) const
{
745 746
    if ( trackerMode() == AlwaysOff ||
            (trackerMode() == ActiveOnly && !isActive() ) ) {
pixhawk's avatar
pixhawk committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
        return QRect();
    }

    if ( d_data->trackerPosition.x() < 0 || d_data->trackerPosition.y() < 0 )
        return QRect();

    QwtText text = trackerText(d_data->trackerPosition);
    if ( text.isEmpty() )
        return QRect();

    QRect textRect(QPoint(0, 0), text.textSize(font));

    const QPoint &pos = d_data->trackerPosition;

    int alignment = 0;
762 763 764
    if ( isActive() && d_data->selection.count() > 1
            && rubberBand() != NoRubberBand ) {
        const QPoint last =
pixhawk's avatar
pixhawk committed
765 766 767 768
            d_data->selection[int(d_data->selection.count()) - 2];

        alignment |= (pos.x() >= last.x()) ? Qt::AlignRight : Qt::AlignLeft;
        alignment |= (pos.y() > last.y()) ? Qt::AlignBottom : Qt::AlignTop;
769
    } else
pixhawk's avatar
pixhawk committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        alignment = Qt::AlignTop | Qt::AlignRight;

    const int margin = 5;

    int x = pos.x();
    if ( alignment & Qt::AlignLeft )
        x -= textRect.width() + margin;
    else if ( alignment & Qt::AlignRight )
        x += margin;

    int y = pos.y();
    if ( alignment & Qt::AlignBottom )
        y += margin;
    else if ( alignment & Qt::AlignTop )
        y -= textRect.height() + margin;
785

pixhawk's avatar
pixhawk committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
    textRect.moveTopLeft(QPoint(x, y));

    int right = qwtMin(textRect.right(), pickRect().right() - margin);
    int bottom = qwtMin(textRect.bottom(), pickRect().bottom() - margin);
    textRect.moveBottomRight(QPoint(right, bottom));

    int left = qwtMax(textRect.left(), pickRect().left() + margin);
    int top = qwtMax(textRect.top(), pickRect().top() + margin);
    textRect.moveTopLeft(QPoint(left, top));

    return textRect;
}

/*!
  \brief Event filter

  When isEnabled() == true all events of the observed widget are filtered.
  Mouse and keyboard events are translated into widgetMouse- and widgetKey-
804
  and widgetWheel-events. Paint and Resize events are handled to keep
pixhawk's avatar
pixhawk committed
805 806 807 808 809 810 811 812
  rubberband and tracker up to date.

  \sa event(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
bool QwtPicker::eventFilter(QObject *o, QEvent *e)
{
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    if ( o && o == parentWidget() ) {
        switch(e->type()) {
        case QEvent::Resize: {
            const QResizeEvent *re = (QResizeEvent *)e;
            if ( d_data->resizeMode == Stretch )
                stretchSelection(re->oldSize(), re->size());

            if ( d_data->rubberBandWidget )
                d_data->rubberBandWidget->resize(re->size());

            if ( d_data->trackerWidget )
                d_data->trackerWidget->resize(re->size());
            break;
        }
        case QEvent::Leave:
            widgetLeaveEvent(e);
            break;
        case QEvent::MouseButtonPress:
            widgetMousePressEvent((QMouseEvent *)e);
            break;
        case QEvent::MouseButtonRelease:
            widgetMouseReleaseEvent((QMouseEvent *)e);
            break;
        case QEvent::MouseButtonDblClick:
            widgetMouseDoubleClickEvent((QMouseEvent *)e);
            break;
        case QEvent::MouseMove:
            widgetMouseMoveEvent((QMouseEvent *)e);
            break;
        case QEvent::KeyPress:
            widgetKeyPressEvent((QKeyEvent *)e);
            break;
        case QEvent::KeyRelease:
            widgetKeyReleaseEvent((QKeyEvent *)e);
            break;
        case QEvent::Wheel:
            widgetWheelEvent((QWheelEvent *)e);
            break;
        default:
            break;
pixhawk's avatar
pixhawk committed
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
        }
    }
    return false;
}

/*!
  Handle a mouse press event for the observed widget.

  Begin and/or end a selection depending on the selection flags.

  \sa QwtPicker, selectionFlags()
  \sa eventFilter(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
void QwtPicker::widgetMousePressEvent(QMouseEvent *e)
{
    transition(e);
}

/*!
  Handle a mouse move event for the observed widget.

  Move the last point of the selection in case of isActive() == true

  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
void QwtPicker::widgetMouseMoveEvent(QMouseEvent *e)
{
    if ( pickRect().contains(e->pos()) )
        d_data->trackerPosition = e->pos();
    else
        d_data->trackerPosition = QPoint(-1, -1);

    if ( !isActive() )
        updateDisplay();

    transition(e);
}

/*!
  Handle a leave event for the observed widget.

  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
902
void QwtPicker::widgetLeaveEvent(QEvent *)
pixhawk's avatar
pixhawk committed
903 904 905 906 907 908 909 910 911 912 913 914
{
    d_data->trackerPosition = QPoint(-1, -1);
    if ( !isActive() )
        updateDisplay();
}

/*!
  Handle a mouse relase event for the observed widget.

  End a selection depending on the selection flags.

  \sa QwtPicker, selectionFlags()
915
  \sa eventFilter(), widgetMousePressEvent(),
pixhawk's avatar
pixhawk committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
void QwtPicker::widgetMouseReleaseEvent(QMouseEvent *e)
{
    transition(e);
}

/*!
  Handle mouse double click event for the observed widget.

  Empty implementation, does nothing.

  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
void QwtPicker::widgetMouseDoubleClickEvent(QMouseEvent *me)
{
    transition(me);
}
937

pixhawk's avatar
pixhawk committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

/*!
  Handle a wheel event for the observed widget.

  Move the last point of the selection in case of isActive() == true

  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetKeyPressEvent(), widgetKeyReleaseEvent()
*/
void QwtPicker::widgetWheelEvent(QWheelEvent *e)
{
    if ( pickRect().contains(e->pos()) )
        d_data->trackerPosition = e->pos();
    else
        d_data->trackerPosition = QPoint(-1, -1);

    updateDisplay();

    transition(e);
}

/*!
  Handle a key press event for the observed widget.

  Selections can be completely done by the keyboard. The arrow keys
  move the cursor, the abort key aborts a selection. All other keys
  are handled by the current state machine.

  \sa QwtPicker, selectionFlags()
  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyReleaseEvent(), stateMachine(),
      QwtEventPattern::KeyPatternCode
*/
void QwtPicker::widgetKeyPressEvent(QKeyEvent *ke)
{
    int dx = 0;
    int dy = 0;

    int offset = 1;
    if ( ke->isAutoRepeat() )
        offset = 5;

    if ( keyMatch(KeyLeft, ke) )
        dx = -offset;
    else if ( keyMatch(KeyRight, ke) )
        dx = offset;
    else if ( keyMatch(KeyUp, ke) )
        dy = -offset;
    else if ( keyMatch(KeyDown, ke) )
        dy = offset;
990
    else if ( keyMatch(KeyAbort, ke) ) {
pixhawk's avatar
pixhawk committed
991
        reset();
992
    } else
pixhawk's avatar
pixhawk committed
993 994
        transition(ke);

995
    if ( dx != 0 || dy != 0 ) {
pixhawk's avatar
pixhawk committed
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
        const QRect rect = pickRect();
        const QPoint pos = parentWidget()->mapFromGlobal(QCursor::pos());

        int x = pos.x() + dx;
        x = qwtMax(rect.left(), x);
        x = qwtMin(rect.right(), x);

        int y = pos.y() + dy;
        y = qwtMax(rect.top(), y);
        y = qwtMin(rect.bottom(), y);

        QCursor::setPos(parentWidget()->mapToGlobal(QPoint(x, y)));
    }
}
1010

pixhawk's avatar
pixhawk committed
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
/*!
  Handle a key release event for the observed widget.

  Passes the event to the state machine.

  \sa eventFilter(), widgetMousePressEvent(), widgetMouseReleaseEvent(),
      widgetMouseDoubleClickEvent(), widgetMouseMoveEvent(),
      widgetWheelEvent(), widgetKeyPressEvent(), stateMachine()
*/
void QwtPicker::widgetKeyReleaseEvent(QKeyEvent *ke)
{
    transition(ke);
}

/*!
1026
  Passes an event to the state machine and executes the resulting
pixhawk's avatar
pixhawk committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  commands. Append and Move commands use the current position
  of the cursor (QCursor::pos()).

  \param e Event
*/
void QwtPicker::transition(const QEvent *e)
{
    if ( !d_data->stateMachine )
        return;

    QwtPickerMachine::CommandList commandList =
        d_data->stateMachine->transition(*this, e);

    QPoint pos;
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    switch(e->type()) {
    case QEvent::MouseButtonDblClick:
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseMove: {
        const QMouseEvent *me = (QMouseEvent *)e;
        pos = me->pos();
        break;
    }
    default:
        pos = parentWidget()->mapFromGlobal(QCursor::pos());
pixhawk's avatar
pixhawk committed
1052 1053
    }

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    for ( uint i = 0; i < (uint)commandList.count(); i++ ) {
        switch(commandList[i]) {
        case QwtPickerMachine::Begin: {
            begin();
            break;
        }
        case QwtPickerMachine::Append: {
            append(pos);
            break;
        }
        case QwtPickerMachine::Move: {
            move(pos);
            break;
        }
        case QwtPickerMachine::End: {
            end();
            break;
        }
pixhawk's avatar
pixhawk committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        }
    }
}

/*!
  Open a selection setting the state to active

  \sa isActive, end(), append(), move()
*/
void QwtPicker::begin()
{
    if ( d_data->isActive )
        return;

    d_data->selection.resize(0);
    d_data->isActive = true;

1089 1090
    if ( trackerMode() != AlwaysOff ) {
        if ( d_data->trackerPosition.x() < 0 || d_data->trackerPosition.y() < 0 ) {
pixhawk's avatar
pixhawk committed
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
            QWidget *w = parentWidget();
            if ( w )
                d_data->trackerPosition = w->mapFromGlobal(QCursor::pos());
        }
    }

    updateDisplay();
    setMouseTracking(true);
}

/*!
  \brief Close a selection setting the state to inactive.

  The selection is validated and maybe fixed by QwtPicker::accept().

  \param ok If true, complete the selection and emit a selected signal
            otherwise discard the selection.
  \return true if the selection is accepted, false otherwise
  \sa isActive, begin(), append(), move(), selected(), accept()
*/
bool QwtPicker::end(bool ok)
{
1113
    if ( d_data->isActive ) {
pixhawk's avatar
pixhawk committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        setMouseTracking(false);

        d_data->isActive = false;

        if ( trackerMode() == ActiveOnly )
            d_data->trackerPosition = QPoint(-1, -1);

        if ( ok )
            ok = accept(d_data->selection);

        if ( ok )
            emit selected(d_data->selection);
        else
            d_data->selection.resize(0);

        updateDisplay();
1130
    } else
pixhawk's avatar
pixhawk committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        ok = false;

    return ok;
}

/*!
   Reset the state machine and terminate (end(false)) the selection
*/
void QwtPicker::reset()
{
    if ( d_data->stateMachine )
        d_data->stateMachine->reset();

    if (isActive())
        end(false);
}

/*!
  Append a point to the selection and update rubberband and tracker.
  The appended() signal is emitted.

  \param pos Additional point

  \sa isActive, begin(), end(), move(), appended()
*/
void QwtPicker::append(const QPoint &pos)
{
1158
    if ( d_data->isActive ) {
pixhawk's avatar
pixhawk committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        const int idx = d_data->selection.count();
        d_data->selection.resize(idx + 1);
        d_data->selection[idx] = pos;

        updateDisplay();

        emit appended(pos);
    }
}

/*!
  Move the last point of the selection
  The moved() signal is emitted.

  \param pos New position
  \sa isActive, begin(), end(), append()

*/
void QwtPicker::move(const QPoint &pos)
{
1179
    if ( d_data->isActive ) {
pixhawk's avatar
pixhawk committed
1180
        const int idx = d_data->selection.count() - 1;
1181 1182
        if ( idx >= 0 ) {
            if ( d_data->selection[idx] != pos ) {
pixhawk's avatar
pixhawk committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
                d_data->selection[idx] = pos;

                updateDisplay();

                emit moved(pos);
            }
        }
    }
}

bool QwtPicker::accept(QwtPolygon &) const
{
    return true;
}

/*!
  A picker is active between begin() and end().
  \return true if the selection is active.
*/
1202
bool QwtPicker::isActive() const
pixhawk's avatar
pixhawk committed
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
{
    return d_data->isActive;
}

//!  Return Selected points
const QwtPolygon &QwtPicker::selection() const
{
    return d_data->selection;
}

/*!
  Scale the selection by the ratios of oldSize and newSize
  The changed() signal is emitted.

  \param oldSize Previous size
  \param newSize Current size

  \sa ResizeMode, setResizeMode(), resizeMode()
*/
void QwtPicker::stretchSelection(const QSize &oldSize, const QSize &newSize)
{
1224 1225
    if ( oldSize.isEmpty() ) {
        // avoid division by zero. But scaling for small sizes also
pixhawk's avatar
pixhawk committed
1226 1227 1228 1229 1230 1231 1232 1233 1234
        // doesn't make much sense, because of rounding losses. TODO ...
        return;
    }

    const double xRatio =
        double(newSize.width()) / double(oldSize.width());
    const double yRatio =
        double(newSize.height()) / double(oldSize.height());

1235
    for ( int i = 0; i < int(d_data->selection.count()); i++ ) {
pixhawk's avatar
pixhawk committed
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        QPoint &p = d_data->selection[i];
        p.setX(qRound(p.x() * xRatio));
        p.setY(qRound(p.y() * yRatio));

        emit changed(d_data->selection);
    }
}

/*!
  Set mouse tracking for the observed widget.

  In case of enable is true, the previous value
  is saved, that is restored when enable is false.

  \warning Even when enable is false, mouse tracking might be restored
           to true. When mouseTracking for the observed widget
           has been changed directly by QWidget::setMouseTracking
           while mouse tracking has been set to true, this value can't
           be restored.
*/

void QwtPicker::setMouseTracking(bool enable)
{
    QWidget *widget = parentWidget();
    if ( !widget )
        return;

1263
    if ( enable ) {
pixhawk's avatar
pixhawk committed
1264 1265
        d_data->mouseTracking = widget->hasMouseTracking();
        widget->setMouseTracking(true);
1266
    } else {
pixhawk's avatar
pixhawk committed
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
        widget->setMouseTracking(d_data->mouseTracking);
    }
}

/*!
  Find the area of the observed widget, where selection might happen.

  \return QFrame::contentsRect() if it is a QFrame, QWidget::rect() otherwise.
*/
QRect QwtPicker::pickRect() const
{
    QRect rect;

    const QWidget *widget = parentWidget();
    if ( !widget )
        return rect;

    if ( widget->inherits("QFrame") )
        rect = ((QFrame *)widget)->contentsRect();
    else
        rect = widget->rect();

    return rect;
}

void QwtPicker::updateDisplay()
{
    QWidget *w = parentWidget();

    bool showRubberband = false;
    bool showTracker = false;
1298
    if ( w && w->isVisible() && d_data->enabled ) {
pixhawk's avatar
pixhawk committed
1299
        if ( rubberBand() != NoRubberBand && isActive() &&
1300
                rubberBandPen().style() != Qt::NoPen ) {
pixhawk's avatar
pixhawk committed
1301 1302 1303 1304
            showRubberband = true;
        }

        if ( trackerMode() == AlwaysOn ||
1305
                (trackerMode() == ActiveOnly && isActive() ) ) {
pixhawk's avatar
pixhawk committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
            if ( trackerPen() != Qt::NoPen )
                showTracker = true;
        }
    }

#if QT_VERSION < 0x040000
    QGuardedPtr<PickerWidget> &rw = d_data->rubberBandWidget;
#else
    QPointer<PickerWidget> &rw = d_data->rubberBandWidget;
#endif
1316 1317
    if ( showRubberband ) {
        if ( rw.isNull() ) {
pixhawk's avatar
pixhawk committed
1318 1319 1320 1321 1322
            rw = new PickerWidget( this, w, PickerWidget::RubberBand);
            rw->resize(w->size());
        }
        rw->updateMask();
        rw->update(); // Needed, when the mask doesn't change
1323
    } else
pixhawk's avatar
pixhawk committed
1324 1325 1326 1327 1328 1329 1330
        delete rw;

#if QT_VERSION < 0x040000
    QGuardedPtr<PickerWidget> &tw = d_data->trackerWidget;
#else
    QPointer<PickerWidget> &tw = d_data->trackerWidget;
#endif
1331 1332
    if ( showTracker ) {
        if ( tw.isNull() ) {
pixhawk's avatar
pixhawk committed
1333 1334 1335 1336 1337
            tw = new PickerWidget( this, w, PickerWidget::Text);
            tw->resize(w->size());
        }
        tw->updateMask();
        tw->update(); // Needed, when the mask doesn't change
1338
    } else
pixhawk's avatar
pixhawk committed
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
        delete tw;
}

const QWidget *QwtPicker::rubberBandWidget() const
{
    return d_data->rubberBandWidget;
}

const QWidget *QwtPicker::trackerWidget() const
{
    return d_data->trackerWidget;
}