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;
163 bool versionDetection;
164 bool quitImmediately;
165 bool resizeViewToRootItem;
167 QString translationFile;
170#if defined(QMLSCENE_BUNDLE)
171QFileInfoList findQmlFiles(const QString &dirName)
177 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
178 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
180 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
181 if (fileInfo.isDir())
182 ret += findQmlFiles(fileInfo.filePath());
183 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
184 ret.append(fileInfo);
191static int displayOptionsDialog(Options *options)
195 QFormLayout *layout = new QFormLayout(&dialog);
197 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
198 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
200 Q_FOREACH (QFileInfo fileInfo, fileInfos)
201 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
203 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
204 originalCheckBox->setText("Use original QML viewer");
205 originalCheckBox->setChecked(options->originalQml);
207 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
208 fullscreenCheckBox->setText("Start fullscreen");
209 fullscreenCheckBox->setChecked(options->fullscreen);
211 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
212 maximizedCheckBox->setText("Start maximized");
213 maximizedCheckBox->setChecked(options->maximized);
215 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
218 QObject::connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
219 QObject::connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
221 layout->addRow("Qml file:", qmlFileComboBox);
222 layout->addWidget(originalCheckBox);
223 layout->addWidget(maximizedCheckBox);
224 layout->addWidget(fullscreenCheckBox);
225 layout->addWidget(buttonBox);
227 int result = dialog.exec();
228 if (result == QDialog::Accepted) {
229 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
230 QFileInfo fileInfo = variant.value<QFileInfo>();
232 if (fileInfo.canonicalFilePath().startsWith(":"))
233 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
235 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
236 options->originalQml = originalCheckBox->isChecked();
237 options->maximized = maximizedCheckBox->isChecked();
238 options->fullscreen = fullscreenCheckBox->isChecked();
244static bool checkVersion(const QUrl &url)
246 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
247 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
249 QString fileName = url.toLocalFile();
250 if (fileName.isEmpty()) {
251 qWarning("qmlscene: filename required.");
256 if (!f.open(QFile::ReadOnly | QFile::Text)) {
257 qWarning("qmlscene: failed to check version of file '%s', could not open...",
258 qPrintable(fileName));
262 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
263 QRegExp qt47("^\\s*import +Qt +4\\.7");
265 QTextStream stream(&f);
266 bool codeFound= false;
268 QString line = stream.readLine();
269 if (line.contains("{")) {
273 if (quick1.indexIn(line) >= 0)
274 import = quick1.cap(0).trimmed();
275 else if (qt47.indexIn(line) >= 0)
276 import = qt47.cap(0).trimmed();
278 if (!import.isNull()) {
279 qWarning("qmlscene: '%s' is no longer supported.\n"
280 "Use qmlviewer to load file '%s'.",
282 qPrintable(fileName));
291static void displayFileDialog(Options *options)
293#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
294 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
295 if (!fileName.isEmpty()) {
296 QFileInfo fi(fileName);
297 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
301 qWarning("No filename specified...");
305#ifndef QT_NO_TRANSLATION
306static void loadTranslationFile(QTranslator &translator, const QString& directory)
308 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
309 QCoreApplication::installTranslator(&translator);
313static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
315 QDir dir(directory+"/dummydata", "*.qml");
316 QStringList list = dir.entryList();
317 for (int i = 0; i < list.size(); ++i) {
318 QString qml = list.at(i);
319 QFile f(dir.filePath(qml));
320 f.open(QIODevice::ReadOnly);
321 QByteArray data = f.readAll();
322 QQmlComponent comp(&engine);
323 comp.setData(data, QUrl());
324 QObject *dummyData = comp.create();
327 QList<QQmlError> errors = comp.errors();
328 Q_FOREACH (const QQmlError &error, errors)
333 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
334 qml.truncate(qml.length()-4);
335 engine.rootContext()->setContextProperty(qml, dummyData);
336 dummyData->setParent(&engine);
341class DummyTestRootObject : public QObject
344 Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
347 DummyTestRootObject(QObject *o) : QObject(o) {}
349 bool windowShown() const { return false; }
352 void windowShownChanged();
355static QObject *s_testRootObject = nullptr;
356static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
359 if (!s_testRootObject) {
360 s_testRootObject = new DummyTestRootObject(engine);
362 return s_testRootObject;
367 qWarning("Usage: uqmlscene [options] <filename>");
369 qWarning(" Options:");
370 qWarning(" --maximized ............................... Run maximized");
371 qWarning(" --fullscreen .............................. Run fullscreen");
372 qWarning(" --transparent ............................. Make the window transparent");
373 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
374 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
375 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
376 qWarning(" --quit .................................... Quit immediately after starting");
377 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
378 qWarning(" -B <name> <file> .......................... Add a named bundle");
379 qWarning(" -translation <translationfile> ............ Set the language to run in");
385int main(int argc, char ** argv)
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]);
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"))
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"))
429 QApplication app(argc, argv);
431 QGuiApplication app(argc, argv);
433 app.setApplicationName("Unity8 QtQmlViewer");
434 app.setOrganizationName("Qt Project");
435 app.setOrganizationDomain("qt-project.org");
437#ifndef QT_NO_TRANSLATION
438 QTranslator translator;
439 QTranslator qtTranslator;
440 QString sysLocale = QLocale::system().name();
441 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
442 app.installTranslator(&translator);
443 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
444 app.installTranslator(&qtTranslator);
446 app.removeTranslator(&translator);
450 QTranslator qmlTranslator;
451 if (!options.translationFile.isEmpty()) {
452 if (qmlTranslator.load(options.translationFile)) {
453 app.installTranslator(&qmlTranslator);
455 qWarning() << "Could not load the translation file" << options.translationFile;
460 if (options.file.isEmpty())
461#if defined(QMLSCENE_BUNDLE)
462 displayOptionsDialog(&options);
464 displayFileDialog(&options);
469 if (!options.file.isEmpty()) {
470 if (!options.versionDetection || checkVersion(options.file)) {
471#ifndef QT_NO_TRANSLATION
472 QTranslator translator;
475 // TODO: as soon as the engine construction completes, the debug service is
476 // listening for connections. But actually we aren't ready to debug anything.
478 QQmlComponent *component = new QQmlComponent(&engine);
479 for (int i = 0; i < imports.size(); ++i)
480 engine.addImportPath(imports.at(i));
481 for (int i = 0; i < bundles.size(); ++i)
482 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
483 if (options.file.isLocalFile()) {
484 QFileInfo fi(options.file.toLocalFile());
485#ifndef QT_NO_TRANSLATION
486 loadTranslationFile(translator, fi.path());
488 loadDummyDataFiles(engine, fi.path());
490 QObject::connect(&engine, &QQmlEngine::quit, QCoreApplication::instance(), &QCoreApplication::quit);
492 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
494 component->loadUrl(options.file);
495 if ( !component->isReady() ) {
496 qWarning("%s", qPrintable(component->errorString()));
500 QObject *topLevel = component->create();
501 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
502 QQuickView* qxView = 0;
504 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
506 qxView = new QQuickView(&engine, nullptr);
508 // Set window default properties; the qml can still override them
509 QString oname = contentItem->objectName();
510 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
511 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
512 if (options.resizeViewToRootItem)
513 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
515 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
516 qxView->setContent(options.file, component, contentItem);
521 QSurfaceFormat surfaceFormat = window->requestedFormat();
522 if (options.multisample)
523 surfaceFormat.setSamples(16);
524 if (options.transparent) {
525 surfaceFormat.setAlphaBufferSize(8);
526 window->setClearBeforeRendering(true);
527 window->setColor(QColor(Qt::transparent));
528 window->setFlags(Qt::FramelessWindowHint);
530 window->setFormat(surfaceFormat);
532 if (options.fullscreen)
533 window->showFullScreen();
534 else if (options.maximized)
535 window->showMaximized();
540 if (options.quitImmediately)
541 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
543 // Now would be a good time to inform the debug service to start listening.
545 exitCode = app.exec();
547#ifdef QML_RUNTIME_TESTING
548 RenderStatistics::printTotalStats();
550 // Ready to exit. If we created qxView, it owns the component;
551 // otherwise, the ownership is still right here. Nobody deletes the engine
552 // (which is odd since the container constructor takes the engine pointer),
553 // 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