Skip to content

Commit

Permalink
全局配置文件存储在版本号子文件夹中 (#872)
Browse files Browse the repository at this point in the history
* feat: 全局配置文件存储在版本号子文件夹中

* chore: 删除无用的翻译资源

* fix: 修复一个读取旧配置的错误
  • Loading branch information
Blinue authored Apr 3, 2024
1 parent 2923586 commit cd7f10b
Show file tree
Hide file tree
Showing 20 changed files with 80 additions and 351 deletions.
144 changes: 76 additions & 68 deletions src/Magpie.App/AppSettings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ using namespace ::Magpie::Core;

namespace winrt::Magpie::App {

static constexpr uint32_t SETTINGS_VERSION = 2;
static constexpr uint32_t CONFIG_VERSION = 2;

_AppSettingsData::_AppSettingsData() {}

Expand Down Expand Up @@ -213,13 +213,15 @@ bool AppSettings::Initialize() noexcept {
Logger& logger = Logger::Get();

// 若程序所在目录存在配置文件则为便携模式
_isPortableMode = Win32Utils::FileExists(
StrUtils::Concat(CommonSharedConstants::CONFIG_DIR, CommonSharedConstants::CONFIG_NAME).c_str());
_UpdateConfigPath();
_isPortableMode = Win32Utils::FileExists(StrUtils::Concat(
CommonSharedConstants::CONFIG_DIR, CommonSharedConstants::CONFIG_FILENAME).c_str());

std::wstring existingConfigPath;
_UpdateConfigPath(&existingConfigPath);

logger.Info(StrUtils::Concat("便携模式:", _isPortableMode ? "" : ""));

if (!Win32Utils::FileExists(_configPath.c_str())) {
if (existingConfigPath.empty()) {
logger.Info("不存在配置文件");
_SetDefaultScalingModes();
_SetDefaultShortcuts();
Expand All @@ -230,13 +232,14 @@ bool AppSettings::Initialize() noexcept {
// 此时 ResourceLoader 使用“首选语言”

std::string configText;
if (!Win32Utils::ReadTextFile(_configPath.c_str(), configText)) {
if (!Win32Utils::ReadTextFile(existingConfigPath.c_str(), configText)) {
logger.Error("读取配置文件失败");
ResourceLoader resourceLoader =
ResourceLoader::GetForCurrentView(CommonSharedConstants::APP_RESOURCE_MAP_ID);
hstring title = resourceLoader.GetString(L"AppSettings_ErrorDialog_ReadFailed");
hstring content = resourceLoader.GetString(L"AppSettings_ErrorDialog_ConfigLocation");
ShowErrorMessage(title.c_str(), fmt::format(fmt::runtime(std::wstring_view(content)), _configPath).c_str());
ShowErrorMessage(title.c_str(),
fmt::format(fmt::runtime(std::wstring_view(content)), existingConfigPath).c_str());
return false;
}

Expand All @@ -256,7 +259,8 @@ bool AppSettings::Initialize() noexcept {
ResourceLoader::GetForCurrentView(CommonSharedConstants::APP_RESOURCE_MAP_ID);
hstring title = resourceLoader.GetString(L"AppSettings_ErrorDialog_NotValidJson");
hstring content = resourceLoader.GetString(L"AppSettings_ErrorDialog_ConfigLocation");
ShowErrorMessage(title.c_str(), fmt::format(fmt::runtime(std::wstring_view(content)), _configPath).c_str());
ShowErrorMessage(title.c_str(),
fmt::format(fmt::runtime(std::wstring_view(content)), existingConfigPath).c_str());
return false;
}

Expand All @@ -266,53 +270,14 @@ bool AppSettings::Initialize() noexcept {
ResourceLoader::GetForCurrentView(CommonSharedConstants::APP_RESOURCE_MAP_ID);
hstring title = resourceLoader.GetString(L"AppSettings_ErrorDialog_ParseFailed");
hstring content = resourceLoader.GetString(L"AppSettings_ErrorDialog_ConfigLocation");
ShowErrorMessage(title.c_str(), fmt::format(fmt::runtime(std::wstring_view(content)), _configPath).c_str());
ShowErrorMessage(title.c_str(),
fmt::format(fmt::runtime(std::wstring_view(content)), existingConfigPath).c_str());
return false;
}

auto root = ((const rapidjson::Document&)doc).GetObj();

uint32_t settingsVersion = 0;
// 不存在 version 字段则视为 0
JsonHelper::ReadUInt(root, "version", settingsVersion);

if (settingsVersion > SETTINGS_VERSION) {
Logger::Get().Warn("未知的配置文件版本");

ResourceLoader resourceLoader =
ResourceLoader::GetForCurrentView(CommonSharedConstants::APP_RESOURCE_MAP_ID);
if (_isPortableMode) {
hstring contentStr = resourceLoader.GetString(
L"AppSettings_PortableModeUnkownConfiguration_Content");
hstring continueStr = resourceLoader.GetString(
L"AppSettings_PortableModeUnkownConfiguration_Continue");
hstring exitStr = resourceLoader.GetString(
L"AppSettings_PortableModeUnkownConfiguration_Exit");
if (!ShowOkCancelWarningMessage(nullptr,
contentStr.c_str(), continueStr.c_str(), exitStr.c_str())
) {
return false;
}
} else {
hstring contentStr = resourceLoader.GetString(
L"AppSettings_UnkownConfiguration_Content");
hstring continueStr = resourceLoader.GetString(
L"AppSettings_UnkownConfiguration_Continue");
hstring enablePortableModeStr = resourceLoader.GetString(
L"AppSettings_UnkownConfiguration_EnablePortableMode");
if (!ShowOkCancelWarningMessage(nullptr,
contentStr.c_str(), continueStr.c_str(), enablePortableModeStr.c_str())
) {
IsPortableMode(true);
_SetDefaultScalingModes();
_SetDefaultShortcuts();
SaveAsync();
return true;
}
}
}

_LoadSettings(root, settingsVersion);
_LoadSettings(root);

if (_SetDefaultShortcuts()) {
SaveAsync();
Expand Down Expand Up @@ -343,7 +308,7 @@ void AppSettings::IsPortableMode(bool value) noexcept {
if (!value) {
// 关闭便携模式需删除本地配置文件
// 不关心是否成功
DeleteFile(StrUtils::Concat(_configDir, CommonSharedConstants::CONFIG_NAME).c_str());
DeleteFile(StrUtils::Concat(_configDir, CommonSharedConstants::CONFIG_FILENAME).c_str());
}

Logger::Get().Info(value ? "已开启便携模式" : "已关闭便携模式");
Expand Down Expand Up @@ -486,9 +451,6 @@ bool AppSettings::_Save(const _AppSettingsData& data) noexcept {
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(json);
writer.StartObject();

writer.Key("version");
writer.Uint(SETTINGS_VERSION);

writer.Key("language");
if (_language < 0) {
writer.String("");
Expand Down Expand Up @@ -582,7 +544,7 @@ bool AppSettings::_Save(const _AppSettingsData& data) noexcept {
}

// 永远不会失败,遇到不合法的配置项时静默忽略
void AppSettings::_LoadSettings(const rapidjson::GenericObject<true, rapidjson::Value>& root, uint32_t /*version*/) noexcept {
void AppSettings::_LoadSettings(const rapidjson::GenericObject<true, rapidjson::Value>& root) noexcept {
{
std::wstring language;
JsonHelper::ReadString(root, "language", language);
Expand Down Expand Up @@ -697,7 +659,7 @@ void AppSettings::_LoadSettings(const rapidjson::GenericObject<true, rapidjson::
// v0.10.0-preview1 使用 alwaysRunAsElevated
JsonHelper::ReadBool(root, "alwaysRunAsElevated", _isAlwaysRunAsAdmin);
}
if (!JsonHelper::ReadBool(root, "showNotifyIcon", _isShowNotifyIcon)) {
if (!JsonHelper::ReadBool(root, "showNotifyIcon", _isShowNotifyIcon, true)) {
// v0.10 使用 showTrayIcon
JsonHelper::ReadBool(root, "showTrayIcon", _isShowNotifyIcon);
}
Expand Down Expand Up @@ -991,33 +953,79 @@ void AppSettings::_SetDefaultScalingModes() noexcept {
_defaultProfile.scalingMode = 0;
}

void AppSettings::_UpdateConfigPath() noexcept {
static std::wstring FindOldConfig(const wchar_t* localAppDataDir) noexcept {
for (uint32_t version = CONFIG_VERSION - 1; version >= 2; --version) {
std::wstring oldConfigPath = fmt::format(
L"{}\\Magpie\\{}v{}\\{}",
localAppDataDir,
CommonSharedConstants::CONFIG_DIR,
version,
CommonSharedConstants::CONFIG_FILENAME
);

if (Win32Utils::FileExists(oldConfigPath.c_str())) {
return oldConfigPath;
}
}

// v1 版本的配置文件不在子目录中
std::wstring v1ConfigPath = StrUtils::Concat(
localAppDataDir,
L"\\Magpie\\",
CommonSharedConstants::CONFIG_DIR,
CommonSharedConstants::CONFIG_FILENAME
);

if (Win32Utils::FileExists(v1ConfigPath.c_str())) {
return v1ConfigPath;
}

return {};
}

void AppSettings::_UpdateConfigPath(std::wstring* existingConfigPath) noexcept {
if (_isPortableMode) {
wchar_t curDir[MAX_PATH];
GetCurrentDirectory(MAX_PATH, curDir);

_configDir = curDir;
if (_configDir.back() != L'\\') {
_configDir.push_back(L'\\');
_configDir = StrUtils::Concat(curDir, L"\\", CommonSharedConstants::CONFIG_DIR);
_configPath = _configDir + CommonSharedConstants::CONFIG_FILENAME;

if (existingConfigPath) {
if (Win32Utils::FileExists(_configPath.c_str())) {
*existingConfigPath = _configPath;
}
}
_configDir += CommonSharedConstants::CONFIG_DIR;
} else {
wchar_t localAppDataDir[MAX_PATH];
HRESULT hr = SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, localAppDataDir);
if (SUCCEEDED(hr)) {
_configDir = StrUtils::Concat(
localAppDataDir,
localAppDataDir[StrUtils::StrLen(localAppDataDir) - 1] == L'\\' ? L"Magpie\\" : L"\\Magpie\\",
CommonSharedConstants::CONFIG_DIR
);
_configDir = fmt::format(L"{}\\Magpie\\{}v{}\\",
localAppDataDir, CommonSharedConstants::CONFIG_DIR, CONFIG_VERSION);
_configPath = _configDir + CommonSharedConstants::CONFIG_FILENAME;

if (existingConfigPath) {
if (Win32Utils::FileExists(_configPath.c_str())) {
*existingConfigPath = _configPath;
} else {
// 查找旧版本配置文件
*existingConfigPath = FindOldConfig(localAppDataDir);
}
}
} else {
Logger::Get().ComError("SHGetFolderPath 失败", hr);

_configDir = CommonSharedConstants::CONFIG_DIR;
_configPath = _configDir + CommonSharedConstants::CONFIG_FILENAME;

if (existingConfigPath) {
if (Win32Utils::FileExists(_configPath.c_str())) {
*existingConfigPath = _configPath;
}
}
}
}

_configPath = _configDir + CommonSharedConstants::CONFIG_NAME;

// 确保 ConfigDir 存在
Win32Utils::CreateDir(_configDir.c_str(), true);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Magpie.App/AppSettings.h
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ class AppSettings : private _AppSettingsData {
void _UpdateWindowPlacement() noexcept;
bool _Save(const _AppSettingsData& data) noexcept;

void _LoadSettings(const rapidjson::GenericObject<true, rapidjson::Value>& root, uint32_t version) noexcept;
void _LoadSettings(const rapidjson::GenericObject<true, rapidjson::Value>& root) noexcept;
bool _LoadProfile(
const rapidjson::GenericObject<true, rapidjson::Value>& profileObj,
Profile& profile,
Expand All @@ -391,7 +391,7 @@ class AppSettings : private _AppSettingsData {
bool _SetDefaultShortcuts() noexcept;
void _SetDefaultScalingModes() noexcept;

void _UpdateConfigPath() noexcept;
void _UpdateConfigPath(std::wstring* existingConfigPath = nullptr) noexcept;

// 用于同步保存
Win32Utils::SRWMutex _saveMutex;
Expand Down
18 changes: 0 additions & 18 deletions src/Magpie.App/Resources.language-de.resw
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,6 @@
<data name="AppSettings_Dialog_Warning" xml:space="preserve">
<value>Warnung</value>
</data>
<data name="AppSettings_UnkownConfiguration_Continue" xml:space="preserve">
<value>Fortfahren</value>
</data>
<data name="About_Version_UpdateCard_ReleaseNotes.Content" xml:space="preserve">
<value>Versionshinweise</value>
</data>
Expand All @@ -283,18 +280,6 @@
<data name="About_DeveloperModeEnabled" xml:space="preserve">
<value>Entwicklermodus ist aktiviert.</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Content" xml:space="preserve">
<value>Die lokale Konfigurationsdatei stammt von einer unbekannten Version und wird möglicherweise nicht korrekt geparst.</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Continue" xml:space="preserve">
<value>Fortfahren</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Exit" xml:space="preserve">
<value>Schließen</value>
</data>
<data name="AppSettings_UnkownConfiguration_Content" xml:space="preserve">
<value>Die globale Konfigurationsdatei stammt von einer unbekannten Version und wird möglicherweise nicht korrekt geparst.</value>
</data>
<data name="Profile_Cursor_DrawCursor_ScalingFactor.Header" xml:space="preserve">
<value>Skalierungsfaktor</value>
</data>
Expand Down Expand Up @@ -544,9 +529,6 @@
<data name="Profile_Cursor_DrawCursor_ScalingFactor_Custom.Content" xml:space="preserve">
<value>Benutzerdefiniert</value>
</data>
<data name="AppSettings_UnkownConfiguration_EnablePortableMode" xml:space="preserve">
<value>Portable mode Aktivieren</value>
</data>
<data name="Profile_SourceWindow_CaptureTitleBar.Description" xml:space="preserve">
<value>Beschränkt auf Grafikerfassung und Desktopduplikation</value>
</data>
Expand Down
18 changes: 0 additions & 18 deletions src/Magpie.App/Resources.language-en-US.resw
Original file line number Diff line number Diff line change
Expand Up @@ -669,24 +669,6 @@
<data name="AppSettings_Dialog_Warning" xml:space="preserve">
<value>Warning</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Content" xml:space="preserve">
<value>The local configuration file comes from an unknown version and may not be parsed correctly.</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Continue" xml:space="preserve">
<value>Continue</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Exit" xml:space="preserve">
<value>Exit</value>
</data>
<data name="AppSettings_UnkownConfiguration_Content" xml:space="preserve">
<value>The global configuration file comes from an unknown version and may not be parsed correctly.</value>
</data>
<data name="AppSettings_UnkownConfiguration_Continue" xml:space="preserve">
<value>Continue</value>
</data>
<data name="AppSettings_UnkownConfiguration_EnablePortableMode" xml:space="preserve">
<value>Enable portable mode</value>
</data>
<data name="Settings_DeveloperOptions.Description" xml:space="preserve">
<value>These settings are for development use only</value>
</data>
Expand Down
18 changes: 0 additions & 18 deletions src/Magpie.App/Resources.language-es.resw
Original file line number Diff line number Diff line change
Expand Up @@ -495,15 +495,6 @@
<data name="AppSettings_Dialog_Warning" xml:space="preserve">
<value>Advertencia</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Continue" xml:space="preserve">
<value>Continuar</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Exit" xml:space="preserve">
<value>Cerrar</value>
</data>
<data name="AppSettings_UnkownConfiguration_EnablePortableMode" xml:space="preserve">
<value>Habilitar el modo portable</value>
</data>
<data name="Settings_DeveloperOptions_DebugMode.Content" xml:space="preserve">
<value>Modo de depuración</value>
</data>
Expand Down Expand Up @@ -693,9 +684,6 @@
<data name="Profile_SourceWindow_CaptureTitleBar.Header" xml:space="preserve">
<value>Capturar barra de título</value>
</data>
<data name="AppSettings_UnkownConfiguration_Content" xml:space="preserve">
<value>El archivo de configuración global proviene de una versión desconocida y es posible que no se analice correctamente.</value>
</data>
<data name="About_Feedback_Discussion.Header" xml:space="preserve">
<value>Discusiones</value>
</data>
Expand Down Expand Up @@ -729,15 +717,9 @@
<data name="Settings_Launch_RunAtStartup_MinimizeAtStartup.Header" xml:space="preserve">
<value>Minimizar a la bandeja del sistema al inicio</value>
</data>
<data name="AppSettings_PortableModeUnkownConfiguration_Content" xml:space="preserve">
<value>El archivo de configuración local proviene de una versión desconocida y es posible que no se analice correctamente.</value>
</data>
<data name="Settings_DeveloperOptions.Description" xml:space="preserve">
<value>Esta configuración es solo para uso de desarrollo</value>
</data>
<data name="AppSettings_UnkownConfiguration_Continue" xml:space="preserve">
<value>Continuar</value>
</data>
<data name="Settings_DeveloperOptions.Header" xml:space="preserve">
<value>Opciones de desarrollador</value>
</data>
Expand Down
Loading

0 comments on commit cd7f10b

Please sign in to comment.