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#ifdef QML_RUNTIME_TESTING
75 static void updateStats();
76 static void printTotalStats();
78 static QVector<qreal> timePerFrame;
79 static QVector<int> timesPerFrames;
82QVector<qreal> RenderStatistics::timePerFrame;
83QVector<int> RenderStatistics::timesPerFrames;
85void RenderStatistics::updateStats()
94 int elapsed = time.elapsed();
95 timesPerFrames.append(elapsed - lastTime);
99 qreal avgtime = elapsed / (qreal) frames;
101 for (int i = 0; i < timesPerFrames.size(); ++i) {
102 qreal diff = timesPerFrames.at(i) - avgtime;
105 var /= timesPerFrames.size();
107 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
109 timePerFrame.append(avgtime);
110 timesPerFrames.clear();
119void RenderStatistics::printTotalStats()
121 int count = timePerFrame.count();
128 for (int i = 0; i < count; ++i) {
129 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
130 maxTime = qMax(maxTime, timePerFrame.at(i));
131 avg += timePerFrame.at(i);
136 qDebug("----- Statistics -----");
137 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
138 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
139 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
140 qDebug("----------------------");
149 , originalQmlRaster(false)
154 , versionDetection(true)
155 , quitImmediately(false)
156 , resizeViewToRootItem(false)
163 bool originalQmlRaster;
167 bool scenegraphOnGraphicsview;
169 bool versionDetection;
170 bool quitImmediately;
171 bool resizeViewToRootItem;
173 QString translationFile;
176#if defined(QMLSCENE_BUNDLE)
177QFileInfoList findQmlFiles(const QString &dirName)
183 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
184 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
186 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
187 if (fileInfo.isDir())
188 ret += findQmlFiles(fileInfo.filePath());
189 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
190 ret.append(fileInfo);
197static int displayOptionsDialog(Options *options)
201 QFormLayout *layout = new QFormLayout(&dialog);
203 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
204 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
206 Q_FOREACH (QFileInfo fileInfo, fileInfos)
207 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
209 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
210 originalCheckBox->setText("Use original QML viewer");
211 originalCheckBox->setChecked(options->originalQml);
213 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
214 fullscreenCheckBox->setText("Start fullscreen");
215 fullscreenCheckBox->setChecked(options->fullscreen);
217 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
218 maximizedCheckBox->setText("Start maximized");
219 maximizedCheckBox->setChecked(options->maximized);
221 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
224 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
225 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
227 layout->addRow("Qml file:", qmlFileComboBox);
228 layout->addWidget(originalCheckBox);
229 layout->addWidget(maximizedCheckBox);
230 layout->addWidget(fullscreenCheckBox);
231 layout->addWidget(buttonBox);
233 int result = dialog.exec();
234 if (result == QDialog::Accepted) {
235 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
236 QFileInfo fileInfo = variant.value<QFileInfo>();
238 if (fileInfo.canonicalFilePath().startsWith(":"))
239 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
241 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
242 options->originalQml = originalCheckBox->isChecked();
243 options->maximized = maximizedCheckBox->isChecked();
244 options->fullscreen = fullscreenCheckBox->isChecked();
250static bool checkVersion(const QUrl &url)
252 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
253 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
255 QString fileName = url.toLocalFile();
256 if (fileName.isEmpty()) {
257 qWarning("qmlscene: filename required.");
262 if (!f.open(QFile::ReadOnly | QFile::Text)) {
263 qWarning("qmlscene: failed to check version of file '%s', could not open...",
264 qPrintable(fileName));
268 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
269 QRegExp qt47("^\\s*import +Qt +4\\.7");
271 QTextStream stream(&f);
272 bool codeFound= false;
274 QString line = stream.readLine();
275 if (line.contains("{")) {
279 if (quick1.indexIn(line) >= 0)
280 import = quick1.cap(0).trimmed();
281 else if (qt47.indexIn(line) >= 0)
282 import = qt47.cap(0).trimmed();
284 if (!import.isNull()) {
285 qWarning("qmlscene: '%s' is no longer supported.\n"
286 "Use qmlviewer to load file '%s'.",
288 qPrintable(fileName));
297static void displayFileDialog(Options *options)
299#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
300 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
301 if (!fileName.isEmpty()) {
302 QFileInfo fi(fileName);
303 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
307 qWarning("No filename specified...");
311#ifndef QT_NO_TRANSLATION
312static void loadTranslationFile(QTranslator &translator, const QString& directory)
314 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
315 QCoreApplication::installTranslator(&translator);
319static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
321 QDir dir(directory+"/dummydata", "*.qml");
322 QStringList list = dir.entryList();
323 for (int i = 0; i < list.size(); ++i) {
324 QString qml = list.at(i);
325 QFile f(dir.filePath(qml));
326 f.open(QIODevice::ReadOnly);
327 QByteArray data = f.readAll();
328 QQmlComponent comp(&engine);
329 comp.setData(data, QUrl());
330 QObject *dummyData = comp.create();
333 QList<QQmlError> errors = comp.errors();
334 Q_FOREACH (const QQmlError &error, errors)
339 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
340 qml.truncate(qml.length()-4);
341 engine.rootContext()->setContextProperty(qml, dummyData);
342 dummyData->setParent(&engine);
347static QObject *s_testRootObject = nullptr;
348static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
351 if (!s_testRootObject) {
352 s_testRootObject = new QObject(engine);
354 return s_testRootObject;
359 qWarning("Usage: uqmlscene [options] <filename>");
361 qWarning(" Options:");
362 qWarning(" --maximized ............................... Run maximized");
363 qWarning(" --fullscreen .............................. Run fullscreen");
364 qWarning(" --transparent ............................. Make the window transparent");
365 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
366 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
367 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
368 qWarning(" --quit .................................... Quit immediately after starting");
369 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
370 qWarning(" -B <name> <file> .......................... Add a named bundle");
371 qWarning(" -translation <translationfile> ............ Set the language to run in");
377int main(int argc, char ** argv)
382 QList<QPair<QString, QString> > bundles;
383 for (int i = 1; i < argc; ++i) {
384 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
385 options.file = QUrl::fromLocalFile(argv[i]);
387 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
388 if (lowerArgument == QLatin1String("--maximized"))
389 options.maximized = true;
390 else if (lowerArgument == QLatin1String("--fullscreen"))
391 options.fullscreen = true;
392 else if (lowerArgument == QLatin1String("--transparent"))
393 options.transparent = true;
394 else if (lowerArgument == QLatin1String("--clip"))
396 else if (lowerArgument == QLatin1String("--no-version-detection"))
397 options.versionDetection = false;
398 else if (lowerArgument == QLatin1String("--quit"))
399 options.quitImmediately = true;
400 else if (lowerArgument == QLatin1String("-translation"))
401 options.translationFile = QLatin1String(argv[++i]);
402 else if (lowerArgument == QLatin1String("--resize-to-root"))
403 options.resizeViewToRootItem = true;
404 else if (lowerArgument == QLatin1String("--multisample"))
405 options.multisample = true;
406 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
407 imports.append(QString::fromLatin1(argv[++i]));
408 else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
409 QString name = QString::fromLatin1(argv[++i]);
410 QString file = QString::fromLatin1(argv[++i]);
411 bundles.append(qMakePair(name, file));
412 } else if (lowerArgument == QLatin1String("--help")
413 || lowerArgument == QLatin1String("-help")
414 || lowerArgument == QLatin1String("--h")
415 || lowerArgument == QLatin1String("-h"))
421 QApplication app(argc, argv);
423 QGuiApplication app(argc, argv);
425 app.setApplicationName("Unity8 QtQmlViewer");
426 app.setOrganizationName("Qt Project");
427 app.setOrganizationDomain("qt-project.org");
429 MouseTouchAdaptor mouseTouchAdaptor;
430 app.installNativeEventFilter(&mouseTouchAdaptor);
431 // Create it before loading the module, so that TestUtil
432 // doesn't create one with a fake timer factory.
433 // When interacting manually with a test we want the real deal.
436#ifndef QT_NO_TRANSLATION
437 QTranslator translator;
438 QTranslator qtTranslator;
439 QString sysLocale = QLocale::system().name();
440 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
441 app.installTranslator(&translator);
442 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
443 app.installTranslator(&qtTranslator);
445 app.removeTranslator(&translator);
449 QTranslator qmlTranslator;
450 if (!options.translationFile.isEmpty()) {
451 if (qmlTranslator.load(options.translationFile)) {
452 app.installTranslator(&qmlTranslator);
454 qWarning() << "Could not load the translation file" << options.translationFile;
459 if (options.file.isEmpty())
460#if defined(QMLSCENE_BUNDLE)
461 displayOptionsDialog(&options);
463 displayFileDialog(&options);
468 if (!options.file.isEmpty()) {
469 if (!options.versionDetection || checkVersion(options.file)) {
470#ifndef QT_NO_TRANSLATION
471 QTranslator translator;
474 // TODO: as soon as the engine construction completes, the debug service is
475 // listening for connections. But actually we aren't ready to debug anything.
477 QQmlComponent *component = new QQmlComponent(&engine);
478 for (int i = 0; i < imports.size(); ++i)
479 engine.addImportPath(imports.at(i));
480 for (int i = 0; i < bundles.size(); ++i)
481 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
482 if (options.file.isLocalFile()) {
483 QFileInfo fi(options.file.toLocalFile());
484#ifndef QT_NO_TRANSLATION
485 loadTranslationFile(translator, fi.path());
487 loadDummyDataFiles(engine, fi.path());
489 QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
491 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
493 component->loadUrl(options.file);
494 if ( !component->isReady() ) {
495 qWarning("%s", qPrintable(component->errorString()));
499 QObject *topLevel = component->create();
500 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
501 QQuickView* qxView = 0;
503 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
505 qxView = new QQuickView(&engine, nullptr);
506 TouchRegistry::instance()->setParent(qxView);
507 qxView->installEventFilter(TouchRegistry::instance());
509 // Set window default properties; the qml can still override them
510 QString oname = contentItem->objectName();
511 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
512 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
513 if (options.resizeViewToRootItem)
514 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
516 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
517 qxView->setContent(options.file, component, contentItem);
522 QSurfaceFormat surfaceFormat = window->requestedFormat();
523 if (options.multisample)
524 surfaceFormat.setSamples(16);
525 if (options.transparent) {
526 surfaceFormat.setAlphaBufferSize(8);
527 window->setClearBeforeRendering(true);
528 window->setColor(QColor(Qt::transparent));
529 window->setFlags(Qt::FramelessWindowHint);
531 window->setFormat(surfaceFormat);
533 if (options.fullscreen)
534 window->showFullScreen();
535 else if (options.maximized)
536 window->showMaximized();
541 if (options.quitImmediately)
542 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
544 // Now would be a good time to inform the debug service to start listening.
546 exitCode = app.exec();
548#ifdef QML_RUNTIME_TESTING
549 RenderStatistics::printTotalStats();
551 // Ready to exit. If we created qxView, it owns the component;
552 // otherwise, the ownership is still right here. Nobody deletes the engine
553 // (which is odd since the container constructor takes the engine pointer),
554 // 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