Add I18N support to qmlscene
[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 Q_DECLARE_METATYPE(QFileInfo);
175 QFileInfoList findQmlFiles(const QString &dirName)
176 {
177     QDir dir(dirName);
178
179     QFileInfoList ret;
180     if (dir.exists()) {
181         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
182                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
183
184         foreach (QFileInfo fileInfo, fileInfos) {
185             if (fileInfo.isDir())
186                 ret += findQmlFiles(fileInfo.filePath());
187             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
188                 ret.append(fileInfo);
189         }
190     }
191
192     return ret;
193 }
194
195 static int displayOptionsDialog(Options *options)
196 {
197     QDialog dialog;
198
199     QFormLayout *layout = new QFormLayout(&dialog);
200
201     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
202     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
203
204     foreach (QFileInfo fileInfo, fileInfos)
205         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
206
207     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
208     originalCheckBox->setText("Use original QML viewer");
209     originalCheckBox->setChecked(options->originalQml);
210
211     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
212     fullscreenCheckBox->setText("Start fullscreen");
213     fullscreenCheckBox->setChecked(options->fullscreen);
214
215     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
216     maximizedCheckBox->setText("Start maximized");
217     maximizedCheckBox->setChecked(options->maximized);
218
219     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
220                                                        Qt::Horizontal,
221                                                        &dialog);
222     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
223     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
224
225     layout->addRow("Qml file:", qmlFileComboBox);
226     layout->addWidget(originalCheckBox);
227     layout->addWidget(maximizedCheckBox);
228     layout->addWidget(fullscreenCheckBox);
229     layout->addWidget(buttonBox);
230
231     int result = dialog.exec();
232     if (result == QDialog::Accepted) {
233         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
234         QFileInfo fileInfo = variant.value<QFileInfo>();
235
236         if (fileInfo.canonicalFilePath().startsWith(":"))
237             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
238         else
239             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
240         options->originalQml = originalCheckBox->isChecked();
241         options->maximized = maximizedCheckBox->isChecked();
242         options->fullscreen = fullscreenCheckBox->isChecked();
243     }
244     return result;
245 }
246 #endif
247
248 static bool checkVersion(const QUrl &url)
249 {
250     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
251         qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
252
253     QString fileName = url.toLocalFile();
254     if (fileName.isEmpty()) {
255         qWarning("qmlscene: filename required.");
256         return false;
257     }
258
259     QFile f(fileName);
260     if (!f.open(QFile::ReadOnly | QFile::Text)) {
261         qWarning("qmlscene: failed to check version of file '%s', could not open...",
262                  qPrintable(fileName));
263         return false;
264     }
265
266     QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
267     QRegExp qt47("^\\s*import +Qt +4\\.7");
268
269     QTextStream stream(&f);
270     bool codeFound= false;
271     while (!codeFound) {
272         QString line = stream.readLine();
273         if (line.contains("{")) {
274             codeFound = true;
275         } else {
276             QString import;
277             if (quick1.indexIn(line) >= 0)
278                 import = quick1.cap(0).trimmed();
279             else if (qt47.indexIn(line) >= 0)
280                 import = qt47.cap(0).trimmed();
281
282             if (!import.isNull()) {
283                 qWarning("qmlscene: '%s' is no longer supported.\n"
284                          "Use qmlviewer to load file '%s'.",
285                          qPrintable(import),
286                          qPrintable(fileName));
287                 return false;
288             }
289         }
290     }
291
292     return true;
293 }
294
295 static void displayFileDialog(Options *options)
296 {
297 #if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
298     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
299     if (!fileName.isEmpty()) {
300         QFileInfo fi(fileName);
301         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
302     }
303 #else
304     Q_UNUSED(options);
305     qWarning("No filename specified...");
306 #endif
307 }
308
309 static void loadTranslationFile(QTranslator &translator, const QString& directory)
310 {
311     translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
312     QApplication::installTranslator(&translator);
313 }
314
315 static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
316 {
317     QDir dir(directory+"/dummydata", "*.qml");
318     QStringList list = dir.entryList();
319     for (int i = 0; i < list.size(); ++i) {
320         QString qml = list.at(i);
321         QFile f(dir.filePath(qml));
322         f.open(QIODevice::ReadOnly);
323         QByteArray data = f.readAll();
324         QQmlComponent comp(&engine);
325         comp.setData(data, QUrl());
326         QObject *dummyData = comp.create();
327
328         if(comp.isError()) {
329             QList<QQmlError> errors = comp.errors();
330             foreach (const QQmlError &error, errors)
331                 qWarning() << error;
332         }
333
334         if (dummyData) {
335             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
336             qml.truncate(qml.length()-4);
337             engine.rootContext()->setContextProperty(qml, dummyData);
338             dummyData->setParent(&engine);
339         }
340     }
341 }
342
343 static void usage()
344 {
345     qWarning("Usage: qmlscene [options] <filename>");
346     qWarning(" ");
347     qWarning(" options:");
348     qWarning("  --maximized ............................... run maximized");
349     qWarning("  --fullscreen .............................. run fullscreen");
350     qWarning("  --transparent ............................. Make the window transparent");
351     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
352     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
353     qWarning("  --slow-animations ......................... Run all animations in slow motion");
354     qWarning("  --resize-to-root .......................... Resize the window to the size of the root item");
355     qWarning("  --quit .................................... Quit immediately after starting");
356     qWarning("  -I <path> ................................. Add <path> to the list of import paths");
357     qWarning("  -B <name> <file> .......................... Add a named bundle");
358     qWarning("  -translation <translationfile> ........... set the language to run in");
359
360     qWarning(" ");
361     exit(1);
362 }
363
364 int main(int argc, char ** argv)
365 {
366     Options options;
367
368     QStringList imports;
369     QList<QPair<QString, QString> > bundles;
370     for (int i = 1; i < argc; ++i) {
371         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
372             options.file = QUrl::fromLocalFile(argv[i]);
373         } else {
374             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
375             if (lowerArgument == QLatin1String("--maximized"))
376                 options.maximized = true;
377             else if (lowerArgument == QLatin1String("--fullscreen"))
378                 options.fullscreen = true;
379             else if (lowerArgument == QLatin1String("--transparent"))
380                 options.transparent = true;
381             else if (lowerArgument == QLatin1String("--clip"))
382                 options.clip = true;
383             else if (lowerArgument == QLatin1String("--no-version-detection"))
384                 options.versionDetection = false;
385             else if (lowerArgument == QLatin1String("--slow-animations"))
386                 options.slowAnimations = true;
387             else if (lowerArgument == QLatin1String("--quit"))
388                 options.quitImmediately = true;
389            else if (lowerArgument == QLatin1String("-translation"))
390                 options.translationFile = QLatin1String(argv[++i]);
391             else if (lowerArgument == QLatin1String("--resize-to-root"))
392                 options.resizeViewToRootItem = true;
393             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
394                 imports.append(QString::fromLatin1(argv[++i]));
395             else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
396                 QString name = QString::fromLatin1(argv[++i]);
397                 QString file = QString::fromLatin1(argv[++i]);
398                 bundles.append(qMakePair(name, file));
399             } else if (lowerArgument == QLatin1String("--help")
400                      || lowerArgument == QLatin1String("-help")
401                      || lowerArgument == QLatin1String("--h")
402                      || lowerArgument == QLatin1String("-h"))
403                 usage();
404         }
405     }
406
407 #ifdef QT_WIDGETS_LIB
408     QApplication app(argc, argv);
409 #else
410     QGuiApplication app(argc, argv);
411 #endif
412     app.setApplicationName("QtQmlViewer");
413     app.setOrganizationName("Nokia");
414     app.setOrganizationDomain("nokia.com");
415
416     QTranslator translator;
417     QTranslator qtTranslator;
418     QString sysLocale = QLocale::system().name();
419     if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
420         app.installTranslator(&translator);
421         if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
422             app.installTranslator(&qtTranslator);
423         } else {
424             app.removeTranslator(&translator);
425         }
426     }
427
428     QTranslator qmlTranslator;
429     if (!options.translationFile.isEmpty()) {
430         if (qmlTranslator.load(options.translationFile)) {
431             app.installTranslator(&qmlTranslator);
432         } else {
433             qWarning() << "Could not load the translation file" << options.translationFile;
434         }
435     }
436
437     QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
438
439     if (options.file.isEmpty())
440 #if defined(QMLSCENE_BUNDLE)
441         displayOptionsDialog(&options);
442 #else
443         displayFileDialog(&options);
444 #endif
445
446     QQmlEngine *engine = 0;
447
448     int exitCode = 0;
449
450     if (!options.file.isEmpty()) {
451         if (!options.versionDetection || checkVersion(options.file)) {
452             QTranslator translator;
453             QQuickView qxView;
454             engine = qxView.engine();
455             for (int i = 0; i < imports.size(); ++i)
456                 engine->addImportPath(imports.at(i));
457             for (int i = 0; i < bundles.size(); ++i)
458                 engine->addNamedBundle(bundles.at(i).first, bundles.at(i).second);
459             if (options.file.isLocalFile()) {
460                 QFileInfo fi(options.file.toLocalFile());
461                 loadTranslationFile(translator, fi.path());
462                 loadDummyDataFiles(*engine, fi.path());
463             }
464             qxView.setSource(options.file);
465
466             QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
467
468             if (options.resizeViewToRootItem)
469                 qxView.setResizeMode(QQuickView::SizeViewToRootObject);
470             else
471                 qxView.setResizeMode(QQuickView::SizeRootObjectToView);
472
473             if (options.transparent) {
474                 QSurfaceFormat surfaceFormat;
475                 surfaceFormat.setAlphaBufferSize(8);
476                 qxView.setFormat(surfaceFormat);
477                 qxView.setClearBeforeRendering(true);
478                 qxView.setColor(QColor(Qt::transparent));
479                 qxView.setWindowFlags(Qt::FramelessWindowHint);
480             }
481
482             qxView.setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
483
484             if (options.fullscreen)
485                 qxView.showFullScreen();
486             else if (options.maximized)
487                 qxView.showMaximized();
488             else
489                 qxView.show();
490
491             if (options.quitImmediately)
492                 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
493
494             exitCode = app.exec();
495
496 #ifdef QML_RUNTIME_TESTING
497             RenderStatistics::printTotalStats();
498 #endif
499         }
500     }
501
502     return exitCode;
503 }