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#ifdef QML_RUNTIME_TESTING
70 static void updateStats();
71 static void printTotalStats();
73 static QVector<qreal> timePerFrame;
74 static QVector<int> timesPerFrames;
77QVector<qreal> RenderStatistics::timePerFrame;
78QVector<int> RenderStatistics::timesPerFrames;
80void RenderStatistics::updateStats()
89 int elapsed = time.elapsed();
90 timesPerFrames.append(elapsed - lastTime);
94 qreal avgtime = elapsed / (qreal) frames;
96 for (int i = 0; i < timesPerFrames.size(); ++i) {
97 qreal diff = timesPerFrames.at(i) - avgtime;
100 var /= timesPerFrames.size();
102 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
104 timePerFrame.append(avgtime);
105 timesPerFrames.clear();
114void RenderStatistics::printTotalStats()
116 int count = timePerFrame.count();
123 for (int i = 0; i < count; ++i) {
124 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
125 maxTime = qMax(maxTime, timePerFrame.at(i));
126 avg += timePerFrame.at(i);
131 qDebug("----- Statistics -----");
132 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
133 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
134 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
135 qDebug("----------------------");
144 , originalQmlRaster(false)
149 , versionDetection(true)
150 , quitImmediately(false)
151 , resizeViewToRootItem(false)
158 bool originalQmlRaster;
162 bool scenegraphOnGraphicsview;
164 bool versionDetection;
165 bool quitImmediately;
166 bool resizeViewToRootItem;
168 QString translationFile;
171#if defined(QMLSCENE_BUNDLE)
172QFileInfoList findQmlFiles(const QString &dirName)
178 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
179 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
181 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
182 if (fileInfo.isDir())
183 ret += findQmlFiles(fileInfo.filePath());
184 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
185 ret.append(fileInfo);
192static int displayOptionsDialog(Options *options)
196 QFormLayout *layout = new QFormLayout(&dialog);
198 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
199 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
201 Q_FOREACH (QFileInfo fileInfo, fileInfos)
202 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
204 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
205 originalCheckBox->setText("Use original QML viewer");
206 originalCheckBox->setChecked(options->originalQml);
208 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
209 fullscreenCheckBox->setText("Start fullscreen");
210 fullscreenCheckBox->setChecked(options->fullscreen);
212 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
213 maximizedCheckBox->setText("Start maximized");
214 maximizedCheckBox->setChecked(options->maximized);
216 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
219 QObject::connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
220 QObject::connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
222 layout->addRow("Qml file:", qmlFileComboBox);
223 layout->addWidget(originalCheckBox);
224 layout->addWidget(maximizedCheckBox);
225 layout->addWidget(fullscreenCheckBox);
226 layout->addWidget(buttonBox);
228 int result = dialog.exec();
229 if (result == QDialog::Accepted) {
230 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
231 QFileInfo fileInfo = variant.value<QFileInfo>();
233 if (fileInfo.canonicalFilePath().startsWith(":"))
234 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
236 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
237 options->originalQml = originalCheckBox->isChecked();
238 options->maximized = maximizedCheckBox->isChecked();
239 options->fullscreen = fullscreenCheckBox->isChecked();
245static bool checkVersion(const QUrl &url)
247 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
248 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
250 QString fileName = url.toLocalFile();
251 if (fileName.isEmpty()) {
252 qWarning("qmlscene: filename required.");
257 if (!f.open(QFile::ReadOnly | QFile::Text)) {
258 qWarning("qmlscene: failed to check version of file '%s', could not open...",
259 qPrintable(fileName));
263 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
264 QRegExp qt47("^\\s*import +Qt +4\\.7");
266 QTextStream stream(&f);
267 bool codeFound= false;
269 QString line = stream.readLine();
270 if (line.contains("{")) {
274 if (quick1.indexIn(line) >= 0)
275 import = quick1.cap(0).trimmed();
276 else if (qt47.indexIn(line) >= 0)
277 import = qt47.cap(0).trimmed();
279 if (!import.isNull()) {
280 qWarning("qmlscene: '%s' is no longer supported.\n"
281 "Use qmlviewer to load file '%s'.",
283 qPrintable(fileName));
292static void displayFileDialog(Options *options)
294#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
295 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
296 if (!fileName.isEmpty()) {
297 QFileInfo fi(fileName);
298 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
302 qWarning("No filename specified...");
306#ifndef QT_NO_TRANSLATION
307static void loadTranslationFile(QTranslator &translator, const QString& directory)
309 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
310 QCoreApplication::installTranslator(&translator);
314static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
316 QDir dir(directory+"/dummydata", "*.qml");
317 QStringList list = dir.entryList();
318 for (int i = 0; i < list.size(); ++i) {
319 QString qml = list.at(i);
320 QFile f(dir.filePath(qml));
321 f.open(QIODevice::ReadOnly);
322 QByteArray data = f.readAll();
323 QQmlComponent comp(&engine);
324 comp.setData(data, QUrl());
325 QObject *dummyData = comp.create();
328 QList<QQmlError> errors = comp.errors();
329 Q_FOREACH (const QQmlError &error, errors)
334 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
335 qml.truncate(qml.length()-4);
336 engine.rootContext()->setContextProperty(qml, dummyData);
337 dummyData->setParent(&engine);
342class DummyTestRootObject : public QObject
345 Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
348 DummyTestRootObject(QObject *o) : QObject(o) {}
350 bool windowShown() const { return false; }
353 void windowShownChanged();
356static QObject *s_testRootObject = nullptr;
357static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
360 if (!s_testRootObject) {
361 s_testRootObject = new DummyTestRootObject(engine);
363 return s_testRootObject;
368 qWarning("Usage: uqmlscene [options] <filename>");
370 qWarning(" Options:");
371 qWarning(" --maximized ............................... Run maximized");
372 qWarning(" --fullscreen .............................. Run fullscreen");
373 qWarning(" --transparent ............................. Make the window transparent");
374 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
375 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
376 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
377 qWarning(" --quit .................................... Quit immediately after starting");
378 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
379 qWarning(" -B <name> <file> .......................... Add a named bundle");
380 qWarning(" -translation <translationfile> ............ Set the language to run in");
386int main(int argc, char ** argv)
391 QList<QPair<QString, QString> > bundles;
392 for (int i = 1; i < argc; ++i) {
393 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
394 options.file = QUrl::fromLocalFile(argv[i]);
396 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
397 if (lowerArgument == QLatin1String("--maximized"))
398 options.maximized = true;
399 else if (lowerArgument == QLatin1String("--fullscreen"))
400 options.fullscreen = true;
401 else if (lowerArgument == QLatin1String("--transparent"))
402 options.transparent = true;
403 else if (lowerArgument == QLatin1String("--clip"))
405 else if (lowerArgument == QLatin1String("--no-version-detection"))
406 options.versionDetection = false;
407 else if (lowerArgument == QLatin1String("--quit"))
408 options.quitImmediately = true;
409 else if (lowerArgument == QLatin1String("-translation"))
410 options.translationFile = QLatin1String(argv[++i]);
411 else if (lowerArgument == QLatin1String("--resize-to-root"))
412 options.resizeViewToRootItem = true;
413 else if (lowerArgument == QLatin1String("--multisample"))
414 options.multisample = true;
415 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
416 imports.append(QString::fromLatin1(argv[++i]));
417 else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
418 QString name = QString::fromLatin1(argv[++i]);
419 QString file = QString::fromLatin1(argv[++i]);
420 bundles.append(qMakePair(name, file));
421 } else if (lowerArgument == QLatin1String("--help")
422 || lowerArgument == QLatin1String("-help")
423 || lowerArgument == QLatin1String("--h")
424 || lowerArgument == QLatin1String("-h"))
430 QApplication app(argc, argv);
432 QGuiApplication app(argc, argv);
434 app.setApplicationName("Unity8 QtQmlViewer");
435 app.setOrganizationName("Qt Project");
436 app.setOrganizationDomain("qt-project.org");
438#ifndef QT_NO_TRANSLATION
439 QTranslator translator;
440 QTranslator qtTranslator;
441 QString sysLocale = QLocale::system().name();
442 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
443 app.installTranslator(&translator);
444 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
445 app.installTranslator(&qtTranslator);
447 app.removeTranslator(&translator);
451 QTranslator qmlTranslator;
452 if (!options.translationFile.isEmpty()) {
453 if (qmlTranslator.load(options.translationFile)) {
454 app.installTranslator(&qmlTranslator);
456 qWarning() << "Could not load the translation file" << options.translationFile;
461 if (options.file.isEmpty())
462#if defined(QMLSCENE_BUNDLE)
463 displayOptionsDialog(&options);
465 displayFileDialog(&options);
470 if (!options.file.isEmpty()) {
471 if (!options.versionDetection || checkVersion(options.file)) {
472#ifndef QT_NO_TRANSLATION
473 QTranslator translator;
476 // TODO: as soon as the engine construction completes, the debug service is
477 // listening for connections. But actually we aren't ready to debug anything.
479 QQmlComponent *component = new QQmlComponent(&engine);
480 for (int i = 0; i < imports.size(); ++i)
481 engine.addImportPath(imports.at(i));
482 for (int i = 0; i < bundles.size(); ++i)
483 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
484 if (options.file.isLocalFile()) {
485 QFileInfo fi(options.file.toLocalFile());
486#ifndef QT_NO_TRANSLATION
487 loadTranslationFile(translator, fi.path());
489 loadDummyDataFiles(engine, fi.path());
491 QObject::connect(&engine, &QQmlEngine::quit, QCoreApplication::instance(), &QCoreApplication::quit);
493 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
495 component->loadUrl(options.file);
496 if ( !component->isReady() ) {
497 qWarning("%s", qPrintable(component->errorString()));
501 QObject *topLevel = component->create();
502 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
503 QQuickView* qxView = 0;
505 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
507 qxView = new QQuickView(&engine, nullptr);
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