first
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
#include "AppInfo.h"
|
||||
|
||||
#include <QQmlContext>
|
||||
#include <QGuiApplication>
|
||||
#include "Version.h"
|
||||
|
||||
AppInfo::AppInfo(QObject *parent) : QObject{parent} {
|
||||
version(APPLICATION_VERSION);
|
||||
}
|
||||
|
||||
|
||||
[[maybe_unused]] void AppInfo::testCrash() {
|
||||
auto *crash = reinterpret_cast<volatile int *>(0);
|
||||
*crash = 0;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QQmlApplicationEngine>
|
||||
|
||||
#include "singleton.h"
|
||||
#include "stdafx.h"
|
||||
|
||||
class AppInfo : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO(QString, version)
|
||||
private:
|
||||
explicit AppInfo(QObject *parent = nullptr);
|
||||
|
||||
public:
|
||||
SINGLETON(AppInfo)
|
||||
[[maybe_unused]] Q_INVOKABLE void testCrash();
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <Windows.h>
|
||||
#include <DbgHelp.h>
|
||||
#include <QDateTime>
|
||||
#include <QDir>
|
||||
#include <QGuiApplication>
|
||||
#include <QProcess>
|
||||
#include <QStandardPaths>
|
||||
#include <QString>
|
||||
|
||||
#pragma comment(lib, "Dbghelp.lib")
|
||||
|
||||
static void miniDumpWriteDump(HANDLE hProcess, DWORD ProcessId, HANDLE hFile,
|
||||
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
|
||||
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam) {
|
||||
typedef HRESULT(WINAPI * MiniDumpWriteDumpPtr)(
|
||||
HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType,
|
||||
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
|
||||
CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
|
||||
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
|
||||
HMODULE module = LoadLibraryW(L"Dbghelp.dll");
|
||||
if (module) {
|
||||
MiniDumpWriteDumpPtr mini_dump_write_dump;
|
||||
mini_dump_write_dump =
|
||||
reinterpret_cast<MiniDumpWriteDumpPtr>(GetProcAddress(module, "MiniDumpWriteDump"));
|
||||
if (mini_dump_write_dump) {
|
||||
mini_dump_write_dump(hProcess, ProcessId, hFile, static_cast<MINIDUMP_TYPE>(80),
|
||||
ExceptionParam, nullptr, CallbackParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BOOL CALLBACK MyMiniDumpCallback(PVOID, const PMINIDUMP_CALLBACK_INPUT input,
|
||||
PMINIDUMP_CALLBACK_OUTPUT output) {
|
||||
if (input == nullptr || output == nullptr)
|
||||
return FALSE;
|
||||
|
||||
BOOL ret = FALSE;
|
||||
switch (input->CallbackType) {
|
||||
case IncludeModuleCallback:
|
||||
case IncludeThreadCallback:
|
||||
case ThreadCallback:
|
||||
case ThreadExCallback:
|
||||
ret = TRUE;
|
||||
break;
|
||||
case ModuleCallback: {
|
||||
if (!(output->ModuleWriteFlags & ModuleReferencedByMemory)) {
|
||||
output->ModuleWriteFlags &= ~ModuleWriteModule;
|
||||
}
|
||||
ret = TRUE;
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void WriteDump(EXCEPTION_POINTERS *exp, const std::wstring &path) {
|
||||
HANDLE h = ::CreateFileW(path.c_str(), GENERIC_WRITE | GENERIC_READ,
|
||||
FILE_SHARE_WRITE | FILE_SHARE_READ, nullptr, CREATE_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
MINIDUMP_EXCEPTION_INFORMATION info;
|
||||
info.ThreadId = ::GetCurrentThreadId();
|
||||
info.ExceptionPointers = exp;
|
||||
info.ClientPointers = FALSE;
|
||||
MINIDUMP_CALLBACK_INFORMATION mci;
|
||||
mci.CallbackRoutine = (MINIDUMP_CALLBACK_ROUTINE) MyMiniDumpCallback;
|
||||
mci.CallbackParam = nullptr;
|
||||
miniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), h, &info, &mci);
|
||||
::CloseHandle(h);
|
||||
}
|
||||
|
||||
LONG WINAPI MyUnhandledExceptionFilter(EXCEPTION_POINTERS *exp) {
|
||||
const QString dumpFileName =
|
||||
QString("%1_%2.dmp").arg("crash", QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
|
||||
const QString dumpDirPath =
|
||||
QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/dmp";
|
||||
const QDir dumpDir(dumpDirPath);
|
||||
if (!dumpDir.exists()) {
|
||||
dumpDir.mkpath(dumpDirPath);
|
||||
}
|
||||
QString dumpFilePath = dumpDir.filePath(dumpFileName);
|
||||
WriteDump(exp, dumpFilePath.toStdWString());
|
||||
QStringList arguments;
|
||||
arguments << "-crashed=" + dumpFilePath;
|
||||
QProcess::startDetached(QGuiApplication::applicationFilePath(), arguments);
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
#include "CircularReveal.h"
|
||||
#include <QGuiApplication>
|
||||
#include <QQuickItemGrabResult>
|
||||
#include <QPainterPath>
|
||||
|
||||
CircularReveal::CircularReveal(QQuickItem *parent) : QQuickPaintedItem(parent) {
|
||||
_target = nullptr;
|
||||
_radius = 0;
|
||||
_anim = new QPropertyAnimation(this, "radius", this);
|
||||
_anim->setDuration(333);
|
||||
_anim->setEasingCurve(QEasingCurve::OutCubic);
|
||||
setVisible(false);
|
||||
connect(_anim, &QPropertyAnimation::finished, this, [=]() {
|
||||
update();
|
||||
setVisible(false);
|
||||
Q_EMIT animationFinished();
|
||||
});
|
||||
connect(this, &CircularReveal::radiusChanged, this, [=]() { update(); });
|
||||
}
|
||||
|
||||
void CircularReveal::paint(QPainter *painter) {
|
||||
painter->save();
|
||||
painter->drawImage(QRect(0, 0, static_cast<int>(width()), static_cast<int>(height())), _source);
|
||||
QPainterPath path;
|
||||
path.moveTo(_center.x(), _center.y());
|
||||
path.addEllipse(QPointF(_center.x(), _center.y()), _radius, _radius);
|
||||
painter->setCompositionMode(QPainter::CompositionMode_Clear);
|
||||
if(_darkToLight){
|
||||
painter->fillPath(path, Qt::white);
|
||||
}else{
|
||||
QPainterPath outerRect;
|
||||
outerRect.addRect(0, 0, width(), height());
|
||||
outerRect = outerRect.subtracted(path);
|
||||
painter->fillPath(outerRect, Qt::black);
|
||||
}
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
[[maybe_unused]] void CircularReveal::start(int w, int h, const QPoint ¢er, int radius) {
|
||||
if (_anim->state() == QAbstractAnimation::Running) {
|
||||
_anim->stop();
|
||||
int currentRadius = _radius;
|
||||
_anim->setStartValue(currentRadius);
|
||||
_anim->setEndValue(_darkToLight ? 0 : radius);
|
||||
} else {
|
||||
if(_darkToLight){
|
||||
_anim->setStartValue(radius);
|
||||
_anim->setEndValue(0);
|
||||
}else{
|
||||
_anim->setStartValue(0);
|
||||
_anim->setEndValue(radius);
|
||||
}
|
||||
}
|
||||
_center = center;
|
||||
_grabResult = _target->grabToImage(QSize(w, h));
|
||||
connect(_grabResult.data(), &QQuickItemGrabResult::ready, this,
|
||||
&CircularReveal::handleGrabResult);
|
||||
}
|
||||
|
||||
void CircularReveal::handleGrabResult() {
|
||||
_grabResult.data()->image().swap(_source);
|
||||
update();
|
||||
setVisible(true);
|
||||
Q_EMIT imageChanged();
|
||||
_anim->start();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include <QQuickItem>
|
||||
#include <QQuickPaintedItem>
|
||||
#include <QPainter>
|
||||
#include <QPropertyAnimation>
|
||||
#include "src/stdafx.h"
|
||||
|
||||
class CircularReveal : public QQuickPaintedItem {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO_P(QQuickItem *, target)
|
||||
Q_PROPERTY_AUTO(int, radius)
|
||||
Q_PROPERTY_AUTO(bool, darkToLight)
|
||||
public:
|
||||
explicit CircularReveal(QQuickItem *parent = nullptr);
|
||||
void paint(QPainter *painter) override;
|
||||
[[maybe_unused]] Q_INVOKABLE void start(int w, int h, const QPoint ¢er, int radius);
|
||||
Q_SIGNAL void imageChanged();
|
||||
Q_SIGNAL void animationFinished();
|
||||
Q_SLOT void handleGrabResult();
|
||||
|
||||
private:
|
||||
QPropertyAnimation *_anim = nullptr;
|
||||
QImage _source;
|
||||
QPoint _center;
|
||||
QSharedPointer<QQuickItemGrabResult> _grabResult;
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
//
|
||||
// Created by rookie on 2025/12/3.
|
||||
//
|
||||
#include <qmath.h>
|
||||
#include "DataGenerator.h"
|
||||
|
||||
QVector<double> DataGenerator::xData() const {
|
||||
QReadLocker locker(&m_lock);
|
||||
return m_xData;
|
||||
}
|
||||
|
||||
QVector<double> DataGenerator::yData() const {
|
||||
QReadLocker locker(&m_lock);
|
||||
return m_yData;
|
||||
}
|
||||
|
||||
bool DataGenerator::isRunning() const {
|
||||
return m_timer->isActive();
|
||||
}
|
||||
|
||||
Q_INVOKABLE void DataGenerator::start() {
|
||||
if (!m_timer->isActive()) {
|
||||
m_timer->start();
|
||||
emit runningChanged(true);
|
||||
generateData();
|
||||
}
|
||||
}
|
||||
|
||||
Q_INVOKABLE void DataGenerator::stop() {
|
||||
if (m_timer->isActive()) {
|
||||
m_timer->stop();
|
||||
emit runningChanged(false);
|
||||
}
|
||||
}
|
||||
|
||||
Q_INVOKABLE void DataGenerator::setParameters(double sineFreq, double sineAmp, double noiseAmp) {
|
||||
QWriteLocker locker(&m_lock);
|
||||
m_sineFrequency = sineFreq;
|
||||
m_sineAmplitude = sineAmp;
|
||||
m_noiseAmplitude = noiseAmp;
|
||||
}
|
||||
|
||||
void DataGenerator::generateData() {
|
||||
QWriteLocker locker(&m_lock);
|
||||
|
||||
m_xData.clear();
|
||||
m_yData.clear();
|
||||
|
||||
double dt = 1.0 / m_sampleRate;
|
||||
|
||||
for (int i = 0; i < m_sampleRate; ++i) {
|
||||
double t = i * dt;
|
||||
|
||||
double sineValue = m_sineAmplitude * std::sin(2 * M_PI * m_sineFrequency * t);
|
||||
|
||||
double randomValue = (QRandomGenerator::global()->generateDouble() - 0.5) * 2.0;
|
||||
double noiseValue = m_noiseAmplitude * randomValue;//-0.03~0.03
|
||||
|
||||
m_xData.append(t);
|
||||
m_yData.append(sineValue + noiseValue);
|
||||
}
|
||||
|
||||
emit dataUpdated();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// Created by rookie on 2025/12/3.
|
||||
//
|
||||
|
||||
#ifndef DATAGENERATOR_H
|
||||
#define DATAGENERATOR_H
|
||||
|
||||
|
||||
#include <QObject>
|
||||
#include <QVector>
|
||||
#include <QTimer>
|
||||
#include <QRandomGenerator>
|
||||
#include <QReadWriteLock>
|
||||
#include <cmath>
|
||||
#include <QDateTime>
|
||||
|
||||
class DataGenerator : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QVector<double> xData READ xData NOTIFY dataUpdated)
|
||||
Q_PROPERTY(QVector<double> yData READ yData NOTIFY dataUpdated)
|
||||
Q_PROPERTY(bool running READ isRunning NOTIFY runningChanged)
|
||||
|
||||
public:
|
||||
explicit DataGenerator(QObject *parent = nullptr)
|
||||
: QObject(parent), m_timer(new QTimer(this)) {
|
||||
|
||||
m_timer->setInterval(50);
|
||||
connect(m_timer, &QTimer::timeout, this, &DataGenerator::generateData);
|
||||
|
||||
m_sampleRate = 20000.0;
|
||||
m_sineFrequency = 2.0; //Hz
|
||||
m_sineAmplitude = 1.5;
|
||||
m_noiseAmplitude = 0.03;
|
||||
|
||||
m_xData.reserve(m_sampleRate);
|
||||
m_yData.reserve(m_sampleRate);
|
||||
}
|
||||
|
||||
~DataGenerator() override {
|
||||
stop();
|
||||
}
|
||||
QVector<double> xData() const;
|
||||
QVector<double> yData() const;
|
||||
bool isRunning() const;
|
||||
|
||||
|
||||
public slots:
|
||||
Q_INVOKABLE void start();
|
||||
Q_INVOKABLE void stop();
|
||||
Q_INVOKABLE void setParameters(double sineFreq, double sineAmp, double noiseAmp);
|
||||
|
||||
signals:
|
||||
void dataUpdated();
|
||||
void runningChanged(bool running);
|
||||
|
||||
private slots:
|
||||
void generateData();
|
||||
|
||||
private:
|
||||
double m_sampleRate;
|
||||
double m_sineFrequency;
|
||||
double m_sineAmplitude;
|
||||
double m_noiseAmplitude;
|
||||
|
||||
QVector<double> m_xData;
|
||||
QVector<double> m_yData;
|
||||
|
||||
QTimer *m_timer;
|
||||
mutable QReadWriteLock m_lock;
|
||||
};
|
||||
|
||||
|
||||
#endif //DATAGENERATOR_H
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "FileWatcher.h"
|
||||
|
||||
FileWatcher::FileWatcher(QObject *parent) : QObject{parent} {
|
||||
connect(&_watcher, &QFileSystemWatcher::fileChanged, this, [=](const QString &path) {
|
||||
Q_EMIT fileChanged();
|
||||
clean();
|
||||
_watcher.addPath(_path);
|
||||
});
|
||||
connect(this, &FileWatcher::pathChanged, this, [=]() {
|
||||
clean();
|
||||
_watcher.addPath(_path.replace("file:///", ""));
|
||||
});
|
||||
if (!_path.isEmpty()) {
|
||||
_watcher.addPath(_path);
|
||||
}
|
||||
}
|
||||
|
||||
void FileWatcher::clean() {
|
||||
for (int i = 0; i <= _watcher.files().size() - 1; ++i) {
|
||||
auto item = _watcher.files().at(i);
|
||||
_watcher.removePath(item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QFileSystemWatcher>
|
||||
#include <QtQml/qqml.h>
|
||||
#include "src/stdafx.h"
|
||||
|
||||
class FileWatcher : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO(QString, path)
|
||||
public:
|
||||
explicit FileWatcher(QObject *parent = nullptr);
|
||||
Q_SIGNAL void fileChanged();
|
||||
|
||||
private:
|
||||
void clean();
|
||||
|
||||
private:
|
||||
QFileSystemWatcher _watcher;
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
#include "FpsItem.h"
|
||||
|
||||
#include <QTimer>
|
||||
#include <QQuickWindow>
|
||||
|
||||
FpsItem::FpsItem() {
|
||||
_fps = 0;
|
||||
auto *timer = new QTimer(this);
|
||||
connect(timer, &QTimer::timeout, this, [this] {
|
||||
fps(_frameCount);
|
||||
_frameCount = 0;
|
||||
});
|
||||
connect(this, &QQuickItem::windowChanged, this, [this] {
|
||||
if (window()) {
|
||||
connect(
|
||||
window(), &QQuickWindow::afterRendering, this, [this] { _frameCount++; },
|
||||
Qt::DirectConnection);
|
||||
}
|
||||
});
|
||||
timer->start(1000);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <QQuickItem>
|
||||
#include "src/stdafx.h"
|
||||
|
||||
class FpsItem : public QQuickItem {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO(int, fps)
|
||||
public:
|
||||
FpsItem();
|
||||
|
||||
private:
|
||||
int _frameCount = 0;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
#include "OpenGLItem.h"
|
||||
|
||||
#include <QOpenGLFramebufferObjectFormat>
|
||||
#include <QOpenGLShaderProgram>
|
||||
#include <QQuickWindow>
|
||||
|
||||
class FBORenderer : public QQuickFramebufferObject::Renderer, protected QOpenGLFunctions {
|
||||
public:
|
||||
explicit FBORenderer(const OpenGLItem *item);
|
||||
void render() override;
|
||||
QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override;
|
||||
QOpenGLShaderProgram program;
|
||||
const OpenGLItem *item = nullptr;
|
||||
};
|
||||
|
||||
FBORenderer::FBORenderer(const OpenGLItem *item) {
|
||||
this->item = item;
|
||||
initializeOpenGLFunctions();
|
||||
program.addCacheableShaderFromSourceCode(QOpenGLShader::Vertex, "attribute highp vec4 vertices;"
|
||||
"varying highp vec2 coords;"
|
||||
"void main() {"
|
||||
" gl_Position = vertices;"
|
||||
" coords = vertices.xy;"
|
||||
"}");
|
||||
program.addCacheableShaderFromSourceCode(
|
||||
QOpenGLShader::Fragment,
|
||||
"uniform lowp float t;"
|
||||
"varying highp vec2 coords;"
|
||||
"void main() {"
|
||||
" lowp float i = 1. - (pow(abs(coords.x), 4.) + pow(abs(coords.y), 4.));"
|
||||
" i = smoothstep(t - 0.8, t + 0.8, i);"
|
||||
" i = floor(i * 20.) / 20.;"
|
||||
" gl_FragColor = vec4(coords * .5 + .5, i, i);"
|
||||
"}");
|
||||
|
||||
program.bindAttributeLocation("vertices", 0);
|
||||
program.link();
|
||||
}
|
||||
|
||||
QOpenGLFramebufferObject *FBORenderer::createFramebufferObject(const QSize &size) {
|
||||
QOpenGLFramebufferObjectFormat format;
|
||||
format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
|
||||
format.setSamples(4);
|
||||
return new QOpenGLFramebufferObject(size, format);
|
||||
}
|
||||
|
||||
void FBORenderer::render() {
|
||||
auto pixelRatio = item->window()->devicePixelRatio();
|
||||
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
glEnable(GL_DEPTH_TEST);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
program.bind();
|
||||
program.enableAttributeArray(0);
|
||||
float values[] = {-1, -1, 1, -1, -1, 1, 1, 1};
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
program.setAttributeArray(0, GL_FLOAT, values, 2);
|
||||
program.setUniformValue("t", (float) item->t());
|
||||
glViewport(0, 0, qRound(item->width() * pixelRatio), qRound(item->height() * pixelRatio));
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
glEnable(GL_BLEND);
|
||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
program.disableAttributeArray(0);
|
||||
program.release();
|
||||
}
|
||||
|
||||
|
||||
OpenGLItem::OpenGLItem(QQuickItem *parent) : QQuickFramebufferObject(parent) {
|
||||
setMirrorVertically(true);
|
||||
startTimer(1);
|
||||
}
|
||||
|
||||
void OpenGLItem::timerEvent(QTimerEvent *) {
|
||||
update();
|
||||
}
|
||||
|
||||
void OpenGLItem::setT(qreal t) {
|
||||
if (t == m_t)
|
||||
return;
|
||||
m_t = t;
|
||||
emit tChanged();
|
||||
}
|
||||
|
||||
|
||||
QQuickFramebufferObject::Renderer *OpenGLItem::createRenderer() const {
|
||||
return new FBORenderer(this);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <QtQuick/QQuickItem>
|
||||
#include <QOpenGLFunctions>
|
||||
#include <QQuickFramebufferObject>
|
||||
|
||||
class FBORenderer;
|
||||
|
||||
class OpenGLItem : public QQuickFramebufferObject, protected QOpenGLFunctions {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(qreal t READ t WRITE setT NOTIFY tChanged)
|
||||
public:
|
||||
explicit OpenGLItem(QQuickItem *parent = nullptr);
|
||||
[[nodiscard]] QQuickFramebufferObject::Renderer *createRenderer() const override;
|
||||
void timerEvent(QTimerEvent *) override;
|
||||
[[nodiscard]] qreal t() const {
|
||||
return m_t;
|
||||
}
|
||||
void setT(qreal t);
|
||||
signals:
|
||||
void tChanged();
|
||||
|
||||
private:
|
||||
qreal m_t{};
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
#include "InitializrHelper.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QGuiApplication>
|
||||
|
||||
[[maybe_unused]] InitializrHelper::InitializrHelper(QObject *parent) : QObject(parent) {
|
||||
}
|
||||
|
||||
InitializrHelper::~InitializrHelper() = default;
|
||||
|
||||
|
||||
bool InitializrHelper::copyDir(const QDir &fromDir, const QDir &toDir, bool coverIfFileExists) {
|
||||
const QDir &_formDir = fromDir;
|
||||
QDir _toDir = toDir;
|
||||
if (!_toDir.exists()) {
|
||||
if (!_toDir.mkdir(toDir.absolutePath()))
|
||||
return false;
|
||||
}
|
||||
QFileInfoList fileInfoList = _formDir.entryInfoList();
|
||||
foreach (QFileInfo fileInfo, fileInfoList) {
|
||||
if (fileInfo.fileName() == "." || fileInfo.fileName() == "..")
|
||||
continue;
|
||||
if (fileInfo.isDir()) {
|
||||
if (!copyDir(fileInfo.filePath(), _toDir.filePath(fileInfo.fileName()), true))
|
||||
return false;
|
||||
} else {
|
||||
if (coverIfFileExists && _toDir.exists(fileInfo.fileName())) {
|
||||
_toDir.remove(fileInfo.fileName());
|
||||
}
|
||||
if (!QFile::copy(fileInfo.filePath(), _toDir.filePath(fileInfo.fileName()))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void InitializrHelper::templateToFile(const QString &source, const QString &dest, Args &&...args) {
|
||||
QFile file(source);
|
||||
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
QTextStream in(&file);
|
||||
QString content = in.readAll().arg(std::forward<Args>(args)...);
|
||||
file.close();
|
||||
QDir outputDir = QFileInfo(dest).absoluteDir();
|
||||
if (!outputDir.exists()) {
|
||||
outputDir.mkpath(outputDir.absolutePath());
|
||||
}
|
||||
QFile outputFile(dest);
|
||||
if (outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
||||
QTextStream out(&outputFile);
|
||||
out << content;
|
||||
outputFile.close();
|
||||
} else {
|
||||
qDebug() << "Failed to open output file.";
|
||||
}
|
||||
} else {
|
||||
qDebug() << "Failed to open resource file.";
|
||||
}
|
||||
}
|
||||
|
||||
void InitializrHelper::copyFile(const QString &source, const QString &dest) {
|
||||
QFile::copy(source, dest);
|
||||
QFile::setPermissions(dest, QFile::WriteOwner | QFile::WriteUser | QFile::WriteGroup |
|
||||
QFile::WriteOther);
|
||||
}
|
||||
|
||||
[[maybe_unused]] void InitializrHelper::generate(const QString &name, const QString &path) {
|
||||
if (name.isEmpty()) {
|
||||
error(tr("The name cannot be empty"));
|
||||
return;
|
||||
}
|
||||
if (path.isEmpty()) {
|
||||
error(tr("The creation path cannot be empty"));
|
||||
return;
|
||||
}
|
||||
QDir projectRootDir(path);
|
||||
if (!projectRootDir.exists()) {
|
||||
error(tr("The path does not exist"));
|
||||
return;
|
||||
}
|
||||
QString projectPath = projectRootDir.filePath(name);
|
||||
QDir projectDir(projectPath);
|
||||
if (projectDir.exists()) {
|
||||
error(tr("%1 folder already exists").arg(name));
|
||||
return;
|
||||
}
|
||||
projectDir.mkpath(projectPath);
|
||||
QDir fluentDir(projectDir.filePath("FluentUI"));
|
||||
copyDir(QDir(QGuiApplication::applicationDirPath() + "/source"), fluentDir);
|
||||
templateToFile(":/example/res/template/CMakeLists.txt.in",
|
||||
projectDir.filePath("CMakeLists.txt"), name);
|
||||
templateToFile(":/example/res/template/src/CMakeLists.txt.in",
|
||||
projectDir.filePath("src/CMakeLists.txt"), name);
|
||||
templateToFile(":/example/res/template/src/main.cpp.in", projectDir.filePath("src/main.cpp"),
|
||||
name);
|
||||
templateToFile(":/example/res/template/src/main.qml.in", projectDir.filePath("src/main.qml"),
|
||||
name);
|
||||
templateToFile(":/example/res/template/src/en_US.ts.in",
|
||||
projectDir.filePath("src/" + name + "_en_US.ts"), name);
|
||||
templateToFile(":/example/res/template/src/zh_CN.ts.in",
|
||||
projectDir.filePath("src/" + name + "_zh_CN.ts"), name);
|
||||
copyFile(":/example/res/template/src/App.qml.in", projectDir.filePath("src/App.qml"));
|
||||
copyFile(":/example/res/template/src/qml.qrc.in", projectDir.filePath("src/qml.qrc"));
|
||||
copyFile(":/example/res/template/src/logo.ico.in", projectDir.filePath("src/logo.ico"));
|
||||
copyFile(":/example/res/template/src/README.md.in", projectDir.filePath("src/README.md"));
|
||||
return this->success(projectPath + "/CMakeLists.txt");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QtQml/qqml.h>
|
||||
#include <QDir>
|
||||
#include "src/singleton.h"
|
||||
|
||||
class InitializrHelper : public QObject {
|
||||
Q_OBJECT
|
||||
private:
|
||||
[[maybe_unused]] explicit InitializrHelper(QObject *parent = nullptr);
|
||||
bool copyDir(const QDir &fromDir, const QDir &toDir, bool coverIfFileExists = true);
|
||||
static void copyFile(const QString &source, const QString &dest);
|
||||
template <typename... Args>
|
||||
void templateToFile(const QString &source, const QString &dest, Args &&...args);
|
||||
|
||||
public:
|
||||
SINGLETON(InitializrHelper)
|
||||
~InitializrHelper() override;
|
||||
[[maybe_unused]] Q_INVOKABLE void generate(const QString &name, const QString &path);
|
||||
Q_SIGNAL void error(const QString &message);
|
||||
Q_SIGNAL void success(const QString &path);
|
||||
};
|
||||
@@ -0,0 +1,218 @@
|
||||
#include "Log.h"
|
||||
#include <QtCore/qdebug.h>
|
||||
#include <QtCore/qfile.h>
|
||||
#include <QtCore/qtextstream.h>
|
||||
#include <QGuiApplication>
|
||||
#include <iostream>
|
||||
#include <QDateTime>
|
||||
#include <QStandardPaths>
|
||||
#include <QDir>
|
||||
#include <QThread>
|
||||
#include <QSettings>
|
||||
#include <QRegularExpression>
|
||||
#include <QMutexLocker>
|
||||
#include <QMutex>
|
||||
#include "Version.h"
|
||||
|
||||
#ifdef WIN32
|
||||
# include <process.h>
|
||||
#else
|
||||
# include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifndef QT_ENDL
|
||||
# if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
|
||||
# define QT_ENDL Qt::endl
|
||||
# else
|
||||
# define QT_ENDL endl
|
||||
# endif
|
||||
#endif
|
||||
|
||||
static QString g_app = {};
|
||||
static QString g_file_path = {};
|
||||
static bool g_logError = false;
|
||||
|
||||
static std::unique_ptr<QFile> g_logFile = nullptr;
|
||||
static std::unique_ptr<QTextStream> g_logStream = nullptr;
|
||||
static QMutex g_logMutex;
|
||||
|
||||
static int g_logLevel = 4;
|
||||
|
||||
std::map<QtMsgType, int> logLevelMap = {
|
||||
{QtFatalMsg, 0},
|
||||
{QtCriticalMsg, 1},
|
||||
{QtWarningMsg, 2},
|
||||
{QtInfoMsg, 3},
|
||||
{QtDebugMsg, 4}
|
||||
};
|
||||
|
||||
QString Log::prettyProductInfoWrapper() {
|
||||
auto productName = QSysInfo::prettyProductName();
|
||||
#if QT_VERSION < QT_VERSION_CHECK(6, 5, 0)
|
||||
# if defined(Q_OS_MACOS)
|
||||
auto macosVersionFile =
|
||||
QString::fromUtf8("/System/Library/CoreServices/.SystemVersionPlatform.plist");
|
||||
auto fi = QFileInfo(macosVersionFile);
|
||||
if (fi.exists() && fi.isReadable()) {
|
||||
auto plistFile = QFile(macosVersionFile);
|
||||
plistFile.open(QIODevice::ReadOnly);
|
||||
while (!plistFile.atEnd()) {
|
||||
auto line = plistFile.readLine();
|
||||
if (line.contains("ProductUserVisibleVersion")) {
|
||||
auto nextLine = plistFile.readLine();
|
||||
if (nextLine.contains("<string>")) {
|
||||
QRegularExpression re(QString::fromUtf8("\\s*<string>(.*)</string>"));
|
||||
auto matches = re.match(QString::fromUtf8(nextLine));
|
||||
if (matches.hasMatch()) {
|
||||
productName = QString::fromUtf8("macOS ") + matches.captured(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
#if defined(Q_OS_WIN)
|
||||
QSettings regKey{
|
||||
QString::fromUtf8(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion)"),
|
||||
QSettings::NativeFormat};
|
||||
if (regKey.contains(QString::fromUtf8("CurrentBuildNumber"))) {
|
||||
auto buildNumber = regKey.value(QString::fromUtf8("CurrentBuildNumber")).toInt();
|
||||
if (buildNumber > 0) {
|
||||
if (buildNumber < 9200) {
|
||||
productName = QString::fromUtf8("Windows 7 build %1").arg(buildNumber);
|
||||
} else if (buildNumber < 10240) {
|
||||
productName = QString::fromUtf8("Windows 8 build %1").arg(buildNumber);
|
||||
} else if (buildNumber < 22000) {
|
||||
productName = QString::fromUtf8("Windows 10 build %1").arg(buildNumber);
|
||||
} else {
|
||||
productName = QString::fromUtf8("Windows 11 build %1").arg(buildNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return productName;
|
||||
}
|
||||
|
||||
static inline void messageHandler(const QtMsgType type, const QMessageLogContext &context,
|
||||
const QString &message) {
|
||||
if (message == "Could not get the INetworkConnection instance for the adapter GUID.") {
|
||||
return;
|
||||
}
|
||||
if (logLevelMap[type] > g_logLevel) {
|
||||
return;
|
||||
}
|
||||
if (!message.isEmpty()) {
|
||||
QString levelName;
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
levelName = QStringLiteral("Debug");
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
levelName = QStringLiteral("Info");
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
levelName = QStringLiteral("Warning");
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
levelName = QStringLiteral("Critical");
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
levelName = QStringLiteral("Fatal");
|
||||
break;
|
||||
}
|
||||
QString fileAndLineLogStr;
|
||||
if (context.file) {
|
||||
std::string strFileTmp = context.file;
|
||||
const char *ptr = strrchr(strFileTmp.c_str(), '/');
|
||||
if (nullptr != ptr) {
|
||||
char fn[512] = {0};
|
||||
sprintf(fn, "%s", ptr + 1);
|
||||
strFileTmp = fn;
|
||||
}
|
||||
const char *ptrTmp = strrchr(strFileTmp.c_str(), '\\');
|
||||
if (nullptr != ptrTmp) {
|
||||
char fn[512] = {0};
|
||||
sprintf(fn, "%s", ptrTmp + 1);
|
||||
strFileTmp = fn;
|
||||
}
|
||||
fileAndLineLogStr = QString::fromStdString("[%1:%2]").arg(
|
||||
QString::fromStdString(strFileTmp), QString::number(context.line));
|
||||
}
|
||||
const QString finalMessage =
|
||||
QString::fromStdString("%1[%2]%3[%4]:%5")
|
||||
.arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz"), levelName,
|
||||
fileAndLineLogStr,
|
||||
QString::number(reinterpret_cast<quintptr>(QThread::currentThreadId())),
|
||||
message);
|
||||
if ((type == QtInfoMsg) || (type == QtDebugMsg)) {
|
||||
std::cout << qPrintable(finalMessage) << std::endl;
|
||||
} else {
|
||||
std::cerr << qPrintable(finalMessage) << std::endl;
|
||||
}
|
||||
if (g_logError) {
|
||||
return;
|
||||
}
|
||||
QMutexLocker locker(&g_logMutex);
|
||||
if (!g_logFile) {
|
||||
g_logFile = std::make_unique<QFile>(g_file_path);
|
||||
if (!g_logFile->open(QFile::WriteOnly | QFile::Text | QFile::Append)) {
|
||||
std::cerr << "Can't open file to write: " << qPrintable(g_logFile->errorString())
|
||||
<< std::endl;
|
||||
g_logFile.reset();
|
||||
g_logError = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!g_logStream) {
|
||||
g_logStream = std::make_unique<QTextStream>();
|
||||
g_logStream->setDevice(g_logFile.get());
|
||||
}
|
||||
(*g_logStream) << finalMessage << QT_ENDL;
|
||||
g_logStream->flush();
|
||||
}
|
||||
}
|
||||
|
||||
void Log::setup(char *argv[], const QString &app, int level) {
|
||||
Q_ASSERT(!app.isEmpty());
|
||||
if (app.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
g_logLevel = level;
|
||||
static bool once = false;
|
||||
if (once) {
|
||||
return;
|
||||
}
|
||||
QString applicationPath = QString::fromStdString(argv[0]);
|
||||
once = true;
|
||||
g_app = app;
|
||||
const QString logFileName =
|
||||
QString("%1_%2.log").arg(g_app, QDateTime::currentDateTime().toString("yyyyMMdd"));
|
||||
const QString logDirPath =
|
||||
QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/log";
|
||||
const QDir logDir(logDirPath);
|
||||
if (!logDir.exists()) {
|
||||
logDir.mkpath(logDirPath);
|
||||
}
|
||||
g_file_path = logDir.filePath(logFileName);
|
||||
qInstallMessageHandler(messageHandler);
|
||||
qInfo() << "===================================================";
|
||||
qInfo() << "[AppName]" << g_app;
|
||||
qInfo() << "[AppVersion]" << APPLICATION_VERSION;
|
||||
qInfo() << "[AppPath]" << applicationPath;
|
||||
qInfo() << "[QtVersion]" << QT_VERSION_STR;
|
||||
#ifdef WIN32
|
||||
qInfo() << "[ProcessId]" << QString::number(_getpid());
|
||||
#else
|
||||
qInfo() << "[ProcessId]" << QString::number(getpid());
|
||||
#endif
|
||||
qInfo() << "[GitHashCode]" << COMMIT_HASH;
|
||||
qInfo() << "[DeviceInfo]";
|
||||
qInfo() << " [DeviceId]" << QSysInfo::machineUniqueId();
|
||||
qInfo() << " [Manufacturer]" << prettyProductInfoWrapper();
|
||||
qInfo() << " [CPU_ABI]" << QSysInfo::currentCpuArchitecture();
|
||||
qInfo() << "[LOG_LEVEL]" << g_logLevel;
|
||||
qInfo() << "[LOG_PATH]" << g_file_path;
|
||||
qInfo() << "===================================================";
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <QtCore/qstring.h>
|
||||
|
||||
namespace Log {
|
||||
QString prettyProductInfoWrapper();
|
||||
void setup(char *argv[], const QString &app, int level = 4);
|
||||
}
|
||||
@@ -0,0 +1,698 @@
|
||||
#include "Network.h"
|
||||
|
||||
#include <QUrlQuery>
|
||||
#include <QBuffer>
|
||||
#include <QHttpMultiPart>
|
||||
#include <QJsonDocument>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkDiskCache>
|
||||
#include <QQmlEngine>
|
||||
#include <QQmlContext>
|
||||
#include <QJSEngine>
|
||||
#include <QJsonArray>
|
||||
#include <QStandardPaths>
|
||||
#include <QThreadPool>
|
||||
#include <QDir>
|
||||
#include <QCryptographicHash>
|
||||
#include <QEventLoop>
|
||||
#include <QGuiApplication>
|
||||
#include <utility>
|
||||
|
||||
NetworkCallable::NetworkCallable(QObject *parent) : QObject{parent} {
|
||||
}
|
||||
|
||||
QString NetworkParams::method2String() const {
|
||||
switch (_method) {
|
||||
case METHOD_GET:
|
||||
return "GET";
|
||||
case METHOD_HEAD:
|
||||
return "HEAD";
|
||||
case METHOD_POST:
|
||||
return "POST";
|
||||
case METHOD_PUT:
|
||||
return "PUT";
|
||||
case METHOD_PATCH:
|
||||
return "PATCH";
|
||||
case METHOD_DELETE:
|
||||
return "DELETE";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
int NetworkParams::getTimeout() const {
|
||||
if (_timeout != -1) {
|
||||
return _timeout;
|
||||
}
|
||||
return Network::getInstance()->timeout();
|
||||
}
|
||||
|
||||
int NetworkParams::getRetry() const {
|
||||
if (_retry != -1) {
|
||||
return _retry;
|
||||
}
|
||||
return Network::getInstance()->retry();
|
||||
}
|
||||
|
||||
bool NetworkParams::getOpenLog() const {
|
||||
if (!_openLog.isNull()) {
|
||||
return _openLog.toBool();
|
||||
}
|
||||
return Network::getInstance()->openLog();
|
||||
}
|
||||
|
||||
FluDownloadParam::FluDownloadParam(QObject *parent) : QObject{parent} {
|
||||
}
|
||||
|
||||
FluDownloadParam::FluDownloadParam(QString destPath, bool append, QObject *parent)
|
||||
: QObject{parent} {
|
||||
this->_destPath = std::move(destPath);
|
||||
this->_append = append;
|
||||
}
|
||||
|
||||
NetworkParams::NetworkParams(QObject *parent) : QObject{parent} {
|
||||
_method = NetworkParams::Method::METHOD_GET;
|
||||
_type = NetworkParams::Type::TYPE_BODY;
|
||||
}
|
||||
|
||||
NetworkParams::NetworkParams(QString url, Type type, Method method, QObject *parent)
|
||||
: QObject{parent} {
|
||||
this->_method = method;
|
||||
this->_url = std::move(url);
|
||||
this->_type = type;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::add(const QString &key, const QVariant &val) {
|
||||
_paramMap.insert(key, val);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::addFile(const QString &key, const QVariant &val) {
|
||||
_fileMap.insert(key, val);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::addHeader(const QString &key, const QVariant &val) {
|
||||
_headerMap.insert(key, val);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::addQuery(const QString &key, const QVariant &val) {
|
||||
_queryMap.insert(key, val);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::setBody(QString val) {
|
||||
_body = std::move(val);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::setTimeout(int val) {
|
||||
_timeout = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::setRetry(int val) {
|
||||
_retry = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::setCacheMode(int val) {
|
||||
_cacheMode = val;
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::toDownload(QString destPath, bool append) {
|
||||
_downloadParam = new FluDownloadParam(std::move(destPath), append, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::bind(QObject *target) {
|
||||
_target = target;
|
||||
return this;
|
||||
}
|
||||
|
||||
NetworkParams *NetworkParams::openLog(QVariant val) {
|
||||
_openLog = std::move(val);
|
||||
return this;
|
||||
}
|
||||
|
||||
QString NetworkParams::buildCacheKey() const {
|
||||
QJsonObject obj;
|
||||
obj.insert("url", _url);
|
||||
obj.insert("method", method2String());
|
||||
obj.insert("body", _body);
|
||||
obj.insert("query", QJsonDocument::fromVariant(_queryMap).object());
|
||||
obj.insert("param", QJsonDocument::fromVariant(_paramMap).object());
|
||||
obj.insert("header", QJsonDocument::fromVariant(_headerMap).object());
|
||||
obj.insert("file", QJsonDocument::fromVariant(_fileMap).object());
|
||||
if (_downloadParam) {
|
||||
QJsonObject downObj;
|
||||
downObj.insert("destPath", _downloadParam->_destPath);
|
||||
downObj.insert("append", _downloadParam->_append);
|
||||
obj.insert("download", downObj);
|
||||
}
|
||||
QByteArray data = QJsonDocument(obj).toJson(QJsonDocument::Compact);
|
||||
return QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex();
|
||||
}
|
||||
|
||||
void NetworkParams::go(NetworkCallable *callable) {
|
||||
QJSValueList data;
|
||||
data << qjsEngine(callable)->newQObject(this);
|
||||
Network::getInstance()->_interceptor.call(data);
|
||||
if (_downloadParam) {
|
||||
Network::getInstance()->handleDownload(this, callable);
|
||||
} else {
|
||||
Network::getInstance()->handle(this, callable);
|
||||
}
|
||||
}
|
||||
|
||||
void Network::handle(NetworkParams *params, NetworkCallable *c) {
|
||||
QPointer<NetworkCallable> callable(c);
|
||||
QThreadPool::globalInstance()->start([=]() {
|
||||
if (!callable.isNull()) {
|
||||
callable->start();
|
||||
}
|
||||
QString cacheKey = params->buildCacheKey();
|
||||
if (params->_cacheMode == NetworkType::CacheMode::FirstCacheThenRequest &&
|
||||
cacheExists(cacheKey)) {
|
||||
if (!callable.isNull()) {
|
||||
callable->cache(readCache(cacheKey));
|
||||
}
|
||||
}
|
||||
if (params->_cacheMode == NetworkType::CacheMode::IfNoneCacheRequest &&
|
||||
cacheExists(cacheKey)) {
|
||||
if (!callable.isNull()) {
|
||||
callable->cache(readCache(cacheKey));
|
||||
callable->finish();
|
||||
params->deleteLater();
|
||||
}
|
||||
return;
|
||||
}
|
||||
QNetworkAccessManager manager;
|
||||
manager.setTransferTimeout(params->getTimeout());
|
||||
QEventLoop loop;
|
||||
connect(&manager, &QNetworkAccessManager::finished, &manager,
|
||||
[&loop](QNetworkReply *reply) { loop.quit(); });
|
||||
for (int i = 0; i <= params->getRetry() - 1; ++i) {
|
||||
QUrl url(params->_url);
|
||||
addQueryParam(&url, params->_queryMap);
|
||||
QNetworkRequest request(url);
|
||||
addHeaders(&request, params->_headerMap);
|
||||
QNetworkReply *reply;
|
||||
sendRequest(&manager, request, params, reply, i == 0, callable);
|
||||
if (!QPointer<QCoreApplication>(QGuiApplication::instance())) {
|
||||
reply->deleteLater();
|
||||
reply = nullptr;
|
||||
return;
|
||||
}
|
||||
auto abortCallable = [reply, &i, params] {
|
||||
if (reply) {
|
||||
i = params->getRetry();
|
||||
reply->abort();
|
||||
}
|
||||
};
|
||||
QMetaObject::Connection conn_destroyed = {};
|
||||
QMetaObject::Connection conn_quit = {};
|
||||
if (params->_target) {
|
||||
conn_destroyed =
|
||||
connect(params->_target, &QObject::destroyed, &manager, abortCallable);
|
||||
}
|
||||
conn_quit = connect(QGuiApplication::instance(), &QGuiApplication::aboutToQuit,
|
||||
&manager, abortCallable);
|
||||
loop.exec();
|
||||
if (conn_destroyed) {
|
||||
disconnect(conn_destroyed);
|
||||
}
|
||||
if (conn_quit) {
|
||||
disconnect(conn_quit);
|
||||
}
|
||||
QString response;
|
||||
if (params->_method == NetworkParams::METHOD_HEAD) {
|
||||
response = headerList2String(reply->rawHeaderPairs());
|
||||
} else {
|
||||
if (reply->isOpen()) {
|
||||
response = QString::fromUtf8(reply->readAll());
|
||||
}
|
||||
}
|
||||
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (httpStatus == 200) {
|
||||
if (!callable.isNull()) {
|
||||
if (params->_cacheMode != NetworkType::CacheMode::NoCache) {
|
||||
saveResponse(cacheKey, response);
|
||||
}
|
||||
callable->success(response);
|
||||
}
|
||||
printRequestEndLog(request, params, reply, response);
|
||||
break;
|
||||
} else {
|
||||
if (i == params->getRetry() - 1) {
|
||||
if (!callable.isNull()) {
|
||||
if (params->_cacheMode == NetworkType::CacheMode::RequestFailedReadCache &&
|
||||
cacheExists(cacheKey)) {
|
||||
if (!callable.isNull()) {
|
||||
callable->cache(readCache(cacheKey));
|
||||
}
|
||||
}
|
||||
callable->error(httpStatus, reply->errorString(), response);
|
||||
}
|
||||
printRequestEndLog(request, params, reply, response);
|
||||
}
|
||||
}
|
||||
reply->deleteLater();
|
||||
}
|
||||
params->deleteLater();
|
||||
if (!callable.isNull()) {
|
||||
callable->finish();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void Network::handleDownload(NetworkParams *params, NetworkCallable *c) {
|
||||
QPointer<NetworkCallable> callable(c);
|
||||
QThreadPool::globalInstance()->start([=]() {
|
||||
if (!callable.isNull()) {
|
||||
callable->start();
|
||||
}
|
||||
QString cacheKey = params->buildCacheKey();
|
||||
QUrl url(params->_url);
|
||||
QNetworkAccessManager manager;
|
||||
manager.setTransferTimeout(params->getTimeout());
|
||||
addQueryParam(&url, params->_queryMap);
|
||||
QNetworkRequest request(url);
|
||||
addHeaders(&request, params->_headerMap);
|
||||
QString cachePath = getCacheFilePath(cacheKey);
|
||||
QString destPath = params->_downloadParam->_destPath;
|
||||
auto *destFile = new QFile(destPath);
|
||||
auto *cacheFile = new QFile(cachePath);
|
||||
bool isOpen;
|
||||
qint64 seek;
|
||||
if (cacheFile->exists() && destFile->exists() && params->_downloadParam->_append) {
|
||||
QJsonObject cacheInfo = QJsonDocument::fromJson(readCache(cacheKey).toUtf8()).object();
|
||||
qint64 fileSize = qRound(cacheInfo.value("fileSize").toDouble());
|
||||
qint64 contentLength = qRound(cacheInfo.value("contentLength").toDouble());
|
||||
if (fileSize == contentLength && destFile->size() == contentLength) {
|
||||
if (!callable.isNull()) {
|
||||
callable->downloadProgress(fileSize, contentLength);
|
||||
callable->success(destPath);
|
||||
callable->finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (fileSize == destFile->size()) {
|
||||
request.setRawHeader("Range", QString("bytes=%1-").arg(fileSize).toUtf8());
|
||||
seek = fileSize;
|
||||
isOpen = destFile->open(QIODevice::WriteOnly | QIODevice::Append);
|
||||
} else {
|
||||
isOpen = destFile->open(QIODevice::WriteOnly | QIODevice::Truncate);
|
||||
}
|
||||
} else {
|
||||
isOpen = destFile->open(QIODevice::WriteOnly | QIODevice::Truncate);
|
||||
}
|
||||
if (!isOpen) {
|
||||
if (!callable.isNull()) {
|
||||
callable->error(-1, "device not open", "");
|
||||
callable->finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (params->_downloadParam->_append) {
|
||||
if (!cacheFile->open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
||||
if (!callable.isNull()) {
|
||||
callable->error(-1, "cache file device not open", "");
|
||||
callable->finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
QEventLoop loop;
|
||||
QNetworkReply *reply = manager.get(request);
|
||||
destFile->setParent(reply);
|
||||
cacheFile->setParent(reply);
|
||||
auto abortCallable = [reply] {
|
||||
if (reply) {
|
||||
reply->abort();
|
||||
}
|
||||
};
|
||||
connect(&manager, &QNetworkAccessManager::finished, &manager,
|
||||
[&loop](QNetworkReply *reply) { loop.quit(); });
|
||||
connect(QGuiApplication::instance(), &QGuiApplication::aboutToQuit, &manager,
|
||||
[&loop, reply]() { reply->abort(), loop.quit(); });
|
||||
QMetaObject::Connection conn_destroyed = {};
|
||||
QMetaObject::Connection conn_quit = {};
|
||||
if (params->_target) {
|
||||
conn_destroyed = connect(params->_target, &QObject::destroyed, &manager, abortCallable);
|
||||
}
|
||||
conn_quit = connect(QGuiApplication::instance(), &QGuiApplication::aboutToQuit, &manager,
|
||||
abortCallable);
|
||||
connect(reply, &QNetworkReply::readyRead, reply,
|
||||
[reply, seek, destFile, cacheFile, callable] {
|
||||
if (!reply || !destFile || reply->error() != QNetworkReply::NoError) {
|
||||
return;
|
||||
}
|
||||
QMap<QString, QVariant> downInfo;
|
||||
qint64 contentLength =
|
||||
reply->header(QNetworkRequest::ContentLengthHeader).toLongLong() + seek;
|
||||
downInfo.insert("contentLength", contentLength);
|
||||
QString eTag = reply->header(QNetworkRequest::ETagHeader).toString();
|
||||
downInfo.insert("eTag", eTag);
|
||||
destFile->write(reply->readAll());
|
||||
destFile->flush();
|
||||
downInfo.insert("fileSize", destFile->size());
|
||||
if (cacheFile->isOpen()) {
|
||||
cacheFile->resize(0);
|
||||
cacheFile->write(
|
||||
QJsonDocument::fromVariant(QVariant(downInfo)).toJson().toBase64());
|
||||
cacheFile->flush();
|
||||
}
|
||||
if (!callable.isNull()) {
|
||||
callable->downloadProgress(destFile->size(), contentLength);
|
||||
}
|
||||
});
|
||||
loop.exec();
|
||||
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (httpStatus == 200) {
|
||||
if (!callable.isNull()) {
|
||||
callable->success(destPath);
|
||||
}
|
||||
printRequestEndLog(request, params, reply, destPath);
|
||||
} else {
|
||||
if (!callable.isNull()) {
|
||||
callable->error(httpStatus, reply->errorString(), destPath);
|
||||
}
|
||||
printRequestEndLog(request, params, reply, destPath);
|
||||
}
|
||||
if (conn_destroyed) {
|
||||
disconnect(conn_destroyed);
|
||||
}
|
||||
if (conn_quit) {
|
||||
disconnect(conn_quit);
|
||||
}
|
||||
params->deleteLater();
|
||||
reply->deleteLater();
|
||||
if (!callable.isNull()) {
|
||||
callable->finish();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
QString Network::readCache(const QString &key) {
|
||||
auto filePath = getCacheFilePath(key);
|
||||
QString result;
|
||||
QFile file(filePath);
|
||||
if (!file.exists()) {
|
||||
return result;
|
||||
}
|
||||
if (file.open(QIODevice::ReadOnly)) {
|
||||
QTextStream stream(&file);
|
||||
result = QString(QByteArray::fromBase64(stream.readAll().toUtf8()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Network::cacheExists(const QString &key) {
|
||||
return QFile(getCacheFilePath(key)).exists();
|
||||
}
|
||||
|
||||
QString Network::getCacheFilePath(const QString &key) {
|
||||
QDir cacheDir(_cacheDir);
|
||||
if (!cacheDir.exists()) {
|
||||
cacheDir.mkpath(_cacheDir);
|
||||
}
|
||||
return cacheDir.absoluteFilePath(key);
|
||||
}
|
||||
|
||||
QString Network::headerList2String(const QList<QNetworkReply::RawHeaderPair> &data) {
|
||||
QJsonObject object;
|
||||
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
|
||||
object.insert(QString(it->first), QString(it->second));
|
||||
}
|
||||
return QJsonDocument(object).toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
QString Network::map2String(const QMap<QString, QVariant> &map) {
|
||||
QStringList parameters;
|
||||
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
|
||||
parameters << QString("%1=%2").arg(it.key(), it.value().toString());
|
||||
}
|
||||
return parameters.join(" ");
|
||||
}
|
||||
|
||||
void Network::sendRequest(QNetworkAccessManager *manager, QNetworkRequest request,
|
||||
NetworkParams *params, QNetworkReply *&reply, bool isFirst,
|
||||
const QPointer<NetworkCallable> &callable) {
|
||||
QByteArray verb = params->method2String().toUtf8();
|
||||
switch (params->_type) {
|
||||
case NetworkParams::TYPE_FORM: {
|
||||
bool isFormData = !params->_fileMap.isEmpty();
|
||||
if (isFormData) {
|
||||
auto *multiPart = new QHttpMultiPart();
|
||||
multiPart->setContentType(QHttpMultiPart::FormDataType);
|
||||
for (const auto &each : params->_paramMap.toStdMap()) {
|
||||
QHttpPart part;
|
||||
part.setHeader(QNetworkRequest::ContentDispositionHeader,
|
||||
QString("form-data; name=\"%1\"").arg(each.first));
|
||||
part.setBody(each.second.toByteArray());
|
||||
multiPart->append(part);
|
||||
}
|
||||
for (const auto &each : params->_fileMap.toStdMap()) {
|
||||
QString filePath = each.second.toString();
|
||||
QString name = each.first;
|
||||
auto *file = new QFile(filePath);
|
||||
QString fileName = QFileInfo(filePath).fileName();
|
||||
file->open(QIODevice::ReadOnly);
|
||||
file->setParent(multiPart);
|
||||
QHttpPart part;
|
||||
part.setHeader(
|
||||
QNetworkRequest::ContentDispositionHeader,
|
||||
QString(R"(form-data; name="%1"; filename="%2")").arg(name, fileName));
|
||||
part.setBodyDevice(file);
|
||||
multiPart->append(part);
|
||||
}
|
||||
reply = manager->sendCustomRequest(request, verb, multiPart);
|
||||
multiPart->setParent(reply);
|
||||
connect(reply, &QNetworkReply::uploadProgress, reply,
|
||||
[callable](qint64 bytesSent, qint64 bytesTotal) {
|
||||
if (!callable.isNull() && bytesSent != 0 && bytesTotal != 0) {
|
||||
Q_EMIT callable->uploadProgress(bytesSent, bytesTotal);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QString("application/x-www-form-urlencoded"));
|
||||
QString value;
|
||||
for (const auto &each : params->_paramMap.toStdMap()) {
|
||||
value += QString("%1=%2").arg(each.first, each.second.toString());
|
||||
value += "&";
|
||||
}
|
||||
if (!params->_paramMap.isEmpty()) {
|
||||
value.chop(1);
|
||||
}
|
||||
QByteArray data = value.toUtf8();
|
||||
reply = manager->sendCustomRequest(request, verb, data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case NetworkParams::TYPE_JSON: {
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QString("application/json;charset=utf-8"));
|
||||
QJsonObject json;
|
||||
for (const auto &each : params->_paramMap.toStdMap()) {
|
||||
json.insert(each.first, each.second.toJsonValue());
|
||||
}
|
||||
QByteArray data = QJsonDocument(json).toJson(QJsonDocument::Compact);
|
||||
reply = manager->sendCustomRequest(request, verb, data);
|
||||
break;
|
||||
}
|
||||
case NetworkParams::TYPE_JSONARRAY: {
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QString("application/json;charset=utf-8"));
|
||||
QJsonArray jsonArray;
|
||||
for (const auto &each : params->_paramMap.toStdMap()) {
|
||||
QJsonObject json;
|
||||
json.insert(each.first, each.second.toJsonValue());
|
||||
jsonArray.append(json);
|
||||
}
|
||||
QByteArray data = QJsonDocument(jsonArray).toJson(QJsonDocument::Compact);
|
||||
reply = manager->sendCustomRequest(request, params->method2String().toUtf8(), data);
|
||||
break;
|
||||
}
|
||||
case NetworkParams::TYPE_BODY: {
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QString("text/plain;charset=utf-8"));
|
||||
QByteArray data = params->_body.toUtf8();
|
||||
reply = manager->sendCustomRequest(request, verb, data);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
reply = manager->sendCustomRequest(request, verb);
|
||||
break;
|
||||
}
|
||||
if (isFirst) {
|
||||
printRequestStartLog(request, params);
|
||||
}
|
||||
}
|
||||
|
||||
void Network::printRequestStartLog(const QNetworkRequest &request, NetworkParams *params) {
|
||||
if (!params->getOpenLog()) {
|
||||
return;
|
||||
}
|
||||
qDebug() << "<------"
|
||||
<< qUtf8Printable(request.header(QNetworkRequest::UserAgentHeader).toString())
|
||||
<< "Request Start ------>";
|
||||
qDebug() << qUtf8Printable(QString::fromStdString("<%1>").arg(params->method2String()))
|
||||
<< qUtf8Printable(params->_url);
|
||||
auto contentType = request.header(QNetworkRequest::ContentTypeHeader).toString();
|
||||
if (!contentType.isEmpty()) {
|
||||
qDebug() << qUtf8Printable(
|
||||
QString::fromStdString("<Header> %1=%2").arg("Content-Type", contentType));
|
||||
}
|
||||
QList<QByteArray> headers = request.rawHeaderList();
|
||||
for (const QByteArray &header : headers) {
|
||||
qDebug() << qUtf8Printable(
|
||||
QString::fromStdString("<Header> %1=%2").arg(header, request.rawHeader(header)));
|
||||
}
|
||||
if (!params->_queryMap.isEmpty()) {
|
||||
qDebug() << "<Query>" << qUtf8Printable(map2String(params->_queryMap));
|
||||
}
|
||||
if (!params->_paramMap.isEmpty()) {
|
||||
qDebug() << "<Param>" << qUtf8Printable(map2String(params->_paramMap));
|
||||
}
|
||||
if (!params->_fileMap.isEmpty()) {
|
||||
qDebug() << "<File>" << qUtf8Printable(map2String(params->_fileMap));
|
||||
}
|
||||
if (!params->_body.isEmpty()) {
|
||||
qDebug() << "<Body>" << qUtf8Printable(params->_body);
|
||||
}
|
||||
}
|
||||
|
||||
void Network::printRequestEndLog(const QNetworkRequest &request, NetworkParams *params,
|
||||
QNetworkReply *&reply, const QString &response) {
|
||||
if (!params->getOpenLog()) {
|
||||
return;
|
||||
}
|
||||
qDebug() << "<------"
|
||||
<< qUtf8Printable(request.header(QNetworkRequest::UserAgentHeader).toString())
|
||||
<< "Request End ------>";
|
||||
qDebug() << qUtf8Printable(QString::fromStdString("<%1>").arg(params->method2String()))
|
||||
<< qUtf8Printable(params->_url);
|
||||
qDebug() << "<Result>" << qUtf8Printable(response);
|
||||
}
|
||||
|
||||
void Network::saveResponse(const QString &key, const QString &response) {
|
||||
QSharedPointer<QFile> file(new QFile(getCacheFilePath(key)));
|
||||
QIODevice::OpenMode mode = QIODevice::WriteOnly | QIODevice::Truncate;
|
||||
if (!file->open(mode)) {
|
||||
return;
|
||||
}
|
||||
file->write(response.toUtf8().toBase64());
|
||||
}
|
||||
|
||||
void Network::addHeaders(QNetworkRequest *request, const QMap<QString, QVariant> &headers) {
|
||||
request->setHeader(
|
||||
QNetworkRequest::UserAgentHeader,
|
||||
QString::fromStdString("Mozilla/5.0 %1/%2")
|
||||
.arg(QGuiApplication::applicationName(), QGuiApplication::applicationVersion()));
|
||||
QMapIterator<QString, QVariant> iter(headers);
|
||||
while (iter.hasNext()) {
|
||||
iter.next();
|
||||
request->setRawHeader(iter.key().toUtf8(), iter.value().toString().toUtf8());
|
||||
}
|
||||
}
|
||||
|
||||
void Network::addQueryParam(QUrl *url, const QMap<QString, QVariant> ¶ms) {
|
||||
QMapIterator<QString, QVariant> iter(params);
|
||||
QUrlQuery urlQuery(*url);
|
||||
while (iter.hasNext()) {
|
||||
iter.next();
|
||||
urlQuery.addQueryItem(iter.key(), iter.value().toString());
|
||||
}
|
||||
url->setQuery(urlQuery);
|
||||
}
|
||||
|
||||
Network::Network(QObject *parent) : QObject{parent} {
|
||||
_timeout = 5000;
|
||||
_retry = 3;
|
||||
_openLog = false;
|
||||
_cacheDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
|
||||
.append(QDir::separator())
|
||||
.append("network");
|
||||
}
|
||||
|
||||
NetworkParams *Network::get(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_NONE, NetworkParams::METHOD_GET, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::head(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_NONE, NetworkParams::METHOD_HEAD, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::postBody(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_BODY, NetworkParams::METHOD_POST, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::putBody(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_BODY, NetworkParams::METHOD_PUT, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::patchBody(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_BODY, NetworkParams::METHOD_PATCH, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::deleteBody(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_BODY, NetworkParams::METHOD_DELETE, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::postForm(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_FORM, NetworkParams::METHOD_POST, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::putForm(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_FORM, NetworkParams::METHOD_PUT, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::patchForm(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_FORM, NetworkParams::METHOD_PATCH, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::deleteForm(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_FORM, NetworkParams::METHOD_DELETE, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::postJson(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSON, NetworkParams::METHOD_POST, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::putJson(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSON, NetworkParams::METHOD_PUT, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::patchJson(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSON, NetworkParams::METHOD_PATCH, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::deleteJson(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSON, NetworkParams::METHOD_DELETE, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::postJsonArray(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSONARRAY, NetworkParams::METHOD_POST, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::putJsonArray(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSONARRAY, NetworkParams::METHOD_PUT, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::patchJsonArray(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSONARRAY, NetworkParams::METHOD_PATCH, this);
|
||||
}
|
||||
|
||||
NetworkParams *Network::deleteJsonArray(const QString &url) {
|
||||
return new NetworkParams(url, NetworkParams::TYPE_JSONARRAY, NetworkParams::METHOD_DELETE,
|
||||
this);
|
||||
}
|
||||
|
||||
void Network::setInterceptor(QJSValue interceptor) {
|
||||
this->_interceptor = std::move(interceptor);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QtQml/qqml.h>
|
||||
#include <QFile>
|
||||
#include <QJsonValue>
|
||||
#include <QJSValue>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include "src/stdafx.h"
|
||||
#include "src/singleton.h"
|
||||
|
||||
namespace NetworkType {
|
||||
Q_NAMESPACE
|
||||
enum CacheMode {
|
||||
NoCache = 0x0000,
|
||||
RequestFailedReadCache = 0x0001,
|
||||
IfNoneCacheRequest = 0x0002,
|
||||
FirstCacheThenRequest = 0x0004,
|
||||
};
|
||||
|
||||
Q_ENUM_NS(CacheMode)
|
||||
|
||||
QML_NAMED_ELEMENT(NetworkType)
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The NetworkCallable class
|
||||
*/
|
||||
class NetworkCallable : public QObject {
|
||||
Q_OBJECT
|
||||
QML_NAMED_ELEMENT(NetworkCallable)
|
||||
public:
|
||||
explicit NetworkCallable(QObject *parent = nullptr);
|
||||
|
||||
Q_SIGNAL void start();
|
||||
|
||||
Q_SIGNAL void finish();
|
||||
|
||||
Q_SIGNAL void error(int status, QString errorString, QString result);
|
||||
|
||||
Q_SIGNAL void success(QString result);
|
||||
|
||||
Q_SIGNAL void cache(QString result);
|
||||
|
||||
Q_SIGNAL void uploadProgress(qint64 sent, qint64 total);
|
||||
|
||||
Q_SIGNAL void downloadProgress(qint64 recv, qint64 total);
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The FluDownloadParam class
|
||||
*/
|
||||
class FluDownloadParam : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit FluDownloadParam(QObject *parent = nullptr);
|
||||
|
||||
FluDownloadParam(QString destPath, bool append, QObject *parent = nullptr);
|
||||
|
||||
public:
|
||||
QString _destPath;
|
||||
bool _append{};
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The NetworkParams class
|
||||
*/
|
||||
class NetworkParams : public QObject {
|
||||
Q_OBJECT
|
||||
QML_NAMED_ELEMENT(NetworkParams)
|
||||
public:
|
||||
enum Method { METHOD_GET, METHOD_HEAD, METHOD_POST, METHOD_PUT, METHOD_PATCH, METHOD_DELETE };
|
||||
enum Type { TYPE_NONE, TYPE_FORM, TYPE_JSON, TYPE_JSONARRAY, TYPE_BODY };
|
||||
|
||||
explicit NetworkParams(QObject *parent = nullptr);
|
||||
|
||||
NetworkParams(QString url, Type type, Method method, QObject *parent = nullptr);
|
||||
|
||||
Q_INVOKABLE NetworkParams *addQuery(const QString &key, const QVariant &val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *addHeader(const QString &key, const QVariant &val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *add(const QString &key, const QVariant &val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *addFile(const QString &key, const QVariant &val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *setBody(QString val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *setTimeout(int val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *setRetry(int val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *setCacheMode(int val);
|
||||
|
||||
Q_INVOKABLE NetworkParams *toDownload(QString destPath, bool append = false);
|
||||
|
||||
Q_INVOKABLE NetworkParams *bind(QObject *target);
|
||||
|
||||
Q_INVOKABLE NetworkParams *openLog(QVariant val);
|
||||
|
||||
Q_INVOKABLE void go(NetworkCallable *result);
|
||||
|
||||
QString buildCacheKey() const;
|
||||
|
||||
QString method2String() const;
|
||||
|
||||
int getTimeout() const;
|
||||
|
||||
int getRetry() const;
|
||||
|
||||
bool getOpenLog() const;
|
||||
|
||||
public:
|
||||
FluDownloadParam *_downloadParam = nullptr;
|
||||
QObject *_target = nullptr;
|
||||
Method _method;
|
||||
Type _type;
|
||||
QString _url;
|
||||
QString _body;
|
||||
QMap<QString, QVariant> _queryMap;
|
||||
QMap<QString, QVariant> _headerMap;
|
||||
QMap<QString, QVariant> _paramMap;
|
||||
QMap<QString, QVariant> _fileMap;
|
||||
int _timeout = -1;
|
||||
int _retry = -1;
|
||||
QVariant _openLog;
|
||||
int _cacheMode = NetworkType::CacheMode::NoCache;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The Network class
|
||||
*/
|
||||
class Network : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO(int, timeout)
|
||||
Q_PROPERTY_AUTO(int, retry)
|
||||
Q_PROPERTY_AUTO(QString, cacheDir)
|
||||
Q_PROPERTY_AUTO(bool, openLog)
|
||||
QML_NAMED_ELEMENT(Network)
|
||||
QML_SINGLETON
|
||||
|
||||
private:
|
||||
explicit Network(QObject *parent = nullptr);
|
||||
|
||||
public:
|
||||
SINGLETON(Network)
|
||||
|
||||
static Network *create(QQmlEngine *qmlEngine, QJSEngine *jsEngine) {
|
||||
return getInstance();
|
||||
}
|
||||
|
||||
Q_INVOKABLE NetworkParams *get(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *head(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *postBody(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *putBody(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *patchBody(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *deleteBody(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *postForm(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *putForm(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *patchForm(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *deleteForm(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *postJson(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *putJson(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *patchJson(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *deleteJson(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *postJsonArray(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *putJsonArray(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *patchJsonArray(const QString &url);
|
||||
|
||||
Q_INVOKABLE NetworkParams *deleteJsonArray(const QString &url);
|
||||
|
||||
Q_INVOKABLE void setInterceptor(QJSValue interceptor);
|
||||
|
||||
void handle(NetworkParams *params, NetworkCallable *result);
|
||||
|
||||
void handleDownload(NetworkParams *params, NetworkCallable *result);
|
||||
|
||||
private:
|
||||
static void sendRequest(QNetworkAccessManager *manager, QNetworkRequest request,
|
||||
NetworkParams *params, QNetworkReply *&reply, bool isFirst,
|
||||
const QPointer<NetworkCallable> &callable);
|
||||
|
||||
static void addQueryParam(QUrl *url, const QMap<QString, QVariant> ¶ms);
|
||||
|
||||
static void addHeaders(QNetworkRequest *request, const QMap<QString, QVariant> &headers);
|
||||
|
||||
void saveResponse(const QString &key, const QString &response);
|
||||
|
||||
QString readCache(const QString &key);
|
||||
|
||||
bool cacheExists(const QString &key);
|
||||
|
||||
QString getCacheFilePath(const QString &key);
|
||||
|
||||
static QString headerList2String(const QList<QNetworkReply::RawHeaderPair> &data);
|
||||
|
||||
static void printRequestStartLog(const QNetworkRequest &request, NetworkParams *params);
|
||||
|
||||
static void printRequestEndLog(const QNetworkRequest &request, NetworkParams *params,
|
||||
QNetworkReply *&reply, const QString &response);
|
||||
|
||||
static QString map2String(const QMap<QString, QVariant> &map);
|
||||
|
||||
public:
|
||||
QJSValue _interceptor;
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "SettingsHelper.h"
|
||||
|
||||
#include <QDataStream>
|
||||
#include <QStandardPaths>
|
||||
|
||||
SettingsHelper::SettingsHelper(QObject *parent) : QObject(parent) {
|
||||
}
|
||||
|
||||
SettingsHelper::~SettingsHelper() = default;
|
||||
|
||||
void SettingsHelper::save(const QString &key, QVariant val) {
|
||||
m_settings->setValue(key, val);
|
||||
}
|
||||
|
||||
|
||||
QVariant SettingsHelper::get(const QString &key, QVariant def) {
|
||||
QVariant data = m_settings->value(key);
|
||||
if (!data.isNull() && data.isValid()) {
|
||||
return data;
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
void SettingsHelper::init(char *argv[]) {
|
||||
QString applicationPath = QString::fromStdString(argv[0]);
|
||||
const QFileInfo fileInfo(applicationPath);
|
||||
const QString iniFileName = fileInfo.completeBaseName() + ".ini";
|
||||
const QString iniFilePath =
|
||||
QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/" + iniFileName;
|
||||
m_settings.reset(new QSettings(iniFilePath, QSettings::IniFormat));
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <QtCore/qobject.h>
|
||||
#include <QtQml/qqml.h>
|
||||
#include <QSettings>
|
||||
#include <QScopedPointer>
|
||||
#include <QFileInfo>
|
||||
#include <QCoreApplication>
|
||||
#include <QDir>
|
||||
#include "src/singleton.h"
|
||||
|
||||
class SettingsHelper : public QObject {
|
||||
Q_OBJECT
|
||||
private:
|
||||
explicit SettingsHelper(QObject *parent = nullptr);
|
||||
|
||||
public:
|
||||
SINGLETON(SettingsHelper)
|
||||
~SettingsHelper() override;
|
||||
void init(char *argv[]);
|
||||
Q_INVOKABLE void saveDarkMode(int darkModel) {
|
||||
save("darkMode", darkModel);
|
||||
}
|
||||
Q_INVOKABLE int getDarkMode() {
|
||||
return get("darkMode", QVariant(0)).toInt();
|
||||
}
|
||||
Q_INVOKABLE void saveUseSystemAppBar(bool useSystemAppBar) {
|
||||
save("useSystemAppBar", useSystemAppBar);
|
||||
}
|
||||
Q_INVOKABLE bool getUseSystemAppBar() {
|
||||
return get("useSystemAppBar", QVariant(false)).toBool();
|
||||
}
|
||||
Q_INVOKABLE void saveLanguage(const QString &language) {
|
||||
save("language", language);
|
||||
}
|
||||
Q_INVOKABLE QString getLanguage() {
|
||||
return get("language", QVariant("en_US")).toString();
|
||||
}
|
||||
|
||||
private:
|
||||
void save(const QString &key, QVariant val);
|
||||
QVariant get(const QString &key, QVariant def = {});
|
||||
|
||||
private:
|
||||
QScopedPointer<QSettings> m_settings;
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "TranslateHelper.h"
|
||||
|
||||
#include <QGuiApplication>
|
||||
#include <QQmlEngine>
|
||||
|
||||
#include "SettingsHelper.h"
|
||||
|
||||
[[maybe_unused]] TranslateHelper::TranslateHelper(QObject *parent) : QObject(parent) {
|
||||
_languages << "en_US";
|
||||
_languages << "zh_CN";
|
||||
_current = SettingsHelper::getInstance()->getLanguage();
|
||||
}
|
||||
|
||||
TranslateHelper::~TranslateHelper() = default;
|
||||
|
||||
void TranslateHelper::init(QQmlEngine *engine) {
|
||||
_engine = engine;
|
||||
_translator = new QTranslator(this);
|
||||
QGuiApplication::installTranslator(_translator);
|
||||
QString translatorPath = QGuiApplication::applicationDirPath() + "/i18n";
|
||||
if (_translator->load(
|
||||
QString::fromStdString("%1/example_%2.qm").arg(translatorPath, _current))) {
|
||||
_engine->retranslate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QtQml/qqml.h>
|
||||
#include <QTranslator>
|
||||
#include "src/singleton.h"
|
||||
#include "src/stdafx.h"
|
||||
|
||||
class TranslateHelper : public QObject {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY_AUTO(QString, current)
|
||||
Q_PROPERTY_READONLY_AUTO(QStringList, languages)
|
||||
private:
|
||||
[[maybe_unused]] explicit TranslateHelper(QObject *parent = nullptr);
|
||||
|
||||
public:
|
||||
SINGLETON(TranslateHelper)
|
||||
~TranslateHelper() override;
|
||||
void init(QQmlEngine *engine);
|
||||
|
||||
private:
|
||||
QQmlEngine *_engine = nullptr;
|
||||
QTranslator *_translator = nullptr;
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
#include <QtQml/qqmlextensionplugin.h>
|
||||
|
||||
#include <QApplication>
|
||||
#include <QDir>
|
||||
#include <QLoggingCategory>
|
||||
#include <QNetworkProxy>
|
||||
#include <QProcess>
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QQmlContext>
|
||||
#include <QQuickWindow>
|
||||
#include <QSslConfiguration>
|
||||
|
||||
#include "AppInfo.h"
|
||||
#include "Version.h"
|
||||
#include "helper/Log.h"
|
||||
#include "src/component/CircularReveal.h"
|
||||
#include "src/component/FileWatcher.h"
|
||||
#include "src/component/FpsItem.h"
|
||||
#include "src/component/OpenGLItem.h"
|
||||
#include "src/helper/InitializrHelper.h"
|
||||
#include "src/helper/Network.h"
|
||||
#include "src/helper/SettingsHelper.h"
|
||||
#include "src/helper/TranslateHelper.h"
|
||||
#include "src/component/DataGenerator.h"
|
||||
|
||||
#ifdef FLUENTUI_BUILD_STATIC_LIB
|
||||
# if (QT_VERSION > QT_VERSION_CHECK(6, 2, 0))
|
||||
Q_IMPORT_QML_PLUGIN(FluentUIPlugin)
|
||||
# endif
|
||||
# include <FluentUI.h>
|
||||
#endif
|
||||
|
||||
#ifdef WIN32
|
||||
# include "app_dmp.h"
|
||||
#endif
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
const char *uri = "example";
|
||||
int major = 1;
|
||||
int minor = 0;
|
||||
#ifdef WIN32
|
||||
::SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
|
||||
qputenv("QT_QPA_PLATFORM", "windows:darkmode=2");
|
||||
#endif
|
||||
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
|
||||
qputenv("QT_QUICK_CONTROLS_STYLE", "Basic");
|
||||
#else
|
||||
qputenv("QT_QUICK_CONTROLS_STYLE", "Default");
|
||||
#endif
|
||||
#ifdef Q_OS_LINUX
|
||||
// fix bug UOSv20 does not print logs
|
||||
qputenv("QT_LOGGING_RULES", "");
|
||||
// fix bug UOSv20 v-sync does not work
|
||||
qputenv("QSG_RENDER_LOOP", "basic");
|
||||
#endif
|
||||
QApplication::setOrganizationName("ZhuZiChu");
|
||||
QApplication::setOrganizationDomain("https://zhuzichu520.github.io");
|
||||
QApplication::setApplicationName("FluentUI");
|
||||
QApplication::setApplicationDisplayName("FluentUI Example");
|
||||
QApplication::setApplicationVersion(APPLICATION_VERSION);
|
||||
QApplication::setQuitOnLastWindowClosed(false);
|
||||
SettingsHelper::getInstance()->init(argv);
|
||||
Log::setup(argv, uri);
|
||||
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
|
||||
QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
|
||||
#endif
|
||||
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
|
||||
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
|
||||
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
|
||||
# if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
|
||||
QApplication::setHighDpiScaleFactorRoundingPolicy(
|
||||
Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
|
||||
# endif
|
||||
#endif
|
||||
QApplication app(argc, argv);
|
||||
//@uri example
|
||||
qmlRegisterType<CircularReveal>(uri, major, minor, "CircularReveal");
|
||||
qmlRegisterType<FileWatcher>(uri, major, minor, "FileWatcher");
|
||||
qmlRegisterType<FpsItem>(uri, major, minor, "FpsItem");
|
||||
qmlRegisterType<NetworkCallable>(uri, major, minor, "NetworkCallable");
|
||||
qmlRegisterType<NetworkParams>(uri, major, minor, "NetworkParams");
|
||||
qmlRegisterType<OpenGLItem>(uri, major, minor, "OpenGLItem");
|
||||
qmlRegisterUncreatableMetaObject(NetworkType::staticMetaObject, uri, major, minor,
|
||||
"NetworkType", "Access to enums & flags only");
|
||||
qmlRegisterType<DataGenerator>(uri, major, minor, "DataGenerator");
|
||||
|
||||
QQmlApplicationEngine engine;
|
||||
TranslateHelper::getInstance()->init(&engine);
|
||||
engine.rootContext()->setContextProperty("AppInfo", AppInfo::getInstance());
|
||||
engine.rootContext()->setContextProperty("SettingsHelper", SettingsHelper::getInstance());
|
||||
engine.rootContext()->setContextProperty("InitializrHelper", InitializrHelper::getInstance());
|
||||
engine.rootContext()->setContextProperty("TranslateHelper", TranslateHelper::getInstance());
|
||||
engine.rootContext()->setContextProperty("Network", Network::getInstance());
|
||||
#ifdef FLUENTUI_BUILD_STATIC_LIB
|
||||
FluentUI::registerTypes(&engine);
|
||||
#endif
|
||||
const QUrl url(QStringLiteral("qrc:/example/qml/App.qml"));
|
||||
QObject::connect(
|
||||
&engine, &QQmlApplicationEngine::objectCreated, &app,
|
||||
[url](QObject *obj, const QUrl &objUrl) {
|
||||
if (!obj && url == objUrl)
|
||||
QCoreApplication::exit(-1);
|
||||
},
|
||||
Qt::QueuedConnection);
|
||||
engine.load(url);
|
||||
const int exec = QApplication::exec();
|
||||
if (exec == 931) {
|
||||
QProcess::startDetached(qApp->applicationFilePath(), qApp->arguments());
|
||||
}
|
||||
return exec;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
/**
|
||||
* @brief The Singleton class
|
||||
*/
|
||||
template <typename T>
|
||||
class Singleton {
|
||||
public:
|
||||
static T *getInstance();
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
T *Singleton<T>::getInstance() {
|
||||
static T *instance = new T();
|
||||
return instance;
|
||||
}
|
||||
|
||||
#define SINGLETON(Class) \
|
||||
private: \
|
||||
friend class Singleton<Class>; \
|
||||
\
|
||||
public: \
|
||||
static Class *getInstance() { \
|
||||
return Singleton<Class>::getInstance(); \
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#define Q_PROPERTY_AUTO_P(TYPE, M) \
|
||||
Q_PROPERTY(TYPE M MEMBER _##M NOTIFY M##Changed) \
|
||||
public: \
|
||||
Q_SIGNAL void M##Changed(); \
|
||||
void M(TYPE in_##M) { \
|
||||
_##M = in_##M; \
|
||||
Q_EMIT M##Changed(); \
|
||||
} \
|
||||
TYPE M() { \
|
||||
return _##M; \
|
||||
} \
|
||||
\
|
||||
private: \
|
||||
TYPE _##M;
|
||||
|
||||
#define Q_PROPERTY_AUTO(TYPE, M) \
|
||||
Q_PROPERTY(TYPE M MEMBER _##M NOTIFY M##Changed) \
|
||||
public: \
|
||||
Q_SIGNAL void M##Changed(); \
|
||||
void M(const TYPE &in_##M) { \
|
||||
_##M = in_##M; \
|
||||
Q_EMIT M##Changed(); \
|
||||
} \
|
||||
TYPE M() { \
|
||||
return _##M; \
|
||||
} \
|
||||
\
|
||||
private: \
|
||||
TYPE _##M;
|
||||
|
||||
|
||||
#define Q_PROPERTY_READONLY_AUTO(TYPE, M) \
|
||||
Q_PROPERTY(TYPE M READ M NOTIFY M##Changed FINAL) \
|
||||
public: \
|
||||
Q_SIGNAL void M##Changed(); \
|
||||
void M(const TYPE &in_##M) { \
|
||||
_##M = in_##M; \
|
||||
Q_EMIT M##Changed(); \
|
||||
} \
|
||||
TYPE M() { \
|
||||
return _##M; \
|
||||
} \
|
||||
\
|
||||
private: \
|
||||
TYPE _##M;
|
||||
Reference in New Issue
Block a user