qtmobility/examples/flickrdemo/flickrdemo.cpp
changeset 4 90517678cc4f
parent 1 2b40d63a9c3d
child 5 453da2cfceef
--- a/qtmobility/examples/flickrdemo/flickrdemo.cpp	Fri Apr 16 15:51:22 2010 +0300
+++ b/qtmobility/examples/flickrdemo/flickrdemo.cpp	Mon May 03 13:18:40 2010 +0300
@@ -50,25 +50,36 @@
 #include <qnetworkconfigmanager.h>
 #include <qnetworksession.h>
 
+#include <QAction>
+#include <QApplication>
+#include <QDialogButtonBox>
+#include <QDir>
+#include <QFile>
+#include <QLabel>
+#include <QMenuBar>
+#include <QMessageBox>
+#include <QNetworkAccessManager>
+#include <QNetworkRequest>
+#include <QProgressDialog>
+#include <QPushButton>
+#include <QTimer>
+#include <QVBoxLayout>
+#include <QWidget>
+
 // static constant intialization
 
 const QSize FlickrDemo::gridSize = QSize(52, 52);
 const QSize FlickrDemo::thumbnailSize = QSize(50, 50);
 const QSize FlickrDemo::imageSize = QSize(150, 150);
 const QString FlickrDemo::apikey = QString("e36784df8a03fea04c22ed93318b291c");
-#ifdef Q_OS_SYMBIAN
-const QString FlickrDemo::savePath = "c:\\Data\\Images\\"; // In S60 Download images to Gallery
-#else
-const QString FlickrDemo::savePath = QDir::tempPath();
-#endif
 
 FlickrDemo::FlickrDemo(QWidget* parent) :
         QMainWindow(parent),
         m_logfileInUse(false),
         m_session(0),
-        m_file(0),
-        m_httpGetId(-1),
-        m_httpThumbnailGetId(-1),
+        m_pictureListReply(0),
+        m_thumbnailReply(0),
+        m_pictureReply(0),
         m_pages(0),
         m_page(1),
         m_satellitesInView(0),
@@ -76,7 +87,7 @@
         m_latitude(-1000),
         m_longitude(-1000),
         m_downloadPictureList(true),
-        m_downloadingThumbnails(false)
+        m_shuttingDown(false)
 {
     resize(252, 344);
 
@@ -132,24 +143,32 @@
                 this, SLOT(satellitesInUseUpdated(const QList<QGeoSatelliteInfo>&)));
     }
 
-    // QHttp
-    m_http = new QHttp(this);
-    connect(m_http, SIGNAL(requestFinished(int, bool)),
-            this, SLOT(httpRequestFinished(int, bool)));
-    connect(m_http, SIGNAL(dataReadProgress(int, int)),
-            this, SLOT(updateDataReadProgress(int, int)));
-    connect(m_http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader&)),
-            this, SLOT(readResponseHeader(const QHttpResponseHeader&)));
+    m_nam = new QNetworkAccessManager(this);
 
     QTimer::singleShot(0, this, SLOT(delayedInit()));
 }
 
 FlickrDemo::~FlickrDemo()
 {
+    m_shuttingDown = true;
+
     m_location->stopUpdates();
     if (m_satellite)
         m_satellite->stopUpdates();
-    m_http->abort();
+
+    if (m_pictureListReply) {
+        m_pictureListReply->abort();
+        delete m_pictureListReply;
+    }
+    if (m_thumbnailReply) {
+        m_thumbnailReply->abort();
+        delete m_thumbnailReply;
+    }
+    if (m_pictureReply) {
+        m_pictureReply->abort();
+        delete m_pictureReply;
+    }
+
     if (m_session)
         m_session->close();
 }
@@ -161,11 +180,11 @@
                                  tr("No GPS support detected, using GPS data from a sample log file instead."));
     }
 
-    QNetworkConfigurationManager manager;
+    QTM_PREPEND_NAMESPACE(QNetworkConfigurationManager) manager;
     const bool canStartIAP = (manager.capabilities()
-                              & QNetworkConfigurationManager::CanStartAndStopInterfaces);
-    QNetworkConfiguration cfg = manager.defaultConfiguration();
-    if (!cfg.isValid() || (!canStartIAP && cfg.state() != QNetworkConfiguration::Active)) {
+                              & QTM_PREPEND_NAMESPACE(QNetworkConfigurationManager)::CanStartAndStopInterfaces);
+    QTM_PREPEND_NAMESPACE(QNetworkConfiguration) cfg = manager.defaultConfiguration();
+    if (!cfg.isValid() || (!canStartIAP && cfg.state() != QTM_PREPEND_NAMESPACE(QNetworkConfiguration)::Active)) {
         QMessageBox::information(this, tr("Flickr Demo"), tr("Available Access Points not found."));
         return;
     }
@@ -282,10 +301,20 @@
 
     QUrl url(urlstring);
 
-    m_http->setHost(url.host(), QHttp::ConnectionModeHttp, url.port() == -1 ? 0 : url.port());
-    m_httpRequestAborted = false;
-
-    m_httpGetId = m_http->get(urlstring);
+    QNetworkRequest req(url);
+    m_pictureListReply = m_nam->get(req);
+    connect(m_pictureListReply,
+            SIGNAL(downloadProgress(qint64, qint64)),
+            this,
+            SLOT(pictureListDownloadProgress(qint64, qint64)));
+    connect(m_pictureListReply,
+            SIGNAL(finished()),
+            this,
+            SLOT(pictureListFinished()));
+    connect(m_pictureListReply,
+            SIGNAL(error(QNetworkReply::NetworkError)),
+            this,
+            SLOT(pictureListError(QNetworkReply::NetworkError)));
 
     m_progressDialog->setWindowTitle(tr("FlickrDemo"));
     m_progressDialog->setLabelText(tr("Downloading\nPicture List."));
@@ -366,49 +395,24 @@
     pictureUrl.append("_m.jpg");
 
     QUrl url(pictureUrl);
-    QFileInfo fileInfo(url.path());
-    QString fileName = fileInfo.fileName();
-    if (fileName.isEmpty()) {
-        fileName = "test.jpg";
-    }
 
-    m_filePath = savePath;
-    m_filePath.append(fileName);
-
-    if (QFile::exists(m_filePath)) {
-        if (QMessageBox::question(this,
-                                  tr("Flickr Demo"),
-                                  tr("File %1 is already downloaded."
-                                     "Overwrite?").arg(fileName),
-                                  QMessageBox::Yes | QMessageBox::No,
-                                  QMessageBox::No)
-                == QMessageBox::No) {
-            displayImage();
-            return;
-        }
-        QFile::remove(m_filePath);
-    }
-
-    m_file = new QFile(m_filePath);
-    if (!m_file->open(QIODevice::WriteOnly)) {
-        QMessageBox::information(this, tr("Flickr Demo"),
-                                 tr("Unable to save the file %1: %2.").arg(m_filePath).arg(m_file->errorString()));
-        delete m_file;
-        m_file = 0;
-        return;
-    }
-
-    m_http->setHost(url.host(), QHttp::ConnectionModeHttp, url.port() == -1 ? 0 : url.port());
-
-    m_httpRequestAborted = false;
-    QByteArray encodedUrl = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
-    if (encodedUrl.isEmpty()) {
-        encodedUrl = "/";
-    }
-    m_httpGetId = m_http->get(encodedUrl, m_file);
+    QNetworkRequest req(url);
+    m_pictureReply = m_nam->get(req);
+    connect(m_pictureReply,
+            SIGNAL(downloadProgress(qint64, qint64)),
+            this,
+            SLOT(pictureDownloadProgress(qint64, qint64)));
+    connect(m_pictureReply,
+            SIGNAL(finished()),
+            this,
+            SLOT(pictureFinished()));
+    connect(m_pictureReply,
+            SIGNAL(error(QNetworkReply::NetworkError)),
+            this,
+            SLOT(pictureError(QNetworkReply::NetworkError)));
 
     m_progressDialog->setWindowTitle(tr("Flickr Demo"));
-    m_progressDialog->setLabelText(tr("Downloading:\n%1").arg(fileName));
+    m_progressDialog->setLabelText(tr("Downloading:\n%1").arg(pictureUrl));
     m_progressDialog->setMaximum(10);
     m_progressDialog->setValue(0);
     m_progressDialog->show();
@@ -418,121 +422,153 @@
 
 void FlickrDemo::cancelDownload()
 {
-    m_httpRequestAborted = true;
-    m_downloadingThumbnails = false;
-    m_http->abort();
-    downloadButton->setEnabled(true);
-}
-
-void FlickrDemo::httpRequestFinished(int requestId, bool error)
-{
-    if (m_downloadingThumbnails && m_httpThumbnailGetId == requestId) {
-        if (!error) {
-            QByteArray picture = m_http->readAll();
-            if (!picture.isNull() && picture.size() > 0) {
-                QListWidgetItem* item = listWidget->item(m_nameCounter);
-                QImage image;
-                if (image.loadFromData(picture, "jpg")) {
-                    item->setIcon(QPixmap::fromImage(image.scaled(thumbnailSize,
-                                                     Qt::KeepAspectRatio, Qt::SmoothTransformation)));
-                    listWidget->update();
-                }
-            }
-        }
-        downloadNextThumbnail();
-        return;
-    }
-
-    if (requestId != m_httpGetId) {
-        return;
+    if (m_pictureListReply) {
+        m_pictureListReply->abort();
+        delete m_pictureListReply;
+        m_pictureListReply = 0;
     }
 
-    m_progressDialog->hide();
-
-    if (m_httpRequestAborted) {
-        if (m_file) {
-            m_file->close();
-            m_file->remove();
-            delete m_file;
-            m_file = 0;
-        }
-
-        return;
-    }
-
-    if (!m_downloadPictureList && m_file) {
-        m_file->close();
-    }
-
-    if (error) {
-        if (!m_downloadPictureList && m_file) {
-            m_file->remove();
-        }
-        QMessageBox::information(this,
-                                 tr("Flickr Demo"),
-                                 tr("Download failed: %1.").arg(m_http->errorString()));
-    }
-
-    if (m_downloadPictureList) {
-        if (parsePictureList(QString::fromUtf8(m_http->readAll()))) {
-            m_downloadPictureList = false;
-            downloadButton->setText(tr("Download Selected Picture"));
-            m_downloadAct->setText(tr("Download Selected Picture"));
-        }
-    } else {
-        displayImage();
+    if (m_pictureReply) {
+        m_pictureReply->abort();
+        delete m_pictureReply;
+        m_pictureReply = 0;
     }
 
     downloadButton->setEnabled(true);
 }
 
-void FlickrDemo::displayImage()
+void FlickrDemo::pictureListDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
+{
+    m_progressDialog->setMaximum(bytesTotal);
+    m_progressDialog->setValue(bytesReceived);
+}
+
+void FlickrDemo::pictureListFinished()
+{
+    m_progressDialog->hide();
+    if (parsePictureList(QString::fromUtf8(m_pictureListReply->readAll()))) {
+        m_downloadPictureList = false;
+        downloadButton->setText(tr("Download Selected Picture"));
+        m_downloadAct->setText(tr("Download Selected Picture"));
+    }
+
+    downloadButton->setEnabled(true);
+
+    QTimer::singleShot(0, this, SLOT(clearPictureListRequest()));
+}
+
+void FlickrDemo::pictureListError(QNetworkReply::NetworkError code)
+{
+    if (m_shuttingDown)
+        return;
+
+    m_progressDialog->hide();
+    QMessageBox::information(this,
+                             tr("Flickr Demo"),
+                             tr("Error downloading picture list: %1.").arg(m_pictureListReply->errorString()));
+
+    QTimer::singleShot(0, this, SLOT(clearPictureListRequest()));
+}
+
+void FlickrDemo::clearPictureListRequest()
+{
+    delete m_pictureListReply;
+    m_pictureListReply = 0;
+}
+
+void FlickrDemo::thumbnailFinished()
+{
+    QByteArray picture = m_thumbnailReply->readAll();
+    if (!picture.isNull() && picture.size() > 0) {
+        QListWidgetItem* item = listWidget->item(m_nameCounter);
+        QImage image;
+        if (image.loadFromData(picture, "jpg")) {
+            item->setIcon(QPixmap::fromImage(
+                              image.scaled(thumbnailSize,
+                                           Qt::KeepAspectRatio,
+                                           Qt::SmoothTransformation)));
+            listWidget->update();
+        }
+    }
+    downloadNextThumbnail();
+}
+
+void FlickrDemo::thumbnailError(QNetworkReply::NetworkError code)
 {
-    PictureDialog dialog(m_filePath, listWidget->currentItem()->text(), this);
+    if (m_shuttingDown)
+        return;
+
+    QMessageBox::information(this,
+                             tr("Flickr Demo"),
+                             tr("Error downloading thumbnails: %1.").arg(m_thumbnailReply->errorString()));
+
+    QTimer::singleShot(0, this, SLOT(clearThumbnailRequest()));
+}
+
+void FlickrDemo::clearThumbnailRequest()
+{
+    delete m_thumbnailReply;
+    m_thumbnailReply = 0;
+}
+
+void FlickrDemo::pictureDownloadProgress(qint64 bytesReceived, qint64 bytesTotal)
+{
+    m_progressDialog->setMaximum(bytesTotal);
+    m_progressDialog->setValue(bytesReceived);
+}
+
+void FlickrDemo::pictureFinished()
+{
+    m_progressDialog->hide();
+    downloadButton->setEnabled(true);
+
+    QByteArray picture = m_pictureReply->readAll();
+
+    if (picture.isNull() || picture.size() <= 0)
+        return;
+
+    QImage image;
+    if (!image.loadFromData(picture, "jpg"))
+        return;
+
+    QPixmap pixmap = QPixmap::fromImage(
+                         image.scaled(imageSize,
+                                      Qt::KeepAspectRatio,
+                                      Qt::SmoothTransformation));
+
+    displayImage(pixmap);
+
+    QTimer::singleShot(0, this, SLOT(clearPictureRequest()));
+}
+
+void FlickrDemo::pictureError(QNetworkReply::NetworkError code)
+{
+    if (m_shuttingDown)
+        return;
+
+    m_progressDialog->hide();
+    QMessageBox::information(this,
+                             tr("Flickr Demo"),
+                             tr("Error downloading picture: %1.").arg(m_pictureReply->errorString()));
+
+    downloadButton->setEnabled(true);
+
+    QTimer::singleShot(0, this, SLOT(clearPictureRequest()));
+}
+
+void FlickrDemo::clearPictureRequest()
+{
+    delete m_pictureReply;
+    m_pictureReply = 0;
+}
+
+void FlickrDemo::displayImage(const QPixmap &pixmap)
+{
+    PictureDialog dialog(pixmap, listWidget->currentItem()->text(), this);
 #if defined(Q_OS_SYMBIAN) || defined (Q_OS_WINCE)
     dialog.showMaximized();
 #endif
-    if (!dialog.exec()) {
-        if (m_file && m_file->exists()) {
-            m_file->remove();
-        }
-    }
-    if(m_file)
-        delete m_file;
-    m_file = 0;
-}
-
-void FlickrDemo::readResponseHeader(const QHttpResponseHeader& responseHeader)
-{
-    switch (responseHeader.statusCode()) {
-        case 200: // Ok
-        case 301: // Moved Permanently
-        case 302: // Found
-        case 303: // See Other
-        case 307: // Temporary Redirect
-            // these are not error conditions
-            break;
-        default:
-            QMessageBox::information(this,
-                                     tr("Flickr Demo"),
-                                     tr("Download failed: %1.").arg(responseHeader.reasonPhrase()));
-            m_downloadingThumbnails = false;
-            m_httpRequestAborted = true;
-            m_progressDialog->hide();
-            m_http->abort();
-    }
-}
-
-void FlickrDemo::updateDataReadProgress(int bytesRead, int totalBytes)
-{
-    if (m_httpRequestAborted) {
-        return;
-    }
-
-    if (!m_downloadingThumbnails) {
-        m_progressDialog->setMaximum(totalBytes);
-        m_progressDialog->setValue(bytesRead);
-    }
+    dialog.exec();
 }
 
 void FlickrDemo::downloadNextThumbnail()
@@ -542,19 +578,23 @@
         QString pictureUrl = m_names[m_nameCounter];
         pictureUrl.append("_s.jpg");
         QUrl url(pictureUrl);
-        m_http->setHost(url.host(), QHttp::ConnectionModeHttp, url.port() == -1 ? 0 : url.port());
-        m_downloadingThumbnails = true;
-        m_httpThumbnailGetId = m_http->get(pictureUrl);
+
+        QNetworkRequest req(url);
+        m_thumbnailReply = m_nam->get(req);
+        connect(m_thumbnailReply,
+                SIGNAL(finished()),
+                this,
+                SLOT(thumbnailFinished()));
+        connect(m_thumbnailReply,
+                SIGNAL(error(QNetworkReply::NetworkError)),
+                this,
+                SLOT(thumbnailError(QNetworkReply::NetworkError)));
     } else {
-        m_downloadingThumbnails = false;
+        QTimer::singleShot(0, this, SLOT(clearThumbnailRequest()));
     }
 }
 
-// static constant intialization
-
-const QSize PictureDialog::imageSize = QSize(150, 150);
-
-PictureDialog::PictureDialog(const QString& filePath, const QString& pictureName, QWidget* parent) :
+PictureDialog::PictureDialog(const QPixmap& pixmap, const QString& pictureName, QWidget* parent) :
         QDialog(parent)
 {
     resize(252, 361);
@@ -563,8 +603,7 @@
     verticalLayout->setContentsMargins(11, 11, 11, 11);
 
     label = new QLabel();
-    QString fileName = QFileInfo(filePath).fileName();
-    label->setText(tr("Downloaded:\n%1\n%2").arg(pictureName).arg(fileName));
+    label->setText(tr("Downloaded:\n%1").arg(pictureName));
 
     QSizePolicy sizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
     sizePolicy.setHorizontalStretch(0);
@@ -575,21 +614,13 @@
     verticalLayout->addWidget(label);
 
     imageLabel = new QLabel();
-    QImage image;
-    image.load(filePath);
-    imageLabel->setPixmap(QPixmap::fromImage(image.scaled(imageSize, Qt::KeepAspectRatio,
-                          Qt::SmoothTransformation)));
+    imageLabel->setPixmap(pixmap);
 
     verticalLayout->addWidget(imageLabel);
 
-    keepButton = new QPushButton(tr("Keep"));
-    keepButton->setDefault(true);
-    discardButton = new QPushButton(tr("Discard"));
-
     buttonBox = new QDialogButtonBox();
-    buttonBox->addButton(keepButton, QDialogButtonBox::AcceptRole);
-    buttonBox->addButton(discardButton, QDialogButtonBox::DestructiveRole);
-    connect(buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(clicked(QAbstractButton *)));
+    buttonBox->setStandardButtons(QDialogButtonBox::Close);
+    connect(buttonBox, SIGNAL(rejected()), this, SLOT(accept()));
 
     verticalLayout->addWidget(buttonBox);
 
@@ -597,12 +628,3 @@
 
     setWindowTitle(tr("Flickr Demo"));
 }
-
-void PictureDialog::clicked(QAbstractButton* button)
-{
-    if (button == keepButton) {
-        accept();
-    } else if (button == discardButton) {
-        reject();
-    }
-}