CmvrControlStation/src/applicationsettings.cpp

245 lines
12 KiB
C++
Raw Normal View History

#include "applicationsettings.h"
#include "applicationstyle.h"
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFontComboBox>
#include <QFormLayout>
#include <QJsonDocument>
#include <QLabel>
#include <QPushButton>
#include <QSaveFile>
#include <QSpinBox>
#include <QTabWidget>
#include <QVBoxLayout>
ApplicationSettings::ApplicationSettings(const QString &path)
: m_path(path.isEmpty() ? QDir(QCoreApplication::applicationDirPath()).filePath(
QStringLiteral("data/application_settings.json")) : path)
{
QFile file(m_path);
if (!file.exists()) return;
if (!file.open(QIODevice::ReadOnly)) {
m_loadError = file.errorString();
return;
}
QJsonParseError error;
const QJsonDocument document = QJsonDocument::fromJson(file.readAll(), &error);
if (error.error != QJsonParseError::NoError || !document.isObject()) {
m_loadError = QStringLiteral("设置文件格式错误,已使用默认设置;原文件已保留。");
return;
}
m_document = document.object();
const QJsonObject appearance = m_document.value("appearance").toObject();
const QString family = appearance.value("fontFamily").toString().trimmed();
if (!family.isEmpty()) m_options.fontFamily = family;
m_options.fontPixels = qBound(11, appearance.value("fontPixels").toInt(13), 18);
const QJsonObject arm = m_document.value("arm").toObject();
m_options.armModelPreview = arm.value("modelPreview").toBool(false);
const QJsonObject window = m_document.value("window").toObject();
m_options.rememberWindow = window.value("rememberGeometry").toBool(true);
m_options.startMaximized = window.value("startMaximized").toBool(true);
const int page = window.value("startupPage").toInt(0);
m_options.startupPage = (page == 0 || page == 1 || page == 2 || page == 11 || page == 16)
? page : 0;
const QJsonObject log = m_document.value("log").toObject();
m_options.logMaximumLines = qBound(500, log.value("maximumLines").toInt(3000), 20000);
m_options.logAutoScroll = log.value("autoScroll").toBool(true);
}
ApplicationSettings &ApplicationSettings::instance()
{
static ApplicationSettings settings;
return settings;
}
QByteArray ApplicationSettings::windowGeometry() const
{
return QByteArray::fromBase64(m_document.value("window").toObject()
.value("geometry").toString().toLatin1());
}
bool ApplicationSettings::write(const QJsonObject &document, QString *error)
{
if (!QDir().mkpath(QFileInfo(m_path).absolutePath())) {
if (error) *error = QStringLiteral("无法创建设置目录:%1").arg(QFileInfo(m_path).absolutePath());
return false;
}
QSaveFile file(m_path);
const QByteArray data = QJsonDocument(document).toJson(QJsonDocument::Indented);
if (!file.open(QIODevice::WriteOnly) || file.write(data) != data.size() || !file.commit()) {
if (error) *error = QStringLiteral("设置保存失败:%1").arg(file.errorString());
return false;
}
m_document = document;
m_loadError.clear();
return true;
}
bool ApplicationSettings::save(const ApplicationOptions &options, QString *error)
{
QJsonObject document = m_document;
QJsonObject appearance = document.value("appearance").toObject();
appearance.insert("fontFamily", options.fontFamily);
appearance.insert("fontPixels", qBound(11, options.fontPixels, 18));
document.insert("appearance", appearance);
QJsonObject arm = document.value("arm").toObject();
arm.insert("modelPreview", options.armModelPreview);
document.insert("arm", arm);
QJsonObject window = document.value("window").toObject();
window.insert("rememberGeometry", options.rememberWindow);
window.insert("startMaximized", options.startMaximized);
window.insert("startupPage", options.startupPage);
document.insert("window", window);
QJsonObject log = document.value("log").toObject();
log.insert("maximumLines", qBound(500, options.logMaximumLines, 20000));
log.insert("autoScroll", options.logAutoScroll);
document.insert("log", log);
document.insert("version", 1);
if (!write(document, error)) return false;
m_options = options;
m_options.fontPixels = appearance.value("fontPixels").toInt();
m_options.logMaximumLines = log.value("maximumLines").toInt();
return true;
}
bool ApplicationSettings::saveWindowGeometry(const QByteArray &geometry, QString *error)
{
// Automatic geometry persistence must not replace a damaged settings file.
if (!m_options.rememberWindow || !m_loadError.isEmpty()) return true;
QJsonObject document = m_document;
QJsonObject window = document.value("window").toObject();
window.insert("geometry", QString::fromLatin1(geometry.toBase64()));
document.insert("window", window);
return write(document, error);
}
void showApplicationSettings(QWidget *parent, const std::function<void()> &applied)
{
auto &settings = ApplicationSettings::instance();
const ApplicationOptions original = settings.options();
QDialog dialog(parent);
dialog.setWindowTitle(QStringLiteral("软件设置"));
dialog.setObjectName(QStringLiteral("applicationSettingsDialog"));
dialog.setWindowModality(Qt::WindowModal);
dialog.resize(660, 540);
dialog.setMinimumSize(580, 480);
auto *layout = new QVBoxLayout(&dialog);
layout->setContentsMargins(22, 20, 22, 20);
layout->setSpacing(16);
auto *intro = new QLabel(QStringLiteral("定制显示与启动行为"), &dialog);
intro->setObjectName(QStringLiteral("sectionTitle"));
layout->addWidget(intro);
auto *tabs = new QTabWidget(&dialog);
tabs->setObjectName(QStringLiteral("settingsTabs"));
auto addPage = [&](const QString &title) {
auto *page = new QWidget(tabs);
auto *form = new QFormLayout(page);
form->setContentsMargins(18, 22, 18, 18);
form->setSpacing(18);
form->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
tabs->addTab(page, title);
return form;
};
auto *appearance = addPage(QStringLiteral("外观"));
auto *family = new QFontComboBox(&dialog);
family->setObjectName(QStringLiteral("settingsFontFamily"));
auto *pixels = new QSpinBox(&dialog);
pixels->setRange(11, 18);
pixels->setSuffix(QStringLiteral(" px"));
appearance->addRow(QStringLiteral("界面字体"), family);
appearance->addRow(QStringLiteral("基础字号"), pixels);
auto *sample = new QLabel(QStringLiteral("CMVR 控制台 · 关节位置 123.456°"), &dialog);
sample->setObjectName(QStringLiteral("settingsFontSample"));
sample->setWordWrap(true);
appearance->addRow(QStringLiteral("字体预览"), sample);
auto previewFont = [=]() {
QString name = family->currentFont().family();
name.remove(QLatin1Char('"')); name.remove(QLatin1Char('\\'));
sample->setStyleSheet(QStringLiteral("QLabel#settingsFontSample { font-family: \"%1\"; font-size: %2px; }")
.arg(name).arg(pixels->value()));
};
QObject::connect(family, &QFontComboBox::currentFontChanged, &dialog, [=](const QFont &) { previewFont(); });
QObject::connect(pixels, QOverload<int>::of(&QSpinBox::valueChanged), &dialog, [=](int) { previewFont(); });
auto *startup = addPage(QStringLiteral("启动与机械臂"));
auto *model = new QCheckBox(QStringLiteral("加载机械臂三维模型预览"), &dialog);
model->setObjectName(QStringLiteral("settingsArmModelPreview"));
startup->addRow(QStringLiteral("模型预览"), model);
auto *modelHint = new QLabel(QStringLiteral("重启程序后生效。默认关闭;开启后使用 Qt3D 加载模型。\n当前工具链曾出现模型加载闪退,建议确认运行环境兼容后开启。"), &dialog);
modelHint->setWordWrap(true);
modelHint->setObjectName(QStringLiteral("mutedLabel"));
startup->addRow(QString(), modelHint);
auto *maximized = new QCheckBox(QStringLiteral("启动时最大化"), &dialog);
auto *remember = new QCheckBox(QStringLiteral("记住窗口大小和位置"), &dialog);
auto *page = new QComboBox(&dialog);
page->addItem(QStringLiteral("系统概览"), 0);
page->addItem(QStringLiteral("设备管理"), 11);
page->addItem(QStringLiteral("机械臂"), 1);
page->addItem(QStringLiteral("相机"), 2);
page->addItem(QStringLiteral("任务编排"), 16);
startup->addRow(QStringLiteral("启动页面"), page);
startup->addRow(QStringLiteral("窗口"), maximized);
startup->addRow(QString(), remember);
auto *logs = addPage(QStringLiteral("日志与数据"));
auto *maximum = new QSpinBox(&dialog);
maximum->setRange(500, 20000);
maximum->setSingleStep(500);
maximum->setSuffix(QStringLiteral(" 行"));
auto *scroll = new QCheckBox(QStringLiteral("新日志到达时滚动到底部"), &dialog);
logs->addRow(QStringLiteral("日志保留上限"), maximum);
logs->addRow(QStringLiteral("自动滚动"), scroll);
auto *dataHint = new QLabel(QStringLiteral("软件设置与任务编排、机械臂点位分别保存。\n修改设置不会清除已有点位、任务或连接信息。"), &dialog);
dataHint->setWordWrap(true);
dataHint->setObjectName(QStringLiteral("mutedLabel"));
logs->addRow(dataHint);
layout->addWidget(tabs, 1);
auto fill = [&](const ApplicationOptions &options) {
family->setCurrentFont(QFont(options.fontFamily)); pixels->setValue(options.fontPixels);
model->setChecked(options.armModelPreview); maximized->setChecked(options.startMaximized);
remember->setChecked(options.rememberWindow);
page->setCurrentIndex(qMax(0, page->findData(options.startupPage)));
maximum->setValue(options.logMaximumLines); scroll->setChecked(options.logAutoScroll);
previewFont();
};
fill(original);
auto *path = new QLabel(QStringLiteral("设置文件:%1").arg(QDir::toNativeSeparators(settings.filePath())), &dialog);
path->setObjectName(QStringLiteral("mutedLabel")); path->setWordWrap(true);
path->setTextInteractionFlags(Qt::TextSelectableByMouse);
layout->addWidget(path);
auto *feedback = new QLabel(settings.loadError(), &dialog);
feedback->setWordWrap(true);
feedback->setObjectName(QStringLiteral("settingsFeedback"));
layout->addWidget(feedback);
auto *buttons = new QDialogButtonBox(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Save | QDialogButtonBox::Cancel, &dialog);
buttons->button(QDialogButtonBox::RestoreDefaults)->setText(QStringLiteral("恢复默认"));
buttons->button(QDialogButtonBox::Save)->setText(QStringLiteral("保存设置"));
buttons->button(QDialogButtonBox::Save)->setObjectName(QStringLiteral("primaryButton"));
buttons->button(QDialogButtonBox::Cancel)->setText(QStringLiteral("取消"));
QObject::connect(buttons->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, &dialog,
[&]() { fill(ApplicationOptions()); });
QObject::connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
QObject::connect(buttons, &QDialogButtonBox::accepted, &dialog, [&]() {
ApplicationOptions options;
options.fontFamily = family->currentFont().family(); options.fontPixels = pixels->value();
options.armModelPreview = model->isChecked(); options.startMaximized = maximized->isChecked();
options.rememberWindow = remember->isChecked(); options.startupPage = page->currentData().toInt();
options.logMaximumLines = maximum->value(); options.logAutoScroll = scroll->isChecked();
QString error;
if (!settings.save(options, &error)) { feedback->setText(error); return; }
ApplicationStyle::apply();
if (applied) applied();
dialog.accept();
});
layout->addWidget(buttons);
dialog.exec();
}