m_TimeOut=params.value("time_out", "60000").toLongLong();
params.setValue("update_connect_str", m_UpdateConnectString);
params.setValue("update_user", m_UpdateUser);
params.setValue("update_passwd", m_UpdatePasswd);
params.setValue("backup_dir", m_BackupDir);
params.setValue("show_dialog", m_ShowDialog);
params.setValue("max_downloads", m_MaxDownloads);
params.setValue("time_out", m_TimeOut);
params.endGroup();
}GSUpdateFiles::transferProgress(qint64 bytesReceived, qint64 bytesTotal)
{int childProgressData=0;
if(bytesTotal)
childProgressData=(float(bytesReceived)/bytesTotal*100);
m_DownloadingItem->setText(9, QString::number(childProgressData));
}GSUpdateFiles::startTransfer(bool value)
{QTreeWidgetItem *rootItem, *currentItem, *childItem;
QUrl src, dst;
QSettings moduleParams;
bool hasErrors=false;
QTime timer;
gsInfo(m_Log, 9)<<" Загружаем обновления."<<endl;
m_NetworkError=false;
rootItem=m_UpdatesTree->invisibleRootItem();
for(int index=0; index<rootItem->childCount(); index++){
currentItem=rootItem->child(index);
if(currentItem->isHidden())
continue;
for(int childIndex=0; childIndex<currentItem->childCount(); childIndex++){
childItem=currentItem->child(childIndex);
src.setUrl(childItem->text(3)+childItem->text(0));
src.setUserName(m_UpdateUser);
src.setPassword(m_UpdatePasswd);
dst.setUrl(childItem->text(4)+childItem->text(5));
m_DownloadingItem=childItem;
currentItem->setText(9,"Загружаем обновление.");
loadUpdate(src, dst, currentItem->text(2)+"/"+childItem->text(2));
hasErrors|=m_NetworkError;
if(!m_NetworkError)
currentItem->setText(9,"Обновление загружено.");
if(currentItem->text(2)+"/"+childItem->text(2)=="dll/Основной"){
moduleParams.beginGroup(m_ModulesSection+"/"+currentItem->text(0));
moduleParams.setValue("module_path",childItem->text(4).mid(8));
moduleParams.setValue("module_file",childItem->text(0));
moduleParams.endGroup();
}
}
}
if(!hasErrors){
timer.start();
while(timer.elapsed()<2000)
qApp->processEvents();
close();
}
else{
m_Button->setVisible(true);
exec();
}
}GSUpdateFiles::loadError(QNetworkReply::NetworkError error)
{
gsInfo(m_Log,0)<<" Превышен интервал выполнения запроса!"<<endl;
if(m_ShowDialog=="1")
m_DownloadingItem->parent()->setText(9, "Ошибка!");
m_NetworkError=true;
}GSUpdateFiles::loadTimeOut()
{}::ProgressBarDelegate(QObject *parent)
: QItemDelegate(parent)
{}ProgressBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{QStyleOptionProgressBar progressBarOption;
if(index.parent()==QModelIndex()){
QItemDelegate::paint(painter, option, index);
return;
}
progressBarOption.state = QStyle::State_Enabled;
progressBarOption.direction = QApplication::layoutDirection();
progressBarOption.rect = option.rect;
progressBarOption.fontMetrics = QApplication::fontMetrics();
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.textAlignment = Qt::AlignCenter;
progressBarOption.textVisible = true;
int progress=index.data().toInt();
progressBarOption.progress = progress < 0 ? 0 : progress;
progressBarOption.text = index.data().toString()+" %";
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
}
Исходный код подсистемы загрузки файлов
#include "headers/downloadmanager.h"
#include "headers/autosaver.h"
#include "headers/browserapplication.h"
#include <math.h>
#include <QtCore/QMetaEnum>
#include <QtCore/QSettings>
#include <QtGui/QDesktopServices>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QFileIconProvider>
#include <QtCore/QDebug>
#include <QWebEngineSettings>
#include <QWebEngineDownloadItem>
#include <QMessageBox>
#include "../../Libs/src/WithQT/DebenuPdfLib/DebenuPDFLibraryDLLQt1113.h"::DownloadWidget(QWebEngineDownloadItem *download, QWidget *parent)
: QWidget(parent)
, m_bytesReceived(0)
, m_download(download)
{
setupUi(this);
QPalette p = downloadInfoLabel->palette();
p.setColor(QPalette::Text, Qt::darkGray);
downloadInfoLabel->setPalette(p);
progressBar->setMaximum(0);
connect(stopButton, SIGNAL(clicked()), this, SLOT(stop()));
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
connect(printButton, SIGNAL(clicked()), this, SLOT(print()));
if (download) {
m_file.setFile(download->path());
m_url = download->url();
}
init();
}DownloadWidget::init()
{
if (m_download) {
connect(m_download.data(), SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
connect(m_download.data(), SIGNAL(finished()),
this, SLOT(finished()));
}
downloadInfoLabel->clear();
progressBar->setValue(0);
getFileName();
// start timer for the download estimation
m_downloadTime.start();
}DownloadWidget::getFileName(bool promptForFileName)
{
QSettings settings;
settings.beginGroup(QLatin1String("downloadmanager"));
QString defaultLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
if (m_file.absoluteDir().exists())
defaultLocation = m_file.absolutePath();
QString downloadDirectory = settings.value(QLatin1String("downloadDirectory"), defaultLocation).toString();
if (!downloadDirectory.isEmpty())
downloadDirectory += QLatin1Char('/');
QString defaultFileName = QFileInfo(downloadDirectory, m_file.fileName()).absoluteFilePath();
QString fileName = defaultFileName;
if (promptForFileName) {
fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) {
if (m_download)
m_download->cancel();
fileNameLabel->setText(tr("Download canceled: %1").arg(QFileInfo(defaultFileName).fileName()));
return false;
}
}
m_file.setFile(fileName);
if (m_download && m_download->state() == QWebEngineDownloadItem::DownloadRequested)
m_download->setPath(m_file.absoluteFilePath());
fileNameLabel->setText(m_file.fileName());
return true;
}DownloadWidget::stop()
{
setUpdatesEnabled(false);
stopButton->setEnabled(false);
stopButton->hide();
setUpdatesEnabled(true);
if (m_download)
m_download->cancel();
emit statusChanged();
}DownloadWidget::open()
{QString strCommand = "cmd /C ", default_editor="";
QSettings params;
QUrl url = QUrl::fromLocalFile(m_file.absoluteFilePath());
default_editor=params.value("default_editor", "").toString();
if(default_editor.isEmpty()){
QMessageBox::critical(0, "Внимание!", "Не настроен редактор документов.\n Редактирование невозможно.",
QMessageBox::Ok);
return;
}
strCommand+=QString("\"")+default_editor+QString("\" ")+url.toString();
m_process.start(strCommand);
}DownloadWidget::print()
{DebenuPDFLibraryDLLQt1113 pdfTest(QString("DebenuPDFLibraryDLL1113.dll"));
int iOptions;
QString pdfFileName, customPrinter;
QStringList printParams;
QSettings moduleParams;
if(!pdfTest.LibraryLoaded()){
QMessageBox::critical(0, "Печать PDF", "Библиотека не загружена!", QMessageBox::Ok);
return;
}
if(pdfTest.UnlockKey("j39163i38a653748u9f66rb5y")!=1){
QMessageBox::critical(0, "Печать PDF", "Ошибка инициализации!", QMessageBox::Ok);
return;
}
pdfFileName=m_file.absoluteFilePath();
printParams=m_download->url().toDisplayString().section("?",1,1).split("&", QString::SkipEmptyParts);
pdfTest.LoadFromFile(pdfFileName, QString(""));
iOptions=printParams.indexOf("printerName=*");
if(iOptions>-1)=moduleParams.value("Printers/"+printParams.at(iOptions).section("=",1,1),pdfTest.GetDefaultPrinterName()).toString();
else
customPrinter=pdfTest.GetDefaultPrinterName();
customPrinter=pdfTest.NewCustomPrinter(customPrinter);
pdfTest.SetupCustomPrinter(customPrinter,1,9);
pdfTest.SetupCustomPrinter(customPrinter,4,1);
pdfTest.SetupCustomPrinter(customPrinter,7,1);
pdfTest.SetupCustomPrinter(customPrinter,11,1);
for(int i=0; i<printParams.size(); i++){
if(printParams.at(i).contains("copies=")).SetupCustomPrinter(customPrinter,4,printParams.at(i).section("=",1,1).toInt());//Количество копий
if(printParams.at(i).contains("format=")){
if(printParams.at(i).section("=",1,1)=="A5")
pdfTest.SetupCustomPrinter(customPrinter,1,11);
}
if(printParams.at(i).contains("duplex=")){
if(printParams.at(i).section("=",1,1)=="vertical")
pdfTest.SetupCustomPrinter(customPrinter,7,2);
if(printParams.at(i).section("=",1,1)=="horizontal")
pdfTest.SetupCustomPrinter(customPrinter,7,3);
}
if(printParams.at(i).contains("orientation=")){
if(printParams.at(i).section("=",1,1)=="landscape")
pdfTest.SetupCustomPrinter(customPrinter,11,2);
}
}
iOptions=pdfTest.PrintOptions(0, 0, "PDF_MIS");
pdfTest.PrintDocument(customPrinter,1,pdfTest.PageCount(),iOptions);
}DownloadWidget::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
m_bytesReceived = bytesReceived;
if (bytesTotal == -1) {
progressBar->setValue(0);
progressBar->setMaximum(0);
} else {
progressBar->setValue(bytesReceived);
progressBar->setMaximum(bytesTotal);
}
updateInfoLabel();
}DownloadWidget::updateInfoLabel()
{
qint64 bytesTotal = progressBar->maximum();
double speed = m_bytesReceived * 1000.0 / m_downloadTime.elapsed();
double timeRemaining = ((double)(bytesTotal - m_bytesReceived)) / speed;
QString timeRemainingString = tr("seconds");
if (timeRemaining > 60) {
timeRemaining = timeRemaining / 60;
timeRemainingString = tr("minutes");
}
timeRemaining = floor(timeRemaining);
// When downloading the eta should never be 0
if (timeRemaining == 0)
timeRemaining = 1;
QString info;
if (!downloadedSuccessfully()) {
QString remaining;
if (bytesTotal != 0)
remaining = tr("- %4 %5 remaining")
.arg(timeRemaining)
.arg(timeRemainingString);
info = tr("%1 of %2 (%3/sec) %4")
.arg(dataString(m_bytesReceived))
.arg(bytesTotal == 0 ? tr("?") : dataString(bytesTotal))
.arg(dataString((int)speed))
.arg(remaining);
} else {
if (m_bytesReceived != bytesTotal) {
info = tr("%1 of %2 - Stopped")
.arg(dataString(bytesTotal));
} else
info = dataString(m_bytesReceived);
}
downloadInfoLabel->setText(info);
}DownloadWidget::dataString(int size) const
{
QString unit;
if (size < 1024) {
unit = tr("bytes");
} else if (size < 1024*1024) {
size /= 1024;
unit = tr("kB");
} else {
size /= 1024*1024;
unit = tr("MB");
}
return QString(QLatin1String("%1 %2")).arg(size).arg(unit);
}DownloadWidget::downloading() const
{
return (progressBar->isVisible());
}DownloadWidget::downloadedSuccessfully() const
{
bool completed = m_download
&& m_download->isFinished()
&& m_download->state() == QWebEngineDownloadItem::DownloadCompleted;
return completed || !stopButton->isVisible();
}DownloadWidget::finished()
{QString url;
if (m_download) {
QWebEngineDownloadItem::DownloadState state = m_download->state();
QString message;
bool interrupted = false;
switch (state) {
case QWebEngineDownloadItem::DownloadRequested: // Fall-through.
case QWebEngineDownloadItem::DownloadInProgress:
Q_UNREACHABLE();
break;
case QWebEngineDownloadItem::DownloadCompleted:
break;
case QWebEngineDownloadItem::DownloadCancelled:
message = QStringLiteral("Download cancelled");
interrupted = true;
break;
case QWebEngineDownloadItem::DownloadInterrupted:
message = QStringLiteral("Download interrupted");
interrupted = true;
break;
}
if (interrupted) {
downloadInfoLabel->setText(message);
return;
}
}
progressBar->hide();
stopButton->setEnabled(false);
stopButton->hide();
updateInfoLabel();
url=m_download->url().toDisplayString();
if(url.contains("fn=open"))
open();
if(url.contains("fn=print"))
print();
emit statusChanged();
}
/*!
DownloadManager is a Dialog that contains a list of DownloadWidgets
It is a basic download manager. It only downloads the file, doesn't do BitTorrent,
extract zipped files or anything fancy.
*/::DownloadManager(QWidget *parent)
: QDialog(parent)
, m_autoSaver(new AutoSaver(this))
, m_iconProvider(0)
, m_removePolicy(Never)
{
setupUi(this);
downloadsView->setShowGrid(false);
downloadsView->verticalHeader()->hide();
downloadsView->horizontalHeader()->hide();
downloadsView->setAlternatingRowColors(true);
downloadsView->horizontalHeader()->setStretchLastSection(true);
m_model = new DownloadModel(this);
downloadsView->setModel(m_model);
connect(cleanupButton, SIGNAL(clicked()), this, SLOT(cleanup()));
load();
}::~DownloadManager()
{
m_autoSaver->changeOccurred();
m_autoSaver->saveIfNeccessary();
if (m_iconProvider)
delete m_iconProvider;
}DownloadManager::activeDownloads() const
{
int count = 0;
for (int i = 0; i < m_downloads.count(); ++i) {
if (m_downloads.at(i)->stopButton->isEnabled())
++count;
}
return count;
}DownloadManager::download(QWebEngineDownloadItem *download)
{
DownloadWidget *widget = new DownloadWidget(download, this);
addItem(widget);
}DownloadManager::addItem(DownloadWidget *widget)
{
connect(widget, SIGNAL(statusChanged()), this, SLOT(updateRow()));
int row = m_downloads.count();
m_model->beginInsertRows(QModelIndex(), row, row);
m_downloads.append(widget);
m_model->endInsertRows();
updateItemCount();
downloadsView->setIndexWidget(m_model->index(row, 0), widget);
QIcon icon = style()->standardIcon(QStyle::SP_FileIcon);
widget->fileIcon->setPixmap(icon.pixmap(48, 48));
downloadsView->setRowHeight(row, widget->sizeHint().height());
}DownloadManager::updateRow()
{
DownloadWidget *widget = qobject_cast<DownloadWidget*>(sender());
int row = m_downloads.indexOf(widget);
if (-1 == row)
return;
if (!m_iconProvider)
m_iconProvider = new QFileIconProvider();
QIcon icon = m_iconProvider->icon(widget->m_file);
if (icon.isNull())
icon = style()->standardIcon(QStyle::SP_FileIcon);
widget->fileIcon->setPixmap(icon.pixmap(48, 48));
downloadsView->setRowHeight(row, widget->minimumSizeHint().height());
bool remove = false;
if (!widget->downloading()
&& BrowserApplication::instance()->privateBrowsing())
remove = true;
if (widget->downloadedSuccessfully()
&& removePolicy() == DownloadManager::SuccessFullDownload) {
remove = true;
}
if (remove)
m_model->removeRow(row);
cleanupButton->setEnabled(m_downloads.count() - activeDownloads() > 0);
}::RemovePolicy DownloadManager::removePolicy() const
{
return m_removePolicy;
}DownloadManager::setRemovePolicy(RemovePolicy policy)
{
if (policy == m_removePolicy)
return;
m_removePolicy = policy;
m_autoSaver->changeOccurred();
}DownloadManager::save() const
{
QSettings settings;
settings.beginGroup(QLatin1String("downloadmanager"));
QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy"));
settings.setValue(QLatin1String("removeDownloadsPolicy"), QLatin1String(removePolicyEnum.valueToKey(m_removePolicy)));
settings.setValue(QLatin1String("size"), size());
if (m_removePolicy == Exit)
return;
for (int i = 0; i < m_downloads.count(); ++i) {
QString key = QString(QLatin1String("download_%1_")).arg(i);
settings.setValue(key + QLatin1String("url"), m_downloads[i]->m_url);
settings.setValue(key + QLatin1String("location"), m_downloads[i]->m_file.filePath());
settings.setValue(key + QLatin1String("done"), m_downloads[i]->downloadedSuccessfully());
}
int i = m_downloads.count();
QString key = QString(QLatin1String("download_%1_")).arg(i);
while (settings.contains(key + QLatin1String("url"))) {
settings.remove(key + QLatin1String("url"));
settings.remove(key + QLatin1String("location"));
settings.remove(key + QLatin1String("done"));
key = QString(QLatin1String("download_%1_")).arg(++i);
}
}DownloadManager::load()
{
QSettings settings;
settings.beginGroup(QLatin1String("downloadmanager"));
QSize size = settings.value(QLatin1String("size")).toSize();
if (size.isValid())
resize(size);
QByteArray value = settings.value(QLatin1String("removeDownloadsPolicy"), QLatin1String("Never")).toByteArray();
QMetaEnum removePolicyEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("RemovePolicy"));
m_removePolicy = removePolicyEnum.keyToValue(value) == -1 ?
Never :_cast<RemovePolicy>(removePolicyEnum.keyToValue(value));
int i = 0;
QString key = QString(QLatin1String("download_%1_")).arg(i);
while (settings.contains(key + QLatin1String("url"))) {
QUrl url = settings.value(key + QLatin1String("url")).toUrl();
QString fileName = settings.value(key + QLatin1String("location")).toString();
bool done = settings.value(key + QLatin1String("done"), true).toBool();
if (done && !url.isEmpty() && !fileName.isEmpty()) {
DownloadWidget *widget = new DownloadWidget(0, this);
widget->m_file.setFile(fileName);
widget->fileNameLabel->setText(widget->m_file.fileName());
widget->m_url = url;
widget->stopButton->setVisible(false);
widget->stopButton->setEnabled(false);
widget->progressBar->hide();
addItem(widget);
}
key = QString(QLatin1String("download_%1_")).arg(++i);
}
cleanupButton->setEnabled(m_downloads.count() - activeDownloads() > 0);