Unity 8
testutil.cpp
1 /*
2  * Copyright (C) 2012, 2013, 2014 Canonical, Ltd.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 3.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 
18 #include "testutil.h"
19 
20 #include <qpa/qwindowsysteminterface.h>
21 #include <QtGui/QGuiApplication>
22 #include <QQuickView>
23 
24 // UbuntuGestures lib
25 #include <TouchRegistry.h>
26 #include <Timer.h>
27 
28 using namespace UbuntuGestures;
29 
30 TestUtil::TestUtil(QObject *parent)
31  : QObject(parent)
32  , m_targetWindow(0)
33  , m_touchDevice(0)
34 {
35 }
36 
37 TestUtil::~TestUtil()
38 {
39 }
40 
41 bool
42 TestUtil::isInstanceOf(QObject *obj, QString name)
43 {
44  if (!obj) return false;
45  bool result = obj->inherits(name.toUtf8());
46  if (!result) {
47  const QMetaObject *metaObject = obj->metaObject();
48  while (!result && metaObject) {
49  const QString className = metaObject->className();
50  const QString qmlName = className.left(className.indexOf("_QMLTYPE_"));
51  result = qmlName == name;
52  metaObject = metaObject->superClass();
53  }
54  }
55  return result;
56 }
57 
58 TouchEventSequenceWrapper *TestUtil::touchEvent(QQuickItem *item)
59 {
60  ensureTargetWindow();
61  ensureTouchDevice();
62  ensureTouchRegistryInstalled();
63 
64  return new TouchEventSequenceWrapper(
65  QTest::touchEvent(m_targetWindow, m_touchDevice, /* autoCommit */ false), item);
66 }
67 
68 void TestUtil::ensureTargetWindow()
69 {
70  if (!m_targetWindow && !QGuiApplication::topLevelWindows().isEmpty())
71  m_targetWindow = QGuiApplication::topLevelWindows()[0];
72 }
73 
74 void TestUtil::ensureTouchDevice()
75 {
76  if (!m_touchDevice) {
77  m_touchDevice = new QTouchDevice;
78  m_touchDevice->setType(QTouchDevice::TouchScreen);
79  QWindowSystemInterface::registerTouchDevice(m_touchDevice);
80  }
81 }
82 
83 void TestUtil::ensureTouchRegistryInstalled()
84 {
85  if (TouchRegistry::instance())
86  return;
87 
88  if (!m_targetWindow)
89  return;
90 
91  // Tests can be *very* slow to run and we don't want things timing out because
92  // of that. So give it fake timers to use (they will never time out)
93  TouchRegistry *touchRegistry = new TouchRegistry(this, new FakeTimerFactory);
94 
95  QQuickView *view = qobject_cast<QQuickView*>(m_targetWindow);
96  if (view) {
97  view->installEventFilter(touchRegistry);
98  touchRegistry->setParent(view);
99  }
100 }