Reorganize codes

Reorganize all parts of codes;
Fix a bug that index page color is not correct when initialized.
This commit is contained in:
zty199
2021-04-17 15:43:11 +08:00
parent 6fd3c40e97
commit e64e7fcae2
19 changed files with 525 additions and 410 deletions

View File

@@ -1,7 +1,9 @@
TEMPLATE = subdirs TEMPLATE = subdirs
CONFIG += ordered CONFIG += ordered
SUBDIRS = third-party/QtNetworkService \ SUBDIRS += \
third-party/QtNetworkService \
src/spark-store.pro src/spark-store.pro
spark-store.depends = third-party/QtNetworkService spark-store.depends = third-party/QtNetworkService

View File

@@ -46,7 +46,8 @@ void AppItem::setDescription(QString description)
void AppItem::setIcon(QString icon) void AppItem::setIcon(QString icon)
{ {
m_icon = icon; m_icon = icon;
if (!icon.isEmpty()) { if(!icon.isEmpty())
{
downloadIcon(icon); downloadIcon(icon);
} }
} }
@@ -58,7 +59,8 @@ void AppItem::setUrl(QString url)
void AppItem::mousePressEvent(QMouseEvent *event) void AppItem::mousePressEvent(QMouseEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event)
emit clicked(QUrl(m_url)); emit clicked(QUrl(m_url));
} }
@@ -68,8 +70,10 @@ void AppItem::mousePressEvent(QMouseEvent *event)
*/ */
void AppItem::downloadIcon(QString icon) void AppItem::downloadIcon(QString icon)
{ {
QtConcurrent::run([=](){ QtConcurrent::run([=]()
{
auto reqManager = new QNetworkAccessManager(); auto reqManager = new QNetworkAccessManager();
QUrl url(icon); QUrl url(icon);
QNetworkReply *reply = reqManager->get(QNetworkRequest(url)); QNetworkReply *reply = reqManager->get(QNetworkRequest(url));
QEventLoop loop; QEventLoop loop;
@@ -77,13 +81,16 @@ void AppItem::downloadIcon(QString icon)
connect(reply, &QNetworkReply::finished, this, [=] () { emit finished(); }); connect(reply, &QNetworkReply::finished, this, [=] () { emit finished(); });
loop.exec(); loop.exec();
reqManager->deleteLater(); reqManager->deleteLater();
QPixmap pixmap; QPixmap pixmap;
pixmap.loadFromData(reply->readAll()); pixmap.loadFromData(reply->readAll());
pixmap = pixmap.scaled(78, 78, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); pixmap = pixmap.scaled(78, 78, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
if (reply->error() == QNetworkReply::NoError) { if (reply->error() == QNetworkReply::NoError)
QMetaObject::invokeMethod(this, "loadIcon", Qt::QueuedConnection, {
Q_ARG(QPixmap, pixmap)); QMetaObject::invokeMethod(this, "loadIcon", Qt::QueuedConnection, Q_ARG(QPixmap, pixmap));
} else { }
else
{
qDebug() << reply->errorString(); qDebug() << reply->errorString();
} }
}); });
@@ -93,5 +100,3 @@ void AppItem::loadIcon(QPixmap pic)
{ {
ui->lbl_icon->setPixmap(pic); ui->lbl_icon->setPixmap(pic);
} }

View File

@@ -14,7 +14,7 @@ class AppItem : public QWidget
public: public:
explicit AppItem(QWidget *parent = nullptr); explicit AppItem(QWidget *parent = nullptr);
~AppItem(); ~AppItem() override;
void setTitle(QString title); void setTitle(QString title);
void setDescription(QString description); void setDescription(QString description);
@@ -24,14 +24,6 @@ public:
protected: protected:
void mousePressEvent(QMouseEvent *event) override; void mousePressEvent(QMouseEvent *event) override;
signals:
void clicked(QUrl url);
void finished();
public slots:
void downloadIcon(QString icon);
void loadIcon(QPixmap pic);
private: private:
Ui::AppItem *ui; Ui::AppItem *ui;
@@ -39,6 +31,15 @@ private:
QString m_description; QString m_description;
QString m_icon; QString m_icon;
QString m_url; QString m_url;
public slots:
void downloadIcon(QString icon);
void loadIcon(QPixmap pic);
signals:
void clicked(QUrl url);
void finished();
}; };
#endif // APPITEM_H #endif // APPITEM_H

View File

@@ -1,22 +1,30 @@
#include "big_image.h" #include "big_image.h"
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QtConcurrent> #include <QtConcurrent>
big_image::big_image(DBlurEffectWidget *parent) : DBlurEffectWidget(parent)
big_image::big_image(DBlurEffectWidget *parent) :
DBlurEffectWidget(parent),
m_image(new QLabel)
{ {
// m_image->setParent(this);
QHBoxLayout *layout=new QHBoxLayout;
setLayout(layout);
layout->addWidget(m_image);
layout->setMargin(0);
m_image->setAlignment(Qt::AlignCenter);
// m_image->setMaximumSize(1360,768);
setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); // 设置图片对话框总在最前 setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); // 设置图片对话框总在最前
setRadius(0); setRadius(0);
setMaskAlpha(60); setMaskAlpha(60);
setMaskColor(QColor("#000000")); setMaskColor(QColor("#000000"));
QHBoxLayout *layout = new QHBoxLayout;
setLayout(layout);
layout->addWidget(m_image);
layout->setMargin(0);
// m_image->setParent(this);
// m_image->setMaximumSize(1360,768);
m_image->setAlignment(Qt::AlignCenter);
}
void big_image::setimage(QPixmap image)
{
m_image->setPixmap(image);
} }
void big_image::mousePressEvent(QMouseEvent *) void big_image::mousePressEvent(QMouseEvent *)
@@ -25,11 +33,6 @@ void big_image::mousePressEvent(QMouseEvent *)
m_image->clear(); m_image->clear();
} }
void big_image::setimage(QPixmap image)
{
m_image->setPixmap(image);
}
void big_image::focusOutEvent(QFocusEvent *) void big_image::focusOutEvent(QFocusEvent *)
{ {
hide(); hide();

View File

@@ -1,25 +1,27 @@
#ifndef BIG_IMAGE_H #ifndef BIG_IMAGE_H
#define BIG_IMAGE_H #define BIG_IMAGE_H
#include <QWidget>
#include <DBlurEffectWidget>
#include <QMouseEvent> #include <QMouseEvent>
#include <QLabel> #include <QLabel>
#include <DBlurEffectWidget>
DWIDGET_USE_NAMESPACE DWIDGET_USE_NAMESPACE
class big_image : public DBlurEffectWidget class big_image : public DBlurEffectWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit big_image(DBlurEffectWidget *parent = nullptr); explicit big_image(DBlurEffectWidget *parent = nullptr);
void mousePressEvent(QMouseEvent *event);
QLabel *m_image=new QLabel; QLabel *m_image;
void setimage(QPixmap); void setimage(QPixmap);
void focusOutEvent(QFocusEvent *event);
signals: protected:
void mousePressEvent(QMouseEvent *event) override;
public slots: void focusOutEvent(QFocusEvent *event) override;
}; };
#endif // BIG_IMAGE_H #endif // BIG_IMAGE_H

View File

@@ -1,19 +1,27 @@
#include "downloadlist.h" #include "downloadlist.h"
#include "ui_downloadlist.h" #include "ui_downloadlist.h"
#include "widget.h"
#include <QDebug>
#include <QIcon>
#include <QPixmap>
#include <QtConcurrent> #include <QtConcurrent>
#include <QProcess> #include <QProcess>
#include <QTextBrowser>
#include "widget.h"
bool downloadlist::isInstall = false; bool downloadlist::isInstall = false;
downloadlist::downloadlist(QWidget *parent) : downloadlist::downloadlist(QWidget *parent) :
QWidget(parent), QWidget(parent),
ui(new Ui::downloadlist) reinstall(false),
close(false),
ui(new Ui::downloadlist),
menu_install(new QMenu),
action_dpkg(new QAction),
action_deepin(new QAction),
action_gdebi(new QAction),
output_w(new DDialog),
textbrowser(new QTextBrowser)
{ {
ui->setupUi(this); ui->setupUi(this);
ui->pushButton_install->setEnabled(false); ui->pushButton_install->setEnabled(false);
ui->progressBar->setValue(0); ui->progressBar->setValue(0);
ui->label_filename->hide(); ui->label_filename->hide();
@@ -22,8 +30,9 @@ downloadlist::downloadlist(QWidget *parent) :
ui->widget_spinner->start(); ui->widget_spinner->start();
ui->widget_spinner->hide(); ui->widget_spinner->hide();
action_dpkg->setText(tr("Spark Store App Installer")); action_dpkg->setText(tr("Spark Store App Installer"));
action_gdebi->setText(tr("gdebi"));
action_deepin->setText(tr("deepin deb installer")); action_deepin->setText(tr("deepin deb installer"));
action_gdebi->setText(tr("gdebi"));
connect(action_dpkg,&QAction::triggered,[=](){downloadlist::install(0);}); connect(action_dpkg,&QAction::triggered,[=](){downloadlist::install(0);});
connect(action_deepin,&QAction::triggered,[=](){downloadlist::install(1);}); connect(action_deepin,&QAction::triggered,[=](){downloadlist::install(1);});
connect(action_gdebi,&QAction::triggered,[=](){downloadlist::install(2);}); connect(action_gdebi,&QAction::triggered,[=](){downloadlist::install(2);});
@@ -31,13 +40,15 @@ downloadlist::downloadlist(QWidget *parent) :
// ssinstall 命令存在时再加入该选项 // ssinstall 命令存在时再加入该选项
QFile ssinstall("/usr/local/bin/ssinstall"); QFile ssinstall("/usr/local/bin/ssinstall");
ssinstall.open(QIODevice::ReadOnly); ssinstall.open(QIODevice::ReadOnly);
if(ssinstall.isOpen()){ if(ssinstall.isOpen())
{
menu_install->addAction(action_dpkg); menu_install->addAction(action_dpkg);
} }
QFile deepin("/usr/bin/deepin-deb-installer"); QFile deepin("/usr/bin/deepin-deb-installer");
deepin.open(QIODevice::ReadOnly); deepin.open(QIODevice::ReadOnly);
if(deepin.isOpen()){ if(deepin.isOpen())
{
menu_install->addAction(action_deepin); menu_install->addAction(action_deepin);
} }
@@ -49,18 +60,19 @@ downloadlist::~downloadlist()
delete ui; delete ui;
} }
void downloadlist::setValue(long long value) void downloadlist::setValue(qint64 value)
{ {
ui->progressBar->setValue(int(value)); ui->progressBar->setValue(qint32(value));
ui->label_2->setText(QString::number(double(value) / 100) + "% (" + speed + ")"); ui->label_2->setText(QString::number(double(value) / 100) + "% (" + speed + ")");
if(ui->label_2->text().left(4)=="100%"){ if(ui->label_2->text().left(4) == "100%")
{
ui->label_2->setText(tr("Downloaded, waiting to install")); ui->label_2->setText(tr("Downloaded, waiting to install"));
} }
} }
void downloadlist::setMax(long long max) void downloadlist::setMax(qint64 max)
{ {
ui->progressBar->setMaximum(int(max)); ui->progressBar->setMaximum(qint32(max));
} }
void downloadlist::setName(QString name) void downloadlist::setName(QString name)
@@ -75,7 +87,8 @@ QString downloadlist::getName()
void downloadlist::readyInstall() void downloadlist::readyInstall()
{ {
if(ui->progressBar->value()!= ui->progressBar->maximum() && !close){ if(ui->progressBar->value() != ui->progressBar->maximum() && !close)
{
ui->progressBar->hide(); ui->progressBar->hide();
ui->pushButton_install->show(); ui->pushButton_install->show();
ui->pushButton_2->hide(); ui->pushButton_2->hide();
@@ -83,10 +96,12 @@ void downloadlist::readyInstall()
"/tmp/spark-store/icon_" + QString::number(num).toUtf8() + ".png"); "/tmp/spark-store/icon_" + QString::number(num).toUtf8() + ".png");
ui->label_2->setText(tr("Download FailedCheck Your Connection")); ui->label_2->setText(tr("Download FailedCheck Your Connection"));
ui->pushButton_install->setEnabled(false); ui->pushButton_install->setEnabled(false);
return;
return;
} }
if(!close){
if(!close)
{
ui->progressBar->hide(); ui->progressBar->hide();
ui->pushButton_install->setEnabled(true); ui->pushButton_install->setEnabled(true);
ui->pushButton_install->show(); ui->pushButton_install->show();
@@ -94,7 +109,6 @@ void downloadlist::readyInstall()
Widget::sendNotification(tr("Finished downloading %1, awaiting to install").arg(ui->label->text()), 5000, Widget::sendNotification(tr("Finished downloading %1, awaiting to install").arg(ui->label->text()), 5000,
"/tmp/spark-store/icon_" + QString::number(num).toUtf8() + ".png"); "/tmp/spark-store/icon_" + QString::number(num).toUtf8() + ".png");
} }
} }
void downloadlist::setFileName(QString fileName) void downloadlist::setFileName(QString fileName)
@@ -119,28 +133,21 @@ void downloadlist::setSpeed(QString s)
void downloadlist::install(int t) void downloadlist::install(int t)
{ {
if(!isInstall){ if(!isInstall)
{
isInstall = true; isInstall = true;
ui->pushButton_install->hide(); ui->pushButton_install->hide();
ui->widget_spinner->show(); ui->widget_spinner->show();
qDebug() << "/tmp/spark-store/" + ui->label_filename->text().toUtf8(); qDebug() << "/tmp/spark-store/" + ui->label_filename->text().toUtf8();
ui->label_2->setText(tr("Installing")); ui->label_2->setText(tr("Installing"));
QtConcurrent::run([=](){
QtConcurrent::run([=]()
{
QProcess installer; QProcess installer;
if(!reinstall){ if(!reinstall)
switch (t) { {
case 0: switch(t)
installer.start("pkexec ssinstall /tmp/spark-store/"+ui->label_filename->text().toUtf8()); {
break;
case 1:
installer.start("deepin-deb-installer /tmp/spark-store/"+ui->label_filename->text().toUtf8());
break;
case 2:
installer.start("pkexec gdebi -n /tmp/spark-store/"+ui->label_filename->text().toUtf8());
break;
}
}else {
switch (t) {
case 0: case 0:
installer.start("pkexec ssinstall /tmp/spark-store/" + ui->label_filename->text().toUtf8()); installer.start("pkexec ssinstall /tmp/spark-store/" + ui->label_filename->text().toUtf8());
break; break;
@@ -152,41 +159,67 @@ void downloadlist::install(int t)
break; break;
} }
} }
else
{
switch(t)
{
case 0:
installer.start("pkexec ssinstall /tmp/spark-store/" + ui->label_filename->text().toUtf8());
break;
case 1:
installer.start("deepin-deb-installer /tmp/spark-store/" + ui->label_filename->text().toUtf8());
break;
case 2:
installer.start("pkexec gdebi -n /tmp/spark-store/" + ui->label_filename->text().toUtf8());
break;
}
}
bool haveError = false; bool haveError = false;
bool notRoot = false; bool notRoot = false;
installer.waitForFinished(); installer.waitForFinished();
out = installer.readAllStandardOutput(); out = installer.readAllStandardOutput();
QStringList everyOut = out.split("\n"); QStringList everyOut = out.split("\n");
for (int i=0;i<everyOut.size();i++) { for(int i=0;i<everyOut.size();i++)
if(everyOut[i].left(2)=="E:"){ {
if(everyOut[i].left(2) == "E:")
{
haveError = true; haveError = true;
} }
if(everyOut[i].right(14)=="Not authorized"){ if(everyOut[i].right(14) == "Not authorized")
{
notRoot = true; notRoot = true;
} }
} }
QProcess isInstall; QProcess isInstall;
isInstall.start("dpkg -s " + pkgName); isInstall.start("dpkg -s " + pkgName);
isInstall.waitForFinished(); isInstall.waitForFinished();
int error = QString::fromStdString(isInstall.readAllStandardError().toStdString()).length(); int error = QString::fromStdString(isInstall.readAllStandardError().toStdString()).length();
if(error==0){ if(error == 0)
{
ui->pushButton_install->hide(); ui->pushButton_install->hide();
ui->label_2->setText(tr("Finish")); ui->label_2->setText(tr("Finish"));
ui->pushButton_3->show(); ui->pushButton_3->show();
}else { }
else
{
ui->pushButton_install->show(); ui->pushButton_install->show();
ui->pushButton_install->setText(tr("Retry")); ui->pushButton_install->setText(tr("Retry"));
ui->label_2->setText(tr("Error happened in dpkg progress , you can try it again")); ui->label_2->setText(tr("Error happened in dpkg progress , you can try it again"));
ui->pushButton_3->show(); ui->pushButton_3->show();
} }
if(notRoot){
if(notRoot)
{
ui->label_2->setText(tr("dpkg progress had been abortedyou can retry installation")); ui->label_2->setText(tr("dpkg progress had been abortedyou can retry installation"));
ui->pushButton_install->show(); ui->pushButton_install->show();
ui->pushButton_3->hide(); ui->pushButton_3->hide();
} }
ui->widget_spinner->hide(); ui->widget_spinner->hide();
downloadlist::isInstall = false; downloadlist::isInstall = false;
}); });
qDebug()<<ui->label_filename->text().toUtf8(); qDebug()<<ui->label_filename->text().toUtf8();
@@ -210,12 +243,13 @@ void downloadlist::on_pushButton_2_clicked()
void downloadlist::on_pushButton_3_clicked() void downloadlist::on_pushButton_3_clicked()
{ {
output_w.layout()->addWidget(textbrowser);
textbrowser->setLineWidth(0); textbrowser->setLineWidth(0);
textbrowser->setText(out); textbrowser->setText(out);
output_w.layout()->setMargin(20);
output_w.setTitle(ui->label->text()); output_w->setMinimumHeight(600);
output_w.setMinimumHeight(600); output_w->setAttribute(Qt::WA_TranslucentBackground);
output_w.setAttribute(Qt::WA_TranslucentBackground); output_w->setTitle(ui->label->text());
output_w.show(); output_w->layout()->setMargin(20);
output_w->layout()->addWidget(textbrowser);
output_w->show();
} }

View File

@@ -2,11 +2,14 @@
#define DOWNLOADLIST_H #define DOWNLOADLIST_H
#include <QWidget> #include <QWidget>
#include <DDialog>
#include <QTextBrowser> #include <QTextBrowser>
#include <QMenu> #include <QMenu>
#include <QAction> #include <QAction>
#include <DDialog>
DWIDGET_USE_NAMESPACE DWIDGET_USE_NAMESPACE
namespace Ui { namespace Ui {
class downloadlist; class downloadlist;
} }
@@ -18,40 +21,45 @@ class downloadlist : public QWidget
public: public:
explicit downloadlist(QWidget *parent = nullptr); explicit downloadlist(QWidget *parent = nullptr);
~downloadlist(); ~downloadlist();
void setValue(long long);
void setMax(long long); int num;
bool free;
static bool isInstall;
bool reinstall;
QString speed;
QString out;
QString pkgName;
bool close;
void setValue(qint64);
void setMax(qint64);
void setName(QString); void setName(QString);
QString getName(); QString getName();
void readyInstall(); void readyInstall();
bool free;
void setFileName(QString); void setFileName(QString);
void seticon(const QPixmap); void seticon(const QPixmap);
void closeDownload(); void closeDownload();
void setSpeed(QString); void setSpeed(QString);
int num;
bool close=false;
QString out;
DDialog output_w;
QTextBrowser *textbrowser=new QTextBrowser;
bool reinstall=false;
QString pkgName;
QMenu *menu_install=new QMenu;
QAction *action_gdebi=new QAction;
QAction *action_dpkg=new QAction;
QAction *action_deepin=new QAction;
void install(int); void install(int);
private slots:
void on_pushButton_install_clicked();
// void on_pushButton_maninst_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private: private:
Ui::downloadlist *ui; Ui::downloadlist *ui;
static bool isInstall;
QString speed;
QMenu *menu_install;
QAction *action_dpkg;
QAction *action_deepin;
QAction *action_gdebi;
DDialog *output_w;
QTextBrowser *textbrowser;
private slots:
void on_pushButton_install_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
}; };
//bool downloadlist::isInstall=false;
#endif // DOWNLOADLIST_H #endif // DOWNLOADLIST_H

View File

@@ -1,10 +1,9 @@
#include "downloadworker.h" #include "downloadworker.h"
#include <QIODevice>
#include <QEventLoop> #include <QEventLoop>
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
#include <QNetworkRequest> #include <QNetworkRequest>
#include <QNetworkReply> #include <QNetworkReply>
#include <QDebug>
#include <QThread> #include <QThread>
#include <QRegularExpression> #include <QRegularExpression>
#include <QFileInfo> #include <QFileInfo>
@@ -12,7 +11,7 @@
DownloadWorker::DownloadWorker(QObject *parent) DownloadWorker::DownloadWorker(QObject *parent)
{ {
Q_UNUSED(parent)
} }
void DownloadWorker::setIdentifier(int identifier) void DownloadWorker::setIdentifier(int identifier)
@@ -39,14 +38,15 @@ void DownloadWorker::doWork()
QNetworkRequest request; QNetworkRequest request;
request.setUrl(url); request.setUrl(url);
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
request.setRawHeader("Range", QString("bytes=%1-%2").arg(startPos) request.setRawHeader("Range", QString("bytes=%1-%2").arg(startPos).arg(endPos).toLocal8Bit());
.arg(endPos).toLocal8Bit());
reply = mgr->get(request); reply = mgr->get(request);
qDebug() << "开始下载数据:" << QString(" %1~%2 -> writePos Start %3") qDebug() << "开始下载数据:" << QString(" %1~%2 -> writePos Start %3").arg(startPos).arg(endPos).arg(receivedPos);
.arg(startPos).arg(endPos).arg(receivedPos);
connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError) > (&QNetworkReply::error), connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError) > (&QNetworkReply::error),
[this](QNetworkReply::NetworkError error){ [this](QNetworkReply::NetworkError error)
if (error != QNetworkReply::NoError) { {
if(error != QNetworkReply::NoError)
{
qDebug() << "出错了:" << reply->errorString(); qDebug() << "出错了:" << reply->errorString();
} }
}); });
@@ -56,7 +56,6 @@ void DownloadWorker::doWork()
connect(reply, &QNetworkReply::downloadProgress, this, &DownloadWorker::handleProcess); connect(reply, &QNetworkReply::downloadProgress, this, &DownloadWorker::handleProcess);
// connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater); // connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
connect(reply, &QNetworkReply::finished, this, &DownloadWorker::doStop); connect(reply, &QNetworkReply::finished, this, &DownloadWorker::doStop);
} }
void DownloadWorker::doStop() void DownloadWorker::doStop()
@@ -80,8 +79,7 @@ void DownloadWorker::dataReady()
void DownloadWorker::slotFinish() void DownloadWorker::slotFinish()
{ {
file->flush(); file->flush();
qDebug() << "数据块下载完毕:" << QString(" %1~%2 -> writePos Start %3") qDebug() << "数据块下载完毕:" << QString(" %1~%2 -> writePos Start %3").arg(startPos).arg(endPos).arg(receivedPos);
.arg(startPos).arg(endPos).arg(receivedPos);
emit workFinished(); emit workFinished();
} }
@@ -93,6 +91,8 @@ void DownloadWorker::handleProcess(qint64, qint64)
DownloadController::DownloadController(QObject *parent) DownloadController::DownloadController(QObject *parent)
{ {
Q_UNUSED(parent)
domains = { domains = {
"d1.store.deepinos.org.cn", "d1.store.deepinos.org.cn",
"d2.store.deepinos.org.cn", "d2.store.deepinos.org.cn",
@@ -105,8 +105,10 @@ DownloadController::DownloadController(QObject *parent)
DownloadController::~DownloadController() DownloadController::~DownloadController()
{ {
if (workers.size() > 0) { if(workers.size() > 0)
for(int i = 0; i < workers.size(); i++) { {
for(int i = 0; i < workers.size(); i++)
{
workers.at(i)->doStop(); workers.at(i)->doStop();
workers.at(i)->disconnect(); workers.at(i)->disconnect();
workers.at(i)->deleteLater(); workers.at(i)->deleteLater();
@@ -130,21 +132,22 @@ void DownloadController::setThreadNum(int threadNum)
*/ */
void DownloadController::startDownload(const QString &url) void DownloadController::startDownload(const QString &url)
{ {
finish = 0; finish = 0;
// 下载任务等分,计算每个线程的下载数据 // 下载任务等分,计算每个线程的下载数据
fileSize = getFileSize(url); fileSize = getFileSize(url);
if (fileSize == 0) { if(fileSize == 0)
{
emit errorOccur("文件大小获取失败"); emit errorOccur("文件大小获取失败");
return; return;
} }
qint64 segmentSize = fileSize / threadNum; qint64 segmentSize = fileSize / threadNum;
ranges.resize(threadNum); ranges.resize(threadNum);
QVector<qint64> receivedBytes; QVector<qint64> receivedBytes;
receivedBytes.resize(threadNum); receivedBytes.resize(threadNum);
for (int i = 0; i < threadNum; i++) { for(int i = 0; i < threadNum; i++)
{
ranges[i].first = i * segmentSize; ranges[i].first = i * segmentSize;
ranges[i].second = i * segmentSize + segmentSize - 1; ranges[i].second = i * segmentSize + segmentSize - 1;
receivedBytes[i] = 0; receivedBytes[i] = 0;
@@ -157,18 +160,24 @@ void DownloadController::startDownload(const QString &url)
file->setFileName(tmpdir.absoluteFilePath(filename)); file->setFileName(tmpdir.absoluteFilePath(filename));
if(file->exists()) if(file->exists())
{
file->remove(); file->remove();
if (!file->open(QIODevice::WriteOnly)) { }
if(!file->open(QIODevice::WriteOnly))
{
delete file; delete file;
file = nullptr; file = nullptr;
emit errorOccur(file->errorString()); emit errorOccur(file->errorString());
return; return;
} }
file->resize(fileSize); file->resize(fileSize);
// 创建下载线程 // 创建下载线程
workers.clear(); workers.clear();
for(int i = 0; i < ranges.size(); i++) { for(int i = 0; i < ranges.size(); i++)
{
qDebug() << QString("第%1个下载请求%2-%3").arg(i).arg(ranges.at(i).first).arg(ranges.at(i).second); qDebug() << QString("第%1个下载请求%2-%3").arg(i).arg(ranges.at(i).first).arg(ranges.at(i).second);
auto worker = new DownloadWorker(this); auto worker = new DownloadWorker(this);
auto range = ranges.at(i); auto range = ranges.at(i);
@@ -176,8 +185,10 @@ void DownloadController::startDownload(const QString &url)
worker->setIdentifier(i); worker->setIdentifier(i);
worker->setParamter(chunkUrl, range, file); worker->setParamter(chunkUrl, range, file);
workers.append(worker); workers.append(worker);
connect(worker, &DownloadWorker::downloadProcess, this, &DownloadController::handleProcess); connect(worker, &DownloadWorker::downloadProcess, this, &DownloadController::handleProcess);
connect(worker, &DownloadWorker::workFinished, this, &DownloadController::chunkDownloadFinish); connect(worker, &DownloadWorker::workFinished, this, &DownloadController::chunkDownloadFinish);
worker->doWork(); worker->doWork();
} }
} }
@@ -187,14 +198,15 @@ void DownloadController::startDownload(const QString &url)
*/ */
void DownloadController::stopDownload() void DownloadController::stopDownload()
{ {
for(int i = 0; i < workers.size(); i++) { for(int i = 0; i < workers.size(); i++)
{
workers.at(i)->doStop(); workers.at(i)->doStop();
workers.at(i)->disconnect(); workers.at(i)->disconnect();
workers.at(i)->deleteLater(); workers.at(i)->deleteLater();
} }
workers.clear(); workers.clear();
qDebug() << "文件下载路径:" << QFileInfo(file->fileName()).absoluteFilePath(); qDebug() << "文件下载路径:" << QFileInfo(file->fileName()).absoluteFilePath();
file->flush(); file->flush();
file->close(); file->close();
delete file; delete file;
@@ -205,7 +217,8 @@ void DownloadController::stopDownload()
void DownloadController::handleProcess() void DownloadController::handleProcess()
{ {
qint64 bytesReceived = 0; qint64 bytesReceived = 0;
for(int i = 0; i < workers.size(); i++) { for(int i = 0; i < workers.size(); i++)
{
bytesReceived += workers.at(i)->getReceivedPos(); bytesReceived += workers.at(i)->getReceivedPos();
} }
qDebug() << QString("下载进度 %1-%2").arg(bytesReceived).arg(fileSize); qDebug() << QString("下载进度 %1-%2").arg(bytesReceived).arg(fileSize);
@@ -216,7 +229,8 @@ void DownloadController::chunkDownloadFinish()
{ {
finish++; finish++;
qDebug() << QString("已下载了%1块共%2块").arg(finish).arg(threadNum); qDebug() << QString("已下载了%1块共%2块").arg(finish).arg(threadNum);
if (finish == threadNum) { if(finish == threadNum)
{
stopDownload(); stopDownload();
emit downloadFinished(); emit downloadFinished();
} }
@@ -231,16 +245,20 @@ qint64 DownloadController::getFileSize(const QString& url)
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
QNetworkReply *reply = requestManager.head(request); QNetworkReply *reply = requestManager.head(request);
connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError) > (&QNetworkReply::error), connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError) > (&QNetworkReply::error),
[this, reply](QNetworkReply::NetworkError error){ [this, reply](QNetworkReply::NetworkError error)
if (error != QNetworkReply::NoError) { {
if(error != QNetworkReply::NoError)
{
emit errorOccur(reply->errorString()); emit errorOccur(reply->errorString());
} }
}); });
connect(reply, &QNetworkReply::finished, &event, &QEventLoop::quit); connect(reply, &QNetworkReply::finished, &event, &QEventLoop::quit);
event.exec(); event.exec();
qint64 fileSize = 0; qint64 fileSize = 0;
if(reply->rawHeader("Accept-Ranges") == QByteArrayLiteral("bytes") if(reply->rawHeader("Accept-Ranges") == QByteArrayLiteral("bytes")
&& reply->hasRawHeader(QString("Content-Length").toLocal8Bit())) { && reply->hasRawHeader(QString("Content-Length").toLocal8Bit()))
{
fileSize = reply->header(QNetworkRequest::ContentLengthHeader).toUInt(); fileSize = reply->header(QNetworkRequest::ContentLengthHeader).toUInt();
} }
qDebug() << "文件大小为:" << fileSize; qDebug() << "文件大小为:" << fileSize;
@@ -251,9 +269,9 @@ qint64 DownloadController::getFileSize(const QString& url)
QString DownloadController::replaceDomain(const QString& url, const QString domain) QString DownloadController::replaceDomain(const QString& url, const QString domain)
{ {
QRegularExpression regex(R"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])"); QRegularExpression regex(R"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9])");
if (regex.match(url).hasMatch()) { if(regex.match(url).hasMatch())
{
return QString(url).replace(regex.match(url).captured(), domain); return QString(url).replace(regex.match(url).captured(), domain);
} }
return url; return url;
} }

View File

@@ -9,8 +9,10 @@
class DownloadWorker : public QObject class DownloadWorker : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit DownloadWorker(QObject *parent = nullptr); explicit DownloadWorker(QObject *parent = nullptr);
void setIdentifier(int identifier); void setIdentifier(int identifier);
void setParamter(const QString &url, QPair<qint64, qint64> range, QFile *flle); void setParamter(const QString &url, QPair<qint64, qint64> range, QFile *flle);
qint64 getReceivedPos(); qint64 getReceivedPos();
@@ -22,12 +24,6 @@ public slots:
void slotFinish(); void slotFinish();
void handleProcess(qint64, qint64); void handleProcess(qint64, qint64);
signals:
void resultReady(int identifier, QByteArray data);
void testSignals();
void workFinished();
void downloadProcess();
private: private:
int identifier; int identifier;
QString url; QString url;
@@ -37,14 +33,23 @@ private:
QNetworkReply *reply; QNetworkReply *reply;
QNetworkAccessManager *mgr; QNetworkAccessManager *mgr;
QFile *file; QFile *file;
signals:
void resultReady(int identifier, QByteArray data);
void testSignals();
void workFinished();
void downloadProcess();
}; };
class DownloadController : public QObject class DownloadController : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit DownloadController(QObject *parent = nullptr); explicit DownloadController(QObject *parent = nullptr);
~DownloadController(); ~DownloadController();
void setFilename(QString filename); void setFilename(QString filename);
void setThreadNum(int threadNum); void setThreadNum(int threadNum);
void startDownload(const QString &url); void startDownload(const QString &url);
@@ -52,15 +57,6 @@ public:
qint64 getFileSize(const QString& url); qint64 getFileSize(const QString& url);
QString replaceDomain(const QString& url, const QString domain); QString replaceDomain(const QString& url, const QString domain);
public slots:
void handleProcess();
void chunkDownloadFinish();
signals:
void errorOccur(const QString& msg);
void downloadProcess(qint64, qint64);
void downloadFinished();
private: private:
int threadNum; int threadNum;
QString filename; QString filename;
@@ -70,6 +66,16 @@ private:
QList<DownloadWorker*> workers; QList<DownloadWorker*> workers;
int finish = 0; int finish = 0;
QVector<QString> domains; QVector<QString> domains;
public slots:
void handleProcess();
void chunkDownloadFinish();
signals:
void errorOccur(const QString& msg);
void downloadProcess(qint64, qint64);
void downloadFinished();
}; };
#endif // FILEDOWNLOADWORKER_H #endif // FILEDOWNLOADWORKER_H

View File

@@ -117,14 +117,14 @@ QLayoutItem *FlowLayout::takeAt(int index)
if (index >= 0 && index < itemList.size()) if (index >= 0 && index < itemList.size())
return itemList.takeAt(index); return itemList.takeAt(index);
else else
return 0; return nullptr;
} }
//! [5] //! [5]
//! [6] //! [6]
Qt::Orientations FlowLayout::expandingDirections() const Qt::Orientations FlowLayout::expandingDirections() const
{ {
return 0; return nullptr;
} }
//! [6] //! [6]
@@ -215,7 +215,7 @@ int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const
return -1; return -1;
} else if (parent->isWidgetType()) { } else if (parent->isWidgetType()) {
QWidget *pw = static_cast<QWidget *>(parent); QWidget *pw = static_cast<QWidget *>(parent);
return pw->style()->pixelMetric(pm, 0, pw); return pw->style()->pixelMetric(pm, nullptr, pw);
} else { } else {
return static_cast<QLayout *>(parent)->spacing(); return static_cast<QLayout *>(parent)->spacing();
} }

View File

@@ -60,7 +60,7 @@ class FlowLayout : public QLayout
public: public:
explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);
explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);
~FlowLayout(); ~FlowLayout() override;
void addItem(QLayoutItem *item) override; void addItem(QLayoutItem *item) override;
int horizontalSpacing() const; int horizontalSpacing() const;

View File

@@ -1,17 +1,13 @@
#include "image_show.h" #include "image_show.h"
#include <QScreen> // Qt5 不再建议使用 QDesktopWidget
#include <QHBoxLayout> #include <QHBoxLayout>
#include <QPainter> #include <QScreen> // Qt5 不再建议使用 QDesktopWidget
#include <QGuiApplication>
#include <DDialog> image_show::image_show(QWidget *parent) :
#include <DBlurEffectWidget> QWidget(parent),
#include <DWidgetUtil> m_dialog(new big_image),
#include <DApplication> m_label(new QLabel)
DWIDGET_USE_NAMESPACE
image_show::image_show(QWidget *parent) : QWidget(parent)
{ {
QHBoxLayout *layout = new QHBoxLayout; QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(m_label); layout->addWidget(m_label);
@@ -23,13 +19,12 @@ void image_show::setImage(QPixmap image)
{ {
QImage screen0; QImage screen0;
screen0 = image.toImage(); screen0 = image.toImage();
// QPainter painter(&screen0);
QImage re_screen1; QImage re_screen1;
QImage re_screen0 = screen0.scaled(QSize(400, 300), Qt::KeepAspectRatio, Qt::SmoothTransformation); QImage re_screen0 = screen0.scaled(QSize(400, 300), Qt::KeepAspectRatio, Qt::SmoothTransformation);
// 获取主屏幕尺寸 // 获取主屏幕尺寸
desktop_w = DApplication::primaryScreen()->geometry().width(); desktop_w = QGuiApplication::primaryScreen()->geometry().width();
desktop_h = DApplication::primaryScreen()->geometry().height(); desktop_h = QGuiApplication::primaryScreen()->geometry().height();
if(screen0.width() > (desktop_w - 20) || screen0.height() > (desktop_h - 20)) if(screen0.width() > (desktop_w - 20) || screen0.height() > (desktop_h - 20))
{ {
@@ -53,5 +48,4 @@ void image_show::mousePressEvent(QMouseEvent *)
m_dialog->setFixedSize(desktop_w, desktop_h); m_dialog->setFixedSize(desktop_w, desktop_h);
m_dialog->move(0,0); m_dialog->move(0,0);
// moveToCenter(m_dialog);
} }

View File

@@ -3,30 +3,30 @@
#include <QWidget> #include <QWidget>
#include <QMouseEvent> #include <QMouseEvent>
#include <QLabel>
#include <QPixmap> #include "big_image.h"
#include <DDialog>
#include <DBlurEffectWidget>
#include <big_image.h>
DWIDGET_USE_NAMESPACE
class image_show : public QWidget class image_show : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit image_show(QWidget *parent = nullptr); explicit image_show(QWidget *parent = nullptr);
void setImage(QPixmap);
int desktop_w; int desktop_w;
int desktop_h; int desktop_h;
private:
QLabel *m_label=new QLabel;
QPixmap m_image;
QLabel image;
big_image *m_dialog=new big_image;
void mousePressEvent(QMouseEvent *event);
signals:
public slots: void setImage(QPixmap);
protected:
void mousePressEvent(QMouseEvent *event) override;
private:
big_image *m_dialog;
QLabel *m_label;
QLabel image;
QPixmap m_image;
}; };
#endif // IMAGE_SHOW_H #endif // IMAGE_SHOW_H

View File

@@ -1,15 +1,18 @@
#include "progressload.h" #include "progressload.h"
ProgressLoad::ProgressLoad(QWidget *parent) : QWidget(parent) ProgressLoad::ProgressLoad(QWidget *parent) :
QWidget(parent),
m_progess(new QWidget(this)),
timer(new QTimer),
value(0)
{ {
m_progess=new QWidget(this);
m_progess->move(0,0); m_progess->move(0,0);
m_progess->show(); m_progess->show();
timer=new QTimer;
value=0;
timer->setInterval(10); timer->setInterval(10);
timer->start(); timer->start();
connect(timer,&QTimer::timeout,[=](){ connect(timer, &QTimer::timeout, [=]()
{
m_progess->setFixedWidth(width() / 100 * value); m_progess->setFixedWidth(width() / 100 * value);
m_progess->setFixedHeight(height()); m_progess->setFixedHeight(height());
}); });
@@ -23,15 +26,17 @@ void ProgressLoad::setValue(int v)
void ProgressLoad::setTheme(bool dark, QColor color) void ProgressLoad::setTheme(bool dark, QColor color)
{ {
if(dark){ if(dark)
{
plt.setColor(QPalette::Background, QColor(28,28,28)); plt.setColor(QPalette::Background, QColor(28,28,28));
setAutoFillBackground(true); setAutoFillBackground(true);
setPalette(plt); setPalette(plt);
}
}else { else
{
plt.setColor(QPalette::Background, QColor(255,255,255)); plt.setColor(QPalette::Background, QColor(255,255,255));
setAutoFillBackground(true); setAutoFillBackground(true);
setPalette(plt); setPalette(plt);
} }
m_progess->setStyleSheet("background-color:"+color.name()); m_progess->setStyleSheet("background-color: " + color.name() + ";");
} }

View File

@@ -4,21 +4,23 @@
#include <QWidget> #include <QWidget>
#include <QTimer> #include <QTimer>
#include <QPalette> #include <QPalette>
class ProgressLoad : public QWidget class ProgressLoad : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ProgressLoad(QWidget *parent = nullptr); explicit ProgressLoad(QWidget *parent = nullptr);
void setValue(int v); void setValue(int v);
void setTheme(bool dark,QColor color); void setTheme(bool dark,QColor color);
signals:
public slots:
private: private:
QWidget *m_progess; QWidget *m_progess;
int value;
QTimer *timer; QTimer *timer;
int value;
QPalette plt; QPalette plt;
}; };
#endif // PROGRESSLOAD_H #endif // PROGRESSLOAD_H

View File

@@ -65,6 +65,24 @@ Widget::Widget(DBlurEffectWidget *parent) :
connect(ui->menu_other, &QPushButton::clicked, this, [=](){Widget::chooseLeftMenu(12);}); connect(ui->menu_other, &QPushButton::clicked, this, [=](){Widget::chooseLeftMenu(12);});
connect(ui->menu_download, &QPushButton::clicked, this, [=](){Widget::chooseLeftMenu(13);}); connect(ui->menu_download, &QPushButton::clicked, this, [=](){Widget::chooseLeftMenu(13);});
connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, [=](DGuiApplicationHelper::ColorType themeType)
{
// 获取系统活动色
QColor main_color;
main_color = DGuiApplicationHelper::instance()->applicationPalette().highlight().color();
if(themeType == DGuiApplicationHelper::DarkType)
{
qDebug() << "Dark";
setTheme(true, main_color);
}
else
{
qDebug() << "Light";
setTheme(false, main_color);
}
});
connect(&appinfoLoadThread, SIGNAL(requestResetUi()), this, SLOT(sltAppinfoResetUi()), Qt::ConnectionType::BlockingQueuedConnection); connect(&appinfoLoadThread, SIGNAL(requestResetUi()), this, SLOT(sltAppinfoResetUi()), Qt::ConnectionType::BlockingQueuedConnection);
connect(&appinfoLoadThread, &SpkAppInfoLoaderThread::requestSetTags, this, &Widget::sltAppinfoTags, Qt::ConnectionType::BlockingQueuedConnection); connect(&appinfoLoadThread, &SpkAppInfoLoaderThread::requestSetTags, this, &Widget::sltAppinfoTags, Qt::ConnectionType::BlockingQueuedConnection);
connect(&appinfoLoadThread, &SpkAppInfoLoaderThread::requestSetAppInformation, this, &Widget::sltAppinfoDetails, Qt::ConnectionType::BlockingQueuedConnection); connect(&appinfoLoadThread, &SpkAppInfoLoaderThread::requestSetAppInformation, this, &Widget::sltAppinfoDetails, Qt::ConnectionType::BlockingQueuedConnection);
@@ -85,24 +103,6 @@ Widget::Widget(DBlurEffectWidget *parent) :
this->setFocus(); this->setFocus();
}); });
connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, [=](DGuiApplicationHelper::ColorType themeType)
{
// 获取系统活动色
QColor main_color;
main_color = DGuiApplicationHelper::instance()->applicationPalette().highlight().color();
if(themeType == DGuiApplicationHelper::DarkType)
{
qDebug() << "Dark";
setTheme(true, main_color);
}
else
{
qDebug() << "Light";
setTheme(false, main_color);
}
});
// 计算显示下载速度 // 计算显示下载速度
download_speed.setInterval(1000); download_speed.setInterval(1000);
download_speed.start(); download_speed.start();
@@ -236,6 +236,16 @@ void Widget::initUI()
main->addWidget(spinner); main->addWidget(spinner);
ui->applist_scrollAreaWidget->setLayout(main); ui->applist_scrollAreaWidget->setLayout(main);
spinner->setFixedSize(80, 80); spinner->setFixedSize(80, 80);
// 初始化主题颜色
if(DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::DarkType)
{
themeIsDark = true;
}
else
{
themeIsDark = false;
}
} }
void Widget::initConfig() void Widget::initConfig()
@@ -543,17 +553,6 @@ void Widget::chooseLeftMenu(int index)
updateUI(); updateUI();
/*
if(QLocale::system().name() == "zh_CN")
{
left_list[index]->setStyleSheet("color: #FFFFFF; background-color: " + main_color.name() + "; border-radius: 8; border: 0px;");
}
else
{
left_list[index]->setStyleSheet("color: #FFFFFF; background-color: " + main_color.name() + "; border-radius: 8; border: 0px; text-align: left; padding-left: 15px;");
}
*/
if(index <= 12) if(index <= 12)
{ {
if(themeIsDark) if(themeIsDark)
@@ -919,7 +918,7 @@ void Widget::sltAppinfoScreenshot(QPixmap *picture, int index)
void Widget::sltAppinfoFinish() void Widget::sltAppinfoFinish()
{ {
ui->label_show->setText(""); ui->label_show->clear();
ui->label_show->hide(); ui->label_show->hide();
} }
@@ -1090,7 +1089,7 @@ void Widget::on_pushButton_updateApt_clicked()
system(("chmod +x " + tmpPath + "/update.sh").c_str()); system(("chmod +x " + tmpPath + "/update.sh").c_str());
QProcess runupdate; QProcess runupdate;
runupdate.start(QString::fromStdString("pkexec " + tmpPath + "/update.sh"), QStringList()); runupdate.start(QString::fromStdString("pkexec " + tmpPath + "/update.sh"));
runupdate.waitForFinished(); runupdate.waitForFinished();
QString error = runupdate.readAllStandardError(); QString error = runupdate.readAllStandardError();
@@ -1132,7 +1131,7 @@ void Widget::on_pushButton_uninstall_clicked()
ui->pushButton_uninstall->setEnabled(false); ui->pushButton_uninstall->setEnabled(false);
QProcess uninstall; QProcess uninstall;
uninstall.start("pkexec apt purge -y " + pkgName.toLower(), QStringList()); uninstall.start("pkexec apt purge -y " + pkgName.toLower());
uninstall.waitForFinished(); uninstall.waitForFinished();
ui->pushButton_download->setEnabled(true); ui->pushButton_download->setEnabled(true);

View File

@@ -1,9 +1,10 @@
#include "workerthreads.h"
#include <QProcess> #include <QProcess>
#include <QDir> #include <QDir>
#include <QFile> #include <QFile>
#include <QJsonDocument> #include <QJsonDocument>
#include "workerthreads.h"
#include "widget.h" #include "widget.h"
#include "HttpClient.h" #include "HttpClient.h"
@@ -15,7 +16,8 @@ void SpkAppInfoLoaderThread::run()
httpClient->get(targetUrl.toString()) httpClient->get(targetUrl.toString())
.header("content-type", "application/json") .header("content-type", "application/json")
.onResponse([this](QByteArray json_array) { .onResponse([this](QByteArray json_array)
{
qDebug() << "请求应用信息 " << json_array; qDebug() << "请求应用信息 " << json_array;
QString urladdress, deatils, more, packagename, appweb; QString urladdress, deatils, more, packagename, appweb;
bool isInstalled; bool isInstalled;
@@ -29,7 +31,8 @@ void SpkAppInfoLoaderThread::run()
urladdress = "https://img.jerrywang.top/"; // 使用图片专用服务器请保留这行,删除后将使用源服务器 urladdress = "https://img.jerrywang.top/"; // 使用图片专用服务器请保留这行,删除后将使用源服务器
urladdress = urladdress.left(urladdress.length() - 1); urladdress = urladdress.left(urladdress.length() - 1);
for (int i=3;i<downloadurl.size();i++) { for(int i = 3; i < downloadurl.size(); i++)
{
urladdress += "/" + downloadurl[i]; urladdress += "/" + downloadurl[i];
deburl += "/" + downloadurl[i]; deburl += "/" + downloadurl[i];
} }
@@ -43,13 +46,15 @@ void SpkAppInfoLoaderThread::run()
QString details; QString details;
details = tr("PkgName: ") + json["Pkgname"].toString() + "\n"; details = tr("PkgName: ") + json["Pkgname"].toString() + "\n";
details += tr("Version: ") + json["Version"].toString() + "\n"; details += tr("Version: ") + json["Version"].toString() + "\n";
if(json["Author"].toString() != "" && json["Author"].toString() != " "){ if(!json["Author"].toString().trimmed().isEmpty())
{
details += tr("Author: ") + json["Author"].toString() + "\n"; details += tr("Author: ") + json["Author"].toString() + "\n";
} }
if(json["Website"].toString() != "" && json["Website"].toString() != " "){ if(!json["Website"].toString().trimmed().isEmpty())
{
details += tr("Official Site: ") + json["Website"].toString() + "\n"; details += tr("Official Site: ") + json["Website"].toString() + "\n";
//ui->pushButton_website->show(); move to setinfo slot // ui->pushButton_website->show(); // move to setinfo slot
appweb = json["Website"].toString(); appweb = json["Website"].toString();
} }
details += tr("Contributor: ") + json["Contributor"].toString() + "\n"; details += tr("Contributor: ") + json["Contributor"].toString() + "\n";
@@ -63,9 +68,13 @@ void SpkAppInfoLoaderThread::run()
isInstall.waitForFinished(); isInstall.waitForFinished();
int error = QString::fromStdString(isInstall.readAllStandardError().toStdString()).length(); int error = QString::fromStdString(isInstall.readAllStandardError().toStdString()).length();
if(error == 0) if(error == 0)
{
isInstalled = true; isInstalled = true;
}
else else
{
isInstalled = false; isInstalled = false;
}
emit requestSetAppInformation(&appName, &details, &more, &appweb, &packagename, &fileUrl, isInstalled); emit requestSetAppInformation(&appName, &details, &more, &appweb, &packagename, &fileUrl, isInstalled);
@@ -76,12 +85,17 @@ void SpkAppInfoLoaderThread::run()
// 图标加载 // 图标加载
httpClient->get(urladdress+"icon.png") httpClient->get(urladdress+"icon.png")
.onResponse([this](QByteArray imgData){ .onResponse([this](QByteArray imgData)
{
QPixmap appicon; QPixmap appicon;
appicon.loadFromData(imgData); appicon.loadFromData(imgData);
emit finishedIconLoad(&appicon); emit finishedIconLoad(&appicon);
}) })
.onError([this](QString errorStr) { .onError([this](QString errorStr)
{
Q_UNUSED(this)
Q_UNUSED(errorStr)
Widget::sendNotification(tr("Failed to load application icon.")); Widget::sendNotification(tr("Failed to load application icon."));
}) })
.block() .block()
@@ -91,17 +105,26 @@ void SpkAppInfoLoaderThread::run()
// 截图展示加载 // 截图展示加载
QPixmap screenshotCache[5]; QPixmap screenshotCache[5];
for (int i = 0; i < 5; i++) { for(int i = 0; i < 5; i++)
{
httpClient->get(urladdress + "screen_" + QString::number(i + 1) + ".png") httpClient->get(urladdress + "screen_" + QString::number(i + 1) + ".png")
.onResponse([this, i, &screenshotCache](QByteArray imgData){ .onResponse([this, i, &screenshotCache](QByteArray imgData)
{
bool s = screenshotCache[i].loadFromData(imgData); bool s = screenshotCache[i].loadFromData(imgData);
if(s){ if(s)
{
emit finishedScreenshotLoad(&screenshotCache[i], i); emit finishedScreenshotLoad(&screenshotCache[i], i);
}else{ }
else
{
emit finishedScreenshotLoad(nullptr, i); emit finishedScreenshotLoad(nullptr, i);
} }
}) })
.onError([this](QString errorStr) { .onError([this](QString errorStr)
{
Q_UNUSED(this)
Q_UNUSED(errorStr)
qDebug() << "截图下载失败"; qDebug() << "截图下载失败";
// Widget::sendNotification(tr("Failed to load application screenshot.")); // Widget::sendNotification(tr("Failed to load application screenshot."));
}) })
@@ -113,13 +136,15 @@ void SpkAppInfoLoaderThread::run()
httpClient->deleteLater(); httpClient->deleteLater();
}) })
.onError([](QString errorStr) { .onError([](QString errorStr)
{
Q_UNUSED(errorStr)
Widget::sendNotification(tr("Failed to download app info. Please check internet connection.")); Widget::sendNotification(tr("Failed to download app info. Please check internet connection."));
}) })
.timeout(5 * 100) .timeout(5 * 100)
.block() .block()
.exec(); .exec();
} }
@@ -135,8 +160,9 @@ void SpkAppInfoLoaderThread::setServer(const QString &server)
void SpkAppInfoLoaderThread::downloadFinished(int exitcode, QProcess::ExitStatus status) void SpkAppInfoLoaderThread::downloadFinished(int exitcode, QProcess::ExitStatus status)
{ {
Q_UNUSED(exitcode); Q_UNUSED(exitcode)
Q_UNUSED(status); Q_UNUSED(status)
qDebug() << "Finish one download"; qDebug() << "Finish one download";
finishedDownload = true; finishedDownload = true;
} }
@@ -146,7 +172,10 @@ int SpkAppInfoLoaderThread::waitDownload(QProcess& downloader)
while(!downloader.waitForFinished(100)) while(!downloader.waitForFinished(100))
{ {
if(downloader.state() == QProcess::NotRunning) if(downloader.state() == QProcess::NotRunning)
{
return -1; return -1;
}
if(this->isInterruptionRequested()) if(this->isInterruptionRequested())
{ {
downloader.terminate(); downloader.terminate();

View File

@@ -6,7 +6,6 @@
#include <QUrl> #include <QUrl>
#include <QProcess> #include <QProcess>
namespace AeaQt { namespace AeaQt {
class HttpClient; class HttpClient;
} }
@@ -14,13 +13,28 @@ namespace AeaQt {
class SpkAppInfoLoaderThread Q_DECL_FINAL : public QThread class SpkAppInfoLoaderThread Q_DECL_FINAL : public QThread
{ {
Q_OBJECT Q_OBJECT
public: public:
// explicit SpkAppInfoLoaderThread() = default; // explicit SpkAppInfoLoaderThread() = default;
protected:
void run() Q_DECL_OVERRIDE; void run() Q_DECL_OVERRIDE;
private:
QUrl targetUrl;
QString serverUrl;
bool finishedDownload = false;
int downloaderRetval = 0;
AeaQt::HttpClient *httpClient;
int waitDownload(QProcess& downloader);
public slots: public slots:
void setUrl(const QUrl &url); void setUrl(const QUrl &url);
void setServer(const QString &server); void setServer(const QString &server);
void downloadFinished(int exitcode, QProcess::ExitStatus status); void downloadFinished(int exitcode, QProcess::ExitStatus status);
signals: signals:
void requestResetUi(); void requestResetUi();
void requestSetTags(QStringList *tagList); void requestSetTags(QStringList *tagList);
@@ -30,14 +44,7 @@ signals:
void finishedIconLoad(QPixmap *icon); void finishedIconLoad(QPixmap *icon);
void finishedScreenshotLoad(QPixmap *icon, int index); // 该信号必须以 BlockingQueued 方式连接 void finishedScreenshotLoad(QPixmap *icon, int index); // 该信号必须以 BlockingQueued 方式连接
void finishAllLoading(); // 该信号必须以 BlockingQueued 方式连接 void finishAllLoading(); // 该信号必须以 BlockingQueued 方式连接
private:
int waitDownload(QProcess& downloader);
QUrl targetUrl;
QString serverUrl;
bool finishedDownload = false;
int downloaderRetval = 0;
AeaQt::HttpClient *httpClient;
}; };
#endif // WORKERTHREADS_H #endif // WORKERTHREADS_H