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 "DebuggingController.h"
68#ifdef QML_RUNTIME_TESTING
72 static void updateStats();
73 static void printTotalStats();
75 static QVector<qreal> timePerFrame;
76 static QVector<int> timesPerFrames;
79QVector<qreal> RenderStatistics::timePerFrame;
80QVector<int> RenderStatistics::timesPerFrames;
82void RenderStatistics::updateStats()
91 int elapsed = time.elapsed();
92 timesPerFrames.append(elapsed - lastTime);
96 qreal avgtime = elapsed / (qreal) frames;
98 for (int i = 0; i < timesPerFrames.size(); ++i) {
99 qreal diff = timesPerFrames.at(i) - avgtime;
102 var /= timesPerFrames.size();
104 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
106 timePerFrame.append(avgtime);
107 timesPerFrames.clear();
116void RenderStatistics::printTotalStats()
118 int count = timePerFrame.count();
125 for (int i = 0; i < count; ++i) {
126 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
127 maxTime = qMax(maxTime, timePerFrame.at(i));
128 avg += timePerFrame.at(i);
133 qDebug("----- Statistics -----");
134 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
135 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
136 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
137 qDebug("----------------------");
146 , originalQmlRaster(false)
151 , versionDetection(true)
152 , quitImmediately(false)
153 , resizeViewToRootItem(false)
160 bool originalQmlRaster;
165 bool versionDetection;
166 bool quitImmediately;
167 bool resizeViewToRootItem;
169 QString translationFile;
172#if defined(QMLSCENE_BUNDLE)
173QFileInfoList findQmlFiles(const QString &dirName)
179 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
180 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
182 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
183 if (fileInfo.isDir())
184 ret += findQmlFiles(fileInfo.filePath());
185 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
186 ret.append(fileInfo);
193static int displayOptionsDialog(Options *options)
197 QFormLayout *layout = new QFormLayout(&dialog);
199 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
200 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
202 Q_FOREACH (QFileInfo fileInfo, fileInfos)
203 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
205 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
206 originalCheckBox->setText("Use original QML viewer");
207 originalCheckBox->setChecked(options->originalQml);
209 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
210 fullscreenCheckBox->setText("Start fullscreen");
211 fullscreenCheckBox->setChecked(options->fullscreen);
213 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
214 maximizedCheckBox->setText("Start maximized");
215 maximizedCheckBox->setChecked(options->maximized);
217 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
220 QObject::connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
221 QObject::connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
223 layout->addRow("Qml file:", qmlFileComboBox);
224 layout->addWidget(originalCheckBox);
225 layout->addWidget(maximizedCheckBox);
226 layout->addWidget(fullscreenCheckBox);
227 layout->addWidget(buttonBox);
229 int result = dialog.exec();
230 if (result == QDialog::Accepted) {
231 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
232 QFileInfo fileInfo = variant.value<QFileInfo>();
234 if (fileInfo.canonicalFilePath().startsWith(":"))
235 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
237 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
238 options->originalQml = originalCheckBox->isChecked();
239 options->maximized = maximizedCheckBox->isChecked();
240 options->fullscreen = fullscreenCheckBox->isChecked();
246static bool checkVersion(const QUrl &url)
248 if (!qEnvironmentVariableIsEmpty("QMLSCENE_IMPORT_NAME"))
249 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
251 QString fileName = url.toLocalFile();
252 if (fileName.isEmpty()) {
253 qWarning("qmlscene: filename required.");
258 if (!f.open(QFile::ReadOnly | QFile::Text)) {
259 qWarning("qmlscene: failed to check version of file '%s', could not open...",
260 qPrintable(fileName));
264 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
265 QRegExp qt47("^\\s*import +Qt +4\\.7");
267 QTextStream stream(&f);
268 bool codeFound= false;
270 QString line = stream.readLine();
271 if (line.contains("{")) {
275 if (quick1.indexIn(line) >= 0)
276 import = quick1.cap(0).trimmed();
277 else if (qt47.indexIn(line) >= 0)
278 import = qt47.cap(0).trimmed();
280 if (!import.isNull()) {
281 qWarning("qmlscene: '%s' is no longer supported.\n"
282 "Use qmlviewer to load file '%s'.",
284 qPrintable(fileName));
293static void displayFileDialog(Options *options)
295#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
296 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
297 if (!fileName.isEmpty()) {
298 QFileInfo fi(fileName);
299 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
303 qWarning("No filename specified...");
307#ifndef QT_NO_TRANSLATION
308static void loadTranslationFile(QTranslator &translator, const QString& directory)
310 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
311 QCoreApplication::installTranslator(&translator);
315static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
317 QDir dir(directory+"/dummydata", "*.qml");
318 QStringList list = dir.entryList();
319 for (int i = 0; i < list.size(); ++i) {
320 QString qml = list.at(i);
321 QFile f(dir.filePath(qml));
322 f.open(QIODevice::ReadOnly);
323 QByteArray data = f.readAll();
324 QQmlComponent comp(&engine);
325 comp.setData(data, QUrl());
326 QObject *dummyData = comp.create();
329 QList<QQmlError> errors = comp.errors();
330 Q_FOREACH (const QQmlError &error, errors)
335 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
336 qml.truncate(qml.length()-4);
337 engine.rootContext()->setContextProperty(qml, dummyData);
338 dummyData->setParent(&engine);
343class DummyTestRootObject : public QObject
346 Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
349 DummyTestRootObject(QObject *o) : QObject(o) {}
351 bool windowShown() const { return false; }
354 void windowShownChanged();
357static QObject *s_testRootObject = nullptr;
358static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
361 if (!s_testRootObject) {
362 s_testRootObject = new DummyTestRootObject(engine);
364 return s_testRootObject;
369 qWarning("Usage: uqmlscene [options] <filename>");
371 qWarning(" Options:");
372 qWarning(" --maximized ............................... Run maximized");
373 qWarning(" --fullscreen .............................. Run fullscreen");
374 qWarning(" --transparent ............................. Make the window transparent");
375 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
376 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
377 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
378 qWarning(" --quit .................................... Quit immediately after starting");
379 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
380 qWarning(" -B <name> <file> .......................... Add a named bundle");
381 qWarning(" -translation <translationfile> ............ Set the language to run in");
387int main(int argc, char ** argv)
392 QVector<QPair<QString, QString> > bundles;
393 for (int i = 1; i < argc; ++i) {
394 if (*argv[i] != '-' && QFileInfo::exists(QFile::decodeName(argv[i]))) {
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#ifndef QT_NO_TRANSLATION
440 QTranslator translator;
441 QTranslator qtTranslator;
442 QString sysLocale = QLocale::system().name();
443 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
444 app.installTranslator(&translator);
445 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
446 app.installTranslator(&qtTranslator);
448 app.removeTranslator(&translator);
452 QTranslator qmlTranslator;
453 if (!options.translationFile.isEmpty()) {
454 if (qmlTranslator.load(options.translationFile)) {
455 app.installTranslator(&qmlTranslator);
457 qWarning() << "Could not load the translation file" << options.translationFile;
462 if (options.file.isEmpty())
463#if defined(QMLSCENE_BUNDLE)
464 displayOptionsDialog(&options);
466 displayFileDialog(&options);
471 new DebuggingController(&app);
473 if (!options.file.isEmpty()) {
474 if (!options.versionDetection || checkVersion(options.file)) {
475#ifndef QT_NO_TRANSLATION
476 QTranslator translator;
479 // TODO: as soon as the engine construction completes, the debug service is
480 // listening for connections. But actually we aren't ready to debug anything.
482 QQmlComponent *component = new QQmlComponent(&engine);
483 for (int i = 0; i < imports.size(); ++i)
484 engine.addImportPath(imports.at(i));
485 for (int i = 0; i < bundles.size(); ++i)
486 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
487 if (options.file.isLocalFile()) {
488 QFileInfo fi(options.file.toLocalFile());
489#ifndef QT_NO_TRANSLATION
490 loadTranslationFile(translator, fi.path());
492 loadDummyDataFiles(engine, fi.path());
494 QObject::connect(&engine, &QQmlEngine::quit, QCoreApplication::instance(), &QCoreApplication::quit);
496 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
498 component->loadUrl(options.file);
499 if ( !component->isReady() ) {
500 qWarning("%s", qPrintable(component->errorString()));
504 QObject *topLevel = component->create();
505 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
506 QQuickView* qxView = 0;
508 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
510 qxView = new QQuickView(&engine, nullptr);
512 // Set window default properties; the qml can still override them
513 QString oname = contentItem->objectName();
514 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
515 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
516 if (options.resizeViewToRootItem)
517 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
519 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
520 qxView->setContent(options.file, component, contentItem);
525 QSurfaceFormat surfaceFormat = window->requestedFormat();
526 if (options.multisample)
527 surfaceFormat.setSamples(16);
528 if (options.transparent) {
529 surfaceFormat.setAlphaBufferSize(8);
530 window->setClearBeforeRendering(true);
531 window->setColor(QColor(Qt::transparent));
532 window->setFlags(Qt::FramelessWindowHint);
534 window->setFormat(surfaceFormat);
536 if (options.fullscreen)
537 window->showFullScreen();
538 else if (options.maximized)
539 window->showMaximized();
544 if (options.quitImmediately)
545 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
547 // Now would be a good time to inform the debug service to start listening.
549 exitCode = app.exec();
551#ifdef QML_RUNTIME_TESTING
552 RenderStatistics::printTotalStats();
554 // Ready to exit. If we created qxView, it owns the component;
555 // otherwise, the ownership is still right here. Nobody deletes the engine
556 // (which is odd since the container constructor takes the engine pointer),
557 // 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