Work around Q_DECLARE_METATYPE(QFileInfo) being added to QtCore
[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 #include <QtCore/QTranslator>
66 #include <QtCore/QLibraryInfo>
67
68 #ifdef QML_RUNTIME_TESTING
69 class RenderStatistics
70 {
71 public:
72     static void updateStats();
73     static void printTotalStats();
74 private:
75     static QVector<qreal> timePerFrame;
76     static QVector<int> timesPerFrames;
77 };
78
79 QVector<qreal> RenderStatistics::timePerFrame;
80 QVector<int> RenderStatistics::timesPerFrames;
81
82 void RenderStatistics::updateStats()
83 {
84     static QTime time;
85     static int frames;
86     static int lastTime;
87
88     if (frames == 0) {
89         time.start();
90     } else {
91         int elapsed = time.elapsed();
92         timesPerFrames.append(elapsed - lastTime);
93         lastTime = elapsed;
94
95         if (elapsed > 5000) {
96             qreal avgtime = elapsed / (qreal) frames;
97             qreal var = 0;
98             for (int i = 0; i < timesPerFrames.size(); ++i) {
99                 qreal diff = timesPerFrames.at(i) - avgtime;
100                 var += diff * diff;
101             }
102             var /= timesPerFrames.size();
103
104             qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
105
106             timePerFrame.append(avgtime);
107             timesPerFrames.clear();
108             time.start();
109             lastTime = 0;
110             frames = 0;
111         }
112     }
113     ++frames;
114 }
115
116 void RenderStatistics::printTotalStats()
117 {
118     int count = timePerFrame.count();
119     if (count == 0)
120         return;
121
122     qreal minTime = 0;
123     qreal maxTime = 0;
124     qreal avg = 0;
125     for (int i = 0; i < count; ++i) {
126         minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
127         maxTime = qMax(maxTime, timePerFrame.at(i));
128         avg += timePerFrame.at(i);
129     }
130     avg /= count;
131
132     qDebug(" ");
133     qDebug("----- Statistics -----");
134     qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
135     qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
136     qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
137     qDebug("----------------------");
138     qDebug(" ");
139 }
140 #endif
141
142 struct Options
143 {
144     Options()
145         : originalQml(false)
146         , originalQmlRaster(false)
147         , maximized(false)
148         , fullscreen(false)
149         , transparent(false)
150         , clip(false)
151         , versionDetection(true)
152         , slowAnimations(false)
153         , quitImmediately(false)
154         , resizeViewToRootItem(false)
155     {
156     }
157
158     QUrl file;
159     bool originalQml;
160     bool originalQmlRaster;
161     bool maximized;
162     bool fullscreen;
163     bool transparent;
164     bool scenegraphOnGraphicsview;
165     bool clip;
166     bool versionDetection;
167     bool slowAnimations;
168     bool quitImmediately;
169     bool resizeViewToRootItem;
170     QString translationFile;
171 };
172
173 #if defined(QMLSCENE_BUNDLE)
174 #ifndef QT_QFILEINFO_METATYPE_DEFINED
175 Q_DECLARE_METATYPE(QFileInfo);
176 #endif
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     QString fileName = url.toLocalFile();
256     if (fileName.isEmpty()) {
257         qWarning("qmlscene: filename required.");
258         return false;
259     }
260
261     QFile f(fileName);
262     if (!f.open(QFile::ReadOnly | QFile::Text)) {
263         qWarning("qmlscene: failed to check version of file '%s', could not open...",
264                  qPrintable(fileName));
265         return false;
266     }
267
268     QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
269     QRegExp qt47("^\\s*import +Qt +4\\.7");
270
271     QTextStream stream(&f);
272     bool codeFound= false;
273     while (!codeFound) {
274         QString line = stream.readLine();
275         if (line.contains("{")) {
276             codeFound = true;
277         } else {
278             QString import;
279             if (quick1.indexIn(line) >= 0)
280                 import = quick1.cap(0).trimmed();
281             else if (qt47.indexIn(line) >= 0)
282                 import = qt47.cap(0).trimmed();
283
284             if (!import.isNull()) {
285                 qWarning("qmlscene: '%s' is no longer supported.\n"
286                          "Use qmlviewer to load file '%s'.",
287                          qPrintable(import),
288                          qPrintable(fileName));
289                 return false;
290             }
291         }
292     }
293
294     return true;
295 }
296
297 static void displayFileDialog(Options *options)
298 {
299 #if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
300     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
301     if (!fileName.isEmpty()) {
302         QFileInfo fi(fileName);
303         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
304     }
305 #else
306     Q_UNUSED(options);
307     qWarning("No filename specified...");
308 #endif
309 }
310
311 static void loadTranslationFile(QTranslator &translator, const QString& directory)
312 {
313     translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
314     QApplication::installTranslator(&translator);
315 }
316
317 static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
318 {
319     QDir dir(directory+"/dummydata", "*.qml");
320     QStringList list = dir.entryList();
321     for (int i = 0; i < list.size(); ++i) {
322         QString qml = list.at(i);
323         QFile f(dir.filePath(qml));
324         f.open(QIODevice::ReadOnly);
325         QByteArray data = f.readAll();
326         QQmlComponent comp(&engine);
327         comp.setData(data, QUrl());
328         QObject *dummyData = comp.create();
329
330         if(comp.isError()) {
331             QList<QQmlError> errors = comp.errors();
332             foreach (const QQmlError &error, errors)
333                 qWarning() << error;
334         }
335
336         if (dummyData) {
337             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
338             qml.truncate(qml.length()-4);
339             engine.rootContext()->setContextProperty(qml, dummyData);
340             dummyData->setParent(&engine);
341         }
342     }
343 }
344
345 static void usage()
346 {
347     qWarning("Usage: qmlscene [options] <filename>");
348     qWarning(" ");
349     qWarning(" options:");
350     qWarning("  --maximized ............................... run maximized");
351     qWarning("  --fullscreen .............................. run fullscreen");
352     qWarning("  --transparent ............................. Make the window transparent");
353     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
354     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
355     qWarning("  --slow-animations ......................... Run all animations in slow motion");
356     qWarning("  --resize-to-root .......................... Resize the window to the size of the root item");
357     qWarning("  --quit .................................... Quit immediately after starting");
358     qWarning("  -I <path> ................................. Add <path> to the list of import paths");
359     qWarning("  -B <name> <file> .......................... Add a named bundle");
360     qWarning("  -translation <translationfile> ........... set the language to run in");
361
362     qWarning(" ");
363     exit(1);
364 }
365
366 int main(int argc, char ** argv)
367 {
368     Options options;
369
370     QStringList imports;
371     QList<QPair<QString, QString> > bundles;
372     for (int i = 1; i < argc; ++i) {
373         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
374             options.file = QUrl::fromLocalFile(argv[i]);
375         } else {
376             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
377             if (lowerArgument == QLatin1String("--maximized"))
378                 options.maximized = true;
379             else if (lowerArgument == QLatin1String("--fullscreen"))
380                 options.fullscreen = true;
381             else if (lowerArgument == QLatin1String("--transparent"))
382                 options.transparent = true;
383             else if (lowerArgument == QLatin1String("--clip"))
384                 options.clip = true;
385             else if (lowerArgument == QLatin1String("--no-version-detection"))
386                 options.versionDetection = false;
387             else if (lowerArgument == QLatin1String("--slow-animations"))
388                 options.slowAnimations = true;
389             else if (lowerArgument == QLatin1String("--quit"))
390                 options.quitImmediately = true;
391            else if (lowerArgument == QLatin1String("-translation"))
392                 options.translationFile = QLatin1String(argv[++i]);
393             else if (lowerArgument == QLatin1String("--resize-to-root"))
394                 options.resizeViewToRootItem = true;
395             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
396                 imports.append(QString::fromLatin1(argv[++i]));
397             else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
398                 QString name = QString::fromLatin1(argv[++i]);
399                 QString file = QString::fromLatin1(argv[++i]);
400                 bundles.append(qMakePair(name, file));
401             } else if (lowerArgument == QLatin1String("--help")
402                      || lowerArgument == QLatin1String("-help")
403                      || lowerArgument == QLatin1String("--h")
404                      || lowerArgument == QLatin1String("-h"))
405                 usage();
406         }
407     }
408
409 #ifdef QT_WIDGETS_LIB
410     QApplication app(argc, argv);
411 #else
412     QGuiApplication app(argc, argv);
413 #endif
414     app.setApplicationName("QtQmlViewer");
415     app.setOrganizationName("Nokia");
416     app.setOrganizationDomain("nokia.com");
417
418     QTranslator translator;
419     QTranslator qtTranslator;
420     QString sysLocale = QLocale::system().name();
421     if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
422         app.installTranslator(&translator);
423         if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
424             app.installTranslator(&qtTranslator);
425         } else {
426             app.removeTranslator(&translator);
427         }
428     }
429
430     QTranslator qmlTranslator;
431     if (!options.translationFile.isEmpty()) {
432         if (qmlTranslator.load(options.translationFile)) {
433             app.installTranslator(&qmlTranslator);
434         } else {
435             qWarning() << "Could not load the translation file" << options.translationFile;
436         }
437     }
438
439     QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
440
441     if (options.file.isEmpty())
442 #if defined(QMLSCENE_BUNDLE)
443         displayOptionsDialog(&options);
444 #else
445         displayFileDialog(&options);
446 #endif
447
448     QQmlEngine *engine = 0;
449
450     int exitCode = 0;
451
452     if (!options.file.isEmpty()) {
453         if (!options.versionDetection || checkVersion(options.file)) {
454             QTranslator translator;
455             QQuickView qxView;
456             engine = qxView.engine();
457             for (int i = 0; i < imports.size(); ++i)
458                 engine->addImportPath(imports.at(i));
459             for (int i = 0; i < bundles.size(); ++i)
460                 engine->addNamedBundle(bundles.at(i).first, bundles.at(i).second);
461             if (options.file.isLocalFile()) {
462                 QFileInfo fi(options.file.toLocalFile());
463                 loadTranslationFile(translator, fi.path());
464                 loadDummyDataFiles(*engine, fi.path());
465             }
466             qxView.setSource(options.file);
467
468             QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
469
470             if (options.resizeViewToRootItem)
471                 qxView.setResizeMode(QQuickView::SizeViewToRootObject);
472             else
473                 qxView.setResizeMode(QQuickView::SizeRootObjectToView);
474
475             if (options.transparent) {
476                 QSurfaceFormat surfaceFormat;
477                 surfaceFormat.setAlphaBufferSize(8);
478                 qxView.setFormat(surfaceFormat);
479                 qxView.setClearBeforeRendering(true);
480                 qxView.setColor(QColor(Qt::transparent));
481                 qxView.setWindowFlags(Qt::FramelessWindowHint);
482             }
483
484             qxView.setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
485
486             if (options.fullscreen)
487                 qxView.showFullScreen();
488             else if (options.maximized)
489                 qxView.showMaximized();
490             else
491                 qxView.show();
492
493             if (options.quitImmediately)
494                 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
495
496             exitCode = app.exec();
497
498 #ifdef QML_RUNTIME_TESTING
499             RenderStatistics::printTotalStats();
500 #endif
501         }
502     }
503
504     return exitCode;
505 }