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 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include <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>
66 #include <QXmlStreamReader>
68 #include <QNetworkReply>
69 #include <QNetworkCookieJar>
70 #include <QNetworkDiskCache>
71 #include <QNetworkAccessManager>
72 #include <QSignalMapper>
73 #include <QDeclarativeComponent>
75 #include <QApplication>
76 #include <QTranslator>
78 #include <QTextBrowser>
81 #include <QVBoxLayout>
82 #include <QProgressDialog>
87 #include <QFileDialog>
88 #include <QInputDialog>
90 #include <QGraphicsObject>
91 #include <QNetworkProxyFactory>
94 #include <QMutexLocker>
95 #include "proxysettings.h"
96 #include "deviceorientation.h"
102 #if defined(Q_WS_S60)
103 #include <aknappui.h> // For locking app orientation
106 #include <qdeclarativetester.h>
110 class DragAndDropView : public QDeclarativeView
114 DragAndDropView(QDeclarativeViewer *parent = 0)
115 : QDeclarativeView(parent)
117 setAcceptDrops(true);
120 void dragEnterEvent(QDragEnterEvent *event)
122 const QMimeData *mimeData = event->mimeData();
123 if (mimeData->hasUrls())
124 event->acceptProposedAction();
127 void dragMoveEvent(QDragMoveEvent *event)
129 event->acceptProposedAction();
132 void dragLeaveEvent(QDragLeaveEvent *event)
137 void dropEvent(QDropEvent *event)
139 const QMimeData *mimeData = event->mimeData();
140 if (!mimeData->hasUrls())
142 const QList<QUrl> urlList = mimeData->urls();
143 foreach (const QUrl &url, urlList) {
144 if (url.scheme() == QLatin1String("file")) {
145 static_cast<QDeclarativeViewer *>(parent())->open(url.toLocalFile());
153 class Runtime : public QObject
157 Q_PROPERTY(bool isActiveWindow READ isActiveWindow NOTIFY isActiveWindowChanged)
158 Q_PROPERTY(DeviceOrientation::Orientation orientation READ orientation NOTIFY orientationChanged)
161 static Runtime* instance()
163 static Runtime *instance = 0;
165 instance = new Runtime;
169 bool isActiveWindow() const { return activeWindow; }
170 void setActiveWindow(bool active)
172 if (active == activeWindow)
174 activeWindow = active;
175 emit isActiveWindowChanged();
178 DeviceOrientation::Orientation orientation() const { return DeviceOrientation::instance()->orientation(); }
181 void isActiveWindowChanged();
182 void orientationChanged();
185 Runtime(QObject *parent=0) : QObject(parent), activeWindow(false)
187 connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
188 this, SIGNAL(orientationChanged()));
196 #if defined(Q_WS_MAEMO_5)
198 class Maemo5PickerAction : public QWidgetAction {
201 Maemo5PickerAction(const QString &text, QActionGroup *actions, QObject *parent)
202 : QWidgetAction(parent), m_text(text), m_actions(actions)
205 QWidget *createWidget(QWidget *parent)
207 QMaemo5ValueButton *button = new QMaemo5ValueButton(m_text, parent);
208 button->setValueLayout(QMaemo5ValueButton::ValueUnderTextCentered);
209 QMaemo5ListPickSelector *pick = new QMaemo5ListPickSelector(button);
210 button->setPickSelector(pick);
213 int curIdx = -1, idx = 0;
214 foreach (QAction *a, m_actions->actions()) {
220 pick->setModel(new QStringListModel(sl));
221 pick->setCurrentIndex(curIdx);
223 button->setEnabled(false);
225 connect(pick, SIGNAL(selected(QString)), this, SLOT(emitTriggered()));
232 QMaemo5ListPickSelector *pick = qobject_cast<QMaemo5ListPickSelector *>(sender());
235 int idx = pick->currentIndex();
237 if (m_actions && idx >= 0 && idx < m_actions->actions().count())
238 m_actions->actions().at(idx)->trigger();
243 QPointer<QActionGroup> m_actions;
246 #endif // Q_WS_MAEMO_5
248 static struct { const char *name, *args; } ffmpegprofiles[] = {
249 {"Maximum Quality", "-sameq"},
250 {"High Quality", "-qmax 2"},
251 {"Medium Quality", "-qmax 6"},
252 {"Low Quality", "-qmax 16"},
253 {"Custom ffmpeg arguments", ""},
257 class RecordingDialog : public QDialog, public Ui::RecordingOptions {
261 RecordingDialog(QWidget *parent) : QDialog(parent)
265 hz->setValidator(new QDoubleValidator(hz));
267 for (int i=0; ffmpegprofiles[i].name; ++i) {
268 profile->addItem(QString::fromAscii(ffmpegprofiles[i].name));
272 void setArguments(QString a)
275 for (i=0; ffmpegprofiles[i].args[0]; ++i) {
276 if (QString::fromAscii(ffmpegprofiles[i].args) == a) {
277 profile->setCurrentIndex(i);
278 args->setText(QString::fromAscii(ffmpegprofiles[i].args));
284 profile->setCurrentIndex(i);
287 QString arguments() const
289 int i = profile->currentIndex();
290 return ffmpegprofiles[i].args[0] ? QLatin1String(ffmpegprofiles[i].args) : customargs;
293 void setOriginalSize(const QSize &s)
295 QString str = tr("Original (%1x%2)").arg(s.width()).arg(s.height());
298 sizeCombo->setItemText(0, str);
300 sizeOriginal->setText(str);
301 if (sizeWidth->value()<=1) {
302 sizeWidth->setValue(s.width());
303 sizeHeight->setValue(s.height());
308 void showffmpegOptions(bool b)
311 profileLabel->setVisible(b);
312 profile->setVisible(b);
313 ffmpegHelp->setVisible(b);
316 ffmpegOptions->setVisible(b);
320 void showRateOptions(bool b)
323 rateLabel->setVisible(b);
324 rateCombo->setVisible(b);
326 rateOptions->setVisible(b);
330 void setVideoRate(int rate)
348 rateCombo->setCurrentIndex(idx);
351 hz24->setChecked(true);
353 hz25->setChecked(true);
355 hz50->setChecked(true);
357 hz60->setChecked(true);
359 hzCustom->setChecked(true);
360 hz->setText(QString::number(rate));
365 int videoRate() const
368 switch (rateCombo->currentIndex()) {
379 if (hz24->isChecked())
381 else if (hz25->isChecked())
383 else if (hz50->isChecked())
385 else if (hz60->isChecked())
388 return hz->text().toInt();
393 QSize videoSize() const
396 switch (sizeCombo->currentIndex()) {
397 case 0: return QSize();
398 case 1: return QSize(640,480);
399 case 2: return QSize(320,240);
400 case 3: return QSize(1280,720);
401 default: return QSize();
404 if (sizeOriginal->isChecked())
406 else if (size720p->isChecked())
407 return QSize(1280,720);
408 else if (sizeVGA->isChecked())
409 return QSize(640,480);
410 else if (sizeQVGA->isChecked())
411 return QSize(320,240);
413 return QSize(sizeWidth->value(), sizeHeight->value());
420 void pickProfile(int i)
422 if (ffmpegprofiles[i].args[0]) {
423 args->setText(QLatin1String(ffmpegprofiles[i].args));
425 args->setText(customargs);
429 void storeCustomArgs(QString s)
438 class PersistentCookieJar : public QNetworkCookieJar {
440 PersistentCookieJar(QObject *parent) : QNetworkCookieJar(parent) { load(); }
441 ~PersistentCookieJar() { save(); }
443 virtual QList<QNetworkCookie> cookiesForUrl(const QUrl &url) const
445 QMutexLocker lock(&mutex);
446 return QNetworkCookieJar::cookiesForUrl(url);
449 virtual bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
451 QMutexLocker lock(&mutex);
452 return QNetworkCookieJar::setCookiesFromUrl(cookieList, url);
458 QMutexLocker lock(&mutex);
459 QList<QNetworkCookie> list = allCookies();
461 foreach (QNetworkCookie cookie, list) {
462 if (!cookie.isSessionCookie()) {
463 data.append(cookie.toRawForm());
468 settings.setValue(QLatin1String("Cookies"), data);
473 QMutexLocker lock(&mutex);
475 QByteArray data = settings.value(QLatin1String("Cookies")).toByteArray();
476 setAllCookies(QNetworkCookie::parseCookies(data));
479 mutable QMutex mutex;
482 class SystemProxyFactory : public QNetworkProxyFactory
485 SystemProxyFactory() : proxyDirty(true), httpProxyInUse(false) {
488 virtual QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query)
492 QString protocolTag = query.protocolTag();
493 if (httpProxyInUse && (protocolTag == QLatin1String("http") || protocolTag == QLatin1String("https"))) {
494 QList<QNetworkProxy> ret;
499 // systemProxyForQuery can take insanely long on Windows (QTBUG-10106)
500 return QNetworkProxyFactory::proxyForQuery(query);
502 return QNetworkProxyFactory::systemProxyForQuery(query);
507 // Don't bother locking because we know that the proxy only
508 // changes in response to the settings dialog and that
509 // the view will be reloaded.
511 httpProxyInUse = ProxySettings::httpProxyInUse();
513 httpProxy = ProxySettings::httpProxy();
516 void proxyChanged() {
521 volatile bool proxyDirty;
523 QNetworkProxy httpProxy;
526 class NetworkAccessManagerFactory : public QObject, public QDeclarativeNetworkAccessManagerFactory
530 NetworkAccessManagerFactory() : cacheSize(0) {}
531 ~NetworkAccessManagerFactory() {}
533 QNetworkAccessManager *create(QObject *parent);
535 void setCacheSize(int size) {
536 if (size != cacheSize) {
541 void proxyChanged() {
542 foreach (QNetworkAccessManager *nam, namList) {
543 static_cast<SystemProxyFactory*>(nam->proxyFactory())->proxyChanged();
547 static PersistentCookieJar *cookieJar;
550 void managerDestroyed(QObject *obj) {
551 namList.removeOne(static_cast<QNetworkAccessManager*>(obj));
557 QList<QNetworkAccessManager*> namList;
560 PersistentCookieJar *NetworkAccessManagerFactory::cookieJar = 0;
562 static void cleanup_cookieJar()
564 delete NetworkAccessManagerFactory::cookieJar;
565 NetworkAccessManagerFactory::cookieJar = 0;
568 QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
570 QMutexLocker lock(&mutex);
571 QNetworkAccessManager *manager = new QNetworkAccessManager(parent);
573 qAddPostRoutine(cleanup_cookieJar);
574 cookieJar = new PersistentCookieJar(0);
576 manager->setCookieJar(cookieJar);
577 cookieJar->setParent(0);
578 manager->setProxyFactory(new SystemProxyFactory);
580 QNetworkDiskCache *cache = new QNetworkDiskCache;
581 cache->setCacheDirectory(QDir::tempPath()+QLatin1String("/qml-viewer-network-cache"));
582 cache->setMaximumCacheSize(cacheSize);
583 manager->setCache(cache);
585 manager->setCache(0);
587 connect(manager, SIGNAL(destroyed(QObject*)), this, SLOT(managerDestroyed(QObject*)));
588 namList.append(manager);
592 QString QDeclarativeViewer::getVideoFileName()
594 QString title = convertAvailable || ffmpegAvailable ? tr("Save Video File") : tr("Save PNG Frames");
596 if (ffmpegAvailable) types += tr("Common Video files")+QLatin1String(" (*.avi *.mpeg *.mov)");
597 if (convertAvailable) types += tr("GIF Animation")+QLatin1String(" (*.gif)");
598 types += tr("Individual PNG frames")+QLatin1String(" (*.png)");
599 if (ffmpegAvailable) types += tr("All ffmpeg formats (*.*)");
600 return QFileDialog::getSaveFileName(this, title, QString(), types.join(QLatin1String(";; ")));
603 QDeclarativeViewer::QDeclarativeViewer(QWidget *parent, Qt::WindowFlags flags)
604 : QMainWindow(parent, flags)
605 , loggerWindow(new LoggerWidget(this))
609 , showWarningsWindow(0)
612 , useQmlFileBrowser(true)
615 QDeclarativeViewer::registerTypes();
616 setWindowTitle(tr("Qt QML Viewer"));
618 setAttribute(Qt::WA_Maemo5StackedWindow);
619 // setPalette(QApplication::palette("QLabel"));
626 record_args += QLatin1String("-sameq");
628 recdlg = new RecordingDialog(this);
629 connect(recdlg->pickfile, SIGNAL(clicked()), this, SLOT(pickRecordingFile()));
632 if (!ffmpegAvailable)
633 recdlg->showffmpegOptions(false);
634 if (!ffmpegAvailable && !convertAvailable)
635 recdlg->showRateOptions(false);
637 if (!ffmpegAvailable) {
638 if (!convertAvailable)
639 warn = tr("ffmpeg and ImageMagick not available - no video output");
641 warn = tr("ffmpeg not available - GIF and PNG outputs only");
642 recdlg->warning->setText(warn);
644 recdlg->warning->hide();
647 canvas = new DragAndDropView(this);
649 canvas->setAttribute(Qt::WA_OpaquePaintEvent);
650 canvas->setAttribute(Qt::WA_NoSystemBackground);
654 QObject::connect(canvas, SIGNAL(sceneResized(QSize)), this, SLOT(sceneResized(QSize)));
655 QObject::connect(canvas, SIGNAL(statusChanged(QDeclarativeView::Status)), this, SLOT(statusChanged()));
656 QObject::connect(canvas->engine(), SIGNAL(quit()), this, SLOT(close()));
658 QObject::connect(warningsWidget(), SIGNAL(opened()), this, SLOT(warningsWidgetOpened()));
659 QObject::connect(warningsWidget(), SIGNAL(closed()), this, SLOT(warningsWidgetClosed()));
661 if (!(flags & Qt::FramelessWindowHint)) {
663 changeOrientation(orientation->actions().value(0));
668 setCentralWidget(canvas);
670 namFactory = new NetworkAccessManagerFactory;
671 canvas->engine()->setNetworkAccessManagerFactory(namFactory);
673 connect(&autoStartTimer, SIGNAL(timeout()), this, SLOT(autoStartRecording()));
674 connect(&autoStopTimer, SIGNAL(timeout()), this, SLOT(autoStopRecording()));
675 connect(&recordTimer, SIGNAL(timeout()), this, SLOT(recordFrame()));
676 connect(DeviceOrientation::instance(), SIGNAL(orientationChanged()),
677 this, SLOT(orientationChanged()), Qt::QueuedConnection);
678 autoStartTimer.setSingleShot(true);
679 autoStopTimer.setSingleShot(true);
680 recordTimer.setSingleShot(false);
682 QObject::connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(appAboutToQuit()));
685 QDeclarativeViewer::~QDeclarativeViewer()
688 canvas->engine()->setNetworkAccessManagerFactory(0);
692 void QDeclarativeViewer::enableExperimentalGestures()
694 #ifndef QT_NO_GESTURES
695 canvas->viewport()->grabGesture(Qt::TapGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
696 canvas->viewport()->grabGesture(Qt::TapAndHoldGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
697 canvas->viewport()->grabGesture(Qt::PanGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
698 canvas->viewport()->grabGesture(Qt::PinchGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
699 canvas->viewport()->grabGesture(Qt::SwipeGesture,Qt::DontStartGestureOnChildren|Qt::ReceivePartialGestures|Qt::IgnoredGesturesPropagateToParent);
700 canvas->viewport()->setAttribute(Qt::WA_AcceptTouchEvents);
704 QDeclarativeView *QDeclarativeViewer::view() const
709 LoggerWidget *QDeclarativeViewer::warningsWidget() const
714 void QDeclarativeViewer::createMenu()
716 QAction *openAction = new QAction(tr("&Open..."), this);
717 openAction->setShortcuts(QKeySequence::Open);
718 connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));
720 QAction *openUrlAction = new QAction(tr("Open &URL..."), this);
721 connect(openUrlAction, SIGNAL(triggered()), this, SLOT(openUrl()));
723 QAction *reloadAction = new QAction(tr("&Reload"), this);
724 reloadAction->setShortcuts(QKeySequence::Refresh);
725 connect(reloadAction, SIGNAL(triggered()), this, SLOT(reload()));
727 QAction *snapshotAction = new QAction(tr("&Take Snapshot"), this);
728 snapshotAction->setShortcut(QKeySequence(tr("F3")));
729 connect(snapshotAction, SIGNAL(triggered()), this, SLOT(takeSnapShot()));
731 recordAction = new QAction(tr("Start Recording &Video"), this);
732 recordAction->setShortcut(QKeySequence(tr("F9")));
733 connect(recordAction, SIGNAL(triggered()), this, SLOT(toggleRecordingWithSelection()));
735 QAction *recordOptions = new QAction(tr("Video &Options..."), this);
736 connect(recordOptions, SIGNAL(triggered()), this, SLOT(chooseRecordingOptions()));
738 QAction *slowAction = new QAction(tr("&Slow Down Animations"), this);
739 slowAction->setShortcut(QKeySequence(tr("Ctrl+.")));
740 slowAction->setCheckable(true);
741 connect(slowAction, SIGNAL(triggered(bool)), this, SLOT(setSlowMode(bool)));
743 showWarningsWindow = new QAction(tr("Show Warnings"), this);
744 #if !defined(Q_OS_SYMBIAN)
745 showWarningsWindow->setCheckable((true));
746 showWarningsWindow->setChecked(loggerWindow->isVisible());
748 connect(showWarningsWindow, SIGNAL(triggered(bool)), this, SLOT(showWarnings(bool)));
750 QAction *proxyAction = new QAction(tr("HTTP &Proxy..."), this);
751 connect(proxyAction, SIGNAL(triggered()), this, SLOT(showProxySettings()));
753 QAction *fullscreenAction = new QAction(tr("Full Screen"), this);
754 fullscreenAction->setCheckable(true);
755 connect(fullscreenAction, SIGNAL(triggered()), this, SLOT(toggleFullScreen()));
757 rotateAction = new QAction(tr("Rotate orientation"), this);
758 rotateAction->setShortcut(QKeySequence(tr("Ctrl+T")));
759 connect(rotateAction, SIGNAL(triggered()), this, SLOT(rotateOrientation()));
761 orientation = new QActionGroup(this);
762 orientation->setExclusive(true);
763 connect(orientation, SIGNAL(triggered(QAction*)), this, SLOT(changeOrientation(QAction*)));
765 #if defined(Q_OS_SYMBIAN)
766 QAction *autoOrientationAction = new QAction(tr("Auto-orientation"), this);
767 autoOrientationAction->setCheckable(true);
769 QAction *portraitAction = new QAction(tr("Portrait"), this);
770 portraitAction->setCheckable(true);
771 QAction *landscapeAction = new QAction(tr("Landscape"), this);
772 landscapeAction->setCheckable(true);
773 #if !defined(Q_OS_SYMBIAN)
774 QAction *portraitInvAction = new QAction(tr("Portrait (inverted)"), this);
775 portraitInvAction->setCheckable(true);
776 QAction *landscapeInvAction = new QAction(tr("Landscape (inverted)"), this);
777 landscapeInvAction->setCheckable(true);
780 QAction *aboutAction = new QAction(tr("&About Qt..."), this);
781 aboutAction->setMenuRole(QAction::AboutQtRole);
782 connect(aboutAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
784 #if !defined(Q_OS_SYMBIAN)
785 QAction *closeAction = new QAction(tr("&Close"), this);
786 closeAction->setShortcuts(QKeySequence::Close);
787 connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
790 QAction *quitAction = new QAction(tr("&Quit"), this);
791 quitAction->setMenuRole(QAction::QuitRole);
792 quitAction->setShortcuts(QKeySequence::Quit);
793 connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
795 QMenuBar *menu = menuBar();
799 #if defined(Q_WS_MAEMO_5)
800 menu->addAction(openAction);
801 menu->addAction(openUrlAction);
802 menu->addAction(reloadAction);
804 menu->addAction(snapshotAction);
805 menu->addAction(recordAction);
807 menu->addAction(recordOptions);
808 menu->addAction(proxyAction);
810 menu->addAction(slowAction);
811 menu->addAction(showWarningsWindow);
813 orientation->addAction(landscapeAction);
814 orientation->addAction(portraitAction);
815 menu->addAction(new Maemo5PickerAction(tr("Set orientation"), orientation, this));
816 menu->addAction(fullscreenAction);
818 #endif // Q_WS_MAEMO_5
820 QMenu *fileMenu = menu->addMenu(tr("&File"));
821 fileMenu->addAction(openAction);
822 fileMenu->addAction(openUrlAction);
823 fileMenu->addAction(reloadAction);
824 #if !defined(Q_OS_SYMBIAN)
825 fileMenu->addSeparator();
826 fileMenu->addAction(closeAction);
827 fileMenu->addAction(quitAction);
829 QMenu *recordMenu = menu->addMenu(tr("&Recording"));
830 recordMenu->addAction(snapshotAction);
831 recordMenu->addAction(recordAction);
832 #endif // ! Q_OS_SYMBIAN
834 QMenu *debugMenu = menu->addMenu(tr("&Debugging"));
835 debugMenu->addAction(slowAction);
836 debugMenu->addAction(showWarningsWindow);
838 QMenu *settingsMenu = menu->addMenu(tr("&Settings"));
839 settingsMenu->addAction(proxyAction);
840 #if defined(Q_OS_SYMBIAN)
841 settingsMenu->addAction(fullscreenAction);
843 settingsMenu->addAction(recordOptions);
844 settingsMenu->addMenu(loggerWindow->preferencesMenu());
845 #endif // !Q_OS_SYMBIAN
846 settingsMenu->addAction(rotateAction);
848 QMenu *propertiesMenu = settingsMenu->addMenu(tr("Properties"));
850 #if defined(Q_OS_SYMBIAN)
851 orientation->addAction(autoOrientationAction);
853 orientation->addAction(portraitAction);
854 orientation->addAction(landscapeAction);
855 #if !defined(Q_OS_SYMBIAN)
856 orientation->addAction(portraitInvAction);
857 orientation->addAction(landscapeInvAction);
859 propertiesMenu->addActions(orientation->actions());
861 QMenu *helpMenu = menu->addMenu(tr("&Help"));
862 helpMenu->addAction(aboutAction);
865 void QDeclarativeViewer::showProxySettings()
867 ProxySettings settingsDlg (this);
869 connect (&settingsDlg, SIGNAL (accepted()), this, SLOT (proxySettingsChanged ()));
874 void QDeclarativeViewer::proxySettingsChanged()
876 namFactory->proxyChanged();
880 void QDeclarativeViewer::rotateOrientation()
882 #if defined(Q_WS_S60)
883 CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
885 CAknAppUi::TAppUiOrientation oldOrientation = appUi->Orientation();
886 QString newOrientation;
887 if (oldOrientation == CAknAppUi::EAppUiOrientationPortrait) {
888 newOrientation = QLatin1String("Landscape");
890 newOrientation = QLatin1String("Portrait");
892 foreach (QAction *action, orientation->actions()) {
893 if (action->text() == newOrientation) {
894 changeOrientation(action);
899 QAction *current = orientation->checkedAction();
900 QList<QAction *> actions = orientation->actions();
901 int index = actions.indexOf(current);
905 QAction *newOrientation = actions[(index + 1) % actions.count()];
906 changeOrientation(newOrientation);
910 void QDeclarativeViewer::toggleFullScreen()
918 void QDeclarativeViewer::showWarnings(bool show)
920 #if defined(Q_OS_SYMBIAN)
921 loggerWindow->showMaximized();
923 loggerWindow->setVisible(show);
927 void QDeclarativeViewer::warningsWidgetOpened()
929 showWarningsWindow->setChecked(true);
932 void QDeclarativeViewer::warningsWidgetClosed()
934 showWarningsWindow->setChecked(false);
937 void QDeclarativeViewer::takeSnapShot()
939 static int snapshotcount = 1;
940 QString snapFileName = QString(QLatin1String("snapshot%1.png")).arg(snapshotcount);
941 QPixmap::grabWidget(canvas).save(snapFileName);
942 qDebug() << "Wrote" << snapFileName;
946 void QDeclarativeViewer::pickRecordingFile()
948 QString fileName = getVideoFileName();
949 if (!fileName.isEmpty())
950 recdlg->file->setText(fileName);
953 void QDeclarativeViewer::chooseRecordingOptions()
956 recdlg->file->setText(record_file);
959 recdlg->setOriginalSize(canvas->size());
962 recdlg->setVideoRate(record_rate);
966 recdlg->setArguments(record_args.join(QLatin1String(" ")));
967 if (recdlg->exec()) {
969 record_file = recdlg->file->text();
971 record_outsize = recdlg->videoSize();
973 record_rate = recdlg->videoRate();
975 record_args = recdlg->arguments().split(QLatin1Char(' '),QString::SkipEmptyParts);
979 void QDeclarativeViewer::toggleRecordingWithSelection()
981 if (!recordTimer.isActive()) {
982 if (record_file.isEmpty()) {
983 QString fileName = getVideoFileName();
984 if (fileName.isEmpty())
986 if (!fileName.contains(QRegExp(QLatin1String(".[^\\/]*$"))))
987 fileName += QLatin1String(".avi");
988 setRecordFile(fileName);
994 void QDeclarativeViewer::toggleRecording()
996 if (record_file.isEmpty()) {
997 toggleRecordingWithSelection();
1000 bool recording = !recordTimer.isActive();
1001 recordAction->setText(recording ? tr("&Stop Recording Video\tF9") : tr("&Start Recording Video\tF9"));
1002 setRecording(recording);
1005 void QDeclarativeViewer::setSlowMode(bool enable)
1007 QUnifiedTimer::instance()->setSlowModeEnabled(enable);
1010 void QDeclarativeViewer::addLibraryPath(const QString& lib)
1012 canvas->engine()->addImportPath(lib);
1015 void QDeclarativeViewer::addPluginPath(const QString& plugin)
1017 canvas->engine()->addPluginPath(plugin);
1020 void QDeclarativeViewer::reload()
1022 launch(currentFileOrUrl);
1025 void QDeclarativeViewer::openFile()
1027 QString cur = canvas->source().toLocalFile();
1028 if (useQmlFileBrowser) {
1029 open(QLatin1String("qrc:/browser/Browser.qml"));
1031 QString fileName = QFileDialog::getOpenFileName(this, tr("Open QML file"), cur, tr("QML Files (*.qml)"));
1032 if (!fileName.isEmpty()) {
1033 QFileInfo fi(fileName);
1034 open(fi.absoluteFilePath());
1039 void QDeclarativeViewer::openUrl()
1041 QString cur = canvas->source().toLocalFile();
1042 QString url= QInputDialog::getText(this, tr("Open QML file"), tr("URL of main QML file:"), QLineEdit::Normal, cur);
1047 void QDeclarativeViewer::statusChanged()
1049 if (canvas->status() == QDeclarativeView::Error && tester)
1050 tester->executefailure();
1052 if (canvas->status() == QDeclarativeView::Ready) {
1053 initialSize = canvas->initialSize();
1054 updateSizeHints(true);
1058 void QDeclarativeViewer::launch(const QString& file_or_url)
1060 QMetaObject::invokeMethod(this, "open", Qt::QueuedConnection, Q_ARG(QString, file_or_url));
1063 void QDeclarativeViewer::loadTranslationFile(const QString& directory)
1066 translator = new QTranslator(this);
1067 QApplication::installTranslator(translator);
1070 translator->load(QLatin1String("qml_" )+QLocale::system().name(), directory + QLatin1String("/i18n"));
1073 void QDeclarativeViewer::loadDummyDataFiles(const QString& directory)
1075 QDir dir(directory + QLatin1String("/dummydata"), QLatin1String("*.qml"));
1076 QStringList list = dir.entryList();
1077 for (int i = 0; i < list.size(); ++i) {
1078 QString qml = list.at(i);
1079 QDeclarativeComponent comp(canvas->engine(), dir.filePath(qml));
1080 QObject *dummyData = comp.create();
1082 if(comp.isError()) {
1083 QList<QDeclarativeError> errors = comp.errors();
1084 foreach (const QDeclarativeError &error, errors) {
1085 qWarning() << error;
1087 if (tester) tester->executefailure();
1091 qWarning() << "Loaded dummy data:" << dir.filePath(qml);
1092 qml.truncate(qml.length()-4);
1093 canvas->rootContext()->setContextProperty(qml, dummyData);
1094 dummyData->setParent(this);
1099 bool QDeclarativeViewer::open(const QString& file_or_url)
1101 currentFileOrUrl = file_or_url;
1104 QFileInfo fi(file_or_url);
1106 url = QUrl::fromLocalFile(fi.absoluteFilePath());
1108 url = QUrl(file_or_url);
1109 setWindowTitle(tr("%1 - Qt QML Viewer").arg(file_or_url));
1111 if (!m_script.isEmpty())
1112 tester = new QDeclarativeTester(m_script, m_scriptOptions, canvas);
1114 delete canvas->rootObject();
1115 canvas->engine()->clearComponentCache();
1116 QDeclarativeContext *ctxt = canvas->rootContext();
1117 ctxt->setContextProperty(QLatin1String("qmlViewer"), this);
1119 ctxt->setContextProperty(QLatin1String("qmlViewerFolder"), QLatin1String("E:\\")); // Documents on your S60 phone
1121 ctxt->setContextProperty(QLatin1String("qmlViewerFolder"), QDir::currentPath());
1124 ctxt->setContextProperty(QLatin1String("runtime"), Runtime::instance());
1126 QString fileName = url.toLocalFile();
1127 if (!fileName.isEmpty()) {
1128 fi.setFile(fileName);
1130 if (fi.suffix().toLower() != QLatin1String("qml")) {
1131 qWarning() << "qml cannot open non-QML file" << fileName;
1135 QFileInfo fi(fileName);
1136 loadTranslationFile(fi.path());
1137 loadDummyDataFiles(fi.path());
1139 qWarning() << "qml cannot find file:" << fileName;
1147 canvas->setSource(url);
1152 void QDeclarativeViewer::setAutoRecord(int from, int to)
1154 if (from==0) from=1; // ensure resized
1155 record_autotime = to-from;
1156 autoStartTimer.setInterval(from);
1157 autoStartTimer.start();
1160 void QDeclarativeViewer::setRecordArgs(const QStringList& a)
1165 void QDeclarativeViewer::setRecordFile(const QString& f)
1170 void QDeclarativeViewer::setRecordRate(int fps)
1175 void QDeclarativeViewer::sceneResized(QSize)
1180 void QDeclarativeViewer::keyPressEvent(QKeyEvent *event)
1182 if (event->key() == Qt::Key_0 && devicemode)
1184 else if (event->key() == Qt::Key_F1 || (event->key() == Qt::Key_1 && devicemode)) {
1185 qDebug() << "F1 - help\n"
1186 << "F2 - save test script\n"
1187 << "F3 - take PNG snapshot\n"
1188 << "F4 - show items and state\n"
1189 << "F5 - reload QML\n"
1190 << "F6 - show object tree\n"
1191 << "F7 - show timing\n"
1192 << "F9 - toggle video recording\n"
1193 << "F10 - toggle orientation\n"
1194 << "device keys: 0=quit, 1..8=F1..F8"
1196 } else if (event->key() == Qt::Key_F2 || (event->key() == Qt::Key_2 && devicemode)) {
1197 if (tester && m_scriptOptions & Record)
1199 } else if (event->key() == Qt::Key_F3 || (event->key() == Qt::Key_3 && devicemode)) {
1201 } else if (event->key() == Qt::Key_F5 || (event->key() == Qt::Key_5 && devicemode)) {
1203 } else if (event->key() == Qt::Key_F9 || (event->key() == Qt::Key_9 && devicemode)) {
1205 } else if (event->key() == Qt::Key_F10) {
1206 rotateOrientation();
1209 QWidget::keyPressEvent(event);
1212 bool QDeclarativeViewer::event(QEvent *event)
1214 if (event->type() == QEvent::WindowActivate) {
1215 Runtime::instance()->setActiveWindow(true);
1216 DeviceOrientation::instance()->resumeListening();
1217 } else if (event->type() == QEvent::WindowDeactivate) {
1218 Runtime::instance()->setActiveWindow(false);
1219 DeviceOrientation::instance()->pauseListening();
1221 return QWidget::event(event);
1224 void QDeclarativeViewer::senseImageMagick()
1227 proc.start(QLatin1String("convert"), QStringList() << QLatin1String("-h"));
1228 proc.waitForFinished(2000);
1229 QString help = QString::fromAscii(proc.readAllStandardOutput());
1230 convertAvailable = help.contains(QLatin1String("ImageMagick"));
1233 void QDeclarativeViewer::senseFfmpeg()
1236 proc.start(QLatin1String("ffmpeg"), QStringList() << QLatin1String("-h"));
1237 proc.waitForFinished(2000);
1238 QString ffmpegHelp = QString::fromAscii(proc.readAllStandardOutput());
1239 ffmpegAvailable = ffmpegHelp.contains(QLatin1String("-s "));
1240 ffmpegHelp = tr("Video recording uses ffmpeg:") + QLatin1String("\n\n") + ffmpegHelp;
1242 QDialog *d = new QDialog(recdlg);
1243 QVBoxLayout *l = new QVBoxLayout(d);
1244 QTextBrowser *b = new QTextBrowser(d);
1245 QFont f = b->font();
1246 f.setFamily(QLatin1String("courier"));
1248 b->setText(ffmpegHelp);
1251 ffmpegHelpWindow = d;
1252 connect(recdlg->ffmpegHelp,SIGNAL(clicked()), ffmpegHelpWindow, SLOT(show()));
1255 void QDeclarativeViewer::setRecording(bool on)
1257 if (on == recordTimer.isActive())
1260 int period = int(1000/record_rate+0.5);
1261 QUnifiedTimer::instance()->setTimingInterval(on ? period:16);
1262 QUnifiedTimer::instance()->setConsistentTiming(on);
1264 canvas->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
1265 recordTimer.setInterval(period);
1266 recordTimer.start();
1267 frame_fmt = record_file.right(4).toLower();
1268 frame = QImage(canvas->width(),canvas->height(),QImage::Format_RGB32);
1269 if (frame_fmt != QLatin1String(".png") && (!convertAvailable || frame_fmt != QLatin1String(".gif"))) {
1270 // Stream video to ffmpeg
1272 QProcess *proc = new QProcess(this);
1273 connect(proc, SIGNAL(finished(int)), this, SLOT(ffmpegFinished(int)));
1274 frame_stream = proc;
1277 args << QLatin1String("-y");
1278 args << QLatin1String("-r") << QString::number(record_rate);
1279 args << QLatin1String("-f") << QLatin1String("rawvideo");
1280 args << QLatin1String("-pix_fmt") << (frame_fmt == QLatin1String(".gif") ? QLatin1String("rgb24") : QLatin1String("rgb32"));
1281 args << QLatin1String("-s") << QString::fromAscii("%1x%2").arg(canvas->width()).arg(canvas->height());
1282 args << QLatin1String("-i") << QLatin1String("-");
1283 if (record_outsize.isValid()) {
1284 args << QLatin1String("-s") << QString::fromAscii("%1x%2").arg(record_outsize.width()).arg(record_outsize.height());
1285 args << QLatin1String("-aspect") << QString::number(double(canvas->width())/canvas->height());
1287 args += record_args;
1288 args << record_file;
1289 proc->start(QLatin1String("ffmpeg"), args);
1292 // Store frames, save to GIF/PNG
1296 canvas->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
1299 qDebug() << "Saving video...";
1300 frame_stream->close();
1301 qDebug() << "Wrote" << record_file;
1303 QProgressDialog progress(tr("Saving frames..."), tr("Cancel"), 0, frames.count()+10, this);
1304 progress.setWindowModality(Qt::WindowModal);
1308 qDebug() << "Saving frames...";
1311 bool png_output = false;
1312 if (record_file.right(4).toLower() == QLatin1String(".png")) {
1313 if (record_file.contains(QLatin1Char('%')))
1314 framename = record_file;
1316 framename = record_file.left(record_file.length()-4) + QLatin1String("%04d") + record_file.right(4);
1319 framename = QLatin1String("tmp-frame%04d.png");
1322 foreach (QImage* img, frames) {
1323 progress.setValue(progress.value()+1);
1324 if (progress.wasCanceled())
1327 name.sprintf(framename.toLocal8Bit(),frame++);
1328 if (record_outsize.isValid())
1329 *img = img->scaled(record_outsize,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
1330 if (record_dither==QLatin1String("ordered"))
1331 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::OrderedDither).save(name);
1332 else if (record_dither==QLatin1String("threshold"))
1333 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::ThresholdDither).save(name);
1334 else if (record_dither==QLatin1String("floyd"))
1335 img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither).save(name);
1342 if (!progress.wasCanceled()) {
1344 framename.replace(QRegExp(QLatin1String("%\\d*.")), QLatin1String("*"));
1345 qDebug() << "Wrote frames" << framename;
1346 inputs.clear(); // don't remove them
1348 // ImageMagick and gifsicle for GIF encoding
1349 progress.setLabelText(tr("Converting frames to GIF file..."));
1351 args << QLatin1String("-delay") << QString::number(period/10);
1353 args << record_file;
1354 qDebug() << "Converting..." << record_file << "(this may take a while)";
1355 if (0!=QProcess::execute(QLatin1String("convert"), args)) {
1356 qWarning() << "Cannot run ImageMagick 'convert' - recorded frames not converted";
1357 inputs.clear(); // don't remove them
1358 qDebug() << "Wrote frames tmp-frame*.png";
1360 if (record_file.right(4).toLower() == QLatin1String(".gif")) {
1361 qDebug() << "Compressing..." << record_file;
1362 if (0!=QProcess::execute(QLatin1String("gifsicle"), QStringList() << QLatin1String("-O2")
1363 << QLatin1String("-o") << record_file << record_file))
1364 qWarning() << "Cannot run 'gifsicle' - not compressed";
1366 qDebug() << "Wrote" << record_file;
1371 progress.setValue(progress.maximum()-1);
1372 foreach (QString name, inputs)
1373 QFile::remove(name);
1378 qDebug() << "Recording: " << (recordTimer.isActive()?"ON":"OFF");
1381 void QDeclarativeViewer::ffmpegFinished(int code)
1383 qDebug() << "ffmpeg returned" << code << frame_stream->readAllStandardError();
1386 void QDeclarativeViewer::appAboutToQuit()
1388 // avoid QGLContext errors about invalid contexts on exit
1389 canvas->setViewport(0);
1391 // avoid crashes if messages are received after app has closed
1392 delete loggerWindow;
1398 void QDeclarativeViewer::autoStartRecording()
1401 autoStopTimer.setInterval(record_autotime);
1402 autoStopTimer.start();
1405 void QDeclarativeViewer::autoStopRecording()
1407 setRecording(false);
1410 void QDeclarativeViewer::recordFrame()
1412 canvas->QWidget::render(&frame);
1414 if (frame_fmt == QLatin1String(".gif")) {
1415 // ffmpeg can't do 32bpp with gif
1416 QImage rgb24 = frame.convertToFormat(QImage::Format_RGB888);
1417 frame_stream->write((char*)rgb24.bits(),rgb24.numBytes());
1419 frame_stream->write((char*)frame.bits(),frame.numBytes());
1422 frames.append(new QImage(frame));
1426 void QDeclarativeViewer::changeOrientation(QAction *action)
1430 QString o = action->text();
1431 action->setChecked(true);
1432 #if defined(Q_WS_S60)
1433 CAknAppUi *appUi = static_cast<CAknAppUi *>(CEikonEnv::Static()->AppUi());
1435 CAknAppUi::TAppUiOrientation orientation = appUi->Orientation();
1436 if (o == QLatin1String("Auto-orientation")) {
1437 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationAutomatic);
1438 rotateAction->setVisible(false);
1439 } else if (o == QLatin1String("Portrait")) {
1440 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationPortrait);
1441 rotateAction->setVisible(true);
1442 } else if (o == QLatin1String("Landscape")) {
1443 appUi->SetOrientationL(CAknAppUi::EAppUiOrientationLandscape);
1444 rotateAction->setVisible(true);
1448 if (o == QLatin1String("Portrait"))
1449 DeviceOrientation::instance()->setOrientation(DeviceOrientation::Portrait);
1450 else if (o == QLatin1String("Landscape"))
1451 DeviceOrientation::instance()->setOrientation(DeviceOrientation::Landscape);
1452 else if (o == QLatin1String("Portrait (inverted)"))
1453 DeviceOrientation::instance()->setOrientation(DeviceOrientation::PortraitInverted);
1454 else if (o == QLatin1String("Landscape (inverted)"))
1455 DeviceOrientation::instance()->setOrientation(DeviceOrientation::LandscapeInverted);
1459 void QDeclarativeViewer::orientationChanged()
1464 void QDeclarativeViewer::setDeviceKeys(bool on)
1469 void QDeclarativeViewer::setNetworkCacheSize(int size)
1471 namFactory->setCacheSize(size);
1474 void QDeclarativeViewer::setUseGL(bool useGL)
1478 QGLFormat format = QGLFormat::defaultFormat();
1480 format.setSampleBuffers(true);
1481 format.setSwapInterval(1);
1483 format.setSampleBuffers(false);
1486 QGLWidget *glWidget = new QGLWidget(format);
1487 //### potentially faster, but causes junk to appear if top-level is Item, not Rectangle
1488 //glWidget->setAutoFillBackground(false);
1490 canvas->setViewport(glWidget);
1497 void QDeclarativeViewer::setUseNativeFileBrowser(bool use)
1499 useQmlFileBrowser = !use;
1502 void QDeclarativeViewer::setSizeToView(bool sizeToView)
1504 QDeclarativeView::ResizeMode resizeMode = sizeToView ? QDeclarativeView::SizeRootObjectToView : QDeclarativeView::SizeViewToRootObject;
1505 if (resizeMode != canvas->resizeMode()) {
1506 canvas->setResizeMode(resizeMode);
1511 void QDeclarativeViewer::updateSizeHints(bool initial)
1513 static bool isRecursive = false;
1519 if (initial || (canvas->resizeMode() == QDeclarativeView::SizeViewToRootObject)) {
1520 QSize newWindowSize = initial ? initialSize : canvas->sizeHint();
1521 //qWarning() << "USH:" << (initial ? "INIT:" : "V2R:") << "setting fixed size " << newWindowSize;
1522 if (!isFullScreen() && !isMaximized()) {
1523 canvas->setFixedSize(newWindowSize);
1525 layout()->setSizeConstraint(QLayout::SetFixedSize);
1526 layout()->activate();
1529 //qWarning() << "USH: R2V: setting free size ";
1530 layout()->setSizeConstraint(QLayout::SetNoConstraint);
1531 layout()->activate();
1532 setMinimumSize(minimumSizeHint());
1533 setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
1534 canvas->setMinimumSize(QSize(0,0));
1535 canvas->setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
1537 isRecursive = false;
1540 void QDeclarativeViewer::registerTypes()
1542 static bool registered = false;
1545 // registering only for exposing the DeviceOrientation::Orientation enum
1546 qmlRegisterUncreatableType<DeviceOrientation>("Qt", 4, 7, "Orientation", QString());
1547 qmlRegisterUncreatableType<DeviceOrientation>("QtQuick", 1, 0, "Orientation", QString());
1554 #include "qmlruntime.moc"