QTfrontend/ui/widget/databrowser.cpp
changeset 6060 fdfc01419815
parent 5780 528dd4a14861
child 6616 f77bb02b669f
equal deleted inserted replaced
6059:ddf020d0941a 6060:fdfc01419815
       
     1 #include <QNetworkAccessManager>
       
     2 #include <QNetworkRequest>
       
     3 #include <QNetworkReply>
       
     4 #include <QDebug>
       
     5 #include <QUrl>
       
     6 
       
     7 #include "databrowser.h"
       
     8 
       
     9 const QNetworkRequest::Attribute typeAttribute = (QNetworkRequest::Attribute)(QNetworkRequest::User + 1);
       
    10 const QNetworkRequest::Attribute urlAttribute = (QNetworkRequest::Attribute)(QNetworkRequest::User + 2);
       
    11 
       
    12 DataBrowser::DataBrowser(QWidget *parent) :
       
    13     QTextBrowser(parent)
       
    14 {
       
    15 
       
    16     manager = new QNetworkAccessManager(this);
       
    17 }
       
    18 
       
    19 QVariant DataBrowser::loadResource(int type, const QUrl & name)
       
    20 {
       
    21     if(type == QTextDocument::ImageResource || type == QTextDocument::StyleSheetResource)
       
    22     {
       
    23         if(resources.contains(name.toString()))
       
    24         {
       
    25             return resources.take(name.toString());
       
    26         }
       
    27         else
       
    28             if(!requestedResources.contains(name.toString()))
       
    29             {
       
    30                 qDebug() << "Requesting resource" << name.toString();
       
    31                 requestedResources.insert(name.toString());
       
    32 
       
    33                 QNetworkRequest newRequest(QUrl("http://www.hedgewars.org" + name.toString()));
       
    34                 newRequest.setAttribute(typeAttribute, type);
       
    35                 newRequest.setAttribute(urlAttribute, name);
       
    36 
       
    37                 QNetworkReply *reply = manager->get(newRequest);
       
    38                 connect(reply, SIGNAL(finished()), this, SLOT(resourceDownloaded()));
       
    39             }
       
    40     }
       
    41 
       
    42     return QVariant();
       
    43 }
       
    44 
       
    45 void DataBrowser::resourceDownloaded()
       
    46 {
       
    47     QNetworkReply * reply = qobject_cast<QNetworkReply *>(sender());
       
    48 
       
    49     if(reply)
       
    50     {
       
    51         int type = reply->request().attribute(typeAttribute).toInt();
       
    52         QUrl url = reply->request().attribute(urlAttribute).toUrl();
       
    53         resources.insert(url.toString(), reply->readAll());
       
    54         document()->addResource(type, reply->request().url(), QVariant());
       
    55         update();
       
    56     }
       
    57 }