forked from ysc3839/AudioPlaybackConnector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SettingsUtil.hpp
73 lines (62 loc) · 2.03 KB
/
SettingsUtil.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#pragma once
#include <ranges>
constexpr auto CONFIG_NAME = L"AudioPlaybackConnector.json";
constexpr auto BUFFER_SIZE = 4096;
inline void DefaultSettings()
{
g_reconnect = false;
g_lastDevices.clear();
}
inline void LoadSettings()
{
try
{
DefaultSettings();
wil::unique_hfile hFile(CreateFileW((GetModuleFsPath(g_hInst).remove_filename() / CONFIG_NAME).c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
THROW_LAST_ERROR_IF(!hFile);
std::string string;
while (true)
{
size_t size = string.size();
string.resize(size + BUFFER_SIZE);
DWORD read = 0;
THROW_IF_WIN32_BOOL_FALSE(ReadFile(hFile.get(), string.data() + size, BUFFER_SIZE, &read, nullptr));
string.resize(size + read);
if (read == 0)
break;
}
std::wstring utf16 = Utf8ToUtf16(string);
auto jsonObj = JsonObject::Parse(utf16);
g_reconnect = jsonObj.Lookup(L"reconnect").GetBoolean();
auto lastDevices = jsonObj.Lookup(L"lastDevices").GetArray();
g_lastDevices.reserve(lastDevices.Size());
for (const auto& i : lastDevices)
{
if (i.ValueType() == JsonValueType::String)
g_lastDevices.push_back(std::wstring(i.GetString()));
}
}
CATCH_LOG();
}
inline void SaveSettings()
{
try
{
JsonObject jsonObj;
jsonObj.Insert(L"reconnect", JsonValue::CreateBooleanValue(g_reconnect));
JsonArray lastDevices;
for (const auto& key : g_audioPlaybackConnections | std::views::keys)
{
lastDevices.Append(JsonValue::CreateStringValue(key));
}
auto t = jsonObj.Insert(L"lastDevices", lastDevices);
wil::unique_hfile hFile(CreateFileW((GetModuleFsPath(g_hInst).remove_filename() / CONFIG_NAME).c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr));
THROW_LAST_ERROR_IF(!hFile);
std::string utf8 = Utf16ToUtf8(jsonObj.Stringify());
DWORD written = 0;
THROW_IF_WIN32_BOOL_FALSE(WriteFile(hFile.get(), utf8.data(), static_cast<DWORD>(utf8.size()), &written, nullptr));
THROW_HR_IF(E_FAIL, written != utf8.size());
t = !t;
}
CATCH_LOG();
}