on 276c910 help sign in
572 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// UbuntuGestures lib
67#include <TouchRegistry.h>
69#define UQMLSCENE_DEBUG_ACTIVE_FOCUS 0
71#if UQMLSCENE_DEBUG_ACTIVE_FOCUS
72 #include "ActiveFocusLogger.h"
73#endif
75#ifdef QML_RUNTIME_TESTING
76class RenderStatistics
78public:
79 static void updateStats();
80 static void printTotalStats();
81private:
82 static QVector<qreal> timePerFrame;
83 static QVector<int> timesPerFrames;
84};
86QVector<qreal> RenderStatistics::timePerFrame;
87QVector<int> RenderStatistics::timesPerFrames;
89void RenderStatistics::updateStats()
91 static QTime time;
92 static int frames;
93 static int lastTime;
95 if (frames == 0) {
96 time.start();
97 } else {
98 int elapsed = time.elapsed();
99 timesPerFrames.append(elapsed - lastTime);
100 lastTime = elapsed;
102 if (elapsed > 5000) {
103 qreal avgtime = elapsed / (qreal) frames;
104 qreal var = 0;
105 for (int i = 0; i < timesPerFrames.size(); ++i) {
106 qreal diff = timesPerFrames.at(i) - avgtime;
107 var += diff * diff;
108 }
109 var /= timesPerFrames.size();
111 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
113 timePerFrame.append(avgtime);
114 timesPerFrames.clear();
115 time.start();
116 lastTime = 0;
117 frames = 0;
118 }
119 }
120 ++frames;
123void RenderStatistics::printTotalStats()
125 int count = timePerFrame.count();
126 if (count == 0)
127 return;
129 qreal minTime = 0;
130 qreal maxTime = 0;
131 qreal avg = 0;
132 for (int i = 0; i < count; ++i) {
133 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
134 maxTime = qMax(maxTime, timePerFrame.at(i));
135 avg += timePerFrame.at(i);
136 }
137 avg /= count;
139 qDebug(" ");
140 qDebug("----- Statistics -----");
141 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
142 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
143 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
144 qDebug("----------------------");
145 qDebug(" ");
147#endif
149struct Options
151 Options()
152 : originalQml(false)
153 , originalQmlRaster(false)
154 , maximized(false)
155 , fullscreen(false)
156 , transparent(false)
157 , clip(false)
158 , versionDetection(true)
159 , quitImmediately(false)
160 , resizeViewToRootItem(false)
161 , multisample(false)
162 {
163 }
165 QUrl file;
166 bool originalQml;
167 bool originalQmlRaster;
168 bool maximized;
169 bool fullscreen;
170 bool transparent;
171 bool scenegraphOnGraphicsview;
172 bool clip;
173 bool versionDetection;
174 bool quitImmediately;
175 bool resizeViewToRootItem;
176 bool multisample;
177 QString translationFile;
178};
180#if defined(QMLSCENE_BUNDLE)
181QFileInfoList findQmlFiles(const QString &dirName)
183 QDir dir(dirName);
185 QFileInfoList ret;
186 if (dir.exists()) {
187 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
188 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
190 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
191 if (fileInfo.isDir())
192 ret += findQmlFiles(fileInfo.filePath());
193 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
194 ret.append(fileInfo);
195 }
196 }
198 return ret;
201static int displayOptionsDialog(Options *options)
203 QDialog dialog;
205 QFormLayout *layout = new QFormLayout(&dialog);
207 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
208 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
210 Q_FOREACH (QFileInfo fileInfo, fileInfos)
211 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
213 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
214 originalCheckBox->setText("Use original QML viewer");
215 originalCheckBox->setChecked(options->originalQml);
217 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
218 fullscreenCheckBox->setText("Start fullscreen");
219 fullscreenCheckBox->setChecked(options->fullscreen);
221 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
222 maximizedCheckBox->setText("Start maximized");
223 maximizedCheckBox->setChecked(options->maximized);
225 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
226 Qt::Horizontal,
227 &dialog);
228 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
229 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
231 layout->addRow("Qml file:", qmlFileComboBox);
232 layout->addWidget(originalCheckBox);
233 layout->addWidget(maximizedCheckBox);
234 layout->addWidget(fullscreenCheckBox);
235 layout->addWidget(buttonBox);
237 int result = dialog.exec();
238 if (result == QDialog::Accepted) {
239 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
240 QFileInfo fileInfo = variant.value<QFileInfo>();
242 if (fileInfo.canonicalFilePath().startsWith(":"))
243 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
244 else
245 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
246 options->originalQml = originalCheckBox->isChecked();
247 options->maximized = maximizedCheckBox->isChecked();
248 options->fullscreen = fullscreenCheckBox->isChecked();
249 }
250 return result;
252#endif
254static bool checkVersion(const QUrl &url)
256 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
257 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
259 QString fileName = url.toLocalFile();
260 if (fileName.isEmpty()) {
261 qWarning("qmlscene: filename required.");
262 return false;
263 }
265 QFile f(fileName);
266 if (!f.open(QFile::ReadOnly | QFile::Text)) {
267 qWarning("qmlscene: failed to check version of file '%s', could not open...",
268 qPrintable(fileName));
269 return false;
270 }
272 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
273 QRegExp qt47("^\\s*import +Qt +4\\.7");
275 QTextStream stream(&f);
276 bool codeFound= false;
277 while (!codeFound) {
278 QString line = stream.readLine();
279 if (line.contains("{")) {
280 codeFound = true;
281 } else {
282 QString import;
283 if (quick1.indexIn(line) >= 0)
284 import = quick1.cap(0).trimmed();
285 else if (qt47.indexIn(line) >= 0)
286 import = qt47.cap(0).trimmed();
288 if (!import.isNull()) {
289 qWarning("qmlscene: '%s' is no longer supported.\n"
290 "Use qmlviewer to load file '%s'.",
291 qPrintable(import),
292 qPrintable(fileName));
293 return false;
294 }
295 }
296 }
298 return true;
301static void displayFileDialog(Options *options)
303#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
304 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
305 if (!fileName.isEmpty()) {
306 QFileInfo fi(fileName);
307 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
308 }
309#else
310 Q_UNUSED(options);
311 qWarning("No filename specified...");
312#endif
315#ifndef QT_NO_TRANSLATION
316static void loadTranslationFile(QTranslator &translator, const QString& directory)
318 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
319 QCoreApplication::installTranslator(&translator);
321#endif
323static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
325 QDir dir(directory+"/dummydata", "*.qml");
326 QStringList list = dir.entryList();
327 for (int i = 0; i < list.size(); ++i) {
328 QString qml = list.at(i);
329 QFile f(dir.filePath(qml));
330 f.open(QIODevice::ReadOnly);
331 QByteArray data = f.readAll();
332 QQmlComponent comp(&engine);
333 comp.setData(data, QUrl());
334 QObject *dummyData = comp.create();
336 if(comp.isError()) {
337 QList<QQmlError> errors = comp.errors();
338 Q_FOREACH (const QQmlError &error, errors)
339 qWarning() << error;
340 }
342 if (dummyData) {
343 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
344 qml.truncate(qml.length()-4);
345 engine.rootContext()->setContextProperty(qml, dummyData);
346 dummyData->setParent(&engine);
347 }
348 }
351static QObject *s_testRootObject = nullptr;
352static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
354 Q_UNUSED(jsEngine);
355 if (!s_testRootObject) {
356 s_testRootObject = new QObject(engine);
357 }
358 return s_testRootObject;
361static void usage()
363 qWarning("Usage: uqmlscene [options] <filename>");
364 qWarning(" ");
365 qWarning(" Options:");
366 qWarning(" --maximized ............................... Run maximized");
367 qWarning(" --fullscreen .............................. Run fullscreen");
368 qWarning(" --transparent ............................. Make the window transparent");
369 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
370 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
371 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
372 qWarning(" --quit .................................... Quit immediately after starting");
373 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
374 qWarning(" -B <name> <file> .......................... Add a named bundle");
375 qWarning(" -translation <translationfile> ............ Set the language to run in");
377 qWarning(" ");
378 exit(1);
381int main(int argc, char ** argv)
383 Options options;
385 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
386 ActiveFocusLogger activeFocusLogger;
387 #endif
389 QStringList imports;
390 QList<QPair<QString, QString> > bundles;
391 for (int i = 1; i < argc; ++i) {
392 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
393 options.file = QUrl::fromLocalFile(argv[i]);
394 } else {
395 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
396 if (lowerArgument == QLatin1String("--maximized"))
397 options.maximized = true;
398 else if (lowerArgument == QLatin1String("--fullscreen"))
399 options.fullscreen = true;
400 else if (lowerArgument == QLatin1String("--transparent"))
401 options.transparent = true;
402 else if (lowerArgument == QLatin1String("--clip"))
403 options.clip = true;
404 else if (lowerArgument == QLatin1String("--no-version-detection"))
405 options.versionDetection = false;
406 else if (lowerArgument == QLatin1String("--quit"))
407 options.quitImmediately = true;
408 else if (lowerArgument == QLatin1String("-translation"))
409 options.translationFile = QLatin1String(argv[++i]);
410 else if (lowerArgument == QLatin1String("--resize-to-root"))
411 options.resizeViewToRootItem = true;
412 else if (lowerArgument == QLatin1String("--multisample"))
413 options.multisample = true;
414 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
415 imports.append(QString::fromLatin1(argv[++i]));
416 else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
417 QString name = QString::fromLatin1(argv[++i]);
418 QString file = QString::fromLatin1(argv[++i]);
419 bundles.append(qMakePair(name, file));
420 } else if (lowerArgument == QLatin1String("--help")
421 || lowerArgument == QLatin1String("-help")
422 || lowerArgument == QLatin1String("--h")
423 || lowerArgument == QLatin1String("-h"))
424 usage();
425 }
426 }
428#ifdef QT_WIDGETS_LIB
429 QApplication app(argc, argv);
430#else
431 QGuiApplication app(argc, argv);
432#endif
433 app.setApplicationName("Unity8 QtQmlViewer");
434 app.setOrganizationName("Qt Project");
435 app.setOrganizationDomain("qt-project.org");
437 // Create it before loading the module, so that TestUtil
438 // doesn't create one with a fake timer factory.
439 // When interacting manually with a test we want the real deal.
440 new TouchRegistry;
442#ifndef QT_NO_TRANSLATION
443 QTranslator translator;
444 QTranslator qtTranslator;
445 QString sysLocale = QLocale::system().name();
446 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
447 app.installTranslator(&translator);
448 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
449 app.installTranslator(&qtTranslator);
450 } else {
451 app.removeTranslator(&translator);
452 }
453 }
455 QTranslator qmlTranslator;
456 if (!options.translationFile.isEmpty()) {
457 if (qmlTranslator.load(options.translationFile)) {
458 app.installTranslator(&qmlTranslator);
459 } else {
460 qWarning() << "Could not load the translation file" << options.translationFile;
461 }
462 }
463#endif
465 if (options.file.isEmpty())
466#if defined(QMLSCENE_BUNDLE)
467 displayOptionsDialog(&options);
468#else
469 displayFileDialog(&options);
470#endif
472 int exitCode = 0;
474 if (!options.file.isEmpty()) {
475 if (!options.versionDetection || checkVersion(options.file)) {
476#ifndef QT_NO_TRANSLATION
477 QTranslator translator;
478#endif
480 // TODO: as soon as the engine construction completes, the debug service is
481 // listening for connections. But actually we aren't ready to debug anything.
482 QQmlEngine engine;
483 QQmlComponent *component = new QQmlComponent(&engine);
484 for (int i = 0; i < imports.size(); ++i)
485 engine.addImportPath(imports.at(i));
486 for (int i = 0; i < bundles.size(); ++i)
487 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
488 if (options.file.isLocalFile()) {
489 QFileInfo fi(options.file.toLocalFile());
490#ifndef QT_NO_TRANSLATION
491 loadTranslationFile(translator, fi.path());
492#endif
493 loadDummyDataFiles(engine, fi.path());
494 }
495 QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
497 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
499 component->loadUrl(options.file);
500 if ( !component->isReady() ) {
501 qWarning("%s", qPrintable(component->errorString()));
502 return -1;
503 }
505 QObject *topLevel = component->create();
506 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
507 QQuickView* qxView = 0;
508 if (!window) {
509 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
510 if (contentItem) {
511 qxView = new QQuickView(&engine, nullptr);
512 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
513 activeFocusLogger.setWindow(qxView);
514 #endif
515 TouchRegistry::instance()->setParent(qxView);
516 qxView->installEventFilter(TouchRegistry::instance());
517 window = qxView;
518 // Set window default properties; the qml can still override them
519 QString oname = contentItem->objectName();
520 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
521 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
522 if (options.resizeViewToRootItem)
523 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
524 else
525 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
526 qxView->setContent(options.file, component, contentItem);
527 }
528 }
530 if (window) {
531 QSurfaceFormat surfaceFormat = window->requestedFormat();
532 if (options.multisample)
533 surfaceFormat.setSamples(16);
534 if (options.transparent) {
535 surfaceFormat.setAlphaBufferSize(8);
536 window->setClearBeforeRendering(true);
537 window->setColor(QColor(Qt::transparent));
538 window->setFlags(Qt::FramelessWindowHint);
539 }
540 window->setFormat(surfaceFormat);
542 if (options.fullscreen)
543 window->showFullScreen();
544 else if (options.maximized)
545 window->showMaximized();
546 else
547 window->show();
548 }
550 if (options.quitImmediately)
551 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
553 // Now would be a good time to inform the debug service to start listening.
555 exitCode = app.exec();
557#ifdef QML_RUNTIME_TESTING
558 RenderStatistics::printTotalStats();
559#endif
560 // Ready to exit. If we created qxView, it owns the component;
561 // otherwise, the ownership is still right here. Nobody deletes the engine
562 // (which is odd since the container constructor takes the engine pointer),
563 // but it's stack-allocated anyway.
564 if (qxView)
565 delete qxView;
566 else
567 delete component;
568 }
569 }
571 return exitCode;