Skip to main content

atmos/kernel/
config.rs

1//! OS 設定・テーマ(配色)の永続化と読み込み。
2//!
3//! [`ThemeConfig`] が1テーマ分の全配色(デスクトップ・ボタン・ログイン画面・システムモニタ等)
4//! を保持する。プリセットテーマは `colorset/*.json`(`default`/`dracula`/`earth`/`nord`/
5//! `sakura`)として同梱され、[`crate::apps::settings`] からカスタムテーマも JSON で
6//! SylFS に保存できる。キーボードレイアウト([`KeyboardLayout`])もここで管理する。
7// src/config.rs - OS Settings & Theme Configuration for AtmOS
8#![allow(dead_code)]
9#![allow(static_mut_refs)]
10
11extern crate alloc;
12use crate::kernel::fs;
13pub use crate::kernel::keyboard::KeyboardLayout;
14use crate::os_lib::json::{self, JsonValue};
15use alloc::collections::BTreeMap;
16use alloc::string::String;
17
18#[derive(Clone, Copy, Debug)]
19pub struct ThemeConfig {
20    pub name: &'static str,
21    pub desktop_bg: u32,
22    pub terminal_bg: u32,
23    pub terminal_fg: u32,
24    pub active_window_border: u32,
25    pub non_active_window_border: u32,
26    pub window_title_bar: u32,
27    pub window_title_fg: u32,
28    // --- GUI Detailed Colors ---
29    pub app_bg: u32,
30    pub app_fg: u32,
31    pub button_bg: u32,
32    pub button_fg: u32,
33    pub button_active_bg: u32,
34    pub button_active_fg: u32,
35    pub focus_highlight: u32,
36    // --- Mouse Cursor Theme Colors ---
37    pub mouse_cursor: u32,
38    pub mouse_stroke: u32,
39    // --- 追加:ログイン画面用 ---
40    pub login_screen_bg: u32,
41    pub login_dialog_bg: u32,
42    pub login_dialog_shadow: u32,
43    pub login_dialog_border: u32,
44    pub login_text_fg: u32,
45    pub login_field_bg: u32,
46    pub login_field_border: u32,
47    // --- 追加:システムモニター用 ---
48    pub sysmon_bg: u32,
49    pub sysmon_header_bg: u32,
50    pub sysmon_accent: u32,
51    pub sysmon_text: u32,
52    pub sysmon_value: u32,
53    pub sysmon_border: u32,
54    // --- 追加:タブエリア用 ---
55    pub tab_area_bg: u32,
56    pub tab_area_border: u32,
57    pub tab_active_bg: u32,
58    pub tab_active_fg: u32,
59    pub tab_inactive_fg: u32,
60    // --- 追加:ファンクションバー用 ---
61    pub fn_bar_bg: u32,
62    pub fn_bar_cell_bg: u32,
63    pub fn_bar_key_bg: u32,
64    pub fn_bar_key_fg: u32,
65    pub fn_bar_text_fg: u32,
66    pub fn_bar_dim_fg: u32,
67    pub fn_bar_border: u32,
68    // --- 追加:IME用 ---
69    pub ime_bg: u32,
70    pub ime_border: u32,
71    pub ime_text: u32,
72    // --- ウィンドウ制御ボタン ---
73    pub win_btn_close: u32,
74    pub win_btn_fullscreen: u32,
75    pub win_btn_maximize: u32,
76    pub win_btn_restore: u32,
77    pub win_btn_minimize: u32,
78    // --- OS共通 UI カラー ---
79    pub error_fg: u32,          // エラーテキスト(赤)
80    pub success_fg: u32,        // 成功・アクティブ表示(緑)
81    pub warning_fg: u32,        // 警告テキスト(オレンジ)
82    pub ui_overlay_bg: u32,     // オーバーレイ背景(暗め)
83    pub ui_overlay_accent: u32, // オーバーレイアクセントライン・フォーカス
84    pub ui_input_bg: u32,       // フォーム入力フィールド背景
85    pub browser_bg: u32,        // ブラウザ内部UI背景
86    pub browser_fg: u32,        // ブラウザ内部UIテキスト
87    pub browser_secondary: u32, // ブラウザ二次カラー(枠線・スクロールバー等)
88    pub login_caret: u32,       // ログイン入力カーソル
89    pub login_hint_fg: u32,     // ログインヒントテキスト
90    // --- スクロールバー ---
91    pub scrollbar_thumb: u32,   // スクロールバーのサム
92    // --- フォーム入力 (Webエンジン) ---
93    pub form_input_bg: u32,         // input/textarea/select 背景
94    pub form_input_fg: u32,         // input/textarea/select 文字色
95    pub form_input_border: u32,     // input/textarea/select 枠線
96    pub form_input_border_focus: u32, // フォーカス時枠線
97    pub form_input_accent: u32,     // select ▼ アイコン色
98    pub form_checkbox_checked: u32, // チェック時 fill 色
99    pub form_checkbox_unchecked: u32, // 未チェック時 fill 色
100    // --- ボタン デフォルトフォールバック (Webエンジン) ---
101    pub btn_default_bg: u32,         // CSSでbg未指定のbutton背景
102    pub btn_default_border: u32,     // 同 border
103    pub btn_hover_bg: u32,           // hover 時 button 背景
104    pub btn_hover_border: u32,       // hover 時 button 枠線
105    // --- テキストエリア・エディタ (Webエンジン) ---
106    pub editor_line_highlight: u32,  // カーソル行の下線色
107    pub editor_dim_fg: u32,          // 制御文字(スペース記号・改行記号等)の色
108    // --- 動画プレーヤー (Webエンジン) ---
109    pub video_bar_bg: u32,           // コントロールバー背景
110    pub video_bar_sep: u32,          // バー上部境界線
111    pub video_progress_fg: u32,      // プログレスバー色
112    pub video_thumb_fg: u32,         // プログレスのサムネイル色
113    // --- Privacy Shield バッジ (Webエンジン) ---
114    pub privacy_badge_bg: u32,       // バッジ背景
115    pub privacy_badge_fg: u32,       // バッジ文字色
116}
117
118pub static PRESET_THEMES: &[ThemeConfig] = &[
119    ThemeConfig {
120        name: "Earth Cream",
121        desktop_bg: 0xFFE5DFD3,
122        terminal_bg: 0xFFFDFBF7,
123        terminal_fg: 0xFF2F2A25,
124        active_window_border: 0xFF8F9779,
125        non_active_window_border: 0xFFC5BDB2,
126        window_title_bar: 0xFFBCAE9B,
127        window_title_fg: 0xFF2F2A25,
128        app_bg: 0xFFFAF8F5,
129        app_fg: 0xFF2F2A25,
130        button_bg: 0xFFDDD6CB,
131        button_fg: 0xFF4E453C,
132        button_active_bg: 0xFFC48B71,
133        button_active_fg: 0xFFFFFFFF,
134        focus_highlight: 0xFFC48B71,
135        mouse_cursor: 0xFFFAF8F5,
136        mouse_stroke: 0xFF2F2A25,
137        login_screen_bg: 0xFF28231E,
138        login_dialog_bg: 0xFFEAE5DC,
139        login_dialog_shadow: 0xFF161311,
140        login_dialog_border: 0xFF8F9779,
141        login_text_fg: 0xFF2F2A25,
142        login_field_bg: 0xFFFAF8F5,
143        login_field_border: 0xFF8F9779,
144        sysmon_bg: 0xFF2F2A25,
145        sysmon_header_bg: 0xFF3D3730,
146        sysmon_accent: 0xFFC48B71,
147        sysmon_text: 0xFFB8B0A5,
148        sysmon_value: 0xFFF6F2EA,
149        sysmon_border: 0xFF4A423B,
150        tab_area_bg: 0xFF3A342E,
151        tab_area_border: 0xFF4A423B,
152        tab_active_bg: 0xFFC48B71,
153        tab_active_fg: 0xFFFDFBF7,
154        tab_inactive_fg: 0xFFB8B0A5,
155        fn_bar_bg: 0xFF25201C,
156        fn_bar_cell_bg: 0xFF2F2A25,
157        fn_bar_key_bg: 0xFF4A423B,
158        fn_bar_key_fg: 0xFFC48B71,
159        fn_bar_text_fg: 0xFFFAF8F5,
160        fn_bar_dim_fg: 0xFF73695F,
161        fn_bar_border: 0xFF4A423B,
162        ime_bg: 0xFFFAF8F5,
163        ime_border: 0xFFC48B71,
164        ime_text: 0xFF2F2A25,
165        win_btn_close: 0xFFB85450,
166        win_btn_fullscreen: 0xFF8A6CA0,
167        win_btn_maximize: 0xFF5A8C5A,
168        win_btn_restore: 0xFFB87840,
169        win_btn_minimize: 0xFFA09040,
170        error_fg: 0xFFCC4444,
171        success_fg: 0xFF4A8A50,
172        warning_fg: 0xFFCC8040,
173        ui_overlay_bg: 0xFF2A2420,
174        ui_overlay_accent: 0xFFC48B71,
175        ui_input_bg: 0xFF3A342E,
176        browser_bg: 0xFF2A2420,
177        browser_fg: 0xFFFDFBF7,
178        browser_secondary: 0xFF4A423B,
179        login_caret: 0xFFC48B71,
180        login_hint_fg: 0xFF8A7E72,
181        scrollbar_thumb: 0xFF8F9779,
182        form_input_bg: 0xFFFAF8F5,
183        form_input_fg: 0xFF2F2A25,
184        form_input_border: 0xFF9E9286,
185        form_input_border_focus: 0xFFC48B71,
186        form_input_accent: 0xFF8F9779,
187        form_checkbox_checked: 0xFFC48B71,
188        form_checkbox_unchecked: 0xFFEAE5DC,
189        btn_default_bg: 0xFFDDD6CB,
190        btn_default_border: 0xFF9E9286,
191        btn_hover_bg: 0xFF8F9779,
192        btn_hover_border: 0xFFC48B71,
193        editor_line_highlight: 0xFFC48B71,
194        editor_dim_fg: 0xFF9E9286,
195        video_bar_bg: 0xFF3A342E,
196        video_bar_sep: 0xFF4A423B,
197        video_progress_fg: 0xFF4A8A50,
198        video_thumb_fg: 0xFFFAF8F5,
199        privacy_badge_bg: 0xFF2F4A2F,
200        privacy_badge_fg: 0xFFECFDF5,
201    },
202    ThemeConfig {
203        name: "Dracula",
204        desktop_bg: 0xFF181A1F,
205        terminal_bg: 0xFF282A36,
206        terminal_fg: 0xFFF8F8F2,
207        active_window_border: 0xFFFF79C6,
208        non_active_window_border: 0xFF6272A4,
209        window_title_bar: 0xFF44475A,
210        window_title_fg: 0xFFF8F8F2,
211        app_bg: 0xFFF3F4F6,
212        app_fg: 0xFF1F2937,
213        button_bg: 0xFFE5E7EB,
214        button_fg: 0xFF1F2937,
215        button_active_bg: 0xFF3B82F6,
216        button_active_fg: 0xFFFFFFFF,
217        focus_highlight: 0xFFF59E0B,
218        mouse_cursor: 0xFFFFFFFF,
219        mouse_stroke: 0xFF000000,
220        login_screen_bg: 0xFF0B0B0D,
221        login_dialog_bg: 0xFF1E1F29,
222        login_dialog_shadow: 0xFF040405,
223        login_dialog_border: 0xFF6272A4,
224        login_text_fg: 0xFFF8F8F2,
225        login_field_bg: 0xFF282A36,
226        login_field_border: 0xFFFF79C6,
227        sysmon_bg: 0xFF1E1F29,
228        sysmon_header_bg: 0xFF282A36,
229        sysmon_accent: 0xFFBD93F9,
230        sysmon_text: 0xFF6272A4,
231        sysmon_value: 0xFFF8F8F2,
232        sysmon_border: 0xFF44475A,
233        tab_area_bg: 0xFF1E1F29,
234        tab_area_border: 0xFF44475A,
235        tab_active_bg: 0xFF44475A,
236        tab_active_fg: 0xFF50FA7B,
237        tab_inactive_fg: 0xFF8BE9FD,
238        fn_bar_bg: 0xFF1E1F29,
239        fn_bar_cell_bg: 0xFF282A36,
240        fn_bar_key_bg: 0xFF44475A,
241        fn_bar_key_fg: 0xFF8BE9FD,
242        fn_bar_text_fg: 0xFFF8F8F2,
243        fn_bar_dim_fg: 0xFF6272A4,
244        fn_bar_border: 0xFF6272A4,
245        ime_bg: 0xFF1E1F29,
246        ime_border: 0xFFBD93F9,
247        ime_text: 0xFFF8F8F2,
248        win_btn_close: 0xFFFF5555,
249        win_btn_fullscreen: 0xFFBD93F9,
250        win_btn_maximize: 0xFF50FA7B,
251        win_btn_restore: 0xFFFFB86C,
252        win_btn_minimize: 0xFFF1FA8C,
253        error_fg: 0xFFFF5555,
254        success_fg: 0xFF50FA7B,
255        warning_fg: 0xFFFFB86C,
256        ui_overlay_bg: 0xFF1E1F29,
257        ui_overlay_accent: 0xFFFF79C6,
258        ui_input_bg: 0xFF1E1F29,
259        browser_bg: 0xFF282A36,
260        browser_fg: 0xFFF8F8F2,
261        browser_secondary: 0xFF44475A,
262        login_caret: 0xFF756CE0,
263        login_hint_fg: 0xFF6272A4,
264        scrollbar_thumb: 0xFF6272A4,
265        form_input_bg: 0xFF1E1F29,
266        form_input_fg: 0xFFF8F8F2,
267        form_input_border: 0xFF6272A4,
268        form_input_border_focus: 0xFFFF79C6,
269        form_input_accent: 0xFF8BE9FD,
270        form_checkbox_checked: 0xFFFF79C6,
271        form_checkbox_unchecked: 0xFF1E1F29,
272        btn_default_bg: 0xFF44475A,
273        btn_default_border: 0xFF6272A4,
274        btn_hover_bg: 0xFF6272A4,
275        btn_hover_border: 0xFF8BE9FD,
276        editor_line_highlight: 0xFF756CE0,
277        editor_dim_fg: 0xFF6272A4,
278        video_bar_bg: 0xFF282A36,
279        video_bar_sep: 0xFF44475A,
280        video_progress_fg: 0xFF50FA7B,
281        video_thumb_fg: 0xFFF8F8F2,
282        privacy_badge_bg: 0xFF064E3B,
283        privacy_badge_fg: 0xFFECFDF5,
284    },
285    ThemeConfig {
286        name: "Slate Blue",
287        desktop_bg: 0xFF0F172A,
288        terminal_bg: 0xFF1E293B,
289        terminal_fg: 0xFFF1F5F9,
290        active_window_border: 0xFF38BDF8,
291        non_active_window_border: 0xFF475569,
292        window_title_bar: 0xFF334155,
293        window_title_fg: 0xFFF1F5F9,
294        app_bg: 0xFFF8FAFC,
295        app_fg: 0xFF0F172A,
296        button_bg: 0xFFE2E8F0,
297        button_fg: 0xFF334155,
298        button_active_bg: 0xFF2563EB,
299        button_active_fg: 0xFFFFFFFF,
300        focus_highlight: 0xFFF59E0B,
301        mouse_cursor: 0xFFFFFFFF,
302        mouse_stroke: 0xFF000000,
303        login_screen_bg: 0xFF0B132B,
304        login_dialog_bg: 0xFF1C2541,
305        login_dialog_shadow: 0xFF050814,
306        login_dialog_border: 0xFF475569,
307        login_text_fg: 0xFFF1F5F9,
308        login_field_bg: 0xFF1E293B,
309        login_field_border: 0xFF38BDF8,
310        sysmon_bg: 0xFF1E293B,
311        sysmon_header_bg: 0xFF334155,
312        sysmon_accent: 0xFF38BDF8,
313        sysmon_text: 0xFF94A3B8,
314        sysmon_value: 0xFFF1F5F9,
315        sysmon_border: 0xFF475569,
316        tab_area_bg: 0xFF1E293B,
317        tab_area_border: 0xFF475569,
318        tab_active_bg: 0xFF334155,
319        tab_active_fg: 0xFF38BDF8,
320        tab_inactive_fg: 0xFF94A3B8,
321        fn_bar_bg: 0xFF0F172A,
322        fn_bar_cell_bg: 0xFF1E293B,
323        fn_bar_key_bg: 0xFF334155,
324        fn_bar_key_fg: 0xFF38BDF8,
325        fn_bar_text_fg: 0xFFF1F5F9,
326        fn_bar_dim_fg: 0xFF64748B,
327        fn_bar_border: 0xFF475569,
328        ime_bg: 0xFF1E293B,
329        ime_border: 0xFF38BDF8,
330        ime_text: 0xFFF1F5F9,
331        win_btn_close: 0xFFEF4444,
332        win_btn_fullscreen: 0xFF8B5CF6,
333        win_btn_maximize: 0xFF22C55E,
334        win_btn_restore: 0xFFF97316,
335        win_btn_minimize: 0xFFEAB308,
336        error_fg: 0xFFEF4444,
337        success_fg: 0xFF22C55E,
338        warning_fg: 0xFFF97316,
339        ui_overlay_bg: 0xFF1E293B,
340        ui_overlay_accent: 0xFF38BDF8,
341        ui_input_bg: 0xFF1E293B,
342        browser_bg: 0xFF1E293B,
343        browser_fg: 0xFFF1F5F9,
344        browser_secondary: 0xFF334155,
345        login_caret: 0xFF38BDF8,
346        login_hint_fg: 0xFF64748B,
347        scrollbar_thumb: 0xFF475569,
348        form_input_bg: 0xFF1E293B,
349        form_input_fg: 0xFFF1F5F9,
350        form_input_border: 0xFF475569,
351        form_input_border_focus: 0xFF38BDF8,
352        form_input_accent: 0xFF38BDF8,
353        form_checkbox_checked: 0xFF38BDF8,
354        form_checkbox_unchecked: 0xFF1E293B,
355        btn_default_bg: 0xFF334155,
356        btn_default_border: 0xFF475569,
357        btn_hover_bg: 0xFF475569,
358        btn_hover_border: 0xFF38BDF8,
359        editor_line_highlight: 0xFF38BDF8,
360        editor_dim_fg: 0xFF64748B,
361        video_bar_bg: 0xFF1E293B,
362        video_bar_sep: 0xFF334155,
363        video_progress_fg: 0xFF22C55E,
364        video_thumb_fg: 0xFFF1F5F9,
365        privacy_badge_bg: 0xFF064E3B,
366        privacy_badge_fg: 0xFFECFDF5,
367    },
368    ThemeConfig {
369        name: "Emerald Green",
370        desktop_bg: 0xFF022C22,
371        terminal_bg: 0xFF064E3B,
372        terminal_fg: 0xFFECFDF5,
373        active_window_border: 0xFF34D399,
374        non_active_window_border: 0xFF059669,
375        window_title_bar: 0xFF047857,
376        window_title_fg: 0xFFECFDF5,
377        app_bg: 0xFFF0FDF4,
378        app_fg: 0xFF064E3B,
379        button_bg: 0xFFD1FAE5,
380        button_fg: 0xFF065F46,
381        button_active_bg: 0xFF10B981,
382        button_active_fg: 0xFFFFFFFF,
383        focus_highlight: 0xFFF59E0B,
384        mouse_cursor: 0xFFFFFFFF,
385        mouse_stroke: 0xFF000000,
386        login_screen_bg: 0xFF021B15,
387        login_dialog_bg: 0xFF064E3B,
388        login_dialog_shadow: 0xFF010C09,
389        login_dialog_border: 0xFF059669,
390        login_text_fg: 0xFFECFDF5,
391        login_field_bg: 0xFF022C22,
392        login_field_border: 0xFF34D399,
393        sysmon_bg: 0xFF064E3B,
394        sysmon_header_bg: 0xFF047857,
395        sysmon_accent: 0xFF34D399,
396        sysmon_text: 0xFF6EE7B7,
397        sysmon_value: 0xFFECFDF5,
398        sysmon_border: 0xFF059669,
399        tab_area_bg: 0xFF064E3B,
400        tab_area_border: 0xFF059669,
401        tab_active_bg: 0xFF047857,
402        tab_active_fg: 0xFF34D399,
403        tab_inactive_fg: 0xFF6EE7B7,
404        fn_bar_bg: 0xFF022C22,
405        fn_bar_cell_bg: 0xFF064E3B,
406        fn_bar_key_bg: 0xFF047857,
407        fn_bar_key_fg: 0xFF34D399,
408        fn_bar_text_fg: 0xFFECFDF5,
409        fn_bar_dim_fg: 0xFF059669,
410        fn_bar_border: 0xFF059669,
411        ime_bg: 0xFF064E3B,
412        ime_border: 0xFF34D399,
413        ime_text: 0xFFECFDF5,
414        win_btn_close: 0xFFEF4444,
415        win_btn_fullscreen: 0xFFA78BFA,
416        win_btn_maximize: 0xFF34D399,
417        win_btn_restore: 0xFFFB923C,
418        win_btn_minimize: 0xFFFBBF24,
419        error_fg: 0xFFEF4444,
420        success_fg: 0xFF34D399,
421        warning_fg: 0xFFFB923C,
422        ui_overlay_bg: 0xFF064E3B,
423        ui_overlay_accent: 0xFF34D399,
424        ui_input_bg: 0xFF064E3B,
425        browser_bg: 0xFF064E3B,
426        browser_fg: 0xFFECFDF5,
427        browser_secondary: 0xFF047857,
428        login_caret: 0xFF34D399,
429        login_hint_fg: 0xFF6EE7B7,
430        scrollbar_thumb: 0xFF059669,
431        form_input_bg: 0xFF064E3B,
432        form_input_fg: 0xFFECFDF5,
433        form_input_border: 0xFF059669,
434        form_input_border_focus: 0xFF34D399,
435        form_input_accent: 0xFF34D399,
436        form_checkbox_checked: 0xFF34D399,
437        form_checkbox_unchecked: 0xFF064E3B,
438        btn_default_bg: 0xFF047857,
439        btn_default_border: 0xFF059669,
440        btn_hover_bg: 0xFF059669,
441        btn_hover_border: 0xFF34D399,
442        editor_line_highlight: 0xFF34D399,
443        editor_dim_fg: 0xFF059669,
444        video_bar_bg: 0xFF064E3B,
445        video_bar_sep: 0xFF047857,
446        video_progress_fg: 0xFF34D399,
447        video_thumb_fg: 0xFFECFDF5,
448        privacy_badge_bg: 0xFF022C22,
449        privacy_badge_fg: 0xFFECFDF5,
450    },
451    ThemeConfig {
452        name: "Cherry Light",
453        desktop_bg: 0xFFFFF1F2,
454        terminal_bg: 0xFFFFE4E6,
455        terminal_fg: 0xFF9F1239,
456        active_window_border: 0xFFF43F5E,
457        non_active_window_border: 0xFFFDA4AF,
458        window_title_bar: 0xFFFECDD3,
459        window_title_fg: 0xFF9F1239,
460        app_bg: 0xFFFFF1F2,
461        app_fg: 0xFF881337,
462        button_bg: 0xFFFFE4E6,
463        button_fg: 0xFF9F1239,
464        button_active_bg: 0xFFE11D48,
465        button_active_fg: 0xFFFFFFFF,
466        focus_highlight: 0xFFF59E0B,
467        mouse_cursor: 0xFFFFFFFF,
468        mouse_stroke: 0xFF000000,
469        login_screen_bg: 0xFF4C0519,
470        login_dialog_bg: 0xFFFFE4E6,
471        login_dialog_shadow: 0xFF27020B,
472        login_dialog_border: 0xFFFDA4AF,
473        login_text_fg: 0xFF9F1239,
474        login_field_bg: 0xFFFFF1F2,
475        login_field_border: 0xFFF43F5E,
476        sysmon_bg: 0xFFFFE4E6,
477        sysmon_header_bg: 0xFFFECDD3,
478        sysmon_accent: 0xFFF43F5E,
479        sysmon_text: 0xFFFDA4AF,
480        sysmon_value: 0xFF9F1239,
481        sysmon_border: 0xFFFDA4AF,
482        tab_area_bg: 0xFFFFE4E6,
483        tab_area_border: 0xFFFDA4AF,
484        tab_active_bg: 0xFFFECDD3,
485        tab_active_fg: 0xFFF43F5E,
486        tab_inactive_fg: 0xFFFDA4AF,
487        fn_bar_bg: 0xFFFFF1F2,
488        fn_bar_cell_bg: 0xFFFFE4E6,
489        fn_bar_key_bg: 0xFFFECDD3,
490        fn_bar_key_fg: 0xFFF43F5E,
491        fn_bar_text_fg: 0xFF9F1239,
492        fn_bar_dim_fg: 0xFFFDA4AF,
493        fn_bar_border: 0xFFFDA4AF,
494        ime_bg: 0xFFFFE4E6,
495        ime_border: 0xFFF43F5E,
496        ime_text: 0xFF9F1239,
497        win_btn_close: 0xFFE11D48,
498        win_btn_fullscreen: 0xFFA855F7,
499        win_btn_maximize: 0xFF22C55E,
500        win_btn_restore: 0xFFF97316,
501        win_btn_minimize: 0xFFEAB308,
502        error_fg: 0xFFE11D48,
503        success_fg: 0xFF22C55E,
504        warning_fg: 0xFFF97316,
505        ui_overlay_bg: 0xFFFFE4E6,
506        ui_overlay_accent: 0xFFF43F5E,
507        ui_input_bg: 0xFFFFE4E6,
508        browser_bg: 0xFFFFE4E6,
509        browser_fg: 0xFF9F1239,
510        browser_secondary: 0xFFFECDD3,
511        login_caret: 0xFFF43F5E,
512        login_hint_fg: 0xFFFDA4AF,
513        scrollbar_thumb: 0xFFFDA4AF,
514        form_input_bg: 0xFFFFF1F2,
515        form_input_fg: 0xFF9F1239,
516        form_input_border: 0xFFFDA4AF,
517        form_input_border_focus: 0xFFF43F5E,
518        form_input_accent: 0xFFF43F5E,
519        form_checkbox_checked: 0xFFF43F5E,
520        form_checkbox_unchecked: 0xFFFFE4E6,
521        btn_default_bg: 0xFFFFE4E6,
522        btn_default_border: 0xFFFDA4AF,
523        btn_hover_bg: 0xFFFDA4AF,
524        btn_hover_border: 0xFFF43F5E,
525        editor_line_highlight: 0xFFF43F5E,
526        editor_dim_fg: 0xFFFDA4AF,
527        video_bar_bg: 0xFFFFE4E6,
528        video_bar_sep: 0xFFFDA4AF,
529        video_progress_fg: 0xFFF43F5E,
530        video_thumb_fg: 0xFF9F1239,
531        privacy_badge_bg: 0xFF4C0519,
532        privacy_badge_fg: 0xFFFFF1F2,
533    },
534];
535
536#[derive(Clone, Debug)]
537pub struct OsConfig {
538    pub keyboard_layout: KeyboardLayout,
539    pub theme_name: String,
540    pub theme: ThemeConfig,
541    /// フォントのフォールバック順([0]=プライマリ)。主にグリフが無い文字を順に次のフォントで補う。
542    pub font_names: [String; 3],
543    pub enable_sound: bool,
544    pub swap_caps_ctrl: bool,
545    pub auto_dhcp: bool,
546    pub wifi_ssid: String,
547    pub wifi_password: String,
548    pub custom_theme: ThemeConfig,  // カスタムテーマ保持値
549    pub enable_custom_colors: bool, // カスタムカラー有効フラグ
550    /// 週 1 回の定期スナップショットの曜日・時刻(`snapshot_schedule.rs`。2026-11-11)。
551    pub snapshot_schedule: crate::kernel::snapshot_schedule::SnapshotSchedule,
552}
553
554impl Default for OsConfig {
555    fn default() -> Self {
556        Self {
557            keyboard_layout: KeyboardLayout::Jis,
558            theme_name: String::from("Earth Cream"),
559            theme: PRESET_THEMES[0],
560            font_names: [
561                String::from(crate::kernel::vector_font::DEFAULT_FONT_CHAIN[0]),
562                String::from(crate::kernel::vector_font::DEFAULT_FONT_CHAIN[1]),
563                String::from(crate::kernel::vector_font::DEFAULT_FONT_CHAIN[2]),
564            ],
565            enable_sound: true,
566            swap_caps_ctrl: false,
567            auto_dhcp: true,
568            wifi_ssid: String::new(),
569            wifi_password: String::new(),
570            custom_theme: PRESET_THEMES[0],
571            enable_custom_colors: false,
572            snapshot_schedule: crate::kernel::snapshot_schedule::SnapshotSchedule::default(),
573        }
574    }
575}
576
577// グローバル設定インスタンス
578pub static mut GLOBAL_CONFIG: Option<OsConfig> = None;
579
580/// 設定読み込みの結果。
581///
582/// `config` は**常に利用可能**(ファイルが壊れていても既定値へ復旧済み)だが、
583/// 途中で起きた失敗(書き込み失敗・壊れた JSON・未知の値・型違い)は
584/// `status` として必ず呼び出し側へ返す。以前はこれらを全て握り潰していたため、
585/// 「設定したのに反映されない/再起動で戻る」原因が誰にも分からなかった。
586///
587/// `status` は**最初に検出した失敗**を保持する(2 件目以降はログのみ)。
588#[derive(Clone, Debug)]
589pub struct ConfigLoad {
590    pub config: OsConfig,
591    pub status: Result<(), &'static str>,
592}
593
594/// 最初の失敗だけを保持する(後続はログ済みなので上書きしない)。
595fn record_failure(status: &mut Result<(), &'static str>, err: &'static str) {
596    if status.is_ok() {
597        *status = Err(err);
598    }
599}
600
601/// グローバル設定を取得する。
602///
603/// # エラーの扱い
604/// 戻り値が `&'static OsConfig` である以上ここで `Result` は返せないため、
605/// 未初期化時の読み込みで失敗が起きた場合は `error!` へ出力したうえで
606/// 既定値へ復旧した設定を返す。**失敗の有無を判定したい呼び出し側は
607/// `init_or_load()` / `reload_and_apply()` を使うこと。**
608pub fn get_config() -> &'static OsConfig {
609    // まだ読み込まれていない場合は初期化してから返す (panic フリー)
610    unsafe {
611        GLOBAL_CONFIG.get_or_insert_with(|| {
612            let loaded = load_config();
613            if let Err(e) = loaded.status {
614                crate::error!("[SYS] get_config: configuration load degraded: {}", e);
615            }
616            loaded.config
617        })
618    }
619}
620
621pub fn init_or_load() -> ConfigLoad {
622    let loaded = load_config();
623    unsafe {
624        GLOBAL_CONFIG = Some(loaded.config.clone());
625    }
626    loaded
627}
628
629pub fn reload_and_apply() -> Result<(), &'static str> {
630    crate::info!("[SYS] Reloading OS Configuration...");
631    let loaded = load_config();
632    let conf = loaded.config;
633    unsafe {
634        GLOBAL_CONFIG = Some(conf.clone());
635    }
636
637    // フォントの動的再ロード(フォールバックチェーン)
638    let chain: alloc::vec::Vec<&str> = conf.font_names.iter().map(|s| s.as_str()).collect();
639    crate::kernel::vector_font::init_global_font_chain(&chain);
640
641    // 描画画面全体が再描画されるようにDirtyフラグを立てる
642    #[allow(unused_mut)]
643    let mut wm = crate::kernel::window_mgr::get_instance();
644    wm.dirty = true;
645
646    // 再読み込み自体で起きた失敗(保存できなかった・設定が壊れていた等)は
647    // 呼び出し側へそのまま返す。適用処理は完了しているが、状態は健全ではない。
648    loaded.status
649}
650
651pub fn parse_hex_color(val: &JsonValue) -> Option<u32> {
652    match val {
653        JsonValue::Number(n) => Some(*n as u32),
654        JsonValue::String(s) => {
655            let s_trimmed = s.trim_start_matches("0x").trim_start_matches('#');
656            u32::from_str_radix(s_trimmed, 16).ok()
657        }
658        _ => None,
659    }
660}
661
662/// カラーセット JSON の 1 キーを適用する。
663///
664/// キーが無いのは正常(未指定=既定色のまま)だが、**キーがあるのに値が
665/// 読めない場合はエラー**を返す。ここを黙って無視すると「その色だけ効かない」
666/// 状態が何の手掛かりも無しに残る。
667fn apply_color(
668    obj: &BTreeMap<String, JsonValue>,
669    key: &'static str,
670    dst: &mut u32,
671) -> Result<(), &'static str> {
672    if let Some(v) = obj.get(key) {
673        match parse_hex_color(v) {
674            Some(c) => *dst = c,
675            None => {
676                crate::error!("[SYS] colorset: invalid color value for key '{}'", key);
677                return Err("colorset: invalid color value");
678            }
679        }
680    }
681    Ok(())
682}
683
684pub fn load_colorset_from_json(
685    json_str: &str,
686    theme: &mut ThemeConfig,
687) -> Result<(), &'static str> {
688    let parsed = json::parse(json_str).map_err(|_| "colorset: malformed JSON")?;
689    let JsonValue::Object(obj) = parsed else {
690        return Err("colorset: root is not an object");
691    };
692    {
693        let obj = &obj;
694        apply_color(obj, "desktop_bg", &mut theme.desktop_bg)?;
695        apply_color(obj, "terminal_bg", &mut theme.terminal_bg)?;
696        apply_color(obj, "terminal_fg", &mut theme.terminal_fg)?;
697        apply_color(obj, "active_window_border", &mut theme.active_window_border)?;
698        apply_color(obj, "non_active_window_border", &mut theme.non_active_window_border)?;
699        apply_color(obj, "window_title_bar", &mut theme.window_title_bar)?;
700        apply_color(obj, "window_title_fg", &mut theme.window_title_fg)?;
701        apply_color(obj, "app_bg", &mut theme.app_bg)?;
702        apply_color(obj, "app_fg", &mut theme.app_fg)?;
703        apply_color(obj, "button_bg", &mut theme.button_bg)?;
704        apply_color(obj, "button_fg", &mut theme.button_fg)?;
705        apply_color(obj, "button_active_bg", &mut theme.button_active_bg)?;
706        apply_color(obj, "button_active_fg", &mut theme.button_active_fg)?;
707        apply_color(obj, "focus_highlight", &mut theme.focus_highlight)?;
708        apply_color(obj, "mouse_cursor", &mut theme.mouse_cursor)?;
709        apply_color(obj, "mouse_stroke", &mut theme.mouse_stroke)?;
710        apply_color(obj, "login_screen_bg", &mut theme.login_screen_bg)?;
711        apply_color(obj, "login_dialog_bg", &mut theme.login_dialog_bg)?;
712        apply_color(obj, "login_dialog_shadow", &mut theme.login_dialog_shadow)?;
713        apply_color(obj, "login_dialog_border", &mut theme.login_dialog_border)?;
714        apply_color(obj, "login_text_fg", &mut theme.login_text_fg)?;
715        apply_color(obj, "login_field_bg", &mut theme.login_field_bg)?;
716        apply_color(obj, "login_field_border", &mut theme.login_field_border)?;
717        apply_color(obj, "sysmon_bg", &mut theme.sysmon_bg)?;
718        apply_color(obj, "sysmon_header_bg", &mut theme.sysmon_header_bg)?;
719        apply_color(obj, "sysmon_accent", &mut theme.sysmon_accent)?;
720        apply_color(obj, "sysmon_text", &mut theme.sysmon_text)?;
721        apply_color(obj, "sysmon_value", &mut theme.sysmon_value)?;
722        apply_color(obj, "sysmon_border", &mut theme.sysmon_border)?;
723        apply_color(obj, "tab_area_bg", &mut theme.tab_area_bg)?;
724        apply_color(obj, "tab_area_border", &mut theme.tab_area_border)?;
725        apply_color(obj, "tab_active_bg", &mut theme.tab_active_bg)?;
726        apply_color(obj, "tab_active_fg", &mut theme.tab_active_fg)?;
727        apply_color(obj, "tab_inactive_fg", &mut theme.tab_inactive_fg)?;
728        apply_color(obj, "fn_bar_bg", &mut theme.fn_bar_bg)?;
729        apply_color(obj, "fn_bar_cell_bg", &mut theme.fn_bar_cell_bg)?;
730        apply_color(obj, "fn_bar_key_bg", &mut theme.fn_bar_key_bg)?;
731        apply_color(obj, "fn_bar_key_fg", &mut theme.fn_bar_key_fg)?;
732        apply_color(obj, "fn_bar_text_fg", &mut theme.fn_bar_text_fg)?;
733        apply_color(obj, "fn_bar_dim_fg", &mut theme.fn_bar_dim_fg)?;
734        apply_color(obj, "fn_bar_border", &mut theme.fn_bar_border)?;
735        apply_color(obj, "ime_bg", &mut theme.ime_bg)?;
736        apply_color(obj, "ime_border", &mut theme.ime_border)?;
737        apply_color(obj, "ime_text", &mut theme.ime_text)?;
738        apply_color(obj, "win_btn_close", &mut theme.win_btn_close)?;
739        apply_color(obj, "win_btn_fullscreen", &mut theme.win_btn_fullscreen)?;
740        apply_color(obj, "win_btn_maximize", &mut theme.win_btn_maximize)?;
741        apply_color(obj, "win_btn_restore", &mut theme.win_btn_restore)?;
742        apply_color(obj, "win_btn_minimize", &mut theme.win_btn_minimize)?;
743        apply_color(obj, "error_fg", &mut theme.error_fg)?;
744        apply_color(obj, "success_fg", &mut theme.success_fg)?;
745        apply_color(obj, "warning_fg", &mut theme.warning_fg)?;
746        apply_color(obj, "ui_overlay_bg", &mut theme.ui_overlay_bg)?;
747        apply_color(obj, "ui_overlay_accent", &mut theme.ui_overlay_accent)?;
748        apply_color(obj, "ui_input_bg", &mut theme.ui_input_bg)?;
749        apply_color(obj, "browser_bg", &mut theme.browser_bg)?;
750        apply_color(obj, "browser_fg", &mut theme.browser_fg)?;
751        apply_color(obj, "browser_secondary", &mut theme.browser_secondary)?;
752        apply_color(obj, "login_caret", &mut theme.login_caret)?;
753        apply_color(obj, "login_hint_fg", &mut theme.login_hint_fg)?;
754        apply_color(obj, "scrollbar_thumb", &mut theme.scrollbar_thumb)?;
755        apply_color(obj, "form_input_bg", &mut theme.form_input_bg)?;
756        apply_color(obj, "form_input_fg", &mut theme.form_input_fg)?;
757        apply_color(obj, "form_input_border", &mut theme.form_input_border)?;
758        apply_color(obj, "form_input_border_focus", &mut theme.form_input_border_focus)?;
759        apply_color(obj, "form_input_accent", &mut theme.form_input_accent)?;
760        apply_color(obj, "form_checkbox_checked", &mut theme.form_checkbox_checked)?;
761        apply_color(obj, "form_checkbox_unchecked", &mut theme.form_checkbox_unchecked)?;
762        apply_color(obj, "btn_default_bg", &mut theme.btn_default_bg)?;
763        apply_color(obj, "btn_default_border", &mut theme.btn_default_border)?;
764        apply_color(obj, "btn_hover_bg", &mut theme.btn_hover_bg)?;
765        apply_color(obj, "btn_hover_border", &mut theme.btn_hover_border)?;
766        apply_color(obj, "editor_line_highlight", &mut theme.editor_line_highlight)?;
767        apply_color(obj, "editor_dim_fg", &mut theme.editor_dim_fg)?;
768        apply_color(obj, "video_bar_bg", &mut theme.video_bar_bg)?;
769        apply_color(obj, "video_bar_sep", &mut theme.video_bar_sep)?;
770        apply_color(obj, "video_progress_fg", &mut theme.video_progress_fg)?;
771        apply_color(obj, "video_thumb_fg", &mut theme.video_thumb_fg)?;
772        apply_color(obj, "privacy_badge_bg", &mut theme.privacy_badge_bg)?;
773        apply_color(obj, "privacy_badge_fg", &mut theme.privacy_badge_fg)?;
774    }
775    Ok(())
776}
777
778/// JSON オブジェクトから真偽値を取り出す。
779/// キーが無いのは正常(未指定)。**あるのに型が違う場合はエラー**を返す。
780fn take_bool(
781    obj: &BTreeMap<String, JsonValue>,
782    key: &'static str,
783    dst: &mut bool,
784) -> Result<(), &'static str> {
785    match obj.get(key) {
786        None => Ok(()),
787        Some(JsonValue::Bool(b)) => {
788            *dst = *b;
789            Ok(())
790        }
791        Some(_) => {
792            crate::error!("[SYS] config: '{}' must be a boolean", key);
793            Err("config: value has wrong type")
794        }
795    }
796}
797
798/// JSON オブジェクトから文字列を取り出す(型違いはエラー)。
799fn take_string(
800    obj: &BTreeMap<String, JsonValue>,
801    key: &'static str,
802    dst: &mut String,
803) -> Result<(), &'static str> {
804    match obj.get(key) {
805        None => Ok(()),
806        Some(JsonValue::String(s)) => {
807            *dst = s.clone();
808            Ok(())
809        }
810        Some(_) => {
811            crate::error!("[SYS] config: '{}' must be a string", key);
812            Err("config: value has wrong type")
813        }
814    }
815}
816
817/// JSON オブジェクトから数値を取り出す(型違い・負値・非有限はエラー)。
818fn take_u32(
819    obj: &BTreeMap<String, JsonValue>,
820    key: &'static str,
821    dst: &mut u32,
822) -> Result<(), &'static str> {
823    match obj.get(key) {
824        None => Ok(()),
825        Some(JsonValue::Number(n)) => {
826            if !n.is_finite() || *n < 0.0 || *n > u32::MAX as f64 {
827                crate::error!("[SYS] config: '{}' is out of range", key);
828                return Err("config: numeric value out of range");
829            }
830            *dst = *n as u32;
831            Ok(())
832        }
833        Some(_) => {
834            crate::error!("[SYS] config: '{}' must be a number", key);
835            Err("config: value has wrong type")
836        }
837    }
838}
839
840/// `system` セクションを `current_config` へ適用する。
841/// 有効値は採用し、**異常値は採用せずエラーとして返す**(最初の 1 件)。
842fn apply_system_section(
843    system: &BTreeMap<String, JsonValue>,
844    current_config: &mut OsConfig,
845    status: &mut Result<(), &'static str>,
846) {
847    // キーボードレイアウトの適用
848    match system.get("keyboard_layout") {
849        None => {}
850        Some(JsonValue::String(layout)) => match KeyboardLayout::parse(layout) {
851            Some(l) => current_config.keyboard_layout = l,
852            None => {
853                crate::error!("[SYS] config: unknown keyboard_layout '{}'", layout);
854                record_failure(status, "config: unknown keyboard_layout");
855            }
856        },
857        Some(_) => {
858            crate::error!("[SYS] config: 'keyboard_layout' must be a string");
859            record_failure(status, "config: value has wrong type");
860        }
861    }
862
863    // カスタム色の読み込み
864    match system.get("custom_colors") {
865        None => {}
866        Some(JsonValue::Object(custom_colors)) => {
867            let t = &mut current_config.custom_theme;
868            let r = (|| -> Result<(), &'static str> {
869                apply_color(custom_colors, "desktop_bg", &mut t.desktop_bg)?;
870                apply_color(custom_colors, "terminal_bg", &mut t.terminal_bg)?;
871                apply_color(custom_colors, "terminal_fg", &mut t.terminal_fg)?;
872                apply_color(custom_colors, "active_window_border", &mut t.active_window_border)?;
873                apply_color(
874                    custom_colors,
875                    "non_active_window_border",
876                    &mut t.non_active_window_border,
877                )?;
878                apply_color(custom_colors, "window_title_bar", &mut t.window_title_bar)?;
879                apply_color(custom_colors, "window_title_fg", &mut t.window_title_fg)?;
880                apply_color(custom_colors, "app_bg", &mut t.app_bg)?;
881                apply_color(custom_colors, "app_fg", &mut t.app_fg)?;
882                apply_color(custom_colors, "button_bg", &mut t.button_bg)?;
883                apply_color(custom_colors, "button_fg", &mut t.button_fg)?;
884                apply_color(custom_colors, "button_active_bg", &mut t.button_active_bg)?;
885                apply_color(custom_colors, "button_active_fg", &mut t.button_active_fg)?;
886                apply_color(custom_colors, "focus_highlight", &mut t.focus_highlight)?;
887                Ok(())
888            })();
889            if let Err(e) = r {
890                record_failure(status, e);
891            }
892        }
893        Some(_) => {
894            crate::error!("[SYS] config: 'custom_colors' must be an object");
895            record_failure(status, "config: value has wrong type");
896        }
897    }
898
899    // テーマの適用
900    // NOTE: プリセット名に一致しないテーマ名("earth" 等のカラーセット名)は
901    // 設計上の正常系。色は後段の colorset.json 側で上書きされる。
902    match system.get("theme_name") {
903        None => {}
904        Some(JsonValue::String(theme_name)) => {
905            current_config.theme_name = theme_name.clone();
906            if theme_name == "Custom" {
907                current_config.theme = current_config.custom_theme;
908            } else {
909                for t in PRESET_THEMES {
910                    if t.name == theme_name {
911                        current_config.theme = *t;
912                        break;
913                    }
914                }
915            }
916        }
917        Some(_) => {
918            crate::error!("[SYS] config: 'theme_name' must be a string");
919            record_failure(status, "config: value has wrong type");
920        }
921    }
922
923    // フォントの適用: 新形式 "font_names":[a,b,c]。旧形式 "font_name":"x" は [0] に。
924    match system.get("font_names") {
925        Some(JsonValue::Array(arr)) => {
926            if arr.len() > 3 {
927                crate::error!("[SYS] config: 'font_names' has more than 3 entries");
928                record_failure(status, "config: too many font names");
929            }
930            for (i, v) in arr.iter().take(3).enumerate() {
931                match v {
932                    JsonValue::String(name) if !name.is_empty() => {
933                        current_config.font_names[i] = name.clone()
934                    }
935                    _ => {
936                        crate::error!("[SYS] config: 'font_names[{}]' is not a valid name", i);
937                        record_failure(status, "config: invalid font name");
938                    }
939                }
940            }
941        }
942        Some(_) => {
943            crate::error!("[SYS] config: 'font_names' must be an array");
944            record_failure(status, "config: value has wrong type");
945        }
946        None => {
947            if let Err(e) = take_string(system, "font_name", &mut current_config.font_names[0]) {
948                record_failure(status, e);
949            }
950        }
951    }
952
953    // 単純な値の適用(型違いはすべてエラーとして記録する)
954    if let Err(e) = take_bool(system, "enable_sound", &mut current_config.enable_sound) {
955        record_failure(status, e);
956    }
957    if let Err(e) = take_bool(
958        system,
959        "enable_custom_colors",
960        &mut current_config.enable_custom_colors,
961    ) {
962        record_failure(status, e);
963    }
964    if current_config.enable_custom_colors {
965        current_config.theme = current_config.custom_theme;
966    }
967    if let Err(e) = take_bool(system, "swap_caps_ctrl", &mut current_config.swap_caps_ctrl) {
968        record_failure(status, e);
969    }
970    if let Err(e) = take_bool(system, "auto_dhcp", &mut current_config.auto_dhcp) {
971        record_failure(status, e);
972    }
973    if let Err(e) = take_string(system, "wifi_ssid", &mut current_config.wifi_ssid) {
974        record_failure(status, e);
975    }
976    if let Err(e) = take_string(system, "wifi_password", &mut current_config.wifi_password) {
977        record_failure(status, e);
978    }
979
980    // 定期スナップショットの予定(曜日 0=日〜6=土・時・分、JST)
981    match system.get("snapshot_schedule") {
982        None => {}
983        Some(JsonValue::Object(o)) => {
984            let mut s = current_config.snapshot_schedule;
985            match o.get("enabled") {
986                None => {}
987                Some(JsonValue::Bool(b)) => s.enabled = *b,
988                Some(_) => record_failure(status, "config: value has wrong type"),
989            }
990            let (mut wd, mut h, mut m) = (u32::from(s.weekday), u32::from(s.hour), u32::from(s.minute));
991            for (key, dst) in [("weekday", &mut wd), ("hour", &mut h), ("minute", &mut m)] {
992                if let Err(e) = take_u32(o, key, dst) {
993                    record_failure(status, e);
994                }
995            }
996            let cand = crate::kernel::snapshot_schedule::SnapshotSchedule {
997                enabled: s.enabled,
998                weekday: wd.min(255) as u8,
999                hour: h.min(255) as u8,
1000                minute: m.min(255) as u8,
1001            };
1002            if cand.is_valid() {
1003                current_config.snapshot_schedule = cand;
1004            } else {
1005                crate::error!("[SYS] config: snapshot_schedule is out of range");
1006                record_failure(status, "config: numeric value out of range");
1007            }
1008        }
1009        Some(_) => {
1010            crate::error!("[SYS] config: 'snapshot_schedule' must be an object");
1011            record_failure(status, "config: value has wrong type");
1012        }
1013    }
1014
1015    // キーリピート設定の適用
1016    match system.get("keyrepeat") {
1017        None => {}
1018        Some(JsonValue::Object(repeat)) => {
1019            // `static mut` への参照を作らないよう、いったんローカルへ複製して
1020            // 検証し、すべて有効値だった項目だけ書き戻す。
1021            let (mut fd, mut fi, mut sc, mut sd, mut si) = unsafe {
1022                (
1023                    crate::REPEAT_PARAMS.first_delay_ms,
1024                    crate::REPEAT_PARAMS.first_interval_ms,
1025                    crate::REPEAT_PARAMS.second_repeat_count,
1026                    crate::REPEAT_PARAMS.second_delay_ms,
1027                    crate::REPEAT_PARAMS.second_interval_ms,
1028                )
1029            };
1030            if let Err(e) = take_u32(repeat, "first_delay_ms", &mut fd) {
1031                record_failure(status, e);
1032            }
1033            if let Err(e) = take_u32(repeat, "first_interval_ms", &mut fi) {
1034                record_failure(status, e);
1035            }
1036            if let Err(e) = take_u32(repeat, "second_repeat_count", &mut sc) {
1037                record_failure(status, e);
1038            }
1039            if let Err(e) = take_u32(repeat, "second_delay_ms", &mut sd) {
1040                record_failure(status, e);
1041            }
1042            if let Err(e) = take_u32(repeat, "second_interval_ms", &mut si) {
1043                record_failure(status, e);
1044            }
1045            unsafe {
1046                crate::REPEAT_PARAMS.first_delay_ms = fd;
1047                crate::REPEAT_PARAMS.first_interval_ms = fi;
1048                crate::REPEAT_PARAMS.second_repeat_count = sc;
1049                crate::REPEAT_PARAMS.second_delay_ms = sd;
1050                crate::REPEAT_PARAMS.second_interval_ms = si;
1051            }
1052        }
1053        Some(_) => {
1054            crate::error!("[SYS] config: 'keyrepeat' must be an object");
1055            record_failure(status, "config: value has wrong type");
1056        }
1057    }
1058}
1059
1060/// `/os/config.json` と `/os/colorset.json` を読み込む。
1061///
1062/// 戻り値の `config` は常に利用可能だが、**途中で起きた失敗は `status` として
1063/// 呼び出し側へ返す**(従来はすべて握り潰していた)。
1064pub fn load_config() -> ConfigLoad {
1065    let mut current_config = OsConfig::default();
1066    let mut status: Result<(), &'static str> = Ok(());
1067    let fs = fs::get_fs();
1068
1069    let mut config_ok = false;
1070    // 【2026-07-28】「存在しない」と「存在するが読めない」を区別する。
1071    // 読めなかっただけのファイルを「無い」と解釈して既定値で上書きすると、
1072    // ユーザーの設定を**こちらから破棄する**ことになる。
1073    let mut unreadable = false;
1074    let read_result = fs.read_file_checked("/os/config.json");
1075    let config_exists = if let Some((_, content)) = match read_result {
1076        Ok(v) => v,
1077        Err(e) => {
1078            crate::error!("[SYS] config: /os/config.json could not be read: {}", e);
1079            record_failure(&mut status, e);
1080            unreadable = true;
1081            None
1082        }
1083    } {
1084        match core::str::from_utf8(&content) {
1085            Err(_) => {
1086                crate::error!("[SYS] config: /os/config.json is not valid UTF-8");
1087            }
1088            Ok(content_str) => match json::parse(content_str) {
1089                Ok(JsonValue::Object(obj)) => {
1090                    config_ok = true;
1091                    match obj.get("system") {
1092                        Some(JsonValue::Object(system)) => {
1093                            apply_system_section(system, &mut current_config, &mut status);
1094                        }
1095                        Some(_) => {
1096                            crate::error!("[SYS] config: 'system' must be an object");
1097                            record_failure(&mut status, "config: value has wrong type");
1098                        }
1099                        None => {
1100                            crate::error!("[SYS] config: 'system' section is missing");
1101                            record_failure(&mut status, "config: 'system' section is missing");
1102                        }
1103                    }
1104                }
1105                _ => {
1106                    crate::error!("[SYS] config: /os/config.json is not a JSON object");
1107                }
1108            },
1109        }
1110        true
1111    } else {
1112        false
1113    };
1114
1115    if unreadable {
1116        // 読み出しに失敗しているだけで、中身は無事かもしれない。
1117        // 退避も既定値の書き出しも行わない(消してしまわないことを優先する)。
1118        crate::error!(
1119            "[SYS] config: keeping /os/config.json untouched because it could not be read"
1120        );
1121    } else if config_exists && !config_ok {
1122        // 【2026-11-11】壊れた設定は、版の履歴の中で一番新しい「正しく読める版」に戻す(SylFS は Git のように
1123        // 版を残すので、`.bak` のようなファイル名レベルのバックアップは作らない)。戻せる版が無ければ既定値を
1124        // 新しい版として保存する(壊れた版も履歴に残るので、後から調べられる)。
1125        crate::error!("[SYS] /os/config.json is corrupted! Restoring the last good version from history...");
1126        record_failure(&mut status, "config: /os/config.json is corrupted");
1127        let restored = restore_last_good("/os/config.json", |text| {
1128            matches!(json::parse(text), Ok(JsonValue::Object(_)))
1129        });
1130        match restored {
1131            Some(text) => {
1132                if let Ok(JsonValue::Object(obj)) = json::parse(&text) {
1133                    if let Some(JsonValue::Object(system)) = obj.get("system") {
1134                        apply_system_section(system, &mut current_config, &mut status);
1135                    }
1136                }
1137                crate::warn!("[SYS] config: /os/config.json を履歴の正しい版に戻した");
1138            }
1139            None => {
1140                crate::warn!("[SYS] config: 戻せる版が無いので既定値を新しい版として保存する");
1141                if let Err(e) = save_config_internal(&current_config) {
1142                    record_failure(&mut status, e);
1143                }
1144            }
1145        }
1146    } else if !config_exists {
1147        crate::info!("[SYS] Config file not found, creating default /os/config.json");
1148        if let Err(e) = save_config_internal(&current_config) {
1149            record_failure(&mut status, e);
1150        }
1151    }
1152
1153    // --- colorsets JSON の埋め込みと初期自動生成 ---
1154    let json_default = include_str!("../../colorset/default.json");
1155    let json_earth = include_str!("../../colorset/earth.json");
1156    let json_dracula = include_str!("../../colorset/dracula.json");
1157    let json_nord = include_str!("../../colorset/nord.json");
1158    let json_sakura = include_str!("../../colorset/sakura.json");
1159
1160    for (path, body) in [
1161        ("/os/default.json", json_default),
1162        ("/os/earth.json", json_earth),
1163        ("/os/dracula.json", json_dracula),
1164        ("/os/nord.json", json_nord),
1165        ("/os/sakura.json", json_sakura),
1166        // デフォルトアースカラーを初期カラーセットに設定
1167        ("/os/colorset.json", json_default),
1168    ] {
1169        // 「読めなかった」ものを「無い」と誤認して上書きしないよう、
1170        // 本当に存在しないと確認できたときだけ作成する。
1171        match fs.read_file_checked(path) {
1172            Ok(None) => {
1173                if let Err(e) = fs.save_file(path, body.as_bytes(), "system,colorset") {
1174                    crate::error!("[SYS] config: failed to create {}: {}", path, e);
1175                    record_failure(&mut status, e);
1176                }
1177            }
1178            Ok(Some(_)) => {}
1179            Err(e) => {
1180                crate::error!("[SYS] config: {} could not be read: {}", path, e);
1181                record_failure(&mut status, e);
1182            }
1183        }
1184    }
1185
1186    let mut colorset_loaded = false;
1187    let colorset_read = match fs.read_file_checked("/os/colorset.json") {
1188        Ok(v) => v,
1189        Err(e) => {
1190            // 読めないカラーセットを .bak へ退避して既定で上書きすると、
1191            // 一時的な読み出し失敗でユーザーの配色を失う。触らずに返す。
1192            crate::error!("[SYS] config: /os/colorset.json could not be read: {}", e);
1193            record_failure(&mut status, e);
1194            return ConfigLoad {
1195                config: current_config,
1196                status,
1197            };
1198        }
1199    };
1200    if let Some((_, colorset_content)) = colorset_read {
1201        match core::str::from_utf8(&colorset_content) {
1202            Err(_) => {
1203                crate::error!("[SYS] config: /os/colorset.json is not valid UTF-8");
1204                record_failure(&mut status, "colorset: not valid UTF-8");
1205            }
1206            Ok(colorset_str) => match load_colorset_from_json(colorset_str, &mut current_config.theme) {
1207                Ok(()) => {
1208                    if let Err(e) =
1209                        load_colorset_from_json(colorset_str, &mut current_config.custom_theme)
1210                    {
1211                        record_failure(&mut status, e);
1212                    }
1213                    colorset_loaded = true;
1214                }
1215                Err(e) => record_failure(&mut status, e),
1216            },
1217        }
1218    }
1219
1220    if !colorset_loaded {
1221        // 【2026-11-11】設定と同じく、版の履歴の中で一番新しい正しく読める版に戻す(`.bak` は作らない)。
1222        crate::error!("[SYS] /os/colorset.json is corrupted! Restoring the last good version from history...");
1223        record_failure(&mut status, "colorset: /os/colorset.json is corrupted");
1224        let restored = restore_last_good("/os/colorset.json", |text| {
1225            let mut probe = current_config.theme;
1226            load_colorset_from_json(text, &mut probe).is_ok()
1227        });
1228        if let Some(text) = restored {
1229            if load_colorset_from_json(&text, &mut current_config.theme).is_ok()
1230                && load_colorset_from_json(&text, &mut current_config.custom_theme).is_ok()
1231            {
1232                crate::warn!("[SYS] config: /os/colorset.json を履歴の正しい版に戻した");
1233                return ConfigLoad {
1234                    config: current_config,
1235                    status,
1236                };
1237            }
1238        }
1239        // 戻せる版が無い: 既定のカラーセットを新しい版として保存する。
1240        if let Err(e) = fs.save_file("/os/colorset.json", json_default.as_bytes(), "system,colorset")
1241        {
1242            crate::error!("[SYS] config: failed to restore default colorset: {}", e);
1243            record_failure(&mut status, e);
1244        }
1245        // 埋め込みの既定カラーセットは常に正しい前提だが、万一壊れていれば
1246        // それも報告する(黙って既定色のままにしない)。
1247        if let Err(e) = load_colorset_from_json(json_default, &mut current_config.theme) {
1248            record_failure(&mut status, e);
1249        }
1250        if let Err(e) = load_colorset_from_json(json_default, &mut current_config.custom_theme) {
1251            record_failure(&mut status, e);
1252        }
1253    }
1254
1255    ConfigLoad {
1256        config: current_config,
1257        status,
1258    }
1259}
1260
1261/// 保存しようとしている設定が妥当かどうかを検査する。
1262///
1263/// 異常値のまま書き出すと、次回起動時に「なぜか設定が効かない」状態に
1264/// なってしまうため、**書き込む前に**弾いて呼び出し側へ返す。
1265pub fn validate_config(config: &OsConfig) -> Result<(), &'static str> {
1266    if config.theme_name.is_empty() {
1267        return Err("config: theme_name is empty");
1268    }
1269    for name in config.font_names.iter() {
1270        if name.is_empty() {
1271            return Err("config: font name is empty");
1272        }
1273    }
1274    Ok(())
1275}
1276
1277/// 設定を保存する。呼び出し側は**戻り値を必ず確認すること**
1278/// (保存できていないのに「保存しました」と表示しないため)。
1279pub fn save_config(
1280    layout: KeyboardLayout,
1281    theme_name: &str,
1282    font_names: &[String],
1283    enable_sound: bool,
1284    swap_caps_ctrl: bool,
1285    auto_dhcp: bool,
1286    enable_custom_colors: bool,
1287) -> Result<(), &'static str> {
1288    let current_custom = get_config().custom_theme;
1289    save_config_with_wifi(
1290        layout,
1291        theme_name,
1292        font_names,
1293        enable_sound,
1294        swap_caps_ctrl,
1295        auto_dhcp,
1296        "",
1297        "",
1298        &current_custom,
1299        enable_custom_colors,
1300    )
1301}
1302
1303/// 設定を WiFi 認証情報つきで保存する。
1304///
1305/// 異常な引数(空のテーマ名/空のフォント名/4 件以上のフォント指定)は
1306/// **1 バイトも書き込まずに** `Err` を返す。従来は 4 件目以降を黙って捨て、
1307/// 空文字も素通ししていた。
1308#[allow(clippy::too_many_arguments)]
1309pub fn save_config_with_wifi(
1310    layout: KeyboardLayout,
1311    theme_name: &str,
1312    font_names: &[String],
1313    enable_sound: bool,
1314    swap_caps_ctrl: bool,
1315    auto_dhcp: bool,
1316    wifi_ssid: &str,
1317    wifi_password: &str,
1318    custom_theme: &ThemeConfig,
1319    enable_custom_colors: bool,
1320) -> Result<(), &'static str> {
1321    if font_names.is_empty() {
1322        return Err("config: no font specified");
1323    }
1324    if font_names.len() > 3 {
1325        crate::error!(
1326            "[SYS] config: {} font names given (max 3)",
1327            font_names.len()
1328        );
1329        return Err("config: too many font names");
1330    }
1331
1332    let mut config = OsConfig {
1333        keyboard_layout: layout,
1334        theme_name: String::from(theme_name),
1335        custom_theme: *custom_theme,
1336        enable_custom_colors,
1337        // 定期スナップショットの予定は Storage タブ(`set_snapshot_schedule`)で変える。ここでは今の値を保つ。
1338        snapshot_schedule: current_snapshot_schedule(),
1339        ..Default::default()
1340    };
1341    for (i, n) in font_names.iter().enumerate() {
1342        config.font_names[i] = n.clone();
1343    }
1344    config.enable_sound = enable_sound;
1345    config.swap_caps_ctrl = swap_caps_ctrl;
1346    config.auto_dhcp = auto_dhcp;
1347    config.wifi_ssid = String::from(wifi_ssid);
1348    config.wifi_password = String::from(wifi_password);
1349
1350    if enable_custom_colors {
1351        config.theme = *custom_theme;
1352    } else {
1353        for t in PRESET_THEMES {
1354            if t.name == theme_name {
1355                config.theme = *t;
1356                break;
1357            }
1358        }
1359    }
1360
1361    validate_config(&config)?;
1362    save_config_internal(&config)
1363}
1364
1365/// 読み込み済みの設定の定期スナップショットの予定(未読み込みなら既定)。設定を読み込み直さない。
1366fn current_snapshot_schedule() -> crate::kernel::snapshot_schedule::SnapshotSchedule {
1367    unsafe { (*core::ptr::addr_of!(GLOBAL_CONFIG)).as_ref().map(|c| c.snapshot_schedule).unwrap_or_default() }
1368}
1369
1370/// 定期スナップショットの予定を変えて保存する(設定アプリの Storage タブ)。今の設定のほかの値はそのまま。
1371pub fn set_snapshot_schedule(s: crate::kernel::snapshot_schedule::SnapshotSchedule) -> Result<(), &'static str> {
1372    if !s.is_valid() {
1373        return Err("config: snapshot schedule out of range");
1374    }
1375    let mut cfg = get_config().clone();
1376    cfg.snapshot_schedule = s;
1377    save_config_internal(&cfg)?;
1378    unsafe {
1379        if let Some(c) = (*core::ptr::addr_of_mut!(GLOBAL_CONFIG)).as_mut() {
1380            c.snapshot_schedule = s;
1381        }
1382    }
1383    Ok(())
1384}
1385
1386/// 壊れたファイルを、版の履歴の中で一番新しい「`is_good` が真になる版」に戻す(新しい版として保存する。
1387/// Git の revert と同じく履歴は消さない)。戻せたらその中身を返す(2026-11-11)。
1388fn restore_last_good(path: &str, is_good: impl Fn(&str) -> bool) -> Option<alloc::string::String> {
1389    let fs = fs::get_fs();
1390    let versions = fs.list_versions(path).ok()?;
1391    // 先頭は今の(壊れた)版なので飛ばす。
1392    for v in versions.iter().skip(1) {
1393        if v.deleted {
1394            continue;
1395        }
1396        let Ok(Some((_, data))) = fs.read_version(path, v.generation) else { continue };
1397        let Ok(text) = core::str::from_utf8(&data) else { continue };
1398        if is_good(text) {
1399            if let Err(e) = fs.restore_version(path, v.generation) {
1400                crate::error!("[SYS] config: {} を世代 {} に戻せなかった: {}", path, v.generation, e);
1401                return None;
1402            }
1403            return Some(alloc::string::String::from(text));
1404        }
1405    }
1406    None
1407}
1408
1409/// 設定を JSON 化して `/os/config.json` へ書き出す。
1410/// **書き込み失敗はそのまま呼び出し側へ返す**(従来は `let _ =` で捨てていた)。
1411pub fn save_config_internal(config: &OsConfig) -> Result<(), &'static str> {
1412    let mut repeat_obj = BTreeMap::new();
1413    unsafe {
1414        repeat_obj.insert(
1415            String::from("first_delay_ms"),
1416            JsonValue::Number(crate::REPEAT_PARAMS.first_delay_ms as f64),
1417        );
1418        repeat_obj.insert(
1419            String::from("first_interval_ms"),
1420            JsonValue::Number(crate::REPEAT_PARAMS.first_interval_ms as f64),
1421        );
1422        repeat_obj.insert(
1423            String::from("second_repeat_count"),
1424            JsonValue::Number(crate::REPEAT_PARAMS.second_repeat_count as f64),
1425        );
1426        repeat_obj.insert(
1427            String::from("second_delay_ms"),
1428            JsonValue::Number(crate::REPEAT_PARAMS.second_delay_ms as f64),
1429        );
1430        repeat_obj.insert(
1431            String::from("second_interval_ms"),
1432            JsonValue::Number(crate::REPEAT_PARAMS.second_interval_ms as f64),
1433        );
1434    }
1435
1436    let mut custom_obj = BTreeMap::new();
1437    custom_obj.insert(
1438        String::from("desktop_bg"),
1439        JsonValue::Number(config.custom_theme.desktop_bg as f64),
1440    );
1441    custom_obj.insert(
1442        String::from("terminal_bg"),
1443        JsonValue::Number(config.custom_theme.terminal_bg as f64),
1444    );
1445    custom_obj.insert(
1446        String::from("terminal_fg"),
1447        JsonValue::Number(config.custom_theme.terminal_fg as f64),
1448    );
1449    custom_obj.insert(
1450        String::from("active_window_border"),
1451        JsonValue::Number(config.custom_theme.active_window_border as f64),
1452    );
1453    custom_obj.insert(
1454        String::from("non_active_window_border"),
1455        JsonValue::Number(config.custom_theme.non_active_window_border as f64),
1456    );
1457    custom_obj.insert(
1458        String::from("window_title_bar"),
1459        JsonValue::Number(config.custom_theme.window_title_bar as f64),
1460    );
1461    custom_obj.insert(
1462        String::from("app_bg"),
1463        JsonValue::Number(config.custom_theme.app_bg as f64),
1464    );
1465    custom_obj.insert(
1466        String::from("app_fg"),
1467        JsonValue::Number(config.custom_theme.app_fg as f64),
1468    );
1469    custom_obj.insert(
1470        String::from("button_bg"),
1471        JsonValue::Number(config.custom_theme.button_bg as f64),
1472    );
1473    custom_obj.insert(
1474        String::from("button_fg"),
1475        JsonValue::Number(config.custom_theme.button_fg as f64),
1476    );
1477    custom_obj.insert(
1478        String::from("button_active_bg"),
1479        JsonValue::Number(config.custom_theme.button_active_bg as f64),
1480    );
1481    custom_obj.insert(
1482        String::from("button_active_fg"),
1483        JsonValue::Number(config.custom_theme.button_active_fg as f64),
1484    );
1485    custom_obj.insert(
1486        String::from("focus_highlight"),
1487        JsonValue::Number(config.custom_theme.focus_highlight as f64),
1488    );
1489
1490    let mut system_obj = BTreeMap::new();
1491    let layout_str = match config.keyboard_layout {
1492        KeyboardLayout::Us => "us",
1493        KeyboardLayout::Jis => "jis",
1494    };
1495    system_obj.insert(
1496        String::from("keyboard_layout"),
1497        JsonValue::String(String::from(layout_str)),
1498    );
1499    system_obj.insert(
1500        String::from("theme_name"),
1501        JsonValue::String(config.theme_name.clone()),
1502    );
1503    system_obj.insert(
1504        String::from("font_names"),
1505        JsonValue::Array(
1506            config
1507                .font_names
1508                .iter()
1509                .map(|n| JsonValue::String(n.clone()))
1510                .collect(),
1511        ),
1512    );
1513    system_obj.insert(
1514        String::from("enable_sound"),
1515        JsonValue::Bool(config.enable_sound),
1516    );
1517    system_obj.insert(
1518        String::from("swap_caps_ctrl"),
1519        JsonValue::Bool(config.swap_caps_ctrl),
1520    );
1521    system_obj.insert(String::from("auto_dhcp"), JsonValue::Bool(config.auto_dhcp));
1522    system_obj.insert(
1523        String::from("enable_custom_colors"),
1524        JsonValue::Bool(config.enable_custom_colors),
1525    );
1526    system_obj.insert(
1527        String::from("wifi_ssid"),
1528        JsonValue::String(config.wifi_ssid.clone()),
1529    );
1530    system_obj.insert(
1531        String::from("wifi_password"),
1532        JsonValue::String(config.wifi_password.clone()),
1533    );
1534    system_obj.insert(String::from("keyrepeat"), JsonValue::Object(repeat_obj));
1535    let mut sched_obj = BTreeMap::new();
1536    sched_obj.insert(String::from("enabled"), JsonValue::Bool(config.snapshot_schedule.enabled));
1537    sched_obj.insert(String::from("weekday"), JsonValue::Number(f64::from(config.snapshot_schedule.weekday)));
1538    sched_obj.insert(String::from("hour"), JsonValue::Number(f64::from(config.snapshot_schedule.hour)));
1539    sched_obj.insert(String::from("minute"), JsonValue::Number(f64::from(config.snapshot_schedule.minute)));
1540    system_obj.insert(String::from("snapshot_schedule"), JsonValue::Object(sched_obj));
1541    system_obj.insert(String::from("custom_colors"), JsonValue::Object(custom_obj));
1542
1543    let mut root_obj = BTreeMap::new();
1544    root_obj.insert(String::from("system"), JsonValue::Object(system_obj));
1545
1546    let json_str = json::to_string(&JsonValue::Object(root_obj));
1547    let fs = fs::get_fs();
1548    if let Err(e) = fs.save_file("/os/config.json", json_str.as_bytes(), "system,config") {
1549        crate::error!("[SYS] config: failed to write /os/config.json: {}", e);
1550        return Err(e);
1551    }
1552    Ok(())
1553}