on c42e54e help sign in
562 lines 20 kB history raw
1/****************************************************************************
2**
3** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4** Contact: http://www.qt-project.org/legal
5**
6** This file is part of the tools applications of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Digia. For licensing terms and
14** conditions see http://qt.digia.com/licensing. For further information
15** use the contact form at http://qt.digia.com/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 2.1 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 2.1 requirements
23** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24**
25** In addition, as a special exception, Digia gives you certain additional
26** rights. These rights are described in the Digia Qt LGPL Exception
27** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28**
29** GNU General Public License Usage
30** Alternatively, this file may be used under the terms of the GNU
31** General Public License version 3.0 as published by the Free Software
32** Foundation and appearing in the file LICENSE.GPL included in the
33** packaging of this file. Please review the following information to
34** ensure the GNU General Public License version 3.0 requirements will be
35** met: http://www.gnu.org/copyleft/gpl.html.
36**
37**
38** $QT_END_LICENSE$
39**
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#ifdef QT_WIDGETS_LIB
59#include <QtWidgets/QApplication>
60#include <QtWidgets/QFileDialog>
61#endif
63#include <QtCore/QTranslator>
64#include <QtCore/QLibraryInfo>
66#define UQMLSCENE_DEBUG_ACTIVE_FOCUS 0
68#if UQMLSCENE_DEBUG_ACTIVE_FOCUS
69 #include "ActiveFocusLogger.h"
70#endif
72#ifdef QML_RUNTIME_TESTING
73class RenderStatistics
75public:
76 static void updateStats();
77 static void printTotalStats();
78private:
79 static QVector<qreal> timePerFrame;
80 static QVector<int> timesPerFrames;
81};
83QVector<qreal> RenderStatistics::timePerFrame;
84QVector<int> RenderStatistics::timesPerFrames;
86void RenderStatistics::updateStats()
88 static QTime time;
89 static int frames;
90 static int lastTime;
92 if (frames == 0) {
93 time.start();
94 } else {
95 int elapsed = time.elapsed();
96 timesPerFrames.append(elapsed - lastTime);
97 lastTime = elapsed;
99 if (elapsed > 5000) {
100 qreal avgtime = elapsed / (qreal) frames;
101 qreal var = 0;
102 for (int i = 0; i < timesPerFrames.size(); ++i) {
103 qreal diff = timesPerFrames.at(i) - avgtime;
104 var += diff * diff;
105 }
106 var /= timesPerFrames.size();
108 qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
110 timePerFrame.append(avgtime);
111 timesPerFrames.clear();
112 time.start();
113 lastTime = 0;
114 frames = 0;
115 }
116 }
117 ++frames;
120void RenderStatistics::printTotalStats()
122 int count = timePerFrame.count();
123 if (count == 0)
124 return;
126 qreal minTime = 0;
127 qreal maxTime = 0;
128 qreal avg = 0;
129 for (int i = 0; i < count; ++i) {
130 minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
131 maxTime = qMax(maxTime, timePerFrame.at(i));
132 avg += timePerFrame.at(i);
133 }
134 avg /= count;
136 qDebug(" ");
137 qDebug("----- Statistics -----");
138 qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
139 qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
140 qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
141 qDebug("----------------------");
142 qDebug(" ");
144#endif
146struct Options
148 Options()
149 : originalQml(false)
150 , originalQmlRaster(false)
151 , maximized(false)
152 , fullscreen(false)
153 , transparent(false)
154 , clip(false)
155 , versionDetection(true)
156 , quitImmediately(false)
157 , resizeViewToRootItem(false)
158 , multisample(false)
159 {
160 }
162 QUrl file;
163 bool originalQml;
164 bool originalQmlRaster;
165 bool maximized;
166 bool fullscreen;
167 bool transparent;
168 bool scenegraphOnGraphicsview;
169 bool clip;
170 bool versionDetection;
171 bool quitImmediately;
172 bool resizeViewToRootItem;
173 bool multisample;
174 QString translationFile;
175};
177#if defined(QMLSCENE_BUNDLE)
178QFileInfoList findQmlFiles(const QString &dirName)
180 QDir dir(dirName);
182 QFileInfoList ret;
183 if (dir.exists()) {
184 QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
185 QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
187 Q_FOREACH (QFileInfo fileInfo, fileInfos) {
188 if (fileInfo.isDir())
189 ret += findQmlFiles(fileInfo.filePath());
190 else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
191 ret.append(fileInfo);
192 }
193 }
195 return ret;
198static int displayOptionsDialog(Options *options)
200 QDialog dialog;
202 QFormLayout *layout = new QFormLayout(&dialog);
204 QComboBox *qmlFileComboBox = new QComboBox(&dialog);
205 QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
207 Q_FOREACH (QFileInfo fileInfo, fileInfos)
208 qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
210 QCheckBox *originalCheckBox = new QCheckBox(&dialog);
211 originalCheckBox->setText("Use original QML viewer");
212 originalCheckBox->setChecked(options->originalQml);
214 QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
215 fullscreenCheckBox->setText("Start fullscreen");
216 fullscreenCheckBox->setChecked(options->fullscreen);
218 QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
219 maximizedCheckBox->setText("Start maximized");
220 maximizedCheckBox->setChecked(options->maximized);
222 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
223 Qt::Horizontal,
224 &dialog);
225 QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
226 QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
228 layout->addRow("Qml file:", qmlFileComboBox);
229 layout->addWidget(originalCheckBox);
230 layout->addWidget(maximizedCheckBox);
231 layout->addWidget(fullscreenCheckBox);
232 layout->addWidget(buttonBox);
234 int result = dialog.exec();
235 if (result == QDialog::Accepted) {
236 QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
237 QFileInfo fileInfo = variant.value<QFileInfo>();
239 if (fileInfo.canonicalFilePath().startsWith(":"))
240 options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
241 else
242 options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
243 options->originalQml = originalCheckBox->isChecked();
244 options->maximized = maximizedCheckBox->isChecked();
245 options->fullscreen = fullscreenCheckBox->isChecked();
246 }
247 return result;
249#endif
251static bool checkVersion(const QUrl &url)
253 if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
254 qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
256 QString fileName = url.toLocalFile();
257 if (fileName.isEmpty()) {
258 qWarning("qmlscene: filename required.");
259 return false;
260 }
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 }
269 QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
270 QRegExp qt47("^\\s*import +Qt +4\\.7");
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();
285 if (!import.isNull()) {
286 qWarning("qmlscene: '%s' is no longer supported.\n"
287 "Use qmlviewer to load file '%s'.",
288 qPrintable(import),
289 qPrintable(fileName));
290 return false;
291 }
292 }
293 }
295 return true;
298static void displayFileDialog(Options *options)
300#if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
301 QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
302 if (!fileName.isEmpty()) {
303 QFileInfo fi(fileName);
304 options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
305 }
306#else
307 Q_UNUSED(options);
308 qWarning("No filename specified...");
309#endif
312#ifndef QT_NO_TRANSLATION
313static void loadTranslationFile(QTranslator &translator, const QString& directory)
315 translator.load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
316 QCoreApplication::installTranslator(&translator);
318#endif
320static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
322 QDir dir(directory+"/dummydata", "*.qml");
323 QStringList list = dir.entryList();
324 for (int i = 0; i < list.size(); ++i) {
325 QString qml = list.at(i);
326 QFile f(dir.filePath(qml));
327 f.open(QIODevice::ReadOnly);
328 QByteArray data = f.readAll();
329 QQmlComponent comp(&engine);
330 comp.setData(data, QUrl());
331 QObject *dummyData = comp.create();
333 if(comp.isError()) {
334 QList<QQmlError> errors = comp.errors();
335 Q_FOREACH (const QQmlError &error, errors)
336 qWarning() << error;
337 }
339 if (dummyData) {
340 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
341 qml.truncate(qml.length()-4);
342 engine.rootContext()->setContextProperty(qml, dummyData);
343 dummyData->setParent(&engine);
344 }
345 }
348static QObject *s_testRootObject = nullptr;
349static QObject *testRootObject(QQmlEngine *engine, QJSEngine *jsEngine)
351 Q_UNUSED(jsEngine);
352 if (!s_testRootObject) {
353 s_testRootObject = new QObject(engine);
354 }
355 return s_testRootObject;
358static void usage()
360 qWarning("Usage: uqmlscene [options] <filename>");
361 qWarning(" ");
362 qWarning(" Options:");
363 qWarning(" --maximized ............................... Run maximized");
364 qWarning(" --fullscreen .............................. Run fullscreen");
365 qWarning(" --transparent ............................. Make the window transparent");
366 qWarning(" --multisample ............................. Enable multisampling (OpenGL anti-aliasing)");
367 qWarning(" --no-version-detection .................... Do not try to detect the version of the .qml file");
368 qWarning(" --resize-to-root .......................... Resize the window to the size of the root item");
369 qWarning(" --quit .................................... Quit immediately after starting");
370 qWarning(" -I <path> ................................. Add <path> to the list of import paths");
371 qWarning(" -B <name> <file> .......................... Add a named bundle");
372 qWarning(" -translation <translationfile> ............ Set the language to run in");
374 qWarning(" ");
375 exit(1);
378int main(int argc, char ** argv)
380 Options options;
382 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
383 ActiveFocusLogger activeFocusLogger;
384 #endif
386 QStringList imports;
387 QList<QPair<QString, QString> > bundles;
388 for (int i = 1; i < argc; ++i) {
389 if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
390 options.file = QUrl::fromLocalFile(argv[i]);
391 } else {
392 const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
393 if (lowerArgument == QLatin1String("--maximized"))
394 options.maximized = true;
395 else if (lowerArgument == QLatin1String("--fullscreen"))
396 options.fullscreen = true;
397 else if (lowerArgument == QLatin1String("--transparent"))
398 options.transparent = true;
399 else if (lowerArgument == QLatin1String("--clip"))
400 options.clip = true;
401 else if (lowerArgument == QLatin1String("--no-version-detection"))
402 options.versionDetection = false;
403 else if (lowerArgument == QLatin1String("--quit"))
404 options.quitImmediately = true;
405 else if (lowerArgument == QLatin1String("-translation"))
406 options.translationFile = QLatin1String(argv[++i]);
407 else if (lowerArgument == QLatin1String("--resize-to-root"))
408 options.resizeViewToRootItem = true;
409 else if (lowerArgument == QLatin1String("--multisample"))
410 options.multisample = true;
411 else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
412 imports.append(QString::fromLatin1(argv[++i]));
413 else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
414 QString name = QString::fromLatin1(argv[++i]);
415 QString file = QString::fromLatin1(argv[++i]);
416 bundles.append(qMakePair(name, file));
417 } else if (lowerArgument == QLatin1String("--help")
418 || lowerArgument == QLatin1String("-help")
419 || lowerArgument == QLatin1String("--h")
420 || lowerArgument == QLatin1String("-h"))
421 usage();
422 }
423 }
425#ifdef QT_WIDGETS_LIB
426 QApplication app(argc, argv);
427#else
428 QGuiApplication app(argc, argv);
429#endif
430 app.setApplicationName("Unity8 QtQmlViewer");
431 app.setOrganizationName("Qt Project");
432 app.setOrganizationDomain("qt-project.org");
434#ifndef QT_NO_TRANSLATION
435 QTranslator translator;
436 QTranslator qtTranslator;
437 QString sysLocale = QLocale::system().name();
438 if (translator.load(QLatin1String("qmlscene_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
439 app.installTranslator(&translator);
440 if (qtTranslator.load(QLatin1String("qt_") + sysLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
441 app.installTranslator(&qtTranslator);
442 } else {
443 app.removeTranslator(&translator);
444 }
445 }
447 QTranslator qmlTranslator;
448 if (!options.translationFile.isEmpty()) {
449 if (qmlTranslator.load(options.translationFile)) {
450 app.installTranslator(&qmlTranslator);
451 } else {
452 qWarning() << "Could not load the translation file" << options.translationFile;
453 }
454 }
455#endif
457 if (options.file.isEmpty())
458#if defined(QMLSCENE_BUNDLE)
459 displayOptionsDialog(&options);
460#else
461 displayFileDialog(&options);
462#endif
464 int exitCode = 0;
466 if (!options.file.isEmpty()) {
467 if (!options.versionDetection || checkVersion(options.file)) {
468#ifndef QT_NO_TRANSLATION
469 QTranslator translator;
470#endif
472 // TODO: as soon as the engine construction completes, the debug service is
473 // listening for connections. But actually we aren't ready to debug anything.
474 QQmlEngine engine;
475 QQmlComponent *component = new QQmlComponent(&engine);
476 for (int i = 0; i < imports.size(); ++i)
477 engine.addImportPath(imports.at(i));
478 for (int i = 0; i < bundles.size(); ++i)
479 engine.addNamedBundle(bundles.at(i).first, bundles.at(i).second);
480 if (options.file.isLocalFile()) {
481 QFileInfo fi(options.file.toLocalFile());
482#ifndef QT_NO_TRANSLATION
483 loadTranslationFile(translator, fi.path());
484#endif
485 loadDummyDataFiles(engine, fi.path());
486 }
487 QObject::connect(&engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
489 qmlRegisterSingletonType<QObject>("Qt.test.qtestroot", 1, 0, "QTestRootObject", testRootObject);
491 component->loadUrl(options.file);
492 if ( !component->isReady() ) {
493 qWarning("%s", qPrintable(component->errorString()));
494 return -1;
495 }
497 QObject *topLevel = component->create();
498 QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
499 QQuickView* qxView = 0;
500 if (!window) {
501 QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
502 if (contentItem) {
503 qxView = new QQuickView(&engine, nullptr);
504 #if UQMLSCENE_DEBUG_ACTIVE_FOCUS
505 activeFocusLogger.setWindow(qxView);
506 #endif
507 window = qxView;
508 // Set window default properties; the qml can still override them
509 QString oname = contentItem->objectName();
510 window->setTitle(oname.isEmpty() ? QString::fromLatin1("qmlscene") : QString::fromLatin1("qmlscene: ") + oname);
511 window->setFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint);
512 if (options.resizeViewToRootItem)
513 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
514 else
515 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
516 qxView->setContent(options.file, component, contentItem);
517 }
518 }
520 if (window) {
521 QSurfaceFormat surfaceFormat = window->requestedFormat();
522 if (options.multisample)
523 surfaceFormat.setSamples(16);
524 if (options.transparent) {
525 surfaceFormat.setAlphaBufferSize(8);
526 window->setClearBeforeRendering(true);
527 window->setColor(QColor(Qt::transparent));
528 window->setFlags(Qt::FramelessWindowHint);
529 }
530 window->setFormat(surfaceFormat);
532 if (options.fullscreen)
533 window->showFullScreen();
534 else if (options.maximized)
535 window->showMaximized();
536 else
537 window->show();
538 }
540 if (options.quitImmediately)
541 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
543 // Now would be a good time to inform the debug service to start listening.
545 exitCode = app.exec();
547#ifdef QML_RUNTIME_TESTING
548 RenderStatistics::printTotalStats();
549#endif
550 // Ready to exit. If we created qxView, it owns the component;
551 // otherwise, the ownership is still right here. Nobody deletes the engine
552 // (which is odd since the container constructor takes the engine pointer),
553 // but it's stack-allocated anyway.
554 if (qxView)
555 delete qxView;
556 else
557 delete component;
558 }
559 }
561 return exitCode;