hf_repo4 / src /platform /settings.cpp
fava21's picture
Backup: patch pack applied + verified on Win11 22000 (d446cc1, ba8617e, dcf5cb8)
2edf277 verified
Raw History Blame Contribute Delete
7.92 kB
// FCS Glass - src/platform/settings.cpp
//
// Implements: J8 (atomic ui.json), D-4 (temp + FlushFileBuffers + MoveFileExW),
// with the RULES in src/core/settings.h.
#include "platform/settings.h"
#include "platform/platform.h"
#include "core/settings.h"
#include <shlobj.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace fcs {
namespace {
constexpr wchar_t kFolder[] = L"FolderCloneSync";
constexpr wchar_t kFile[] = L"ui.json";
// The whole parser. Tiny on purpose, but with a hard rule: a file with none of
// our keys is NOT "parsed, all defaults". Treating it that way would let a
// truncated write look like a successful load and then be saved straight back,
// permanently truncating it - which is how a corrupt file becomes permanent.
bool ParseSettings(const std::string& text, Settings* out, std::string* note) {
const char* reduce = std::strstr(text.c_str(), "\"reduce_motion\"");
const char* scale = std::strstr(text.c_str(), "\"text_scale\"");
if (reduce == nullptr && scale == nullptr) {
if (note != nullptr) *note = "no recognised keys; treating as corrupt";
return false;
}
if (reduce != nullptr) {
const char* colon = std::strchr(reduce, ':');
if (colon != nullptr) out->reduce_motion = (std::strstr(colon, "true") != nullptr);
}
if (scale != nullptr) {
const char* colon = std::strchr(scale, ':');
if (colon != nullptr) out->text_scale = static_cast<float>(std::atof(colon + 1));
if (!(out->text_scale > 0.0f)) out->text_scale = 1.0f; // refuse garbage
}
return true;
}
std::string Serialize(const Settings& s) {
char buf[256];
std::snprintf(buf, sizeof(buf),
"{\n \"reduce_motion\": %s,\n \"text_scale\": %.3f\n}\n",
s.reduce_motion ? "true" : "false",
static_cast<double>(s.text_scale));
return std::string(buf);
}
// J12 predicates throughout, never a cast integer comparison.
bool WriteAll(HANDLE h, const std::string& data, std::string* note) {
DWORD written = 0;
if (!::WriteFile(h, data.data(), static_cast<DWORD>(data.size()), &written,
nullptr) || written != data.size()) {
if (note != nullptr) *note = "WriteFile failed or short";
return false;
}
// D-4: durability, not atomicity. Without this the rename can be durable
// while the contents are still only in cache, so a power cut can leave a
// correctly-named EMPTY ui.json - which is rule 2's corrupt case.
if (!::FlushFileBuffers(h)) {
if (note != nullptr) *note = "FlushFileBuffers failed";
return false;
}
return true;
}
} // namespace
std::wstring Settings::Path() {
// Cached. MEASURED, not assumed: the FIRST call to
// SHGetKnownFolderPath(FOLDERID_RoamingAppData) kicks off asynchronous
// folder-redirector startup, and presenting into that contends badly enough to
// take the frame cadence from 16.7 ms to ~256 ms. The probe showed it by
// bisection: adding a 2 s settle after the call restores 16.65 ms and n=301
// exactly. So the cost is one-time background work, not per-call - which means
// it belongs in a static, paid once at startup, rather than on any path a
// frame can reach.
static const std::wstring cached = [] {
PWSTR known = nullptr;
// FOLDERID_* is a `const GUID` OBJECT, not a pointer - the API takes it by
// reference, so `&FOLDERID_RoamingAppData` is a `const GUID*` and does not
// bind. (And note Roaming, not Local: preferences that should follow the
// user between machines belong in Roaming; the app's own caches belong in
// Local, and mixing them up is how a roaming profile grows a
// multi-megabyte LocalAppData. J8's requirement is a KNOWN folder either
// way - this is not an invented path under %APPDATA%.)
if (FAILED(::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &known)) ||
known == nullptr) {
return std::wstring();
}
std::wstring dir(known);
::CoTaskMemFree(known);
return dir + L"\\" + kFolder + L"\\" + kFile;
}();
return cached;
}
std::wstring Settings::TempPath() {
const std::wstring target = Path();
if (target.empty()) return std::wstring();
// J8 rule 1: SAME DIRECTORY, so the replace is a rename and therefore atomic.
// core::TempPathFor is the tested form of that rule; the probe asserts the two
// agree on the directory rather than trusting this comment.
return target + L".tmp";
}
bool Settings::Load(Settings* out, std::string* note) {
if (out == nullptr) return false;
const std::wstring path = Path();
if (path.empty()) {
if (note != nullptr) *note = "no known-folder path";
return false;
}
// Rule 3: a leftover temp is REMOVED, never read. A half-written ui.json.tmp
// is not the user's settings, and treating it as recoverable state is how a
// corrupt file becomes permanent.
const std::wstring temp = TempPath();
if (!temp.empty() &&
::GetFileAttributesW(temp.c_str()) != INVALID_FILE_ATTRIBUTES) {
::DeleteFileW(temp.c_str());
}
HANDLE h = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
bool exists = IsValidFileHandle(h);
std::string text;
if (exists) {
char buf[4096];
DWORD got = 0;
if (::ReadFile(h, buf, sizeof(buf), &got, nullptr) && got > 0) {
text.assign(buf, got);
} else {
exists = false; // unreadable is NOT the same as parsed
}
::CloseHandle(h);
}
Settings parsed;
std::string parse_note;
const bool parsed_ok = exists && ParseSettings(text, &parsed, &parse_note);
const core::LoadOutcome outcome = core::ClassifyLoad(exists, parsed_ok);
if (outcome == core::LoadOutcome::UseFile) {
*out = parsed;
if (note != nullptr) note->clear();
return true;
}
// NoFile or CorruptKeepFile: run on DEFAULTS either way. The difference - and
// the reason LoadOutcome has three values - is rule 2: the corrupt case must
// NOT be saved over, and only the caller can enforce that, so it is told.
if (note != nullptr) {
*note = (outcome == core::LoadOutcome::CorruptKeepFile)
? "ui.json unparseable; DEFAULTS IN USE, FILE PRESERVED"
: "no ui.json; defaults";
}
out->text_scale = 1.0f;
out->reduce_motion = false;
out->tier_override = -1;
return false;
}
bool Settings::Save(std::string* note) const {
const std::wstring target = Path();
const std::wstring temp = TempPath();
if (target.empty() || temp.empty()) {
if (note != nullptr) *note = "no known-folder path";
return false;
}
const std::string data = Serialize(*this);
HANDLE h = ::CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (IsInvalidFileHandle(h)) { // J12: INVALID_HANDLE_VALUE, not NULL
if (note != nullptr) *note = "could not create temp";
return false;
}
if (!WriteAll(h, data, note)) {
::CloseHandle(h);
::DeleteFileW(temp.c_str()); // never leave a half-written temp
return false;
}
::CloseHandle(h);
// D-4: REPLACE_EXISTING swaps in one step; WRITE_THROUGH makes the rename
// itself durable rather than merely atomic. On failure the OLD file is still
// there and the temp is cleaned up - the failure mode is "nothing changed".
if (!::MoveFileExW(temp.c_str(), target.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
if (note != nullptr) *note = "MoveFileExW failed; old file kept";
::DeleteFileW(temp.c_str());
return false;
}
if (note != nullptr) note->clear();
return true;
}
} // namespace fcs