1 /****************************************************************************
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the tools applications of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include <QtCore/qdebug.h>
43 #include <QtCore/qabstractanimation.h>
44 #include <QtWidgets/qapplication.h>
45 #include <QtDeclarative/qdeclarative.h>
46 #include <QtDeclarative/qdeclarativeengine.h>
47 #include <QtDeclarative/qdeclarativecomponent.h>
48 #include <QtQuick1/qdeclarativeview.h>
49 #include <QtCore/qdir.h>
50 #include <QtWidgets/QFormLayout>
51 #include <QtWidgets/QComboBox>
52 #include <QtWidgets/QCheckBox>
53 #include <QtWidgets/QDialog>
54 #include <QtWidgets/QDialogButtonBox>
55 #include <QtWidgets/QFileDialog>
56 #include <QtWidgets/QGraphicsView>
58 #include <QtDeclarative/qdeclarativecontext.h>
60 // ### This should be private API
61 #include <QtQuick/qquickitem.h>
62 #include <QtQuick/qquickview.h>
64 #define QT_NO_SCENEGRAPHITEM
66 #ifndef QT_NO_SCENEGRAPHITEM
67 #include "scenegraphitem.h"
70 #include <QtCore/qmath.h>
72 #ifdef QML_RUNTIME_TESTING
73 class RenderStatistics
76 static void updateStats();
77 static void printTotalStats();
79 static QVector<qreal> timePerFrame;
80 static QVector<int> timesPerFrames;
83 QVector<qreal> RenderStatistics::timePerFrame;
84 QVector<int> RenderStatistics::timesPerFrames;
86 void RenderStatistics::updateStats()
95 int elapsed = time.elapsed();
96 timesPerFrames.append(elapsed - lastTime);
100 qreal avgtime = elapsed / (qreal) frames;
102 for (int i = 0; i < timesPerFrames.size(); ++i) {
103 qreal diff = timesPerFrames.at(i) - avgtime;
106 var /= timesPerFrames.size();
108 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
110 timePerFrame.append(avgtime);
111 timesPerFrames.clear();
120 void RenderStatistics::printTotalStats()
122 int count = timePerFrame.count();
129 for (int i = 0; i < count; ++i) {
130 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
131 maxTime = qMax(maxTime, timePerFrame.at(i));
132 avg += timePerFrame.at(i);
137 qDebug("----- Statistics -----");
138 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
139 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
140 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
141 qDebug("----------------------");
146 class MyQQuickView : public QQuickView
149 MyQQuickView() : QQuickView()
151 setResizeMode(QQuickView::SizeRootObjectToView);
155 class MyDeclarativeView: public QDeclarativeView
158 MyDeclarativeView(QWidget *parent = 0) : QDeclarativeView(parent)
160 setResizeMode(QDeclarativeView::SizeRootObjectToView);
164 #ifndef QT_NO_SCENEGRAPHITEM
165 class MyGraphicsView: public QGraphicsView
168 MyGraphicsView(bool clip, QWidget *parent = 0) : QGraphicsView(parent)
170 setViewport(new QGLWidget(getFormat()));
172 scene.addItem(&item);
173 item.setFlag(QGraphicsItem::ItemClipsToShape, clip);
174 QGraphicsTextItem *text;
175 text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
178 text->setDefaultTextColor(Qt::black);
179 text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
182 text->setDefaultTextColor(Qt::yellow);
185 SceneGraphItem *sceneGraphItem() { return &item; }
188 void paintEvent(QPaintEvent *event)
190 QGraphicsView::paintEvent(event);
192 #ifdef QML_RUNTIME_TESTING
193 RenderStatistics::updateStats();
196 static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
197 if (continuousUpdate)
198 QGraphicsView::scene()->update();
201 QGraphicsScene scene;
210 , originalQmlRaster(false)
213 , scenegraphOnGraphicsview(false)
215 , versionDetection(true)
222 bool originalQmlRaster;
225 bool scenegraphOnGraphicsview;
227 bool versionDetection;
231 #if defined(QMLSCENE_BUNDLE)
232 Q_DECLARE_METATYPE(QFileInfo);
233 QFileInfoList findQmlFiles(const QString &dirName)
239 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
240 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
242 foreach (QFileInfo fileInfo, fileInfos) {
243 if (fileInfo.isDir())
244 ret += findQmlFiles(fileInfo.filePath());
245 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
246 ret.append(fileInfo);
253 static int displayOptionsDialog(Options *options)
257 QFormLayout *layout = new QFormLayout(&dialog);
259 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
260 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
262 foreach (QFileInfo fileInfo, fileInfos)
263 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
265 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
266 originalCheckBox->setText("Use original QML viewer");
267 originalCheckBox->setChecked(options->originalQml);
269 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
270 fullscreenCheckBox->setText("Start fullscreen");
271 fullscreenCheckBox->setChecked(options->fullscreen);
273 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
274 maximizedCheckBox->setText("Start maximized");
275 maximizedCheckBox->setChecked(options->maximized);
277 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
280 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
281 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
283 layout->addRow("Qml file:", qmlFileComboBox);
284 layout->addWidget(originalCheckBox);
285 layout->addWidget(maximizedCheckBox);
286 layout->addWidget(fullscreenCheckBox);
287 layout->addWidget(buttonBox);
289 int result = dialog.exec();
290 if (result == QDialog::Accepted) {
291 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
292 QFileInfo fileInfo = variant.value<QFileInfo>();
294 if (fileInfo.canonicalFilePath().startsWith(":"))
295 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
297 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
298 options->originalQml = originalCheckBox->isChecked();
299 options->maximized = maximizedCheckBox->isChecked();
300 options->fullscreen = fullscreenCheckBox->isChecked();
306 static void checkAndAdaptVersion(const QUrl &url)
308 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
312 QString fileName = url.toLocalFile();
313 if (fileName.isEmpty())
317 if (!f.open(QFile::ReadOnly | QFile::Text)) {
318 qWarning("qmlscene: failed to check version of file '%s', could not open...",
319 qPrintable(fileName));
323 QRegExp quick1("^\\s*import +QtQuick +1\\.");
324 QRegExp quick2("^\\s*import +QtQuick +2\\.");
325 QRegExp qt47("^\\s*import +Qt +4\\.7");
330 QTextStream stream(&f);
331 bool codeFound= false;
333 QString line = stream.readLine();
334 if (line.contains("{"))
336 if (envToWrite.isEmpty() && quick1.indexIn(line) >= 0) {
337 envToWrite = QLatin1String("quick1");
338 compat = QLatin1String("QtQuick 1.0");
339 } else if (envToWrite.isEmpty() && qt47.indexIn(line) >= 0) {
340 envToWrite = QLatin1String("qt");
341 compat = QLatin1String("Qt 4.7");
342 } else if (quick2.indexIn(line) >= 0) {
349 if (!envToWrite.isEmpty()) {
350 qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
351 if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
352 qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
356 static void displayFileDialog(Options *options)
358 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
359 if (!fileName.isEmpty()) {
360 QFileInfo fi(fileName);
361 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
365 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
367 QDir dir(directory+"/dummydata", "*.qml");
368 QStringList list = dir.entryList();
369 for (int i = 0; i < list.size(); ++i) {
370 QString qml = list.at(i);
371 QFile f(dir.filePath(qml));
372 f.open(QIODevice::ReadOnly);
373 QByteArray data = f.readAll();
374 QDeclarativeComponent comp(&engine);
375 comp.setData(data, QUrl());
376 QObject *dummyData = comp.create();
379 QList<QDeclarativeError> errors = comp.errors();
380 foreach (const QDeclarativeError &error, errors) {
386 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
387 qml.truncate(qml.length()-4);
388 engine.rootContext()->setContextProperty(qml, dummyData);
389 dummyData->setParent(&engine);
396 qWarning("Usage: qmlscene [options] <filename>");
398 qWarning(" options:");
399 qWarning(" --maximized ............................... run maximized");
400 qWarning(" --fullscreen .............................. run fullscreen");
401 qWarning(" --original-qml ............................ run using QGraphicsView instead of scenegraph (OpenGL engine)");
402 qWarning(" --original-qml-raster ..................... run using QGraphicsView instead of scenegraph (Raster engine)");
403 qWarning(" --no-multisample .......................... Disable multisampling (anti-aliasing)");
404 qWarning(" --continuous-update ....................... Continuously render the scene");
405 qWarning(" --nonblocking-swap ........................ Do not wait for v-sync to swap buffers");
406 qWarning(" --stereo .................................. Enable stereo on the GL context");
407 #ifndef QT_NO_SCENEGRAPHITEM
408 qWarning(" --sg-on-gv [--clip] ....................... Scenegraph on graphicsview (and clip to item)");
410 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
411 qWarning(" --no-vsync-animations ..................... Do not use vsync based animations");
417 int main(int argc, char ** argv)
420 QApplication::setAttribute(Qt::AA_X11InitThreads);
426 for (int i = 1; i < argc; ++i) {
427 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
428 options.file = QUrl::fromLocalFile(argv[i]);
430 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
431 if (lowerArgument == QLatin1String("--original-qml"))
432 options.originalQml = true;
433 else if (lowerArgument == QLatin1String("--original-qml-raster"))
434 options.originalQmlRaster = true;
435 else if (lowerArgument == QLatin1String("--maximized"))
436 options.maximized = true;
437 else if (lowerArgument == QLatin1String("--fullscreen"))
438 options.fullscreen = true;
439 else if (lowerArgument == QLatin1String("--sg-on-gv"))
440 options.scenegraphOnGraphicsview = true;
441 else if (lowerArgument == QLatin1String("--clip"))
443 else if (lowerArgument == QLatin1String("--no-version-detection"))
444 options.versionDetection = false;
445 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
446 imports.append(QString::fromLatin1(argv[++i]));
447 else if (lowerArgument == QLatin1String("--no-vsync-animations"))
448 options.vsync = false;
449 else if (lowerArgument == QLatin1String("--help")
450 || lowerArgument == QLatin1String("-help")
451 || lowerArgument == QLatin1String("--h")
452 || lowerArgument == QLatin1String("-h"))
457 QApplication::setGraphicsSystem("raster");
459 QApplication app(argc, argv);
460 app.setApplicationName("QtQmlViewer");
461 app.setOrganizationName("Nokia");
462 app.setOrganizationDomain("nokia.com");
464 if (options.file.isEmpty())
465 #if defined(QMLSCENE_BUNDLE)
466 displayOptionsDialog(&options);
468 displayFileDialog(&options);
472 QDeclarativeEngine *engine = 0;
476 if (!options.file.isEmpty()) {
477 #ifndef QT_NO_SCENEGRAPHITEM
478 if (options.scenegraphOnGraphicsview) {
479 MyGraphicsView *gvView = new MyGraphicsView(options.clip);
480 SceneGraphItem *item = gvView->sceneGraphItem();
481 engine = item->engine();
482 for (int i = 0; i < imports.size(); ++i)
483 engine->addImportPath(imports.at(i));
485 if (options.file.isLocalFile()) {
486 QFileInfo fi(options.file.toLocalFile());
487 loadDummyDataFiles(*engine, fi.path());
489 item->setSource(options.file);
492 if (options.versionDetection)
493 checkAndAdaptVersion(options.file);
494 QQuickView *qxView = new MyQQuickView();
495 qxView->setVSyncAnimations(options.vsync);
496 engine = qxView->engine();
497 for (int i = 0; i < imports.size(); ++i)
498 engine->addImportPath(imports.at(i));
500 if (options.file.isLocalFile()) {
501 QFileInfo fi(options.file.toLocalFile());
502 loadDummyDataFiles(*engine, fi.path());
504 qxView->setSource(options.file);
506 QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
508 window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
509 if (options.fullscreen)
510 window->showFullScreen();
511 else if (options.maximized)
512 window->showMaximized();
521 exitCode = app.exec();
525 #ifdef QML_RUNTIME_TESTING
526 RenderStatistics::printTotalStats();