201112-ui-framework: flesh out the event router.
[composite:composite-labs.git] / 201112-ui-framework / EventRouter.cpp
1 #include "EventRouter.hpp"
2 #include <QApplication>
3 #include <QEvent>
4 #include <QMouseEvent>
5 #include <QGraphicsSceneMouseEvent>
6 #include <QGraphicsScene>
7 #include <QDebug>
8 #include <iostream>
9 #include <cassert>
10
11 using namespace std;
12
13 EventRouter::EventRouter()
14 {
15     setAcceptTouchEvents(true);
16     setAcceptedMouseButtons( acceptedMouseButtons() );
17 }
18
19 bool EventRouter::event(QEvent *e)
20 {
21     QDeclarativeItem *parent = parentItem();
22     bool handled = false;
23
24     switch(e->type()) {
25     case QEvent::MouseButtonDblClick:
26     case QEvent::MouseButtonPress:
27     case QEvent::MouseButtonRelease:
28     case QEvent::MouseMove: {
29         QMouseEvent *me = dynamic_cast<QMouseEvent*>(e);
30         assert(me);
31         cout << "MouseEvent" << endl;
32         handled = true;
33     }   break;
34     case QEvent::GraphicsSceneMouseDoubleClick:
35     case QEvent::GraphicsSceneMousePress:
36     case QEvent::GraphicsSceneMouseRelease:
37     case QEvent::GraphicsSceneMouseMove: {
38         QGraphicsSceneMouseEvent *me = dynamic_cast<QGraphicsSceneMouseEvent*>(e);
39         assert(me);
40         QPointF pos = me->scenePos();
41         QList<QObject*> children = parent->children();
42         QObject *c;
43         QGraphicsItem *g;
44         foreach(c, children) {
45             if (c == this) continue;
46             g = dynamic_cast<QGraphicsItem*>(c);
47             if (g) {
48                 if (g->sceneBoundingRect().contains(pos)) {
49                     QGraphicsScene *s = scene();
50                     handled = s->sendEvent(g, e);
51                     qDebug() << g->sceneBoundingRect();
52                     break;
53                 }
54             }
55         }
56         qDebug() << "GraphicsSceneMouseEvent "
57                  << ((handled)?("handled"):("ignored"));
58         handled = true;
59     }   break;
60     default:
61         cout << ((int)(e->type())) << " unhandled" << endl;
62         handled = false;
63     }
64     return handled;
65 }
66
67 bool EventRouter::acceptTouchEvents() const
68 {
69     return true;
70 }
71
72 Qt::MouseButtons EventRouter::acceptedMouseButtons() const
73 {
74     return Qt::LeftButton | Qt::RightButton | Qt::MidButton |
75         Qt::MiddleButton | Qt::XButton1 | Qt::XButton2;
76 }