0d97ba190bc1a66057186ad77d368123a84e26ca
[profile/ivi/qtdeclarative.git] / tools / qmlscene / main.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the tools applications of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
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>
47
48 #include <QtGui/QGuiApplication>
49
50 #include <QtQml/qqml.h>
51 #include <QtQml/qqmlengine.h>
52 #include <QtQml/qqmlcomponent.h>
53 #include <QtQml/qqmlcontext.h>
54
55 #include <QtQuick/qquickitem.h>
56 #include <QtQuick/qquickview.h>
57
58 #include <private/qabstractanimation_p.h>
59
60 #ifdef QT_WIDGETS_LIB
61 #include <QtWidgets/QApplication>
62 #include <QtWidgets/QFileDialog>
63 #endif
64
65
66 #ifdef QML_RUNTIME_TESTING
67 class RenderStatistics
68 {
69 public:
70     static void updateStats();
71     static void printTotalStats();
72 private:
73     static QVector<qreal> timePerFrame;
74     static QVector<int> timesPerFrames;
75 };
76
77 QVector<qreal> RenderStatistics::timePerFrame;
78 QVector<int> RenderStatistics::timesPerFrames;
79
80 void RenderStatistics::updateStats()
81 {
82     static QTime time;
83     static int frames;
84     static int lastTime;
85
86     if (frames == 0) {
87         time.start();
88     } else {
89         int elapsed = time.elapsed();
90         timesPerFrames.append(elapsed - lastTime);
91         lastTime = elapsed;
92
93         if (elapsed > 5000) {
94             qreal avgtime = elapsed / (qreal) frames;
95             qreal var = 0;
96             for (int i = 0; i < timesPerFrames.size(); ++i) {
97                 qreal diff = timesPerFrames.at(i) - avgtime;
98                 var += diff * diff;
99             }
100             var /= timesPerFrames.size();
101
102             qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
103
104             timePerFrame.append(avgtime);
105             timesPerFrames.clear();
106             time.start();
107             lastTime = 0;
108             frames = 0;
109         }
110     }
111     ++frames;
112 }
113
114 void RenderStatistics::printTotalStats()
115 {
116     int count = timePerFrame.count();
117     if (count == 0)
118         return;
119
120     qreal minTime = 0;
121     qreal maxTime = 0;
122     qreal avg = 0;
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);
127     }
128     avg /= count;
129
130     qDebug(" ");
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("----------------------");
136     qDebug(" ");
137 }
138 #endif
139
140 class MyQQuickView : public QQuickView
141 {
142 public:
143     MyQQuickView() : QQuickView()
144     {
145         setResizeMode(QQuickView::SizeRootObjectToView);
146     }
147 };
148
149 struct Options
150 {
151     Options()
152         : originalQml(false)
153         , originalQmlRaster(false)
154         , maximized(false)
155         , fullscreen(false)
156         , clip(false)
157         , versionDetection(true)
158         , slowAnimations(false)
159         , quitImmediately(false)
160     {
161     }
162
163     QUrl file;
164     bool originalQml;
165     bool originalQmlRaster;
166     bool maximized;
167     bool fullscreen;
168     bool scenegraphOnGraphicsview;
169     bool clip;
170     bool versionDetection;
171     bool slowAnimations;
172     bool quitImmediately;
173 };
174
175 #if defined(QMLSCENE_BUNDLE)
176 Q_DECLARE_METATYPE(QFileInfo);
177 QFileInfoList findQmlFiles(const QString &dirName)
178 {
179     QDir dir(dirName);
180
181     QFileInfoList ret;
182     if (dir.exists()) {
183         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
184                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
185
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);
191         }
192     }
193
194     return ret;
195 }
196
197 static int displayOptionsDialog(Options *options)
198 {
199     QDialog dialog;
200
201     QFormLayout *layout = new QFormLayout(&dialog);
202
203     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
204     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
205
206     foreach (QFileInfo fileInfo, fileInfos)
207         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
208
209     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
210     originalCheckBox->setText("Use original QML viewer");
211     originalCheckBox->setChecked(options->originalQml);
212
213     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
214     fullscreenCheckBox->setText("Start fullscreen");
215     fullscreenCheckBox->setChecked(options->fullscreen);
216
217     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
218     maximizedCheckBox->setText("Start maximized");
219     maximizedCheckBox->setChecked(options->maximized);
220
221     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
222                                                        Qt::Horizontal,
223                                                        &dialog);
224     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
225     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
226
227     layout->addRow("Qml file:", qmlFileComboBox);
228     layout->addWidget(originalCheckBox);
229     layout->addWidget(maximizedCheckBox);
230     layout->addWidget(fullscreenCheckBox);
231     layout->addWidget(buttonBox);
232
233     int result = dialog.exec();
234     if (result == QDialog::Accepted) {
235         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
236         QFileInfo fileInfo = variant.value<QFileInfo>();
237
238         if (fileInfo.canonicalFilePath().startsWith(":"))
239             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
240         else
241             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
242         options->originalQml = originalCheckBox->isChecked();
243         options->maximized = maximizedCheckBox->isChecked();
244         options->fullscreen = fullscreenCheckBox->isChecked();
245     }
246     return result;
247 }
248 #endif
249
250 static bool checkVersion(const QUrl &url)
251 {
252     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
253         qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
254     }
255
256     QString fileName = url.toLocalFile();
257     if (fileName.isEmpty()) {
258         qWarning("qmlscene: filename required.");
259         return false;
260     }
261
262     QFile f(fileName);
263     if (!f.open(QFile::ReadOnly | QFile::Text)) {
264         qWarning("qmlscene: failed to check version of file '%s', could not open...",
265                  qPrintable(fileName));
266         return false;
267     }
268
269     QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
270     QRegExp qt47("^\\s*import +Qt +4\\.7");
271
272     QTextStream stream(&f);
273     bool codeFound= false;
274     while (!codeFound) {
275         QString line = stream.readLine();
276         if (line.contains("{")) {
277             codeFound = true;
278         } else {
279             QString import;
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();
284             }
285
286             if (!import.isNull()) {
287                 qWarning("qmlscene: '%s' is no longer supported.\n"
288                          "Use qmlviewer to load file '%s'.",
289                          qPrintable(import),
290                          qPrintable(fileName));
291                 return false;
292             }
293         }
294     }
295
296     return true;
297 }
298
299 static void displayFileDialog(Options *options)
300 {
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());
306     }
307 #else
308     Q_UNUSED(options);
309     qWarning("No filename specified...");
310 #endif
311 }
312
313 static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
314 {
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();
325
326         if(comp.isError()) {
327             QList<QQmlError> errors = comp.errors();
328             foreach (const QQmlError &error, errors) {
329                 qWarning() << error;
330             }
331         }
332
333         if (dummyData) {
334             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
335             qml.truncate(qml.length()-4);
336             engine.rootContext()->setContextProperty(qml, dummyData);
337             dummyData->setParent(&engine);
338         }
339     }
340 }
341
342 static void usage()
343 {
344     qWarning("Usage: qmlscene [options] <filename>");
345     qWarning(" ");
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");
353     qWarning("  -I <path> ................................. Add <path> to the list of import paths");
354     qWarning("  -B <name> <file> .......................... Add a named bundle");
355
356     qWarning(" ");
357     exit(1);
358 }
359
360 int main(int argc, char ** argv)
361 {
362     Options options;
363
364     QStringList imports;
365     QList<QPair<QString, QString> > bundles;
366     for (int i = 1; i < argc; ++i) {
367         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
368             options.file = QUrl::fromLocalFile(argv[i]);
369         } else {
370             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
371             if (lowerArgument == QLatin1String("--maximized"))
372                 options.maximized = true;
373             else if (lowerArgument == QLatin1String("--fullscreen"))
374                 options.fullscreen = true;
375             else if (lowerArgument == QLatin1String("--clip"))
376                 options.clip = true;
377             else if (lowerArgument == QLatin1String("--no-version-detection"))
378                 options.versionDetection = false;
379             else if (lowerArgument == QLatin1String("--slow-animations"))
380                 options.slowAnimations = true;
381             else if (lowerArgument == QLatin1String("--quit"))
382                 options.quitImmediately = true;
383             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
384                 imports.append(QString::fromLatin1(argv[++i]));
385             else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
386                 QString name = QString::fromLatin1(argv[++i]);
387                 QString file = QString::fromLatin1(argv[++i]);
388                 bundles.append(qMakePair(name, file));
389             } else if (lowerArgument == QLatin1String("--help")
390                      || lowerArgument == QLatin1String("-help")
391                      || lowerArgument == QLatin1String("--h")
392                      || lowerArgument == QLatin1String("-h"))
393                 usage();
394         }
395     }
396
397 #ifdef QT_WIDGETS_LIB
398     QApplication app(argc, argv);
399 #else
400     QGuiApplication app(argc, argv);
401 #endif
402     app.setApplicationName("QtQmlViewer");
403     app.setOrganizationName("Nokia");
404     app.setOrganizationDomain("nokia.com");
405
406     QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
407
408     if (options.file.isEmpty())
409 #if defined(QMLSCENE_BUNDLE)
410         displayOptionsDialog(&options);
411 #else
412         displayFileDialog(&options);
413 #endif
414
415     QWindow *window = 0;
416     QQmlEngine *engine = 0;
417
418     int exitCode = 0;
419
420     if (!options.file.isEmpty()) {
421         if (!options.versionDetection || checkVersion(options.file)) {
422             QQuickView *qxView = new MyQQuickView();
423             engine = qxView->engine();
424             for (int i = 0; i < imports.size(); ++i)
425                 engine->addImportPath(imports.at(i));
426             for (int i = 0; i < bundles.size(); ++i)
427                 engine->addNamedBundle(bundles.at(i).first, bundles.at(i).second);
428             window = qxView;
429             if (options.file.isLocalFile()) {
430                 QFileInfo fi(options.file.toLocalFile());
431                 loadDummyDataFiles(*engine, fi.path());
432             }
433             qxView->setSource(options.file);
434
435             QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
436
437             window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
438             if (options.fullscreen)
439                 window->showFullScreen();
440             else if (options.maximized)
441                 window->showMaximized();
442             else
443                 window->show();
444
445             if (options.quitImmediately) {
446                 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
447             }
448
449             exitCode = app.exec();
450
451             delete window;
452
453 #ifdef QML_RUNTIME_TESTING
454             RenderStatistics::printTotalStats();
455 #endif
456         }
457     }
458
459     return exitCode;
460 }
461