156d8157655f69e089ccd2f3b70b98532b1e6ed9
[profile/ivi/qtbase.git] / tests / auto / widgets / graphicsview / qgraphicsview / tst_qgraphicsview.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the test suite of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42
43 #include <QtTest/QtTest>
44
45 #include <qgraphicsitem.h>
46 #include <qgraphicsscene.h>
47 #include <qgraphicssceneevent.h>
48 #include <qgraphicsview.h>
49 #include <qgraphicswidget.h>
50 #include <qgraphicsproxywidget.h>
51
52 #include <math.h>
53
54 #include <QtWidgets/QLabel>
55 #if !defined(QT_NO_STYLE_MOTIF)
56 #include <QtWidgets/QMotifStyle>
57 #endif
58 #if !defined(QT_NO_STYLE_WINDOWS)
59 #include <QtWidgets/QWindowsStyle>
60 #endif
61 #if !defined(QT_NO_STYLE_PLASTIQUE)
62 #include <QtWidgets/QPlastiqueStyle>
63 #endif
64 #include <QtGui/QPainterPath>
65 #include <QtWidgets/QRubberBand>
66 #include <QtWidgets/QScrollBar>
67 #include <QtWidgets/QStyleOption>
68 #include <QtWidgets/QBoxLayout>
69 #include <QtWidgets/QStyle>
70 #include <QtWidgets/QPushButton>
71 #include <QtWidgets/QDesktopWidget>
72 #include <private/qgraphicsscene_p.h>
73 #include <private/qgraphicsview_p.h>
74 #include "../../../platformquirks.h"
75 #include "../../../shared/platforminputcontext.h"
76 #include <private/qinputmethod_p.h>
77
78 Q_DECLARE_METATYPE(QList<int>)
79 Q_DECLARE_METATYPE(QList<QRectF>)
80 Q_DECLARE_METATYPE(QMatrix)
81 Q_DECLARE_METATYPE(QPainterPath)
82 Q_DECLARE_METATYPE(QPointF)
83 Q_DECLARE_METATYPE(QPolygonF)
84 Q_DECLARE_METATYPE(QRectF)
85 Q_DECLARE_METATYPE(Qt::ScrollBarPolicy)
86
87 #ifdef Q_OS_MAC
88 //On mac we get full update. So check that the expected region is contained inside the actual
89 #define COMPARE_REGIONS(ACTUAL, EXPECTED) QVERIFY((EXPECTED).subtracted(ACTUAL).isEmpty())
90 #else
91 #define COMPARE_REGIONS QCOMPARE
92 #endif
93
94 static void sendMousePress(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::LeftButton)
95 {
96     QMouseEvent event(QEvent::MouseButtonPress, point, widget->mapToGlobal(point), button, 0, 0);
97     QApplication::sendEvent(widget, &event);
98 }
99
100 static void sendMouseMove(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::NoButton, Qt::MouseButtons buttons = 0)
101 {
102     QTest::mouseMove(widget, point);
103     QMouseEvent event(QEvent::MouseMove, point, button, buttons, 0);
104     QApplication::sendEvent(widget, &event);
105     QApplication::processEvents();
106 }
107
108 static void sendMouseRelease(QWidget *widget, const QPoint &point, Qt::MouseButton button = Qt::LeftButton)
109 {
110     QMouseEvent event(QEvent::MouseButtonRelease, point, widget->mapToGlobal(point), button, 0, 0);
111     QApplication::sendEvent(widget, &event);
112 }
113
114 class EventSpy : public QObject
115 {
116     Q_OBJECT
117 public:
118     EventSpy(QObject *watched, QEvent::Type type)
119         : _count(0), spied(type)
120     {
121         watched->installEventFilter(this);
122     }
123
124     int count() const { return _count; }
125     void reset() { _count = 0; }
126
127 protected:
128     bool eventFilter(QObject *watched, QEvent *event)
129     {
130         Q_UNUSED(watched);
131         if (event->type() == spied)
132             ++_count;
133         return false;
134     }
135
136     int _count;
137     QEvent::Type spied;
138 };
139
140 #if defined QT_BUILD_INTERNAL
141 class FriendlyGraphicsScene : public QGraphicsScene
142 {
143     friend class tst_QGraphicsView;
144     Q_DECLARE_PRIVATE(QGraphicsScene);
145 };
146 #endif
147
148 class tst_QGraphicsView : public QObject
149 {
150     Q_OBJECT
151
152 private slots:
153     void initTestCase();
154     void cleanup();
155     void construction();
156     void renderHints();
157     void alignment();
158     void interactive();
159     void scene();
160     void setScene();
161     void deleteScene();
162     void sceneRect();
163     void sceneRect_growing();
164     void setSceneRect();
165     void viewport();
166     void dragMode_scrollHand();
167     void dragMode_rubberBand();
168     void rubberBandSelectionMode();
169     void backgroundBrush();
170     void foregroundBrush();
171     void matrix();
172     void matrix_convenience();
173     void matrix_combine();
174     void centerOnPoint();
175     void centerOnItem();
176     void ensureVisibleRect();
177     void fitInView();
178     void itemsAtPoint();
179 #if defined QT_BUILD_INTERNAL
180     void itemsAtPosition_data();
181     void itemsAtPosition();
182 #endif
183     void itemsInRect();
184     void itemsInRect_cosmeticAdjust_data();
185     void itemsInRect_cosmeticAdjust();
186     void itemsInPoly();
187     void itemsInPath();
188     void itemAt();
189     void itemAt2();
190     void mapToScene();
191     void mapToScenePoint();
192     void mapToSceneRect_data();
193     void mapToSceneRect();
194     void mapToScenePoly();
195     void mapToScenePath();
196     void mapFromScenePoint();
197     void mapFromSceneRect();
198     void mapFromScenePoly();
199     void mapFromScenePath();
200     void sendEvent();
201     void wheelEvent();
202     void cursor();
203     void cursor2();
204     void transformationAnchor();
205     void resizeAnchor();
206     void viewportUpdateMode();
207     void viewportUpdateMode2();
208 #ifndef QT_NO_DRAGANDDROP
209     void acceptDrops();
210 #endif
211     void optimizationFlags();
212     void optimizationFlags_dontSavePainterState();
213     void optimizationFlags_dontSavePainterState2_data();
214     void optimizationFlags_dontSavePainterState2();
215     void levelOfDetail_data();
216     void levelOfDetail();
217     void scrollBarRanges_data();
218     void scrollBarRanges();
219     void acceptMousePressEvent();
220     void replayMouseMove();
221     void itemsUnderMouse();
222     void embeddedViews();
223     void scrollAfterResize_data();
224     void scrollAfterResize();
225     void moveItemWhileScrolling_data();
226     void moveItemWhileScrolling();
227     void centerOnDirtyItem();
228     void mouseTracking();
229     void mouseTracking2();
230     void mouseTracking3();
231     void render();
232     void exposeRegion();
233     void update_data();
234     void update();
235     void update2_data();
236     void update2();
237     void update_ancestorClipsChildrenToShape();
238     void update_ancestorClipsChildrenToShape2();
239     void inputMethodSensitivity();
240     void inputContextReset();
241     void indirectPainting();
242     void compositionModeInDrawBackground();
243
244     // task specific tests below me
245     void task172231_untransformableItems();
246     void task180429_mouseReleaseDragMode();
247     void task187791_setSceneCausesUpdate();
248     void task186827_deleteReplayedItem();
249     void task207546_focusCrash();
250     void task210599_unsetDragWhileDragging();
251     void task236394_sendShortcutOverrideEvent();
252     void task239729_noViewUpdate_data();
253     void task239729_noViewUpdate();
254     void task239047_fitInViewSmallViewport();
255     void task245469_itemsAtPointWithClip();
256     void task253415_reconnectUpdateSceneOnSceneChanged();
257     void task255529_transformationAnchorMouseAndViewportMargins();
258     void task259503_scrollingArtifacts();
259     void QTBUG_4151_clipAndIgnore_data();
260     void QTBUG_4151_clipAndIgnore();
261     void QTBUG_5859_exposedRect();
262     void QTBUG_7438_cursor();
263     void hoverLeave();
264     void QTBUG_16063_microFocusRect();
265
266 public slots:
267     void dummySlot() {}
268 };
269
270 void tst_QGraphicsView::initTestCase()
271 {
272 #ifdef Q_OS_WINCE_WM
273     qApp->setAutoMaximizeThreshold(-1);
274 #endif
275 }
276
277 void tst_QGraphicsView::cleanup()
278 {
279     // ensure not even skipped tests with custom input context leave it dangling
280     QInputMethodPrivate *inputMethodPrivate = QInputMethodPrivate::get(qApp->inputMethod());
281     inputMethodPrivate->testContext = 0;
282 }
283
284 void tst_QGraphicsView::construction()
285 {
286     QGraphicsView view;
287     QCOMPARE(view.renderHints(), QPainter::TextAntialiasing);
288     QCOMPARE(view.dragMode(), QGraphicsView::NoDrag);
289     QVERIFY(view.isInteractive());
290     QVERIFY(!view.scene());
291     QCOMPARE(view.sceneRect(), QRectF());
292     QVERIFY(view.viewport());
293     QCOMPARE(view.viewport()->metaObject()->className(), "QWidget");
294     QCOMPARE(view.matrix(), QMatrix());
295     QVERIFY(view.items().isEmpty());
296     QVERIFY(view.items(QPoint()).isEmpty());
297     QVERIFY(view.items(QRect()).isEmpty());
298     QVERIFY(view.items(QPolygon()).isEmpty());
299     QVERIFY(view.items(QPainterPath()).isEmpty());
300     QVERIFY(!view.itemAt(QPoint()));
301     QCOMPARE(view.mapToScene(QPoint()), QPointF());
302     QCOMPARE(view.mapToScene(QRect()), QPolygonF());
303     QCOMPARE(view.mapToScene(QPolygon()), QPolygonF());
304     QCOMPARE(view.mapFromScene(QPointF()), QPoint());
305     QPolygon poly;
306     poly << QPoint() << QPoint() << QPoint() << QPoint();
307     QCOMPARE(view.mapFromScene(QRectF()), poly);
308     QCOMPARE(view.mapFromScene(QPolygonF()), QPolygon());
309     QCOMPARE(view.transformationAnchor(), QGraphicsView::AnchorViewCenter);
310     QCOMPARE(view.resizeAnchor(), QGraphicsView::NoAnchor);
311     view.show();
312     QTest::qWaitForWindowShown(&view);
313 }
314
315 class TestItem : public QGraphicsItem
316 {
317 public:
318     QRectF boundingRect() const
319     { return QRectF(-10, -10, 20, 20); }
320
321     void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
322     { hints = painter->renderHints(); painter->drawRect(boundingRect()); }
323
324     bool sceneEvent(QEvent *event)
325     {
326         events << event->type();
327         return QGraphicsItem::sceneEvent(event);
328     }
329
330     QList<QEvent::Type> events;
331     QPainter::RenderHints hints;
332 };
333
334 void tst_QGraphicsView::renderHints()
335 {
336     QGraphicsView view;
337     QCOMPARE(view.renderHints(), QPainter::TextAntialiasing);
338     view.setRenderHint(QPainter::TextAntialiasing, false);
339     QCOMPARE(view.renderHints(), 0);
340     view.setRenderHint(QPainter::Antialiasing, false);
341     QCOMPARE(view.renderHints(), 0);
342     view.setRenderHint(QPainter::TextAntialiasing, true);
343     QCOMPARE(view.renderHints(), QPainter::TextAntialiasing);
344     view.setRenderHint(QPainter::Antialiasing);
345     QCOMPARE(view.renderHints(), QPainter::TextAntialiasing | QPainter::Antialiasing);
346     view.setRenderHints(0);
347     QCOMPARE(view.renderHints(), 0);
348
349     TestItem *item = new TestItem;
350     QGraphicsScene scene;
351     scene.addItem(item);
352
353     view.setScene(&scene);
354
355     view.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::NonCosmeticDefaultPen);
356     QCOMPARE(view.renderHints(), QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::NonCosmeticDefaultPen);
357
358     QCOMPARE(item->hints, 0);
359     view.show();
360     QTest::qWaitForWindowShown(&view);
361     view.repaint();
362     QTRY_COMPARE(item->hints, view.renderHints());
363
364     view.setRenderHints(QPainter::Antialiasing | QPainter::NonCosmeticDefaultPen);
365     QCOMPARE(view.renderHints(), QPainter::Antialiasing | QPainter::NonCosmeticDefaultPen);
366
367     view.repaint();
368     QTRY_COMPARE(item->hints, view.renderHints());
369 }
370
371 void tst_QGraphicsView::alignment()
372 {
373     QGraphicsScene scene;
374     scene.addRect(QRectF(-10, -10, 20, 20));
375
376     QGraphicsView view(&scene);
377     view.show();
378     QTest::qWaitForWindowShown(&view);
379
380     for (int i = 0; i < 3; ++i) {
381         for (int j = 0; j < 3; ++j) {
382             Qt::Alignment alignment = 0;
383             switch (i) {
384             case 0:
385                 alignment |= Qt::AlignLeft;
386                 break;
387             case 1:
388                 alignment |= Qt::AlignHCenter;
389                 break;
390             case 2:
391             default:
392                 alignment |= Qt::AlignRight;
393                 break;
394             }
395             switch (j) {
396             case 0:
397                 alignment |= Qt::AlignTop;
398                 break;
399             case 1:
400                 alignment |= Qt::AlignVCenter;
401                 break;
402             case 2:
403             default:
404                 alignment |= Qt::AlignBottom;
405                 break;
406             }
407             view.setAlignment(alignment);
408             QCOMPARE(view.alignment(), alignment);
409
410             for (int k = 0; k < 3; ++k) {
411                 view.resize(100 + k * 25, 100 + k * 25);
412                 QApplication::processEvents();
413             }
414         }
415     }
416 }
417
418 void tst_QGraphicsView::interactive()
419 {
420     TestItem *item = new TestItem;
421     item->setFlags(QGraphicsItem::ItemIsMovable);
422     QCOMPARE(item->events.size(), 0);
423
424     QGraphicsScene scene(-200, -200, 400, 400);
425     scene.addItem(item);
426
427     QGraphicsView view(&scene);
428     if (PlatformQuirks::isAutoMaximizing())
429         view.setWindowFlags(view.windowFlags()|Qt::X11BypassWindowManagerHint);
430     view.setFixedSize(300, 300);
431     QCOMPARE(item->events.size(), 0);
432     view.show();
433     QTest::qWaitForWindowShown(&view);
434     view.activateWindow();
435
436     QApplication::processEvents();
437     QTRY_COMPARE(item->events.size(), 1); // activate
438
439     QPoint itemPoint = view.mapFromScene(item->scenePos());
440
441     QVERIFY(view.itemAt(itemPoint));
442
443     for (int i = 0; i < 100; ++i) {
444         sendMousePress(view.viewport(), itemPoint);
445         QCOMPARE(item->events.size(), i * 5 + 3);
446         QCOMPARE(item->events.at(item->events.size() - 2), QEvent::GrabMouse);
447         QCOMPARE(item->events.at(item->events.size() - 1), QEvent::GraphicsSceneMousePress);
448         sendMouseRelease(view.viewport(), itemPoint);
449         QCOMPARE(item->events.size(), i * 5 + 5);
450         QCOMPARE(item->events.at(item->events.size() - 2), QEvent::GraphicsSceneMouseRelease);
451         QCOMPARE(item->events.at(item->events.size() - 1), QEvent::UngrabMouse);
452         QContextMenuEvent contextEvent(QContextMenuEvent::Mouse, itemPoint, view.mapToGlobal(itemPoint));
453         QApplication::sendEvent(view.viewport(), &contextEvent);
454         QCOMPARE(item->events.size(), i * 5 + 6);
455         QCOMPARE(item->events.last(), QEvent::GraphicsSceneContextMenu);
456     }
457
458     view.setInteractive(false);
459
460     for (int i = 0; i < 100; ++i) {
461         sendMousePress(view.viewport(), itemPoint);
462         QCOMPARE(item->events.size(), 501);
463         QCOMPARE(item->events.last(), QEvent::GraphicsSceneContextMenu);
464         sendMouseRelease(view.viewport(), itemPoint);
465         QCOMPARE(item->events.size(), 501);
466         QCOMPARE(item->events.last(), QEvent::GraphicsSceneContextMenu);
467         QContextMenuEvent contextEvent(QContextMenuEvent::Mouse, itemPoint, view.mapToGlobal(itemPoint));
468         QApplication::sendEvent(view.viewport(), &contextEvent);
469         QCOMPARE(item->events.size(), 501);
470         QCOMPARE(item->events.last(), QEvent::GraphicsSceneContextMenu);
471     }
472 }
473
474 void tst_QGraphicsView::scene()
475 {
476     QGraphicsView view;
477     QVERIFY(!view.scene());
478     view.setScene(0);
479     QVERIFY(!view.scene());
480
481     {
482         QGraphicsScene scene;
483         view.setScene(&scene);
484         QCOMPARE(view.scene(), &scene);
485     }
486
487     QCOMPARE(view.scene(), (QGraphicsScene *)0);
488 }
489
490 void tst_QGraphicsView::setScene()
491 {
492     QGraphicsScene scene(-1000, -1000, 2000, 2000);
493
494     QGraphicsView view(&scene);
495     view.show();
496     QTest::qWaitForWindowShown(&view);
497
498     QCOMPARE(view.sceneRect(), scene.sceneRect());
499
500     QVERIFY(view.horizontalScrollBar()->isVisible());
501     QVERIFY(view.verticalScrollBar()->isVisible());
502     QVERIFY(!view.horizontalScrollBar()->isHidden());
503     QVERIFY(!view.verticalScrollBar()->isHidden());
504
505     view.setScene(0);
506
507     QTest::qWait(25);
508
509     QVERIFY(!view.horizontalScrollBar()->isVisible());
510     QVERIFY(!view.verticalScrollBar()->isVisible());
511     QVERIFY(!view.horizontalScrollBar()->isHidden());
512     QVERIFY(!view.verticalScrollBar()->isHidden());
513
514     QCOMPARE(view.sceneRect(), QRectF());
515 }
516
517 void tst_QGraphicsView::deleteScene()
518 {
519     QGraphicsScene *scene = new QGraphicsScene;
520     QGraphicsView view1(scene);
521     view1.show();
522     QGraphicsView view2(scene);
523     view2.show();
524     QGraphicsView view3(scene);
525     view3.show();
526     delete scene;
527     QCOMPARE(view1.scene(), (QGraphicsScene *)0);
528     QCOMPARE(view2.scene(), (QGraphicsScene *)0);
529     QCOMPARE(view3.scene(), (QGraphicsScene *)0);
530 }
531
532 void tst_QGraphicsView::sceneRect()
533 {
534     QGraphicsView view;
535     QCOMPARE(view.sceneRect(), QRectF());
536
537     view.setSceneRect(QRectF(-100, -100, 200, 200));
538     QCOMPARE(view.sceneRect(), QRectF(-100, -100, 200, 200));
539     view.setSceneRect(-100, -100, 200, 200);
540     QCOMPARE(view.sceneRect(), QRectF(-100, -100, 200, 200));
541
542     view.setSceneRect(QRectF());
543     QCOMPARE(view.sceneRect(), QRectF());
544     QGraphicsScene scene;
545     QGraphicsRectItem *item = scene.addRect(QRectF(-100, -100, 100, 100));
546
547     view.setScene(&scene);
548
549     QCOMPARE(view.sceneRect(), QRectF(-100, -100, 100, 100));
550     item->moveBy(-100, -100);
551     QCOMPARE(view.sceneRect(), QRectF(-200, -200, 200, 200));
552     item->moveBy(100, 100);
553     QCOMPARE(view.sceneRect(), QRectF(-200, -200, 200, 200));
554
555     view.setScene(0);
556     view.setSceneRect(QRectF());
557     QCOMPARE(view.sceneRect(), QRectF());
558 }
559
560 void tst_QGraphicsView::sceneRect_growing()
561 {
562     QWidget toplevel;
563
564     QGraphicsScene scene;
565     for (int i = 0; i < 100; ++i)
566         scene.addText(QString("(0, %1)").arg((i - 50) * 20))->setPos(0, (i - 50) * 20);
567
568     QGraphicsView view(&scene, &toplevel);
569     view.setFixedSize(200, 200);
570     toplevel.show();
571
572     int size = 200;
573     scene.setSceneRect(-size, -size, size * 2, size * 2);
574     QCOMPARE(view.sceneRect(), scene.sceneRect());
575
576     QTest::qWait(25);
577
578     QPointF topLeft = view.mapToScene(0, 0);
579
580     for (int i = 0; i < 5; ++i) {
581         size *= 2;
582         scene.setSceneRect(-size, -size, size * 2, size * 2);
583
584         QApplication::processEvents();
585
586         QCOMPARE(view.sceneRect(), scene.sceneRect());
587         QCOMPARE(view.mapToScene(0, 0), topLeft);
588         view.setSceneRect(-size, -size, size * 2, size * 2);
589         QCOMPARE(view.mapToScene(0, 0), topLeft);
590         view.setSceneRect(QRectF());
591     }
592 }
593
594 void tst_QGraphicsView::setSceneRect()
595 {
596     QRectF rect1(-100, -100, 200, 200);
597     QRectF rect2(-300, -300, 150, 150);
598
599     QGraphicsScene scene;
600     QGraphicsView view(&scene);
601
602     scene.setSceneRect(rect1);
603     QCOMPARE(scene.sceneRect(), rect1);
604     QCOMPARE(view.sceneRect(), rect1);
605
606     scene.setSceneRect(rect2);
607     QCOMPARE(scene.sceneRect(), rect2);
608     QCOMPARE(view.sceneRect(), rect2);
609
610     view.setSceneRect(rect1);
611     QCOMPARE(scene.sceneRect(), rect2);
612     QCOMPARE(view.sceneRect(), rect1);
613
614     view.setSceneRect(rect2);
615     QCOMPARE(scene.sceneRect(), rect2);
616     QCOMPARE(view.sceneRect(), rect2);
617
618     scene.setSceneRect(rect1);
619     QCOMPARE(scene.sceneRect(), rect1);
620     QCOMPARE(view.sceneRect(), rect2);
621
622     // extreme transformations will max out the scrollbars' ranges.
623     view.setSceneRect(-2000000, -2000000, 4000000, 4000000);
624     view.scale(9000, 9000);
625     QCOMPARE(view.horizontalScrollBar()->minimum(), INT_MIN);
626     QCOMPARE(view.horizontalScrollBar()->maximum(), INT_MAX);
627     QCOMPARE(view.verticalScrollBar()->minimum(), INT_MIN);
628     QCOMPARE(view.verticalScrollBar()->maximum(), INT_MAX);
629 }
630
631 void tst_QGraphicsView::viewport()
632 {
633     QGraphicsScene scene;
634     scene.addText("GraphicsView");
635
636     QGraphicsView view(&scene);
637     QVERIFY(view.viewport() != 0);
638
639     view.show();
640     QTest::qWait(25);
641
642     QPointer<QWidget> widget = new QWidget;
643     view.setViewport(widget);
644     QCOMPARE(view.viewport(), (QWidget *)widget);
645
646     view.show();
647     QTest::qWait(25);
648
649     view.setViewport(0);
650     QVERIFY(widget.isNull());
651     QVERIFY(view.viewport() != 0);
652     QVERIFY(view.viewport() != widget);
653
654     view.show();
655     QTest::qWait(25);
656 }
657
658 void tst_QGraphicsView::dragMode_scrollHand()
659 {
660     for (int j = 0; j < 2; ++j) {
661         QGraphicsView view;
662         QCOMPARE(view.dragMode(), QGraphicsView::NoDrag);
663
664         view.setSceneRect(-1000, -1000, 2000, 2000);
665         view.setFixedSize(100, 100);
666         view.show();
667
668         QTest::qWaitForWindowShown(&view);
669         QApplication::processEvents();
670
671         view.setInteractive(j ? false : true);
672
673         QGraphicsScene scene;
674         scene.addRect(QRectF(-100, -100, 5, 5));
675         scene.addRect(QRectF(95, -100, 5, 5));
676         scene.addRect(QRectF(95, 95, 5, 5));
677         QGraphicsItem *item = scene.addRect(QRectF(-100, 95, 5, 5));
678         item->setFlag(QGraphicsItem::ItemIsSelectable);
679         item->setSelected(true);
680         QVERIFY(item->isSelected());
681         QVERIFY(!view.scene());
682
683         view.setDragMode(QGraphicsView::ScrollHandDrag);
684
685         for (int i = 0; i < 2; ++i) {
686             // ScrollHandDrag
687 #ifndef QT_NO_CURSOR
688             Qt::CursorShape cursorShape = view.viewport()->cursor().shape();
689 #endif
690             int horizontalScrollBarValue = view.horizontalScrollBar()->value();
691             int verticalScrollBarValue = view.verticalScrollBar()->value();
692             {
693                 // Press
694                 QMouseEvent event(QEvent::MouseButtonPress,
695                                   view.viewport()->rect().center(),
696                                   Qt::LeftButton, Qt::LeftButton, 0);
697                 event.setAccepted(true);
698                 QApplication::sendEvent(view.viewport(), &event);
699                 QVERIFY(event.isAccepted());
700             }
701             QApplication::processEvents();
702
703             QTRY_VERIFY(item->isSelected());
704
705             for (int k = 0; k < 4; ++k) {
706 #ifndef QT_NO_CURSOR
707                 QCOMPARE(view.viewport()->cursor().shape(), Qt::ClosedHandCursor);
708 #endif
709                 {
710                     // Move
711                     QMouseEvent event(QEvent::MouseMove,
712                                       view.viewport()->rect().center() + QPoint(10, 0),
713                                       Qt::LeftButton, Qt::LeftButton, 0);
714                     event.setAccepted(true);
715                     QApplication::sendEvent(view.viewport(), &event);
716                     QVERIFY(event.isAccepted());
717                 }
718                 QVERIFY(item->isSelected());
719                 QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue - 10);
720                 QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue);
721                 {
722                     // Move
723                     QMouseEvent event(QEvent::MouseMove,
724                                       view.viewport()->rect().center() + QPoint(10, 10),
725                                       Qt::LeftButton, Qt::LeftButton, 0);
726                     event.setAccepted(true);
727                     QApplication::sendEvent(view.viewport(), &event);
728                     QVERIFY(event.isAccepted());
729                 }
730                 QVERIFY(item->isSelected());
731                 QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue - 10);
732                 QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue - 10);
733             }
734
735             {
736                 // Release
737                 QMouseEvent event(QEvent::MouseButtonRelease,
738                                   view.viewport()->rect().center() + QPoint(10, 10),
739                                   Qt::LeftButton, Qt::LeftButton, 0);
740                 event.setAccepted(true);
741                 QApplication::sendEvent(view.viewport(), &event);
742                 QVERIFY(event.isAccepted());
743             }
744             QApplication::processEvents();
745
746             QTRY_VERIFY(item->isSelected());
747             QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue - 10);
748             QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue - 10);
749 #ifndef QT_NO_CURSOR
750             QCOMPARE(view.viewport()->cursor().shape(), cursorShape);
751 #endif
752
753             // Check that items are not unselected because of a scroll hand drag.
754             QVERIFY(item->isSelected());
755
756             // Check that a click will still unselect the item.
757             {
758                 // Press
759                 QMouseEvent event(QEvent::MouseButtonPress,
760                                   view.viewport()->rect().center() + QPoint(10, 10),
761                                   Qt::LeftButton, Qt::LeftButton, 0);
762                 QApplication::sendEvent(view.viewport(), &event);
763             }
764             {
765                 // Release
766                 QMouseEvent event(QEvent::MouseButtonRelease,
767                                   view.viewport()->rect().center() + QPoint(10, 10),
768                                   Qt::LeftButton, Qt::LeftButton, 0);
769                 QApplication::sendEvent(view.viewport(), &event);
770             }
771
772             if (view.isInteractive()) {
773                 if (view.scene()) {
774                     QVERIFY(!item->isSelected());
775                     item->setSelected(true);
776                 } else {
777                     QVERIFY(item->isSelected());
778                 }
779             } else {
780                 QVERIFY(item->isSelected());
781             }
782
783             view.setScene(&scene);
784         }
785     }
786 }
787
788 void tst_QGraphicsView::dragMode_rubberBand()
789 {
790     QGraphicsView view;
791     QCOMPARE(view.dragMode(), QGraphicsView::NoDrag);
792
793     view.setSceneRect(-1000, -1000, 2000, 2000);
794     view.show();
795
796     QGraphicsScene scene;
797     scene.addRect(QRectF(-100, -100, 25, 25))->setFlag(QGraphicsItem::ItemIsSelectable);
798     scene.addRect(QRectF(75, -100, 25, 25))->setFlag(QGraphicsItem::ItemIsSelectable);
799     scene.addRect(QRectF(75, 75, 25, 25))->setFlag(QGraphicsItem::ItemIsSelectable);
800     scene.addRect(QRectF(-100, 75, 25, 25))->setFlag(QGraphicsItem::ItemIsSelectable);
801
802     view.setDragMode(QGraphicsView::RubberBandDrag);
803
804     QTest::qWaitForWindowShown(&view);
805     QApplication::processEvents();
806
807     for (int i = 0; i < 2; ++i) {
808         // RubberBandDrag
809 #ifndef QT_NO_CURSOR
810         Qt::CursorShape cursorShape = view.viewport()->cursor().shape();
811 #endif
812         int horizontalScrollBarValue = view.horizontalScrollBar()->value();
813         int verticalScrollBarValue = view.verticalScrollBar()->value();
814         {
815             // Press
816             QMouseEvent event(QEvent::MouseButtonPress,
817                               view.viewport()->rect().center(),
818                               Qt::LeftButton, Qt::LeftButton, 0);
819             event.setAccepted(true);
820             QApplication::sendEvent(view.viewport(), &event);
821             QVERIFY(event.isAccepted());
822         }
823 #ifndef QT_NO_CURSOR
824         QCOMPARE(view.viewport()->cursor().shape(), cursorShape);
825 #endif
826
827         QApplication::processEvents();
828
829         {
830             // Move
831             QMouseEvent event(QEvent::MouseMove,
832                               view.viewport()->rect().center() + QPoint(100, 0),
833                               Qt::LeftButton, Qt::LeftButton, 0);
834             event.setAccepted(true);
835             QApplication::sendEvent(view.viewport(), &event);
836             QVERIFY(event.isAccepted());
837         }
838         QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue);
839         QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue);
840
841         // We don't use QRubberBand as of 4.3; the band is drawn internally.
842         QVERIFY(!qFindChild<QRubberBand *>(&view));
843
844         QTest::qWait(25);
845
846         {
847             // Move
848             QMouseEvent event(QEvent::MouseMove,
849                               view.viewport()->rect().center() + QPoint(100, 100),
850                               Qt::LeftButton, Qt::LeftButton, 0);
851             event.setAccepted(true);
852             QApplication::sendEvent(view.viewport(), &event);
853             QVERIFY(event.isAccepted());
854         }
855         QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue);
856         QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue);
857
858         QTest::qWait(25);
859
860         {
861             // Release
862             QMouseEvent event(QEvent::MouseButtonRelease,
863                               view.viewport()->rect().center() + QPoint(100, 100),
864                               Qt::LeftButton, Qt::LeftButton, 0);
865             event.setAccepted(true);
866             QApplication::sendEvent(view.viewport(), &event);
867             QVERIFY(event.isAccepted());
868         }
869         QCOMPARE(view.horizontalScrollBar()->value(), horizontalScrollBarValue);
870         QCOMPARE(view.verticalScrollBar()->value(), verticalScrollBarValue);
871 #ifndef QT_NO_CURSOR
872         QCOMPARE(view.viewport()->cursor().shape(), cursorShape);
873 #endif
874
875         QTest::qWait(25);
876
877         if (view.scene())
878             QCOMPARE(scene.selectedItems().size(), 1);
879
880         view.setScene(&scene);
881         view.centerOn(0, 0);
882     }
883 }
884
885 void tst_QGraphicsView::rubberBandSelectionMode()
886 {
887     QWidget toplevel;
888
889     QGraphicsScene scene;
890     QGraphicsRectItem *rect = scene.addRect(QRectF(10, 10, 80, 80));
891     rect->setFlag(QGraphicsItem::ItemIsSelectable);
892
893     QGraphicsView view(&scene, &toplevel);
894     QCOMPARE(view.rubberBandSelectionMode(), Qt::IntersectsItemShape);
895     view.setDragMode(QGraphicsView::RubberBandDrag);
896     view.resize(120, 120);
897     toplevel.show();
898
899     // Disable mouse tracking to prevent the window system from sending mouse
900     // move events to the viewport while we are synthesizing events. If
901     // QGraphicsView gets a mouse move event with no buttons down, it'll
902     // terminate the rubber band.
903     view.viewport()->setMouseTracking(false);
904
905     QCOMPARE(scene.selectedItems(), QList<QGraphicsItem *>());
906     sendMousePress(view.viewport(), QPoint(), Qt::LeftButton);
907     sendMouseMove(view.viewport(), view.viewport()->rect().center(),
908                   Qt::LeftButton, Qt::LeftButton);
909     QCOMPARE(scene.selectedItems(), QList<QGraphicsItem *>() << rect);
910     sendMouseRelease(view.viewport(), QPoint(), Qt::LeftButton);
911
912     view.setRubberBandSelectionMode(Qt::ContainsItemShape);
913     QCOMPARE(view.rubberBandSelectionMode(), Qt::ContainsItemShape);
914     sendMousePress(view.viewport(), QPoint(), Qt::LeftButton);
915     QCOMPARE(scene.selectedItems(), QList<QGraphicsItem *>());
916     sendMouseMove(view.viewport(), view.viewport()->rect().center(),
917                   Qt::LeftButton, Qt::LeftButton);
918     QCOMPARE(scene.selectedItems(), QList<QGraphicsItem *>());
919     sendMouseMove(view.viewport(), view.viewport()->rect().bottomRight(),
920                   Qt::LeftButton, Qt::LeftButton);
921     QCOMPARE(scene.selectedItems(), QList<QGraphicsItem *>() << rect);
922 }
923
924 void tst_QGraphicsView::backgroundBrush()
925 {
926     QGraphicsScene scene;
927     QGraphicsView view(&scene);
928     scene.setBackgroundBrush(Qt::blue);
929     QCOMPARE(scene.backgroundBrush(), QBrush(Qt::blue));
930
931     view.show();
932     QTest::qWait(25);
933
934     scene.setBackgroundBrush(QBrush());
935     QCOMPARE(scene.backgroundBrush(), QBrush());
936     QTest::qWait(25);
937
938     QRadialGradient gradient(0, 0, 10);
939     gradient.setSpread(QGradient::RepeatSpread);
940     scene.setBackgroundBrush(gradient);
941
942     QCOMPARE(scene.backgroundBrush(), QBrush(gradient));
943     QTest::qWait(25);
944 }
945
946 void tst_QGraphicsView::foregroundBrush()
947 {
948     QGraphicsScene scene;
949     QGraphicsView view(&scene);
950     scene.setForegroundBrush(Qt::blue);
951     QCOMPARE(scene.foregroundBrush(), QBrush(Qt::blue));
952
953     view.show();
954     QTest::qWait(25);
955
956     scene.setForegroundBrush(QBrush());
957     QCOMPARE(scene.foregroundBrush(), QBrush());
958     QTest::qWait(25);
959
960     QRadialGradient gradient(0, 0, 10);
961     gradient.setSpread(QGradient::RepeatSpread);
962     scene.setForegroundBrush(gradient);
963
964     QCOMPARE(scene.foregroundBrush(), QBrush(gradient));
965     QTest::qWait(25);
966
967     for (int i = 0; i < 50; ++i) {
968         QRadialGradient gradient(view.rect().center() + QPoint(int(sin(i / 2.0) * 10), int(cos(i / 2.0) * 10)), 10);
969         gradient.setColorAt(0, Qt::transparent);
970         gradient.setColorAt(0.5, Qt::black);
971         gradient.setColorAt(1, Qt::transparent);
972         gradient.setSpread(QGradient::RepeatSpread);
973         scene.setForegroundBrush(gradient);
974
975         QRadialGradient gradient2(view.rect().center() + QPoint(int(sin(i / 1.7) * 10), int(cos(i / 1.7) * 10)), 10);
976         gradient2.setColorAt(0, Qt::transparent);
977         gradient2.setColorAt(0.5, Qt::black);
978         gradient2.setColorAt(1, Qt::transparent);
979         gradient2.setSpread(QGradient::RepeatSpread);
980         scene.setBackgroundBrush(gradient2);
981
982         QRadialGradient gradient3(view.rect().center() + QPoint(int(sin(i / 1.85) * 10), int(cos(i / 1.85) * 10)), 10);
983         gradient3.setColorAt(0, Qt::transparent);
984         gradient3.setColorAt(0.5, Qt::black);
985         gradient3.setColorAt(1, Qt::transparent);
986         gradient3.setSpread(QGradient::RepeatSpread);
987         scene.setBackgroundBrush(gradient3);
988
989         QApplication::processEvents();
990     }
991
992     view.setSceneRect(-1000, -1000, 2000, 2000);
993     for (int i = -500; i < 500; i += 10) {
994         view.centerOn(i, 0);
995         QApplication::processEvents();
996         QApplication::processEvents();
997     }
998     for (int i = -500; i < 500; i += 10) {
999         view.centerOn(0, i);
1000         QApplication::processEvents();
1001         QApplication::processEvents();
1002     }
1003 }
1004
1005 void tst_QGraphicsView::matrix()
1006 {
1007     {
1008         QGraphicsScene scene;
1009         QGraphicsView view(&scene);
1010         view.show();
1011
1012         // Show rendering of background with no scene
1013         for (int i = 0; i < 50; ++i) {
1014             view.rotate(5);
1015             QRadialGradient gradient(view.rect().center() + QPoint(int(sin(i / 2.0) * 10), int(cos(i / 2.0) * 10)), 10);
1016             gradient.setColorAt(0, Qt::transparent);
1017             gradient.setColorAt(0.5, Qt::black);
1018             gradient.setColorAt(1, Qt::transparent);
1019             gradient.setSpread(QGradient::RepeatSpread);
1020             scene.setForegroundBrush(gradient);
1021             QRadialGradient gradient2(view.rect().center() + QPoint(int(sin(i / 1.7) * 10), int(cos(i / 1.7) * 10)), 10);
1022             gradient2.setColorAt(0, Qt::transparent);
1023             gradient2.setColorAt(0.5, Qt::black);
1024             gradient2.setColorAt(1, Qt::transparent);
1025             gradient2.setSpread(QGradient::RepeatSpread);
1026             scene.setBackgroundBrush(gradient2);
1027             QApplication::processEvents();
1028             QApplication::processEvents();
1029         }
1030     }
1031
1032     // Test transformation extremes, see if they cause crashes
1033     {
1034         QGraphicsScene scene;
1035         scene.addText("GraphicsView rotated clockwise");
1036
1037         QGraphicsView view(&scene);
1038         view.show();
1039         for (int i = 0; i < 160; ++i) {
1040             view.rotate(18);
1041             QApplication::processEvents();
1042             QApplication::processEvents();
1043         }
1044         /*
1045           // These cause a crash
1046         for (int i = 0; i < 40; ++i) {
1047             view.shear(1.2, 1.2);
1048             QTest::qWait(20);
1049         }
1050         for (int i = 0; i < 40; ++i) {
1051             view.shear(-1.2, -1.2);
1052             QTest::qWait(20);
1053         }
1054         */
1055         for (int i = 0; i < 20; ++i) {
1056             view.scale(1.2, 1.2);
1057             QApplication::processEvents();
1058             QApplication::processEvents();
1059         }
1060         for (int i = 0; i < 20; ++i) {
1061             view.scale(0.6, 0.6);
1062             QApplication::processEvents();
1063             QApplication::processEvents();
1064         }
1065     }
1066 }
1067
1068 void tst_QGraphicsView::matrix_convenience()
1069 {
1070     QGraphicsView view;
1071     QCOMPARE(view.matrix(), QMatrix());
1072
1073     // Check the convenience functions
1074     view.rotate(90);
1075     QCOMPARE(view.matrix(), QMatrix().rotate(90));
1076     view.scale(2, 2);
1077     QCOMPARE(view.matrix(), QMatrix().scale(2, 2) * QMatrix().rotate(90));
1078     view.shear(1.2, 1.2);
1079     QCOMPARE(view.matrix(), QMatrix().shear(1.2, 1.2) * QMatrix().scale(2, 2) * QMatrix().rotate(90));
1080     view.translate(1, 1);
1081     QCOMPARE(view.matrix(), QMatrix().translate(1, 1) * QMatrix().shear(1.2, 1.2) * QMatrix().scale(2, 2) * QMatrix().rotate(90));
1082 }
1083
1084 void tst_QGraphicsView::matrix_combine()
1085 {
1086     // Check matrix combining
1087     QGraphicsView view;
1088     QCOMPARE(view.matrix(), QMatrix());
1089     view.setMatrix(QMatrix().rotate(90), true);
1090     view.setMatrix(QMatrix().rotate(90), true);
1091     view.setMatrix(QMatrix().rotate(90), true);
1092     view.setMatrix(QMatrix().rotate(90), true);
1093     QCOMPARE(view.matrix(), QMatrix());
1094
1095     view.resetMatrix();
1096     QCOMPARE(view.matrix(), QMatrix());
1097     view.setMatrix(QMatrix().rotate(90), false);
1098     view.setMatrix(QMatrix().rotate(90), false);
1099     view.setMatrix(QMatrix().rotate(90), false);
1100     view.setMatrix(QMatrix().rotate(90), false);
1101     QCOMPARE(view.matrix(), QMatrix().rotate(90));
1102 }
1103
1104 void tst_QGraphicsView::centerOnPoint()
1105 {
1106     QWidget toplevel;
1107
1108     QGraphicsScene scene;
1109     scene.addEllipse(QRectF(-100, -100, 50, 50));
1110     scene.addEllipse(QRectF(50, -100, 50, 50));
1111     scene.addEllipse(QRectF(-100, 50, 50, 50));
1112     scene.addEllipse(QRectF(50, 50, 50, 50));
1113
1114     QGraphicsView view(&scene, &toplevel);
1115     view.setSceneRect(-400, -400, 800, 800);
1116     view.setFixedSize(100, 100);
1117     toplevel.show();
1118
1119     int tolerance = 5;
1120
1121     for (int i = 0; i < 3; ++i) {
1122         for (int y = -100; y < 100; y += 23) {
1123             for (int x = -100; x < 100; x += 23) {
1124                 view.centerOn(x, y);
1125                 QPoint viewCenter = view.mapToScene(view.viewport()->rect().center()).toPoint();
1126
1127                 // Fuzzy compare
1128                 if (viewCenter.x() < x - tolerance || viewCenter.x() > x + tolerance
1129                     || viewCenter.y() < y - tolerance || viewCenter.y() > y + tolerance) {
1130                     QString error = QString("Compared values are not the same\n\tActual: (%1, %2)\n\tExpected: (%3, %4)")
1131                                     .arg(viewCenter.x()).arg(viewCenter.y()).arg(x).arg(y);
1132                     QFAIL(qPrintable(error));
1133                 }
1134
1135                 QApplication::processEvents();
1136             }
1137         }
1138
1139         view.rotate(13);
1140         view.scale(1.5, 1.5);
1141         view.shear(1.25, 1.25);
1142     }
1143 }
1144
1145 void tst_QGraphicsView::centerOnItem()
1146 {
1147     QGraphicsScene scene;
1148     QGraphicsItem *items[4];
1149     items[0] = scene.addEllipse(QRectF(-25, -25, 50, 50));
1150     items[1] = scene.addEllipse(QRectF(-25, -25, 50, 50));
1151     items[2] = scene.addEllipse(QRectF(-25, -25, 50, 50));
1152     items[3] = scene.addEllipse(QRectF(-25, -25, 50, 50));
1153     items[0]->setPos(-100, -100);
1154     items[1]->setPos(100, -100);
1155     items[2]->setPos(-100, 100);
1156     items[3]->setPos(100, 100);
1157
1158     QGraphicsView view(&scene);
1159     view.setSceneRect(-1000, -1000, 2000, 2000);
1160     view.show();
1161     QTest::qWaitForWindowShown(&view);
1162     int tolerance = 7;
1163
1164     for (int x = 0; x < 3; ++x) {
1165         for (int i = 0; i < 4; ++i) {
1166             QApplication::processEvents();
1167             view.centerOn(items[i]);
1168
1169             QPoint viewCenter = view.mapToScene(view.viewport()->rect().center()).toPoint();
1170             qreal x = items[i]->pos().x();
1171             qreal y = items[i]->pos().y();
1172
1173             // Fuzzy compare
1174             if (viewCenter.x() < x - tolerance || viewCenter.x() > x + tolerance
1175                 || viewCenter.y() < y - tolerance || viewCenter.y() > y + tolerance) {
1176                 QString error = QString("Compared values are not the same\n\tActual: (%1, %2)\n\tExpected: (%3, %4)")
1177                                 .arg(viewCenter.x()).arg(viewCenter.y()).arg(x).arg(y);
1178                 QFAIL(qPrintable(error));
1179             }
1180
1181             QApplication::processEvents();
1182         }
1183
1184         view.rotate(13);
1185         view.scale(1.5, 1.5);
1186         view.shear(1.25, 1.25);
1187     }
1188 }
1189
1190 void tst_QGraphicsView::ensureVisibleRect()
1191 {
1192     QWidget toplevel;
1193
1194     QGraphicsScene scene;
1195     QGraphicsItem *items[4];
1196     items[0] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::green));
1197     items[1] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::red));
1198     items[2] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::blue));
1199     items[3] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::yellow));
1200     scene.addLine(QLineF(0, -100, 0, 100), QPen(Qt::blue, 2));
1201     scene.addLine(QLineF(-100, 0, 100, 0), QPen(Qt::blue, 2));
1202     items[0]->setPos(-100, -100);
1203     items[1]->setPos(100, -100);
1204     items[2]->setPos(-100, 100);
1205     items[3]->setPos(100, 100);
1206
1207     QGraphicsItem *icon = scene.addEllipse(QRectF(-10, -10, 20, 20), QPen(Qt::black), QBrush(Qt::gray));
1208
1209     QGraphicsView view(&scene, &toplevel);
1210     view.setSceneRect(-500, -500, 1000, 1000);
1211     view.setFixedSize(250, 250);
1212     toplevel.show();
1213     QTest::qWaitForWindowShown(&toplevel);
1214
1215     for (int y = -100; y < 100; y += 25) {
1216         for (int x = -100; x < 100; x += 13) {
1217
1218             icon->setPos(x, y);
1219
1220             switch (x & 3) {
1221             case 0:
1222                 view.centerOn(-500, -500);
1223                 break;
1224             case 1:
1225                 view.centerOn(500, -500);
1226                 break;
1227             case 2:
1228                 view.centerOn(-500, 500);
1229                 break;
1230             case 3:
1231             default:
1232                 view.centerOn(500, 500);
1233                 break;
1234             }
1235
1236             QVERIFY(!view.viewport()->rect().contains(view.mapFromScene(x, y)));
1237
1238             for (int margin = 10; margin < 60; margin += 15) {
1239                 view.ensureVisible(x, y, 0, 0, margin, margin);
1240
1241                 QRect viewRect = view.viewport()->rect();
1242                 QPoint viewPoint = view.mapFromScene(x, y);
1243
1244                 QVERIFY(viewRect.contains(viewPoint));
1245                 QVERIFY(qAbs(viewPoint.x() - viewRect.left()) >= margin -1);
1246                 QVERIFY(qAbs(viewPoint.x() - viewRect.right()) >= margin -1);
1247                 QVERIFY(qAbs(viewPoint.y() - viewRect.top()) >= margin -1);
1248                 QVERIFY(qAbs(viewPoint.y() - viewRect.bottom()) >= margin -1);
1249
1250                 QApplication::processEvents();
1251             }
1252         }
1253         view.rotate(5);
1254         view.scale(1.05, 1.05);
1255         view.translate(30, -30);
1256     }
1257 }
1258
1259 void tst_QGraphicsView::fitInView()
1260 {
1261     QGraphicsScene scene;
1262     QGraphicsItem *items[4];
1263     items[0] = scene.addEllipse(QRectF(-25, -25, 100, 20), QPen(Qt::black), QBrush(Qt::green));
1264     items[1] = scene.addEllipse(QRectF(-25, -25, 20, 100), QPen(Qt::black), QBrush(Qt::red));
1265     items[2] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::blue));
1266     items[3] = scene.addEllipse(QRectF(-25, -25, 50, 50), QPen(Qt::black), QBrush(Qt::yellow));
1267     scene.addLine(QLineF(0, -100, 0, 100), QPen(Qt::blue, 2));
1268     scene.addLine(QLineF(-100, 0, 100, 0), QPen(Qt::blue, 2));
1269     items[0]->setPos(-100, -100);
1270     items[1]->setPos(100, -100);
1271     items[2]->setPos(-100, 100);
1272     items[3]->setPos(100, 100);
1273
1274     items[0]->rotate(30);
1275     items[1]->rotate(-30);
1276
1277 #if defined(Q_OS_WINCE)
1278     //Is the standard scrollbar size
1279     int scrollbarSize = qApp->style()->pixelMetric(QStyle::PM_ScrollBarExtent) - 13;
1280 #endif
1281
1282     QGraphicsView view(&scene);
1283     view.setSceneRect(-400, -400, 800, 800);
1284
1285 #if defined(Q_OS_WINCE)
1286     //We need to take in account the scrollbar size for the WindowsMobilStyle
1287     view.setFixedSize(400 + scrollbarSize, 200 + scrollbarSize);
1288 #else
1289     view.setFixedSize(400, 200);
1290 #endif
1291
1292     if (PlatformQuirks::isAutoMaximizing())
1293         view.setWindowFlags(view.windowFlags()|Qt::X11BypassWindowManagerHint);
1294
1295     view.show();
1296     view.fitInView(scene.itemsBoundingRect(), Qt::IgnoreAspectRatio);
1297     qApp->processEvents();
1298
1299     // Sampled coordinates.
1300     QVERIFY(!view.itemAt(45, 41));
1301     QVERIFY(!view.itemAt(297, 44));
1302     QVERIFY(!view.itemAt(359, 143));
1303     QCOMPARE(view.itemAt(79, 22), items[0]);
1304     QCOMPARE(view.itemAt(329, 41), items[1]);
1305     QCOMPARE(view.itemAt(38, 158), items[2]);
1306     QCOMPARE(view.itemAt(332, 160), items[3]);
1307
1308     view.fitInView(items[0], Qt::IgnoreAspectRatio);
1309     qApp->processEvents();
1310
1311     QCOMPARE(view.itemAt(19, 13), items[0]);
1312     QCOMPARE(view.itemAt(91, 47), items[0]);
1313     QCOMPARE(view.itemAt(202, 94), items[0]);
1314     QCOMPARE(view.itemAt(344, 161), items[0]);
1315     QVERIFY(!view.itemAt(236, 54));
1316     QVERIFY(!view.itemAt(144, 11));
1317     QVERIFY(!view.itemAt(29, 69));
1318     QVERIFY(!view.itemAt(251, 167));
1319
1320     view.fitInView(items[0], Qt::KeepAspectRatio);
1321     qApp->processEvents();
1322
1323     QCOMPARE(view.itemAt(325, 170), items[0]);
1324     QCOMPARE(view.itemAt(206, 74), items[0]);
1325     QCOMPARE(view.itemAt(190, 115), items[0]);
1326     QCOMPARE(view.itemAt(55, 14), items[0]);
1327     QVERIFY(!view.itemAt(109, 4));
1328     QVERIFY(!view.itemAt(244, 68));
1329     QVERIFY(!view.itemAt(310, 125));
1330     QVERIFY(!view.itemAt(261, 168));
1331
1332     view.fitInView(items[0], Qt::KeepAspectRatioByExpanding);
1333     qApp->processEvents();
1334
1335     QCOMPARE(view.itemAt(18, 10), items[0]);
1336     QCOMPARE(view.itemAt(95, 4), items[0]);
1337     QCOMPARE(view.itemAt(279, 175), items[0]);
1338     QCOMPARE(view.itemAt(359, 170), items[0]);
1339     QVERIFY(!view.itemAt(370, 166));
1340     QVERIFY(!view.itemAt(136, 7));
1341     QVERIFY(!view.itemAt(31, 44));
1342     QVERIFY(!view.itemAt(203, 153));
1343 }
1344
1345 void tst_QGraphicsView::itemsAtPoint()
1346 {
1347     QGraphicsScene scene;
1348     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(1);
1349     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(0);
1350     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(2);
1351     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(-1);
1352     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(3);
1353
1354     QGraphicsView view;
1355     QVERIFY(view.items(0, 0).isEmpty());
1356
1357     view.setScene(&scene);
1358     view.setSceneRect(-10000, -10000, 20000, 20000);
1359     view.show();
1360
1361     QList<QGraphicsItem *> items = view.items(view.viewport()->rect().center());
1362     QCOMPARE(items.size(), 5);
1363     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1364     QCOMPARE(items.takeFirst()->zValue(), qreal(2));
1365     QCOMPARE(items.takeFirst()->zValue(), qreal(1));
1366     QCOMPARE(items.takeFirst()->zValue(), qreal(0));
1367     QCOMPARE(items.takeFirst()->zValue(), qreal(-1));
1368 }
1369
1370 #if defined QT_BUILD_INTERNAL
1371 void tst_QGraphicsView::itemsAtPosition_data()
1372 {
1373     QTest::addColumn<float>("rotation");
1374     QTest::addColumn<float>("scale");
1375     QTest::addColumn<QPoint>("viewPos");
1376     QTest::addColumn<bool>("ignoreTransform");
1377     QTest::addColumn<bool>("hit");
1378     QTest::newRow("scaled + ignore transform, no hit") << 0.0f << 1000.0f << QPoint(0, 0) << true << false;
1379     QTest::newRow("scaled + ignore transform, hit") << 0.0f << 1000.0f << QPoint(100, 100) << true << true;
1380     QTest::newRow("rotated + scaled, no hit") << 45.0f << 2.0f << QPoint(90, 90) << false << false;
1381     QTest::newRow("rotated + scaled, hit") << 45.0f << 2.0f << QPoint(100, 100) << false << true;
1382 }
1383
1384 void tst_QGraphicsView::itemsAtPosition()
1385 {
1386     QFETCH(float, rotation);
1387     QFETCH(float, scale);
1388     QFETCH(QPoint, viewPos);
1389     QFETCH(bool, ignoreTransform);
1390     QFETCH(bool, hit);
1391
1392     FriendlyGraphicsScene scene;
1393     scene.setSceneRect(QRect(-100, -100, 200, 200));
1394     QGraphicsItem *item = scene.addRect(-5, -5, 10, 10);
1395
1396     if (ignoreTransform)
1397         item->setFlag(QGraphicsItem::ItemIgnoresTransformations);
1398
1399     QGraphicsView view;
1400     view.setFrameStyle(QFrame::NoFrame);
1401     view.resize(200, 200);
1402     view.scale(scale, scale);
1403     view.rotate(rotation);
1404     view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1405     view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1406     view.setScene(&scene);
1407     view.show();
1408     QTest::qWaitForWindowShown(&view);
1409
1410     QPoint screenPos = view.viewport()->mapToGlobal(viewPos);
1411     QPointF scenePos = view.mapToScene(viewPos);
1412     QGraphicsScenePrivate *viewPrivate = scene.d_func();
1413     QList<QGraphicsItem *> items;
1414     items = viewPrivate->itemsAtPosition(screenPos, scenePos, view.viewport());
1415     QCOMPARE(!items.empty(), hit);
1416 }
1417 #endif
1418
1419 void tst_QGraphicsView::itemsInRect()
1420 {
1421     QGraphicsScene scene;
1422     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(1);
1423     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(0);
1424     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(2);
1425     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(-1);
1426     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(3);
1427
1428     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(5);
1429     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(4);
1430     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(6);
1431     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(3);
1432     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(7);
1433
1434     QGraphicsView view;
1435     QVERIFY(view.items(QRect(-100, -100, 200, 200)).isEmpty());
1436     view.setScene(&scene);
1437     view.setSceneRect(-10000, -10000, 20000, 20000);
1438     view.show();
1439
1440     QRect leftRect = view.mapFromScene(-30, -10, 20, 20).boundingRect();
1441     QRect rightRect = view.mapFromScene(30, -10, 20, 20).boundingRect();
1442
1443     QList<QGraphicsItem *> items = view.items(leftRect);
1444     QCOMPARE(items.size(), 5);
1445     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1446     QCOMPARE(items.takeFirst()->zValue(), qreal(2));
1447     QCOMPARE(items.takeFirst()->zValue(), qreal(1));
1448     QCOMPARE(items.takeFirst()->zValue(), qreal(0));
1449     QCOMPARE(items.takeFirst()->zValue(), qreal(-1));
1450
1451     items = view.items(rightRect);
1452     QCOMPARE(items.size(), 5);
1453     QCOMPARE(items.takeFirst()->zValue(), qreal(7));
1454     QCOMPARE(items.takeFirst()->zValue(), qreal(6));
1455     QCOMPARE(items.takeFirst()->zValue(), qreal(5));
1456     QCOMPARE(items.takeFirst()->zValue(), qreal(4));
1457     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1458 }
1459
1460 class CountPaintItem : public QGraphicsRectItem
1461 {
1462 public:
1463     int numPaints;
1464
1465     CountPaintItem(const QRectF &rect)
1466         : QGraphicsRectItem(rect), numPaints(0)
1467     { }
1468
1469     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0)
1470     {
1471         ++numPaints;
1472         QGraphicsRectItem::paint(painter, option, widget);
1473     }
1474 };
1475
1476 void tst_QGraphicsView::itemsInRect_cosmeticAdjust_data()
1477 {
1478     QTest::addColumn<QRect>("updateRect");
1479     QTest::addColumn<int>("numPaints");
1480     QTest::addColumn<bool>("adjustForAntialiasing");
1481
1482     // Aliased.
1483     QTest::newRow("nil") << QRect() << 1 << false;
1484     QTest::newRow("0, 0, 300, 100") << QRect(0, 0, 300, 100) << 1 << false;
1485     QTest::newRow("0, 0, 100, 300") << QRect(0, 0, 100, 300) << 1 << false;
1486     QTest::newRow("200, 0, 100, 300") << QRect(200, 0, 100, 300) << 1 << false;
1487     QTest::newRow("0, 200, 300, 100") << QRect(0, 200, 300, 100) << 1 << false;
1488     QTest::newRow("0, 0, 300, 99") << QRect(0, 0, 300, 99) << 0 << false;
1489     QTest::newRow("0, 0, 99, 300") << QRect(0, 0, 99, 300) << 0 << false;
1490     QTest::newRow("201, 0, 99, 300") << QRect(201, 0, 99, 300) << 0 << false;
1491     QTest::newRow("0, 201, 300, 99") << QRect(0, 201, 300, 99) << 0 << false;
1492
1493     // Anti-aliased.
1494     QTest::newRow("nil") << QRect() << 1 << true;
1495     QTest::newRow("0, 0, 300, 100") << QRect(0, 0, 300, 100) << 1 << true;
1496     QTest::newRow("0, 0, 100, 300") << QRect(0, 0, 100, 300) << 1 << true;
1497     QTest::newRow("200, 0, 100, 300") << QRect(200, 0, 100, 300) << 1 << true;
1498     QTest::newRow("0, 200, 300, 100") << QRect(0, 200, 300, 100) << 1 << true;
1499     QTest::newRow("0, 0, 300, 99") << QRect(0, 0, 300, 99) << 1 << true;
1500     QTest::newRow("0, 0, 99, 300") << QRect(0, 0, 99, 300) << 1 << true;
1501     QTest::newRow("201, 0, 99, 300") << QRect(201, 0, 99, 300) << 1 << true;
1502     QTest::newRow("0, 201, 300, 99") << QRect(0, 201, 300, 99) << 1 << true;
1503     QTest::newRow("0, 0, 300, 98") << QRect(0, 0, 300, 98) << 0 << false;
1504     QTest::newRow("0, 0, 98, 300") << QRect(0, 0, 98, 300) << 0 << false;
1505     QTest::newRow("202, 0, 98, 300") << QRect(202, 0, 98, 300) << 0 << false;
1506     QTest::newRow("0, 202, 300, 98") << QRect(0, 202, 300, 98) << 0 << false;
1507 }
1508
1509 void tst_QGraphicsView::itemsInRect_cosmeticAdjust()
1510 {
1511     QFETCH(QRect, updateRect);
1512     QFETCH(int, numPaints);
1513     QFETCH(bool, adjustForAntialiasing);
1514
1515     QGraphicsScene scene(-100, -100, 200, 200);
1516     CountPaintItem *rect = new CountPaintItem(QRectF(-50, -50, 100, 100));
1517     scene.addItem(rect);
1518
1519     QGraphicsView view(&scene);
1520     view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, !adjustForAntialiasing);
1521     view.setRenderHint(QPainter::Antialiasing, adjustForAntialiasing);
1522     if (PlatformQuirks::isAutoMaximizing())
1523         view.setWindowFlags(view.windowFlags()|Qt::X11BypassWindowManagerHint);
1524     view.setFrameStyle(0);
1525     view.resize(300, 300);
1526     view.show();
1527     QTest::qWaitForWindowShown(&view);
1528     QTRY_VERIFY(rect->numPaints > 0);
1529
1530     rect->numPaints = 0;
1531     if (updateRect.isNull())
1532         view.viewport()->update();
1533     else
1534         view.viewport()->update(updateRect);
1535     qApp->processEvents();
1536     QTRY_COMPARE(rect->numPaints, numPaints);
1537 }
1538
1539 void tst_QGraphicsView::itemsInPoly()
1540 {
1541     QGraphicsScene scene;
1542     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(1);
1543     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(0);
1544     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(2);
1545     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(-1);
1546     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(3);
1547
1548     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(5);
1549     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(4);
1550     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(6);
1551     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(3);
1552     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(7);
1553
1554     QGraphicsView view;
1555     QVERIFY(view.items(QPolygon()).isEmpty());
1556     view.setScene(&scene);
1557     view.setSceneRect(-10000, -10000, 20000, 20000);
1558     view.show();
1559
1560     QPolygon leftPoly = view.mapFromScene(QRectF(-30, -10, 20, 20));
1561     QPolygon rightPoly = view.mapFromScene(QRectF(30, -10, 20, 20));
1562
1563     QList<QGraphicsItem *> items = view.items(leftPoly);
1564     QCOMPARE(items.size(), 5);
1565     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1566     QCOMPARE(items.takeFirst()->zValue(), qreal(2));
1567     QCOMPARE(items.takeFirst()->zValue(), qreal(1));
1568     QCOMPARE(items.takeFirst()->zValue(), qreal(0));
1569     QCOMPARE(items.takeFirst()->zValue(), qreal(-1));
1570
1571     items = view.items(rightPoly);
1572     QCOMPARE(items.size(), 5);
1573     QCOMPARE(items.takeFirst()->zValue(), qreal(7));
1574     QCOMPARE(items.takeFirst()->zValue(), qreal(6));
1575     QCOMPARE(items.takeFirst()->zValue(), qreal(5));
1576     QCOMPARE(items.takeFirst()->zValue(), qreal(4));
1577     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1578 }
1579
1580 void tst_QGraphicsView::itemsInPath()
1581 {
1582     QGraphicsScene scene;
1583     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(1);
1584     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(0);
1585     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(2);
1586     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(-1);
1587     scene.addRect(QRectF(-30, -10, 20, 20))->setZValue(3);
1588
1589     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(5);
1590     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(4);
1591     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(6);
1592     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(3);
1593     scene.addRect(QRectF(30, -10, 20, 20))->setZValue(7);
1594
1595     QGraphicsView view;
1596     QVERIFY(view.items(QPainterPath()).isEmpty());
1597     view.setScene(&scene);
1598     view.translate(100, 400);
1599     view.rotate(22.3);
1600     view.setSceneRect(-10000, -10000, 20000, 20000);
1601     view.show();
1602
1603     QPainterPath leftPath;
1604     leftPath.addEllipse(QRect(view.mapFromScene(-30, -10), QSize(20, 20)));
1605
1606     QPainterPath rightPath;
1607     rightPath.addEllipse(QRect(view.mapFromScene(30, -10), QSize(20, 20)));
1608
1609     QList<QGraphicsItem *> items = view.items(leftPath);
1610
1611     QCOMPARE(items.size(), 5);
1612     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1613     QCOMPARE(items.takeFirst()->zValue(), qreal(2));
1614     QCOMPARE(items.takeFirst()->zValue(), qreal(1));
1615     QCOMPARE(items.takeFirst()->zValue(), qreal(0));
1616     QCOMPARE(items.takeFirst()->zValue(), qreal(-1));
1617
1618     items = view.items(rightPath);
1619     QCOMPARE(items.size(), 5);
1620     QCOMPARE(items.takeFirst()->zValue(), qreal(7));
1621     QCOMPARE(items.takeFirst()->zValue(), qreal(6));
1622     QCOMPARE(items.takeFirst()->zValue(), qreal(5));
1623     QCOMPARE(items.takeFirst()->zValue(), qreal(4));
1624     QCOMPARE(items.takeFirst()->zValue(), qreal(3));
1625 }
1626
1627 void tst_QGraphicsView::itemAt()
1628 {
1629     QGraphicsScene scene;
1630     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(1);
1631     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(0);
1632     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(2);
1633     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(-1);
1634     scene.addRect(QRectF(-10, -10, 20, 20))->setZValue(3);
1635
1636     QGraphicsView view;
1637     QCOMPARE(view.itemAt(0, 0), (QGraphicsItem *)0);
1638
1639     view.setScene(&scene);
1640     view.setSceneRect(-10000, -10000, 20000, 20000);
1641     view.show();
1642
1643     QCOMPARE(view.itemAt(0, 0), (QGraphicsItem *)0);
1644     QGraphicsItem* item = view.itemAt(view.viewport()->rect().center());
1645     QVERIFY(item);
1646     QCOMPARE(item->zValue(), qreal(3));
1647 }
1648
1649 void tst_QGraphicsView::itemAt2()
1650 {
1651     // test precision of the itemAt() function with items that are smaller
1652     // than 1 pixel.
1653     QGraphicsScene scene(0, 0, 100, 100);
1654
1655     // Add a 0.5x0.5 item at position 0 on the scene, top-left corner at -0.25, -0.25.
1656     QGraphicsItem *item = scene.addRect(QRectF(-0.25, -0.25, 0.5, 0.5), QPen(Qt::black, 0.1));
1657
1658     QGraphicsView view(&scene);
1659     view.setFixedSize(200, 200);
1660     view.setTransformationAnchor(QGraphicsView::NoAnchor);
1661     view.setRenderHint(QPainter::Antialiasing);
1662     view.show();
1663     QTest::qWaitForWindowShown(&view);
1664     QApplication::processEvents();
1665
1666     QPoint itemViewPoint = view.mapFromScene(item->scenePos());
1667
1668     for (int i = 0; i < 3; ++i) {
1669         QVERIFY(view.itemAt(itemViewPoint));
1670         QVERIFY(!view.items(itemViewPoint).isEmpty());
1671         QVERIFY(view.itemAt(itemViewPoint + QPoint(-1, 0)));
1672         QVERIFY(!view.items(itemViewPoint + QPoint(-1, 0)).isEmpty());
1673         QVERIFY(view.itemAt(itemViewPoint + QPoint(-1, -1)));
1674         QVERIFY(!view.items(itemViewPoint + QPoint(-1, -1)).isEmpty());
1675         QVERIFY(view.itemAt(itemViewPoint + QPoint(0, -1)));
1676         QVERIFY(!view.items(itemViewPoint + QPoint(0, -1)).isEmpty());
1677         item->moveBy(0.1, 0);
1678     }
1679
1680     // Here
1681     QVERIFY(view.itemAt(itemViewPoint));
1682     QVERIFY(!view.items(itemViewPoint).isEmpty());
1683     QVERIFY(view.itemAt(itemViewPoint + QPoint(0, -1)));
1684     QVERIFY(!view.items(itemViewPoint + QPoint(0, -1)).isEmpty());
1685
1686     if (sizeof(qreal) != sizeof(double))
1687         QSKIP("Skipped due to rounding errors");
1688
1689     // Not here
1690     QVERIFY(!view.itemAt(itemViewPoint + QPoint(-1, 0)));
1691     QVERIFY(view.items(itemViewPoint + QPoint(-1, 0)).isEmpty());
1692     QVERIFY(!view.itemAt(itemViewPoint + QPoint(-1, -1)));
1693     QVERIFY(view.items(itemViewPoint + QPoint(-1, -1)).isEmpty());
1694 }
1695
1696 void tst_QGraphicsView::mapToScene()
1697 {
1698     // Uncomment the commented-out code to see what's going on. It doesn't
1699     // affect the test; it just slows it down.
1700
1701     QGraphicsScene scene;
1702     scene.addPixmap(QPixmap("3D-Qt-1-2.png"));
1703
1704     QWidget topLevel;
1705     QGraphicsView view(&topLevel);
1706     view.setScene(&scene);
1707     view.setSceneRect(-500, -500, 1000, 1000);
1708 #if defined(Q_OS_WINCE)
1709     QSize viewSize(200,200);
1710 #else
1711     QSize viewSize(300,300);
1712 #endif
1713
1714     view.setFixedSize(viewSize);
1715     topLevel.show();
1716     QApplication::processEvents();
1717     QVERIFY(view.isVisible());
1718     QCOMPARE(view.size(), viewSize);
1719
1720     // First once without setting the scene rect
1721 #ifdef Q_PROCESSOR_ARM
1722     const int step = 20;
1723 #else
1724     const int step = 1;
1725 #endif
1726
1727     for (int x = 0; x < view.width(); x += step) {
1728         for (int y = 0; y < view.height(); y += step) {
1729             QCOMPARE(view.mapToScene(QPoint(x, y)),
1730                      QPointF(view.horizontalScrollBar()->value() + x,
1731                              view.verticalScrollBar()->value() + y));
1732         }
1733     }
1734
1735     for (int sceneRectHeight = 250; sceneRectHeight < 1000; sceneRectHeight += 250) {
1736         for (int sceneRectWidth = 250; sceneRectWidth < 1000; sceneRectWidth += 250) {
1737             view.setSceneRect(QRectF(-int(sceneRectWidth / 2), -int(sceneRectHeight / 2),
1738                                      sceneRectWidth, sceneRectHeight));
1739             QApplication::processEvents();
1740
1741             int hmin = view.horizontalScrollBar()->minimum();
1742             int hmax = view.horizontalScrollBar()->maximum();
1743             int hstep = (hmax - hmin) / 3;
1744             int vmin = view.verticalScrollBar()->minimum();
1745             int vmax = view.verticalScrollBar()->maximum();
1746             int vstep = (vmax - vmin) / 3;
1747
1748             for (int hscrollValue = hmin; hscrollValue < hmax; hscrollValue += hstep) {
1749                 for (int vscrollValue = vmin; vscrollValue < vmax; vscrollValue += vstep) {
1750
1751                     view.horizontalScrollBar()->setValue(hscrollValue);
1752                     view.verticalScrollBar()->setValue(vscrollValue);
1753                     QApplication::processEvents();
1754
1755                     int h = view.horizontalScrollBar()->value();
1756                     int v = view.verticalScrollBar()->value();
1757
1758                     for (int x = 0; x < view.width(); x += step) {
1759                         for (int y = 0; y < view.height(); y += step) {
1760                             QCOMPARE(view.mapToScene(QPoint(x, y)), QPointF(h + x, v + y));
1761                             QCOMPARE(view.mapFromScene(QPointF(h + x, v + y)), QPoint(x, y));
1762                         }
1763                     }
1764                 }
1765             }
1766         }
1767     }
1768 }
1769
1770 void tst_QGraphicsView::mapToScenePoint()
1771 {
1772     QGraphicsScene scene;
1773     QGraphicsView view(&scene);
1774     view.rotate(90);
1775     view.setFixedSize(117, 117);
1776     view.show();
1777     QPoint center = view.viewport()->rect().center();
1778     QCOMPARE(view.mapToScene(center + QPoint(10, 0)),
1779              view.mapToScene(center) + QPointF(0, -10));
1780 }
1781
1782 void tst_QGraphicsView::mapToSceneRect_data()
1783 {
1784     QTest::addColumn<QRect>("viewRect");
1785     QTest::addColumn<QPolygonF>("scenePoly");
1786     QTest::addColumn<qreal>("rotation");
1787
1788     QTest::newRow("nil") << QRect() << QPolygonF() << qreal(0);
1789     QTest::newRow("0, 0, 1, 1") << QRect(0, 0, 1, 1) << QPolygonF(QRectF(0, 0, 1, 1)) << qreal(0);
1790     QTest::newRow("0, 0, 10, 10") << QRect(0, 0, 10, 10) << QPolygonF(QRectF(0, 0, 10, 10)) << qreal(0);
1791     QTest::newRow("nil") << QRect() << QPolygonF() << qreal(90);
1792     QPolygonF p;
1793     p << QPointF(0, 0) << QPointF(0, -1) << QPointF(1, -1) << QPointF(1, 0) << QPointF(0, 0);
1794     QTest::newRow("0, 0, 1, 1") << QRect(0, 0, 1, 1)
1795                                 << p
1796                                 << qreal(90);
1797     p.clear();
1798     p << QPointF(0, 0) << QPointF(0, -10) << QPointF(10, -10) << QPointF(10, 0) << QPointF(0, 0);
1799     QTest::newRow("0, 0, 10, 10") << QRect(0, 0, 10, 10)
1800                                   << p
1801                                   << qreal(90);
1802 }
1803
1804 void tst_QGraphicsView::mapToSceneRect()
1805 {
1806     QFETCH(QRect, viewRect);
1807     QFETCH(QPolygonF, scenePoly);
1808     QFETCH(qreal, rotation);
1809
1810     QGraphicsScene scene(-1000, -1000, 2000, 2000);
1811     scene.addRect(25, -25, 50, 50);
1812     QGraphicsView view(&scene);
1813     view.setFrameStyle(0);
1814     view.setAlignment(Qt::AlignTop | Qt::AlignLeft);
1815     view.setFixedSize(200, 200);
1816     view.setTransformationAnchor(QGraphicsView::NoAnchor);
1817     view.setResizeAnchor(QGraphicsView::NoAnchor);
1818     view.show();
1819
1820     view.rotate(rotation);
1821
1822     QPolygonF poly = view.mapToScene(viewRect);
1823     if (!poly.isEmpty())
1824         poly << poly[0];
1825
1826     QCOMPARE(poly, scenePoly);
1827 }
1828
1829 void tst_QGraphicsView::mapToScenePoly()
1830 {
1831     QGraphicsScene scene;
1832     QGraphicsView view(&scene);
1833     view.translate(100, 100);
1834     view.setFixedSize(117, 117);
1835     view.show();
1836     QPoint center = view.viewport()->rect().center();
1837     QRect rect(center + QPoint(10, 0), QSize(10, 10));
1838
1839     QPolygon poly;
1840     poly << rect.topLeft();
1841     poly << rect.topRight();
1842     poly << rect.bottomRight();
1843     poly << rect.bottomLeft();
1844
1845     QPolygonF poly2;
1846     poly2 << view.mapToScene(rect.topLeft());
1847     poly2 << view.mapToScene(rect.topRight());
1848     poly2 << view.mapToScene(rect.bottomRight());
1849     poly2 << view.mapToScene(rect.bottomLeft());
1850
1851     QCOMPARE(view.mapToScene(poly), poly2);
1852 }
1853
1854 void tst_QGraphicsView::mapToScenePath()
1855 {
1856     QGraphicsScene scene;
1857     QGraphicsView view(&scene);
1858     view.setSceneRect(-300, -300, 600, 600);
1859     view.translate(10, 10);
1860     view.setFixedSize(300, 300);
1861     view.show();
1862     QRect rect(QPoint(10, 0), QSize(10, 10));
1863
1864     QPainterPath path;
1865     path.addRect(rect);
1866
1867     QPainterPath path2;
1868     path2.addRect(rect.translated(view.horizontalScrollBar()->value() - 10,
1869                                   view.verticalScrollBar()->value() - 10));
1870     QCOMPARE(view.mapToScene(path), path2);
1871 }
1872
1873 void tst_QGraphicsView::mapFromScenePoint()
1874 {
1875     {
1876         QGraphicsScene scene;
1877         QGraphicsView view(&scene);
1878         view.rotate(90);
1879         view.scale(10, 10);
1880         view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1881         view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1882         view.show();
1883
1884         QPoint mapped = view.mapFromScene(0, 0);
1885         QPoint center = view.viewport()->rect().center();
1886         if (qAbs(mapped.x() - center.x()) >= 2
1887             || qAbs(mapped.y() - center.y()) >= 2) {
1888             QString error = QString("Compared values are not the same\n\tActual: (%1, %2)\n\tExpected: (%3, %4)")
1889                             .arg(mapped.x()).arg(mapped.y()).arg(center.x()).arg(center.y());
1890             QFAIL(qPrintable(error));
1891         }
1892     }
1893     {
1894         QWidget toplevel;
1895
1896         QGraphicsScene scene(0, 0, 200, 200);
1897         scene.addRect(QRectF(0, 0, 200, 200), QPen(Qt::black, 1));
1898         QGraphicsView view(&scene, &toplevel);
1899         view.ensurePolished();
1900         view.resize(view.sizeHint());
1901         toplevel.show();
1902
1903         QCOMPARE(view.mapFromScene(0, 0), QPoint(0, 0));
1904         QCOMPARE(view.mapFromScene(0.4, 0.4), QPoint(0, 0));
1905         QCOMPARE(view.mapFromScene(0.5, 0.5), QPoint(1, 1));
1906         QCOMPARE(view.mapFromScene(0.9, 0.9), QPoint(1, 1));
1907         QCOMPARE(view.mapFromScene(1.0, 1.0), QPoint(1, 1));
1908         QCOMPARE(view.mapFromScene(100, 100), QPoint(100, 100));
1909         QCOMPARE(view.mapFromScene(100.5, 100.5), QPoint(101, 101));
1910         QCOMPARE(view.mapToScene(0, 0), QPointF(0, 0));
1911         QCOMPARE(view.mapToScene(1, 1), QPointF(1, 1));
1912         QCOMPARE(view.mapToScene(100, 100), QPointF(100, 100));
1913     }
1914 }
1915
1916 void tst_QGraphicsView::mapFromSceneRect()
1917 {
1918     QGraphicsScene scene;
1919     QWidget topLevel;
1920     QGraphicsView view(&scene,&topLevel);
1921     view.rotate(90);
1922     view.setFixedSize(200, 200);
1923     view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1924     view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1925     topLevel.show();
1926     QTest::qWait(25);
1927
1928     QPolygon polygon;
1929     polygon << QPoint(98, 98);
1930     polygon << QPoint(98, 108);
1931     polygon << QPoint(88, 108);
1932     polygon << QPoint(88, 98);
1933
1934
1935     QPolygon viewPolygon = view.mapFromScene(0, 0, 10, 10);
1936     for (int i = 0; i < 4; ++i) {
1937         QVERIFY(qAbs(viewPolygon[i].x() - polygon[i].x()) < 3);
1938         QVERIFY(qAbs(viewPolygon[i].y() - polygon[i].y()) < 3);
1939     }
1940
1941     QPoint pt = view.mapFromScene(QPointF());
1942     QPolygon p;
1943     p << pt << pt << pt << pt;
1944     QCOMPARE(view.mapFromScene(QRectF()), p);
1945 }
1946
1947 void tst_QGraphicsView::mapFromScenePoly()
1948 {
1949     QGraphicsScene scene;
1950     QGraphicsView view(&scene);
1951     view.rotate(90);
1952     view.setFixedSize(200, 200);
1953     view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1954     view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1955     view.show();
1956
1957     QPolygonF polygon;
1958     polygon << QPoint(0, 0);
1959     polygon << QPoint(10, 0);
1960     polygon << QPoint(10, 10);
1961     polygon << QPoint(0, 10);
1962
1963     QPolygon polygon2;
1964     polygon2 << QPoint(98, 98);
1965     polygon2 << QPoint(98, 108);
1966     polygon2 << QPoint(88, 108);
1967     polygon2 << QPoint(88, 98);
1968
1969     QPolygon viewPolygon = view.mapFromScene(polygon);
1970     for (int i = 0; i < 4; ++i) {
1971         QVERIFY(qAbs(viewPolygon[i].x() - polygon2[i].x()) < 3);
1972         QVERIFY(qAbs(viewPolygon[i].y() - polygon2[i].y()) < 3);
1973     }
1974 }
1975
1976 void tst_QGraphicsView::mapFromScenePath()
1977 {
1978     QGraphicsScene scene;
1979     QGraphicsView view(&scene);
1980     view.rotate(90);
1981     view.setFixedSize(200, 200);
1982     view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1983     view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1984     view.show();
1985
1986     QPolygonF polygon;
1987     polygon << QPoint(0, 0);
1988     polygon << QPoint(10, 0);
1989     polygon << QPoint(10, 10);
1990     polygon << QPoint(0, 10);
1991     QPainterPath path;
1992     path.addPolygon(polygon);
1993
1994     QPolygon polygon2;
1995     polygon2 << QPoint(98, 98);
1996     polygon2 << QPoint(98, 108);
1997     polygon2 << QPoint(88, 108);
1998     polygon2 << QPoint(88, 98);
1999     QPainterPath path2;
2000     path2.addPolygon(polygon2);
2001
2002     QPolygonF pathPoly = view.mapFromScene(path).toFillPolygon();
2003     QPolygonF path2Poly = path2.toFillPolygon();
2004
2005     for (int i = 0; i < pathPoly.size(); ++i) {
2006         QVERIFY(qAbs(pathPoly[i].x() - path2Poly[i].x()) < 3);
2007         QVERIFY(qAbs(pathPoly[i].y() - path2Poly[i].y()) < 3);
2008     }
2009 }
2010
2011 void tst_QGraphicsView::sendEvent()
2012 {
2013     QGraphicsScene scene;
2014
2015     TestItem *item = new TestItem;
2016     scene.addItem(item);
2017     item->setFlag(QGraphicsItem::ItemIsFocusable);
2018     item->setFlag(QGraphicsItem::ItemIsMovable);
2019
2020     QGraphicsView view(&scene);
2021     view.show();
2022     QTest::qWaitForWindowShown(&view);
2023     QApplication::setActiveWindow(&view);
2024     QTest::qWait(20);
2025     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2026
2027     item->setFocus();
2028
2029     QCOMPARE(scene.focusItem(), (QGraphicsItem *)item);
2030     QCOMPARE(item->events.size(), 2);
2031     QCOMPARE(item->events.last(), QEvent::FocusIn);
2032
2033     QPoint itemPoint = view.mapFromScene(item->scenePos());
2034     sendMousePress(view.viewport(), itemPoint);
2035     QCOMPARE(item->events.size(), 4);
2036     QCOMPARE(item->events.at(item->events.size() - 2), QEvent::GrabMouse);
2037     QCOMPARE(item->events.at(item->events.size() - 1), QEvent::GraphicsSceneMousePress);
2038
2039     QMouseEvent mouseMoveEvent(QEvent::MouseMove, itemPoint, view.viewport()->mapToGlobal(itemPoint),
2040                                 Qt::LeftButton, Qt::LeftButton, 0);
2041     QApplication::sendEvent(view.viewport(), &mouseMoveEvent);
2042     QCOMPARE(item->events.size(), 5);
2043     QCOMPARE(item->events.last(), QEvent::GraphicsSceneMouseMove);
2044
2045     QMouseEvent mouseReleaseEvent(QEvent::MouseButtonRelease, itemPoint,
2046                                   view.viewport()->mapToGlobal(itemPoint),
2047                                   Qt::LeftButton, 0, 0);
2048     QApplication::sendEvent(view.viewport(), &mouseReleaseEvent);
2049     QCOMPARE(item->events.size(), 7);
2050     QCOMPARE(item->events.at(item->events.size() - 2), QEvent::GraphicsSceneMouseRelease);
2051     QCOMPARE(item->events.at(item->events.size() - 1), QEvent::UngrabMouse);
2052
2053     QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_Space, 0);
2054     QApplication::sendEvent(view.viewport(), &keyPress);
2055     QCOMPARE(item->events.size(), 9);
2056     QCOMPARE(item->events.at(item->events.size() - 2), QEvent::ShortcutOverride);
2057     QCOMPARE(item->events.last(), QEvent::KeyPress);
2058 }
2059
2060 class MouseWheelScene : public QGraphicsScene
2061 {
2062 public:
2063     Qt::Orientation orientation;
2064
2065     void wheelEvent(QGraphicsSceneWheelEvent *event)
2066     {
2067         orientation = event->orientation();
2068         QGraphicsScene::wheelEvent(event);
2069     }
2070 };
2071
2072 void tst_QGraphicsView::wheelEvent()
2073 {
2074     // Create a scene with an invalid orientation.
2075     MouseWheelScene scene;
2076     scene.orientation = Qt::Orientation(-1);
2077
2078     QGraphicsWidget *widget = new QGraphicsWidget;
2079     widget->setGeometry(0, 0, 400, 400);
2080     widget->setFocusPolicy(Qt::WheelFocus);
2081
2082     EventSpy spy(widget, QEvent::GraphicsSceneWheel);
2083     QCOMPARE(spy.count(), 0);
2084
2085     scene.addItem(widget);
2086
2087     // Assign a view.
2088     QGraphicsView view(&scene);
2089     view.show();
2090     QTest::qWaitForWindowShown(&view);
2091     QApplication::setActiveWindow(&view);
2092     QTest::qWait(20);
2093     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2094
2095
2096     // Send a wheel event with horizontal orientation.
2097     {
2098         QWheelEvent event(view.mapFromScene(widget->boundingRect().center()),
2099                           view.mapToGlobal(view.mapFromScene(widget->boundingRect().center())),
2100                           120, 0, 0, Qt::Horizontal);
2101         QApplication::sendEvent(view.viewport(), &event);
2102         QCOMPARE(scene.orientation, Qt::Horizontal);
2103     }
2104
2105     // Send a wheel event with vertical orientation.
2106     {
2107         QWheelEvent event(view.mapFromScene(widget->boundingRect().center()),
2108                           view.mapToGlobal(view.mapFromScene(widget->boundingRect().center())),
2109                           120, 0, 0, Qt::Vertical);
2110         QApplication::sendEvent(view.viewport(), &event);
2111         QCOMPARE(scene.orientation, Qt::Vertical);
2112     }
2113
2114     QCOMPARE(spy.count(), 2);
2115     QVERIFY(widget->hasFocus());
2116 }
2117
2118 void tst_QGraphicsView::cursor()
2119 {
2120 #ifndef QT_NO_CURSOR
2121 #if defined(Q_OS_WINCE)
2122     QSKIP("Qt/CE does not have regular cursor support");
2123 #endif
2124     if (PlatformQuirks::haveMouseCursor())
2125         QSKIP("The Platform does not have regular cursor support");
2126
2127     QGraphicsScene scene;
2128     QGraphicsItem *item = scene.addRect(QRectF(-10, -10, 20, 20));
2129     item->setCursor(Qt::IBeamCursor);
2130
2131     QGraphicsView view(&scene);
2132     view.setFixedSize(400, 400);
2133     view.show();
2134     QTest::qWaitForWindowShown(&view);
2135
2136     QCOMPARE(view.viewport()->cursor().shape(), QCursor().shape());
2137     view.viewport()->setCursor(Qt::PointingHandCursor);
2138     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2139
2140     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2141     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2142
2143     sendMouseMove(view.viewport(), QPoint(5, 5));
2144     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2145 #endif
2146 }
2147
2148 // Qt/CE does not have regular cursor support.
2149 #if !defined(QT_NO_CURSOR) && !defined(Q_OS_WINCE)
2150 void tst_QGraphicsView::cursor2()
2151 {
2152 #ifndef QT_NO_CURSOR
2153 #if defined(Q_OS_WINCE)
2154     QSKIP("Qt/CE does not have regular cursor support");
2155 #endif
2156     if (PlatformQuirks::haveMouseCursor())
2157         QSKIP("The Platform does not have regular cursor support");
2158
2159     QGraphicsScene scene;
2160     QGraphicsItem *item = scene.addRect(QRectF(-10, -10, 20, 20));
2161     item->setCursor(Qt::IBeamCursor);
2162     item->setZValue(1);
2163
2164     QGraphicsItem *item2 = scene.addRect(QRectF(-20, -20, 40, 40));
2165     item2->setZValue(0);
2166
2167     QGraphicsView view(&scene);
2168     view.viewport()->setCursor(Qt::PointingHandCursor);
2169     view.setFixedSize(400, 400);
2170     view.show();
2171     QTest::qWaitForWindowShown(&view);
2172
2173     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2174     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2175     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2176     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2177     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2178     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2179     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2180     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2181     sendMouseMove(view.viewport(), view.mapFromScene(-15, 0));
2182     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2183
2184     view.setDragMode(QGraphicsView::ScrollHandDrag);
2185
2186     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2187     QCOMPARE(view.viewport()->cursor().shape(), Qt::OpenHandCursor);
2188     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2189     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2190     sendMouseMove(view.viewport(), view.mapFromScene(-15, -15));
2191     QCOMPARE(view.viewport()->cursor().shape(), Qt::OpenHandCursor);
2192
2193     view.setDragMode(QGraphicsView::NoDrag);
2194     QCOMPARE(view.viewport()->cursor().shape(), Qt::ArrowCursor);
2195     view.viewport()->setCursor(Qt::PointingHandCursor);
2196     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2197
2198     item2->setCursor(Qt::SizeAllCursor);
2199
2200     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2201     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2202     sendMouseMove(view.viewport(), view.mapFromScene(-15, -15));
2203     QCOMPARE(view.viewport()->cursor().shape(), Qt::SizeAllCursor);
2204     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2205     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2206     sendMouseMove(view.viewport(), view.mapFromScene(-15, -15));
2207     QCOMPARE(view.viewport()->cursor().shape(), Qt::SizeAllCursor);
2208     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2209     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2210     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2211     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
2212
2213     view.setDragMode(QGraphicsView::ScrollHandDrag);
2214
2215     sendMouseMove(view.viewport(), view.mapFromScene(-30, -30));
2216     QCOMPARE(view.viewport()->cursor().shape(), Qt::OpenHandCursor);
2217     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
2218     QCOMPARE(view.viewport()->cursor().shape(), Qt::IBeamCursor);
2219     sendMouseMove(view.viewport(), view.mapFromScene(-15, -15));
2220     QCOMPARE(view.viewport()->cursor().shape(), Qt::SizeAllCursor);
2221 #endif
2222 }
2223
2224 void tst_QGraphicsView::transformationAnchor()
2225 {
2226     QGraphicsScene scene(-1000, -1000, 2000, 2000);
2227     scene.addRect(QRectF(-50, -50, 100, 100), QPen(Qt::black), QBrush(Qt::blue));
2228
2229     QGraphicsView view(&scene);
2230
2231     for (int i = 0; i < 2; ++i) {
2232         view.resize(100, 100);
2233         view.show();
2234
2235         if (i == 0) {
2236             QCOMPARE(view.transformationAnchor(), QGraphicsView::AnchorViewCenter);
2237         } else {
2238             view.setTransformationAnchor(QGraphicsView::NoAnchor);
2239         }
2240         view.centerOn(0, 0);
2241         view.horizontalScrollBar()->setValue(100);
2242         QApplication::processEvents();
2243
2244         QPointF center = view.mapToScene(view.viewport()->rect().center());
2245
2246         view.scale(10, 10);
2247
2248         QPointF newCenter = view.mapToScene(view.viewport()->rect().center());
2249
2250         if (i == 0) {
2251             qreal slack = 3;
2252             QVERIFY(qAbs(newCenter.x() - center.x()) < slack);
2253             QVERIFY(qAbs(newCenter.y() - center.y()) < slack);
2254         } else {
2255             qreal slack = qreal(0.3);
2256             QVERIFY(qAbs(newCenter.x() - center.x() / 10) < slack);
2257             QVERIFY(qAbs(newCenter.y() - center.y() / 10) < slack);
2258         }
2259     }
2260 }
2261
2262 void tst_QGraphicsView::resizeAnchor()
2263 {
2264     QGraphicsScene scene(-1000, -1000, 2000, 2000);
2265     scene.addRect(QRectF(-50, -50, 100, 100), QPen(Qt::black), QBrush(Qt::blue));
2266
2267     QGraphicsView view(&scene);
2268
2269     for (int i = 0; i < 2; ++i) {
2270         view.resize(100, 100);
2271         view.show();
2272         QTest::qWaitForWindowShown(&view);
2273         QApplication::processEvents();
2274
2275         if (i == 0) {
2276             QCOMPARE(view.resizeAnchor(), QGraphicsView::NoAnchor);
2277         } else {
2278             view.setResizeAnchor(QGraphicsView::AnchorViewCenter);
2279         }
2280         view.centerOn(0, 0);
2281         QTest::qWait(25);
2282
2283         QPointF f = view.mapToScene(50, 50);
2284         QPointF center = view.mapToScene(view.viewport()->rect().center());
2285
2286         QApplication::processEvents();
2287
2288         for (int size = 200; size <= 400; size += 25) {
2289             view.resize(size, size);
2290             if (i == 0) {
2291                 QTRY_COMPARE(view.mapToScene(50, 50), f);
2292                 QTRY_VERIFY(view.mapToScene(view.viewport()->rect().center()) != center);
2293             } else {
2294                 QTRY_VERIFY(view.mapToScene(50, 50) != f);
2295
2296                 QPointF newCenter = view.mapToScene(view.viewport()->rect().center());
2297                 int slack = 3;
2298                 QVERIFY(qAbs(newCenter.x() - center.x()) < slack);
2299                 QVERIFY(qAbs(newCenter.y() - center.y()) < slack);
2300             }
2301             QApplication::processEvents();
2302         }
2303     }
2304 }
2305
2306 class CustomView : public QGraphicsView
2307 {
2308     Q_OBJECT
2309 public:
2310     CustomView(QGraphicsScene *s = 0) : QGraphicsView(s) {}
2311     CustomView(QGraphicsScene *s, QWidget *parent)
2312         : QGraphicsView(s, parent) {}
2313     QList<QRegion> lastUpdateRegions;
2314     bool painted;
2315
2316 protected:
2317     void paintEvent(QPaintEvent *event)
2318     {
2319         lastUpdateRegions << event->region();
2320         painted = true;
2321         QGraphicsView::paintEvent(event);
2322     }
2323 };
2324
2325 void tst_QGraphicsView::viewportUpdateMode()
2326 {
2327     QGraphicsScene scene(0, 0, 100, 100);
2328     scene.setBackgroundBrush(Qt::red);
2329
2330     CustomView view;
2331     QDesktopWidget desktop;
2332     view.setFixedSize(QSize(500, 500).boundedTo(desktop.availableGeometry().size())); // 500 is too big for all common smartphones
2333     view.setScene(&scene);
2334     if(PlatformQuirks::isAutoMaximizing())
2335         view.setWindowFlags(view.windowFlags()|Qt::X11BypassWindowManagerHint);
2336     QCOMPARE(view.viewportUpdateMode(), QGraphicsView::MinimalViewportUpdate);
2337
2338     // Show the view, and initialize our test.
2339     view.show();
2340     QTest::qWaitForWindowShown(&view);
2341     QTRY_VERIFY(!view.lastUpdateRegions.isEmpty());
2342     view.lastUpdateRegions.clear();
2343
2344     // Issue two scene updates.
2345     scene.update(QRectF(0, 0, 10, 10));
2346     scene.update(QRectF(20, 0, 10, 10));
2347     QTest::qWait(50);
2348
2349     // The view gets two updates for the update scene updates.
2350     QTRY_VERIFY(!view.lastUpdateRegions.isEmpty());
2351 #ifndef Q_OS_MAC //cocoa doesn't support drawing regions
2352     QCOMPARE(view.lastUpdateRegions.last().rects().size(), 2);
2353     QCOMPARE(view.lastUpdateRegions.last().rects().at(0).size(), QSize(14, 14));
2354     QCOMPARE(view.lastUpdateRegions.last().rects().at(1).size(), QSize(14, 14));
2355 #endif
2356
2357     // Set full update mode.
2358     view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
2359     QCOMPARE(view.viewportUpdateMode(), QGraphicsView::FullViewportUpdate);
2360     view.lastUpdateRegions.clear();
2361
2362     // Issue two scene updates.
2363     scene.update(QRectF(0, 0, 10, 10));
2364     scene.update(QRectF(20, 0, 10, 10));
2365     qApp->processEvents();
2366     qApp->processEvents();
2367
2368     // The view gets one full viewport update for the update scene updates.
2369     QCOMPARE(view.lastUpdateRegions.last().rects().size(), 1);
2370     QCOMPARE(view.lastUpdateRegions.last().rects().at(0).size(), view.viewport()->size());
2371     view.lastUpdateRegions.clear();
2372
2373     // Set smart update mode
2374     view.setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
2375     QCOMPARE(view.viewportUpdateMode(), QGraphicsView::SmartViewportUpdate);
2376
2377     // Issue 100 mini-updates
2378     for (int i = 0; i < 10; ++i) {
2379         for (int j = 0; j < 10; ++j) {
2380             scene.update(QRectF(i * 3, j * 3, 1, 1));
2381         }
2382     }
2383     qApp->processEvents();
2384     qApp->processEvents();
2385
2386     // The view gets one bounding rect update.
2387     QCOMPARE(view.lastUpdateRegions.last().rects().size(), 1);
2388     QCOMPARE(view.lastUpdateRegions.last().rects().at(0).size(), QSize(32, 32));
2389
2390     // Set no update mode
2391     view.setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
2392     QCOMPARE(view.viewportUpdateMode(), QGraphicsView::NoViewportUpdate);
2393
2394     // Issue two scene updates.
2395     view.lastUpdateRegions.clear();
2396     TestItem item;
2397     scene.addItem(&item);
2398     item.moveBy(10, 10);
2399     scene.update(QRectF(0, 0, 10, 10));
2400     scene.update(QRectF(20, 0, 10, 10));
2401     qApp->processEvents();
2402     qApp->processEvents();
2403
2404     // The view should not get any painting calls from the scene updates
2405     QCOMPARE(view.lastUpdateRegions.size(), 0);
2406 }
2407
2408 void tst_QGraphicsView::viewportUpdateMode2()
2409 {
2410     QWidget toplevel;
2411
2412     // Create a view with viewport rect equal to QRect(0, 0, 200, 200).
2413     QGraphicsScene dummyScene;
2414     CustomView view(0, &toplevel);
2415     view.painted = false;
2416     view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
2417     view.setScene(&dummyScene);
2418     view.ensurePolished(); // make sure we get the right content margins
2419     int left, top, right, bottom;
2420     view.getContentsMargins(&left, &top, &right, &bottom);
2421     view.resize(200 + left + right, 200 + top + bottom);
2422     toplevel.show();
2423     QTest::qWaitForWindowShown(&toplevel);
2424     QTest::qWait(50);
2425     QTRY_VERIFY(view.painted);
2426     const QRect viewportRect = view.viewport()->rect();
2427     QCOMPARE(viewportRect, QRect(0, 0, 200, 200));
2428
2429 #if defined QT_BUILD_INTERNAL
2430     QGraphicsViewPrivate *viewPrivate = static_cast<QGraphicsViewPrivate *>(qt_widget_private(&view));
2431
2432     QRect boundingRect;
2433     const QRect rect1(0, 0, 10, 10);
2434     QVERIFY(viewPrivate->updateRect(rect1));
2435     QVERIFY(!viewPrivate->fullUpdatePending);
2436     boundingRect |= rect1;
2437     QCOMPARE(viewPrivate->dirtyBoundingRect, boundingRect);
2438
2439     const QRect rect2(50, 50, 10, 10);
2440     QVERIFY(viewPrivate->updateRect(rect2));
2441     QVERIFY(!viewPrivate->fullUpdatePending);
2442     boundingRect |= rect2;
2443     QCOMPARE(viewPrivate->dirtyBoundingRect, boundingRect);
2444
2445     const QRect rect3(190, 190, 10, 10);
2446     QVERIFY(viewPrivate->updateRect(rect3));
2447     QVERIFY(viewPrivate->fullUpdatePending);
2448     boundingRect |= rect3;
2449     QCOMPARE(viewPrivate->dirtyBoundingRect, boundingRect);
2450
2451     view.lastUpdateRegions.clear();
2452     viewPrivate->processPendingUpdates();
2453     QTest::qWait(50);
2454     QCOMPARE(view.lastUpdateRegions.size(), 1);
2455     // Note that we adjust by 2 for antialiasing.
2456     QCOMPARE(view.lastUpdateRegions.at(0), QRegion(boundingRect.adjusted(-2, -2, 2, 2) & viewportRect));
2457 #endif
2458 }
2459
2460 #ifndef QT_NO_DRAGANDDROP
2461 void tst_QGraphicsView::acceptDrops()
2462 {
2463     QGraphicsView view;
2464
2465     // Excepted default behavior.
2466     QVERIFY(view.acceptDrops());
2467     QVERIFY(view.viewport()->acceptDrops());
2468
2469     // Excepted behavior with no drops.
2470     view.setAcceptDrops(false);
2471     QVERIFY(!view.acceptDrops());
2472     QVERIFY(!view.viewport()->acceptDrops());
2473
2474     // Setting a widget with drops on a QGraphicsView without drops.
2475     QWidget *widget = new QWidget;
2476     widget->setAcceptDrops(true);
2477     view.setViewport(widget);
2478     QVERIFY(!view.acceptDrops());
2479     QVERIFY(!view.viewport()->acceptDrops());
2480
2481     // Switching the view to accept drops.
2482     view.setAcceptDrops(true);
2483     QVERIFY(view.acceptDrops());
2484     QVERIFY(view.viewport()->acceptDrops());
2485
2486     // Setting a widget with no drops on a QGraphicsView with drops.
2487     widget = new QWidget;
2488     widget->setAcceptDrops(false);
2489     view.setViewport(widget);
2490     QVERIFY(view.viewport()->acceptDrops());
2491     QVERIFY(view.acceptDrops());
2492
2493     // Switching the view to not accept drops.
2494     view.setAcceptDrops(false);
2495     QVERIFY(!view.viewport()->acceptDrops());
2496 }
2497 #endif
2498
2499 void tst_QGraphicsView::optimizationFlags()
2500 {
2501     QGraphicsView view;
2502     QVERIFY(!view.optimizationFlags());
2503
2504     view.setOptimizationFlag(QGraphicsView::DontClipPainter);
2505     QVERIFY(view.optimizationFlags() & QGraphicsView::DontClipPainter);
2506     view.setOptimizationFlag(QGraphicsView::DontClipPainter, false);
2507     QVERIFY(!view.optimizationFlags());
2508
2509     view.setOptimizationFlag(QGraphicsView::DontSavePainterState);
2510     QVERIFY(view.optimizationFlags() & QGraphicsView::DontSavePainterState);
2511     view.setOptimizationFlag(QGraphicsView::DontSavePainterState, false);
2512     QVERIFY(!view.optimizationFlags());
2513
2514     view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing);
2515     QVERIFY(view.optimizationFlags() & QGraphicsView::DontAdjustForAntialiasing);
2516     view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, false);
2517     QVERIFY(!view.optimizationFlags());
2518
2519     view.setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing
2520                               | QGraphicsView::DontClipPainter);
2521     QCOMPARE(view.optimizationFlags(), QGraphicsView::OptimizationFlags(QGraphicsView::DontAdjustForAntialiasing
2522              | QGraphicsView::DontClipPainter));
2523 }
2524
2525 class MessUpPainterItem : public QGraphicsRectItem
2526 {
2527 public:
2528     MessUpPainterItem(const QRectF &rect) : QGraphicsRectItem(rect), dirtyPainter(false)
2529     { }
2530
2531     bool dirtyPainter;
2532
2533     void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
2534     {
2535         dirtyPainter = (painter->pen().width() != 0);
2536         painter->setPen(QPen(Qt::black, 1.0));
2537     }
2538 };
2539
2540 class MyGraphicsView : public QGraphicsView
2541 {
2542 public:
2543       MyGraphicsView(QGraphicsScene * scene) : QGraphicsView(scene)
2544       { }
2545
2546       void drawBackground(QPainter * painter, const QRectF & rect) {
2547           painter->setCompositionMode(QPainter::CompositionMode_Source);
2548           painter->drawRect(rect);
2549       }
2550
2551       void drawItems (QPainter * painter, int numItems, QGraphicsItem *items[], const QStyleOptionGraphicsItem options[]) {
2552            if (!(optimizationFlags() & QGraphicsView::DontSavePainterState))
2553                QCOMPARE(painter->compositionMode(),QPainter::CompositionMode_SourceOver);
2554            else
2555                QCOMPARE(painter->compositionMode(),QPainter::CompositionMode_Source);
2556            QGraphicsView::drawItems(painter,numItems,items,options);
2557       }
2558 };
2559
2560 void tst_QGraphicsView::optimizationFlags_dontSavePainterState()
2561 {
2562     MessUpPainterItem *parent = new MessUpPainterItem(QRectF(0, 0, 100, 100));
2563     MessUpPainterItem *child = new MessUpPainterItem(QRectF(0, 0, 100, 100));
2564     child->setParentItem(parent);
2565
2566     QGraphicsScene scene;
2567     scene.addItem(parent);
2568
2569     QGraphicsView view(&scene);
2570     view.show();
2571     QTest::qWaitForWindowShown(&view);
2572     view.viewport()->repaint();
2573
2574     QVERIFY(!parent->dirtyPainter);
2575     QVERIFY(!child->dirtyPainter);
2576
2577     view.setOptimizationFlags(QGraphicsView::DontSavePainterState);
2578     view.viewport()->repaint();
2579
2580 #ifdef Q_OS_MAC
2581     // Repaint on Mac OS X actually does require spinning the event loop.
2582     QTest::qWait(100);
2583 #endif
2584     QVERIFY(!parent->dirtyPainter);
2585     QVERIFY(child->dirtyPainter);
2586
2587     MyGraphicsView painter(&scene);
2588     painter.show();
2589     QTest::qWaitForWindowShown(&painter);
2590
2591     MyGraphicsView painter2(&scene);
2592     painter2.setOptimizationFlag(QGraphicsView::DontSavePainterState,true);
2593     painter2.show();
2594     QTest::qWaitForWindowShown(&painter2);
2595 }
2596
2597 void tst_QGraphicsView::optimizationFlags_dontSavePainterState2_data()
2598 {
2599     QTest::addColumn<bool>("savePainter");
2600     QTest::addColumn<bool>("indirectPainting");
2601     QTest::newRow("With painter state protection, without indirect painting") << true << false;
2602     QTest::newRow("Without painter state protection, without indirect painting") << false << false;
2603     QTest::newRow("With painter state protectionm, with indirect painting") << true << true;
2604     QTest::newRow("Without painter state protection, with indirect painting") << false << true;
2605 }
2606
2607 void tst_QGraphicsView::optimizationFlags_dontSavePainterState2()
2608 {
2609     QFETCH(bool, savePainter);
2610     QFETCH(bool, indirectPainting);
2611
2612     class MyScene : public QGraphicsScene
2613     {
2614     public:
2615         void drawBackground(QPainter *p, const QRectF &)
2616         { transformInDrawBackground = p->worldTransform(); opacityInDrawBackground = p->opacity(); }
2617
2618         void drawForeground(QPainter *p, const QRectF &)
2619         { transformInDrawForeground = p->worldTransform(); opacityInDrawForeground = p->opacity(); }
2620
2621         QTransform transformInDrawBackground;
2622         QTransform transformInDrawForeground;
2623         qreal opacityInDrawBackground;
2624         qreal opacityInDrawForeground;
2625     };
2626
2627     MyScene scene;
2628     // Add transformed dummy items to make sure the painter's worldTransform() is changed in drawItems.
2629     scene.addRect(0, 0, 20, 20)->setTransform(QTransform::fromScale(2, 2));
2630     scene.addRect(50, 50, 20, 20)->setTransform(QTransform::fromTranslate(200, 200));
2631
2632     foreach (QGraphicsItem *item, scene.items())
2633         item->setOpacity(0.6);
2634
2635     CustomView view(&scene);
2636     if (!savePainter)
2637         view.setOptimizationFlag(QGraphicsView::DontSavePainterState);
2638     view.setOptimizationFlag(QGraphicsView::IndirectPainting, indirectPainting);
2639     view.rotate(45);
2640     view.scale(1.5, 1.5);
2641     view.show();
2642 #ifdef Q_WS_X11
2643     qt_x11_wait_for_window_manager(&view);
2644 #endif
2645
2646     // Make sure the view is repainted; otherwise the tests below will fail.
2647     view.viewport()->repaint();
2648     QTest::qWait(200);
2649     QVERIFY(view.painted);
2650
2651     // Make sure the painter's world transform is preserved after drawItems.
2652     QTransform expectedTransform = view.viewportTransform();
2653     QVERIFY(!expectedTransform.isIdentity());
2654     QCOMPARE(scene.transformInDrawForeground, expectedTransform);
2655     QCOMPARE(scene.transformInDrawBackground, expectedTransform);
2656
2657     qreal expectedOpacity = 1.0;
2658     QCOMPARE(scene.opacityInDrawBackground, expectedOpacity);
2659     QCOMPARE(scene.opacityInDrawForeground, expectedOpacity);
2660
2661     // Trigger more painting, this time from QGraphicsScene::render.
2662     QImage image(scene.sceneRect().size().toSize(), QImage::Format_RGB32);
2663     QPainter painter(&image);
2664     scene.render(&painter);
2665     painter.end();
2666
2667     expectedTransform = QTransform();
2668     QCOMPARE(scene.transformInDrawForeground, expectedTransform);
2669     QCOMPARE(scene.transformInDrawBackground, expectedTransform);
2670     QCOMPARE(scene.opacityInDrawBackground, expectedOpacity);
2671     QCOMPARE(scene.opacityInDrawForeground, expectedOpacity);
2672
2673     // Trigger more painting with another opacity on the painter.
2674     painter.begin(&image);
2675     painter.setOpacity(0.4);
2676     expectedOpacity = 0.4;
2677     scene.render(&painter);
2678     painter.end();
2679
2680     QCOMPARE(scene.transformInDrawForeground, expectedTransform);
2681     QCOMPARE(scene.transformInDrawBackground, expectedTransform);
2682     QCOMPARE(scene.opacityInDrawBackground, expectedOpacity);
2683     QCOMPARE(scene.opacityInDrawForeground, expectedOpacity);
2684 }
2685
2686 class LodItem : public QGraphicsRectItem
2687 {
2688 public:
2689     LodItem(const QRectF &rect) : QGraphicsRectItem(rect), lastLod(-42)
2690     { }
2691
2692     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *viewport)
2693     {
2694         lastLod = option->levelOfDetailFromTransform(painter->worldTransform());
2695         QGraphicsRectItem::paint(painter, option, viewport);
2696     }
2697
2698     qreal lastLod;
2699 };
2700
2701 void tst_QGraphicsView::levelOfDetail_data()
2702 {
2703     QTest::addColumn<QTransform>("transform");
2704     QTest::addColumn<qreal>("lod");
2705
2706     QTest::newRow("1:4, 1:4") << QTransform().scale(0.25, 0.25) << qreal(0.25);
2707     QTest::newRow("1:2, 1:4") << QTransform().scale(0.5, 0.25) << qreal(::sqrt(0.125));
2708     QTest::newRow("4:1, 1:2") << QTransform().scale(0.25, 0.5) << qreal(::sqrt(0.125));
2709
2710     QTest::newRow("1:2, 1:2") << QTransform().scale(0.5, 0.5) << qreal(0.5);
2711     QTest::newRow("1:1, 1:2") << QTransform().scale(1, 0.5) << qreal(::sqrt(0.5));
2712     QTest::newRow("2:1, 1:1") << QTransform().scale(0.5, 1) << qreal(::sqrt(0.5));
2713
2714     QTest::newRow("1:1, 1:1") << QTransform().scale(1, 1) << qreal(1.0);
2715     QTest::newRow("2:1, 1:1") << QTransform().scale(2, 1) << qreal(::sqrt(2.0));
2716     QTest::newRow("1:1, 2:1") << QTransform().scale(2, 1) << qreal(::sqrt(2.0));
2717     QTest::newRow("2:1, 2:1") << QTransform().scale(2, 2) << qreal(2.0);
2718     QTest::newRow("2:1, 4:1") << QTransform().scale(2, 4) << qreal(::sqrt(8.0));
2719     QTest::newRow("4:1, 2:1") << QTransform().scale(4, 2) << qreal(::sqrt(8.0));
2720     QTest::newRow("4:1, 4:1") << QTransform().scale(4, 4) << qreal(4.0);
2721 }
2722
2723 void tst_QGraphicsView::levelOfDetail()
2724 {
2725     QFETCH(QTransform, transform);
2726     QFETCH(qreal, lod);
2727
2728     LodItem *item = new LodItem(QRectF(0, 0, 100, 100));
2729
2730     QGraphicsScene scene;
2731     scene.addItem(item);
2732
2733     QGraphicsView view(&scene);
2734     view.show();
2735     QTest::qWaitForWindowShown(&view);
2736
2737     QTRY_COMPARE(item->lastLod, qreal(1));
2738
2739     view.setTransform(transform);
2740
2741     QTRY_COMPARE(item->lastLod, lod);
2742 }
2743
2744 // Moved to tst_qgraphicsview_2.cpp
2745 extern void _scrollBarRanges_data();
2746
2747 void tst_QGraphicsView::scrollBarRanges_data()
2748 {
2749     _scrollBarRanges_data();
2750 }
2751
2752 void tst_QGraphicsView::scrollBarRanges()
2753 {
2754     QFETCH(QSize, viewportSize);
2755     QFETCH(QRectF, sceneRect);
2756     QFETCH(QTransform, transform);
2757     QFETCH(Qt::ScrollBarPolicy, hbarpolicy);
2758     QFETCH(Qt::ScrollBarPolicy, vbarpolicy);
2759     QFETCH(int, hmin);
2760     QFETCH(int, hmax);
2761     QFETCH(int, vmin);
2762     QFETCH(int, vmax);
2763     QFETCH(bool, useMotif);
2764     QFETCH(bool, useStyledPanel);
2765
2766     QGraphicsScene scene(sceneRect);
2767     scene.addRect(sceneRect, QPen(Qt::blue), QBrush(QColor(Qt::green)));
2768     QGraphicsView view(&scene);
2769     view.setRenderHint(QPainter::Antialiasing);
2770     view.setTransform(transform);
2771     view.setFrameStyle(useStyledPanel ? QFrame::StyledPanel : QFrame::NoFrame);
2772
2773     if (useMotif) {
2774 #if !defined(QT_NO_STYLE_MOTIF)
2775         view.setStyle(new QMotifStyle);
2776 #else
2777         QSKIP("No Motif style compiled.");
2778 #endif
2779     } else {
2780 #if defined(Q_OS_WINCE)
2781         view.setStyle(new QWindowsStyle);
2782 #elif !defined(QT_NO_STYLE_PLASTIQUE)
2783         view.setStyle(new QPlastiqueStyle);
2784 #endif
2785     }
2786     view.setStyleSheet(" "); // enables style propagation ;-)
2787
2788     int adjust = 0;
2789     if (useStyledPanel)
2790         adjust = view.style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2;
2791     view.resize(viewportSize + QSize(adjust, adjust));
2792
2793     view.setHorizontalScrollBarPolicy(hbarpolicy);
2794     view.setVerticalScrollBarPolicy(vbarpolicy);
2795
2796     view.show();
2797
2798     QCOMPARE(view.horizontalScrollBar()->minimum(), hmin);
2799     QCOMPARE(view.verticalScrollBar()->minimum(), vmin);
2800     QCOMPARE(view.horizontalScrollBar()->maximum(), hmax);
2801     QCOMPARE(view.verticalScrollBar()->maximum(), vmax);
2802 }
2803
2804 class TestView : public QGraphicsView
2805 {
2806 public:
2807     TestView(QGraphicsScene *scene)
2808         : QGraphicsView(scene), accepted(false)
2809     { }
2810
2811     bool accepted;
2812
2813 protected:
2814     void mousePressEvent(QMouseEvent *event)
2815     {
2816         QGraphicsView::mousePressEvent(event);
2817         accepted = event->isAccepted();
2818     }
2819 };
2820
2821 void tst_QGraphicsView::acceptMousePressEvent()
2822 {
2823     QGraphicsScene scene;
2824
2825     TestView view(&scene);
2826     view.show();
2827     QTest::qWaitForWindowShown(&view);
2828
2829     QMouseEvent event(QEvent::MouseButtonPress,
2830                       view.viewport()->rect().center(),
2831                       view.viewport()->mapToGlobal(view.viewport()->rect().center()),
2832                       Qt::LeftButton, 0, 0);
2833     event.setAccepted(false);
2834     QApplication::sendEvent(view.viewport(), &event);
2835     QVERIFY(!view.accepted);
2836
2837     scene.addRect(0, 0, 2000, 2000)->setFlag(QGraphicsItem::ItemIsMovable);
2838
2839     qApp->processEvents(); // ensure scene rect is updated
2840
2841     QApplication::sendEvent(view.viewport(), &event);
2842     QVERIFY(view.accepted);
2843 }
2844
2845 void tst_QGraphicsView::replayMouseMove()
2846 {
2847     // An empty scene in a view. The view will send the events to the scene in
2848     // any case. Note that the view doesn't have to be shown - the mouse event
2849     // sending functions below send the events directly to the viewport.
2850     QGraphicsScene scene(-10000, -10000, 20000, 20000);
2851     QGraphicsView view(&scene);
2852
2853     EventSpy sceneSpy(&scene, QEvent::GraphicsSceneMouseMove);
2854     EventSpy viewSpy(view.viewport(), QEvent::MouseMove);
2855
2856     sendMousePress(view.viewport(), view.viewport()->rect().center());
2857
2858     // One mouse event should be translated into one scene event.
2859     for (int i = 0; i < 3; ++i) {
2860         sendMouseMove(view.viewport(), view.viewport()->rect().center(),
2861                       Qt::LeftButton, Qt::MouseButtons(Qt::LeftButton));
2862         QCOMPARE(viewSpy.count(), i + 1);
2863         QCOMPARE(sceneSpy.count(), i + 1);
2864     }
2865
2866     // When the view is transformed, the view should get no more events.  But
2867     // the scene should get replays.
2868     for (int i = 0; i < 3; ++i) {
2869         view.rotate(10);
2870         QCOMPARE(viewSpy.count(), 3);
2871         QCOMPARE(sceneSpy.count(), 3 + i + 1);
2872     }
2873
2874     // When the view is scrolled, the view should get no more events.  But the
2875     // scene should get replays.
2876     for (int i = 0; i < 3; ++i) {
2877         view.horizontalScrollBar()->setValue((i + 1) * 10);
2878         QCOMPARE(viewSpy.count(), 3);
2879         QCOMPARE(sceneSpy.count(), 6 + i + 1);
2880     }
2881 }
2882
2883 void tst_QGraphicsView::itemsUnderMouse()
2884 {
2885    QGraphicsScene scene;
2886    QGraphicsProxyWidget w;
2887    w.setWidget(new QPushButton("W"));
2888    w.resize(50,50);
2889    QGraphicsProxyWidget w2(&w);
2890    w2.setWidget(new QPushButton("W2"));
2891    w2.resize(50,50);
2892    QGraphicsProxyWidget w3(&w2);
2893    w3.setWidget(new QPushButton("W3"));
2894    w3.resize(50,50);
2895    w.setZValue(150);
2896    w2.setZValue(50);
2897    w3.setZValue(0);
2898    scene.addItem(&w);
2899
2900    QGraphicsView view(&scene);
2901    view.show();
2902    QTest::qWaitForWindowShown(&view);
2903
2904    QCOMPARE(view.items(view.mapFromScene(w3.boundingRect().center())).first(),
2905             static_cast<QGraphicsItem *>(&w3));
2906    w2.setFlag(QGraphicsItem::ItemIgnoresTransformations, true);
2907    QCOMPARE(view.items(view.mapFromScene(w3.boundingRect().center())).first(),
2908             static_cast<QGraphicsItem *>(&w3));
2909 }
2910
2911 class QGraphicsTextItem_task172231 : public QGraphicsTextItem
2912 {
2913 public:
2914     QGraphicsTextItem_task172231(const QString & text, QGraphicsItem * parent = 0)
2915         : QGraphicsTextItem(text, parent) {}
2916     QRectF exposedRect;
2917     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
2918     {
2919         exposedRect = option->exposedRect;
2920         QGraphicsTextItem::paint(painter, option, widget);
2921     }
2922 };
2923
2924 void tst_QGraphicsView::task172231_untransformableItems()
2925 {
2926     // check fix in QGraphicsView::paintEvent()
2927
2928     QGraphicsScene scene;
2929
2930     QGraphicsTextItem_task172231 *text =
2931         new QGraphicsTextItem_task172231("abcdefghijklmnopqrstuvwxyz");
2932     text->setFlag(QGraphicsItem::ItemIgnoresTransformations);
2933     scene.addItem(text);
2934
2935     QGraphicsView view(&scene);
2936
2937     view.scale(2, 1);
2938     view.show();
2939     QTest::qWaitForWindowShown(&view);
2940     QApplication::setActiveWindow(&view);
2941     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
2942
2943     QRectF origExposedRect = text->exposedRect;
2944
2945     view.resize(int(0.75 * view.width()), view.height());
2946     qApp->processEvents();
2947
2948     QCOMPARE(text->exposedRect, origExposedRect);
2949
2950     // notice that the fix also goes into QGraphicsView::render()
2951     // and QGraphicsScene::render(), but in duplicated code that
2952     // is pending a refactoring, so for now we omit autotesting
2953     // these functions separately
2954 }
2955
2956 class MousePressReleaseScene : public QGraphicsScene
2957 {
2958 public:
2959     MousePressReleaseScene()
2960         : presses(0), releases(0)
2961     { }
2962     int presses;
2963     int releases;
2964
2965 protected:
2966     void mousePressEvent(QGraphicsSceneMouseEvent *event)
2967     { ++presses; QGraphicsScene::mousePressEvent(event); }
2968     void mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
2969     { ++releases; QGraphicsScene::mouseReleaseEvent(event); }
2970 };
2971
2972 void tst_QGraphicsView::task180429_mouseReleaseDragMode()
2973 {
2974     MousePressReleaseScene scene;
2975
2976     QGraphicsView view(&scene);
2977     view.show();
2978
2979     sendMousePress(view.viewport(), view.viewport()->rect().center());
2980     QCOMPARE(scene.presses, 1);
2981     QCOMPARE(scene.releases, 0);
2982     sendMouseRelease(view.viewport(), view.viewport()->rect().center());
2983     QCOMPARE(scene.presses, 1);
2984     QCOMPARE(scene.releases, 1);
2985
2986     view.setDragMode(QGraphicsView::RubberBandDrag);
2987     sendMousePress(view.viewport(), view.viewport()->rect().center());
2988     QCOMPARE(scene.presses, 2);
2989     QCOMPARE(scene.releases, 1);
2990     sendMouseRelease(view.viewport(), view.viewport()->rect().center());
2991     QCOMPARE(scene.presses, 2);
2992     QCOMPARE(scene.releases, 2);
2993 }
2994
2995 void tst_QGraphicsView::task187791_setSceneCausesUpdate()
2996 {
2997     QGraphicsScene scene(0, 0, 200, 200);
2998     QGraphicsView view(&scene);
2999     view.show();
3000     QTest::qWaitForWindowShown(&view);
3001
3002     EventSpy updateSpy(view.viewport(), QEvent::Paint);
3003     QCOMPARE(updateSpy.count(), 0);
3004
3005     view.setScene(0);
3006     QApplication::processEvents();
3007     QTRY_COMPARE(updateSpy.count(), 1);
3008     view.setScene(&scene);
3009     QApplication::processEvents();
3010     QTRY_COMPARE(updateSpy.count(), 2);
3011 }
3012
3013 class MouseMoveCounter : public QGraphicsView
3014 {
3015 public:
3016     MouseMoveCounter() : mouseMoves(0)
3017     { }
3018     int mouseMoves;
3019 protected:
3020     void mouseMoveEvent(QMouseEvent *event)
3021     {
3022         ++mouseMoves;
3023         QGraphicsView::mouseMoveEvent(event);
3024         foreach (QGraphicsItem *item, scene()->items()) {
3025             scene()->removeItem(item);
3026             delete item;
3027         }
3028         scene()->addRect(0, 0, 50, 50);
3029         scene()->addRect(0, 0, 100, 100);
3030     }
3031 };
3032
3033 void tst_QGraphicsView::task186827_deleteReplayedItem()
3034 {
3035     // make sure the mouse is not over the window, causing spontaneous mouse moves
3036     QCursor::setPos(1, 1);
3037
3038     QGraphicsScene scene;
3039     scene.addRect(0, 0, 50, 50);
3040     scene.addRect(0, 0, 100, 100);
3041
3042     MouseMoveCounter view;
3043     view.setScene(&scene);
3044     view.show();
3045     QTest::qWaitForWindowShown(&view);
3046     view.viewport()->setMouseTracking(true);
3047
3048     QCOMPARE(view.mouseMoves, 0);
3049     {
3050         QMouseEvent event(QEvent::MouseMove, view.mapFromScene(25, 25), Qt::NoButton, 0, 0);
3051         QApplication::sendEvent(view.viewport(), &event);
3052     }
3053     QCOMPARE(view.mouseMoves, 1);
3054     QTest::qWait(25);
3055     QTRY_COMPARE(view.mouseMoves, 1);
3056     QTest::qWait(25);
3057     {
3058         QMouseEvent event(QEvent::MouseMove, view.mapFromScene(25, 25), Qt::NoButton, 0, 0);
3059         QApplication::sendEvent(view.viewport(), &event);
3060     }
3061     QCOMPARE(view.mouseMoves, 2);
3062     QTest::qWait(15);
3063 }
3064
3065 void tst_QGraphicsView::task207546_focusCrash()
3066 {
3067     class _Widget : public QWidget
3068     {
3069     public:
3070         bool focusNextPrevChild(bool next) { return QWidget::focusNextPrevChild(next); }
3071     } widget;
3072
3073     widget.setLayout(new QVBoxLayout());
3074     QGraphicsView *gr1 = new QGraphicsView(&widget);
3075     QGraphicsView *gr2 = new QGraphicsView(&widget);
3076     widget.layout()->addWidget(gr1);
3077     widget.layout()->addWidget(gr2);
3078     widget.show();
3079     QTest::qWaitForWindowShown(&widget);
3080     widget.activateWindow();
3081     QApplication::setActiveWindow(&widget);
3082     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&widget));
3083     widget.focusNextPrevChild(true);
3084     QCOMPARE(static_cast<QWidget *>(gr2), widget.focusWidget());
3085 }
3086
3087 void tst_QGraphicsView::task210599_unsetDragWhileDragging()
3088 {
3089     QGraphicsScene scene(0, 0, 400, 400);
3090     QGraphicsView view(&scene);
3091     view.setGeometry(0, 0, 200, 200);
3092     view.show();
3093
3094     QPoint origPos = QPoint(100, 100);
3095     QPoint step1Pos = QPoint(100, 110);
3096     QPoint step2Pos = QPoint(100, 120);
3097
3098     // Enable and do a drag
3099     {
3100         view.setDragMode(QGraphicsView::ScrollHandDrag);
3101         QMouseEvent press(QEvent::MouseButtonPress, origPos, Qt::LeftButton, 0, 0);
3102         QMouseEvent move(QEvent::MouseMove, step1Pos, Qt::LeftButton, 0, 0);
3103         QApplication::sendEvent(view.viewport(), &press);
3104         QApplication::sendEvent(view.viewport(), &move);
3105     }
3106
3107     // unset drag and release mouse, inverse order
3108     {
3109         view.setDragMode(QGraphicsView::NoDrag);
3110         QMouseEvent release(QEvent::MouseButtonRelease, step1Pos, Qt::LeftButton, 0, 0);
3111         QApplication::sendEvent(view.viewport(), &release);
3112     }
3113
3114     QPoint basePos = view.mapFromScene(0, 0);
3115
3116     // reset drag, and move mouse without holding button down.
3117     {
3118         view.setDragMode(QGraphicsView::ScrollHandDrag);
3119         QMouseEvent move(QEvent::MouseMove, step2Pos, Qt::LeftButton, 0, 0);
3120         QApplication::sendEvent(view.viewport(), &move);
3121     }
3122
3123     // Check that no draggin has occurred...
3124     QCOMPARE(basePos, view.mapFromScene(0, 0));
3125 }
3126
3127 void tst_QGraphicsView::task236394_sendShortcutOverrideEvent()
3128 {
3129     QGraphicsView view;
3130     view.show();
3131     QKeyEvent event(QEvent::ShortcutOverride, Qt::Key_A, 0, QString("A"));
3132     QApplication::sendEvent(&view, &event);
3133 }
3134
3135 class ChangedListener : public QObject
3136 {
3137     Q_OBJECT
3138 public:
3139     QList<QList<QRectF> > changes;
3140
3141 public slots:
3142     void changed(const QList<QRectF> &dirty)
3143     {
3144         changes << dirty;
3145     }
3146 };
3147
3148 void tst_QGraphicsView::task239729_noViewUpdate_data()
3149 {
3150     QTest::addColumn<bool>("a");
3151
3152     QTest::newRow("a") << false;
3153     QTest::newRow("b") << true;
3154 }
3155
3156 void tst_QGraphicsView::task239729_noViewUpdate()
3157 {
3158     QFETCH(bool, a);
3159     // The scene's changed signal is connected to something that isn't a view.
3160     QGraphicsScene scene;
3161     ChangedListener cl;
3162     QGraphicsView *view = 0;
3163
3164     if (a) {
3165         view = new QGraphicsView(&scene);
3166         connect(&scene, SIGNAL(changed(const QList<QRectF> &)), &cl, SLOT(changed(const QList<QRectF> &)));
3167     } else {
3168         connect(&scene, SIGNAL(changed(const QList<QRectF> &)), &cl, SLOT(changed(const QList<QRectF> &)));
3169         view = new QGraphicsView(&scene);
3170     }
3171
3172     EventSpy spy(view->viewport(), QEvent::Paint);
3173     QCOMPARE(spy.count(), 0);
3174
3175     view->show();
3176     QTest::qWaitForWindowShown(view);
3177
3178     QTRY_VERIFY(spy.count() >= 1);
3179     spy.reset();
3180     scene.update();
3181     QApplication::processEvents();
3182     QTRY_COMPARE(spy.count(), 1);
3183
3184     delete view;
3185 }
3186
3187 void tst_QGraphicsView::task239047_fitInViewSmallViewport()
3188 {
3189     // Ensure that with a small viewport, fitInView doesn't mirror the
3190     // scene.
3191     QWidget widget;
3192     QGraphicsScene scene;
3193     QGraphicsView *view = new QGraphicsView(&scene, &widget);
3194     view->resize(3, 3);
3195     QCOMPARE(view->size(), QSize(3, 3));
3196     widget.show();
3197     view->fitInView(0, 0, 100, 100);
3198     QPointF topLeft = view->mapToScene(0, 0);
3199     QPointF bottomRight = view->mapToScene(100, 100);
3200     QVERIFY(bottomRight.x() > topLeft.x());
3201     QVERIFY(bottomRight.y() > topLeft.y());
3202
3203     view->fitInView(0, 0, 0, 100);
3204
3205     // Don't crash
3206     view->scale(0, 0);
3207     view->fitInView(0, 0, 100, 100);
3208 }
3209
3210 void tst_QGraphicsView::task245469_itemsAtPointWithClip()
3211 {
3212     QGraphicsScene scene;
3213     QGraphicsItem *parent = scene.addRect(0, 0, 100, 100);
3214     QGraphicsItem *child = new QGraphicsRectItem(40, 40, 20, 20, parent);
3215     parent->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
3216
3217     QGraphicsView view(&scene);
3218     view.resize(150,150);
3219     view.rotate(90);
3220     view.show();
3221     QTest::qWaitForWindowShown(&view);
3222
3223     QList<QGraphicsItem *> itemsAtCenter = view.items(view.viewport()->rect().center());
3224     QCOMPARE(itemsAtCenter, (QList<QGraphicsItem *>() << child << parent));
3225
3226     QPolygonF p = view.mapToScene(QRect(view.viewport()->rect().center(), QSize(1, 1)));
3227     QList<QGraphicsItem *> itemsAtCenter2 = scene.items(p);
3228     QCOMPARE(itemsAtCenter2, itemsAtCenter);
3229 }
3230
3231 static QGraphicsView *createSimpleViewAndScene()
3232 {
3233     QGraphicsView *view = new QGraphicsView;
3234     QGraphicsScene *scene = new QGraphicsScene;
3235     view->setScene(scene);
3236
3237     view->setBackgroundBrush(Qt::blue);
3238
3239     QGraphicsRectItem *rect = scene->addRect(0, 0, 10, 10);
3240     rect->setBrush(Qt::red);
3241     rect->setPen(Qt::NoPen);
3242     return view;
3243 }
3244
3245 class SpyItem : public QGraphicsRectItem
3246 {
3247 public:
3248     SpyItem()
3249         : QGraphicsRectItem(QRectF(0, 0, 100, 100))
3250     {
3251     }
3252
3253     void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
3254     {
3255         transform = painter->transform();
3256     }
3257
3258     QTransform transform;
3259 };
3260
3261 void tst_QGraphicsView::embeddedViews()
3262 {
3263     QGraphicsView *v1 = createSimpleViewAndScene();
3264     QGraphicsView *v2 = createSimpleViewAndScene();
3265
3266     QGraphicsProxyWidget *proxy = v1->scene()->addWidget(v2);
3267
3268     SpyItem *item = new SpyItem;
3269     v2->scene()->addItem(item);
3270
3271     proxy->translate(5, 5);
3272
3273     QImage actual(64, 64, QImage::Format_ARGB32_Premultiplied);
3274     actual.fill(0);
3275     v1->QWidget::render(&actual);
3276     QTransform a = item->transform;
3277
3278     v2->QWidget::render(&actual);
3279     QTransform b = item->transform;
3280
3281     QVERIFY(a == b);
3282     delete v1;
3283 }
3284
3285 void tst_QGraphicsView::scrollAfterResize_data()
3286 {
3287     QTest::addColumn<bool>("reverse");
3288     QTest::addColumn<QTransform>("x1");
3289     QTest::addColumn<QTransform>("x2");
3290     QTest::addColumn<QTransform>("x3");
3291
3292 #if !defined(QT_NO_STYLE_PLASTIQUE)
3293     QPlastiqueStyle style;
3294 #elif !defined(QT_NO_STYLE_WINDOWS)
3295     QWindowsStyle style;
3296 #else
3297     QCommonStyle style;
3298 #endif
3299
3300     int frameWidth = style.pixelMetric(QStyle::PM_DefaultFrameWidth);
3301     int extent = style.pixelMetric(QStyle::PM_ScrollBarExtent);
3302     int inside = style.styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents);
3303     int viewportWidth = 300;
3304     int scrollBarIndent = viewportWidth - extent - (inside ? 4 : 2)*frameWidth;
3305
3306     QTest::newRow("normal") << false
3307                             << QTransform()
3308                             << QTransform()
3309                             << QTransform().translate(-10, 0);
3310     QTest::newRow("reverse") << true
3311                              << QTransform().translate(scrollBarIndent, 0)
3312                              << QTransform().translate(scrollBarIndent + 100, 0)
3313                              << QTransform().translate(scrollBarIndent + 110, 0);
3314 }
3315
3316 void tst_QGraphicsView::scrollAfterResize()
3317 {
3318     QFETCH(bool, reverse);
3319     QFETCH(QTransform, x1);
3320     QFETCH(QTransform, x2);
3321     QFETCH(QTransform, x3);
3322
3323 #if !defined(QT_NO_STYLE_PLASTIQUE)
3324     QPlastiqueStyle style;
3325 #elif !defined(QT_NO_STYLE_WINDOWS)
3326     QWindowsStyle style;
3327 #else
3328     QCommonStyle style;
3329 #endif
3330     QWidget toplevel;
3331
3332     QGraphicsView view(&toplevel);
3333     view.setStyle(&style);
3334     if (reverse)
3335         view.setLayoutDirection(Qt::RightToLeft);
3336
3337     view.setSceneRect(-1000, -1000, 2000, 2000);
3338     view.resize(300, 300);
3339     toplevel.show();
3340     QTest::qWaitForWindowShown(&toplevel);
3341     view.horizontalScrollBar()->setValue(0);
3342     view.verticalScrollBar()->setValue(0);
3343     QCOMPARE(view.viewportTransform(), x1);
3344     view.resize(400, 300);
3345     QCOMPARE(view.viewportTransform(), x2);
3346     view.horizontalScrollBar()->setValue(10);
3347     QCOMPARE(view.viewportTransform(), x3);
3348 }
3349
3350 void tst_QGraphicsView::moveItemWhileScrolling_data()
3351 {
3352     QTest::addColumn<bool>("adjustForAntialiasing");
3353     QTest::addColumn<bool>("changedConnected");
3354
3355     QTest::newRow("no adjust") << false << false;
3356     QTest::newRow("adjust") << true << false;
3357     QTest::newRow("no adjust changedConnected") << false << true;
3358     QTest::newRow("adjust changedConnected") << true << true;
3359 }
3360
3361 void tst_QGraphicsView::moveItemWhileScrolling()
3362 {
3363     QFETCH(bool, adjustForAntialiasing);
3364     QFETCH(bool, changedConnected);
3365
3366     class MoveItemScrollView : public QGraphicsView
3367     {
3368     public:
3369         MoveItemScrollView()
3370         {
3371             setWindowFlags(Qt::X11BypassWindowManagerHint);
3372             setScene(new QGraphicsScene(0, 0, 1000, 1000));
3373             rect = scene()->addRect(0, 0, 10, 10);
3374             rect->setPos(50, 50);
3375             painted = false;
3376         }
3377         QRegion lastPaintedRegion;
3378         QGraphicsItem *rect;
3379         bool painted;
3380         void waitForPaintEvent()
3381         {
3382             QTimer::singleShot(2000, &eventLoop, SLOT(quit()));
3383             eventLoop.exec();
3384         }
3385     protected:
3386         QEventLoop eventLoop;
3387         void paintEvent(QPaintEvent *event)
3388         {
3389             painted = true;
3390             lastPaintedRegion = event->region();
3391             QGraphicsView::paintEvent(event);
3392             if (eventLoop.isRunning())
3393                 eventLoop.quit();
3394         }
3395     };
3396
3397     MoveItemScrollView view;
3398     view.setFrameStyle(0);
3399     view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
3400     view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
3401     view.setResizeAnchor(QGraphicsView::NoAnchor);
3402     view.setTransformationAnchor(QGraphicsView::NoAnchor);
3403     if (!adjustForAntialiasing)
3404         view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing);
3405     view.resize(200, 200);
3406     view.painted = false;
3407     view.show();
3408     if (changedConnected)
3409         QObject::connect(view.scene(), SIGNAL(changed(QList<QRectF>)), this, SLOT(dummySlot()));
3410     QTest::qWaitForWindowShown(&view);
3411     QApplication::processEvents();
3412     QTRY_VERIFY(view.painted);
3413     view.painted = false;
3414     view.lastPaintedRegion = QRegion();
3415     view.horizontalScrollBar()->setValue(view.horizontalScrollBar()->value() + 10);
3416     view.rect->moveBy(0, 10);
3417     view.waitForPaintEvent();
3418     QTRY_VERIFY(view.painted);
3419
3420     QRegion expectedRegion;
3421     expectedRegion += QRect(0, 0, 200, 200);
3422     expectedRegion -= QRect(0, 0, 190, 200);
3423     int a = adjustForAntialiasing ? 2 : 1;
3424     expectedRegion += QRect(40, 50, 10, 10).adjusted(-a, -a, a, a);
3425     expectedRegion += QRect(40, 60, 10, 10).adjusted(-a, -a, a, a);
3426 #ifdef Q_OS_WIN
3427     QEXPECT_FAIL("", "QTBUG-24296", Abort);
3428 #endif
3429     COMPARE_REGIONS(view.lastPaintedRegion, expectedRegion);
3430 }
3431
3432 void tst_QGraphicsView::centerOnDirtyItem()
3433 {
3434     QWidget toplevel;
3435
3436     QGraphicsView view(&toplevel);
3437     toplevel.setWindowFlags(view.windowFlags() | Qt::WindowStaysOnTopHint);
3438     view.resize(200, 200);
3439
3440     QGraphicsScene *scene = new QGraphicsScene;
3441     view.setScene(scene);
3442     view.setSceneRect(-1000, -1000, 2000, 2000);
3443
3444     QGraphicsRectItem *item = new QGraphicsRectItem(0, 0, 10, 10);
3445     item->setBrush(Qt::red);
3446     scene->addItem(item);
3447     view.centerOn(item);
3448
3449     toplevel.show();
3450     QTest::qWaitForWindowShown(&toplevel);
3451     QTest::qWait(50);
3452
3453     QImage before(view.viewport()->size(), QImage::Format_ARGB32);
3454     view.viewport()->render(&before);
3455
3456     item->setPos(20, 0);
3457     view.centerOn(item);
3458
3459     QTest::qWait(50);
3460
3461     QImage after(view.viewport()->size(), QImage::Format_ARGB32);
3462     view.viewport()->render(&after);
3463
3464     QCOMPARE(before, after);
3465 }
3466
3467 void tst_QGraphicsView::mouseTracking()
3468 {
3469     // Mouse tracking should only be automatically enabled if items either accept hover events
3470     // or have a cursor set. We never disable mouse tracking if it is already enabled.
3471
3472     { // Make sure mouse tracking is disabled by default.
3473         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3474         QGraphicsView view(&scene);
3475         QVERIFY(!view.viewport()->hasMouseTracking());
3476     }
3477
3478     { // Make sure we don't disable mouse tracking in setupViewport/setScene.
3479         QGraphicsView view;
3480         QWidget *viewport = new QWidget;
3481         viewport->setMouseTracking(true);
3482         view.setViewport(viewport);
3483         QVERIFY(viewport->hasMouseTracking());
3484
3485         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3486         view.setScene(&scene);
3487         QVERIFY(viewport->hasMouseTracking());
3488     }
3489
3490     // Make sure we enable mouse tracking when having items that accept hover events.
3491     {
3492         // Adding an item to the scene after the scene is set on the view.
3493         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3494         QGraphicsView view(&scene);
3495
3496         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3497         item->setAcceptHoverEvents(true);
3498         scene.addItem(item);
3499         QVERIFY(view.viewport()->hasMouseTracking());
3500     }
3501     {
3502         // Adding an item to the scene before the scene is set on the view.
3503         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3504         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3505         item->setAcceptHoverEvents(true);
3506         scene.addItem(item);
3507
3508         QGraphicsView view(&scene);
3509         QVERIFY(view.viewport()->hasMouseTracking());
3510     }
3511     {
3512         // QGraphicsWidget implicitly accepts hover if it has window decoration.
3513         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3514         QGraphicsView view(&scene);
3515
3516         QGraphicsWidget *widget = new QGraphicsWidget;
3517         scene.addItem(widget);
3518         QVERIFY(!view.viewport()->hasMouseTracking());
3519         // Enable window decoraton.
3520         widget->setWindowFlags(Qt::Window | Qt::WindowTitleHint);
3521         QVERIFY(view.viewport()->hasMouseTracking());
3522     }
3523
3524     // Make sure we enable mouse tracking when having items with a cursor set.
3525     {
3526         // Adding an item to the scene after the scene is set on the view.
3527         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3528         QGraphicsView view(&scene);
3529
3530         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3531 #ifndef QT_NO_CURSOR
3532         item->setCursor(Qt::CrossCursor);
3533 #endif
3534         scene.addItem(item);
3535         QVERIFY(view.viewport()->hasMouseTracking());
3536     }
3537     {
3538         // Adding an item to the scene before the scene is set on the view.
3539         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3540         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3541 #ifndef QT_NO_CURSOR
3542         item->setCursor(Qt::CrossCursor);
3543 #endif
3544         scene.addItem(item);
3545
3546         QGraphicsView view(&scene);
3547         QVERIFY(view.viewport()->hasMouseTracking());
3548     }
3549
3550     // Make sure we propagate mouse tracking to all views.
3551     {
3552         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3553         QGraphicsView view1(&scene);
3554         QGraphicsView view2(&scene);
3555         QGraphicsView view3(&scene);
3556
3557         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3558 #ifndef QT_NO_CURSOR
3559         item->setCursor(Qt::CrossCursor);
3560 #endif
3561         scene.addItem(item);
3562
3563         QVERIFY(view1.viewport()->hasMouseTracking());
3564         QVERIFY(view2.viewport()->hasMouseTracking());
3565         QVERIFY(view3.viewport()->hasMouseTracking());
3566     }
3567 }
3568
3569 void tst_QGraphicsView::mouseTracking2()
3570 {
3571     // Make sure mouse move events propagates to the scene when
3572     // mouse tracking is explicitly enabled on the view,
3573     // even when all items ignore hover events / use default cursor.
3574
3575     QGraphicsScene scene;
3576     scene.addRect(0, 0, 100, 100);
3577
3578     QGraphicsView view(&scene);
3579     view.show();
3580     QTest::qWaitForWindowShown(&view);
3581
3582     QVERIFY(!view.viewport()->hasMouseTracking());
3583     view.viewport()->setMouseTracking(true); // Explicitly enable mouse tracking.
3584     QVERIFY(view.viewport()->hasMouseTracking());
3585
3586     EventSpy spy(&scene, QEvent::GraphicsSceneMouseMove);
3587     QCOMPARE(spy.count(), 0);
3588     QMouseEvent event(QEvent::MouseMove,view.viewport()->rect().center(), Qt::NoButton,
3589                       Qt::MouseButtons(Qt::NoButton), 0);
3590     QApplication::sendEvent(view.viewport(), &event);
3591     QCOMPARE(spy.count(), 1);
3592 }
3593
3594 void tst_QGraphicsView::mouseTracking3()
3595 {
3596     // Mouse tracking should be automatically enabled if AnchorUnderMouse is used for
3597     // view transform or resize. We never disable mouse tracking if it is already enabled.
3598
3599     { // Make sure we enable mouse tracking when using AnchorUnderMouse for view transformation.
3600         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3601         QGraphicsView view(&scene);
3602         QVERIFY(!view.viewport()->hasMouseTracking());
3603
3604         view.setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
3605         QVERIFY(view.viewport()->hasMouseTracking());
3606     }
3607
3608     { // Make sure we enable mouse tracking when using AnchorUnderMouse for view resizing.
3609         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3610         QGraphicsView view(&scene);
3611         QVERIFY(!view.viewport()->hasMouseTracking());
3612
3613         view.setResizeAnchor(QGraphicsView::AnchorUnderMouse);
3614         QVERIFY(view.viewport()->hasMouseTracking());
3615     }
3616
3617     { // Make sure we don't disable mouse tracking in setViewport/setScene (transformation anchor).
3618         QGraphicsView view;
3619         view.setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
3620         QVERIFY(view.viewport()->hasMouseTracking());
3621
3622         QWidget *viewport = new QWidget;
3623         view.setViewport(viewport);
3624         QVERIFY(viewport->hasMouseTracking());
3625
3626         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3627         view.setScene(&scene);
3628         QVERIFY(viewport->hasMouseTracking());
3629     }
3630
3631     { // Make sure we don't disable mouse tracking in setViewport/setScene (resize anchor).
3632         QGraphicsView view;
3633         view.setResizeAnchor(QGraphicsView::AnchorUnderMouse);
3634         QVERIFY(view.viewport()->hasMouseTracking());
3635
3636         QWidget *viewport = new QWidget;
3637         view.setViewport(viewport);
3638         QVERIFY(viewport->hasMouseTracking());
3639
3640         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3641         view.setScene(&scene);
3642         QVERIFY(viewport->hasMouseTracking());
3643     }
3644
3645     // Make sure we don't disable mouse tracking when adding an item (transformation anchor).
3646     { // Adding an item to the scene before the scene is set on the view.
3647         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3648         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3649         scene.addItem(item);
3650
3651         QGraphicsView view;
3652         view.setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
3653         view.setScene(&scene);
3654         QVERIFY(view.viewport()->hasMouseTracking());
3655     }
3656
3657     { // Adding an item to the scene after the scene is set on the view.
3658         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3659         QGraphicsView view(&scene);
3660         view.setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
3661
3662         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3663         scene.addItem(item);
3664         QVERIFY(view.viewport()->hasMouseTracking());
3665     }
3666
3667     // Make sure we don't disable mouse tracking when adding an item (resize anchor).
3668     { // Adding an item to the scene before the scene is set on the view.
3669         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3670         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3671         scene.addItem(item);
3672
3673         QGraphicsView view;
3674         view.setResizeAnchor(QGraphicsView::AnchorUnderMouse);
3675         view.setScene(&scene);
3676         QVERIFY(view.viewport()->hasMouseTracking());
3677     }
3678
3679     { // Adding an item to the scene after the scene is set on the view.
3680         QGraphicsScene scene(-10000, -10000, 20000, 20000);
3681         QGraphicsView view(&scene);
3682         view.setResizeAnchor(QGraphicsView::AnchorUnderMouse);
3683
3684         QGraphicsRectItem *item = new QGraphicsRectItem(10, 10, 10, 10);
3685         scene.addItem(item);
3686         QVERIFY(view.viewport()->hasMouseTracking());
3687     }
3688 }
3689
3690 class RenderTester : public QGraphicsRectItem
3691 {
3692 public:
3693     RenderTester(const QRectF &rect)
3694         : QGraphicsRectItem(rect), paints(0)
3695     { }
3696
3697     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
3698                QWidget *widget)
3699     {
3700         QGraphicsRectItem::paint(painter, option, widget);
3701         ++paints;
3702     }
3703
3704     int paints;
3705 };
3706
3707 void tst_QGraphicsView::render()
3708 {
3709     // ### This test can be much more thorough - see QGraphicsScene::render.
3710     QGraphicsScene scene;
3711     CustomView view(&scene);
3712     view.setFrameStyle(0);
3713     view.resize(200, 200);
3714     view.painted = false;
3715     view.show();
3716     QTest::qWaitForWindowShown(&view);
3717     QApplication::processEvents();
3718     QTRY_VERIFY(view.painted);
3719
3720     RenderTester *r1 = new RenderTester(QRectF(0, 0, 50, 50));
3721     RenderTester *r2 = new RenderTester(QRectF(50, 50, 50, 50));
3722     RenderTester *r3 = new RenderTester(QRectF(0, 50, 50, 50));
3723     RenderTester *r4 = new RenderTester(QRectF(50, 0, 50, 50));
3724     scene.addItem(r1);
3725     scene.addItem(r2);
3726     scene.addItem(r3);
3727     scene.addItem(r4);
3728
3729     qApp->processEvents();
3730
3731     QTRY_COMPARE(r1->paints, 1);
3732     QCOMPARE(r2->paints, 1);
3733     QCOMPARE(r3->paints, 1);
3734     QCOMPARE(r4->paints, 1);
3735
3736     QPixmap pix(200, 200);
3737     pix.fill(Qt::transparent);
3738     QPainter painter(&pix);
3739     view.render(&painter);
3740     painter.end();
3741
3742     QCOMPARE(r1->paints, 2);
3743     QCOMPARE(r2->paints, 2);
3744     QCOMPARE(r3->paints, 2);
3745     QCOMPARE(r4->paints, 2);
3746 }
3747
3748 void tst_QGraphicsView::exposeRegion()
3749 {
3750     RenderTester *item = new RenderTester(QRectF(0, 0, 20, 20));
3751     QGraphicsScene scene;
3752     scene.addItem(item);
3753
3754     item->paints = 0;
3755     CustomView view;
3756     view.setScene(&scene);
3757     view.show();
3758     QTest::qWaitForWindowShown(&view);
3759     QTRY_VERIFY(item->paints > 0);
3760
3761     item->paints = 0;
3762     view.lastUpdateRegions.clear();
3763
3764     // Update a small area in the viewport's topLeft() and bottomRight().
3765     // (the boundingRect() of this area covers the entire viewport).
3766     QWidget *viewport = view.viewport();
3767     QRegion expectedExposeRegion = QRect(0, 0, 5, 5);
3768     expectedExposeRegion += QRect(viewport->rect().bottomRight() - QPoint(5, 5), QSize(5, 5));
3769     viewport->update(expectedExposeRegion);
3770     QApplication::processEvents();
3771
3772     // Make sure it triggers correct repaint on the view.
3773     QTRY_COMPARE(view.lastUpdateRegions.size(), 1);
3774     COMPARE_REGIONS(view.lastUpdateRegions.at(0), expectedExposeRegion);
3775
3776     // Make sure the item didn't get any repaints.
3777 #ifndef Q_OS_MAC
3778     QCOMPARE(item->paints, 0);
3779 #endif
3780 }
3781
3782 void tst_QGraphicsView::update_data()
3783 {
3784     // In view.viewport() coordinates. (viewport rect: QRect(0, 0, 200, 200))
3785     QTest::addColumn<QRect>("updateRect");
3786     QTest::newRow("empty") << QRect();
3787     QTest::newRow("outside left") << QRect(-200, 0, 100, 100);
3788     QTest::newRow("outside right") << QRect(400, 0 ,100, 100);
3789     QTest::newRow("outside top") << QRect(0, -200, 100, 100);
3790     QTest::newRow("outside bottom") << QRect(0, 400, 100, 100);
3791     QTest::newRow("partially inside left") << QRect(-50, 0, 100, 100);
3792     QTest::newRow("partially inside right") << QRect(-150, 0, 100, 100);
3793     QTest::newRow("partially inside top") << QRect(0, -150, 100, 100);
3794     QTest::newRow("partially inside bottom") << QRect(0, 150, 100, 100);
3795     QTest::newRow("on topLeft edge") << QRect(-100, -100, 100, 100);
3796     QTest::newRow("on topRight edge") << QRect(200, -100, 100, 100);
3797     QTest::newRow("on bottomRight edge") << QRect(200, 200, 100, 100);
3798     QTest::newRow("on bottomLeft edge") << QRect(-200, 200, 100, 100);
3799     QTest::newRow("inside topLeft") << QRect(-99, -99, 100, 100);
3800     QTest::newRow("inside topRight") << QRect(199, -99, 100, 100);
3801     QTest::newRow("inside bottomRight") << QRect(199, 199, 100, 100);
3802     QTest::newRow("inside bottomLeft") << QRect(-199, 199, 100, 100);
3803     QTest::newRow("large1") << QRect(50, -100, 100, 400);
3804     QTest::newRow("large2") << QRect(-100, 50, 400, 100);
3805     QTest::newRow("large3") << QRect(-100, -100, 400, 400);
3806     QTest::newRow("viewport rect") << QRect(0, 0, 200, 200);
3807 }
3808
3809 void tst_QGraphicsView::update()
3810 {
3811     QFETCH(QRect, updateRect);
3812
3813     // some window manager resize the toplevel to max screen size
3814     // so we must make our view a child (no layout!) of a dummy toplevel
3815     // to ensure that it's really 200x200 pixels
3816     QWidget toplevel;
3817
3818     // Create a view with viewport rect equal to QRect(0, 0, 200, 200).
3819     QGraphicsScene dummyScene;
3820     CustomView view(0, &toplevel);
3821     view.setScene(&dummyScene);
3822     view.ensurePolished(); // must ensure polished to get content margins right
3823     int left, top, right, bottom;
3824     view.getContentsMargins(&left, &top, &right, &bottom);
3825     view.resize(200 + left + right, 200 + top + bottom);
3826     toplevel.show();
3827     QTest::qWaitForWindowShown(&toplevel);
3828
3829
3830     QApplication::setActiveWindow(&toplevel);
3831     QApplication::processEvents();
3832     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&toplevel));
3833
3834     const QRect viewportRect = view.viewport()->rect();
3835     QCOMPARE(viewportRect, QRect(0, 0, 200, 200));
3836
3837 #if defined QT_BUILD_INTERNAL
3838     const bool intersects = updateRect.intersects(viewportRect);
3839     QGraphicsViewPrivate *viewPrivate = static_cast<QGraphicsViewPrivate *>(qt_widget_private(&view));
3840     QTRY_COMPARE(viewPrivate->updateRect(updateRect), intersects);
3841     QApplication::processEvents();
3842
3843     view.lastUpdateRegions.clear();
3844     viewPrivate->processPendingUpdates();
3845     QVERIFY(viewPrivate->dirtyRegion.isEmpty());
3846     QVERIFY(viewPrivate->dirtyBoundingRect.isEmpty());
3847     QApplication::processEvents();
3848     if (!intersects) {
3849         QTRY_VERIFY(view.lastUpdateRegions.isEmpty());
3850     } else {
3851         QTRY_COMPARE(view.lastUpdateRegions.size(), 1);
3852         QTRY_COMPARE(view.lastUpdateRegions.at(0), QRegion(updateRect) & viewportRect);
3853     }
3854     QTRY_VERIFY(!viewPrivate->fullUpdatePending);
3855 #endif
3856 }
3857
3858 void tst_QGraphicsView::update2_data()
3859 {
3860     QTest::addColumn<qreal>("penWidth");
3861     QTest::addColumn<bool>("antialiasing");
3862     QTest::addColumn<bool>("changedConnected");
3863
3864     // Anti-aliased.
3865     QTest::newRow("pen width: 0.0, antialiasing: true") << qreal(0.0) << true << false;
3866     QTest::newRow("pen width: 1.5, antialiasing: true") << qreal(1.5) << true << false;
3867     QTest::newRow("pen width: 2.0, antialiasing: true") << qreal(2.0) << true << false;
3868     QTest::newRow("pen width: 3.0, antialiasing: true") << qreal(3.0) << true << false;
3869
3870     // Aliased.
3871     QTest::newRow("pen width: 0.0, antialiasing: false") << qreal(0.0) << false << false;
3872     QTest::newRow("pen width: 1.5, antialiasing: false") << qreal(1.5) << false << false;
3873     QTest::newRow("pen width: 2.0, antialiasing: false") << qreal(2.0) << false << false;
3874     QTest::newRow("pen width: 3.0, antialiasing: false") << qreal(3.0) << false << false;
3875
3876     // changed() connected
3877     QTest::newRow("pen width: 0.0, antialiasing: false, changed") << qreal(0.0) << false << true;
3878     QTest::newRow("pen width: 1.5, antialiasing: true, changed") << qreal(1.5) << true << true;
3879     QTest::newRow("pen width: 2.0, antialiasing: false, changed") << qreal(2.0) << false << true;
3880     QTest::newRow("pen width: 3.0, antialiasing: true, changed") << qreal(3.0) << true << true;
3881 }
3882
3883 void tst_QGraphicsView::update2()
3884 {
3885     QFETCH(qreal, penWidth);
3886     QFETCH(bool, antialiasing);
3887     QFETCH(bool, changedConnected);
3888
3889     // Create a rect item.
3890     const QRectF rawItemRect(-50.4, -50.3, 100.2, 100.1);
3891     CountPaintItem *rect = new CountPaintItem(rawItemRect);
3892     QPen pen;
3893     pen.setWidthF(penWidth);
3894     rect->setPen(pen);
3895
3896     // Add item to a scene.
3897     QGraphicsScene scene(-100, -100, 200, 200);
3898     if (changedConnected)
3899         QObject::connect(&scene, SIGNAL(changed(QList<QRectF>)), this, SLOT(dummySlot()));
3900
3901     scene.addItem(rect);
3902
3903     // Create a view on the scene.
3904     CustomView view(&scene);
3905     view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing, !antialiasing);
3906     view.setRenderHint(QPainter::Antialiasing, antialiasing);
3907     view.setFrameStyle(0);
3908     view.resize(200, 200);
3909     view.show();
3910     QTest::qWaitForWindowShown(&view) ;
3911     QTRY_VERIFY(rect->numPaints > 0);
3912
3913     // Calculate expected update region for the rect.
3914     QRectF expectedItemBoundingRect = rawItemRect;
3915     const qreal halfPenWidth = penWidth / qreal(2.0);
3916     expectedItemBoundingRect.adjust(-halfPenWidth, -halfPenWidth, halfPenWidth, halfPenWidth);
3917     QCOMPARE(rect->boundingRect(), expectedItemBoundingRect);
3918
3919     QRect expectedItemDeviceBoundingRect = rect->deviceTransform(view.viewportTransform())
3920                                            .mapRect(expectedItemBoundingRect).toAlignedRect();
3921     if (antialiasing)
3922         expectedItemDeviceBoundingRect.adjust(-2, -2, 2, 2);
3923     else
3924         expectedItemDeviceBoundingRect.adjust(-1, -1, 1, 1);
3925     const QRegion expectedUpdateRegion(expectedItemDeviceBoundingRect);
3926
3927     // Reset.
3928     rect->numPaints = 0;
3929     view.lastUpdateRegions.clear();
3930     view.painted = false;
3931
3932     rect->update();
3933     QTRY_VERIFY(view.painted);
3934
3935 #ifndef Q_OS_MAC //cocoa doesn't support drawing regions
3936     QTRY_VERIFY(view.painted);
3937     QCOMPARE(view.lastUpdateRegions.size(), 1);
3938     QCOMPARE(view.lastUpdateRegions.at(0), expectedUpdateRegion);
3939 #endif
3940 }
3941
3942 void tst_QGraphicsView::update_ancestorClipsChildrenToShape()
3943 {
3944     QGraphicsScene scene(-150, -150, 300, 300);
3945
3946     /*
3947     Add three rects:
3948
3949     +------------------+
3950     | child            |
3951     | +--------------+ |
3952     | | parent       | |
3953     | |  +-----------+ |
3954     | |  |grandParent| |
3955     | |  +-----------+ |
3956     | +--------------+ |
3957     +------------------+
3958
3959     ... where both the parent and the grand parent clips children to shape.
3960     */
3961     QApplication::processEvents(); // Get rid of pending update.
3962
3963     QGraphicsRectItem *grandParent = static_cast<QGraphicsRectItem *>(scene.addRect(0, 0, 50, 50));
3964     grandParent->setBrush(Qt::black);
3965     grandParent->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
3966
3967     QGraphicsRectItem *parent = static_cast<QGraphicsRectItem *>(scene.addRect(-50, -50, 100, 100));
3968     parent->setBrush(QColor(0, 0, 255, 125));
3969     parent->setParentItem(grandParent);
3970     parent->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
3971
3972     QGraphicsRectItem *child = static_cast<QGraphicsRectItem *>(scene.addRect(-100, -100, 200, 200));
3973     child->setBrush(QColor(255, 0, 0, 125));
3974     child->setParentItem(parent);
3975
3976     CustomView view(&scene);
3977     view.show();
3978     QTest::qWaitForWindowShown(&view);
3979     QTRY_VERIFY(view.painted);
3980
3981     view.lastUpdateRegions.clear();
3982     view.painted = false;
3983
3984     // Call child->update() and make sure the updated area is within the ancestors' clip.
3985     QRectF expected = child->deviceTransform(view.viewportTransform()).mapRect(child->boundingRect());
3986     expected &= grandParent->deviceTransform(view.viewportTransform()).mapRect(grandParent->boundingRect());
3987
3988     child->update();
3989     QTRY_VERIFY(view.painted);
3990
3991 #ifndef Q_OS_MAC //cocoa doesn't support drawing regions
3992     QTRY_VERIFY(view.painted);
3993     QCOMPARE(view.lastUpdateRegions.size(), 1);
3994     QCOMPARE(view.lastUpdateRegions.at(0), QRegion(expected.toAlignedRect()));
3995 #endif
3996 }
3997
3998 void tst_QGraphicsView::update_ancestorClipsChildrenToShape2()
3999 {
4000     QGraphicsScene scene(-150, -150, 300, 300);
4001
4002     /*
4003     Add two rects:
4004
4005     +------------------+
4006     | child            |
4007     | +--------------+ |
4008     | | parent       | |
4009     | |              | |
4010     | |              | |
4011     | |              | |
4012     | +--------------+ |
4013     +------------------+
4014
4015     ... where the parent has no contents and clips the child to shape.
4016     */
4017     QApplication::processEvents(); // Get rid of pending update.
4018
4019     QGraphicsRectItem *parent = static_cast<QGraphicsRectItem *>(scene.addRect(-50, -50, 100, 100));
4020     parent->setBrush(QColor(0, 0, 255, 125));
4021     parent->setFlag(QGraphicsItem::ItemClipsChildrenToShape);
4022     parent->setFlag(QGraphicsItem::ItemHasNoContents);
4023
4024     QGraphicsRectItem *child = static_cast<QGraphicsRectItem *>(scene.addRect(-100, -100, 200, 200));
4025     child->setBrush(QColor(255, 0, 0, 125));
4026     child->setParentItem(parent);
4027
4028     CustomView view(&scene);
4029     view.show();
4030     QTest::qWaitForWindowShown(&view);
4031     QTRY_VERIFY(view.painted);
4032
4033     view.lastUpdateRegions.clear();
4034     view.painted = false;
4035
4036     // Call child->update() and make sure the updated area is within its parent's clip.
4037     QRectF expected = child->deviceTransform(view.viewportTransform()).mapRect(child->boundingRect());
4038     expected &= parent->deviceTransform(view.viewportTransform()).mapRect(parent->boundingRect());
4039
4040     child->update();
4041     QTRY_VERIFY(view.painted);
4042
4043 #ifndef Q_OS_MAC //cocoa doesn't support drawing regions
4044     QTRY_VERIFY(view.painted);
4045     QCOMPARE(view.lastUpdateRegions.size(), 1);
4046     QCOMPARE(view.lastUpdateRegions.at(0), QRegion(expected.toAlignedRect()));
4047 #endif
4048
4049     QTest::qWait(50);
4050
4051     view.lastUpdateRegions.clear();
4052     view.painted = false;
4053
4054     // Invalidate the parent's geometry and trigger an update.
4055     // The update area should be clipped to the parent's bounding rect for 'normal' items,
4056     // but in this case the item has no contents (ItemHasNoContents) and its geometry
4057     // is invalidated, which means we cannot clip the child update. So, the expected
4058     // area is exactly the same as the child's bounding rect (adjusted for antialiasing).
4059     parent->setRect(parent->rect().adjusted(-10, -10, -10, -10));
4060     expected = child->deviceTransform(view.viewportTransform()).mapRect(child->boundingRect());
4061     expected.adjust(-2, -2, 2, 2); // Antialiasing
4062
4063 #ifndef Q_OS_MAC //cocoa doesn't support drawing regions
4064     QTRY_VERIFY(view.painted);
4065     QCOMPARE(view.lastUpdateRegions.size(), 1);
4066     QCOMPARE(view.lastUpdateRegions.at(0), QRegion(expected.toAlignedRect()));
4067 #endif
4068 }
4069
4070 class FocusItem : public QGraphicsRectItem
4071 {
4072 public:
4073     FocusItem() : QGraphicsRectItem(0, 0, 20, 20) {
4074         m_viewHasIMEnabledInFocusInEvent = false;
4075     }
4076
4077     void focusInEvent(QFocusEvent * /* event */)
4078     {
4079         QGraphicsView *view = scene()->views().first();
4080         m_viewHasIMEnabledInFocusInEvent = view->testAttribute(Qt::WA_InputMethodEnabled);
4081     }
4082
4083     bool m_viewHasIMEnabledInFocusInEvent;
4084 };
4085
4086 void tst_QGraphicsView::inputMethodSensitivity()
4087 {
4088     QGraphicsScene scene;
4089     QGraphicsView view(&scene);
4090     view.show();
4091     QTest::qWaitForWindowShown(&view);
4092     QApplication::setActiveWindow(&view);
4093     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
4094
4095     FocusItem *item = new FocusItem;
4096
4097     view.setAttribute(Qt::WA_InputMethodEnabled, true);
4098
4099     scene.addItem(item);
4100     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4101
4102     scene.removeItem(item);
4103     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4104
4105     item->setFlag(QGraphicsItem::ItemAcceptsInputMethod);
4106     scene.addItem(item);
4107     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4108
4109     scene.removeItem(item);
4110     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4111
4112     scene.addItem(item);
4113     scene.setFocusItem(item);
4114     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4115
4116     scene.removeItem(item);
4117     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4118
4119     item->setFlag(QGraphicsItem::ItemIsFocusable);
4120     scene.addItem(item);
4121     scene.setFocusItem(item);
4122     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4123     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), true);
4124     QCOMPARE(item->m_viewHasIMEnabledInFocusInEvent, true);
4125
4126     item->setFlag(QGraphicsItem::ItemAcceptsInputMethod, false);
4127     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4128
4129     item->setFlag(QGraphicsItem::ItemAcceptsInputMethod, true);
4130     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), true);
4131
4132     // introduce another item that is focusable but does not accept input methods
4133     FocusItem *item2 = new FocusItem;
4134     item2->setFlag(QGraphicsItem::ItemIsFocusable);
4135     scene.addItem(item2);
4136     scene.setFocusItem(item2);
4137     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4138     QCOMPARE(item2->m_viewHasIMEnabledInFocusInEvent, false);
4139     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item2));
4140
4141     scene.setFocusItem(item);
4142     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), true);
4143     QCOMPARE(item->m_viewHasIMEnabledInFocusInEvent, true);
4144     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4145
4146     view.setScene(0);
4147     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4148     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4149
4150     view.setScene(&scene);
4151     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), true);
4152     QCOMPARE(item->m_viewHasIMEnabledInFocusInEvent, true);
4153     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4154
4155     scene.setFocusItem(item2);
4156     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4157     QCOMPARE(item2->m_viewHasIMEnabledInFocusInEvent, false);
4158     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item2));
4159
4160     view.setScene(0);
4161     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4162     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item2));
4163
4164     scene.setFocusItem(item);
4165     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), false);
4166     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4167
4168     view.setScene(&scene);
4169     QCOMPARE(view.testAttribute(Qt::WA_InputMethodEnabled), true);
4170     QCOMPARE(item->m_viewHasIMEnabledInFocusInEvent, true);
4171     QCOMPARE(scene.focusItem(), static_cast<QGraphicsItem *>(item));
4172 }
4173
4174 void tst_QGraphicsView::inputContextReset()
4175 {
4176     PlatformInputContext inputContext;
4177     QInputMethodPrivate *inputMethodPrivate = QInputMethodPrivate::get(qApp->inputMethod());
4178     inputMethodPrivate->testContext = &inputContext;
4179
4180     QGraphicsScene scene;
4181     QGraphicsView view(&scene);
4182     QVERIFY(view.testAttribute(Qt::WA_InputMethodEnabled));
4183
4184     view.show();
4185     QTest::qWaitForWindowShown(&view);
4186     QApplication::setActiveWindow(&view);
4187     QTRY_COMPARE(QApplication::activeWindow(), static_cast<QWidget *>(&view));
4188
4189     QGraphicsItem *item1 = new QGraphicsRectItem;
4190     item1->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod);
4191
4192     inputContext.m_resetCallCount = 0;
4193     inputContext.m_commitCallCount = 0;
4194     scene.addItem(item1);
4195     QCOMPARE(inputContext.m_resetCallCount, 0);
4196     QCOMPARE(inputContext.m_commitCallCount, 0);
4197
4198     scene.setFocusItem(item1);
4199     QCOMPARE(scene.focusItem(), (QGraphicsItem *)item1);
4200     QVERIFY(view.testAttribute(Qt::WA_InputMethodEnabled));
4201     QCOMPARE(inputContext.m_resetCallCount, 0);
4202     QCOMPARE(inputContext.m_commitCallCount, 0);
4203
4204     scene.setFocusItem(0);
4205     // the input context is reset twice, once because an item has lost focus and again because
4206     // the Qt::WA_InputMethodEnabled flag is cleared because no item has focus.
4207     //    QEXPECT_FAIL("", "QTBUG-22454", Abort);
4208     QCOMPARE(inputContext.m_resetCallCount + inputContext.m_commitCallCount, 2);
4209
4210     // introduce another item that is focusable but does not accept input methods
4211     QGraphicsItem *item2 = new QGraphicsRectItem;
4212     item2->setFlags(QGraphicsItem::ItemIsFocusable);
4213     scene.addItem(item2);
4214
4215     inputContext.m_resetCallCount = 0;
4216     inputContext.m_commitCallCount = 0;
4217     scene.setFocusItem(item2);
4218     QCOMPARE(inputContext.m_resetCallCount, 0);
4219     QCOMPARE(inputContext.m_commitCallCount, 0);
4220
4221     scene.setFocusItem(item1);
4222     QCOMPARE(inputContext.m_resetCallCount, 0);
4223     QCOMPARE(inputContext.m_commitCallCount, 0);
4224
4225     // test changing between between items that accept input methods.
4226     item2->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod);
4227     scene.setFocusItem(item2);
4228     QCOMPARE(inputContext.m_resetCallCount + inputContext.m_commitCallCount, 1);
4229 }
4230
4231 void tst_QGraphicsView::indirectPainting()
4232 {
4233     class MyScene : public QGraphicsScene
4234     { public:
4235         MyScene() : QGraphicsScene(), drawCount(0) {}
4236         void drawItems(QPainter *, int, QGraphicsItem **, const QStyleOptionGraphicsItem *, QWidget *)
4237         { ++drawCount; }
4238         int drawCount;
4239     };
4240
4241     MyScene scene;
4242     QGraphicsItem *item = scene.addRect(0, 0, 50, 50);
4243
4244     QGraphicsView view(&scene);
4245     view.setOptimizationFlag(QGraphicsView::IndirectPainting);
4246     view.show();
4247     QTest::qWaitForWindowShown(&view);
4248     QTest::qWait(100);
4249
4250     scene.drawCount = 0;
4251     item->setPos(20, 20);
4252     QApplication::processEvents();
4253     QTRY_VERIFY(scene.drawCount > 0);
4254 }
4255
4256 void tst_QGraphicsView::compositionModeInDrawBackground()
4257 {
4258     class MyView : public QGraphicsView
4259     { public:
4260         MyView(QGraphicsScene *scene) : QGraphicsView(scene),
4261         painted(false), compositionMode(QPainter::CompositionMode_SourceOver) {}
4262         bool painted;
4263         QPainter::CompositionMode compositionMode;
4264         void drawBackground(QPainter *painter, const QRectF &)
4265         {
4266             compositionMode = painter->compositionMode();
4267             painted = true;
4268         }
4269     };
4270
4271     QGraphicsScene dummy;
4272     MyView view(&dummy);
4273     view.show();
4274     QTest::qWaitForWindowShown(&view);
4275
4276     // Make sure the painter's composition mode is SourceOver in drawBackground.
4277     QTRY_VERIFY(view.painted);
4278     QCOMPARE(view.compositionMode, QPainter::CompositionMode_SourceOver);
4279
4280     view.painted = false;
4281     view.setCacheMode(QGraphicsView::CacheBackground);
4282     view.viewport()->update();
4283
4284     // Make sure the painter's composition mode is SourceOver in drawBackground
4285     // with background cache enabled.
4286     QTRY_VERIFY(view.painted);
4287     QCOMPARE(view.compositionMode, QPainter::CompositionMode_SourceOver);
4288 }
4289 void tst_QGraphicsView::task253415_reconnectUpdateSceneOnSceneChanged()
4290 {
4291     QGraphicsView view;
4292     QGraphicsView dummyView;
4293     view.setWindowFlags(view.windowFlags() | Qt::WindowStaysOnTopHint);
4294     view.resize(200, 200);
4295
4296     QGraphicsScene scene1;
4297     QObject::connect(&scene1, SIGNAL(changed(QList<QRectF>)), &dummyView, SLOT(updateScene(QList<QRectF>)));
4298     view.setScene(&scene1);
4299
4300     QTest::qWait(12);
4301
4302     QGraphicsScene scene2;
4303     QObject::connect(&scene2, SIGNAL(changed(QList<QRectF>)), &dummyView, SLOT(updateScene(QList<QRectF>)));
4304     view.setScene(&scene2);
4305
4306     QTest::qWait(12);
4307
4308     bool wasConnected2 = QObject::disconnect(&scene2, SIGNAL(changed(QList<QRectF>)), &view, 0);
4309     QVERIFY(wasConnected2);
4310 }
4311
4312 void tst_QGraphicsView::task255529_transformationAnchorMouseAndViewportMargins()
4313 {
4314 #if defined(Q_OS_WINCE)
4315     QSKIP("Qt/CE does not implement mouse tracking at this point");
4316 #endif
4317     QGraphicsScene scene(-100, -100, 200, 200);
4318     scene.addRect(QRectF(-50, -50, 100, 100), QPen(Qt::black), QBrush(Qt::blue));
4319
4320     class VpGraphicsView: public QGraphicsView
4321     {
4322     public:
4323         VpGraphicsView(QGraphicsScene *scene, QWidget *parent=0)
4324             : QGraphicsView(scene, parent)
4325         {
4326             setViewportMargins(8, 16, 12, 20);
4327             setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
4328             setMouseTracking(true);
4329         }
4330     };
4331
4332     VpGraphicsView view(&scene);
4333     view.setWindowFlags(Qt::X11BypassWindowManagerHint);
4334     view.show();
4335
4336     QTest::qWaitForWindowShown(&view);
4337     QTest::qWait(50);
4338     QPoint mouseViewPos(20, 20);
4339     sendMouseMove(view.viewport(), mouseViewPos);
4340
4341     QPointF mouseScenePos = view.mapToScene(mouseViewPos);
4342     view.setTransform(QTransform().scale(5, 5).rotate(5, Qt::ZAxis), true);
4343
4344     QPointF newMouseScenePos = view.mapToScene(mouseViewPos);
4345
4346     qreal slack = 1;
4347
4348     const qreal dx = qAbs(newMouseScenePos.x() - mouseScenePos.x());
4349     const qreal dy = qAbs(newMouseScenePos.y() - mouseScenePos.y());
4350     const QByteArray message = QString::fromLatin1("QTBUG-22455, distance: dx=%1, dy=%2 slack=%3 (%4).").
4351                      arg(dx).arg(dy).arg(slack).arg(qApp->style()->metaObject()->className()).toLocal8Bit();
4352     // This is highly unstable (observed to pass on Windows and some Linux configurations).
4353 #ifdef Q_OS_MAC
4354     QEXPECT_FAIL("", message.constData(), Abort);
4355 #endif
4356     QVERIFY2(dx < slack && dy < slack, message.constData());
4357 #endif
4358 }
4359
4360 void tst_QGraphicsView::task259503_scrollingArtifacts()
4361 {
4362     QGraphicsScene scene(0, 0, 800, 600);
4363
4364     QGraphicsRectItem card;
4365     card.setRect(0, 0, 50, 50);
4366     card.setPen(QPen(Qt::darkRed));
4367     card.setBrush(QBrush(Qt::cyan));
4368     card.setZValue(2.0);
4369     card.setPos(300, 300);
4370     scene.addItem(&card);
4371
4372     class SAGraphicsView: public QGraphicsView
4373     {
4374     public:
4375         SAGraphicsView(QGraphicsScene *scene)
4376             : QGraphicsView(scene)
4377             , itSTimeToTest(false)
4378         {
4379             setViewportUpdateMode( QGraphicsView::MinimalViewportUpdate );
4380             resize(QSize(640, 480));
4381         }
4382
4383         QRegion updateRegion;
4384         bool itSTimeToTest;
4385
4386         void paintEvent(QPaintEvent *event)
4387         {
4388             QGraphicsView::paintEvent(event);
4389
4390             if (itSTimeToTest)
4391             {
4392 #ifndef Q_OS_WIN
4393                 QEXPECT_FAIL("", "QTBUG-24296", Continue);
4394 #endif
4395                 QCOMPARE(event->region(), updateRegion);
4396             }
4397         }
4398     };
4399
4400     SAGraphicsView view(&scene);
4401     view.show();
4402     QTest::qWaitForWindowShown(&view);
4403
4404     int hsbValue = view.horizontalScrollBar()->value();
4405     view.horizontalScrollBar()->setValue(hsbValue / 2);
4406     QTest::qWait(10);
4407     view.horizontalScrollBar()->setValue(0);
4408     QTest::qWait(10);
4409
4410     QRect itemDeviceBoundingRect = card.deviceTransform(view.viewportTransform()).mapRect(card.boundingRect()).toRect();
4411     itemDeviceBoundingRect.adjust(-2, -2, 2, 2);
4412     view.updateRegion = itemDeviceBoundingRect;
4413     view.updateRegion += itemDeviceBoundingRect.translated(-100, 0);
4414     view.itSTimeToTest = true;
4415     card.setPos(200, 300);
4416     QTest::qWait(10);
4417 }
4418
4419 void tst_QGraphicsView::QTBUG_4151_clipAndIgnore_data()
4420 {
4421     QTest::addColumn<bool>("clip");
4422     QTest::addColumn<bool>("ignoreTransformations");
4423     QTest::addColumn<int>("numItems");
4424
4425     QTest::newRow("none") << false << false << 3;
4426     QTest::newRow("clip") << true << false << 3;
4427     QTest::newRow("ignore") << false << true << 3;
4428     QTest::newRow("clip+ignore") << true << true << 3;
4429 }
4430
4431 void tst_QGraphicsView::QTBUG_4151_clipAndIgnore()
4432 {
4433     QFETCH(bool, clip);
4434     QFETCH(bool, ignoreTransformations);
4435     QFETCH(int, numItems);
4436
4437     QGraphicsScene scene;
4438
4439     QGraphicsRectItem *parent = new QGraphicsRectItem(QRectF(0, 0, 50, 50), 0);
4440     QGraphicsRectItem *child = new QGraphicsRectItem(QRectF(-10, -10, 40, 40), parent);
4441     QGraphicsRectItem *ignore = new QGraphicsRectItem(QRectF(60, 60, 50, 50), 0);
4442
4443     if (clip)
4444         parent->setFlags(QGraphicsItem::ItemClipsChildrenToShape);
4445     if (ignoreTransformations)
4446         ignore->setFlag(QGraphicsItem::ItemIgnoresTransformations);
4447
4448     parent->setBrush(Qt::red);
4449     child->setBrush(QColor(0, 0, 255, 128));
4450     ignore->setBrush(Qt::green);
4451
4452     scene.addItem(parent);
4453     scene.addItem(ignore);
4454
4455     QGraphicsView view(&scene);
4456     view.setFrameStyle(0);
4457     view.resize(75, 75);
4458     view.show();
4459     QTest::qWaitForWindowShown(&view);
4460     view.activateWindow();
4461
4462     QTRY_COMPARE(QApplication::activeWindow(), (QWidget *)&view);
4463
4464     QCOMPARE(view.items(view.rect()).size(), numItems);
4465 }
4466
4467 void tst_QGraphicsView::QTBUG_5859_exposedRect()
4468 {
4469     class CustomScene : public QGraphicsScene
4470     {
4471     public:
4472         CustomScene(const QRectF &rect) : QGraphicsScene(rect) { }
4473         void drawBackground(QPainter * /* painter */, const QRectF &rect)
4474         { lastBackgroundExposedRect = rect; }
4475         QRectF lastBackgroundExposedRect;
4476     };
4477
4478     class CustomRectItem : public QGraphicsRectItem
4479     {
4480     public:
4481         CustomRectItem(const QRectF &rect) : QGraphicsRectItem(rect)
4482         { setFlag(QGraphicsItem::ItemUsesExtendedStyleOption); }
4483         void paint(QPainter * /* painter */, const QStyleOptionGraphicsItem *option, QWidget * /* widget */ = 0)
4484         { lastExposedRect = option->exposedRect; }
4485         QRectF lastExposedRect;
4486     };
4487
4488     CustomScene scene(QRectF(0,0,50,50));
4489
4490     CustomRectItem item(scene.sceneRect());
4491
4492     scene.addItem(&item);
4493
4494     QGraphicsView view(&scene);
4495     if (PlatformQuirks::isAutoMaximizing())
4496         view.setWindowFlags(view.windowFlags()|Qt::X11BypassWindowManagerHint);
4497     view.scale(4.15, 4.15);
4498     view.show();
4499     QTest::qWaitForWindowShown(&view);
4500
4501     view.viewport()->repaint(10,10,20,20);
4502     QApplication::processEvents();
4503
4504     QCOMPARE(item.lastExposedRect, scene.lastBackgroundExposedRect);
4505 }
4506
4507 void tst_QGraphicsView::QTBUG_7438_cursor()
4508 {
4509 #ifndef QT_NO_CURSOR
4510 #if defined(Q_OS_WINCE)
4511     QSKIP("Qt/CE does not have regular cursor support");
4512 #endif
4513     QGraphicsScene scene;
4514     QGraphicsItem *item = scene.addRect(QRectF(-10, -10, 20, 20));
4515     item->setFlag(QGraphicsItem::ItemIsMovable);
4516
4517     QGraphicsView view(&scene);
4518     view.setFixedSize(400, 400);
4519     view.show();
4520     QTest::qWaitForWindowShown(&view);
4521
4522     QCOMPARE(view.viewport()->cursor().shape(), QCursor().shape());
4523     view.viewport()->setCursor(Qt::PointingHandCursor);
4524     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
4525     sendMouseMove(view.viewport(), view.mapFromScene(0, 0));
4526     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
4527     sendMousePress(view.viewport(), view.mapFromScene(0, 0));
4528     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
4529     sendMouseRelease(view.viewport(), view.mapFromScene(0, 0));
4530     QCOMPARE(view.viewport()->cursor().shape(), Qt::PointingHandCursor);
4531 #endif
4532 }
4533
4534 class GraphicsItemWithHover : public QGraphicsRectItem
4535 {
4536 public:
4537     GraphicsItemWithHover()
4538         : receivedEnterEvent(false), receivedLeaveEvent(false),
4539           enterWidget(0), leaveWidget(0)
4540     {
4541         setRect(0, 0, 100, 100);
4542         setAcceptHoverEvents(true);
4543     }
4544
4545     bool sceneEvent(QEvent *event)
4546     {
4547         if (event->type() == QEvent::GraphicsSceneHoverEnter) {
4548             receivedEnterEvent = true;
4549             enterWidget = static_cast<QGraphicsSceneHoverEvent *>(event)->widget();
4550         } else if (event->type() == QEvent::GraphicsSceneHoverLeave) {
4551             receivedLeaveEvent = true;
4552             leaveWidget = static_cast<QGraphicsSceneHoverEvent *>(event)->widget();
4553         }
4554         return QGraphicsRectItem::sceneEvent(event);
4555     }
4556
4557     bool receivedEnterEvent;
4558     bool receivedLeaveEvent;
4559     QWidget *enterWidget;
4560     QWidget *leaveWidget;
4561 };
4562
4563 void tst_QGraphicsView::hoverLeave()
4564 {
4565     QGraphicsScene scene;
4566     QGraphicsView view(&scene);
4567     GraphicsItemWithHover *item = new GraphicsItemWithHover;
4568     scene.addItem(item);
4569
4570     // move the cursor out of the way
4571     QCursor::setPos(1,1);
4572
4573     view.show();
4574     QTest::qWaitForWindowShown(&view);
4575
4576     QPoint pos = view.viewport()->mapToGlobal(view.mapFromScene(item->mapToScene(10, 10)));
4577     QCursor::setPos(pos);
4578     QTest::qWait(200);
4579     QVERIFY(item->receivedEnterEvent);
4580     QCOMPARE(item->enterWidget, view.viewport());
4581
4582     QCursor::setPos(1,1);
4583     QTest::qWait(200);
4584     QVERIFY(item->receivedLeaveEvent);
4585     QCOMPARE(item->leaveWidget, view.viewport());
4586 }
4587
4588 class IMItem : public QGraphicsRectItem
4589 {
4590 public:
4591     IMItem(QGraphicsItem *parent = 0):
4592         QGraphicsRectItem(QRectF(0, 0, 20, 20), parent)
4593     {
4594         setFlag(QGraphicsItem::ItemIsFocusable, true);
4595         setFlag(QGraphicsItem::ItemAcceptsInputMethod, true);
4596     }
4597
4598     QVariant inputMethodQuery(Qt::InputMethodQuery) const
4599     {
4600         return mf;
4601     }
4602
4603     static QRectF mf;
4604 };
4605
4606 QRectF IMItem::mf(1.5, 1.6, 10, 10);
4607
4608 void tst_QGraphicsView::QTBUG_16063_microFocusRect()
4609 {
4610     QGraphicsScene scene;
4611     IMItem *item = new IMItem();
4612     scene.addItem(item);
4613
4614     QGraphicsView view(&scene);
4615
4616     view.setFixedSize(40, 40);
4617     view.show();
4618     QTest::qWaitForWindowShown(&view);
4619
4620     scene.setFocusItem(item);
4621     view.setFocus();
4622     QRectF mfv = view.inputMethodQuery(Qt::ImMicroFocus).toRectF();
4623     QCOMPARE(mfv, IMItem::mf.translated(-view.mapToScene(view.sceneRect().toRect()).boundingRect().topLeft()));
4624 }
4625
4626 QTEST_MAIN(tst_QGraphicsView)
4627 #include "tst_qgraphicsview.moc"