1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the tools applications of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 #include <QtQuick1/qdeclarativeview.h>
48 # include <QMaemo5ValueButton>
49 # include <QMaemo5ListPickSelector>
50 # include <QWidgetAction>
51 # include <QStringListModel>
52 # include "ui_recopts_maemo5.h"
54 # include "ui_recopts.h"
57 #include "qmlruntime.h"
58 #include <qdeclarativecontext.h>
59 #include <qdeclarativeengine.h>
60 #include <qdeclarativenetworkaccessmanagerfactory.h>
61 #include "qdeclarative.h"
62 #include <QAbstractAnimation>
63 #include <private/qabstractanimation_p.h>
67 #include <QXmlStreamReader>
69 #include <QNetworkReply>
70 #include <QNetworkCookieJar>
71 #include <QNetworkDiskCache>
72 #include <QNetworkAccessManager>
73 #include <QSignalMapper>
74 #include <QDeclarativeComponent>
76 #include <QApplication>
77 #include <QTranslator>
79 #include <QTextBrowser>
82 #include <QVBoxLayout>
83 #include <QProgressDialog>
88 #include <QFileDialog>
89 #include <QInputDialog>
91 #include <QGraphicsObject>
92 #include <QNetworkProxyFactory>
96 #include <QMutexLocker>
97 #include "proxysettings.h"
98 #include "deviceorientation.h"
104 #if defined(Q_WS_S60)
105 #include <aknappui.h> // For locking app orientation
108 #include <qdeclarativetester.h>
112 class DragAndDropView : public QDeclarativeView
116 DragAndDropView(QDeclarativeViewer *parent = 0)
117 : QDeclarativeView(parent)
119 setAcceptDrops(true);
122 void dragEnterEvent(QDragEnterEvent *event)
124 const QMimeData *mimeData = event->mimeData();
125 if (mimeData->hasUrls())
126 event->acceptProposedAction();
129 void dragMoveEvent(QDragMoveEvent *event)
131 event->acceptProposedAction();
134 void dragLeaveEvent(QDragLeaveEvent *event)
139 void dropEvent(QDropEvent *event)
141 const QMimeData *mimeData = event->mimeData();
142 if (!mimeData->hasUrls())
144 const QList<QUrl> urlList = mimeData->urls();
145 foreach (const QUrl &url, urlList) {
146 if (url.scheme() == QLatin1String("file")) {
147 static_cast<QDeclarativeViewer *>(parent())->open(url.toLocalFile());
155 class Runtime : public QObject
159 Q_PROPERTY(bool isActiveWindow READ isActiveWindow NOTIFY isActiveWindowChanged)
160 Q_PROPERTY(DeviceOrientation::Orientation orientation READ orientation NOTIFY orientationChanged)
163 static Runtime* instance()
165 static Runtime *instance = 0;
167 instance = new Runtime;
171 bool isActiveWindow() const { return activeWindow; }
172 void setActiveWindow(bool active)
174 if (active == activeWindow)
176 activeWindow = active;
177 emit isActiveWindowChanged();
180 DeviceOrientation::Orientation orientation() const { return DeviceOrientation::instance()->orientation(); }
183 void isActiveWindowChanged();
184 void orientationChanged();
187 Runtime(QObject *parent=0) : QObject(parent), activeWindow(false)
189 connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
190 this, SIGNAL(orientationChanged()));
198 #if defined(Q_WS_MAEMO_5)
200 class Maemo5PickerAction : public QWidgetAction {
203 Maemo5PickerAction(const QString &text, QActionGroup *actions, QObject *parent)
204 : QWidgetAction(parent), m_text(text), m_actions(actions)
207 QWidget *createWidget(QWidget *parent)
209 QMaemo5ValueButton *button = new QMaemo5ValueButton(m_text, parent);
210 button->setValueLayout(QMaemo5ValueButton::ValueUnderTextCentered);
211 QMaemo5ListPickSelector *pick = new QMaemo5ListPickSelector(button);
212 button->setPickSelector(pick);
215 int curIdx = -1, idx = 0;
216 foreach (QAction *a, m_actions->actions()) {
222 pick->setModel(new QStringListModel(sl));
223 pick->setCurrentIndex(curIdx);
225 button->setEnabled(false);
227 connect(pick, SIGNAL(selected(QString)), this, SLOT(emitTriggered()));
234 QMaemo5ListPickSelector *pick = qobject_cast<QMaemo5ListPickSelector *>(sender());
237 int idx = pick->currentIndex();
239 if (m_actions && idx >= 0 && idx < m_actions->actions().count())
240 m_actions->actions().at(idx)->trigger();
245 QPointer<QActionGroup> m_actions;
248 #endif // Q_WS_MAEMO_5
250 static struct { const char *name, *args; } ffmpegprofiles[] = {
251 {"Maximum Quality", "-sameq"},
252 {"High Quality", "-qmax 2"},
253 {"Medium Quality", "-qmax 6"},
254 {"Low Quality", "-qmax 16"},
255 {"Custom ffmpeg arguments", ""},
259 class RecordingDialog : public QDialog, public Ui::RecordingOptions {
263 RecordingDialog(QWidget *parent) : QDialog(parent)
267 hz->setValidator(new QDoubleValidator(hz));
269 for (int i=0; ffmpegprofiles[i].name; ++i) {
270 profile->addItem(QString::fromAscii(ffmpegprofiles[i].name));
274 void setArguments(QString a)
277 for (i=0; ffmpegprofiles[i].args[0]; ++i) {
278 if (QString::fromAscii(ffmpegprofiles[i].args) == a) {
279 profile->setCurrentIndex(i);
280 args->setText(QString::fromAscii(ffmpegprofiles[i].args));
286 profile->setCurrentIndex(i);
289 QString arguments() const
291 int i = profile->currentIndex();
292 return ffmpegprofiles[i].args[0] ? QLatin1String(ffmpegprofiles[i].args) : customargs;
295 void setOriginalSize(const QSize &s)
297 QString str = tr("Original (%1x%2)").arg(s.width()).arg(s.height());
300 sizeCombo->setItemText(0, str);
302 sizeOriginal->setText(str);
303 if (sizeWidth->value()<=1) {
304 sizeWidth->setValue(s.width());
305 sizeHeight->setValue(s.height());
310 void showffmpegOptions(bool b)
313 profileLabel->setVisible(b);
314 profile->setVisible(b);
315 ffmpegHelp->setVisible(b);
318 ffmpegOptions->setVisible(b);
322 void showRateOptions(bool b)
325 rateLabel->setVisible(b);
326 rateCombo->setVisible(b);
328 rateOptions->setVisible(b);
332 void setVideoRate(int rate)
350 rateCombo->setCurrentIndex(idx);
353 hz24->setChecked(true);
355 hz25->setChecked(true);
357 hz50->setChecked(true);
359 hz60->setChecked(true);
361 hzCustom->setChecked(true);
362 hz->setText(QString::number(rate));
367 int videoRate() const
370 switch (rateCombo->currentIndex()) {
381 if (hz24->isChecked())
383 else if (hz25->isChecked())
385 else if (hz50->isChecked())
387 else if (hz60->isChecked())
390 return hz->text().toInt();
395 QSize videoSize() const
398 switch (sizeCombo->currentIndex()) {
399 case 0: return QSize();
400 case 1: return QSize(640,480);
401 case 2: return QSize(320,240);
402 case 3: return QSize(1280,720);
403 default: return QSize();
406 if (sizeOriginal->isChecked())
408 else if (size720p->isChecked())
409 return QSize(1280,720);
410 else if (sizeVGA->isChecked())
411 return QSize(640,480);
412 else if (sizeQVGA->isChecked())
413 return QSize(320,240);
415 return QSize(sizeWidth->value(), sizeHeight->value());
422 void pickProfile(int i)
424 if (ffmpegprofiles[i].args[0]) {
425 args->setText(QLatin1String(ffmpegprofiles[i].args));
427 args->setText(customargs);
431 void storeCustomArgs(QString s)
440 class PersistentCookieJar : public QNetworkCookieJar {
442 PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
443 ~PersistentCookieJar() { save(); }
445 virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const
447 QMutexLocker lock(&mutex);
448 return QNetworkCookieJar::cookiesForUrl(url);
451 virtual bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
453 QMutexLocker lock(&mutex);
454 return QNetworkCookieJar::setCookiesFromUrl(cookieList, url);
460 QMutexLocker lock(&mutex);
461 QList<QNetworkCookie> list = allCookies();
463 foreach (QNetworkCookie cookie, list) {
464 if (!cookie.isSessionCookie()) {
465 data.append(cookie.toRawForm());
470 settings.setValue(QLatin1String("Cookies"), data);
475 QMutexLocker lock(&mutex);
477 QByteArray data = settings.value(QLatin1String("Cookies")).toByteArray();
478 setAllCookies(QNetworkCookie::parseCookies(data));
481 mutable QMutex mutex;
484 class SystemProxyFactory : public QNetworkProxyFactory
487 SystemProxyFactory() : proxyDirty(true), httpProxyInUse(false) {
490 virtual QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query)
494 QString protocolTag = query.protocolTag();
495 if (httpProxyInUse && (protocolTag == QLatin1String("http") || protocolTag == QLatin1String("https"))) {
496 QList<QNetworkProxy> ret;
501 // systemProxyForQuery can take insanely long on Windows (QTBUG-10106)
502 return QNetworkProxyFactory::proxyForQuery(query);
504 return QNetworkProxyFactory::systemProxyForQuery(query);
509 // Don't bother locking because we know that the proxy only
510 // changes in response to the settings dialog and that
511 // the view will be reloaded.
513 httpProxyInUse = ProxySettings::httpProxyInUse();
515 httpProxy = ProxySettings::httpProxy();
518 void proxyChanged() {
523 volatile bool proxyDirty;
525 QNetworkProxy httpProxy;
528 class NetworkAccessManagerFactory : public QObject, public QDeclarativeNetworkAccessManagerFactory
532 NetworkAccessManagerFactory() : cacheSize(0) {}
533 ~NetworkAccessManagerFactory() {}
535 QNetworkAccessManager *create(QObject *parent);
537 void setCacheSize(int size) {
538 if (size != cacheSize) {
543 void proxyChanged() {
544 foreach (QNetworkAccessManager *nam, namList) {
545 static_cast<SystemProxyFactory*>(nam->proxyFactory())->proxyChanged();
549 static PersistentCookieJar *cookieJar;
552 void managerDestroyed(QObject *obj) {
553 namList.removeOne(static_cast<QNetworkAccessManager*>(obj));
559 QList<QNetworkAccessManager*> namList;
562 PersistentCookieJar *NetworkAccessManagerFactory::cookieJar = 0;
564 static void cleanup_cookieJar()
566 delete NetworkAccessManagerFactory::cookieJar;
567 NetworkAccessManagerFactory::cookieJar = 0;
570 QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
572 QMutexLocker lock(&mutex);
573 QNetworkAccessManager *manager = new QNetworkAccessManager(parent);
575 qAddPostRoutine(cleanup_cookieJar);
576 cookieJar = new PersistentCookieJar(0);
578 manager->setCookieJar(cookieJar);
579 cookieJar->setParent(0);
580 manager->setProxyFactory(new SystemProxyFactory);
582 QNetworkDiskCache *cache = new QNetworkDiskCache;
583 cache->setCacheDirectory(QDir::tempPath()+QLatin1String("/qml-viewer-network-cache"));
584 cache->setMaximumCacheSize(cacheSize);
585 manager->setCache(cache);
587 manager->setCache(0);
589 connect(manager, SIGNAL(destroyed(QObject*)), this, SLOT(managerDestroyed(QObject*)));
590 namList.append(manager);
594 QString QDeclarativeViewer::getVideoFileName()
596 QString title = convertAvailable || ffmpegAvailable ? tr("Save Video File") : tr("Save PNG Frames");
598 if (ffmpegAvailable) types += tr("Common Video files")+QLatin1String(" (*.avi *.mpeg *.mov)");
599 if (convertAvailable) types += tr("GIF Animation")+QLatin1String(" (*.gif)");
600 types += tr("Individual PNG frames")+QLatin1String(" (*.png)");
601 if (ffmpegAvailable) types += tr("All ffmpeg formats (*.*)");
602 return QFileDialog::getSaveFileName(this, title, QString(), types.join(QLatin1String(";; ")));
605 QDeclarativeViewer::QDeclarativeViewer(QWidget *parent, Qt::WindowFlags flags)
606 : QMainWindow(parent, flags)
607 , loggerWindow(new LoggerWidget(this))
611 , showWarningsWindow(0)
614 , useQmlFileBrowser(true)
617 QDeclarativeViewer::registerTypes();
618 setWindowTitle(tr("Qt QML Viewer"));
620 setAttribute(Qt::WA_Maemo5StackedWindow);
621 // setPalette(QApplication::palette("QLabel"));
628 record_args += QLatin1String("-sameq");
630 recdlg = new RecordingDialog(this);
631 connect(recdlg->pickfile, SIGNAL(clicked()), this, SLOT(pickRecordingFile()));
634 if (!ffmpegAvailable)
635 recdlg->showffmpegOptions(false);
636 if (!ffmpegAvailable && !convertAvailable)
637 recdlg->showRateOptions(false);
639 if (!ffmpegAvailable) {
640 if (!convertAvailable)
641 warn = tr("ffmpeg and ImageMagick not available - no video output");
643 warn = tr("ffmpeg not available - GIF and PNG outputs only");
644 recdlg->warning->setText(warn);
646 recdlg->warning->hide();
649 canvas = new DragAndDropView(this);
651 canvas->setAttribute(Qt::WA_OpaquePaintEvent);
652 canvas->setAttribute(Qt::WA_NoSystemBackground);
656 QObject::connect(canvas, SIGNAL(initialSizeChanged(QSize)), this, SLOT(initialSizeChanged(QSize)));
657 QObject::connect(canvas, SIGNAL(statusChanged(QDeclarativeView::Status)), this, SLOT(statusChanged()));
658 QObject::connect(canvas->engine(), SIGNAL(quit()), this, SLOT(close()));
660 QObject::connect(warningsWidget(), SIGNAL(opened()), this, SLOT(warningsWidgetOpened()));
661 QObject::connect(warningsWidget(), SIGNAL(closed()), this, SLOT(warningsWidgetClosed()));
663 if (!(flags & Qt::FramelessWindowHint)) {
665 changeOrientation(orientation->actions().value(0));
670 setCentralWidget(canvas);
672 namFactory = new NetworkAccessManagerFactory;
673 canvas->engine()->setNetworkAccessManagerFactory(namFactory);
675 connect(&autoStartTimer, SIGNAL(timeout()), this, SLOT(autoStartRecording()));
676 connect(&autoStopTimer, SIGNAL(timeout()), this, SLOT(autoStopRecording()));
677 connect(&recordTimer, SIGNAL(timeout()), this, SLOT(recordFrame()));
678 connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
679 this, SLOT(orientationChanged()), Qt::QueuedConnection);
680 autoStartTimer.setSingleShot(true);
681 autoStopTimer.setSingleShot(true);
682 recordTimer.setSingleShot(false);
684 QObject::connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(appAboutToQuit()));
687 QDeclarativeViewer::~QDeclarativeViewer()
690 canvas->engine()->setNetworkAccessManagerFactory(0);
694 void QDeclarativeViewer::enableExperimentalGestures()
696 #ifndef QT_NO_GESTURES
697 canvas->viewport()->grabGesture(Qt::TapGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
698 canvas->viewport()->grabGesture(Qt::TapAndHoldGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
699 canvas->viewport()->grabGesture(Qt::PanGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
700 canvas->viewport()->grabGesture(Qt::PinchGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
701 canvas->viewport()->grabGesture(Qt::SwipeGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
702 canvas->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);
706 QDeclarativeView *QDeclarativeViewer::view() const
711 LoggerWidget *QDeclarativeViewer::warningsWidget() const
716 void QDeclarativeViewer::createMenu()
718 QAction *openAction = new QAction(tr("&Open..."), this);
719 openAction->setShortcuts(QKeySequence::Open);
720 connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
722 QAction *openUrlAction = new QAction(tr("Open &URL..."), this);
723 connect(openUrlAction, SIGNAL(triggered()), this, SLOT(openUrl()));
725 QAction *reloadAction = new QAction(tr("&Reload"), this);
726 reloadAction->setShortcuts(QKeySequence::Refresh);
727 connect(reloadAction, SIGNAL(triggered()), this, SLOT(reload()));
729 QAction *snapshotAction = new QAction(tr("&Take Snapshot"), this);
730 snapshotAction->setShortcut(QKeySequence(tr("F3")));
731 connect(snapshotAction, SIGNAL(triggered()), this, SLOT(takeSnapShot()));
733 recordAction = new QAction(tr("Start Recording &Video"), this);
734 recordAction->setShortcut(QKeySequence(tr("F9")));
735 connect(recordAction, SIGNAL(triggered()), this, SLOT(toggleRecordingWithSelection()));
737 QAction *recordOptions = new QAction(tr("Video &Options..."), this);
738 connect(recordOptions, SIGNAL(triggered()), this, SLOT(chooseRecordingOptions()));
740 QAction *slowAction = new QAction(tr("&Slow Down Animations"), this);
741 slowAction->setShortcut(QKeySequence(tr("Ctrl+.")));
742 slowAction->setCheckable(true);
743 connect(slowAction, SIGNAL(triggered(bool)), this, SLOT(setSlowMode(bool)));
745 showWarningsWindow = new QAction(tr("Show Warnings"), this);
746 #if !defined(Q_OS_SYMBIAN)
747 showWarningsWindow->setCheckable((true));
748 showWarningsWindow->setChecked(loggerWindow->isVisible());
750 connect(showWarningsWindow, SIGNAL(triggered(bool)), this, SLOT(showWarnings(bool)));
752 QAction *proxyAction = new QAction(tr("HTTP &Proxy..."), this);
753 connect(proxyAction, SIGNAL(triggered()), this, SLOT(showProxySettings()));
755 QAction *fullscreenAction = new QAction(tr("Full Screen"), this);
756 fullscreenAction->setCheckable(true);
757 connect(fullscreenAction, SIGNAL(triggered()), this, SLOT(toggleFullScreen()));
759 rotateAction = new QAction(tr("Rotate orientation"), this);
760 rotateAction->setShortcut(QKeySequence(tr("Ctrl+T")));
761 connect(rotateAction, SIGNAL(triggered()), this, SLOT(rotateOrientation()));
763 orientation = new QActionGroup(this);
764 orientation->setExclusive(true);
765 connect(orientation, SIGNAL(triggered(QAction*)), this, SLOT(changeOrientation(QAction*)));
767 #if defined(Q_OS_SYMBIAN)
768 QAction *autoOrientationAction = new QAction(tr("Auto-orientation"), this);
769 autoOrientationAction->setCheckable(true);
771 QAction *portraitAction = new QAction(tr("Portrait"), this);
772 portraitAction->setCheckable(true);
773 QAction *landscapeAction = new QAction(tr("Landscape"), this);
774 landscapeAction->setCheckable(true);
775 #if !defined(Q_OS_SYMBIAN)
776 QAction *portraitInvAction = new QAction(tr("Portrait (inverted)"), this);
777 portraitInvAction->setCheckable(true);
778 QAction *landscapeInvAction = new QAction(tr("Landscape (inverted)"), this);
779 landscapeInvAction->setCheckable(true);
782 QAction *aboutAction = new QAction(tr("&About Qt..."), this);
783 aboutAction->setMenuRole(QAction::AboutQtRole);
784 connect(aboutAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
786 #if !defined(Q_OS_SYMBIAN)
787 QAction *closeAction = new QAction(tr("&Close"), this);
788 closeAction->setShortcuts(QKeySequence::Close);
789 connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
792 QAction *quitAction = new QAction(tr("&Quit"), this);
793 quitAction->setMenuRole(QAction::QuitRole);
794 quitAction->setShortcuts(QKeySequence::Quit);
795 connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
797 QMenuBar *menu = menuBar();
801 #if defined(Q_WS_MAEMO_5)
802 menu->addAction(openAction);
803 menu->addAction(openUrlAction);
804 menu->addAction(reloadAction);
806 menu->addAction(snapshotAction);
807 menu->addAction(recordAction);
809 menu->addAction(recordOptions);
810 menu->addAction(proxyAction);
812 menu->addAction(slowAction);
813 menu->addAction(showWarningsWindow);
815 orientation->addAction(landscapeAction);
816 orientation->addAction(portraitAction);
817 menu->addAction(new Maemo5PickerAction(tr("Set orientation"), orientation, this));
818 menu->addAction(fullscreenAction);
820 #endif // Q_WS_MAEMO_5
822 QMenu *fileMenu = menu->addMenu(tr("&File"));
823 fileMenu->addAction(openAction);
824 fileMenu->addAction(openUrlAction);
825 fileMenu->addAction(reloadAction);
826 #if !defined(Q_OS_SYMBIAN)
827 fileMenu->addSeparator();
828 fileMenu->addAction(closeAction);
829 fileMenu->addAction(quitAction);
831 QMenu *recordMenu = menu->addMenu(tr("&Recording"));
832 recordMenu->addAction(snapshotAction);
833 recordMenu->addAction(recordAction);
834 #endif // ! Q_OS_SYMBIAN
836 QMenu *debugMenu = menu->addMenu(tr("&Debugging"));
837 debugMenu->addAction(slowAction);
838 debugMenu->addAction(showWarningsWindow);
840 QMenu *settingsMenu = menu->addMenu(tr("&Settings"));
841 settingsMenu->addAction(proxyAction);
842 #if defined(Q_OS_SYMBIAN)
843 settingsMenu->addAction(fullscreenAction);
845 settingsMenu->addAction(recordOptions);
846 settingsMenu->addMenu(loggerWindow->preferencesMenu());
847 #endif // !Q_OS_SYMBIAN
848 settingsMenu->addAction(rotateAction);
850 QMenu *propertiesMenu = settingsMenu->addMenu(tr("Properties"));
852 #if defined(Q_OS_SYMBIAN)
853 orientation->addAction(autoOrientationAction);
855 orientation->addAction(portraitAction);
856 orientation->addAction(landscapeAction);
857 #if !defined(Q_OS_SYMBIAN)
858 orientation->addAction(portraitInvAction);
859 orientation->addAction(landscapeInvAction);
861 propertiesMenu->addActions(orientation->actions());
863 QMenu *helpMenu = menu->addMenu(tr("&Help"));
864 helpMenu->addAction(aboutAction);
867 void QDeclarativeViewer::showProxySettings()
869 ProxySettings settingsDlg (this);
871 connect (&settingsDlg, SIGNAL (accepted()), this, SLOT (proxySettingsChanged ()));
876 void QDeclarativeViewer::proxySettingsChanged()
878 namFactory->proxyChanged();
882 void QDeclarativeViewer::rotateOrientation()
884 #if defined(Q_WS_S60)
885 CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
887 CAknAppUi::TAppUiOrientation oldOrientation = appUi->Orientation();
888 QString newOrientation;
889 if (oldOrientation == CAknAppUi::EAppUiOrientationPortrait) {
890 newOrientation = QLatin1String("Landscape");
892 newOrientation = QLatin1String("Portrait");
894 foreach (QAction *action, orientation->actions()) {
895 if (action->text() == newOrientation) {
896 changeOrientation(action);
901 QAction *current = orientation->checkedAction();
902 QList<QAction *> actions = orientation->actions();
903 int index = actions.indexOf(current);
907 QAction *newOrientation = actions[(index + 1) % actions.count()];
908 changeOrientation(newOrientation);
912 void QDeclarativeViewer::toggleFullScreen()
920 void QDeclarativeViewer::showWarnings(bool show)
922 #if defined(Q_OS_SYMBIAN)
923 loggerWindow->showMaximized();
925 loggerWindow->setVisible(show);
929 void QDeclarativeViewer::warningsWidgetOpened()
931 showWarningsWindow->setChecked(true);
934 void QDeclarativeViewer::warningsWidgetClosed()
936 showWarningsWindow->setChecked(false);
939 void QDeclarativeViewer::takeSnapShot()
941 static int snapshotcount = 1;
942 QString snapFileName = QString(QLatin1String("snapshot%1.png")).arg(snapshotcount);
943 QPixmap::grabWidget(canvas).save(snapFileName);
944 qDebug() << "Wrote" << snapFileName;
948 void QDeclarativeViewer::pickRecordingFile()
950 QString fileName = getVideoFileName();
951 if (!fileName.isEmpty())
952 recdlg->file->setText(fileName);
955 void QDeclarativeViewer::chooseRecordingOptions()
958 recdlg->file->setText(record_file);
961 recdlg->setOriginalSize(canvas->size());
964 recdlg->setVideoRate(record_rate);
968 recdlg->setArguments(record_args.join(QLatin1String(" ")));
969 if (recdlg->exec()) {
971 record_file = recdlg->file->text();
973 record_outsize = recdlg->videoSize();
975 record_rate = recdlg->videoRate();
977 record_args = recdlg->arguments().split(QLatin1Char(' '),QString::SkipEmptyParts);
981 void QDeclarativeViewer::toggleRecordingWithSelection()
983 if (!recordTimer.isActive()) {
984 if (record_file.isEmpty()) {
985 QString fileName = getVideoFileName();
986 if (fileName.isEmpty())
988 if (!fileName.contains(QRegExp(QLatin1String(".[^\\/]*$"))))
989 fileName += QLatin1String(".avi");
990 setRecordFile(fileName);
996 void QDeclarativeViewer::toggleRecording()
998 if (record_file.isEmpty()) {
999 toggleRecordingWithSelection();
1002 bool recording = !recordTimer.isActive();
1003 recordAction->setText(recording ? tr("&Stop Recording Video\tF9") : tr("&Start Recording Video\tF9"));
1004 setRecording(recording);
1007 void QDeclarativeViewer::setSlowMode(bool enable)
1009 QUnifiedTimer::instance()->setSlowModeEnabled(enable);
1012 void QDeclarativeViewer::addLibraryPath(const QString& lib)
1014 canvas->engine()->addImportPath(lib);
1017 void QDeclarativeViewer::addPluginPath(const QString& plugin)
1019 canvas->engine()->addPluginPath(plugin);
1022 void QDeclarativeViewer::reload()
1024 launch(currentFileOrUrl);
1027 void QDeclarativeViewer::openFile()
1029 QString cur = canvas->source().toLocalFile();
1030 if (useQmlFileBrowser) {
1031 open(QLatin1String("qrc:/browser/Browser.qml"));
1033 QString fileName = QFileDialog::getOpenFileName(this, tr("Open QML file"), cur, tr("QML Files (*.qml)"));
1034 if (!fileName.isEmpty()) {
1035 QFileInfo fi(fileName);
1036 open(fi.absoluteFilePath());
1041 void QDeclarativeViewer::openUrl()
1043 QString cur = canvas->source().toLocalFile();
1044 QString url= QInputDialog::getText(this, tr("Open QML file"), tr("URL of main QML file:"), QLineEdit::Normal, cur);
1049 void QDeclarativeViewer::statusChanged()
1051 if (canvas->status() == QDeclarativeView::Error && tester)
1052 tester->executefailure();
1054 if (canvas->status() == QDeclarativeView::Ready) {
1055 initialSize = canvas->initialSize();
1056 updateSizeHints(true);
1057 QObject::connect(canvas, SIGNAL(sceneResized(QSize)), this, SLOT(sceneResized(QSize)));
1061 void QDeclarativeViewer::launch(const QString& file_or_url)
1063 QMetaObject::invokeMethod(this, "open", Qt::QueuedConnection, Q_ARG(QString, file_or_url));
1066 void QDeclarativeViewer::loadTranslationFile(const QString& directory)
1069 translator = new QTranslator(this);
1070 QApplication::installTranslator(translator);
1073 translator->load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
1076 void QDeclarativeViewer::loadDummyDataFiles(const QString& directory)
1078 QDir dir(directory + QLatin1String("/dummydata"), QLatin1String("*.qml"));
1079 QStringList list = dir.entryList();
1080 for (int i = 0; i < list.size(); ++i) {
1081 QString qml = list.at(i);
1082 QDeclarativeComponent comp(canvas->engine(), dir.filePath(qml));
1083 QObject *dummyData = comp.create();
1085 if(comp.isError()) {
1086 QList<QDeclarativeError> errors = comp.errors();
1087 foreach (const QDeclarativeError &error, errors) {
1088 qWarning() << error;
1090 if (tester) tester->executefailure();
1094 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
1095 qml.truncate(qml.length()-4);
1096 canvas->rootContext()->setContextProperty(qml, dummyData);
1097 dummyData->setParent(this);
1102 bool QDeclarativeViewer::open(const QString& file_or_url)
1104 currentFileOrUrl = file_or_url;
1107 QFileInfo fi(file_or_url);
1109 url = QUrl::fromLocalFile(fi.absoluteFilePath());
1111 url = QUrl(file_or_url);
1112 setWindowTitle(tr("%1 - Qt QML Viewer").arg(file_or_url));
1114 if (!m_script.isEmpty())
1115 tester = new QDeclarativeTester(m_script, m_scriptOptions, canvas);
1117 delete canvas->rootObject();
1118 canvas->engine()->clearComponentCache();
1119 QDeclarativeContext *ctxt = canvas->rootContext();
1120 ctxt->setContextProperty(QLatin1String("qmlViewer"), this);
1122 ctxt->setContextProperty(QLatin1String("qmlViewerFolder"), QLatin1String("E:\\")); // Documents on your S60 phone
1124 ctxt->setContextProperty(QLatin1String("qmlViewerFolder"), QDir::currentPath());
1127 ctxt->setContextProperty(QLatin1String("runtime"), Runtime::instance());
1129 QString fileName = url.toLocalFile();
1130 if (!fileName.isEmpty()) {
1131 fi.setFile(fileName);
1133 if (fi.suffix().toLower() != QLatin1String("qml")) {
1134 qWarning() << "qml cannot open non-QML file" << fileName;
1138 QFileInfo fi(fileName);
1139 loadTranslationFile(fi.path());
1140 loadDummyDataFiles(fi.path());
1142 qWarning() << "qml cannot find file:" << fileName;
1150 QObject::disconnect(canvas, SIGNAL(sceneResized(QSize)), this, SLOT(sceneResized(QSize)));
1151 canvas->setSource(url);
1156 void QDeclarativeViewer::setAutoRecord(int from, int to)
1158 if (from==0) from=1; // ensure resized
1159 record_autotime = to-from;
1160 autoStartTimer.setInterval(from);
1161 autoStartTimer.start();
1164 void QDeclarativeViewer::setRecordArgs(const QStringList& a)
1169 void QDeclarativeViewer::setRecordFile(const QString& f)
1174 void QDeclarativeViewer::setRecordRate(int fps)
1179 void QDeclarativeViewer::sceneResized(QSize)
1184 void QDeclarativeViewer::initialSizeChanged(QSize size)
1186 if (!isFullScreen() && !isMaximized()) {
1187 canvas->setGeometry(0,0,size.width(),size.height());
1188 layout()->setSizeConstraint(QLayout::SetFixedSize);
1189 layout()->activate();
1193 void QDeclarativeViewer::keyPressEvent(QKeyEvent *event)
1195 if (event->key() == Qt::Key_0 && devicemode)
1197 else if (event->key() == Qt::Key_F1 || (event->key() == Qt::Key_1 && devicemode)) {
1198 qDebug() << "F1 - help\n"
1199 << "F2 - save test script\n"
1200 << "F3 - take PNG snapshot\n"
1201 << "F4 - show items and state\n"
1202 << "F5 - reload QML\n"
1203 << "F6 - show object tree\n"
1204 << "F7 - show timing\n"
1205 << "F9 - toggle video recording\n"
1206 << "F10 - toggle orientation\n"
1207 << "device keys: 0=quit, 1..8=F1..F8"
1209 } else if (event->key() == Qt::Key_F2 || (event->key() == Qt::Key_2 && devicemode)) {
1210 if (tester && m_scriptOptions & Record)
1212 } else if (event->key() == Qt::Key_F3 || (event->key() == Qt::Key_3 && devicemode)) {
1214 } else if (event->key() == Qt::Key_F5 || (event->key() == Qt::Key_5 && devicemode)) {
1216 } else if (event->key() == Qt::Key_F9 || (event->key() == Qt::Key_9 && devicemode)) {
1218 } else if (event->key() == Qt::Key_F10) {
1219 rotateOrientation();
1222 QWidget::keyPressEvent(event);
1225 bool QDeclarativeViewer::event(QEvent *event)
1227 if (event->type() == QEvent::WindowActivate) {
1228 Runtime::instance()->setActiveWindow(true);
1229 DeviceOrientation::instance()->resumeListening();
1230 } else if (event->type() == QEvent::WindowDeactivate) {
1231 Runtime::instance()->setActiveWindow(false);
1232 DeviceOrientation::instance()->pauseListening();
1234 return QWidget::event(event);
1237 void QDeclarativeViewer::senseImageMagick()
1240 proc.start(QLatin1String("convert"), QStringList() << QLatin1String("-h"));
1241 proc.waitForFinished(2000);
1242 QString help = QString::fromAscii(proc.readAllStandardOutput());
1243 convertAvailable = help.contains(QLatin1String("ImageMagick"));
1246 void QDeclarativeViewer::senseFfmpeg()
1249 proc.start(QLatin1String("ffmpeg"), QStringList() << QLatin1String("-h"));
1250 proc.waitForFinished(2000);
1251 QString ffmpegHelp = QString::fromAscii(proc.readAllStandardOutput());
1252 ffmpegAvailable = ffmpegHelp.contains(QLatin1String("-s "));
1253 ffmpegHelp = tr("Video recording uses ffmpeg:") + QLatin1String("\n\n") + ffmpegHelp;
1255 QDialog *d = new QDialog(recdlg);
1256 QVBoxLayout *l = new QVBoxLayout(d);
1257 QTextBrowser *b = new QTextBrowser(d);
1258 QFont f = b->font();
1259 f.setFamily(QLatin1String("courier"));
1261 b->setText(ffmpegHelp);
1264 ffmpegHelpWindow = d;
1265 connect(recdlg->ffmpegHelp,SIGNAL(clicked()), ffmpegHelpWindow, SLOT(show()));
1268 void QDeclarativeViewer::setRecording(bool on)
1270 if (on == recordTimer.isActive())
1273 int period = int(1000/record_rate+0.5);
1274 QUnifiedTimer::instance()->setTimingInterval(on ? period:16);
1275 QUnifiedTimer::instance()->setConsistentTiming(on);
1277 canvas->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
1278 recordTimer.setInterval(period);
1279 recordTimer.start();
1280 frame_fmt = record_file.right(4).toLower();
1281 frame = QImage(canvas->width(),canvas->height(),QImage::Format_RGB32);
1282 if (frame_fmt != QLatin1String(".png") && (!convertAvailable || frame_fmt != QLatin1String(".gif"))) {
1283 // Stream video to ffmpeg
1285 QProcess *proc = new QProcess(this);
1286 connect(proc, SIGNAL(finished(int)), this, SLOT(ffmpegFinished(int)));
1287 frame_stream = proc;
1290 args << QLatin1String("-y");
1291 args << QLatin1String("-r") << QString::number(record_rate);
1292 args << QLatin1String("-f") << QLatin1String("rawvideo");
1293 args << QLatin1String("-pix_fmt") << (frame_fmt == QLatin1String(".gif") ? QLatin1String("rgb24") : QLatin1String("rgb32"));
1294 args << QLatin1String("-s") << QString::fromAscii("%1x%2").arg(canvas->width()).arg(canvas->height());
1295 args << QLatin1String("-i") << QLatin1String("-");
1296 if (record_outsize.isValid()) {
1297 args << QLatin1String("-s") << QString::fromAscii("%1x%2").arg(record_outsize.width()).arg(record_outsize.height());
1298 args << QLatin1String("-aspect") << QString::number(double(canvas->width())/canvas->height());
1300 args += record_args;
1301 args << record_file;
1302 proc->start(QLatin1String("ffmpeg"), args);
1305 // Store frames, save to GIF/PNG
1309 canvas->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
1312 qDebug() << "Saving video...";
1313 frame_stream->close();
1314 qDebug() << "Wrote" << record_file;
1316 QProgressDialog progress(tr("Saving frames..."), tr("Cancel"), 0, frames.count()+10, this);
1317 progress.setWindowModality(Qt::WindowModal);
1321 qDebug() << "Saving frames...";
1324 bool png_output = false;
1325 if (record_file.right(4).toLower() == QLatin1String(".png")) {
1326 if (record_file.contains(QLatin1Char('%')))
1327 framename = record_file;
1329 framename = record_file.left(record_file.length()-4) + QLatin1String("%04d") + record_file.right(4);
1332 framename = QLatin1String("tmp-frame%04d.png");
1335 foreach (QImage* img, frames) {
1336 progress.setValue(progress.value()+1);
1337 if (progress.wasCanceled())
1340 name.sprintf(framename.toLocal8Bit(),frame++);
1341 if (record_outsize.isValid())
1342 *img = img->scaled(record_outsize,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
1343 if (record_dither==QLatin1String("ordered"))
1344 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::OrderedDither).save(name);
1345 else if (record_dither==QLatin1String("threshold"))
1346 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::ThresholdDither).save(name);
1347 else if (record_dither==QLatin1String("floyd"))
1348 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither).save(name);
1355 if (!progress.wasCanceled()) {
1357 framename.replace(QRegExp(QLatin1String("%\\d*.")), QLatin1String("*"));
1358 qDebug() << "Wrote frames" << framename;
1359 inputs.clear(); // don't remove them
1361 // ImageMagick and gifsicle for GIF encoding
1362 progress.setLabelText(tr("Converting frames to GIF file..."));
1364 args << QLatin1String("-delay") << QString::number(period/10);
1366 args << record_file;
1367 qDebug() << "Converting..." << record_file << "(this may take a while)";
1368 if (0!=QProcess::execute(QLatin1String("convert"), args)) {
1369 qWarning() << "Cannot run ImageMagick 'convert' - recorded frames not converted";
1370 inputs.clear(); // don't remove them
1371 qDebug() << "Wrote frames tmp-frame*.png";
1373 if (record_file.right(4).toLower() == QLatin1String(".gif")) {
1374 qDebug() << "Compressing..." << record_file;
1375 if (0!=QProcess::execute(QLatin1String("gifsicle"), QStringList() << QLatin1String("-O2")
1376 << QLatin1String("-o") << record_file << record_file))
1377 qWarning() << "Cannot run 'gifsicle' - not compressed";
1379 qDebug() << "Wrote" << record_file;
1384 progress.setValue(progress.maximum()-1);
1385 foreach (QString name, inputs)
1386 QFile::remove(name);
1391 qDebug() << "Recording: " << (recordTimer.isActive()?"ON":"OFF");
1394 void QDeclarativeViewer::ffmpegFinished(int code)
1396 qDebug() << "ffmpeg returned" << code << frame_stream->readAllStandardError();
1399 void QDeclarativeViewer::appAboutToQuit()
1401 // avoid QGLContext errors about invalid contexts on exit
1402 canvas->setViewport(0);
1404 // avoid crashes if messages are received after app has closed
1405 delete loggerWindow;
1412 void QDeclarativeViewer::autoStartRecording()
1415 autoStopTimer.setInterval(record_autotime);
1416 autoStopTimer.start();
1419 void QDeclarativeViewer::autoStopRecording()
1421 setRecording(false);
1424 void QDeclarativeViewer::recordFrame()
1426 canvas->QWidget::render(&frame);
1428 if (frame_fmt == QLatin1String(".gif")) {
1429 // ffmpeg can't do 32bpp with gif
1430 QImage rgb24 = frame.convertToFormat(QImage::Format_RGB888);
1431 frame_stream->write((char*)rgb24.bits(),rgb24.byteCount());
1433 frame_stream->write((char*)frame.bits(),frame.byteCount());
1436 frames.append(new QImage(frame));
1440 void QDeclarativeViewer::changeOrientation(QAction *action)
1444 QString o = action->text();
1445 action->setChecked(true);
1446 #if defined(Q_WS_S60)
1447 CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
1449 CAknAppUi::TAppUiOrientation orientation = appUi->Orientation();
1450 if (o == QLatin1String("Auto-orientation")) {
1451 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationAutomatic);
1452 rotateAction->setVisible(false);
1453 } else if (o == QLatin1String("Portrait")) {
1454 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationPortrait);
1455 rotateAction->setVisible(true);
1456 } else if (o == QLatin1String("Landscape")) {
1457 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape);
1458 rotateAction->setVisible(true);
1462 if (o == QLatin1String("Portrait"))
1463 DeviceOrientation::instance()->setOrientation(DeviceOrientation::Portrait);
1464 else if (o == QLatin1String("Landscape"))
1465 DeviceOrientation::instance()->setOrientation(DeviceOrientation::Landscape);
1466 else if (o == QLatin1String("Portrait (inverted)"))
1467 DeviceOrientation::instance()->setOrientation(DeviceOrientation::PortraitInverted);
1468 else if (o == QLatin1String("Landscape (inverted)"))
1469 DeviceOrientation::instance()->setOrientation(DeviceOrientation::LandscapeInverted);
1473 void QDeclarativeViewer::orientationChanged()
1478 void QDeclarativeViewer::setDeviceKeys(bool on)
1483 void QDeclarativeViewer::setNetworkCacheSize(int size)
1485 namFactory->setCacheSize(size);
1488 void QDeclarativeViewer::setUseGL(bool useGL)
1492 QGLFormat format = QGLFormat::defaultFormat();
1494 format.setSampleBuffers(true);
1495 format.setSwapInterval(1);
1497 format.setSampleBuffers(false);
1500 QGLWidget *glWidget = new QGLWidget(format);
1501 //### potentially faster, but causes junk to appear if top-level is Item, not Rectangle
1502 //glWidget->setAutoFillBackground(false);
1504 canvas->setViewport(glWidget);
1511 void QDeclarativeViewer::setUseNativeFileBrowser(bool use)
1513 useQmlFileBrowser = !use;
1516 void QDeclarativeViewer::setSizeToView(bool sizeToView)
1518 QDeclarativeView::ResizeMode resizeMode = sizeToView ? QDeclarativeView::SizeRootObjectToView : QDeclarativeView::SizeViewToRootObject;
1519 if (resizeMode != canvas->resizeMode()) {
1520 canvas->setResizeMode(resizeMode);
1525 void QDeclarativeViewer::updateSizeHints(bool initial)
1527 static bool isRecursive = false;
1533 if (initial || (canvas->resizeMode() == QDeclarativeView::SizeViewToRootObject)) {
1534 QSize newWindowSize = initial ? initialSize : canvas->sizeHint();
1535 //qWarning() << "USH:" << (initial ? "INIT:" : "V2R:") << "setting fixed size " << newWindowSize;
1536 if (!isFullScreen() && !isMaximized()) {
1537 canvas->setGeometry(0,0,newWindowSize.width(),newWindowSize.height());
1539 layout()->setSizeConstraint(QLayout::SetFixedSize);
1540 layout()->activate();
1543 //qWarning() << "USH: R2V: setting free size ";
1544 layout()->setSizeConstraint(QLayout::SetNoConstraint);
1545 layout()->activate();
1546 setMinimumSize(minimumSizeHint());
1547 setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
1548 canvas->setMinimumSize(QSize(0,0));
1549 canvas->setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
1551 isRecursive = false;
1554 void QDeclarativeViewer::registerTypes()
1556 static bool registered = false;
1559 // registering only for exposing the DeviceOrientation::Orientation enum
1560 qmlRegisterUncreatableType<DeviceOrientation>("Qt", 4, 7, "Orientation", QString());
1561 qmlRegisterUncreatableType<DeviceOrientation>("QtQuick", 1, 0, "Orientation", QString());
1568 #include "qmlruntime.moc"