using System; using System.IO; using System.Text.Json; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Windows.System; using EveryPublish.Client.Services; namespace EveryPublish.Client.Pages; public sealed partial class SettingsPage : Page { private ClientContext _ctx = null!; public SettingsPage() { InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { _ctx = (ClientContext)e.Parameter; DataDirText.Text = _ctx.DataDir; ServerBox.Text = ReadServer(); AutoStartToggle.IsOn = AutoStart.IsEnabled(); FakeAllToggle.IsOn = ReadBool("fakeAll"); } private bool ReadBool(string key) { try { var path = Path.Combine(_ctx.DataDir, "config.json"); if (!File.Exists(path)) return false; using var doc = JsonDocument.Parse(File.ReadAllText(path)); if (doc.RootElement.TryGetProperty(key, out var v)) return v.GetBoolean(); } catch { /* 忽略 */ } return false; } private string ReadServer() { try { var path = Path.Combine(_ctx.DataDir, "config.json"); if (!File.Exists(path)) return "http://127.0.0.1:8090"; using var doc = JsonDocument.Parse(File.ReadAllText(path)); if (doc.RootElement.TryGetProperty("server", out var s)) return s.GetString() ?? ""; } catch { /* 忽略 */ } return "http://127.0.0.1:8090"; } private void WriteServer(string server) { var path = Path.Combine(_ctx.DataDir, "config.json"); var doc = File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path)) : JsonDocument.Parse("{}").RootElement; using var json = JsonDocument.Parse(doc.GetRawText()); var dict = JsonSerializer.Deserialize>(json.RootElement.GetRawText()) ?? new(); dict["server"] = JsonSerializer.SerializeToElement(server); File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true })); } private void Save_Click(object sender, RoutedEventArgs e) { var server = ServerBox.Text.Trim(); if (string.IsNullOrEmpty(server)) { ResultText.Text = "服务器地址不能为空"; return; } WriteServer(server); WriteBool("fakeAll", FakeAllToggle.IsOn); AutoStart.SetEnabled(AutoStartToggle.IsOn); _ctx.Watchdog.Restart(); ResultText.Text = "已保存,核心进程已重启"; } private void WriteBool(string key, bool value) { var path = Path.Combine(_ctx.DataDir, "config.json"); var dict = File.Exists(path) ? JsonSerializer.Deserialize>(File.ReadAllText(path)) ?? new() : new(); dict[key] = JsonSerializer.SerializeToElement(value); File.WriteAllText(path, JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true })); } private async void OpenDir_Click(object sender, RoutedEventArgs e) { Directory.CreateDirectory(_ctx.DataDir); await Launcher.LaunchFolderPathAsync(_ctx.DataDir); } private void Exit_Click(object sender, RoutedEventArgs e) { MainWindow.ExitAction?.Invoke(); } }