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 <QtGui/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 <QtGui/QFormLayout>
51 #include <QtGui/QComboBox>
52 #include <QtGui/QCheckBox>
53 #include <QtGui/QDialog>
54 #include <QtGui/QDialogButtonBox>
55 #include <QtGui/QFileDialog>
56 #include <QtGui/QGraphicsView>
58 #include <QtDeclarative/qdeclarativecontext.h>
60 // ### This should be private API
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("----------------------");
147 static QGLFormat getFormat()
149 QGLFormat f = QGLFormat::defaultFormat();
150 f.setSampleBuffers(!qApp->arguments().contains("--no-multisample"));
151 f.setSwapInterval(qApp->arguments().contains("--nonblocking-swap") ? 0 : 1);
152 f.setStereo(qApp->arguments().contains("--stereo"));
156 class MyQSGView : public QSGView
159 MyQSGView() : QSGView(getFormat())
161 setResizeMode(QSGView::SizeRootObjectToView);
165 void paintEvent(QPaintEvent *e) {
166 QSGView::paintEvent(e);
168 #ifdef QML_RUNTIME_TESTING
169 // RenderStatistics::updateStats();
172 static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
173 if (continuousUpdate)
178 class MyDeclarativeView: public QDeclarativeView
181 MyDeclarativeView(QWidget *parent = 0) : QDeclarativeView(parent)
183 setResizeMode(QDeclarativeView::SizeRootObjectToView);
187 void paintEvent(QPaintEvent *event)
189 QDeclarativeView::paintEvent(event);
191 #ifdef QML_RUNTIME_TESTING
192 RenderStatistics::updateStats();
195 static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
196 if (continuousUpdate)
201 #ifndef QT_NO_SCENEGRAPHITEM
202 class MyGraphicsView: public QGraphicsView
205 MyGraphicsView(bool clip, QWidget *parent = 0) : QGraphicsView(parent)
207 setViewport(new QGLWidget(getFormat()));
209 scene.addItem(&item);
210 item.setFlag(QGraphicsItem::ItemClipsToShape, clip);
211 QGraphicsTextItem *text;
212 text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
215 text->setDefaultTextColor(Qt::black);
216 text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
219 text->setDefaultTextColor(Qt::yellow);
222 SceneGraphItem *sceneGraphItem() { return &item; }
225 void paintEvent(QPaintEvent *event)
227 QGraphicsView::paintEvent(event);
229 #ifdef QML_RUNTIME_TESTING
230 RenderStatistics::updateStats();
233 static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
234 if (continuousUpdate)
235 QGraphicsView::scene()->update();
238 QGraphicsScene scene;
247 , originalQmlRaster(false)
250 , scenegraphOnGraphicsview(false)
252 , versionDetection(true)
259 bool originalQmlRaster;
262 bool scenegraphOnGraphicsview;
264 bool versionDetection;
268 #if defined(QMLSCENE_BUNDLE)
269 Q_DECLARE_METATYPE(QFileInfo);
270 QFileInfoList findQmlFiles(const QString &dirName)
276 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
277 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
279 foreach (QFileInfo fileInfo, fileInfos) {
280 if (fileInfo.isDir())
281 ret += findQmlFiles(fileInfo.filePath());
282 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
283 ret.append(fileInfo);
290 static int displayOptionsDialog(Options *options)
294 QFormLayout *layout = new QFormLayout(&dialog);
296 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
297 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
299 foreach (QFileInfo fileInfo, fileInfos)
300 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
302 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
303 originalCheckBox->setText("Use original QML viewer");
304 originalCheckBox->setChecked(options->originalQml);
306 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
307 fullscreenCheckBox->setText("Start fullscreen");
308 fullscreenCheckBox->setChecked(options->fullscreen);
310 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
311 maximizedCheckBox->setText("Start maximized");
312 maximizedCheckBox->setChecked(options->maximized);
314 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
317 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
318 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
320 layout->addRow("Qml file:", qmlFileComboBox);
321 layout->addWidget(originalCheckBox);
322 layout->addWidget(maximizedCheckBox);
323 layout->addWidget(fullscreenCheckBox);
324 layout->addWidget(buttonBox);
326 int result = dialog.exec();
327 if (result == QDialog::Accepted) {
328 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
329 QFileInfo fileInfo = variant.value<QFileInfo>();
331 if (fileInfo.canonicalFilePath().startsWith(":"))
332 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
334 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
335 options->originalQml = originalCheckBox->isChecked();
336 options->maximized = maximizedCheckBox->isChecked();
337 options->fullscreen = fullscreenCheckBox->isChecked();
343 static void checkAndAdaptVersion(const QUrl &url)
345 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
349 QString fileName = url.toLocalFile();
350 if (fileName.isEmpty())
354 if (!f.open(QFile::ReadOnly | QFile::Text)) {
355 qWarning("qmlscene: failed to check version of file '%s', could not open...",
356 qPrintable(fileName));
360 QRegExp quick1("^\\s*import +QtQuick +1\\.");
361 QRegExp quick2("^\\s*import +QtQuick +2\\.");
362 QRegExp qt47("^\\s*import +Qt +4\\.7");
367 QTextStream stream(&f);
368 bool codeFound= false;
370 QString line = stream.readLine();
371 if (line.contains("{"))
373 if (envToWrite.isEmpty() && quick1.indexIn(line) >= 0) {
374 envToWrite = QLatin1String("quick1");
375 compat = QLatin1String("QtQuick 1.0");
376 } else if (envToWrite.isEmpty() && qt47.indexIn(line) >= 0) {
377 envToWrite = QLatin1String("qt");
378 compat = QLatin1String("Qt 4.7");
379 } else if (quick2.indexIn(line) >= 0) {
386 if (!envToWrite.isEmpty()) {
387 qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
388 if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
389 qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
393 static void displayFileDialog(Options *options)
395 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
396 if (!fileName.isEmpty()) {
397 QFileInfo fi(fileName);
398 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
402 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
404 QDir dir(directory+"/dummydata", "*.qml");
405 QStringList list = dir.entryList();
406 for (int i = 0; i < list.size(); ++i) {
407 QString qml = list.at(i);
408 QFile f(dir.filePath(qml));
409 f.open(QIODevice::ReadOnly);
410 QByteArray data = f.readAll();
411 QDeclarativeComponent comp(&engine);
412 comp.setData(data, QUrl());
413 QObject *dummyData = comp.create();
416 QList<QDeclarativeError> errors = comp.errors();
417 foreach (const QDeclarativeError &error, errors) {
423 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
424 qml.truncate(qml.length()-4);
425 engine.rootContext()->setContextProperty(qml, dummyData);
426 dummyData->setParent(&engine);
433 qWarning("Usage: qmlscene [options] <filename>");
435 qWarning(" options:");
436 qWarning(" --maximized ............................... run maximized");
437 qWarning(" --fullscreen .............................. run fullscreen");
438 qWarning(" --original-qml ............................ run using QGraphicsView instead of scenegraph (OpenGL engine)");
439 qWarning(" --original-qml-raster ..................... run using QGraphicsView instead of scenegraph (Raster engine)");
440 qWarning(" --no-multisample .......................... Disable multisampling (anti-aliasing)");
441 qWarning(" --continuous-update ....................... Continuously render the scene");
442 qWarning(" --nonblocking-swap ........................ Do not wait for v-sync to swap buffers");
443 qWarning(" --stereo .................................. Enable stereo on the GL context");
444 #ifndef QT_NO_SCENEGRAPHITEM
445 qWarning(" --sg-on-gv [--clip] ....................... Scenegraph on graphicsview (and clip to item)");
447 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
448 qWarning(" --no-vsync-animations ..................... Do not use vsync based animations");
454 int main(int argc, char ** argv)
457 QApplication::setAttribute(Qt::AA_X11InitThreads);
463 for (int i = 1; i < argc; ++i) {
464 if (*argv[i] != '-' && QFileInfo(argv[i]).exists())
465 options.file = QUrl::fromLocalFile(argv[i]);
466 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml"))
467 options.originalQml = true;
468 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml-raster"))
469 options.originalQmlRaster = true;
470 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--maximized"))
471 options.maximized = true;
472 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--fullscreen"))
473 options.fullscreen = true;
474 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--sg-on-gv"))
475 options.scenegraphOnGraphicsview = true;
476 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--clip"))
478 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-version-detection"))
479 options.versionDetection = false;
480 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("-i") && i + 1 < argc)
481 imports.append(QString::fromLatin1(argv[++i]));
482 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-vsync-animations"))
483 options.vsync = false;
484 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--help")
485 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-help")
486 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("--h")
487 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-h"))
491 QApplication::setGraphicsSystem("raster");
493 QApplication app(argc, argv);
494 app.setApplicationName("QtQmlViewer");
495 app.setOrganizationName("Nokia");
496 app.setOrganizationDomain("nokia.com");
498 if (options.file.isEmpty())
499 #if defined(QMLSCENE_BUNDLE)
500 displayOptionsDialog(&options);
502 displayFileDialog(&options);
506 QDeclarativeEngine *engine = 0;
510 if (!options.file.isEmpty()) {
511 #ifndef QT_NO_SCENEGRAPHITEM
512 if (options.scenegraphOnGraphicsview) {
513 MyGraphicsView *gvView = new MyGraphicsView(options.clip);
514 SceneGraphItem *item = gvView->sceneGraphItem();
515 engine = item->engine();
516 for (int i = 0; i < imports.size(); ++i)
517 engine->addImportPath(imports.at(i));
519 if (options.file.isLocalFile()) {
520 QFileInfo fi(options.file.toLocalFile());
521 loadDummyDataFiles(*engine, fi.path());
523 item->setSource(options.file);
526 if (!options.originalQml && !options.originalQmlRaster) {
527 if (options.versionDetection)
528 checkAndAdaptVersion(options.file);
529 QSGView *qxView = new MyQSGView();
530 qxView->setVSyncAnimations(options.vsync);
531 engine = qxView->engine();
532 for (int i = 0; i < imports.size(); ++i)
533 engine->addImportPath(imports.at(i));
535 if (options.file.isLocalFile()) {
536 QFileInfo fi(options.file.toLocalFile());
537 loadDummyDataFiles(*engine, fi.path());
539 qxView->setSource(options.file);
542 MyDeclarativeView *gvView = new MyDeclarativeView();
543 engine = gvView->engine();
544 for (int i = 0; i < imports.size(); ++i)
545 engine->addImportPath(imports.at(i));
547 if (options.file.isLocalFile()) {
548 QFileInfo fi(options.file.toLocalFile());
549 loadDummyDataFiles(*engine, fi.path());
551 gvView->setSource(options.file);
552 if (!options.originalQmlRaster) {
553 QGLWidget *viewport = new QGLWidget(getFormat());
554 gvView->setViewport(viewport);
558 QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
560 if (options.fullscreen)
561 view->showFullScreen();
562 else if (options.maximized)
563 view->showMaximized();
571 exitCode = app.exec();
575 #ifdef QML_RUNTIME_TESTING
576 RenderStatistics::printTotalStats();