File size: 7,915 Bytes
2edf277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// 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