Skip to main content

atmos/apps/settings/
mod.rs

1//! OS 設定アプリ。
2//!
3//! テーマ(配色 JSON、`colorset/`)・キーボードレイアウト・フォントフォールバック順・
4//! キーリピート設定・WiFi 接続(SSID/パスワード)等を [`crate::kernel::config`] 経由で
5//! 読み書きする。設定変更は即時 SylFS へ永続化される。
6// src/settings.rs - OS Settings App for AtmOS
7#![allow(dead_code)]
8
9extern crate alloc;
10use alloc::string::String;
11use alloc::string::ToString;
12
13use crate::kernel::config::{self, KeyboardLayout};
14use crate::kernel::snapshot_schedule::{self, SnapshotSchedule};
15use crate::kernel::draw::{Color, Screen};
16use crate::kernel::text_box::TextBox;
17use crate::kernel::window_mgr::App;
18use crate::os_lib::json::{self};
19
20static ICON_APPEARANCE: &[u8] = include_bytes!("../../../icons/ic_fluent_color_20_regular.svg");
21static ICON_KEYBOARD: &[u8] = include_bytes!("../../../icons/ic_fluent_keyboard_20_regular.svg");
22static ICON_SYSTEM: &[u8] = include_bytes!("../../../icons/ic_fluent_settings_20_regular.svg");
23static ICON_NETWORK: &[u8] = include_bytes!("../../../icons/ic_fluent_settings_20_regular.svg");
24
25pub struct SettingsApp {
26    selected_layout: KeyboardLayout,
27    selected_theme: String,
28    /// フォントのフォールバック順([0]=プライマリ)。設定アプリで3段セレクトする。
29    selected_fonts: [String; 3],
30    selected_sound: bool,
31    repeat_first_delay: u32,
32    repeat_first_interval: u32,
33    repeat_second_count: u32,
34    repeat_second_delay: u32,
35    repeat_second_interval: u32,
36    selected_caps_ctrl: bool,
37    last_win_w: u32,
38    last_win_h: u32,
39    active_tab_idx: usize,
40    selected_auto_dhcp: bool,
41    focused_item_idx: Option<usize>,
42    // Network タブ
43    ssid_box: TextBox,
44    password_box: TextBox,
45    wifi_focused: u8, // 0=none 1=ssid 2=password
46    wifi_status_msg: String,
47    wifi_connecting: bool,
48    /// 保存・適用の結果表示。失敗を黙って捨てず、必ずユーザーへ見せる。
49    status_msg: String,
50    /// `status_msg` が失敗の通知かどうか(表示色の切り替え用)。
51    status_is_error: bool,
52    // 詳細色編集用
53    custom_theme: config::ThemeConfig,
54    custom_edit_idx: usize,
55    enable_custom_colors: bool,
56    available_themes: alloc::vec::Vec<alloc::string::String>,
57    // Storage タブ(週 1 回の定期スナップショット)
58    snapshot_sched: SnapshotSchedule,
59    /// Storage タブの説明の行と、それを作った時刻(ms)。描画のたびに FS の錠を取ってスナップショットの表を
60    /// 読まないよう、2 秒ごとか操作の後だけ作り直す(2026-11-12)。
61    storage_info: Option<([String; 3], u64)>,
62}
63
64impl Default for SettingsApp {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl SettingsApp {
71    pub fn new() -> Self {
72        let current_config = config::get_config();
73
74        let (fd, fi, sc, sd, si) = unsafe {
75            (
76                crate::REPEAT_PARAMS.first_delay_ms,
77                crate::REPEAT_PARAMS.first_interval_ms,
78                crate::REPEAT_PARAMS.second_repeat_count,
79                crate::REPEAT_PARAMS.second_delay_ms,
80                crate::REPEAT_PARAMS.second_interval_ms,
81            )
82        };
83
84        let wifi_status = if crate::kernel::wifi::is_connected() {
85            let ip = crate::kernel::wifi::get_ip();
86            alloc::format!("Connected — {}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
87        } else {
88            String::from("Not connected")
89        };
90
91        let mut available_themes = alloc::vec![
92            String::from("default"),
93            String::from("earth"),
94            String::from("dracula"),
95            String::from("nord"),
96            String::from("sakura"),
97        ];
98
99        // ディスク上の /os/*.json を走査して追加する
100        let fs = crate::kernel::fs::get_fs();
101        let files = fs.list_dir("/os/");
102        for f in files {
103            let name = f.get_filename();
104            if name.ends_with(".json") && name != "/os/config.json" && name != "/os/colorset.json" {
105                if let Some(_pos) = name.rfind('/') {
106                    let tname = name.split('/').next_back().unwrap_or("");
107                    let tname = tname.trim_end_matches(".json").to_string();
108                    if !available_themes.contains(&tname) {
109                        available_themes.push(tname);
110                    }
111                }
112            }
113        }
114
115        Self {
116            selected_layout: current_config.keyboard_layout,
117            selected_theme: current_config.theme_name.clone(),
118            selected_fonts: current_config.font_names.clone(),
119            selected_sound: current_config.enable_sound,
120            repeat_first_delay: fd,
121            repeat_first_interval: fi,
122            repeat_second_count: sc,
123            repeat_second_delay: sd,
124            repeat_second_interval: si,
125            selected_caps_ctrl: current_config.swap_caps_ctrl,
126            last_win_w: 480,
127            last_win_h: 560,
128            active_tab_idx: 0,
129            selected_auto_dhcp: current_config.auto_dhcp,
130            focused_item_idx: None,
131            ssid_box: TextBox::with_text(&current_config.wifi_ssid),
132            password_box: TextBox::with_text(&current_config.wifi_password),
133            wifi_focused: 0,
134            wifi_status_msg: wifi_status,
135            wifi_connecting: false,
136            status_msg: String::new(),
137            status_is_error: false,
138            custom_theme: current_config.custom_theme,
139            custom_edit_idx: 0,
140            enable_custom_colors: current_config.enable_custom_colors,
141            available_themes,
142            snapshot_sched: current_config.snapshot_schedule,
143            storage_info: None,
144        }
145    }
146
147    fn get_item_count(&self) -> usize {
148        let tabs = self.tabs();
149        if self.active_tab_idx >= tabs.len() {
150            return 0;
151        }
152        match tabs[self.active_tab_idx].as_str() {
153            "ColorTheme" => {
154                self.available_themes.len() + 1 + 1 // テーマ数 + チェックボックス(1) + Apply(1)
155            }
156            "CustomColor" => {
157                39 + 1 // 13色 * 3チャンネル(39) + Applyボタン(1)
158            }
159            "FontOrder" => 3 + 1,
160            "Keyboard" => 15,
161            "System" => 5,
162            "Storage" => 10,
163            _ => 3,
164        }
165    }
166
167    fn draw_focus_rect(
168        &self,
169        screen: &Screen,
170        x: u32,
171        y: u32,
172        w: u32,
173        h: u32,
174        is_focused: bool,
175        focus_color: Color,
176    ) {
177        if is_focused {
178            screen.boxfill(
179                x.saturating_sub(2),
180                y.saturating_sub(2),
181                x + w + 2,
182                y + h + 2,
183                focus_color,
184            );
185        }
186    }
187
188    fn draw_text_field(
189        &self,
190        screen: &Screen,
191        x: u32,
192        y: u32,
193        w: u32,
194        tb: &TextBox,
195        focused: bool,
196        placeholder: &str,
197        mask: bool,
198    ) {
199        let t = &config::get_config().theme;
200        let border = if focused { t.active_window_border } else { t.browser_secondary };
201        let bg = if focused { t.browser_bg } else { t.ui_input_bg };
202        screen.boxfill(x, y, x + w, y + 28, Color(bg));
203        // border
204        screen.boxfill(x, y, x + w, y + 1, Color(border));
205        screen.boxfill(x, y + 27, x + w, y + 28, Color(border));
206        screen.boxfill(x, y, x + 1, y + 28, Color(border));
207        screen.boxfill(x + w - 1, y, x + w, y + 28, Color(border));
208
209        let display = if tb.text.is_empty() && !focused {
210            String::from(placeholder)
211        } else if mask {
212            tb.text.chars().map(|_| '*').collect()
213        } else {
214            tb.text.clone()
215        };
216
217        let text_color = if tb.text.is_empty() && !focused {
218            t.fn_bar_dim_fg
219        } else {
220            t.login_text_fg
221        };
222        screen.draw_string_vector(x + 8, y + 7, &display, Color(text_color), 13);
223
224        // フォーカス中はカーソル位置に縦棒カーソル(ターミナル共通色 0xFF756CE0)
225        if focused {
226            let mut prefix = String::new();
227            if mask {
228                for _ in 0..tb.cursor_pos {
229                    prefix.push('*');
230                }
231            } else {
232                prefix = tb.text.chars().take(tb.cursor_pos).collect();
233            }
234            let pw = crate::kernel::vector_font::get_vector_string_width(&prefix, 13);
235            let cursor_x = x + 8 + pw;
236            screen.boxfill(
237                cursor_x,
238                y + 6,
239                cursor_x + 1,
240                y + 22,
241                Color(crate::kernel::ime::cursor_color()),
242            );
243        }
244    }
245
246    /// 設定を適用・保存する。
247    ///
248    /// **失敗を握り潰さない**: 以前は保存結果を捨てて常に完了音を鳴らし
249    /// 「Config applied and saved!」と表示していたため、書き込めていなくても
250    /// ユーザーには成功に見えていた。成功したときだけ成功を名乗る。
251    fn apply_and_save(&mut self) {
252        match self.try_apply_and_save() {
253            Ok(()) => {
254                self.status_msg = String::from("Saved.");
255                self.status_is_error = false;
256                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
257                crate::info!("[SYS] Settings: Config applied and saved!");
258            }
259            Err(e) => {
260                self.status_msg = alloc::format!("Save failed: {}", e);
261                self.status_is_error = true;
262                crate::error!("[SYS] Settings: failed to apply/save config: {}", e);
263            }
264        }
265    }
266
267    fn try_apply_and_save(&self) -> Result<(), &'static str> {
268        // 定期スナップショットの予定(Storage タブ)。`save_config_with_wifi` は読み込み済みの値を保つので、先に入れる。
269        if !self.snapshot_sched.is_valid() {
270            return Err("snapshot schedule out of range");
271        }
272        unsafe {
273            if let Some(c) = (*core::ptr::addr_of_mut!(config::GLOBAL_CONFIG)).as_mut() {
274                c.snapshot_schedule = self.snapshot_sched;
275            }
276        }
277        unsafe {
278            crate::REPEAT_PARAMS.first_delay_ms = self.repeat_first_delay;
279            crate::REPEAT_PARAMS.first_interval_ms = self.repeat_first_interval;
280            crate::REPEAT_PARAMS.second_repeat_count = self.repeat_second_count;
281            crate::REPEAT_PARAMS.second_delay_ms = self.repeat_second_delay;
282            crate::REPEAT_PARAMS.second_interval_ms = self.repeat_second_interval;
283        }
284
285        config::save_config_with_wifi(
286            self.selected_layout,
287            &self.selected_theme,
288            &self.selected_fonts,
289            self.selected_sound,
290            self.selected_caps_ctrl,
291            self.selected_auto_dhcp,
292            &self.ssid_box.text,
293            &self.password_box.text,
294            &self.custom_theme,
295            self.enable_custom_colors,
296        )?;
297
298        if self.enable_custom_colors {
299            let mut obj = alloc::collections::BTreeMap::new();
300            obj.insert(String::from("desktop_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.desktop_bg)));
301            obj.insert(String::from("terminal_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.terminal_bg)));
302            obj.insert(String::from("terminal_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.terminal_fg)));
303            obj.insert(String::from("active_window_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.active_window_border)));
304            obj.insert(String::from("non_active_window_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.non_active_window_border)));
305            obj.insert(String::from("window_title_bar"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.window_title_bar)));
306            obj.insert(String::from("window_title_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.window_title_fg)));
307            obj.insert(String::from("app_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.app_bg)));
308            obj.insert(String::from("app_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.app_fg)));
309            obj.insert(String::from("button_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.button_bg)));
310            obj.insert(String::from("button_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.button_fg)));
311            obj.insert(String::from("button_active_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.button_active_bg)));
312            obj.insert(String::from("button_active_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.button_active_fg)));
313            obj.insert(String::from("focus_highlight"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.focus_highlight)));
314            obj.insert(String::from("mouse_cursor"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.mouse_cursor)));
315            obj.insert(String::from("mouse_stroke"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.mouse_stroke)));
316            obj.insert(String::from("login_screen_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_screen_bg)));
317            obj.insert(String::from("login_dialog_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_dialog_bg)));
318            obj.insert(String::from("login_dialog_shadow"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_dialog_shadow)));
319            obj.insert(String::from("login_dialog_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_dialog_border)));
320            obj.insert(String::from("login_text_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_text_fg)));
321            obj.insert(String::from("login_field_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_field_bg)));
322            obj.insert(String::from("login_field_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.login_field_border)));
323            obj.insert(String::from("sysmon_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_bg)));
324            obj.insert(String::from("sysmon_header_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_header_bg)));
325            obj.insert(String::from("sysmon_accent"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_accent)));
326            obj.insert(String::from("sysmon_text"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_text)));
327            obj.insert(String::from("sysmon_value"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_value)));
328            obj.insert(String::from("sysmon_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.sysmon_border)));
329            obj.insert(String::from("tab_area_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.tab_area_bg)));
330            obj.insert(String::from("tab_area_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.tab_area_border)));
331            obj.insert(String::from("tab_active_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.tab_active_bg)));
332            obj.insert(String::from("tab_active_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.tab_active_fg)));
333            obj.insert(String::from("tab_inactive_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.tab_inactive_fg)));
334            obj.insert(String::from("fn_bar_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_bg)));
335            obj.insert(String::from("fn_bar_cell_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_cell_bg)));
336            obj.insert(String::from("fn_bar_key_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_key_bg)));
337            obj.insert(String::from("fn_bar_key_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_key_fg)));
338            obj.insert(String::from("fn_bar_text_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_text_fg)));
339            obj.insert(String::from("fn_bar_dim_fg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_dim_fg)));
340            obj.insert(String::from("fn_bar_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.fn_bar_border)));
341            obj.insert(String::from("ime_bg"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.ime_bg)));
342            obj.insert(String::from("ime_border"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.ime_border)));
343            obj.insert(String::from("ime_text"), json::JsonValue::String(alloc::format!("0x{:08X}", self.custom_theme.ime_text)));
344
345            let json_str = json::to_string(&json::JsonValue::Object(obj));
346            let fs = crate::kernel::fs::get_fs();
347            fs.save_file("/os/colorset.json", json_str.as_bytes(), "system,colorset")?;
348        }
349
350        config::reload_and_apply()
351    }
352
353    fn get_color_rgb(c: u32) -> (u8, u8, u8) {
354        (
355            ((c >> 16) & 0xFF) as u8,
356            ((c >> 8) & 0xFF) as u8,
357            (c & 0xFF) as u8,
358        )
359    }
360
361    fn make_color_u32(r: u8, g: u8, b: u8) -> u32 {
362        0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
363    }
364
365    fn get_custom_color_by_idx(&self, idx: usize) -> u32 {
366        match idx {
367            0 => self.custom_theme.desktop_bg,
368            1 => self.custom_theme.terminal_bg,
369            2 => self.custom_theme.terminal_fg,
370            3 => self.custom_theme.active_window_border,
371            4 => self.custom_theme.window_title_bar,
372            5 => self.custom_theme.app_bg,
373            6 => self.custom_theme.app_fg,
374            7 => self.custom_theme.non_active_window_border,
375            8 => self.custom_theme.mouse_cursor,
376            9 => self.custom_theme.login_screen_bg,
377            10 => self.custom_theme.sysmon_bg,
378            11 => self.custom_theme.tab_area_bg,
379            _ => self.custom_theme.fn_bar_bg,
380        }
381    }
382
383    fn set_custom_color_by_idx(&mut self, idx: usize, color: u32) {
384        match idx {
385            0 => self.custom_theme.desktop_bg = color,
386            1 => self.custom_theme.terminal_bg = color,
387            2 => self.custom_theme.terminal_fg = color,
388            3 => self.custom_theme.active_window_border = color,
389            4 => self.custom_theme.window_title_bar = color,
390            5 => self.custom_theme.app_bg = color,
391            6 => self.custom_theme.app_fg = color,
392            7 => self.custom_theme.non_active_window_border = color,
393            8 => self.custom_theme.mouse_cursor = color,
394            9 => self.custom_theme.login_screen_bg = color,
395            10 => self.custom_theme.sysmon_bg = color,
396            11 => self.custom_theme.tab_area_bg = color,
397            _ => self.custom_theme.fn_bar_bg = color,
398        }
399    }
400
401    fn adjust_channel(val: u8, dir: i32) -> u8 {
402        let step = 16i32;
403        let new_val = (val as i32 + dir * step).clamp(0, 255);
404        new_val as u8
405    }
406
407    fn get_custom_color_name(idx: usize) -> &'static str {
408        static CUSTOM_COLOR_NAMES: &[&str] = &[
409            "Desktop BG",
410            "Terminal BG",
411            "Terminal FG",
412            "Active Border",
413            "Title Bar",
414            "App BG",
415            "App FG",
416            "Inactive Border",
417            "Mouse Cursor",
418            "Login Screen BG",
419            "System Monitor BG",
420            "Tab Area BG",
421            "Function Bar BG",
422        ];
423        if idx < CUSTOM_COLOR_NAMES.len() {
424            CUSTOM_COLOR_NAMES[idx]
425        } else {
426            ""
427        }
428    }
429
430    fn get_theme_preview_colors(name: &str) -> (u32, u32, u32) {
431        let fs = crate::kernel::fs::get_fs();
432        let path = alloc::format!("/os/{}.json", name);
433        let mut desktop_bg = 0xFF2EAE3D; // 初期フォールバック
434        let mut terminal_bg = 0xFFF9F5EB;
435        let mut active_border = 0xFFE14D2A;
436
437        let content_opt = match fs.read_file_checked(&path) {
438            Ok(v) => v,
439            Err(e) => {
440                crate::warn!("[SETTINGS] テーマファイル '{}' の読み込みに失敗しました: {}", path, e);
441                None
442            }
443        };
444        if let Some((_, content)) = content_opt {
445            if let Ok(content_str) = core::str::from_utf8(&content) {
446                if let Ok(json::JsonValue::Object(obj)) = json::parse(content_str) {
447                    if let Some(v) = obj.get("desktop_bg") {
448                        if let Some(c) = config::parse_hex_color(v) { desktop_bg = c; }
449                    }
450                    if let Some(v) = obj.get("terminal_bg") {
451                        if let Some(c) = config::parse_hex_color(v) { terminal_bg = c; }
452                    }
453                    if let Some(v) = obj.get("active_window_border") {
454                        if let Some(c) = config::parse_hex_color(v) { active_border = c; }
455                    }
456                }
457            }
458        }
459        (desktop_bg, terminal_bg, active_border)
460    }
461
462    fn start_wifi_connect(&mut self) {
463        let ssid = self.ssid_box.text.clone();
464        let pass = self.password_box.text.clone();
465        if ssid.is_empty() {
466            self.wifi_status_msg = String::from("Error: SSID is empty");
467            return;
468        }
469        self.wifi_status_msg = String::from("Connecting...");
470        self.wifi_connecting = true;
471        let ok = crate::kernel::wifi::connect(&ssid, &pass);
472        if ok {
473            let ip = crate::kernel::wifi::get_ip();
474            self.wifi_status_msg =
475                alloc::format!("Connected — {}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3]);
476            self.apply_and_save();
477        } else {
478            self.wifi_status_msg = String::from("Failed to connect");
479        }
480        self.wifi_connecting = false;
481    }
482
483    fn cycle_font(&mut self, slot: usize, dir: i32) {
484        if slot >= 3 {
485            return;
486        }
487        let list = crate::kernel::vector_font::AVAILABLE_FONTS;
488        let n = list.len() as i32;
489        if n == 0 {
490            return;
491        }
492        let cur = list
493            .iter()
494            .position(|f| *f == self.selected_fonts[slot])
495            .unwrap_or(0) as i32;
496        let next = ((cur + dir) % n + n) % n;
497        self.selected_fonts[slot] = String::from(list[next as usize]);
498    }
499
500    /// 指定テーマのカラーセット `/os/<name>.json` を `/os/colorset.json` へ複製し、
501    /// 設定を再読み込みする。読み出し・書き込み・再読み込みのどの失敗も
502    /// 呼び出し側へ返す(従来は 3 段すべて `let _ =` で捨てていたため、
503    /// テーマを選んでも色が変わらない理由が分からなかった)。
504    fn apply_theme_colorset(&mut self, theme_name: &str) -> Result<(), &'static str> {
505        let fs = crate::kernel::fs::get_fs();
506        let src_path = alloc::format!("/os/{}.json", theme_name);
507        let (_, data) = fs
508            .read_file_checked(&src_path)?
509            .ok_or("theme colorset file not found")?;
510        fs.save_file("/os/colorset.json", &data, "system,colorset")?;
511        config::reload_and_apply()
512    }
513
514    /// テーマ選択(キーボード操作・マウス操作の共通処理)。
515    fn select_theme(&mut self, theme_name: &str) {
516        self.selected_theme = String::from(theme_name);
517        self.enable_custom_colors = false;
518
519        match self.apply_theme_colorset(theme_name) {
520            Ok(()) => {
521                self.status_msg = String::new();
522                self.status_is_error = false;
523            }
524            Err(e) => {
525                self.status_msg = alloc::format!("Theme change failed: {}", e);
526                self.status_is_error = true;
527                crate::error!("[SYS] Settings: theme '{}' not applied: {}", theme_name, e);
528            }
529        }
530        self.custom_theme = config::get_config().custom_theme;
531
532        let mut wm = crate::kernel::window_mgr::get_instance();
533        wm.dirty = true;
534    }
535
536    /// カスタムカラーの有効・無効を切り替える(キーボード・マウス共通処理)。
537    fn toggle_custom_colors(&mut self) {
538        self.enable_custom_colors = !self.enable_custom_colors;
539        unsafe {
540            if let Some(ref mut conf) = config::GLOBAL_CONFIG {
541                conf.enable_custom_colors = self.enable_custom_colors;
542                if self.enable_custom_colors {
543                    conf.theme = self.custom_theme;
544                }
545            }
546        }
547        if !self.enable_custom_colors {
548            // プリセットへ戻すので、選択中テーマのカラーセットを再適用する。
549            let name = self.selected_theme.clone();
550            if let Err(e) = self.apply_theme_colorset(&name) {
551                self.status_msg = alloc::format!("Theme restore failed: {}", e);
552                self.status_is_error = true;
553                crate::error!("[SYS] Settings: theme '{}' not restored: {}", name, e);
554            }
555        }
556        let mut wm = crate::kernel::window_mgr::get_instance();
557        wm.dirty = true;
558    }
559
560    /// 定期スナップショットの予定を 1 段変える(`field`: 0=曜日 1=時 2=分(5 分刻み)、`dir`: ±1。端で一周する)。
561    fn step_schedule(&mut self, field: u8, dir: i32) {
562        self.storage_info = None;
563        let s = &mut self.snapshot_sched;
564        match field {
565            0 => s.weekday = ((i32::from(s.weekday) + dir).rem_euclid(7)) as u8,
566            1 => s.hour = ((i32::from(s.hour) + dir).rem_euclid(24)) as u8,
567            _ => s.minute = ((i32::from(s.minute) + dir * 5).rem_euclid(60)) as u8,
568        }
569    }
570
571    /// 今すぐスナップショットを取って回収する(予定を待たずに整理したいとき)。
572    fn snapshot_now(&mut self) {
573        self.storage_info = None;
574        let _guard = crate::kernel::fs::FS_LOCK.lock();
575        let fs = crate::kernel::fs::get_fs();
576        match fs.create_snapshot("manual") {
577            Ok(g) => {
578                let freed = fs.collect_garbage().map(|r| r.freed).unwrap_or(0);
579                self.status_msg = alloc::format!("Snapshot taken (generation {}), freed {} sectors.", g, freed);
580                self.status_is_error = false;
581            }
582            Err(e) => {
583                self.status_msg = alloc::format!("Snapshot failed: {}", e);
584                self.status_is_error = true;
585            }
586        }
587    }
588
589    /// Storage タブの説明の行(2 秒以内に作ったものがあればそれ)。
590    fn storage_info_cached(&mut self) -> [String; 3] {
591        let now = crate::kernel::timer::get_system_time_ms();
592        if let Some((lines, at)) = &self.storage_info {
593            if now.saturating_sub(*at) < 2_000 {
594                return lines.clone();
595            }
596        }
597        let lines = self.storage_info_lines();
598        self.storage_info = Some((lines.clone(), now));
599        lines
600    }
601
602    /// Storage タブの説明の行(次の予定・スナップショットの件数・最新)。
603    fn storage_info_lines(&self) -> [String; 3] {
604        let next = match crate::kernel::timer::get_unix_time() {
605            Some(now) if self.snapshot_sched.enabled => {
606                snapshot_schedule::format_jst(snapshot_schedule::next_occurrence(now, &self.snapshot_sched))
607            }
608            Some(_) => String::from("(disabled)"),
609            None => String::from("(clock not set yet)"),
610        };
611        let _guard = crate::kernel::fs::FS_LOCK.lock();
612        let fs = crate::kernel::fs::get_fs();
613        let snaps = fs.list_snapshots().unwrap_or_default();
614        let pinned = snaps.iter().filter(|s| s.pinned).count();
615        let latest = snaps
616            .last()
617            .map(|s| alloc::format!("{} (generation {}, {})", snapshot_schedule::format_jst(s.time), s.generation, s.name))
618            .unwrap_or_else(|| String::from("none"));
619        [
620            alloc::format!("Next snapshot: {}", next),
621            alloc::format!("Snapshots: {} (pinned {} / max {})", snaps.len(), pinned, fs.max_pins()),
622            alloc::format!("Latest: {}", latest),
623        ]
624    }
625
626    fn handle_action(&mut self, idx: usize) {
627        let tabs = self.tabs();
628        if self.active_tab_idx >= tabs.len() {
629            return;
630        }
631        match tabs[self.active_tab_idx].as_str() {
632            "ColorTheme" => {
633                let n_themes = self.available_themes.len();
634                if idx < n_themes {
635                    let theme_name = self.available_themes[idx].clone();
636                    self.select_theme(&theme_name);
637                } else if idx == n_themes {
638                    self.toggle_custom_colors();
639                } else {
640                    self.apply_and_save();
641                }
642            }
643            "CustomColor" => {
644                if idx < 39 {
645                    let color_idx = idx / 3;
646                    let chan_idx = idx % 3;
647                    let color_val = self.get_custom_color_by_idx(color_idx);
648                    let (mut r, mut g, mut b) = Self::get_color_rgb(color_val);
649                    match chan_idx {
650                        0 => r = Self::adjust_channel(r, 1),
651                        1 => g = Self::adjust_channel(g, 1),
652                        _ => b = Self::adjust_channel(b, 1),
653                    }
654                    let new_c = Self::make_color_u32(r, g, b);
655                    self.set_custom_color_by_idx(color_idx, new_c);
656                    if self.enable_custom_colors {
657                        unsafe {
658                            if let Some(ref mut conf) = config::GLOBAL_CONFIG {
659                                conf.custom_theme = self.custom_theme;
660                                conf.theme = self.custom_theme;
661                            }
662                        }
663                        let mut wm = crate::kernel::window_mgr::get_instance();
664                        wm.dirty = true;
665                    }
666                } else {
667                    self.apply_and_save();
668                }
669            }
670            "FontOrder" => {
671                if idx < 3 {
672                    self.cycle_font(idx, 1);
673                } else {
674                    self.apply_and_save();
675                }
676            }
677            "Keyboard" => match idx {
678                0 => self.selected_layout = KeyboardLayout::Jis,
679                1 => self.selected_layout = KeyboardLayout::Us,
680                2 => self.repeat_first_delay = self.repeat_first_delay.saturating_sub(50).max(50),
681                3 => self.repeat_first_delay = self.repeat_first_delay.saturating_add(50).min(2000),
682                4 => {
683                    self.repeat_first_interval = self.repeat_first_interval.saturating_sub(5).max(5)
684                }
685                5 => {
686                    self.repeat_first_interval =
687                        self.repeat_first_interval.saturating_add(5).min(500)
688                }
689                6 => self.repeat_second_count = self.repeat_second_count.saturating_sub(1),
690                7 => self.repeat_second_count = self.repeat_second_count.saturating_add(1).min(100),
691                8 => self.repeat_second_delay = self.repeat_second_delay.saturating_sub(50).max(50),
692                9 => {
693                    self.repeat_second_delay = self.repeat_second_delay.saturating_add(50).min(2000)
694                }
695                10 => {
696                    self.repeat_second_interval =
697                        self.repeat_second_interval.saturating_sub(5).max(5)
698                }
699                11 => {
700                    self.repeat_second_interval =
701                        self.repeat_second_interval.saturating_add(5).min(500)
702                }
703                12 => self.selected_caps_ctrl = true,
704                13 => self.selected_caps_ctrl = false,
705                14 => self.apply_and_save(),
706                _ => {}
707            },
708            "Storage" => match idx {
709                0 => {
710                    self.snapshot_sched.enabled = true;
711                    self.storage_info = None;
712                }
713                1 => {
714                    self.snapshot_sched.enabled = false;
715                    self.storage_info = None;
716                }
717                2 => self.step_schedule(0, -1),
718                3 => self.step_schedule(0, 1),
719                4 => self.step_schedule(1, -1),
720                5 => self.step_schedule(1, 1),
721                6 => self.step_schedule(2, -1),
722                7 => self.step_schedule(2, 1),
723                8 => self.snapshot_now(),
724                9 => self.apply_and_save(),
725                _ => {}
726            },
727            "System" => match idx {
728                0 => self.selected_sound = true,
729                1 => self.selected_sound = false,
730                2 => self.selected_auto_dhcp = true,
731                3 => self.selected_auto_dhcp = false,
732                4 => self.apply_and_save(),
733                _ => {}
734            },
735            _ => {}
736        }
737    }
738}
739
740impl App for SettingsApp {
741    fn name(&self) -> &str {
742        "settings"
743    }
744
745    fn tabs(&self) -> alloc::vec::Vec<alloc::string::String> {
746        if self.enable_custom_colors {
747            alloc::vec![
748                String::from("ColorTheme"),
749                String::from("CustomColor"),
750                String::from("FontOrder"),
751                String::from("Keyboard"),
752                String::from("System"),
753                String::from("Storage"),
754                String::from("Network"),
755            ]
756        } else {
757            alloc::vec![
758                String::from("ColorTheme"),
759                String::from("FontOrder"),
760                String::from("Keyboard"),
761                String::from("System"),
762                String::from("Storage"),
763                String::from("Network"),
764            ]
765        }
766    }
767
768    fn active_tab(&self) -> usize {
769        self.active_tab_idx
770    }
771
772    fn switch_tab(&mut self, idx: usize) {
773        let max_tabs = self.tabs().len();
774        self.active_tab_idx = if idx < max_tabs { idx } else { 0 };
775        self.focused_item_idx = None;
776        self.wifi_focused = 0;
777    }
778
779    fn draw(&mut self, screen: &Screen, win_x: u32, win_y: u32, win_w: u32, win_h: u32) {
780        self.last_win_w = win_w;
781        self.last_win_h = win_h;
782
783        let theme = &config::get_config().theme;
784        let bg = Color(theme.app_bg);
785        let fg = Color(theme.app_fg);
786        let btn_bg = Color(theme.button_bg);
787        let btn_fg = Color(theme.button_fg);
788        let btn_act_bg = Color(theme.button_active_bg);
789        let btn_act_fg = Color(theme.button_active_fg);
790        let focus_c = Color(theme.focus_highlight);
791
792        screen.boxfill(win_x, win_y, win_x + win_w, win_y + win_h, bg);
793
794        let tabs = self.tabs();
795        let tab_name = if self.active_tab_idx < tabs.len() {
796            tabs[self.active_tab_idx].as_str()
797        } else {
798            ""
799        };
800
801        let (tab_title, icon) = match tab_name {
802            "ColorTheme" => ("COLOR THEME SETTINGS", ICON_APPEARANCE),
803            "CustomColor" => ("CUSTOM COLOR CONFIG", ICON_APPEARANCE),
804            "FontOrder" => ("FONT FALLBACK ORDER", ICON_APPEARANCE),
805            "Keyboard" => ("KEYBOARD SETTINGS", ICON_KEYBOARD),
806            "System" => ("SYSTEM SETTINGS", ICON_SYSTEM),
807            "Storage" => ("STORAGE (WEEKLY SNAPSHOT)", ICON_SYSTEM),
808            _ => ("NETWORK SETTINGS", ICON_NETWORK),
809        };
810        screen.draw_svg_icon(win_x + 15, win_y + 12, icon, 24, fg);
811        screen.draw_string_vector(win_x + 45, win_y + 15, tab_title, fg, 18);
812        screen.boxfill(
813            win_x + 15,
814            win_y + 40,
815            win_x + win_w - 15,
816            win_y + 41,
817            Color(theme.fn_bar_border),
818        );
819
820        if tab_name == "ColorTheme" {
821            // === COLOR THEME ===
822            screen.draw_string_vector(win_x + 15, win_y + 55, "Color Theme Presets (JSON):", fg, 15);
823
824            let n_themes = self.available_themes.len();
825            for i in 0..n_themes {
826                let card_x = win_x + 15 + (i as u32 % 2) * 205;
827                let card_y = win_y + 80 + (i as u32 / 2) * 75;
828                let is_focused = self.focused_item_idx == Some(i);
829
830                let theme_name = &self.available_themes[i];
831                let is_selected = !self.enable_custom_colors && self.selected_theme == *theme_name;
832                self.draw_focus_rect(screen, card_x, card_y, 195, 65, is_focused, focus_c);
833                let border_color = if is_selected {
834                    btn_act_bg
835                } else {
836                    Color(theme.fn_bar_border)
837                };
838                screen.boxfill(card_x, card_y, card_x + 195, card_y + 65, border_color);
839                screen.boxfill(
840                    card_x + 2,
841                    card_y + 2,
842                    card_x + 193,
843                    card_y + 63,
844                    Color(theme.login_dialog_bg),
845                );
846
847                screen.draw_string_vector(card_x + 10, card_y + 8, theme_name, Color(theme.app_fg), 13);
848
849                // プレビュー色ボックス描画
850                let (dbg, tbg, aborder) = Self::get_theme_preview_colors(theme_name);
851                screen.boxfill(card_x + 10, card_y + 32, card_x + 45, card_y + 53, Color(dbg));
852                screen.boxfill(card_x + 55, card_y + 32, card_x + 90, card_y + 53, Color(tbg));
853                screen.boxfill(card_x + 100, card_y + 32, card_x + 135, card_y + 53, Color(aborder));
854            }
855
856            // 「Enable Custom Colors」トグルスイッチ
857            let check_y = win_y + 80 + (n_themes as u32).div_ceil(2) * 75 + 10;
858            let check_idx = n_themes;
859            let is_check_focused = self.focused_item_idx == Some(check_idx);
860            self.draw_focus_rect(
861                screen,
862                win_x + 15,
863                check_y,
864                280,
865                28,
866                is_check_focused,
867                focus_c,
868            );
869
870            screen.boxfill(
871                win_x + 15,
872                check_y + 4,
873                win_x + 35,
874                check_y + 24,
875                Color(theme.fn_bar_border),
876            );
877            if self.enable_custom_colors {
878                screen.boxfill(
879                    win_x + 17,
880                    check_y + 6,
881                    win_x + 33,
882                    check_y + 22,
883                    Color(theme.success_fg),
884                );
885            } else {
886                screen.boxfill(
887                    win_x + 17,
888                    check_y + 6,
889                    win_x + 33,
890                    check_y + 22,
891                    Color(theme.login_dialog_bg),
892                );
893            }
894            screen.draw_string_vector(win_x + 45, check_y + 6, "Enable Custom Colors / Edit Colors", fg, 13);
895        } else if tab_name == "CustomColor" {
896            // === CUSTOM COLOR (ALL LIST) ===
897            screen.draw_string_vector(win_x + 15, win_y + 55, "Custom Colors (2 Columns List):", fg, 14);
898
899            for i in 0..13usize {
900                let is_right_col = i >= 7;
901                let col_idx = if is_right_col { i - 7 } else { i };
902                let col_x_offset = if is_right_col { 390u32 } else { 0u32 };
903                let row_y = win_y + 80 + col_idx as u32 * 35;
904
905                let color_name = Self::get_custom_color_name(i);
906                screen.draw_string_vector(win_x + 15 + col_x_offset, row_y + 6, color_name, fg, 11);
907
908                let color_val = self.get_custom_color_by_idx(i);
909                let (r, g, b) = Self::get_color_rgb(color_val);
910                let channels = [r, g, b];
911
912                for chan_idx in 0..3usize {
913                    let cx = win_x + 140 + col_x_offset + (chan_idx as u32) * 72;
914                    let focus_idx = i * 3 + chan_idx;
915                    let is_focused = self.focused_item_idx == Some(focus_idx);
916
917                    // ◀ ボタン
918                    screen.boxfill(cx, row_y, cx + 14, row_y + 24, btn_bg);
919                    screen.draw_string_vector(cx + 4, row_y + 4, "<", btn_fg, 12);
920
921                    // 値ボックス
922                    self.draw_focus_rect(screen, cx + 18, row_y, 32, 24, is_focused, focus_c);
923                    screen.boxfill(cx + 18, row_y, cx + 50, row_y + 24, btn_act_bg);
924                    let val_str = alloc::format!("{:02X}", channels[chan_idx]);
925                    screen.draw_string_vector(cx + 20, row_y + 5, &val_str, btn_act_fg, 10);
926
927                    // ▶ ボタン
928                    screen.boxfill(cx + 54, row_y, cx + 68, row_y + 24, btn_bg);
929                    screen.draw_string_vector(cx + 59, row_y + 4, ">", btn_fg, 12);
930                }
931
932                // プレビュー
933                let px = win_x + 358 + col_x_offset;
934                screen.boxfill(px - 1, row_y - 1, px + 21, row_y + 25, Color(theme.fn_bar_border));
935                screen.boxfill(px, row_y, px + 20, row_y + 24, Color(color_val));
936            }
937        } else if tab_name == "FontOrder" {
938            // === FONT FALLBACK ORDER ===
939            screen.draw_string_vector(win_x + 15, win_y + 55, "Font fallback order:", fg, 16);
940            let labels = ["1st", "2nd", "3rd"];
941            for slot in 0..3usize {
942                let by = win_y + 85 + slot as u32 * 36;
943                let is_focused = self.focused_item_idx == Some(slot);
944                screen.draw_string_vector(win_x + 15, by + 6, labels[slot], fg, 14);
945                screen.boxfill(win_x + 48, by, win_x + 74, by + 28, btn_bg);
946                screen.draw_string_vector(win_x + 56, by + 5, "<", btn_fg, 16);
947                self.draw_focus_rect(screen, win_x + 80, by, 224, 28, is_focused, focus_c);
948                screen.boxfill(win_x + 80, by, win_x + 304, by + 28, btn_act_bg);
949                screen.draw_string_vector(
950                    win_x + 88,
951                    by + 6,
952                    &self.selected_fonts[slot],
953                    btn_act_fg,
954                    14,
955                );
956                screen.boxfill(win_x + 310, by, win_x + 336, by + 28, btn_bg);
957                screen.draw_string_vector(win_x + 318, by + 5, ">", btn_fg, 16);
958            }
959        } else if tab_name == "Keyboard" {
960            // === KEYBOARD ===
961            screen.draw_string_vector(win_x + 15, win_y + 55, "Keyboard Layout:", fg, 16);
962
963            let is_jis = self.selected_layout == KeyboardLayout::Jis;
964            let (jis_bg, jis_fg) = if is_jis {
965                (btn_act_bg, btn_act_fg)
966            } else {
967                (btn_bg, btn_fg)
968            };
969            let (us_bg, us_fg) = if !is_jis {
970                (btn_act_bg, btn_act_fg)
971            } else {
972                (btn_bg, btn_fg)
973            };
974
975            self.draw_focus_rect(
976                screen,
977                win_x + 160,
978                win_y + 50,
979                90,
980                26,
981                self.focused_item_idx == Some(0),
982                focus_c,
983            );
984            screen.boxfill(win_x + 160, win_y + 50, win_x + 250, win_y + 76, jis_bg);
985            screen.draw_string_vector(win_x + 185, win_y + 55, "JIS", jis_fg, 14);
986
987            self.draw_focus_rect(
988                screen,
989                win_x + 265,
990                win_y + 50,
991                90,
992                26,
993                self.focused_item_idx == Some(1),
994                focus_c,
995            );
996            screen.boxfill(win_x + 265, win_y + 50, win_x + 355, win_y + 76, us_bg);
997            screen.draw_string_vector(win_x + 295, win_y + 55, "US", us_fg, 14);
998
999            let repeat_items = [
1000                (
1001                    "1st Delay:",
1002                    self.repeat_first_delay,
1003                    "ms",
1004                    2usize,
1005                    win_y + 90,
1006                ),
1007                (
1008                    "1st Interval:",
1009                    self.repeat_first_interval,
1010                    "ms",
1011                    4,
1012                    win_y + 130,
1013                ),
1014                (
1015                    "2nd Count:",
1016                    self.repeat_second_count,
1017                    "times",
1018                    6,
1019                    win_y + 170,
1020                ),
1021                ("2nd Delay:", self.repeat_second_delay, "ms", 8, win_y + 210),
1022                (
1023                    "2nd Interval:",
1024                    self.repeat_second_interval,
1025                    "ms",
1026                    10,
1027                    win_y + 250,
1028                ),
1029            ];
1030            for (label, val, unit, base_idx, by) in repeat_items.iter() {
1031                screen.draw_string_vector(win_x + 15, *by + 5, label, fg, 16);
1032                let is_minus_focused = self.focused_item_idx == Some(*base_idx);
1033                self.draw_focus_rect(screen, win_x + 160, *by, 30, 26, is_minus_focused, focus_c);
1034                screen.boxfill(win_x + 160, *by, win_x + 190, *by + 26, btn_bg);
1035                screen.draw_string_vector(win_x + 170, *by + 5, "-", btn_fg, 16);
1036                let val_str = alloc::format!("{} {}", val, unit);
1037                screen.draw_string_vector(win_x + 200, *by + 5, &val_str, fg, 16);
1038                let is_plus_focused = self.focused_item_idx == Some(*base_idx + 1);
1039                self.draw_focus_rect(screen, win_x + 280, *by, 30, 26, is_plus_focused, focus_c);
1040                screen.boxfill(win_x + 280, *by, win_x + 310, *by + 26, btn_bg);
1041                screen.draw_string_vector(win_x + 290, *by + 5, "+", btn_fg, 16);
1042            }
1043
1044            screen.draw_string_vector(win_x + 15, win_y + 295, "CapsLock as Ctrl:", fg, 16);
1045            let (on_bg, on_fg) = if self.selected_caps_ctrl {
1046                (btn_act_bg, btn_act_fg)
1047            } else {
1048                (btn_bg, btn_fg)
1049            };
1050            let (off_bg, off_fg) = if !self.selected_caps_ctrl {
1051                (Color(theme.error_fg), btn_act_fg)
1052            } else {
1053                (btn_bg, btn_fg)
1054            };
1055            self.draw_focus_rect(
1056                screen,
1057                win_x + 160,
1058                win_y + 290,
1059                70,
1060                26,
1061                self.focused_item_idx == Some(12),
1062                focus_c,
1063            );
1064            screen.boxfill(win_x + 160, win_y + 290, win_x + 230, win_y + 316, on_bg);
1065            screen.draw_string_vector(win_x + 185, win_y + 295, "ON", on_fg, 14);
1066            self.draw_focus_rect(
1067                screen,
1068                win_x + 245,
1069                win_y + 290,
1070                70,
1071                26,
1072                self.focused_item_idx == Some(13),
1073                focus_c,
1074            );
1075            screen.boxfill(win_x + 245, win_y + 290, win_x + 315, win_y + 316, off_bg);
1076            screen.draw_string_vector(win_x + 268, win_y + 295, "OFF", off_fg, 14);
1077        } else if tab_name == "System" {
1078            // === SYSTEM ===
1079            screen.draw_string_vector(win_x + 15, win_y + 55, "System Sound:", fg, 16);
1080            let (on_bg, on_fg) = if self.selected_sound {
1081                (Color(theme.success_fg), btn_act_fg)
1082            } else {
1083                (btn_bg, btn_fg)
1084            };
1085            let (off_bg, off_fg) = if !self.selected_sound {
1086                (Color(theme.error_fg), btn_act_fg)
1087            } else {
1088                (btn_bg, btn_fg)
1089            };
1090            self.draw_focus_rect(
1091                screen,
1092                win_x + 160,
1093                win_y + 50,
1094                70,
1095                26,
1096                self.focused_item_idx == Some(0),
1097                focus_c,
1098            );
1099            screen.boxfill(win_x + 160, win_y + 50, win_x + 230, win_y + 76, on_bg);
1100            screen.draw_string_vector(win_x + 185, win_y + 55, "ON", on_fg, 14);
1101            self.draw_focus_rect(
1102                screen,
1103                win_x + 245,
1104                win_y + 50,
1105                70,
1106                26,
1107                self.focused_item_idx == Some(1),
1108                focus_c,
1109            );
1110            screen.boxfill(win_x + 245, win_y + 50, win_x + 315, win_y + 76, off_bg);
1111            screen.draw_string_vector(win_x + 268, win_y + 55, "OFF", off_fg, 14);
1112
1113            screen.draw_string_vector(win_x + 15, win_y + 95, "Auto DHCP on Boot:", fg, 16);
1114            let (dhcp_on_bg, dhcp_on_fg) = if self.selected_auto_dhcp {
1115                (Color(theme.success_fg), btn_act_fg)
1116            } else {
1117                (btn_bg, btn_fg)
1118            };
1119            let (dhcp_off_bg, dhcp_off_fg) = if !self.selected_auto_dhcp {
1120                (Color(theme.error_fg), btn_act_fg)
1121            } else {
1122                (btn_bg, btn_fg)
1123            };
1124            self.draw_focus_rect(
1125                screen,
1126                win_x + 160,
1127                win_y + 90,
1128                70,
1129                26,
1130                self.focused_item_idx == Some(2),
1131                focus_c,
1132            );
1133            screen.boxfill(
1134                win_x + 160,
1135                win_y + 90,
1136                win_x + 230,
1137                win_y + 116,
1138                dhcp_on_bg,
1139            );
1140            screen.draw_string_vector(win_x + 185, win_y + 95, "ON", dhcp_on_fg, 14);
1141            self.draw_focus_rect(
1142                screen,
1143                win_x + 245,
1144                win_y + 90,
1145                70,
1146                26,
1147                self.focused_item_idx == Some(3),
1148                focus_c,
1149            );
1150            screen.boxfill(
1151                win_x + 245,
1152                win_y + 90,
1153                win_x + 315,
1154                win_y + 116,
1155                dhcp_off_bg,
1156            );
1157            screen.draw_string_vector(win_x + 268, win_y + 95, "OFF", dhcp_off_fg, 14);
1158        } else if tab_name == "Storage" {
1159            // === STORAGE(週 1 回の定期スナップショット) ===
1160            screen.draw_string_vector(win_x + 15, win_y + 55, "Weekly Snapshot:", fg, 16);
1161            let on = self.snapshot_sched.enabled;
1162            let (on_bg, on_fg) = if on { (Color(theme.success_fg), btn_act_fg) } else { (btn_bg, btn_fg) };
1163            let (off_bg, off_fg) = if !on { (Color(theme.error_fg), btn_act_fg) } else { (btn_bg, btn_fg) };
1164            self.draw_focus_rect(screen, win_x + 160, win_y + 50, 70, 26, self.focused_item_idx == Some(0), focus_c);
1165            screen.boxfill(win_x + 160, win_y + 50, win_x + 230, win_y + 76, on_bg);
1166            screen.draw_string_vector(win_x + 185, win_y + 55, "ON", on_fg, 14);
1167            self.draw_focus_rect(screen, win_x + 245, win_y + 50, 70, 26, self.focused_item_idx == Some(1), focus_c);
1168            screen.boxfill(win_x + 245, win_y + 50, win_x + 315, win_y + 76, off_bg);
1169            screen.draw_string_vector(win_x + 268, win_y + 55, "OFF", off_fg, 14);
1170
1171            let day = snapshot_schedule::WEEKDAY_NAMES
1172                .get(self.snapshot_sched.weekday as usize)
1173                .copied()
1174                .unwrap_or("?");
1175            let rows = [
1176                ("Day:", String::from(day), 2usize, win_y + 90),
1177                ("Hour (JST):", alloc::format!("{:02}", self.snapshot_sched.hour), 4, win_y + 130),
1178                ("Minute:", alloc::format!("{:02}", self.snapshot_sched.minute), 6, win_y + 170),
1179            ];
1180            for (label, val, base_idx, by) in rows.iter() {
1181                screen.draw_string_vector(win_x + 15, *by + 5, label, fg, 16);
1182                self.draw_focus_rect(screen, win_x + 160, *by, 30, 26, self.focused_item_idx == Some(*base_idx), focus_c);
1183                screen.boxfill(win_x + 160, *by, win_x + 190, *by + 26, btn_bg);
1184                screen.draw_string_vector(win_x + 170, *by + 5, "-", btn_fg, 16);
1185                screen.draw_string_vector(win_x + 210, *by + 5, val, fg, 16);
1186                self.draw_focus_rect(screen, win_x + 280, *by, 30, 26, self.focused_item_idx == Some(*base_idx + 1), focus_c);
1187                screen.boxfill(win_x + 280, *by, win_x + 310, *by + 26, btn_bg);
1188                screen.draw_string_vector(win_x + 290, *by + 5, "+", btn_fg, 16);
1189            }
1190
1191            for (i, line) in self.storage_info_cached().iter().enumerate() {
1192                screen.draw_string_vector(win_x + 15, win_y + 215 + i as u32 * 22, line, fg, 13);
1193            }
1194            screen.draw_string_vector(
1195                win_x + 15,
1196                win_y + 283,
1197                "Snapshots keep versions; versions between snapshots are cleaned up.",
1198                Color(theme.fn_bar_dim_fg),
1199                11,
1200            );
1201
1202            self.draw_focus_rect(screen, win_x + 15, win_y + 300, 220, 32, self.focused_item_idx == Some(8), focus_c);
1203            screen.boxfill(win_x + 15, win_y + 300, win_x + 235, win_y + 332, btn_bg);
1204            screen.draw_string_vector(win_x + 30, win_y + 308, "Take Snapshot Now", btn_fg, 14);
1205        } else {
1206            // === NETWORK ===
1207            let fw = win_w.saturating_sub(30);
1208
1209            let connected = crate::kernel::wifi::is_connected();
1210            let status_color = if connected {
1211                Color(theme.success_fg)
1212            } else {
1213                Color(theme.error_fg)
1214            };
1215            let status_dot = if connected {
1216                "● Connected"
1217            } else {
1218                "● Not connected"
1219            };
1220            screen.draw_string_vector(win_x + 15, win_y + 55, status_dot, status_color, 15);
1221
1222            if crate::kernel::wifi::is_connected() {
1223                let ip = crate::kernel::wifi::get_ip();
1224                let ip_str = alloc::format!("IP: {}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3]);
1225                screen.draw_string_vector(win_x + 15, win_y + 78, &ip_str, fg, 14);
1226                let ssid = crate::kernel::wifi::get_ssid();
1227                let ssid_str = alloc::format!("SSID: {}", ssid);
1228                screen.draw_string_vector(win_x + 15, win_y + 98, &ssid_str, fg, 14);
1229            }
1230
1231            if !self.wifi_status_msg.is_empty() {
1232                screen.draw_string_vector(
1233                    win_x + 15,
1234                    win_y + 122,
1235                    &self.wifi_status_msg,
1236                    Color(theme.warning_fg),
1237                    13,
1238                );
1239            }
1240
1241            screen.draw_string_vector(win_x + 15, win_y + 152, "SSID:", fg, 14);
1242            let ssid_focused = self.wifi_focused == 1;
1243            self.draw_text_field(
1244                screen,
1245                win_x + 15,
1246                win_y + 170,
1247                fw,
1248                &self.ssid_box,
1249                ssid_focused,
1250                "Enter Wi-Fi network name",
1251                false,
1252            );
1253
1254            screen.draw_string_vector(win_x + 15, win_y + 212, "Password:", fg, 14);
1255            let pass_focused = self.wifi_focused == 2;
1256            self.draw_text_field(
1257                screen,
1258                win_x + 15,
1259                win_y + 230,
1260                fw,
1261                &self.password_box,
1262                pass_focused,
1263                "Enter password",
1264                true,
1265            );
1266
1267            let btn_x0 = win_x + 15;
1268            let btn_y0 = win_y + 278;
1269            let btn_w = 160u32;
1270            let btn_bg_c = if self.wifi_connecting {
1271                Color(theme.fn_bar_dim_fg)
1272            } else {
1273                Color(theme.success_fg)
1274            };
1275            screen.boxfill(btn_x0, btn_y0, btn_x0 + btn_w, btn_y0 + 34, btn_bg_c);
1276            screen.draw_string_vector(
1277                btn_x0 + 22,
1278                btn_y0 + 9,
1279                "Connect / Save",
1280                btn_act_fg,
1281                14,
1282            );
1283
1284            if connected {
1285                let disc_x = btn_x0 + btn_w + 12;
1286                screen.boxfill(disc_x, btn_y0, disc_x + 130, btn_y0 + 34, Color(theme.error_fg));
1287                screen.draw_string_vector(
1288                    disc_x + 10,
1289                    btn_y0 + 9,
1290                    "Disconnect",
1291                    btn_act_fg,
1292                    14,
1293                );
1294            }
1295
1296            screen.draw_string_vector(
1297                win_x + 15,
1298                win_y + 325,
1299                "Click a field and type to edit.",
1300                Color(theme.fn_bar_dim_fg),
1301                12,
1302            );
1303        }
1304
1305        // 保存・適用の結果(成功/失敗)。失敗を黙って捨てないための表示。
1306        if !self.status_msg.is_empty() {
1307            let color = if self.status_is_error {
1308                Color(theme.error_fg)
1309            } else {
1310                Color(theme.success_fg)
1311            };
1312            screen.draw_string_vector(win_x + 15, win_y + win_h - 66, &self.status_msg, color, 13);
1313        }
1314
1315        // Apply ボタン(Network タブ以外)
1316        if tab_name != "Network" {
1317            let btn_x0 = win_x + (win_w - 200) / 2;
1318            let btn_y0 = win_y + win_h - 45;
1319            let apply_idx = self.get_item_count() - 1;
1320            self.draw_focus_rect(
1321                screen,
1322                btn_x0,
1323                btn_y0,
1324                200,
1325                32,
1326                self.focused_item_idx == Some(apply_idx),
1327                focus_c,
1328            );
1329            screen.boxfill(btn_x0, btn_y0, btn_x0 + 200, btn_y0 + 32, Color(theme.success_fg));
1330            screen.draw_string_vector(
1331                btn_x0 + 42,
1332                btn_y0 + 8,
1333                "Apply & Save",
1334                btn_act_fg,
1335                15,
1336            );
1337        }
1338    }
1339
1340    fn on_mouse(
1341        &mut self,
1342        local_x: i32,
1343        local_y: i32,
1344        btn_left: bool,
1345        _btn_right: bool,
1346        _wheel: i32,
1347    ) {
1348        if !btn_left {
1349            return;
1350        }
1351        let x = local_x;
1352        let y = local_y;
1353        let ww = self.last_win_w as i32;
1354        let wh = self.last_win_h as i32;
1355
1356        let tabs = self.tabs();
1357        if self.active_tab_idx >= tabs.len() {
1358            return;
1359        }
1360        let tab_name = tabs[self.active_tab_idx].as_str();
1361
1362        match tab_name {
1363            "ColorTheme" => {
1364                let n_themes = self.available_themes.len();
1365                for i in 0..n_themes {
1366                    let cx = 15 + (i as i32 % 2) * 205;
1367                    let cy = 80 + (i as i32 / 2) * 75;
1368                    if x >= cx && x < cx + 195 && y >= cy && y < cy + 65 {
1369                        let theme_name = self.available_themes[i].clone();
1370                        self.select_theme(&theme_name);
1371                        return;
1372                    }
1373                }
1374
1375                // Enable Custom Colors チェックボックス
1376                let check_y = 80 + ((n_themes as i32 + 1) / 2) * 75 + 10;
1377                if (15..350).contains(&x) && (check_y..check_y + 28).contains(&y) {
1378                    self.toggle_custom_colors();
1379                    return;
1380                }
1381
1382                let bx = (ww - 200) / 2;
1383                let by = wh - 45;
1384                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1385                    self.apply_and_save();
1386                }
1387            }
1388            "CustomColor" => {
1389                for i in 0..13usize {
1390                    let is_right_col = i >= 7;
1391                    let col_idx = if is_right_col { i - 7 } else { i };
1392                    let col_x_offset = if is_right_col { 390 } else { 0 };
1393                    let row_y = 80 + col_idx as i32 * 35;
1394
1395                    if y >= row_y && y < row_y + 26 {
1396                        let color_val = self.get_custom_color_by_idx(i);
1397                        let (mut r, mut g, mut b) = Self::get_color_rgb(color_val);
1398
1399                        for chan_idx in 0..3usize {
1400                            let cx = 140 + col_x_offset + (chan_idx as i32) * 72;
1401                            // ◀ ボタン (幅 14px)
1402                            if x >= cx && x < cx + 14 {
1403                                match chan_idx {
1404                                    0 => r = Self::adjust_channel(r, -1),
1405                                    1 => g = Self::adjust_channel(g, -1),
1406                                    _ => b = Self::adjust_channel(b, -1),
1407                                }
1408                                let new_c = Self::make_color_u32(r, g, b);
1409                                self.set_custom_color_by_idx(i, new_c);
1410                                if self.enable_custom_colors {
1411                                    unsafe {
1412                                        if let Some(ref mut conf) = config::GLOBAL_CONFIG {
1413                                            conf.custom_theme = self.custom_theme;
1414                                            conf.theme = self.custom_theme;
1415                                        }
1416                                    }
1417                                    let mut wm = crate::kernel::window_mgr::get_instance();
1418                                    wm.dirty = true;
1419                                }
1420                                return;
1421                            }
1422                            // ▶ ボタン (幅 14px、オフセット cx + 54)
1423                            if x >= cx + 54 && x < cx + 68 {
1424                                match chan_idx {
1425                                    0 => r = Self::adjust_channel(r, 1),
1426                                    1 => g = Self::adjust_channel(g, 1),
1427                                    _ => b = Self::adjust_channel(b, 1),
1428                                }
1429                                let new_c = Self::make_color_u32(r, g, b);
1430                                self.set_custom_color_by_idx(i, new_c);
1431                                if self.enable_custom_colors {
1432                                    unsafe {
1433                                        if let Some(ref mut conf) = config::GLOBAL_CONFIG {
1434                                            conf.custom_theme = self.custom_theme;
1435                                            conf.theme = self.custom_theme;
1436                                        }
1437                                    }
1438                                    let mut wm = crate::kernel::window_mgr::get_instance();
1439                                    wm.dirty = true;
1440                                }
1441                                return;
1442                            }
1443                        }
1444                    }
1445                }
1446
1447                let bx = (ww - 200) / 2;
1448                let by = wh - 45;
1449                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1450                    self.apply_and_save();
1451                }
1452            }
1453            "FontOrder" => {
1454                for slot in 0..3usize {
1455                    let by = 85 + slot as i32 * 36;
1456                    if y >= by && y < by + 28 {
1457                        if (48..74).contains(&x) {
1458                            self.cycle_font(slot, -1);
1459                            return;
1460                        }
1461                        if (80..304).contains(&x) || (310..336).contains(&x) {
1462                            self.cycle_font(slot, 1);
1463                            return;
1464                        }
1465                    }
1466                }
1467                let bx = (ww - 200) / 2;
1468                let by = wh - 45;
1469                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1470                    self.apply_and_save();
1471                }
1472            }
1473            "Keyboard" => {
1474                if (160..250).contains(&x) && (50..76).contains(&y) {
1475                    self.selected_layout = KeyboardLayout::Jis;
1476                    return;
1477                }
1478                if (265..355).contains(&x) && (50..76).contains(&y) {
1479                    self.selected_layout = KeyboardLayout::Us;
1480                    return;
1481                }
1482                let rows: [(i32, &mut u32, u32, u32, u32); 5] = unsafe {
1483                    let s = &mut *(self as *mut Self);
1484                    [
1485                        (90, &mut s.repeat_first_delay, 50, 2000, 50),
1486                        (130, &mut s.repeat_first_interval, 5, 500, 5),
1487                        (170, &mut s.repeat_second_count, 0, 100, 1),
1488                        (210, &mut s.repeat_second_delay, 50, 2000, 50),
1489                        (250, &mut s.repeat_second_interval, 5, 500, 5),
1490                    ]
1491                };
1492                for (row_y, val, min, max, step) in rows {
1493                    if y >= row_y && y < row_y + 26 {
1494                        if (160..190).contains(&x) {
1495                            *val = val.saturating_sub(step).max(min);
1496                            return;
1497                        }
1498                        if (280..310).contains(&x) {
1499                            *val = (*val + step).min(max);
1500                            return;
1501                        }
1502                    }
1503                }
1504                if (290..316).contains(&y) {
1505                    if (160..230).contains(&x) {
1506                        self.selected_caps_ctrl = true;
1507                        return;
1508                    }
1509                    if (245..315).contains(&x) {
1510                        self.selected_caps_ctrl = false;
1511                        return;
1512                    }
1513                }
1514                let bx = (ww - 200) / 2;
1515                let by = wh - 45;
1516                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1517                    self.apply_and_save();
1518                }
1519            }
1520            "System" => {
1521                if (50..76).contains(&y) {
1522                    if (160..230).contains(&x) {
1523                        self.selected_sound = true;
1524                        return;
1525                    }
1526                    if (245..315).contains(&x) {
1527                        self.selected_sound = false;
1528                        return;
1529                    }
1530                }
1531                if (90..116).contains(&y) {
1532                    if (160..230).contains(&x) {
1533                        self.selected_auto_dhcp = true;
1534                        return;
1535                    }
1536                    if (245..315).contains(&x) {
1537                        self.selected_auto_dhcp = false;
1538                        return;
1539                    }
1540                }
1541                let bx = (ww - 200) / 2;
1542                let by = wh - 45;
1543                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1544                    self.apply_and_save();
1545                }
1546            }
1547            "Storage" => {
1548                if (50..76).contains(&y) {
1549                    if (160..230).contains(&x) {
1550                        self.snapshot_sched.enabled = true;
1551                        self.storage_info = None;
1552                        return;
1553                    }
1554                    if (245..315).contains(&x) {
1555                        self.snapshot_sched.enabled = false;
1556                        self.storage_info = None;
1557                        return;
1558                    }
1559                }
1560                for (field, row_y) in [(0u8, 90), (1, 130), (2, 170)] {
1561                    if y >= row_y && y < row_y + 26 {
1562                        if (160..190).contains(&x) {
1563                            self.step_schedule(field, -1);
1564                            return;
1565                        }
1566                        if (280..310).contains(&x) {
1567                            self.step_schedule(field, 1);
1568                            return;
1569                        }
1570                    }
1571                }
1572                if (15..235).contains(&x) && (300..332).contains(&y) {
1573                    self.snapshot_now();
1574                    return;
1575                }
1576                let bx = (ww - 200) / 2;
1577                let by = wh - 45;
1578                if x >= bx && x < bx + 200 && y >= by && y < by + 32 {
1579                    self.apply_and_save();
1580                }
1581            }
1582            _ => {
1583                let fw = (ww - 30).max(0);
1584                if x >= 15 && x < 15 + fw && (170..198).contains(&y) {
1585                    self.wifi_focused = 1;
1586                    return;
1587                }
1588                if x >= 15 && x < 15 + fw && (230..258).contains(&y) {
1589                    self.wifi_focused = 2;
1590                    return;
1591                }
1592                if (15..175).contains(&x) && (278..312).contains(&y) {
1593                    self.wifi_focused = 0;
1594                    self.start_wifi_connect();
1595                    return;
1596                }
1597                if crate::kernel::wifi::is_connected()
1598                    && (187..317).contains(&x)
1599                    && (278..312).contains(&y)
1600                {
1601                    crate::kernel::wifi::disconnect();
1602                    self.wifi_status_msg = String::from("Disconnected");
1603                    self.wifi_focused = 0;
1604                    return;
1605                }
1606                self.wifi_focused = 0;
1607            }
1608        }
1609    }
1610
1611    fn on_key(&mut self, keycode: u8, pressed: bool, ascii: Option<char>) {
1612        if !pressed {
1613            return;
1614        }
1615
1616        let tabs = self.tabs();
1617        if self.active_tab_idx >= tabs.len() {
1618            return;
1619        }
1620        let tab_name = tabs[self.active_tab_idx].as_str();
1621
1622        if tab_name == "Network" {
1623            match self.wifi_focused {
1624                1 => {
1625                    if keycode == 0x0F {
1626                        self.wifi_focused = 2;
1627                    } else if keycode == 0x1C {
1628                        self.start_wifi_connect();
1629                    } else {
1630                        let _ = self.ssid_box.handle_key(keycode, ascii);
1631                    }
1632                }
1633                2 => {
1634                    if keycode == 0x0F {
1635                        self.wifi_focused = 1;
1636                    } else if keycode == 0x1C {
1637                        self.start_wifi_connect();
1638                    } else {
1639                        let _ = self.password_box.handle_key(keycode, ascii);
1640                    }
1641                }
1642                _ => {
1643                    if keycode == 0x0F {
1644                        self.wifi_focused = 1;
1645                    }
1646                }
1647            }
1648            return;
1649        }
1650
1651        let count = self.get_item_count();
1652        if ascii == Some('\t') {
1653            if let Some(idx) = self.focused_item_idx {
1654                self.focused_item_idx = Some((idx + 1) % count);
1655            } else {
1656                self.focused_item_idx = Some(0);
1657            }
1658            crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
1659        } else if ascii == Some('\n') {
1660            if let Some(idx) = self.focused_item_idx {
1661                self.handle_action(idx);
1662                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Apply);
1663            }
1664        }
1665    }
1666}