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 qt47("^\\s*import +Qt +4\\.7");
366 QTextStream stream(&f);
367 bool codeFound= false;
368 while (!codeFound && envToWrite.isEmpty()) {
369 QString line = stream.readLine();
370 if (line.contains("{"))
372 if (quick1.indexIn(line) >= 0) {
373 envToWrite = QLatin1String("quick1");
374 compat = QLatin1String("QtQuick 1.0");
375 } else if (qt47.indexIn(line) >= 0) {
376 envToWrite = QLatin1String("qt");
377 compat = QLatin1String("Qt 4.7");
381 if (!envToWrite.isEmpty()) {
382 qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
383 if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
384 qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
388 static void displayFileDialog(Options *options)
390 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
391 if (!fileName.isEmpty()) {
392 QFileInfo fi(fileName);
393 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
397 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
399 QDir dir(directory+"/dummydata", "*.qml");
400 QStringList list = dir.entryList();
401 for (int i = 0; i < list.size(); ++i) {
402 QString qml = list.at(i);
403 QFile f(dir.filePath(qml));
404 f.open(QIODevice::ReadOnly);
405 QByteArray data = f.readAll();
406 QDeclarativeComponent comp(&engine);
407 comp.setData(data, QUrl());
408 QObject *dummyData = comp.create();
411 QList<QDeclarativeError> errors = comp.errors();
412 foreach (const QDeclarativeError &error, errors) {
418 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
419 qml.truncate(qml.length()-4);
420 engine.rootContext()->setContextProperty(qml, dummyData);
421 dummyData->setParent(&engine);
428 qWarning("Usage: qmlscene [options] <filename>");
430 qWarning(" options:");
431 qWarning(" --maximized ............................... run maximized");
432 qWarning(" --fullscreen .............................. run fullscreen");
433 qWarning(" --original-qml ............................ run using QGraphicsView instead of scenegraph (OpenGL engine)");
434 qWarning(" --original-qml-raster ..................... run using QGraphicsView instead of scenegraph (Raster engine)");
435 qWarning(" --no-multisample .......................... Disable multisampling (anti-aliasing)");
436 qWarning(" --continuous-update ....................... Continuously render the scene");
437 qWarning(" --nonblocking-swap ........................ Do not wait for v-sync to swap buffers");
438 qWarning(" --stereo .................................. Enable stereo on the GL context");
439 #ifndef QT_NO_SCENEGRAPHITEM
440 qWarning(" --sg-on-gv [--clip] ....................... Scenegraph on graphicsview (and clip to item)");
442 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
443 qWarning(" --no-vsync-animations ..................... Do not use vsync based animations");
449 int main(int argc, char ** argv)
452 QApplication::setAttribute(Qt::AA_X11InitThreads);
458 for (int i = 1; i < argc; ++i) {
459 if (*argv[i] != '-' && QFileInfo(argv[i]).exists())
460 options.file = QUrl::fromLocalFile(argv[i]);
461 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml"))
462 options.originalQml = true;
463 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml-raster"))
464 options.originalQmlRaster = true;
465 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--maximized"))
466 options.maximized = true;
467 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--fullscreen"))
468 options.fullscreen = true;
469 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--sg-on-gv"))
470 options.scenegraphOnGraphicsview = true;
471 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--clip"))
473 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-version-detection"))
474 options.versionDetection = false;
475 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("-i") && i + 1 < argc)
476 imports.append(QString::fromLatin1(argv[++i]));
477 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-vsync-animations"))
478 options.vsync = false;
479 else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--help")
480 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-help")
481 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("--h")
482 || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-h"))
486 QApplication::setGraphicsSystem("raster");
488 QApplication app(argc, argv);
489 app.setApplicationName("QtQmlViewer");
490 app.setOrganizationName("Nokia");
491 app.setOrganizationDomain("nokia.com");
493 if (options.file.isEmpty())
494 #if defined(QMLSCENE_BUNDLE)
495 displayOptionsDialog(&options);
497 displayFileDialog(&options);
501 QDeclarativeEngine *engine = 0;
505 if (!options.file.isEmpty()) {
506 #ifndef QT_NO_SCENEGRAPHITEM
507 if (options.scenegraphOnGraphicsview) {
508 MyGraphicsView *gvView = new MyGraphicsView(options.clip);
509 SceneGraphItem *item = gvView->sceneGraphItem();
510 engine = item->engine();
511 for (int i = 0; i < imports.size(); ++i)
512 engine->addImportPath(imports.at(i));
514 if (options.file.isLocalFile()) {
515 QFileInfo fi(options.file.toLocalFile());
516 loadDummyDataFiles(*engine, fi.path());
518 item->setSource(options.file);
521 if (!options.originalQml && !options.originalQmlRaster) {
522 if (options.versionDetection)
523 checkAndAdaptVersion(options.file);
524 QSGView *qxView = new MyQSGView();
525 qxView->setVSyncAnimations(options.vsync);
526 engine = qxView->engine();
527 for (int i = 0; i < imports.size(); ++i)
528 engine->addImportPath(imports.at(i));
530 if (options.file.isLocalFile()) {
531 QFileInfo fi(options.file.toLocalFile());
532 loadDummyDataFiles(*engine, fi.path());
534 qxView->setSource(options.file);
537 MyDeclarativeView *gvView = new MyDeclarativeView();
538 engine = gvView->engine();
539 for (int i = 0; i < imports.size(); ++i)
540 engine->addImportPath(imports.at(i));
542 if (options.file.isLocalFile()) {
543 QFileInfo fi(options.file.toLocalFile());
544 loadDummyDataFiles(*engine, fi.path());
546 gvView->setSource(options.file);
547 if (!options.originalQmlRaster) {
548 QGLWidget *viewport = new QGLWidget(getFormat());
549 gvView->setViewport(viewport);
553 QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
555 if (options.fullscreen)
556 view->showFullScreen();
557 else if (options.maximized)
558 view->showMaximized();
566 exitCode = app.exec();
570 #ifdef QML_RUNTIME_TESTING
571 RenderStatistics::printTotalStats();