Skip to main content

atmos/apps/files/
mod.rs

1//! SylFS 用の 2x2 グリッド型ファイラアプリ。
2//!
3//! [`crate::kernel::fs`](SylFS)をブラウズ・コピー・移動・削除するための GUI。
4//! 上段=フォルダ一覧、下段=ファイル一覧の2ペイン構成で、キーボードショートカット
5//! ([`crate::kernel::shortcut_manager`])中心の操作を提供する。
6// src/files_app.rs - 2x2 Grid Stateless Filer for AtmOS
7#![allow(dead_code)]
8
9extern crate alloc;
10use alloc::boxed::Box;
11use alloc::string::String;
12use alloc::string::ToString;
13use alloc::vec;
14use alloc::vec::Vec;
15
16use crate::apps::browser::WebBrowser;
17use crate::kernel::config;
18use crate::kernel::draw::{Color, Screen};
19use crate::kernel::fs;
20use crate::kernel::shortcut_manager::{
21    InputAction, Modifiers, Shortcut, ShortcutLayer, ShortcutManager,
22};
23use crate::kernel::window_mgr::{App, Window};
24
25static ICON_FOLDER: &[u8] = include_bytes!("../../../icons/ic_fluent_folder_20_regular.svg");
26static ICON_FILE: &[u8] = include_bytes!("../../../icons/ic_fluent_document_20_regular.svg");
27
28// --- Filer App Commands ---
29const CMD_NAV_UP: u32 = 1;
30const CMD_NAV_DOWN: u32 = 2;
31const CMD_NAV_LEFT: u32 = 3;
32const CMD_NAV_RIGHT: u32 = 4;
33const CMD_FOCUS_UP: u32 = 5;
34const CMD_FOCUS_DOWN: u32 = 6;
35const CMD_FOCUS_LEFT: u32 = 7;
36const CMD_FOCUS_RIGHT: u32 = 8;
37const CMD_TAB_PREV: u32 = 9;
38const CMD_TAB_NEXT: u32 = 10;
39const CMD_FILE_COPY: u32 = 11;
40const CMD_FILE_MOVE: u32 = 12;
41const CMD_ENTER: u32 = 13;
42const CMD_DELETE: u32 = 14;
43
44#[derive(Clone)]
45pub struct FilerState {
46    pub current_path: String,
47    pub folders: Vec<String>,
48    pub files: Vec<fs::FileMetadata>,
49    pub selected_folder: usize,
50    pub selected_file: usize,
51    pub scroll_folder: usize,
52    pub scroll_file: usize,
53    pub active_pane: usize, // 0: folder (upper), 1: file (lower)
54}
55
56impl FilerState {
57    pub fn new(initial_path: &str) -> Self {
58        let mut state = Self {
59            current_path: String::from(initial_path),
60            folders: Vec::new(),
61            files: Vec::new(),
62            selected_folder: 0,
63            selected_file: 0,
64            scroll_folder: 0,
65            scroll_file: 0,
66            active_pane: 0,
67        };
68        state.refresh();
69        state
70    }
71
72    pub fn refresh(&mut self) {
73        self.folders.clear();
74        self.files.clear();
75
76        let all_files = fs::get_fs().list_files();
77        let mut folder_set = alloc::collections::BTreeSet::new();
78
79        let search_path = if self.current_path.ends_with('/') {
80            self.current_path.clone()
81        } else {
82            alloc::format!("{}/", self.current_path)
83        };
84
85        for meta in all_files {
86            let filename = meta.get_filename();
87            if filename.starts_with(&search_path) {
88                let remainder = filename.get(search_path.len()..).unwrap_or("");
89                if let Some(slash_idx) = remainder.find('/') {
90                    // It's a folder
91                    let folder_name = remainder.get(..slash_idx).unwrap_or("");
92                    if !folder_name.is_empty() {
93                        folder_set.insert(String::from(folder_name));
94                    }
95                } else if !remainder.is_empty() {
96                    // It's a file in the current directory
97                    self.files.push(meta);
98                }
99            } else if search_path == "/" && !filename.is_empty() && !filename.starts_with('/') {
100                // Handle files/folders at root without leading slash (though AtmOS paths usually start with /)
101                if let Some(slash_idx) = filename.find('/') {
102                    folder_set.insert(String::from(filename.get(..slash_idx).unwrap_or("")));
103                } else {
104                    self.files.push(meta);
105                }
106            }
107        }
108
109        // 特別な仮想ディレクトリ "apps", "user", "sys" などをルートに強制表示(存在しなくても表示させるため)
110        if self.current_path == "/" {
111            folder_set.insert(String::from("apps"));
112            folder_set.insert(String::from("user"));
113            folder_set.insert(String::from("sys"));
114        }
115
116        for f in folder_set {
117            self.folders.push(f);
118        }
119
120        if self.selected_folder >= self.folders.len() {
121            self.selected_folder = self.folders.len().saturating_sub(1);
122        }
123        if self.selected_file >= self.files.len() {
124            self.selected_file = self.files.len().saturating_sub(1);
125        }
126    }
127}
128
129#[derive(Clone)]
130pub struct TabState {
131    pub left: FilerState,
132    pub right: FilerState,
133    pub active_panel: usize,
134}
135
136pub struct FilesApp {
137    tabs: Vec<TabState>,
138    active_tab: usize,
139    status: String,
140    last_win_w: u32,
141    last_win_h: u32,
142    alt_held: bool,
143    ctrl_held: bool,
144    shortcut_mgr: ShortcutManager,
145}
146
147impl Default for FilesApp {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153impl FilesApp {
154    pub fn new() -> Self {
155        let tabs = vec![TabState {
156            left: FilerState::new("/"),
157            right: FilerState::new("/apps"),
158            active_panel: 0,
159        }];
160
161        let mut shortcut_mgr = ShortcutManager::new();
162
163        // --- 3キー操作 (優先度最高) ---
164        shortcut_mgr.register(Shortcut::new(
165            0x48,
166            Modifiers::new(true, true, false),
167            ShortcutLayer::App,
168            InputAction::AppCommand(CMD_FOCUS_UP),
169        )); // Ctrl+Alt+Up
170        shortcut_mgr.register(Shortcut::new(
171            0x50,
172            Modifiers::new(true, true, false),
173            ShortcutLayer::App,
174            InputAction::AppCommand(CMD_FOCUS_DOWN),
175        )); // Ctrl+Alt+Down
176        shortcut_mgr.register(Shortcut::new(
177            0x4B,
178            Modifiers::new(true, true, false),
179            ShortcutLayer::App,
180            InputAction::AppCommand(CMD_FOCUS_LEFT),
181        )); // Ctrl+Alt+Left
182        shortcut_mgr.register(Shortcut::new(
183            0x4D,
184            Modifiers::new(true, true, false),
185            ShortcutLayer::App,
186            InputAction::AppCommand(CMD_FOCUS_RIGHT),
187        )); // Ctrl+Alt+Right
188
189        // --- 2キー操作 ---
190        shortcut_mgr.register(Shortcut::new(
191            0x19,
192            Modifiers::new(true, false, false),
193            ShortcutLayer::App,
194            InputAction::AppCommand(CMD_NAV_UP),
195        )); // Ctrl+P
196        shortcut_mgr.register(Shortcut::new(
197            0x31,
198            Modifiers::new(true, false, false),
199            ShortcutLayer::App,
200            InputAction::AppCommand(CMD_NAV_DOWN),
201        )); // Ctrl+N
202        shortcut_mgr.register(Shortcut::new(
203            0x21,
204            Modifiers::new(true, false, false),
205            ShortcutLayer::App,
206            InputAction::AppCommand(CMD_NAV_RIGHT),
207        )); // Ctrl+F
208        shortcut_mgr.register(Shortcut::new(
209            0x30,
210            Modifiers::new(true, false, false),
211            ShortcutLayer::App,
212            InputAction::AppCommand(CMD_NAV_LEFT),
213        )); // Ctrl+B
214
215        shortcut_mgr.register(Shortcut::new(
216            0x48,
217            Modifiers::new(false, true, false),
218            ShortcutLayer::App,
219            InputAction::AppCommand(CMD_TAB_PREV),
220        )); // Alt+Up
221        shortcut_mgr.register(Shortcut::new(
222            0x50,
223            Modifiers::new(false, true, false),
224            ShortcutLayer::App,
225            InputAction::AppCommand(CMD_TAB_NEXT),
226        )); // Alt+Down
227        shortcut_mgr.register(Shortcut::new(
228            0x2E,
229            Modifiers::new(false, true, false),
230            ShortcutLayer::App,
231            InputAction::AppCommand(CMD_FILE_COPY),
232        )); // Alt+C
233        shortcut_mgr.register(Shortcut::new(
234            0x32,
235            Modifiers::new(false, true, false),
236            ShortcutLayer::App,
237            InputAction::AppCommand(CMD_FILE_MOVE),
238        )); // Alt+M
239
240        // --- 1キー操作 (単独) ---
241        shortcut_mgr.register(Shortcut::new(
242            0x48,
243            Modifiers::new(false, false, false),
244            ShortcutLayer::App,
245            InputAction::AppCommand(CMD_NAV_UP),
246        )); // Up
247        shortcut_mgr.register(Shortcut::new(
248            0x50,
249            Modifiers::new(false, false, false),
250            ShortcutLayer::App,
251            InputAction::AppCommand(CMD_NAV_DOWN),
252        )); // Down
253        shortcut_mgr.register(Shortcut::new(
254            0x4D,
255            Modifiers::new(false, false, false),
256            ShortcutLayer::App,
257            InputAction::AppCommand(CMD_NAV_RIGHT),
258        )); // Right
259        shortcut_mgr.register(Shortcut::new(
260            0x4B,
261            Modifiers::new(false, false, false),
262            ShortcutLayer::App,
263            InputAction::AppCommand(CMD_NAV_LEFT),
264        )); // Left
265        shortcut_mgr.register(Shortcut::new(
266            0x1C,
267            Modifiers::new(false, false, false),
268            ShortcutLayer::App,
269            InputAction::AppCommand(CMD_ENTER),
270        )); // Enter
271        shortcut_mgr.register(Shortcut::new(
272            0x53,
273            Modifiers::new(false, false, false),
274            ShortcutLayer::App,
275            InputAction::AppCommand(CMD_DELETE),
276        )); // Delete
277
278        Self {
279            tabs,
280            active_tab: 0,
281            status: String::from("Ready"),
282            last_win_w: 1000,
283            last_win_h: 600,
284            alt_held: false,
285            ctrl_held: false,
286            shortcut_mgr,
287        }
288    }
289
290    fn active_panel(&self) -> usize {
291        self.tabs[self.active_tab].active_panel
292    }
293
294    fn set_active_panel(&mut self, val: usize) {
295        self.tabs[self.active_tab].active_panel = val;
296    }
297
298    fn active_state(&mut self) -> &mut FilerState {
299        let active_tab = self.active_tab;
300        let tab = &mut self.tabs[active_tab];
301        if tab.active_panel == 0 {
302            &mut tab.left
303        } else {
304            &mut tab.right
305        }
306    }
307
308    fn inactive_state(&mut self) -> &mut FilerState {
309        let active_tab = self.active_tab;
310        let tab = &mut self.tabs[active_tab];
311        if tab.active_panel == 1 {
312            &mut tab.left
313        } else {
314            &mut tab.right
315        }
316    }
317
318    fn refresh_all(&mut self) {
319        for tab in self.tabs.iter_mut() {
320            tab.left.refresh();
321            tab.right.refresh();
322        }
323    }
324
325    fn get_active_file_path(&mut self) -> Option<String> {
326        let state = self.active_state();
327        if state.active_pane == 1 && !state.files.is_empty() {
328            Some(String::from(
329                state.files[state.selected_file].get_filename(),
330            ))
331        } else {
332            None
333        }
334    }
335
336    fn open_selected(&mut self) {
337        if let Some(filename) = self.get_active_file_path() {
338            // アプリケーションパッケージ内のファイルであれば、アプリを起動する
339            if filename.starts_with("/apps/") {
340                let parts: Vec<&str> = filename.split('/').collect();
341                if parts.len() > 2 {
342                    let app_name = parts[2];
343                    if app_name == "note" {
344                        let mut app = crate::apps::note::NoteApp::new();
345                        if let Some((_meta, content)) =
346                            fs::get_fs().read_file_checked("/apps/note/index.html").ok().flatten()
347                        {
348                            if let Ok(html_str) = core::str::from_utf8(&content) {
349                                app.engine.load_html(html_str, "/apps/note/index.html", 0);
350                            }
351                        }
352                        let win = Window::new(200, 150, 600, 450, "Note - Untitled", Box::new(app));
353                        crate::kernel::window_mgr::get_instance().add_window(win);
354                        self.status = "Launched Note App".to_string();
355                        return;
356                    } else if app_name == "settings" {
357                        let app = crate::apps::settings::SettingsApp::new();
358                        let win = Window::new(150, 100, 480, 560, "OS Settings", Box::new(app));
359                        crate::kernel::window_mgr::get_instance().add_window(win);
360                        self.status = "Launched Settings App".to_string();
361                        return;
362                    } else if app_name == "music" {
363                        let app = crate::apps::music::MusicApp::new();
364                        let win = Window::new(180, 120, 500, 420, "Music Player", Box::new(app));
365                        crate::kernel::window_mgr::get_instance().add_window(win);
366                        self.status = "Launched Music Player".to_string();
367                        return;
368                    } else if app_name == "files" {
369                        let app = crate::apps::files::FilesApp::new();
370                        let win = Window::new(140, 90, 1180, 760, "Files", Box::new(app));
371                        crate::kernel::window_mgr::get_instance().add_window(win);
372                        self.status = "Launched Files App".to_string();
373                        return;
374                    } else if app_name == "browser" {
375                        // WebBrowser::new() が OS 内蔵の静的ホームページを表示する(ネットワーク不要)。
376                        // 【2026-11-18】TODO R3: ブラウザはアプリのスレッドで開く(OS のメインループで JS・同期の取得を走らせない)。
377                        let app = WebBrowser::new();
378                        crate::os_lib::aura::builtins::launch_in_app_thread(
379                            100, 100, 800, 600, "Browser - AtmOS", Box::new(app),
380                        );
381                        self.status = "Launched Browser App".to_string();
382                        return;
383                    }
384                }
385            }
386
387            if filename.ends_with(".html") || filename.ends_with(".htm") {
388                let mut app = WebBrowser::new();
389                if let Some((_meta, content)) = fs::get_fs().read_file_checked(&filename).ok().flatten() {
390                    if let Ok(html_str) = core::str::from_utf8(&content) {
391                        let top = app.top_offset();
392                        app.engine.load_html(html_str, &filename, top);
393                    }
394                }
395                // 【2026-11-18】TODO R3: HTML の中の `<script src>`・CSS の取得や JS が OS のメインループで走らないよう、
396                // アプリのスレッドで開く(以前は `add_window` で直接開き、`gui_shell` の上で同期の取得をしていた)。
397                crate::os_lib::aura::builtins::launch_in_app_thread(
398                    100,
399                    100,
400                    800,
401                    600,
402                    &alloc::format!("Browser - {}", filename),
403                    Box::new(app),
404                );
405                self.status = alloc::format!("Opened HTML file '{}'", filename);
406            } else {
407                let content = fs::get_fs()
408                    .read_file_checked(&filename)
409                    .ok()
410                    .flatten()
411                    .and_then(|(_meta, bytes)| {
412                        core::str::from_utf8(&bytes)
413                            .ok()
414                            .map(alloc::string::String::from)
415                    })
416                    .unwrap_or_default();
417                let app = crate::apps::note::NoteApp::open_file(&filename, &content);
418                let win = Window::new(
419                    200,
420                    150,
421                    600,
422                    450,
423                    &alloc::format!("Note - {}", filename),
424                    Box::new(app),
425                );
426                crate::kernel::window_mgr::get_instance().add_window(win);
427                self.status = alloc::format!("Opened '{}' in Note", filename);
428            }
429        }
430    }
431
432    fn copy_to_inactive_panel(&mut self) {
433        if let Some(src_path) = self.get_active_file_path() {
434            let dest_path_base = self.inactive_state().current_path.clone();
435
436            let dest_dir = if dest_path_base.ends_with('/') {
437                dest_path_base
438            } else {
439                alloc::format!("{}/", dest_path_base)
440            };
441
442            let filename_only = match src_path.rfind('/') {
443                Some(idx) => src_path.get(idx + 1..).unwrap_or(""),
444                None => &src_path,
445            };
446
447            let dest_path = alloc::format!("{}{}", dest_dir, filename_only);
448
449            if let Some((meta, content)) = fs::get_fs().read_file_checked(&src_path).ok().flatten() {
450                if fs::get_fs()
451                    .save_file(&dest_path, &content, meta.get_labels())
452                    .is_ok()
453                {
454                    self.status = alloc::format!("Copied to {}", dest_path);
455                    self.refresh_all();
456                    return;
457                }
458            }
459            self.status = alloc::format!("Failed to copy {}", src_path);
460        }
461    }
462
463    fn move_to_inactive_panel(&mut self) {
464        if let Some(src_path) = self.get_active_file_path() {
465            let dest_path_base = self.inactive_state().current_path.clone();
466
467            let dest_dir = if dest_path_base.ends_with('/') {
468                dest_path_base
469            } else {
470                alloc::format!("{}/", dest_path_base)
471            };
472            let filename_only = match src_path.rfind('/') {
473                Some(idx) => src_path.get(idx + 1..).unwrap_or(""),
474                None => &src_path,
475            };
476            let dest_path = alloc::format!("{}{}", dest_dir, filename_only);
477
478            let fs_ref = fs::get_fs();
479            // 【2026-11-11】まず名前の変更で移す(データを写さず、1 回の切り替えで済む。電源断でも
480            // どちらか一方にだけある)。置き場をまたぐなど名前の変更ができないときだけ、写して消す。
481            if fs_ref.rename_file(&src_path, &dest_path).is_ok() {
482                self.status = alloc::format!("Moved to {}", dest_path);
483                self.refresh_all();
484                return;
485            }
486            if let Some((meta, content)) = fs_ref.read_file_checked(&src_path).ok().flatten() {
487                if fs_ref
488                    .save_file(&dest_path, &content, meta.get_labels())
489                    .is_ok()
490                {
491                    let _ = fs_ref.delete_file(&src_path);
492                    self.status = alloc::format!("Moved to {}", dest_path);
493                    self.refresh_all();
494                    return;
495                }
496            }
497            self.status = alloc::format!("Failed to move {}", src_path);
498        }
499    }
500
501    fn delete_selected(&mut self) {
502        if let Some(filename) = self.get_active_file_path() {
503            if fs::get_fs().delete_file(&filename).is_ok() {
504                self.status = alloc::format!("Deleted '{}'", filename);
505                crate::kernel::audio::play_system_se(crate::kernel::audio::SeType::Delete);
506                self.refresh_all();
507            } else {
508                self.status = alloc::format!("ERROR: Failed to delete '{}'", filename);
509            }
510        }
511    }
512
513    fn get_folders_at(path: &str) -> Vec<String> {
514        let mut folder_set = alloc::collections::BTreeSet::new();
515        let all_files = fs::get_fs().list_files();
516
517        let search_path = if path.ends_with('/') {
518            path.to_string()
519        } else {
520            alloc::format!("{}/", path)
521        };
522
523        for meta in all_files {
524            let filename = meta.get_filename();
525            if filename.starts_with(&search_path) {
526                let remainder = filename.get(search_path.len()..).unwrap_or("");
527                if let Some(slash_idx) = remainder.find('/') {
528                    let folder_name = remainder.get(..slash_idx).unwrap_or("");
529                    if !folder_name.is_empty() {
530                        folder_set.insert(String::from(folder_name));
531                    }
532                }
533            }
534        }
535
536        if path == "/" {
537            folder_set.insert(String::from("apps"));
538            folder_set.insert(String::from("user"));
539            folder_set.insert(String::from("sys"));
540        }
541
542        folder_set.into_iter().collect()
543    }
544
545    fn draw_panel(
546        &self,
547        screen: &Screen,
548        is_right: bool,
549        px: u32,
550        py: u32,
551        pw: u32,
552        ph: u32,
553        active_panel: bool,
554    ) {
555        let tab = &self.tabs[self.active_tab];
556        let state = if is_right {
557            &tab.right
558        } else {
559            &tab.left
560        };
561
562        let config = config::get_config();
563        let bg = Color(config.theme.desktop_bg);
564        let list_bg = Color(config.theme.terminal_bg);
565        let fg = Color(config.theme.terminal_fg);
566        let active_color = Color(config.theme.active_window_border);
567        let inactive_color = Color(config.theme.non_active_window_border);
568        let preview_color = Color(config.theme.non_active_window_border);
569
570        // Panel Border
571        let border_color = if active_panel {
572            active_color
573        } else {
574            inactive_color
575        };
576        screen.boxfill(px, py, px + pw, py + ph, border_color);
577        screen.boxfill(px + 2, py + 2, px + pw - 2, py + ph - 2, bg);
578
579        let half_h = (ph - 4) / 2;
580
581        // --- Upper Pane: Horizontal Columns (Parent, Current, Child Preview) ---
582        let upper_py = py + 2;
583        let upper_ph = half_h;
584        let upper_active = active_panel && state.active_pane == 0;
585
586        screen.boxfill(
587            px + 4,
588            upper_py + 4,
589            px + pw - 4,
590            upper_py + upper_ph - 4,
591            list_bg,
592        );
593
594        // Draw Current Path Header
595        screen.draw_string_vector(
596            px + 8,
597            upper_py + 8,
598            &alloc::format!("Path: {}", state.current_path),
599            Color(config.theme.focus_highlight),
600            14,
601        );
602
603        // 3-Column horizontal division
604        let col_w = (pw - 20) / 3;
605        let col_h = upper_ph - 38;
606        let col_y = upper_py + 36;
607
608        // Draw Column Headers (Parent, Current, Child Preview)
609        let header_y = upper_py + 22;
610        screen.draw_string_vector(px + 10, header_y, "Parent", Color(config.theme.non_active_window_border), 10);
611        screen.draw_string_vector(px + 10 + col_w, header_y, "Current", Color(config.theme.active_window_border), 10);
612        screen.draw_string_vector(
613            px + 10 + col_w * 2,
614            header_y,
615            "Child Preview",
616            Color(config.theme.non_active_window_border),
617            10,
618        );
619
620        // 1. Column 1 (Left): Parent Directory Folders
621        let parent_path = if state.current_path == "/" {
622            String::from("/")
623        } else {
624            let mut p = state.current_path.trim_end_matches('/').to_string();
625            if let Some(idx) = p.rfind('/') {
626                p.truncate(idx + 1);
627                if p.is_empty() {
628                    String::from("/")
629                } else {
630                    p
631                }
632            } else {
633                String::from("/")
634            }
635        };
636
637        let parent_folders = if state.current_path == "/" {
638            Vec::new()
639        } else {
640            Self::get_folders_at(&parent_path)
641        };
642
643        // Draw column separator 1
644        screen.boxfill(
645            px + 4 + col_w,
646            col_y,
647            px + 4 + col_w + 1,
648            col_y + col_h,
649            Color(config.theme.non_active_window_border),
650        );
651
652        // Determine basename of current path for matching in parent column
653        let trimmed_cur = state.current_path.trim_end_matches('/');
654        let current_basename = match trimmed_cur.rfind('/') {
655            Some(idx) => trimmed_cur.get(idx + 1..).unwrap_or(""),
656            None => state.current_path.trim_start_matches('/'),
657        };
658
659        let line_h = 20;
660        let visible_lines = (col_h / line_h) as usize;
661
662        for i in 0..visible_lines {
663            if i >= parent_folders.len() {
664                break;
665            }
666            let y = col_y + i as u32 * line_h;
667            let is_matched = parent_folders[i] == current_basename;
668            let col_x0 = px + 6;
669
670            if is_matched {
671                // Highlight the matched parent folder with a subtle gray box
672                screen.boxfill(
673                    col_x0,
674                    y,
675                    px + 4 + col_w - 2,
676                    y + line_h - 2,
677                    Color(config.theme.button_bg),
678                );
679            }
680
681            screen.draw_svg_icon(col_x0 + 4, y + 3, ICON_FOLDER, 12, preview_color);
682            screen.draw_string_vector(
683                col_x0 + 20,
684                y + 2,
685                &alloc::format!("{} <", parent_folders[i]),
686                preview_color,
687                12,
688            );
689        }
690
691        // 2. Column 2 (Center): Current Directory Folders (Active Focus Column)
692        // Draw column separator 2
693        screen.boxfill(
694            px + 6 + col_w * 2,
695            col_y,
696            px + 6 + col_w * 2 + 1,
697            col_y + col_h,
698            Color(config.theme.non_active_window_border),
699        );
700
701        for i in 0..visible_lines {
702            let idx = state.scroll_folder + i;
703            if idx >= state.folders.len() {
704                break;
705            }
706
707            let y = col_y + i as u32 * line_h;
708            let selected = idx == state.selected_folder;
709            let col_x0 = px + 6 + col_w;
710            let col_x1 = px + 6 + col_w * 2 - 2;
711
712            if selected {
713                let sel_bg = if upper_active {
714                    active_color
715                } else {
716                    inactive_color
717                };
718                screen.boxfill(col_x0, y, col_x1, y + line_h - 2, sel_bg);
719                // フォーカスハイライト枠: アクティブパネルの選択行に明るいボーダー
720                if upper_active {
721                    let bord = Color(config.theme.focus_highlight);
722                    screen.boxfill(col_x0, y, col_x1, y + 1, bord);
723                    screen.boxfill(col_x0, y + line_h - 3, col_x1, y + line_h - 2, bord);
724                    screen.boxfill(col_x0, y, col_x0 + 1, y + line_h - 2, bord);
725                    screen.boxfill(col_x1 - 1, y, col_x1, y + line_h - 2, bord);
726                }
727            }
728
729            let fg_color = if selected && upper_active {
730                Color(config.theme.button_active_fg)
731            } else {
732                fg
733            };
734            let icon_color = if selected && upper_active {
735                Color(config.theme.active_window_border)
736            } else {
737                fg_color
738            };
739            screen.draw_svg_icon(col_x0 + 4, y + 3, ICON_FOLDER, 12, icon_color);
740            screen.draw_string_vector(
741                col_x0 + 20,
742                y + 2,
743                &alloc::format!("{} >", state.folders[idx]),
744                fg_color,
745                12,
746            );
747        }
748
749        // 3. Column 3 (Right): Child Directory Preview (Subfolders under currently selected folder)
750        let child_folders =
751            if !state.folders.is_empty() && state.selected_folder < state.folders.len() {
752                let mut child_path = state.current_path.clone();
753                if !child_path.ends_with('/') {
754                    child_path.push('/');
755                }
756                child_path.push_str(&state.folders[state.selected_folder]);
757                Self::get_folders_at(&child_path)
758            } else {
759                Vec::new()
760            };
761
762        for i in 0..visible_lines {
763            if i >= child_folders.len() {
764                break;
765            }
766            let y = col_y + i as u32 * line_h;
767            let col_x0 = px + 8 + col_w * 2;
768
769            screen.draw_svg_icon(col_x0 + 4, y + 3, ICON_FOLDER, 12, preview_color);
770            screen.draw_string_vector(col_x0 + 20, y + 2, &child_folders[i], preview_color, 12);
771        }
772
773        // --- Lower Pane: List (Files) ---
774        let lower_py = py + 2 + half_h;
775        let lower_ph = half_h;
776        let lower_active = active_panel && state.active_pane == 1;
777
778        screen.boxfill(
779            px + 4,
780            lower_py + 4,
781            px + pw - 4,
782            lower_py + lower_ph - 4,
783            list_bg,
784        );
785
786        let visible_files = ((lower_ph - 12) / line_h) as usize;
787
788        for i in 0..visible_files {
789            let idx = state.scroll_file + i;
790            if idx >= state.files.len() {
791                break;
792            }
793
794            let y = lower_py + 8 + i as u32 * line_h;
795            let selected = idx == state.selected_file;
796
797            if selected {
798                let sel_bg = if lower_active {
799                    active_color
800                } else {
801                    inactive_color
802                };
803                let x0 = px + 6;
804                let x1 = px + pw - 6;
805                screen.boxfill(x0, y, x1, y + line_h - 2, sel_bg);
806                // フォーカスハイライト枠
807                if lower_active {
808                    let bord = Color(config.theme.focus_highlight);
809                    screen.boxfill(x0, y, x1, y + 1, bord);
810                    screen.boxfill(x0, y + line_h - 3, x1, y + line_h - 2, bord);
811                    screen.boxfill(x0, y, x0 + 1, y + line_h - 2, bord);
812                    screen.boxfill(x1 - 1, y, x1, y + line_h - 2, bord);
813                }
814            }
815
816            let fg_color = if selected && lower_active {
817                Color(config.theme.button_active_fg)
818            } else {
819                fg
820            };
821            let filename = state.files[idx].get_filename();
822
823            // Extract just the basename for display
824            let basename = match filename.rfind('/') {
825                Some(slash_idx) => filename.get(slash_idx + 1..).unwrap_or(""),
826                None => filename,
827            };
828
829            let icon_color = if selected && lower_active {
830                Color(config.theme.active_window_border)
831            } else {
832                fg_color
833            };
834            screen.draw_svg_icon(px + 12, y + 3, ICON_FILE, 12, icon_color);
835            screen.draw_string_vector(px + 30, y + 2, basename, fg_color, 14);
836        }
837    }
838}
839
840impl App for FilesApp {
841    fn name(&self) -> &str {
842        "files"
843    }
844
845    fn draw(&mut self, screen: &Screen, win_x: u32, win_y: u32, win_w: u32, win_h: u32) {
846        self.last_win_w = win_w;
847        self.last_win_h = win_h;
848
849        let config = config::get_config();
850        let bg_color = Color(config.theme.desktop_bg);
851        let header_bg = Color(config.theme.window_title_bar);
852
853        // Background
854        screen.boxfill(win_x, win_y, win_x + win_w, win_y + win_h, bg_color);
855
856        // Top Toolbar
857        screen.boxfill(win_x, win_y, win_x + win_w, win_y + 26, header_bg);
858        screen.draw_string_vector(
859            win_x + 10,
860            win_y + 5,
861            "2x2 Grid Filer",
862            Color(config.theme.window_title_fg),
863            14,
864        );
865
866        // Layout Dimensions
867        let panel_w = (win_w - 20) / 2;
868        let panel_h = win_h - 60; // Leave room for top toolbar and bottom status
869
870        // Left Panel
871        self.draw_panel(
872            screen,
873            false,
874            win_x + 6,
875            win_y + 30,
876            panel_w,
877            panel_h,
878            self.active_panel() == 0,
879        );
880
881        // Right Panel
882        self.draw_panel(
883            screen,
884            true,
885            win_x + 10 + panel_w,
886            win_y + 30,
887            panel_w,
888            panel_h,
889            self.active_panel() == 1,
890        );
891
892        // Status Bar
893        let footer_y = win_y + win_h - 24;
894        screen.boxfill(win_x, footer_y, win_x + win_w, win_y + win_h, header_bg);
895        screen.draw_string_vector(win_x + 8, footer_y + 4, &self.status, Color(config.theme.window_title_fg), 14);
896    }
897
898    fn on_mouse(
899        &mut self,
900        _local_x: i32,
901        _local_y: i32,
902        _btn_left: bool,
903        _btn_right: bool,
904        _wheel: i32,
905    ) {
906        // Filer is now keyboard-driven. Mouse support minimized.
907    }
908
909    fn on_key(&mut self, keycode: u8, pressed: bool, _ascii: Option<char>) {
910        if keycode == 0x38 {
911            // Alt key
912            self.alt_held = pressed;
913            return;
914        }
915
916        if keycode == 0x1D {
917            // Ctrl key
918            self.ctrl_held = pressed;
919            return;
920        }
921
922        if !pressed {
923            return;
924        }
925
926        // --- 1. ショートカットマネージャによる優先度付き評価 ---
927        let mods = Modifiers::new(self.ctrl_held, self.alt_held, false);
928        let action = self.shortcut_mgr.evaluate(keycode, mods);
929
930        match action {
931            InputAction::AppCommand(cmd) => {
932                match cmd {
933                    CMD_FOCUS_UP => {
934                        self.active_state().active_pane = 0;
935                    }
936                    CMD_FOCUS_DOWN => {
937                        self.active_state().active_pane = 1;
938                    }
939                    CMD_FOCUS_LEFT => {
940                        self.set_active_panel(0);
941                    }
942                    CMD_FOCUS_RIGHT => {
943                        self.set_active_panel(1);
944                    }
945
946                    CMD_TAB_PREV => {
947                        self.active_tab = self.active_tab.saturating_sub(1);
948                    }
949                    CMD_TAB_NEXT => {
950                        self.active_tab = (self.active_tab + 1).min(self.tabs.len().saturating_sub(1));
951                    }
952                    CMD_FILE_COPY => {
953                        self.copy_to_inactive_panel();
954                    }
955                    CMD_FILE_MOVE => {
956                        self.move_to_inactive_panel();
957                    }
958
959                    CMD_NAV_UP | CMD_NAV_DOWN | CMD_NAV_LEFT | CMD_NAV_RIGHT | CMD_ENTER
960                    | CMD_DELETE => {
961                        let state = self.active_state();
962                        let is_up = cmd == CMD_NAV_UP;
963                        let is_down = cmd == CMD_NAV_DOWN;
964                        let is_left = cmd == CMD_NAV_LEFT;
965                        let is_right = cmd == CMD_NAV_RIGHT;
966
967                        if state.active_pane == 0 {
968                            // Folder Pane
969                            if is_up && state.selected_folder > 0 {
970                                state.selected_folder -= 1;
971                                if state.selected_folder < state.scroll_folder {
972                                    state.scroll_folder = state.selected_folder;
973                                }
974                            } else if is_down && state.selected_folder + 1 < state.folders.len() {
975                                state.selected_folder += 1;
976                                if state.selected_folder >= state.scroll_folder + 10 {
977                                    state.scroll_folder += 1;
978                                }
979                            } else if is_right && !state.folders.is_empty() {
980                                // Enter Folder
981                                let folder_name = &state.folders[state.selected_folder];
982                                let mut new_path = state.current_path.clone();
983                                if !new_path.ends_with('/') {
984                                    new_path.push('/');
985                                }
986                                new_path.push_str(folder_name);
987                                state.current_path = new_path;
988                                state.refresh();
989                            } else if is_left && state.current_path != "/" {
990                                // Go Up Directory
991                                let mut p = state.current_path.trim_end_matches('/').to_string();
992                                if let Some(idx) = p.rfind('/') {
993                                    p.truncate(idx + 1);
994                                    if p.is_empty() {
995                                        p = String::from("/");
996                                    }
997                                } else {
998                                    p = String::from("/");
999                                }
1000                                state.current_path = p;
1001                                state.refresh();
1002                            }
1003                        } else {
1004                            // File Pane
1005                            if is_up && state.selected_file > 0 {
1006                                state.selected_file -= 1;
1007                                if state.selected_file < state.scroll_file {
1008                                    state.scroll_file = state.selected_file;
1009                                }
1010                            } else if is_down && state.selected_file + 1 < state.files.len() {
1011                                state.selected_file += 1;
1012                                if state.selected_file >= state.scroll_file + 10 {
1013                                    state.scroll_file += 1;
1014                                }
1015                            } else if cmd == CMD_ENTER {
1016                                // Enter -> Open
1017                            } else if cmd == CMD_DELETE {
1018                                // Delete -> Delete
1019                            }
1020                        }
1021                    }
1022                    _ => {}
1023                }
1024            }
1025            _ => {
1026                // Not an AppCommand, or Ignore
1027            }
1028        }
1029
1030        // --- 2. ミュータブル借用のスコープを分ける処理 ---
1031        // CMD_ENTER / CMD_DELETE は FilerApp 全体のメソッド呼び出しを伴うためここで処理
1032        if let InputAction::AppCommand(cmd) = action {
1033            if cmd == CMD_ENTER && self.active_state().active_pane == 1 {
1034                self.open_selected();
1035            } else if cmd == CMD_DELETE && self.active_state().active_pane == 1 {
1036                self.delete_selected();
1037            }
1038        }
1039    }
1040
1041    fn tabs(&self) -> Vec<String> {
1042        let mut titles = Vec::new();
1043        for (i, tab) in self.tabs.iter().enumerate() {
1044            let left_name = tab.left.current_path.trim_end_matches('/').split('/').next_back().unwrap_or("");
1045            let right_name = tab.right.current_path.trim_end_matches('/').split('/').next_back().unwrap_or("");
1046            let l_label = if left_name.is_empty() { "Root" } else { left_name };
1047            let r_label = if right_name.is_empty() { "Root" } else { right_name };
1048            titles.push(alloc::format!("{}: {} | {}", i + 1, l_label, r_label));
1049        }
1050        titles
1051    }
1052
1053    fn active_tab(&self) -> usize {
1054        self.active_tab
1055    }
1056
1057    fn close_tab(&mut self, idx: usize) -> bool {
1058        if self.tabs.len() > 1 && idx < self.tabs.len() {
1059            self.tabs.remove(idx);
1060            if self.active_tab >= self.tabs.len() {
1061                self.active_tab = self.tabs.len() - 1;
1062            }
1063            false
1064        } else {
1065            true
1066        }
1067    }
1068
1069    fn switch_tab(&mut self, idx: usize) {
1070        if idx < self.tabs.len() {
1071            self.active_tab = idx;
1072        }
1073    }
1074
1075    fn add_tab(&mut self) {
1076        self.tabs.push(TabState {
1077            left: FilerState::new("/"),
1078            right: FilerState::new("/apps"),
1079            active_panel: 0,
1080        });
1081        self.active_tab = self.tabs.len() - 1;
1082    }
1083}