1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the tools applications of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
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>
58 #include <private/qabstractanimation_p.h>
61 #include <QtWidgets/QApplication>
62 #include <QtWidgets/QFileDialog>
66 #ifdef QML_RUNTIME_TESTING
67 class RenderStatistics
70 static void updateStats();
71 static void printTotalStats();
73 static QVector<qreal> timePerFrame;
74 static QVector<int> timesPerFrames;
77 QVector<qreal> RenderStatistics::timePerFrame;
78 QVector<int> RenderStatistics::timesPerFrames;
80 void 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();
114 void 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("----------------------");
140 class MyQQuickView : public QQuickView
143 MyQQuickView() : QQuickView()
145 setResizeMode(QQuickView::SizeRootObjectToView);
153 , originalQmlRaster(false)
157 , versionDetection(true)
158 , slowAnimations(false)
159 , quitImmediately(false)
165 bool originalQmlRaster;
168 bool scenegraphOnGraphicsview;
170 bool versionDetection;
172 bool quitImmediately;
175 #if defined(QMLSCENE_BUNDLE)
176 Q_DECLARE_METATYPE(QFileInfo);
177 QFileInfoList findQmlFiles(const QString &dirName)
183 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
184 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
186 foreach (QFileInfo fileInfo, fileInfos) {
187 if (fileInfo.isDir())
188 ret += findQmlFiles(fileInfo.filePath());
189 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
190 ret.append(fileInfo);
197 static int displayOptionsDialog(Options *options)
201 QFormLayout *layout = new QFormLayout(&dialog);
203 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
204 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
206 foreach (QFileInfo fileInfo, fileInfos)
207 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
209 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
210 originalCheckBox->setText("Use original QML viewer");
211 originalCheckBox->setChecked(options->originalQml);
213 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
214 fullscreenCheckBox->setText("Start fullscreen");
215 fullscreenCheckBox->setChecked(options->fullscreen);
217 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
218 maximizedCheckBox->setText("Start maximized");
219 maximizedCheckBox->setChecked(options->maximized);
221 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
224 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
225 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
227 layout->addRow("Qml file:", qmlFileComboBox);
228 layout->addWidget(originalCheckBox);
229 layout->addWidget(maximizedCheckBox);
230 layout->addWidget(fullscreenCheckBox);
231 layout->addWidget(buttonBox);
233 int result = dialog.exec();
234 if (result == QDialog::Accepted) {
235 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
236 QFileInfo fileInfo = variant.value<QFileInfo>();
238 if (fileInfo.canonicalFilePath().startsWith(":"))
239 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
241 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
242 options->originalQml = originalCheckBox->isChecked();
243 options->maximized = maximizedCheckBox->isChecked();
244 options->fullscreen = fullscreenCheckBox->isChecked();
250 static bool checkVersion(const QUrl &url)
252 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
253 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
256 QString fileName = url.toLocalFile();
257 if (fileName.isEmpty()) {
258 qWarning("qmlscene: filename required.");
263 if (!f.open(QFile::ReadOnly | QFile::Text)) {
264 qWarning("qmlscene: failed to check version of file '%s', could not open...",
265 qPrintable(fileName));
269 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
270 QRegExp qt47("^\\s*import +Qt +4\\.7");
272 QTextStream stream(&f);
273 bool codeFound= false;
275 QString line = stream.readLine();
276 if (line.contains("{")) {
280 if (quick1.indexIn(line) >= 0) {
281 import = quick1.cap(0).trimmed();
282 } else if (qt47.indexIn(line) >= 0) {
283 import = qt47.cap(0).trimmed();
286 if (!import.isNull()) {
287 qWarning("qmlscene: '%s' is no longer supported.\n"
288 "Use qmlviewer to load file '%s'.",
290 qPrintable(fileName));
299 static void displayFileDialog(Options *options)
301 #ifdef QT_WIDGETS_LIB
302 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
303 if (!fileName.isEmpty()) {
304 QFileInfo fi(fileName);
305 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
309 qWarning("No filename specified...");
313 static 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 foreach (const QQmlError &error, errors) {
334 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
335 qml.truncate(qml.length()-4);
336 engine.rootContext()->setContextProperty(qml, dummyData);
337 dummyData->setParent(&engine);
344 qWarning("Usage: qmlscene [options] <filename>");
346 qWarning(" options:");
347 qWarning(" --maximized ............................... run maximized");
348 qWarning(" --fullscreen .............................. run fullscreen");
349 qWarning(" --no-multisample .......................... Disable multisampling (anti-aliasing)");
350 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
351 qWarning(" --slow-animations ......................... Run all animations in slow motion");
352 qWarning(" --quit .................................... Quit immediately after starting");
358 int main(int argc, char ** argv)
363 for (int i = 1; i < argc; ++i) {
364 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
365 options.file = QUrl::fromLocalFile(argv[i]);
367 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
368 if (lowerArgument == QLatin1String("--maximized"))
369 options.maximized = true;
370 else if (lowerArgument == QLatin1String("--fullscreen"))
371 options.fullscreen = true;
372 else if (lowerArgument == QLatin1String("--clip"))
374 else if (lowerArgument == QLatin1String("--no-version-detection"))
375 options.versionDetection = false;
376 else if (lowerArgument == QLatin1String("--slow-animations"))
377 options.slowAnimations = true;
378 else if (lowerArgument == QLatin1String("--quit"))
379 options.quitImmediately = true;
380 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
381 imports.append(QString::fromLatin1(argv[++i]));
382 else if (lowerArgument == QLatin1String("--help")
383 || lowerArgument == QLatin1String("-help")
384 || lowerArgument == QLatin1String("--h")
385 || lowerArgument == QLatin1String("-h"))
390 #ifdef QT_WIDGETS_LIB
391 QApplication app(argc, argv);
393 QGuiApplication app(argc, argv);
395 app.setApplicationName("QtQmlViewer");
396 app.setOrganizationName("Nokia");
397 app.setOrganizationDomain("nokia.com");
399 QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
401 if (options.file.isEmpty())
402 #if defined(QMLSCENE_BUNDLE)
403 displayOptionsDialog(&options);
405 displayFileDialog(&options);
409 QQmlEngine *engine = 0;
413 if (!options.file.isEmpty()) {
414 if (!options.versionDetection || checkVersion(options.file)) {
415 QQuickView *qxView = new MyQQuickView();
416 engine = qxView->engine();
417 for (int i = 0; i < imports.size(); ++i)
418 engine->addImportPath(imports.at(i));
420 if (options.file.isLocalFile()) {
421 QFileInfo fi(options.file.toLocalFile());
422 loadDummyDataFiles(*engine, fi.path());
424 qxView->setSource(options.file);
426 QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
428 window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
429 if (options.fullscreen)
430 window->showFullScreen();
431 else if (options.maximized)
432 window->showMaximized();
436 if (options.quitImmediately) {
437 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
440 exitCode = app.exec();
444 #ifdef QML_RUNTIME_TESTING
445 RenderStatistics::printTotalStats();