on 436b607 help sign in
576 lines 21 kB history raw
1/****************************************************************************
2**
3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4** Contact: http://www.qt-project.org/legal
5**
6** This file is part of the tools applications of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Digia. For licensing terms and
14** conditions see http://qt.digia.com/licensing. For further information
15** use the contact form at http://qt.digia.com/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 2.1 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 2.1 requirements
23** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24**
25** In addition, as a special exception, Digia gives you certain additional
26** rights. These rights are described in the Digia Qt LGPL Exception
27** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28**
29** GNU General Public License Usage
30** Alternatively, this file may be used under the terms of the GNU
31** General Public License version 3.0 as published by the Free Software
32** Foundation and appearing in the file LICENSE.GPL included in the
33** packaging of this file. Please review the following information to
34** ensure the GNU General Public License version 3.0 requirements will be
35** met: http://www.gnu.org/copyleft/gpl.html.
36**
37**
38** $QT_END_LICENSE$
39**
40****************************************************************************/
42#include <QtCore/qdebug.h>
43#include <QtCore/qabstractanimation.h>
44#include <QtCore/qdir.h>
45#include <QtCore/qmath.h>
46#include <QtCore/qdatetime.h>
48#include <QtGui/QGuiApplication>
50#include <QtQml/qqml.h>
51#include <QtQml/qqmlengine.h>
52#include <QtQml/qqmlcomponent.h>
53#include <QtQml/qqmlcontext.h>
55#include <QtQuick/qquickitem.h>
56#include <QtQuick/qquickview.h>
58#ifdef QT_WIDGETS_LIB
59#include <QtWidgets/QApplication>
60#include <QtWidgets/QFileDialog>
61#endif
63#include <QtCore/QTranslator>
64#include <QtCore/QLibraryInfo>
66#include <MouseTouchAdaptor.h>
68// UbuntuGestures lib
69#include <TouchRegistry.h>
71#define UQMLSCENE_DEBUG_ACTIVE_FOCUS 0
73#if UQMLSCENE_DEBUG_ACTIVE_FOCUS
74 #include "ActiveFocusLogger.h"
75#endif
77#ifdef QML_RUNTIME_TESTING
78class RenderStatistics
80public:
81 static void updateStats();
82 static void printTotalStats();
83private:
84 static QVector<qreal> timePerFrame;
85 static QVector<int> timesPerFrames;
86};
88QVector<qreal> RenderStatistics::timePerFrame;
89QVector<int> RenderStatistics::timesPerFrames;
91void RenderStatistics::updateStats()
93 static QTime time;
94 static int frames;
95 static int lastTime;
97 if (frames == 0) {
98 time.start();
99 } else {
100 int elapsed = time.elapsed();
101 timesPerFrames.append(elapsed - lastTime);
102 lastTime = elapsed;
104 if (elapsed > 5000) {
105 qreal avgtime = elapsed / (qreal) frames;
106 qreal var = 0;
107 for (int i = 0; i < timesPerFrames.size(); ++i) {
108 qreal diff = timesPerFrames.at(i) - avgtime;
109 var += diff * diff;
110 }
111 var /= timesPerFrames.size();
113 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
115 timePerFrame.append(avgtime);
116 timesPerFrames.clear();
117 time.start();
118 lastTime = 0;
119 frames = 0;
120 }
121 }
122 ++frames;
125void RenderStatistics::printTotalStats()
127 int count = timePerFrame.count();
128 if (count == 0)
129 return;
131 qreal minTime = 0;
132 qreal maxTime = 0;
133 qreal avg = 0;
134 for (int i = 0; i < count; ++i) {
135 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
136 maxTime = qMax(maxTime, timePerFrame.at(i));
137 avg += timePerFrame.at(i);
138 }
139 avg /= count;
141 qDebug(" ");
142 qDebug("----- Statistics -----");
143 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
144 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
145 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
146 qDebug("----------------------");
147 qDebug(" ");
149#endif
151struct Options
153 Options()
154 : originalQml(false)
155 , originalQmlRaster(false)
156 , maximized(false)
157 , fullscreen(false)
158 , transparent(false)
159 , clip(false)
160 , versionDetection(true)
161 , quitImmediately(false)
162 , resizeViewToRootItem(false)
163 , multisample(false)
164 {
165 }
167 QUrl file;
168 bool originalQml;
169 bool originalQmlRaster;
170 bool maximized;
171 bool fullscreen;
172 bool transparent;
173 bool scenegraphOnGraphicsview;
174 bool clip;
175 bool versionDetection;
176 bool quitImmediately;
177 bool resizeViewToRootItem;
178 bool multisample;
179 QString translationFile;
180};
182#if defined(QMLSCENE_BUNDLE)
183QFileInfoList findQmlFiles(const QString &dirName)
185 QDir dir(dirName);
187 QFileInfoList ret;
188 if (dir.exists()) {
189 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
190 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
192 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
193 if (fileInfo.isDir())
194 ret += findQmlFiles(fileInfo.filePath());
195 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
196 ret.append(fileInfo);
197 }
198 }
200 return ret;
203static int displayOptionsDialog(Options *options)
205 QDialog dialog;
207 QFormLayout *layout = new QFormLayout(&dialog);
209 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
210 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
212 Q_FOREACH (QFileInfo fileInfo, fileInfos)
213 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
215 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
216 originalCheckBox->setText("Use original QML viewer");
217 originalCheckBox->setChecked(options->originalQml);
219 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
220 fullscreenCheckBox->setText("Start fullscreen");
221 fullscreenCheckBox->setChecked(options->fullscreen);
223 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
224 maximizedCheckBox->setText("Start maximized");
225 maximizedCheckBox->setChecked(options->maximized);
227 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
228 Qt::Horizontal,
229 &dialog);
230 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
231 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
233 layout->addRow("Qml file:", qmlFileComboBox);
234 layout->addWidget(originalCheckBox);
235 layout->addWidget(maximizedCheckBox);
236 layout->addWidget(fullscreenCheckBox);
237 layout->addWidget(buttonBox);
239 int result = dialog.exec();
240 if (result == QDialog::Accepted) {
241 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
242 QFileInfo fileInfo = variant.value<QFileInfo>();
244 if (fileInfo.canonicalFilePath().startsWith(":"))
245 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
246 else
247 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
248 options->originalQml = originalCheckBox->isChecked();
249 options->maximized = maximizedCheckBox->isChecked();
250 options->fullscreen = fullscreenCheckBox->isChecked();
251 }
252 return result;
254#endif
256static bool checkVersion(const QUrl &url)
258 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
259 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
261 QString fileName = url.toLocalFile();
262 if (fileName.isEmpty()) {
263 qWarning("qmlscene: filename required.");
264 return false;
265 }
267 QFile f(fileName);
268 if (!f.open(QFile::ReadOnly | QFile::Text)) {
269 qWarning("qmlscene: failed to check version of file '%s', could not open...",
270 qPrintable(fileName));
271 return false;
272 }
274 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
275 QRegExp qt47("^\\s*import +Qt +4\\.7");
277 QTextStream stream(&f);
278 bool codeFound= false;
279 while (!codeFound) {
280 QString line = stream.readLine();
281 if (line.contains("{")) {
282 codeFound = true;
283 } else {
284 QString import;
285 if (quick1.indexIn(line) >= 0)
286 import = quick1.cap(0).trimmed();
287 else if (qt47.indexIn(line) >= 0)
288 import = qt47.cap(0).trimmed();
290 if (!import.isNull()) {
291 qWarning("qmlscene: '%s' is no longer supported.\n"
292 "Use qmlviewer to load file '%s'.",
293 qPrintable(import),
294 qPrintable(fileName));
295 return false;
296 }
297 }
298 }
300 return true;
303static void displayFileDialog(Options *options)
305#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
306 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
307 if (!fileName.isEmpty()) {
308 QFileInfo fi(fileName);
309 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
310 }
311#else
312 Q_UNUSED(options);
313 qWarning("No filename specified...");
314#endif
317#ifndef QT_NO_TRANSLATION
318static void loadTranslationFile(QTranslator &translator, const QString& directory)
320 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
321 QCoreApplication::installTranslator(&translator);
323#endif
325static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
327 QDir dir(directory+"/dummydata", "*.qml");
328 QStringList list = dir.entryList();
329 for (int i = 0; i < list.size(); ++i) {
330 QString qml = list.at(i);
331 QFile f(dir.filePath(qml));
332 f.open(QIODevice::ReadOnly);
333 QByteArray data = f.readAll();
334 QQmlComponent comp(&engine);
335 comp.setData(data, QUrl());
336 QObject *dummyData = comp.create();
338 if(comp.isError()) {
339 QList<QQmlError> errors = comp.errors();
340 Q_FOREACH (const QQmlError &error, errors)
341 qWarning() << error;
342 }
344 if (dummyData) {
345 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
346 qml.truncate(qml.length()-4);
347 engine.rootContext()->setContextProperty(qml, dummyData);
348 dummyData->setParent(&engine);
349 }
350 }
353static QObject *s_testRootObject = nullptr;
354static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
356 Q_UNUSED(jsEngine);
357 if (!s_testRootObject) {
358 s_testRootObject = new QObject(engine);
359 }
360 return s_testRootObject;
363static void usage()
365 qWarning("Usage: uqmlscene [options] <filename>");
366 qWarning(" ");
367 qWarning(" Options:");
368 qWarning(" --maximized ............................... Run maximized");
369 qWarning(" --fullscreen .............................. Run fullscreen");
370 qWarning(" --transparent ............................. Make the window transparent");
371 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
372 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
373 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
374 qWarning(" --quit .................................... Quit immediately after starting");
375 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
376 qWarning(" -B <name> <file> .......................... Add a named bundle");
377 qWarning(" -translation <translationfile> ............ Set the language to run in");
379 qWarning(" ");
380 exit(1);
383int main(int argc, char ** argv)
385 Options options;
387 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
388 ActiveFocusLogger activeFocusLogger;
389 #endif
391 QStringList imports;
392 QList<QPair<QString, QString> > bundles;
393 for (int i = 1; i < argc; ++i) {
394 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
395 options.file = QUrl::fromLocalFile(argv[i]);
396 } else {
397 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
398 if (lowerArgument == QLatin1String("--maximized"))
399 options.maximized = true;
400 else if (lowerArgument == QLatin1String("--fullscreen"))
401 options.fullscreen = true;
402 else if (lowerArgument == QLatin1String("--transparent"))
403 options.transparent = true;
404 else if (lowerArgument == QLatin1String("--clip"))
405 options.clip = true;
406 else if (lowerArgument == QLatin1String("--no-version-detection"))
407 options.versionDetection = false;
408 else if (lowerArgument == QLatin1String("--quit"))
409 options.quitImmediately = true;
410 else if (lowerArgument == QLatin1String("-translation"))
411 options.translationFile = QLatin1String(argv[++i]);
412 else if (lowerArgument == QLatin1String("--resize-to-root"))
413 options.resizeViewToRootItem = true;
414 else if (lowerArgument == QLatin1String("--multisample"))
415 options.multisample = true;
416 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
417 imports.append(QString::fromLatin1(argv[++i]));
418 else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
419 QString name = QString::fromLatin1(argv[++i]);
420 QString file = QString::fromLatin1(argv[++i]);
421 bundles.append(qMakePair(name, file));
422 } else if (lowerArgument == QLatin1String("--help")
423 || lowerArgument == QLatin1String("-help")
424 || lowerArgument == QLatin1String("--h")
425 || lowerArgument == QLatin1String("-h"))
426 usage();
427 }
428 }
430#ifdef QT_WIDGETS_LIB
431 QApplication app(argc, argv);
432#else
433 QGuiApplication app(argc, argv);
434#endif
435 app.setApplicationName("Unity8 QtQmlViewer");
436 app.setOrganizationName("Qt Project");
437 app.setOrganizationDomain("qt-project.org");
439 MouseTouchAdaptor mouseTouchAdaptor;
440 app.installNativeEventFilter(&mouseTouchAdaptor);
441 // Create it before loading the module, so that TestUtil
442 // doesn't create one with a fake timer factory.
443 // When interacting manually with a test we want the real deal.
444 new TouchRegistry;
446#ifndef QT_NO_TRANSLATION
447 QTranslator translator;
448 QTranslator qtTranslator;
449 QString sysLocale = QLocale::system().name();
450 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
451 app.installTranslator(&translator);
452 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
453 app.installTranslator(&qtTranslator);
454 } else {
455 app.removeTranslator(&translator);
456 }
457 }
459 QTranslator qmlTranslator;
460 if (!options.translationFile.isEmpty()) {
461 if (qmlTranslator.load(options.translationFile)) {
462 app.installTranslator(&qmlTranslator);
463 } else {
464 qWarning() << "Could not load the translation file" << options.translationFile;
465 }
466 }
467#endif
469 if (options.file.isEmpty())
470#if defined(QMLSCENE_BUNDLE)
471 displayOptionsDialog(&options);
472#else
473 displayFileDialog(&options);
474#endif
476 int exitCode = 0;
478 if (!options.file.isEmpty()) {
479 if (!options.versionDetection || checkVersion(options.file)) {
480#ifndef QT_NO_TRANSLATION
481 QTranslator translator;
482#endif
484 // TODO: as soon as the engine construction completes, the debug service is
485 // listening for connections. But actually we aren't ready to debug anything.
486 QQmlEngine engine;
487 QQmlComponent *component = new QQmlComponent(&engine);
488 for (int i = 0; i < imports.size(); ++i)
489 engine.addImportPath(imports.at(i));
490 for (int i = 0; i < bundles.size(); ++i)
491 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
492 if (options.file.isLocalFile()) {
493 QFileInfo fi(options.file.toLocalFile());
494#ifndef QT_NO_TRANSLATION
495 loadTranslationFile(translator, fi.path());
496#endif
497 loadDummyDataFiles(engine, fi.path());
498 }
499 QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
501 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
503 component->loadUrl(options.file);
504 if ( !component->isReady() ) {
505 qWarning("%s", qPrintable(component->errorString()));
506 return -1;
507 }
509 QObject *topLevel = component->create();
510 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
511 QQuickView* qxView = 0;
512 if (!window) {
513 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
514 if (contentItem) {
515 qxView = new QQuickView(&engine, nullptr);
516 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
517 activeFocusLogger.setWindow(qxView);
518 #endif
519 TouchRegistry::instance()->setParent(qxView);
520 qxView->installEventFilter(TouchRegistry::instance());
521 window = qxView;
522 // Set window default properties; the qml can still override them
523 QString oname = contentItem->objectName();
524 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
525 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
526 if (options.resizeViewToRootItem)
527 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
528 else
529 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
530 qxView->setContent(options.file, component, contentItem);
531 }
532 }
534 if (window) {
535 QSurfaceFormat surfaceFormat = window->requestedFormat();
536 if (options.multisample)
537 surfaceFormat.setSamples(16);
538 if (options.transparent) {
539 surfaceFormat.setAlphaBufferSize(8);
540 window->setClearBeforeRendering(true);
541 window->setColor(QColor(Qt::transparent));
542 window->setFlags(Qt::FramelessWindowHint);
543 }
544 window->setFormat(surfaceFormat);
546 if (options.fullscreen)
547 window->showFullScreen();
548 else if (options.maximized)
549 window->showMaximized();
550 else
551 window->show();
552 }
554 if (options.quitImmediately)
555 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
557 // Now would be a good time to inform the debug service to start listening.
559 exitCode = app.exec();
561#ifdef QML_RUNTIME_TESTING
562 RenderStatistics::printTotalStats();
563#endif
564 // Ready to exit. If we created qxView, it owns the component;
565 // otherwise, the ownership is still right here. Nobody deletes the engine
566 // (which is odd since the container constructor takes the engine pointer),
567 // but it's stack-allocated anyway.
568 if (qxView)
569 delete qxView;
570 else
571 delete component;
572 }
573 }
575 return exitCode;