1/****************************************************************************
3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4** Contact: http://www.qt-project.org/legal
6** This file is part of the tools applications of the Qt Toolkit.
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.
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.
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.
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.
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>
59#include <QtWidgets/QApplication>
60#include <QtWidgets/QFileDialog>
63#include <QtCore/QTranslator>
64#include <QtCore/QLibraryInfo>
66#include <MouseTouchAdaptor.h>
69#include <TouchRegistry.h>
71#define UQMLSCENE_DEBUG_ACTIVE_FOCUS 0
73#if UQMLSCENE_DEBUG_ACTIVE_FOCUS
74 #include "ActiveFocusLogger.h"
77#ifdef QML_RUNTIME_TESTING
81 static void updateStats();
82 static void printTotalStats();
84 static QVector<qreal> timePerFrame;
85 static QVector<int> timesPerFrames;
88QVector<qreal> RenderStatistics::timePerFrame;
89QVector<int> RenderStatistics::timesPerFrames;
91void RenderStatistics::updateStats()
100 int elapsed = time.elapsed();
101 timesPerFrames.append(elapsed - lastTime);
104 if (elapsed > 5000) {
105 qreal avgtime = elapsed / (qreal) frames;
107 for (int i = 0; i < timesPerFrames.size(); ++i) {
108 qreal diff = timesPerFrames.at(i) - avgtime;
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();
125void RenderStatistics::printTotalStats()
127 int count = timePerFrame.count();
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);
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("----------------------");
155 , originalQmlRaster(false)
160 , versionDetection(true)
161 , quitImmediately(false)
162 , resizeViewToRootItem(false)
169 bool originalQmlRaster;
173 bool scenegraphOnGraphicsview;
175 bool versionDetection;
176 bool quitImmediately;
177 bool resizeViewToRootItem;
179 QString translationFile;
182#if defined(QMLSCENE_BUNDLE)
183QFileInfoList findQmlFiles(const QString &dirName)
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);
203static int displayOptionsDialog(Options *options)
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,
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());
247 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
248 options->originalQml = originalCheckBox->isChecked();
249 options->maximized = maximizedCheckBox->isChecked();
250 options->fullscreen = fullscreenCheckBox->isChecked();
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.");
268 if (!f.open(QFile::ReadOnly | QFile::Text)) {
269 qWarning("qmlscene: failed to check version of file '%s', could not open...",
270 qPrintable(fileName));
274 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
275 QRegExp qt47("^\\s*import +Qt +4\\.7");
277 QTextStream stream(&f);
278 bool codeFound= false;
280 QString line = stream.readLine();
281 if (line.contains("{")) {
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'.",
294 qPrintable(fileName));
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());
313 qWarning("No filename specified...");
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);
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();
339 QList<QQmlError> errors = comp.errors();
340 Q_FOREACH (const QQmlError &error, errors)
345 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
346 qml.truncate(qml.length()-4);
347 engine.rootContext()->setContextProperty(qml, dummyData);
348 dummyData->setParent(&engine);
353static QObject *s_testRootObject = nullptr;
354static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
357 if (!s_testRootObject) {
358 s_testRootObject = new QObject(engine);
360 return s_testRootObject;
365 qWarning("Usage: uqmlscene [options] <filename>");
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");
383int main(int argc, char ** argv)
387 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
388 ActiveFocusLogger activeFocusLogger;
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]);
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"))
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"))
431 QApplication app(argc, argv);
433 QGuiApplication app(argc, argv);
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.
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);
455 app.removeTranslator(&translator);
459 QTranslator qmlTranslator;
460 if (!options.translationFile.isEmpty()) {
461 if (qmlTranslator.load(options.translationFile)) {
462 app.installTranslator(&qmlTranslator);
464 qWarning() << "Could not load the translation file" << options.translationFile;
469 if (options.file.isEmpty())
470#if defined(QMLSCENE_BUNDLE)
471 displayOptionsDialog(&options);
473 displayFileDialog(&options);
478 if (!options.file.isEmpty()) {
479 if (!options.versionDetection || checkVersion(options.file)) {
480#ifndef QT_NO_TRANSLATION
481 QTranslator translator;
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.
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());
497 loadDummyDataFiles(engine, fi.path());
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()));
509 QObject *topLevel = component->create();
510 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
511 QQuickView* qxView = 0;
513 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
515 qxView = new QQuickView(&engine, nullptr);
516 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
517 activeFocusLogger.setWindow(qxView);
519 TouchRegistry::instance()->setParent(qxView);
520 qxView->installEventFilter(TouchRegistry::instance());
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);
529 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
530 qxView->setContent(options.file, component, contentItem);
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);
544 window->setFormat(surfaceFormat);
546 if (options.fullscreen)
547 window->showFullScreen();
548 else if (options.maximized)
549 window->showMaximized();
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();
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.
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list