-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAppSettings.cs
More file actions
828 lines (735 loc) · 28.4 KB
/
AppSettings.cs
File metadata and controls
828 lines (735 loc) · 28.4 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using WinRT;
namespace NoteUI;
public record BackdropSettings(
string Type,
double TintOpacity,
double LuminosityOpacity,
string TintColor = "#000000",
string FallbackColor = "#000000",
string Kind = "Base");
public record PersistedWindowState(
string Type,
string NoteId,
int X,
int Y,
bool IsCompact = false);
public static class AppSettings
{
private static readonly string SettingsDir =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NoteUI");
private static readonly string SettingsPath = Path.Combine(SettingsDir, "settings.json");
private static readonly string DefaultNotesFolder =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NoteUI");
public static string GetDefaultNotesFolder() => DefaultNotesFolder;
// ── Master Password (DPAPI) ─────────────────────────────────
private static readonly string MasterPasswordPath = Path.Combine(SettingsDir, "master_pw.dat");
public static bool HasMasterPassword() => File.Exists(MasterPasswordPath);
public static void SaveMasterPasswordHash(string sha256Hash)
{
try
{
Directory.CreateDirectory(SettingsDir);
var bytes = Encoding.UTF8.GetBytes(sha256Hash);
var encrypted = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
File.WriteAllBytes(MasterPasswordPath, encrypted);
}
catch { }
}
public static string? LoadMasterPasswordHash()
{
try
{
if (!File.Exists(MasterPasswordPath)) return null;
var encrypted = File.ReadAllBytes(MasterPasswordPath);
var decrypted = ProtectedData.Unprotect(encrypted, null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(decrypted);
}
catch { return null; }
}
public static void DeleteMasterPassword()
{
try { if (File.Exists(MasterPasswordPath)) File.Delete(MasterPasswordPath); } catch { }
}
public static string HashPassword(string password)
{
var bytes = Encoding.UTF8.GetBytes(password);
var hash = SHA256.HashData(bytes);
return Convert.ToHexString(hash).ToLowerInvariant();
}
// ── Language ────────────────────────────────────────────────
public static string LoadLanguage()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("language", out var prop))
return prop.GetString() ?? "en";
}
}
catch { }
return "en";
}
public static void SaveLanguage(string lang)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["language"] = lang });
}
// ── Font ─────────────────────────────────────────────────
public static string LoadFontSetting()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("font", out var prop))
return prop.GetString() ?? "geist";
}
}
catch { }
return "geist";
}
public static void SaveFontSetting(string font)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["font"] = font });
}
public static FontFamily GetFontFamily(string font)
{
return font switch
{
"segoe" => new FontFamily("Segoe UI"),
"inter" => new FontFamily("Assets/Fonts/Inter-Regular.ttf#Inter"),
"jetbrains" => new FontFamily("Assets/Fonts/JetBrainsMono-Regular.ttf#JetBrains Mono"),
_ => new FontFamily("Assets/Fonts/Geist-Regular.otf#Geist"),
};
}
public static void ApplyFontToTree(FrameworkElement root, FontFamily fontFamily)
{
if (root is Control c)
c.FontFamily = fontFamily;
else if (root is TextBlock tb)
tb.FontFamily = fontFamily;
if (root is Panel panel)
{
foreach (var child in panel.Children)
if (child is FrameworkElement fe)
ApplyFontToTree(fe, fontFamily);
}
else if (root is ContentControl cc && cc.Content is FrameworkElement content)
{
ApplyFontToTree(content, fontFamily);
}
}
// ── Note style ────────────────────────────────────────────
public static string LoadNoteStyle()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("noteStyle", out var prop))
return prop.GetString() ?? "titlebar";
}
}
catch { }
return "titlebar";
}
public static void SaveNoteStyle(string style)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["noteStyle"] = style });
}
// ── Startup ─────────────────────────────────────────────────
private const string StartupRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
private const string StartupRegistryName = "NoteUI";
public static bool LoadStartWithWindows()
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(StartupRegistryKey, false);
return key?.GetValue(StartupRegistryName) is string;
}
catch { return false; }
}
public static void SaveStartWithWindows(bool enabled)
{
try
{
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(StartupRegistryKey, true);
if (key == null) return;
if (enabled)
{
var exePath = Environment.ProcessPath ?? "";
if (!string.IsNullOrEmpty(exePath))
key.SetValue(StartupRegistryName, $"\"{exePath}\"");
}
else
{
key.DeleteValue(StartupRegistryName, false);
}
}
catch { }
}
public static bool LoadStartMinimized()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("startMinimized", out var prop))
return prop.GetBoolean();
}
}
catch { }
return false;
}
public static void SaveStartMinimized(bool enabled)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["startMinimized"] = enabled });
}
// ── Compact cards ────────────────────────────────────────
public static bool LoadCompactCards()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("compactCards", out var prop))
return prop.GetBoolean();
}
}
catch { }
return false;
}
public static void SaveCompactCards(bool enabled)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["compactCards"] = enabled });
}
// ── Sort preference ────────────────────────────────────────
public static string LoadSortPreference()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("sortMode", out var prop))
return prop.GetString() ?? "created";
}
}
catch { }
return "created";
}
public static void SaveSortPreference(string mode)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["sortMode"] = mode });
}
// ── Slash commands ──────────────────────────────────────────
public static bool LoadSlashEnabled()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("slashEnabled", out var prop))
return prop.GetBoolean();
}
}
catch { }
return true;
}
public static void SaveSlashEnabled(bool enabled)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["slashEnabled"] = enabled });
}
public static string LoadNotesFolder()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("notesFolder", out var prop))
{
var folder = prop.GetString();
if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
return folder;
}
}
}
catch { }
return DefaultNotesFolder;
}
public static void SaveNotesFolder(string folder)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["notesFolder"] = folder });
}
// ── Firebase ───────────────────────────────────────────────
public static (string Url, string ApiKey, string RefreshToken) LoadFirebaseSettings()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
var url = doc.RootElement.TryGetProperty("firebaseUrl", out var uProp)
? uProp.GetString() ?? "" : "";
var key = doc.RootElement.TryGetProperty("firebaseApiKey", out var kProp)
? kProp.GetString() ?? "" : "";
var token = doc.RootElement.TryGetProperty("firebaseRefreshToken", out var tProp)
? tProp.GetString() ?? "" : "";
return (url, key, token);
}
}
catch { }
return ("", "", "");
}
public static void SaveFirebaseSettings(string url, string apiKey, string refreshToken = "")
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["firebaseUrl"] = url,
["firebaseApiKey"] = apiKey,
["firebaseRefreshToken"] = refreshToken
});
}
/// <summary>Note ids ever present under RTDB <c>users/{uid}/notes</c> (aligns with web localStorage key semantics).</summary>
public static HashSet<string> LoadFirebaseEverSeenNoteIds(string userId)
{
if (string.IsNullOrEmpty(userId))
return new HashSet<string>(StringComparer.Ordinal);
try
{
var path = FirebaseEverSeenNoteIdsPath(userId);
if (!File.Exists(path))
return new HashSet<string>(StringComparer.Ordinal);
var list = JsonSerializer.Deserialize<List<string>>(File.ReadAllText(path));
return list is { Count: > 0 }
? new HashSet<string>(list, StringComparer.Ordinal)
: new HashSet<string>(StringComparer.Ordinal);
}
catch
{
return new HashSet<string>(StringComparer.Ordinal);
}
}
public static void SaveFirebaseEverSeenNoteIds(string userId, IEnumerable<string> ids)
{
if (string.IsNullOrEmpty(userId)) return;
try
{
Directory.CreateDirectory(SettingsDir);
var dir = Path.Combine(SettingsDir, "firebase-ever-seen");
Directory.CreateDirectory(dir);
var path = FirebaseEverSeenNoteIdsPath(userId);
var arr = ids.Distinct(StringComparer.Ordinal).OrderBy(s => s, StringComparer.Ordinal).ToArray();
File.WriteAllText(path, JsonSerializer.Serialize(arr));
}
catch { }
}
private static string FirebaseEverSeenNoteIdsPath(string userId)
{
var safe = string.Concat(userId.Where(c => char.IsLetterOrDigit(c) || c is '-' or '_'));
if (string.IsNullOrEmpty(safe)) safe = "unknown";
return Path.Combine(SettingsDir, "firebase-ever-seen", $"{safe}.json");
}
// ── WebDAV ─────────────────────────────────────────────────
public static (string Url, string Username, string Password) LoadWebDavSettings()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
var url = doc.RootElement.TryGetProperty("webdavUrl", out var uProp)
? uProp.GetString() ?? "" : "";
var user = doc.RootElement.TryGetProperty("webdavUser", out var userProp)
? userProp.GetString() ?? "" : "";
var pass = doc.RootElement.TryGetProperty("webdavPass", out var pProp)
? pProp.GetString() ?? "" : "";
return (url, user, pass);
}
}
catch { }
return ("", "", "");
}
public static void SaveWebDavSettings(string url, string username, string password)
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["webdavUrl"] = url,
["webdavUser"] = username,
["webdavPass"] = password
});
}
// ── Apply to any window ─────────────────────────────────────
public static void ApplyToWindow(Window window, BackdropSettings settings,
ref IDisposable? controller, ref SystemBackdropConfiguration? configSource)
{
controller?.Dispose();
controller = null;
configSource = null;
window.SystemBackdrop = null;
if (settings.Type == "none")
return;
controller = CreateBackdropController(settings);
if (controller is null)
return;
configSource = new SystemBackdropConfiguration
{
IsInputActive = true,
Theme = SystemBackdropTheme.Default
};
if (window.Content is FrameworkElement fe)
configSource.Theme = (SystemBackdropTheme)fe.ActualTheme;
ConfigureBackdropController(
controller,
window.As<Microsoft.UI.Composition.ICompositionSupportsSystemBackdrop>(),
configSource);
}
private static IDisposable? CreateBackdropController(BackdropSettings settings)
{
return settings.Type switch
{
"mica" when MicaController.IsSupported() => new MicaController(),
"mica_alt" when MicaController.IsSupported() => new MicaController { Kind = MicaKind.BaseAlt },
"acrylic_custom" when DesktopAcrylicController.IsSupported() => new DesktopAcrylicController
{
TintOpacity = (float)settings.TintOpacity,
LuminosityOpacity = (float)settings.LuminosityOpacity,
TintColor = ParseColor(settings.TintColor),
FallbackColor = ParseColor(settings.FallbackColor),
Kind = settings.Kind == "Thin"
? DesktopAcrylicKind.Thin
: DesktopAcrylicKind.Base,
},
_ when DesktopAcrylicController.IsSupported() => new DesktopAcrylicController(),
_ => null
};
}
private static void ConfigureBackdropController(
IDisposable controller,
Microsoft.UI.Composition.ICompositionSupportsSystemBackdrop target,
SystemBackdropConfiguration config)
{
switch (controller)
{
case MicaController mica:
mica.AddSystemBackdropTarget(target);
mica.SetSystemBackdropConfiguration(config);
break;
case DesktopAcrylicController acrylic:
acrylic.AddSystemBackdropTarget(target);
acrylic.SetSystemBackdropConfiguration(config);
break;
}
}
public static void ApplyThemeToWindow(Window window, string theme,
SystemBackdropConfiguration? configSource = null)
{
if (window.Content is FrameworkElement fe)
{
fe.RequestedTheme = theme switch
{
"light" => ElementTheme.Light,
"dark" => ElementTheme.Dark,
_ => ElementTheme.Default
};
if (configSource != null)
configSource.Theme = (SystemBackdropTheme)fe.ActualTheme;
}
}
// ── Persistence ─────────────────────────────────────────────
public static BackdropSettings LoadSettings()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var type = root.TryGetProperty("backdrop", out var bProp)
? bProp.GetString() ?? "acrylic" : "acrylic";
var tintOpacity = root.TryGetProperty("tintOpacity", out var tProp)
? tProp.GetDouble() : 0.8;
var luminosity = root.TryGetProperty("luminosityOpacity", out var lProp)
? lProp.GetDouble() : 0.8;
var tintColor = root.TryGetProperty("tintColor", out var tcProp)
? tcProp.GetString() ?? "#000000" : "#000000";
var fallbackColor = root.TryGetProperty("fallbackColor", out var fcProp)
? fcProp.GetString() ?? "#000000" : "#000000";
var kind = root.TryGetProperty("kind", out var kProp)
? kProp.GetString() ?? "Base" : "Base";
return new BackdropSettings(type, tintOpacity, luminosity, tintColor, fallbackColor, kind);
}
}
catch { }
return new BackdropSettings("acrylic", 0.8, 0.8);
}
public static string LoadThemeSetting()
{
try
{
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("theme", out var prop))
return prop.GetString() ?? "system";
}
}
catch { }
return "system";
}
public static (int X, int Y, int W, int H)? LoadMainWindowPosition()
{
try
{
if (!File.Exists(SettingsPath))
return null;
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("mainWindowX", out var xProp) &&
root.TryGetProperty("mainWindowY", out var yProp) &&
xProp.TryGetInt32(out var x) &&
yProp.TryGetInt32(out var y))
{
int w = 380, h = 650;
if (root.TryGetProperty("mainWindowW", out var wProp) && wProp.TryGetInt32(out var ww)) w = ww;
if (root.TryGetProperty("mainWindowH", out var hProp) && hProp.TryGetInt32(out var hh)) h = hh;
return (x, y, w, h);
}
}
catch { }
return null;
}
public static bool LoadMainWindowCompact()
{
try
{
if (!File.Exists(SettingsPath))
return false;
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("mainWindowCompact", out var compactProp) &&
(compactProp.ValueKind == JsonValueKind.True || compactProp.ValueKind == JsonValueKind.False))
{
return compactProp.GetBoolean();
}
}
catch { }
return false;
}
public static void SaveBackdropSettings(BackdropSettings settings)
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["backdrop"] = settings.Type,
["tintOpacity"] = settings.TintOpacity,
["luminosityOpacity"] = settings.LuminosityOpacity,
["tintColor"] = settings.TintColor,
["fallbackColor"] = settings.FallbackColor,
["kind"] = settings.Kind
});
}
public static void SaveThemeSetting(string theme)
{
MergeAndSaveSettings(new Dictionary<string, object> { ["theme"] = theme });
}
public static void SaveNotepadPosition(int x, int y, int w, int h)
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["notepadX"] = x,
["notepadY"] = y,
["notepadW"] = w,
["notepadH"] = h
});
}
public static (int X, int Y, int W, int H)? LoadNotepadPosition()
{
try
{
if (!File.Exists(SettingsPath)) return null;
var json = File.ReadAllText(SettingsPath);
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("notepadX", out var xProp) &&
doc.RootElement.TryGetProperty("notepadY", out var yProp) &&
xProp.TryGetInt32(out var x) &&
yProp.TryGetInt32(out var y))
{
int w = 920, h = 640;
if (doc.RootElement.TryGetProperty("notepadW", out var wProp) && wProp.TryGetInt32(out var ww)) w = ww;
if (doc.RootElement.TryGetProperty("notepadH", out var hProp) && hProp.TryGetInt32(out var hh)) h = hh;
return (x, y, w, h);
}
}
catch { }
return null;
}
public static void SaveMainWindowPosition(Windows.Graphics.PointInt32 position, Windows.Graphics.SizeInt32 size)
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["mainWindowX"] = position.X,
["mainWindowY"] = position.Y,
["mainWindowW"] = size.Width,
["mainWindowH"] = size.Height
});
}
public static void SaveMainWindowCompact(bool isCompact)
{
MergeAndSaveSettings(new Dictionary<string, object>
{
["mainWindowCompact"] = isCompact
});
}
public static List<PersistedWindowState> LoadOpenWindows()
{
var result = new List<PersistedWindowState>();
try
{
if (!File.Exists(SettingsPath))
return result;
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("openWindows", out var windowsProp))
{
return result;
}
var arrayElement = windowsProp;
JsonDocument? nestedDoc = null;
if (windowsProp.ValueKind == JsonValueKind.String)
{
var raw = windowsProp.GetString();
if (!string.IsNullOrWhiteSpace(raw))
{
nestedDoc = JsonDocument.Parse(raw);
arrayElement = nestedDoc.RootElement;
}
}
if (arrayElement.ValueKind != JsonValueKind.Array)
{
nestedDoc?.Dispose();
return result;
}
foreach (var item in arrayElement.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.Object)
continue;
var type = item.TryGetProperty("type", out var typeProp)
? typeProp.GetString() ?? ""
: "";
var noteId = item.TryGetProperty("noteId", out var noteIdProp)
? noteIdProp.GetString() ?? ""
: "";
if (!item.TryGetProperty("x", out var xProp) ||
!item.TryGetProperty("y", out var yProp) ||
!xProp.TryGetInt32(out var x) ||
!yProp.TryGetInt32(out var y) ||
string.IsNullOrWhiteSpace(type))
{
continue;
}
var isCompact =
item.TryGetProperty("isCompact", out var compactProp) &&
(compactProp.ValueKind == JsonValueKind.True || compactProp.ValueKind == JsonValueKind.False) &&
compactProp.GetBoolean();
result.Add(new PersistedWindowState(type, noteId, x, y, isCompact));
}
nestedDoc?.Dispose();
}
catch { }
return result;
}
public static void SaveOpenWindows(IEnumerable<PersistedWindowState> windows)
{
var payload = windows.Select(w => new Dictionary<string, object>
{
["type"] = w.Type,
["noteId"] = w.NoteId,
["x"] = w.X,
["y"] = w.Y,
["isCompact"] = w.IsCompact
}).ToList();
MergeAndSaveSettings(new Dictionary<string, object>
{
["openWindows"] = payload
});
}
private static void MergeAndSaveSettings(Dictionary<string, object> newValues)
{
try
{
var existing = new Dictionary<string, object>();
if (File.Exists(SettingsPath))
{
var json = File.ReadAllText(SettingsPath);
var doc = JsonDocument.Parse(json);
foreach (var prop in doc.RootElement.EnumerateObject())
{
if (newValues.ContainsKey(prop.Name)) continue;
existing[prop.Name] = ConvertJsonElement(prop.Value) ?? "";
}
}
foreach (var kv in newValues)
existing[kv.Key] = kv.Value;
Directory.CreateDirectory(SettingsDir);
File.WriteAllText(SettingsPath, JsonSerializer.Serialize(existing));
}
catch { }
}
private static object? ConvertJsonElement(JsonElement value)
{
return value.ValueKind switch
{
JsonValueKind.Object => value.EnumerateObject()
.ToDictionary(p => p.Name, p => ConvertJsonElement(p.Value)),
JsonValueKind.Array => value.EnumerateArray()
.Select(ConvertJsonElement)
.ToList(),
JsonValueKind.String => value.GetString(),
JsonValueKind.Number => value.TryGetInt64(out var l) ? l : value.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null => null,
_ => value.GetRawText()
};
}
public static Windows.UI.Color ParseColor(string hex)
{
hex = hex.TrimStart('#');
if (hex.Length != 6)
return new Windows.UI.Color { A = 255, R = 0, G = 0, B = 0 };
return new Windows.UI.Color
{
A = 255,
R = Convert.ToByte(hex[..2], 16),
G = Convert.ToByte(hex[2..4], 16),
B = Convert.ToByte(hex[4..6], 16)
};
}
}