Example #1
0
void DownloadManager::clearList()
{
  QList<DownloadItem*> items;
  for (int i = 0; i < listWidget_->count(); i++) {
    DownloadItem* downItem = qobject_cast<DownloadItem*>(listWidget_->itemWidget(listWidget_->item(i)));
    if (!downItem) {
      continue;
    }
    if (downItem->isDownloading()) {
      continue;
    }
    items.append(downItem);
  }
  qDeleteAll(items);
}
Example #2
0
void DownloadManager::clearFinished()
{
    for(int i = count() - 1; i >= 0; i--)
    {
        DownloadItem * item = m_items.at(i);
        if(item->isFinished())
        {
            beginRemoveRows(QModelIndex(), i, i);
            item->deleteLater();
            m_items.removeAt(i);
            endRemoveRows();
            emit itemDeleted(i);
        }
    }
}
Example #3
0
void DownloadView::buttonPushed(QModelIndex index) {
    const DownloadItemPointer downloadItemPointer = index.data(DownloadItemRole).value<DownloadItemPointer>();
    DownloadItem *downloadItem = downloadItemPointer.data();

    switch (downloadItem->status()) {
    case Downloading:
    case Starting:
        downloadItem->stop();
        break;
    case Idle:
    case Failed:
        downloadItem->tryAgain();
        break;
    case Finished:
        downloadItem->openFolder();
    }

}
void DownloadManager::handleUnsupportedContent(QNetworkReply *reply, bool requestFileName)
{
    if (!reply || reply->url().isEmpty())
        return;
    QVariant header = reply->header(QNetworkRequest::ContentLengthHeader);
    bool ok;
    int size = header.toInt(&ok);
    if (ok && size == 0)
        return;

    qDebug() << "DownloadManager::handleUnsupportedContent" << reply->url() << "requestFileName" << requestFileName;
    DownloadItem *item = new DownloadItem(reply, requestFileName, this);
    
    if (item->initSuccess())
        addItem(item);
    else
        delete item;
}
Example #5
0
bool DownloadManager::canClose()
{
    if (m_isClosing) {
        return true;
    }

    bool isDownloading = false;
    for (int i = 0; i < ui->list->count(); i++) {
        DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
        if (!downItem) {
            continue;
        }
        if (downItem->isDownloading()) {
            isDownloading = true;
            break;
        }
    }

    return !isDownloading;
}
Example #6
0
void DownloadView::onLoadFinished()
{
    DownloadItem *item = qobject_cast<DownloadItem*>(sender());
    QString file_name = item->fileName();
    if (file_name.endsWith(".pdf") ||
        file_name.endsWith(".epub") ||
        file_name.endsWith(".txt") ||
        file_name.endsWith(".pdb") ||
        file_name.endsWith(".rtf") ||
        file_name.endsWith(".mobi"))
    {
        latest_file_name_ = file_name;
    }

    if (download_manager_ != 0 && download_manager_->stillDownloading())
    {
        return;
    }
    noticeLoadFinish();
}
Example #7
0
void DownloadManager::downloadFinished(bool success)
{
    m_activeDownloadsCount = 0;
    bool downloadingAllFilesFinished = true;
    for (int i = 0; i < ui->list->count(); i++) {
        DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
        if (!downItem) {
            continue;
        }
        if (downItem->isDownloading()) {
            m_activeDownloadsCount++;
        }
        if (downItem->isCancelled() || !downItem->isDownloading()) {
            continue;
        }
        downloadingAllFilesFinished = false;
    }

    emit downloadsCountChanged();

    if (downloadingAllFilesFinished) {
        if (success && qApp->activeWindow() != this) {
            mApp->desktopNotifications()->showNotification(QIcon::fromTheme(QSL("download"), QIcon(QSL(":icons/other/download.svg"))).pixmap(48), tr("QupZilla: Download Finished"), tr("All files have been successfully downloaded."));
            if (!m_closeOnFinish) {
                raise();
                activateWindow();
            }
        }
        ui->speedLabel->clear();
        setWindowTitle(tr("Download Manager"));
#ifdef Q_OS_WIN
        if (m_taskbarButton) {
            m_taskbarButton->progress()->hide();
        }
#endif
        if (m_closeOnFinish) {
            close();
        }
    }
}
Example #8
0
void DownloadManager::updateInfo()
{
  QVector<QTime> remTimes;
  for (int i = 0; i < listWidget_->count(); i++) {
    DownloadItem* downItem = qobject_cast<DownloadItem*>(listWidget_->itemWidget(listWidget_->item(i)));
    if (!downItem || !downItem->isDownloading()) {
      continue;
    }
    remTimes.append(downItem->remainingTime());
  }
  QTime remaining;
  foreach (const QTime &time, remTimes) {
    if (time > remaining) {
      remaining = time;
    }
  }

  QString info;
  if (remTimes.count())
    info = QString("%1 (%2)").arg(remaining.toString("mm:ss")).arg(remTimes.count());

  emit signalUpdateInfo(info);
}
Example #9
0
void DownloadManager::timerEvent(QTimerEvent* e)
{
    QVector<QTime> remTimes;
    QVector<int> progresses;
    QVector<double> speeds;

    if (e->timerId() == m_timer.timerId()) {
        if (!ui->list->count()) {
            ui->speedLabel->clear();
            setWindowTitle(tr("Download Manager"));
            return;
        }
        for (int i = 0; i < ui->list->count(); i++) {
            DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
            if (!downItem || (downItem && downItem->isCancelled()) || !downItem->isDownloading()) {
                continue;
            }
            progresses.append(downItem->progress());
            remTimes.append(downItem->remainingTime());
            speeds.append(downItem->currentSpeed());
        }
        if (remTimes.isEmpty()) {
            return;
        }

        QTime remaining;
        foreach (const QTime &time, remTimes) {
            if (time > remaining) {
                remaining = time;
            }
        }

        int progress = 0;
        foreach (int prog, progresses) {
            progress += prog;
        }
        progress = progress / progresses.count();

        double speed = 0.00;
        foreach (double spee, speeds) {
            speed += spee;
        }

        ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()),
                                DownloadItem::currentSpeedToString(speed),
                                DownloadItem::remaingTimeToString(remaining)));
        setWindowTitle(tr("%1% - Download Manager").arg(progress));
#ifdef W7TASKBAR
        if (QtWin::isRunningWindows7()) {
            win7.setProgressValue(progress, 100);
            win7.setProgressState(win7.Normal);
        }
#endif
    }

    QWidget::timerEvent(e);
}
Example #10
0
QImage TransferThumbnailImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{

  int width = requestedSize.width() > 0 ? requestedSize.width() : 200;
  int height = requestedSize.height() > 0 ? requestedSize.height() :100;

  if (size)
    *size = QSize(width, height);


  //Default image
  QImage image(width,
               height,QImage::Format_ARGB32);

  image.fill(qRgba(0, 0, 0, 0));



  int transferId = id.toInt();



  //Load from file
  DownloadItem* download = theApp->models()->downloadsModel()->get(transferId);

  Q_ASSERT(download);
  if(download == NULL)
    return image;

  QString type = theUtils->getFileExtension(download->fileName());

  return theUtils->getFileTypeImage(type,width,height);



}
Example #11
0
void DownloadUI::UpdateInfo(void)
{
    if (!isVisible)
        return;

    DownloadItem *dli = downloadList[m_currentindex];

    if (!dli) {
        gtk_label_set_text(GTK_LABEL(artist), "");
        gtk_label_set_text(GTK_LABEL(album), "");
        gtk_label_set_text(GTK_LABEL(title), "");
        gtk_label_set_text(GTK_LABEL(genre), "");
        gtk_label_set_text(GTK_LABEL(playlist), "");
        gtk_label_set_text(GTK_LABEL(name), "");
        gtk_label_set_text(GTK_LABEL(size), "");
        return;
    }

    gtk_label_set_text(GTK_LABEL(artist), dli->GetMetaData().Artist().c_str());
    gtk_label_set_text(GTK_LABEL(album), dli->GetMetaData().Album().c_str());
    gtk_label_set_text(GTK_LABEL(title), dli->GetMetaData().Title().c_str());
    gtk_label_set_text(GTK_LABEL(genre), dli->GetMetaData().Genre().c_str());
    gtk_label_set_text(GTK_LABEL(playlist), dli->PlaylistName().c_str());
    gtk_label_set_text(GTK_LABEL(name), dli->DestinationFile().c_str());
    float total;
    char totsize[64];
    
    total = dli->GetTotalBytes();
    if (total >= 1048576) {
        total /= 1048576;
        sprintf(totsize, "%.2f MB", total);;
    }
    else if(total >= 1024) {
        total /= 1024;
        sprintf(totsize, "%.2f KB", total);
    }
    else
        sprintf(totsize, "%.2f Bytes", total);
 
    string display = totsize;

    gtk_label_set_text(GTK_LABEL(size), display.c_str());
}
Example #12
0
void DownloadManager::download(QWebEngineDownloadItem *downloadItem)
{
    closeDownloadTab(downloadItem->url());

    QString downloadPath;
    bool openFile = false;

    QString fileName = QFileInfo(downloadItem->path()).fileName();
    fileName = QUrl::fromPercentEncoding(fileName.toUtf8());
    // Filename may have been percent encoded and actually containing path
    fileName = QFileInfo(fileName).fileName();

    const bool forceAsk = downloadItem->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat
            || downloadItem->type() == QWebEngineDownloadItem::UserRequested;

    if (m_useExternalManager) {
        startExternalManager(downloadItem->url());
    } else if (forceAsk || m_downloadPath.isEmpty()) {
        enum Result { Open = 1, Save = 2, ExternalManager = 3, SavePage = 4, Unknown = 0 };
        Result result = Unknown;

        if (downloadItem->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat) {
            // Save Page requested
            result = SavePage;
        } else if (downloadItem->type() == QWebEngineDownloadItem::UserRequested) {
            // Save x as... requested
            result = Save;
        } else {
            // Ask what to do
            DownloadOptionsDialog optionsDialog(fileName, downloadItem, mApp->activeWindow());
            optionsDialog.showExternalManagerOption(m_useExternalManager);
            optionsDialog.setLastDownloadOption(m_lastDownloadOption);
            result = Result(optionsDialog.exec());
        }

        switch (result) {
        case Open:
            openFile = true;
            downloadPath = QzTools::ensureUniqueFilename(DataPaths::path(DataPaths::Temp) + QLatin1Char('/') + fileName);
            m_lastDownloadOption = OpenFile;
            break;

        case Save:
            downloadPath = QFileDialog::getSaveFileName(mApp->activeWindow(), tr("Save file as..."), m_lastDownloadPath + QLatin1Char('/') + fileName);

            if (!downloadPath.isEmpty()) {
                m_lastDownloadPath = QFileInfo(downloadPath).absolutePath();
                Settings().setValue(QSL("DownloadManager/lastDownloadPath"), m_lastDownloadPath);
                m_lastDownloadOption = SaveFile;
            }
            break;

        case SavePage: {
            const QString mhtml = tr("MIME HTML Archive (*.mhtml)");
            const QString htmlSingle = tr("HTML Page, single (*.html)");
            const QString htmlComplete = tr("HTML Page, complete (*.html)");
            const QString filter = QStringLiteral("%1;;%2;;%3").arg(mhtml, htmlSingle, htmlComplete);

            QString selectedFilter;
            downloadPath = QFileDialog::getSaveFileName(mApp->activeWindow(), tr("Save page as..."),
                                                        m_lastDownloadPath + QLatin1Char('/') + fileName,
                                                        filter, &selectedFilter);

            if (!downloadPath.isEmpty()) {
                m_lastDownloadPath = QFileInfo(downloadPath).absolutePath();
                Settings().setValue(QSL("DownloadManager/lastDownloadPath"), m_lastDownloadPath);
                m_lastDownloadOption = SaveFile;

                QWebEngineDownloadItem::SavePageFormat format = QWebEngineDownloadItem::UnknownSaveFormat;

                if (selectedFilter == mhtml) {
                    format = QWebEngineDownloadItem::MimeHtmlSaveFormat;
                } else if (selectedFilter == htmlSingle) {
                    format = QWebEngineDownloadItem::SingleHtmlSaveFormat;
                } else if (selectedFilter == htmlComplete) {
                    format = QWebEngineDownloadItem::CompleteHtmlSaveFormat;
                }

                if (format != QWebEngineDownloadItem::UnknownSaveFormat) {
                    downloadItem->setSavePageFormat(format);
                }
            }
            break;
        }

        case ExternalManager:
            startExternalManager(downloadItem->url());
            // fallthrough

        default:
            downloadItem->cancel();
            return;
        }
    } else {
        downloadPath = QzTools::ensureUniqueFilename(m_downloadPath + QL1C('/') + fileName);
    }

    if (downloadPath.isEmpty()) {
        downloadItem->cancel();
        return;
    }

    // Set download path and accept
    downloadItem->setPath(downloadPath);
    downloadItem->accept();

    // Create download item
    QListWidgetItem* listItem = new QListWidgetItem(ui->list);
    DownloadItem* downItem = new DownloadItem(listItem, downloadItem, QFileInfo(downloadPath).absolutePath(), QFileInfo(downloadPath).fileName(), openFile, this);
    connect(downItem, SIGNAL(deleteItem(DownloadItem*)), this, SLOT(deleteItem(DownloadItem*)));
    connect(downItem, SIGNAL(downloadFinished(bool)), this, SLOT(downloadFinished(bool)));
    ui->list->setItemWidget(listItem, downItem);
    listItem->setSizeHint(downItem->sizeHint());
    downItem->show();

    m_activeDownloadsCount++;
    emit downloadsCountChanged();
}
Example #13
0
void DownloadManager::timerEvent(QTimerEvent* e)
{
    QVector<QTime> remTimes;
    QVector<int> progresses;
    QVector<double> speeds;

    if (e->timerId() == m_timer.timerId()) {
        if (!ui->list->count()) {
            ui->speedLabel->clear();
            setWindowTitle(tr("Download Manager"));
#ifdef Q_OS_WIN
            if (m_taskbarButton) {
                m_taskbarButton->progress()->hide();
            }
#endif
            return;
        }
        for (int i = 0; i < ui->list->count(); i++) {
            DownloadItem* downItem = qobject_cast<DownloadItem*>(ui->list->itemWidget(ui->list->item(i)));
            if (!downItem || downItem->isCancelled() || !downItem->isDownloading()) {
                continue;
            }
            progresses.append(downItem->progress());
            remTimes.append(downItem->remainingTime());
            speeds.append(downItem->currentSpeed());
        }
        if (remTimes.isEmpty()) {
            return;
        }

        QTime remaining;
        foreach (const QTime &time, remTimes) {
            if (time > remaining) {
                remaining = time;
            }
        }

        int progress = 0;
        foreach (int prog, progresses) {
            progress += prog;
        }
        progress = progress / progresses.count();

        double speed = 0.00;
        foreach (double spee, speeds) {
            speed += spee;
        }

#ifndef Q_OS_WIN
        ui->speedLabel->setText(tr("%1% of %2 files (%3) %4 remaining").arg(QString::number(progress), QString::number(progresses.count()),
                                DownloadItem::currentSpeedToString(speed),
                                DownloadItem::remaingTimeToString(remaining)));
#endif
        setWindowTitle(tr("%1% - Download Manager").arg(progress));
#ifdef Q_OS_WIN
        if (m_taskbarButton) {
            m_taskbarButton->progress()->show();
            m_taskbarButton->progress()->setValue(progress);
        }
#endif
    }

    QWidget::timerEvent(e);
}
Example #14
0
DownloadItem* DownloadsModel::addDownload(DownloadItem *pde, struct GNUNET_FS_DownloadContext *dc,
                                          const struct GNUNET_FS_Uri *uri, QString filePath,
                                          const struct GNUNET_CONTAINER_MetaData *meta, qint64 size,
                                          qint64 completed )
{


    //Convert uri to Key
    GNUNET_HashCode hashcode;
    GNUNET_FS_uri_to_key(uri,&hashcode);

    //Get as QString
    const char * hash = GNUNET_h2s_full(&hashcode);
    QString strHash = QString(hash);



    DownloadItem* download = new DownloadItem(strHash);

    download->setParent(pde);
    download->setContext(dc);
    char* fancyName =  GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
                                                                 EXTRACTOR_METATYPE_PACKAGE_NAME,
                                                                 EXTRACTOR_METATYPE_TITLE,
                                                                 EXTRACTOR_METATYPE_BOOK_TITLE,
                                                                 EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
                                                                 EXTRACTOR_METATYPE_FILENAME,
                                                                 EXTRACTOR_METATYPE_DESCRIPTION,
                                                                 EXTRACTOR_METATYPE_SUMMARY,
                                                                 EXTRACTOR_METATYPE_ALBUM,
                                                                 EXTRACTOR_METATYPE_COMMENT,
                                                                 EXTRACTOR_METATYPE_SUBJECT,
                                                                 EXTRACTOR_METATYPE_KEYWORDS,
                                                                 -1);

    char* fileName =  GNUNET_CONTAINER_meta_data_get_first_by_types (meta,
                                                                 EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME,
                                                                 EXTRACTOR_METATYPE_PACKAGE_NAME,
                                                                 EXTRACTOR_METATYPE_TITLE,
                                                                 EXTRACTOR_METATYPE_BOOK_TITLE,
                                                                 EXTRACTOR_METATYPE_FILENAME,
                                                                 EXTRACTOR_METATYPE_DESCRIPTION,
                                                                 EXTRACTOR_METATYPE_SUMMARY,
                                                                 EXTRACTOR_METATYPE_ALBUM,
                                                                 EXTRACTOR_METATYPE_COMMENT,
                                                                 EXTRACTOR_METATYPE_SUBJECT,
                                                                 EXTRACTOR_METATYPE_KEYWORDS,
                                                                 -1);



    download->setPath(filePath);
    download->setFancyName(QString(fancyName));
    download->setFileName(QString(fileName));
    download->setMetadata(meta);
    download->setSize(size);
    download->setCompleted(completed);


    emit addDownloadSignal(download);

    return download;


}
Example #15
0
static bool downloadResource(const KUrl& srcUrl, const KIO::MetaData& metaData = KIO::MetaData(),
                             QWidget * parent = 0, const QString & suggestedName = QString())
{
    KUrl destUrl;

    int result = KIO::R_OVERWRITE;
    const QString fileName((suggestedName.isEmpty() ? srcUrl.fileName() : suggestedName));

    do
    {
        // follow bug:184202 fixes
        destUrl = KFileDialog::getSaveFileName(KUrl(KGlobalSettings::downloadPath().append(fileName)), QString(), parent);

        if (destUrl.isEmpty())
            return false;

        if (destUrl.isLocalFile())
        {
            QFileInfo finfo(destUrl.toLocalFile());
            if (finfo.exists())
            {
                QDateTime now = QDateTime::currentDateTime();
                QPointer<KIO::RenameDialog> dlg = new KIO::RenameDialog(parent,
                        i18n("Overwrite File?"),
                        srcUrl,
                        destUrl,
                        KIO::RenameDialog_Mode(KIO::M_OVERWRITE | KIO::M_SKIP),
                        -1,
                        finfo.size(),
                        now.toTime_t(),
                        finfo.created().toTime_t(),
                        now.toTime_t(),
                        finfo.lastModified().toTime_t()
                                                                       );
                result = dlg->exec();
                delete dlg;
            }
        }
    }
    while (result == KIO::R_CANCEL && destUrl.isValid());

    // Save download history
    DownloadItem *item = rApp->downloadManager()->addDownload(srcUrl.pathOrUrl(), destUrl.pathOrUrl());

    if (!KStandardDirs::findExe("kget").isNull() && ReKonfig::kgetDownload())
    {
        //KGet integration:
        if (!QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kget"))
        {
            KToolInvocation::kdeinitExecWait("kget");
        }
        QDBusInterface kget("org.kde.kget", "/KGet", "org.kde.kget.main");
        if (!kget.isValid())
            return false;

        QDBusMessage transfer = kget.call(QL1S("addTransfer"), srcUrl.prettyUrl(), destUrl.prettyUrl(), true);
        if (transfer.arguments().isEmpty())
            return true;

        const QString transferPath = transfer.arguments().first().toString();
        item->setKGetTransferDbusPath(transferPath);
        return true;
    }

    KIO::Job *job = KIO::file_copy(srcUrl, destUrl, -1, KIO::Overwrite);
    if (item)
    {
        QObject::connect(job, SIGNAL(percent(KJob *,unsigned long)), item, SLOT(updateProgress(KJob *,unsigned long)));
        QObject::connect(job, SIGNAL(finished(KJob *)), item, SLOT(onFinished(KJob*)));
    }

    if (!metaData.isEmpty())
        job->setMetaData(metaData);

    job->addMetaData(QL1S("MaxCacheSize"), QL1S("0")); // Don't store in http cache.
    job->addMetaData(QL1S("cache"), QL1S("cache")); // Use entry from cache if available.
    job->uiDelegate()->setAutoErrorHandlingEnabled(true);
    return true;
}
Example #16
0
void NetworkAccessManager::HandleDownload(QObject *object){
#ifdef WEBENGINEVIEW
    static QSet<QObject*> set;
    if(set.contains(object)) return;
    set << object;
    connect(object, &QObject::destroyed, [object](){ set.remove(object);});

    Application::AskDownloadPolicyIfNeed();

    DownloadItem *item = new DownloadItem(object);
    QWebEngineDownloadItem *orig_item = qobject_cast<QWebEngineDownloadItem*>(object);

    QString dir = Application::GetDownloadDirectory();
    QString filename;
    QString mime;
    QUrl url;
    if(orig_item){
        if(WebEngineView *w = qobject_cast<WebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = orig_item->path();
        mime = orig_item->mimeType();
        url = orig_item->url();
    } else {
        if(QuickWebEngineView *w = qobject_cast<QuickWebEngineView*>(Application::CurrentWidget())){
            if(TreeBank *tb = w->GetTreeBank()) tb->GoBackOrCloseForDownload(w);
        }
        filename = object->property("path").toString();
        mime = object->property("mimeType").toString();
        url = object->property("url").toUrl();
    }

    filename = filename.isEmpty() ? dir
        : dir + filename.split(QStringLiteral("/")).last();

    if(filename.isEmpty() ||
       Application::GetDownloadPolicy() == Application::Undefined_ ||
       Application::GetDownloadPolicy() == Application::AskForEachDownload){

        QString filter;

        QMimeDatabase db;
        QMimeType mimeType = db.mimeTypeForName(mime);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForFile(filename);
        if(!mimeType.isValid() || mimeType.isDefault()) mimeType = db.mimeTypeForUrl(url);

        if(mimeType.isValid() && !mimeType.isDefault()) filter = mimeType.filterString();

        filename = ModalDialog::GetSaveFileName_(QString(), filename, filter);
    }

    if(filename.isEmpty()){
        QMetaObject::invokeMethod(object, "cancel");
        item->deleteLater();
        return;
    }

    item->SetPath(filename);
    if(orig_item){
        orig_item->setPath(filename);
    } else {
        object->setProperty("path", filename);
    }
    QMetaObject::invokeMethod(object, "accept");
    MainWindow *win = Application::GetCurrentWindow();
    if(win && win->GetTreeBank()->GetNotifier())
        win->GetTreeBank()->GetNotifier()->RegisterDownload(item);

    QStringList path = filename.split(QStringLiteral("/"));
    path.removeLast();
    Application::SetDownloadDirectory(path.join(QStringLiteral("/")) + QStringLiteral("/"));
#else
    Q_UNUSED(object);
#endif
}