Implemented multiple windows and GL context sharing
[profile/ivi/qtdeclarative.git] / tools / qmlscene / main.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the tools applications of the Qt Toolkit.
8 **
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.
17 **
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.
21 **
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.
29 **
30 ** Other Usage
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.
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 <QtDeclarative/qdeclarative.h>
51 #include <QtDeclarative/qdeclarativeengine.h>
52 #include <QtDeclarative/qdeclarativecomponent.h>
53 #include <QtDeclarative/qdeclarativecontext.h>
54
55 #include <QtQuick/qquickitem.h>
56 #include <QtQuick/qquickview.h>
57
58
59 #ifdef QML_RUNTIME_TESTING
60 class RenderStatistics
61 {
62 public:
63     static void updateStats();
64     static void printTotalStats();
65 private:
66     static QVector<qreal> timePerFrame;
67     static QVector<int> timesPerFrames;
68 };
69
70 QVector<qreal> RenderStatistics::timePerFrame;
71 QVector<int> RenderStatistics::timesPerFrames;
72
73 void RenderStatistics::updateStats()
74 {
75     static QTime time;
76     static int frames;
77     static int lastTime;
78
79     if (frames == 0) {
80         time.start();
81     } else {
82         int elapsed = time.elapsed();
83         timesPerFrames.append(elapsed - lastTime);
84         lastTime = elapsed;
85
86         if (elapsed > 5000) {
87             qreal avgtime = elapsed / (qreal) frames;
88             qreal var = 0;
89             for (int i = 0; i < timesPerFrames.size(); ++i) {
90                 qreal diff = timesPerFrames.at(i) - avgtime;
91                 var += diff * diff;
92             }
93             var /= timesPerFrames.size();
94
95             qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
96
97             timePerFrame.append(avgtime);
98             timesPerFrames.clear();
99             time.start();
100             lastTime = 0;
101             frames = 0;
102         }
103     }
104     ++frames;
105 }
106
107 void RenderStatistics::printTotalStats()
108 {
109     int count = timePerFrame.count();
110     if (count == 0)
111         return;
112
113     qreal minTime = 0;
114     qreal maxTime = 0;
115     qreal avg = 0;
116     for (int i = 0; i < count; ++i) {
117         minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
118         maxTime = qMax(maxTime, timePerFrame.at(i));
119         avg += timePerFrame.at(i);
120     }
121     avg /= count;
122
123     qDebug(" ");
124     qDebug("----- Statistics -----");
125     qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
126     qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
127     qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
128     qDebug("----------------------");
129     qDebug(" ");
130 }
131 #endif
132
133 class MyQQuickView : public QQuickView
134 {
135 public:
136     MyQQuickView() : QQuickView()
137     {
138         setResizeMode(QQuickView::SizeRootObjectToView);
139     }
140 };
141
142 struct Options
143 {
144     Options()
145         : originalQml(false)
146         , originalQmlRaster(false)
147         , maximized(false)
148         , fullscreen(false)
149         , clip(false)
150         , versionDetection(true)
151     {
152     }
153
154     QUrl file;
155     bool originalQml;
156     bool originalQmlRaster;
157     bool maximized;
158     bool fullscreen;
159     bool scenegraphOnGraphicsview;
160     bool clip;
161     bool versionDetection;
162 };
163
164 #if defined(QMLSCENE_BUNDLE)
165 Q_DECLARE_METATYPE(QFileInfo);
166 QFileInfoList findQmlFiles(const QString &dirName)
167 {
168     QDir dir(dirName);
169
170     QFileInfoList ret;
171     if (dir.exists()) {
172         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
173                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
174
175         foreach (QFileInfo fileInfo, fileInfos) {
176             if (fileInfo.isDir())
177                 ret += findQmlFiles(fileInfo.filePath());
178             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
179                 ret.append(fileInfo);
180         }
181     }
182
183     return ret;
184 }
185
186 static int displayOptionsDialog(Options *options)
187 {
188     QDialog dialog;
189
190     QFormLayout *layout = new QFormLayout(&dialog);
191
192     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
193     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
194
195     foreach (QFileInfo fileInfo, fileInfos)
196         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
197
198     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
199     originalCheckBox->setText("Use original QML viewer");
200     originalCheckBox->setChecked(options->originalQml);
201
202     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
203     fullscreenCheckBox->setText("Start fullscreen");
204     fullscreenCheckBox->setChecked(options->fullscreen);
205
206     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
207     maximizedCheckBox->setText("Start maximized");
208     maximizedCheckBox->setChecked(options->maximized);
209
210     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
211                                                        Qt::Horizontal,
212                                                        &dialog);
213     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
214     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
215
216     layout->addRow("Qml file:", qmlFileComboBox);
217     layout->addWidget(originalCheckBox);
218     layout->addWidget(maximizedCheckBox);
219     layout->addWidget(fullscreenCheckBox);
220     layout->addWidget(buttonBox);
221
222     int result = dialog.exec();
223     if (result == QDialog::Accepted) {
224         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
225         QFileInfo fileInfo = variant.value<QFileInfo>();
226
227         if (fileInfo.canonicalFilePath().startsWith(":"))
228             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
229         else
230             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
231         options->originalQml = originalCheckBox->isChecked();
232         options->maximized = maximizedCheckBox->isChecked();
233         options->fullscreen = fullscreenCheckBox->isChecked();
234     }
235     return result;
236 }
237 #endif
238
239 static void checkAndAdaptVersion(const QUrl &url)
240 {
241     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
242         return;
243     }
244
245     QString fileName = url.toLocalFile();
246     if (fileName.isEmpty())
247         return;
248
249     QFile f(fileName);
250     if (!f.open(QFile::ReadOnly | QFile::Text)) {
251         qWarning("qmlscene: failed to check version of file '%s', could not open...",
252                  qPrintable(fileName));
253         return;
254     }
255
256     QRegExp quick1("^\\s*import +QtQuick +1\\.");
257     QRegExp quick2("^\\s*import +QtQuick +2\\.");
258     QRegExp qt47("^\\s*import +Qt +4\\.7");
259
260     QString envToWrite;
261     QString compat;
262
263     QTextStream stream(&f);
264     bool codeFound= false;
265     while (!codeFound) {
266         QString line = stream.readLine();
267         if (line.contains("{"))
268             codeFound = true;
269         if (envToWrite.isEmpty() && quick1.indexIn(line) >= 0) {
270             envToWrite = QLatin1String("quick1");
271             compat = QLatin1String("QtQuick 1.0");
272         } else if (envToWrite.isEmpty() && qt47.indexIn(line) >= 0) {
273             envToWrite = QLatin1String("qt");
274             compat = QLatin1String("Qt 4.7");
275         } else if (quick2.indexIn(line) >= 0) {
276             envToWrite.clear();
277             compat.clear();
278             break;
279         }
280     }
281
282     if (!envToWrite.isEmpty()) {
283         qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
284         if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
285             qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
286     }
287 }
288
289 static void displayFileDialog(Options *options)
290 {
291 #ifdef QT_WIDGETS_LIB
292     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
293     if (!fileName.isEmpty()) {
294         QFileInfo fi(fileName);
295         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
296     }
297 #else
298     Q_UNUSED(options);
299     qWarning("No filename specified...");
300 #endif
301 }
302
303 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
304 {
305     QDir dir(directory+"/dummydata", "*.qml");
306     QStringList list = dir.entryList();
307     for (int i = 0; i < list.size(); ++i) {
308         QString qml = list.at(i);
309         QFile f(dir.filePath(qml));
310         f.open(QIODevice::ReadOnly);
311         QByteArray data = f.readAll();
312         QDeclarativeComponent comp(&engine);
313         comp.setData(data, QUrl());
314         QObject *dummyData = comp.create();
315
316         if(comp.isError()) {
317             QList<QDeclarativeError> errors = comp.errors();
318             foreach (const QDeclarativeError &error, errors) {
319                 qWarning() << error;
320             }
321         }
322
323         if (dummyData) {
324             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
325             qml.truncate(qml.length()-4);
326             engine.rootContext()->setContextProperty(qml, dummyData);
327             dummyData->setParent(&engine);
328         }
329     }
330 }
331
332 static void usage()
333 {
334     qWarning("Usage: qmlscene [options] <filename>");
335     qWarning(" ");
336     qWarning(" options:");
337     qWarning("  --maximized ............................... run maximized");
338     qWarning("  --fullscreen .............................. run fullscreen");
339     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
340     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
341
342     qWarning(" ");
343     exit(1);
344 }
345
346 int main(int argc, char ** argv)
347 {
348     Options options;
349
350     QStringList imports;
351     for (int i = 1; i < argc; ++i) {
352         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
353             options.file = QUrl::fromLocalFile(argv[i]);
354         } else {
355             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
356             if (lowerArgument == QLatin1String("--maximized"))
357                 options.maximized = true;
358             else if (lowerArgument == QLatin1String("--fullscreen"))
359                 options.fullscreen = true;
360             else if (lowerArgument == QLatin1String("--clip"))
361                 options.clip = true;
362             else if (lowerArgument == QLatin1String("--no-version-detection"))
363                 options.versionDetection = false;
364             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
365                 imports.append(QString::fromLatin1(argv[++i]));
366             else if (lowerArgument == QLatin1String("--help")
367                      || lowerArgument == QLatin1String("-help")
368                      || lowerArgument == QLatin1String("--h")
369                      || lowerArgument == QLatin1String("-h"))
370                 usage();
371         }
372     }
373
374     QGuiApplication app(argc, argv);
375     app.setApplicationName("QtQmlViewer");
376     app.setOrganizationName("Nokia");
377     app.setOrganizationDomain("nokia.com");
378
379     if (options.file.isEmpty())
380 #if defined(QMLSCENE_BUNDLE)
381         displayOptionsDialog(&options);
382 #else
383         displayFileDialog(&options);
384 #endif
385
386     QWindow *window = 0;
387     QDeclarativeEngine *engine = 0;
388
389     int exitCode = 0;
390
391     if (!options.file.isEmpty()) {
392         if (options.versionDetection)
393             checkAndAdaptVersion(options.file);
394         QQuickView *qxView = new MyQQuickView();
395         engine = qxView->engine();
396         for (int i = 0; i < imports.size(); ++i)
397             engine->addImportPath(imports.at(i));
398         window = qxView;
399         if (options.file.isLocalFile()) {
400             QFileInfo fi(options.file.toLocalFile());
401             loadDummyDataFiles(*engine, fi.path());
402         }
403         qxView->setSource(options.file);
404
405         QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
406
407         window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
408         if (options.fullscreen)
409             window->showFullScreen();
410         else if (options.maximized)
411             window->showMaximized();
412         else
413             window->show();
414
415         exitCode = app.exec();
416
417         delete window;
418
419 #ifdef QML_RUNTIME_TESTING
420         RenderStatistics::printTotalStats();
421 #endif
422     }
423
424     return exitCode;
425 }
426