Skip to main content

atmos/apps/note/
mod.rs

1//! マルチタブテキストエディタアプリ。
2//!
3//! [`NoteTab`] ごとに独立したファイル内容を保持し、複数ファイルをタブで切替編集できる。
4//! `.aura` スクリプトの編集・実行結果表示(出力ペイン)も兼ねる。
5// note.rs - Note Multi-Tab Text Editor Application for AtmOS
6#![allow(dead_code)]
7
8use crate::kernel::draw::{Color, Screen};
9use crate::os_lib::web_engine::WebEngine;
10use alloc::string::String;
11use alloc::vec::Vec;
12
13const MENU_HEIGHT: u32 = 24;
14
15/// 1つのノートタブが持つ状態
16struct NoteTab {
17    filename: String,
18    content: String,
19    dirty: bool,
20}
21
22impl NoteTab {
23    fn new_untitled() -> Self {
24        Self {
25            filename: String::from("Untitled"),
26            content: String::new(),
27            dirty: false,
28        }
29    }
30
31    fn title(&self) -> String {
32        if self.dirty {
33            alloc::format!("* {}", self.filename)
34        } else {
35            self.filename.clone()
36        }
37    }
38}
39
40pub struct NoteApp {
41    tabs_data: Vec<NoteTab>,
42    active_idx: usize,
43    pub engine: WebEngine,
44    pub last_win_w: u32,
45    pub last_win_h: u32,
46    pub show_menu: bool,
47    pub open_menu: Option<u8>, // 0:File, 1:Edit, 2:Run, 3:Format, 4:View, 5:Help
48    pub last_btn: bool,
49    ctrl_held: bool,
50    alt_held: bool,
51
52    // スライドパネル(Open/Save)
53    pub panel_slide: i32,
54    pub panel_mode: u8, // 0: None, 1: Open, 2: Save
55    pub panel_files: Vec<String>,
56    pub panel_input: String,
57    pub panel_selected: Option<usize>,
58
59    // 実行結果ペインの状態
60    pub output_panel_open: bool,
61    pub output_text: String,
62    pub output_panel_height: u32,
63}
64
65impl Default for NoteApp {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl NoteApp {
72    /// 外部からファイルを指定して開くためのヘルパー(FilesApp・Aura から呼び出し)
73    pub fn open_file(filename: &str, content: &str) -> Self {
74        let mut app = Self::new();
75        if let Some(tab) = app.tabs_data.get_mut(0) {
76            tab.filename = String::from(filename);
77            tab.content = String::from(content);
78            tab.dirty = false;
79        }
80        app.engine
81            .form_values
82            .insert(String::from("editor"), String::from(content));
83        app.engine
84            .form_values
85            .insert(String::from("filename"), String::from(filename));
86        app.engine.dirty = true;
87        app
88    }
89
90    pub fn new() -> Self {
91        let mut engine = WebEngine::new();
92        engine
93            .form_values
94            .insert(String::from("filename"), String::from("Untitled"));
95        engine.parse_and_layout(
96            r#"<style>html, body { width: 100%; height: 100%; margin: 0; padding: 0; background-color: #1E1F29; overflow: hidden; } textarea { width: 100%; height: 100%; margin: 0; padding: 4px; border: none; outline: none; background-color: #1E1F29; color: #F8F8F2; box-sizing: border-box; }</style><textarea id="editor" autofocus></textarea>"#,
97            None,
98            0, 600, 450,
99        );
100        Self {
101            tabs_data: alloc::vec![NoteTab::new_untitled()],
102            active_idx: 0,
103            engine,
104            last_win_w: 600,
105            last_win_h: 450,
106            show_menu: false,
107            open_menu: None,
108            last_btn: false,
109            ctrl_held: false,
110            alt_held: false,
111            panel_slide: 0,
112            panel_mode: 0,
113            panel_files: Vec::new(),
114            panel_input: String::new(),
115            panel_selected: None,
116            output_panel_open: false,
117            output_text: String::new(),
118            output_panel_height: 120,
119        }
120    }
121
122    // エンジンの内容を現在のタブに同期する
123    fn flush_current_tab(&mut self) {
124        if let Some(content) = self.engine.form_values.get("editor") {
125            let content = content.clone();
126            if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
127                if tab.content != content {
128                    tab.content = content;
129                    tab.dirty = true;
130                }
131            }
132        }
133    }
134
135    // タブのコンテンツをエンジンに反映する
136    fn load_tab_into_engine(&mut self, idx: usize) {
137        if idx >= self.tabs_data.len() {
138            return;
139        }
140        let content = self.tabs_data[idx].content.clone();
141        let filename = self.tabs_data[idx].filename.clone();
142        self.engine
143            .form_values
144            .insert(String::from("editor"), content);
145        self.engine
146            .form_values
147            .insert(String::from("filename"), filename);
148        self.engine.dirty = true;
149    }
150
151    fn open_panel(&mut self, mode: u8) {
152        self.flush_current_tab();
153        self.panel_mode = mode;
154        if let Some(tab) = self.tabs_data.get(self.active_idx) {
155            self.panel_input = tab.filename.clone();
156        }
157        self.panel_selected = None;
158        self.panel_files.clear();
159        let fs = crate::kernel::fs::get_fs();
160        for meta in fs.list_files() {
161            self.panel_files.push(String::from(meta.get_filename()));
162        }
163    }
164
165    fn save_current(&mut self) {
166        self.flush_current_tab();
167        let (filename, content) = if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
168            (tab.filename.clone(), tab.content.clone())
169        } else {
170            return;
171        };
172
173        let fs = crate::kernel::fs::get_fs();
174        if fs.save_file(&filename, content.as_bytes(), "note").is_ok() {
175            crate::info!("[FS] Note: Saved to {}", filename);
176            if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
177                tab.dirty = false;
178            }
179            self.engine
180                .form_values
181                .insert(String::from("filename"), filename.clone());
182            crate::kernel::window_mgr::get_instance().dirty = true;
183        } else {
184            crate::error!("[FS] Note: Failed to save {}", filename);
185        }
186    }
187
188    fn load_file_into_current(&mut self) {
189        let filename = if let Some(tab) = self.tabs_data.get(self.active_idx) {
190            tab.filename.clone()
191        } else {
192            return;
193        };
194
195        let fs = crate::kernel::fs::get_fs();
196        if let Some((_, content_bytes)) = fs.read_file_checked(&filename).ok().flatten() {
197            if let Ok(content_str) = core::str::from_utf8(&content_bytes) {
198                if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
199                    tab.content = String::from(content_str);
200                    tab.dirty = false;
201                }
202                self.load_tab_into_engine(self.active_idx);
203                crate::info!("[FS] Note: Loaded from {}", filename);
204                crate::kernel::window_mgr::get_instance().dirty = true;
205            }
206        }
207    }
208
209    fn new_tab_action(&mut self) {
210        self.flush_current_tab();
211        self.tabs_data.push(NoteTab::new_untitled());
212        let new_idx = self.tabs_data.len() - 1;
213        self.active_idx = new_idx;
214        self.load_tab_into_engine(new_idx);
215        // WM側にタブ追加を通知しない(tabs()の戻り値が変わるので次のdraw_allで反映)
216        crate::kernel::window_mgr::get_instance().dirty = true;
217    }
218
219    /// Aura をサンドボックス内で実行する
220    fn run_script(&mut self) {
221        self.flush_current_tab();
222        let content = self
223            .engine
224            .form_values
225            .get("editor")
226            .cloned()
227            .unwrap_or_default();
228
229        self.output_text = String::from("Running script...\n");
230        self.output_panel_open = true;
231        crate::kernel::window_mgr::get_instance().dirty = true;
232
233        // グローバル環境をキーボードなしでセットアップ
234        let mut run_env = crate::os_lib::aura::eval::setup_global_env(core::ptr::null_mut());
235
236        // サンドボックスを上書き設定(権限が空、名前を "note_sandbox" に設定)
237        let manifest = crate::kernel::app_sandbox::AppManifest {
238            name: String::from("note_sandbox"),
239            permissions: alloc::vec![], // 権限なし (fs_user, fs_global もなし)
240            ..Default::default()
241        };
242
243        let mut sandbox = crate::kernel::app_sandbox::AppSandbox::new(0, manifest);
244        sandbox.data_dir = String::from("/apps/note/sandbox/");
245        run_env.sandbox = Some(sandbox);
246
247        // カレントディレクトリを制限フォルダにする
248        run_env.set(
249            alloc::string::String::from("cwd"),
250            crate::os_lib::aura::eval::Value::Str(String::from("/apps/note/sandbox/")),
251        );
252
253        // 実行して出力を受ける
254        let result = crate::os_lib::aura::eval_string(&content, &mut run_env);
255
256        if result.is_empty() {
257            self.output_text = String::from("Execution finished (no output).");
258        } else {
259            self.output_text = result;
260        }
261    }
262}
263
264impl crate::kernel::window_mgr::App for NoteApp {
265    fn name(&self) -> &str {
266        "note"
267    }
268
269    fn instance_info(&self) -> String {
270        if let Some(tab) = self.tabs_data.get(self.active_idx) {
271            tab.filename.clone()
272        } else {
273            String::from("Note")
274        }
275    }
276
277    fn draw(&mut self, screen: &Screen, win_x: u32, win_y: u32, win_w: u32, win_h: u32) {
278        let config = crate::kernel::config::get_config();
279        let bg_color = Color(config.theme.active_window_border);
280        let text_color = Color(config.theme.window_title_fg);
281        let highlight = Color(config.theme.focus_highlight);
282
283        // リサイズ・表示状態変化検出
284        let target_editor_h = if self.output_panel_open {
285            win_h
286                .saturating_sub(MENU_HEIGHT)
287                .saturating_sub(self.output_panel_height)
288        } else {
289            win_h.saturating_sub(MENU_HEIGHT)
290        };
291
292        if self.last_win_w != win_w
293            || self.last_win_h != win_h
294            || self.engine.win_h != target_editor_h
295        {
296            self.last_win_w = win_w;
297            self.last_win_h = win_h;
298            self.engine.win_w = win_w;
299            self.engine.win_h = target_editor_h;
300            let html = self.engine.last_html.clone();
301            self.engine
302                .parse_and_layout(&html, None, 0, self.engine.win_w, self.engine.win_h);
303        }
304
305        // エンジン内の変更をタブに同期(描画前)
306        if let Some(content) = self.engine.form_values.get("editor") {
307            let content = content.clone();
308            if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
309                if !tab.dirty && tab.content != content {
310                    tab.dirty = true;
311                    crate::kernel::window_mgr::get_instance().dirty = true;
312                }
313                tab.content = content;
314            }
315        }
316
317        // 1. ネイティブメニューバー
318        screen.boxfill(
319            win_x,
320            win_y,
321            win_x + win_w - 1,
322            win_y + MENU_HEIGHT - 1,
323            bg_color,
324        );
325        let menus = ["File", "Edit", "Run", "Format", "View", "Help"];
326        for (i, title) in menus.iter().enumerate() {
327            let mx = win_x + 10 + (i as u32 * 55);
328            if Some(i as u8) == self.open_menu {
329                screen.boxfill(mx - 5, win_y, mx + 45, win_y + MENU_HEIGHT - 1, highlight);
330            }
331            screen.draw_string_vector(mx, win_y + 4, title, text_color, 14);
332        }
333
334        // 2. テキストエリア本体
335        if win_h > MENU_HEIGHT {
336            let editor_h = if self.output_panel_open {
337                win_h
338                    .saturating_sub(MENU_HEIGHT)
339                    .saturating_sub(self.output_panel_height)
340            } else {
341                win_h.saturating_sub(MENU_HEIGHT)
342            };
343            if editor_h > 0 {
344                self.engine
345                    .draw(screen, win_x, win_y + MENU_HEIGHT, win_w, editor_h, 0);
346            }
347        }
348
349        // 3. ドロップダウンメニュー
350        if let Some(menu_idx) = self.open_menu {
351            let mx = win_x + 10 + (menu_idx as u32 * 55) - 5;
352            let my = win_y + MENU_HEIGHT;
353            let mw = 200u32;
354            let items: &[(&str, &str)] = match menu_idx {
355                0 => &[
356                    ("New Tab", "Alt+T"),
357                    ("Open...", "Alt+O"),
358                    ("Save", "Alt+S"),
359                    ("Save As...", ""),
360                ],
361                1 => &[("Undo", ""), ("Cut", ""), ("Copy", ""), ("Paste", "")],
362                2 => &[], // Run はクリック時に即実行
363                3 => &[(
364                    if self.engine.editor_wrap {
365                        "Word Wrap: ON"
366                    } else {
367                        "Word Wrap: OFF"
368                    },
369                    "",
370                )],
371                4 => &[
372                    ("Zoom In", ""),
373                    ("Zoom Out", ""),
374                    ("Toggle Output", "Alt+P"),
375                ],
376                5 => &[("About AtmNote", "")],
377                _ => &[],
378            };
379
380            let mh = (items.len() as u32) * 24 + 4;
381            if mh > 4 {
382                screen.boxfill(mx + 2, my + 2, mx + mw + 2, my + mh + 2, Color(0x80000000));
383                screen.boxfill(mx, my, mx + mw, my + mh, bg_color);
384
385                for (j, (label, shortcut)) in items.iter().enumerate() {
386                    let iy = my + 4 + (j as u32 * 24);
387                    screen.draw_string_vector(mx + 10, iy, label, text_color, 14);
388                    if !shortcut.is_empty() {
389                        screen.draw_string_vector(
390                            mx + mw - 60,
391                            iy,
392                            shortcut,
393                            Color(config.theme.app_fg),
394                            12,
395                        );
396                    }
397                }
398            }
399        }
400
401        // 4. スライドパネル(Open/Save)
402        if self.panel_mode > 0 {
403            if self.panel_slide < 100 {
404                self.panel_slide += 10;
405                if self.panel_slide > 100 {
406                    self.panel_slide = 100;
407                }
408                crate::kernel::window_mgr::get_instance().dirty = true;
409            }
410        } else if self.panel_slide > 0 {
411            self.panel_slide -= 10;
412            if self.panel_slide < 0 {
413                self.panel_slide = 0;
414            }
415            crate::kernel::window_mgr::get_instance().dirty = true;
416        }
417
418        if self.panel_slide > 0 {
419            let panel_w = 300u32;
420            let current_w = (panel_w * self.panel_slide as u32) / 100;
421            let px = win_x + win_w - current_w;
422            let py = win_y + MENU_HEIGHT;
423            let ph = win_h.saturating_sub(MENU_HEIGHT);
424
425            screen.boxfill(px, py, win_x + win_w, py + ph, Color(config.theme.app_bg));
426            screen.boxfill(px.saturating_sub(2), py, px, py + ph, Color(0x80000000));
427
428            if self.panel_slide >= 100 {
429                let title = if self.panel_mode == 1 {
430                    "Open File"
431                } else {
432                    "Save As"
433                };
434                screen.draw_string_vector(px + 10, py + 10, title, Color(config.theme.app_fg), 18);
435
436                let list_y = py + 40;
437                let list_h = ph.saturating_sub(120);
438                screen.boxfill(
439                    px + 10,
440                    list_y,
441                    px + panel_w - 10,
442                    list_y + list_h,
443                    Color(config.theme.terminal_bg),
444                );
445                for (i, file) in self.panel_files.iter().take(12).enumerate() {
446                    let item_y = list_y + (i as u32) * 22;
447                    if Some(i) == self.panel_selected {
448                        screen.boxfill(
449                            px + 10,
450                            item_y,
451                            px + panel_w - 10,
452                            item_y + 22,
453                            Color(config.theme.focus_highlight),
454                        );
455                    }
456                    screen.draw_string_vector(
457                        px + 15,
458                        item_y + 3,
459                        file,
460                        Color(config.theme.app_fg),
461                        13,
462                    );
463                }
464
465                let input_y = py + ph.saturating_sub(70);
466                screen.boxfill(
467                    px + 10,
468                    input_y,
469                    px + panel_w - 10,
470                    input_y + 24,
471                    Color(config.theme.terminal_bg),
472                );
473                screen.draw_string_vector(
474                    px + 15,
475                    input_y + 4,
476                    &self.panel_input,
477                    Color(config.theme.app_fg),
478                    14,
479                );
480                // カーソル
481                let cx = px + 15 + (self.panel_input.len() as u32 * 8);
482                screen.boxfill(
483                    cx,
484                    input_y + 4,
485                    cx + 1,
486                    input_y + 18,
487                    Color(config.theme.app_fg),
488                );
489
490                let btn_y = py + ph.saturating_sub(35);
491                screen.boxfill(
492                    px + 10,
493                    btn_y,
494                    px + 80,
495                    btn_y + 24,
496                    Color(config.theme.focus_highlight),
497                );
498                screen.draw_string_vector(px + 20, btn_y + 4, "Cancel", text_color, 14);
499                screen.boxfill(
500                    px + 100,
501                    btn_y,
502                    px + 180,
503                    btn_y + 24,
504                    Color(config.theme.button_active_bg),
505                );
506                let action_label = if self.panel_mode == 1 { "Open" } else { "Save" };
507                screen.draw_string_vector(px + 120, btn_y + 4, action_label, text_color, 14);
508            }
509        }
510
511        // 5. 出力ペイン (Execution Output)
512        if self.output_panel_open {
513            let py = win_y + win_h - self.output_panel_height;
514            let ph = self.output_panel_height;
515            let px = win_x;
516            let pw = win_w;
517
518            // 背景塗りつぶし
519            screen.boxfill(px, py, px + pw - 1, py + ph - 1, Color(config.theme.ui_overlay_bg));
520            // 上部境界線
521            screen.boxfill(
522                px,
523                py,
524                px + pw - 1,
525                py + 1,
526                Color(config.theme.active_window_border),
527            );
528
529            // タイトルバー
530            let title_bg = Color(config.theme.active_window_border);
531            let title_h = 20u32;
532            screen.boxfill(px, py + 2, px + pw - 1, py + title_h - 1, title_bg);
533            screen.draw_string_vector(
534                px + 10,
535                py + 4,
536                "Execution Output",
537                Color(config.theme.window_title_fg),
538                12,
539            );
540
541            // [X] 閉じるボタン
542            let close_btn_w = 20u32;
543            let bx1 = px + pw - close_btn_w - 5;
544            let bx2 = px + pw - 5;
545            screen.boxfill(bx1, py + 3, bx2, py + title_h - 3, Color(config.theme.win_btn_close));
546            screen.draw_string_vector(bx1 + 6, py + 4, "X", Color(config.theme.browser_fg), 11);
547
548            // テキスト表示領域
549            let text_y_start = py + title_h + 5;
550            let text_h_limit = ph.saturating_sub(title_h).saturating_sub(10);
551            let line_height = 16u32;
552            let max_display_lines = (text_h_limit / line_height) as usize;
553
554            let lines: Vec<&str> = self.output_text.split('\n').collect();
555            let start_line = if lines.len() > max_display_lines {
556                lines.len() - max_display_lines
557            } else {
558                0
559            };
560
561            for (i, line) in lines[start_line..].iter().enumerate() {
562                let ly = text_y_start + (i as u32 * line_height);
563                let text_color = if line.starts_with("Eval Error:")
564                    || line.starts_with("Syntax Error:")
565                    || line.starts_with("Error:")
566                {
567                    Color(config.theme.error_fg)
568                } else {
569                    Color(config.theme.browser_fg)
570                };
571                screen.draw_string_vector(px + 15, ly, line, text_color, 12);
572            }
573        }
574    }
575
576    fn on_mouse(
577        &mut self,
578        local_x: i32,
579        local_y: i32,
580        btn_left: bool,
581        btn_right: bool,
582        wheel: i32,
583    ) {
584        let just_pressed = btn_left && !self.last_btn;
585        self.last_btn = btn_left;
586
587        // パネルが開いている場合
588        if self.panel_mode > 0 && self.panel_slide >= 100 {
589            if just_pressed {
590                let panel_w = 300i32;
591                let px = self.last_win_w as i32 - panel_w;
592                if local_x >= px {
593                    let py = MENU_HEIGHT as i32;
594                    let ph = self.last_win_h as i32 - MENU_HEIGHT as i32;
595                    let list_y = py + 40;
596                    let list_h = ph - 120;
597
598                    if local_y >= list_y && local_y <= list_y + list_h {
599                        let idx = (local_y - list_y) / 22;
600                        if idx >= 0 && (idx as usize) < self.panel_files.len() {
601                            self.panel_selected = Some(idx as usize);
602                            self.panel_input = self.panel_files[idx as usize].clone();
603                            crate::kernel::window_mgr::get_instance().dirty = true;
604                        }
605                    }
606
607                    let btn_y = py + ph - 35;
608                    if local_y >= btn_y && local_y <= btn_y + 24 {
609                        if local_x >= px + 10 && local_x <= px + 80 {
610                            self.panel_mode = 0;
611                        } else if local_x >= px + 100
612                            && local_x <= px + 180
613                            && !self.panel_input.is_empty()
614                        {
615                            if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
616                                tab.filename = self.panel_input.clone();
617                            }
618                            if self.panel_mode == 1 {
619                                self.load_file_into_current();
620                            } else {
621                                self.save_current();
622                            }
623                            self.panel_mode = 0;
624                        }
625                    }
626                } else {
627                    self.panel_mode = 0;
628                }
629            }
630            return;
631        }
632
633        // 下ペインの [X] 閉じるボタンのクリック判定
634        if self.output_panel_open {
635            let py = self.last_win_h as i32 - self.output_panel_height as i32;
636            let close_btn_w = 20i32;
637            let bx1 = self.last_win_w as i32 - close_btn_w - 5;
638            let bx2 = self.last_win_w as i32 - 5;
639            if just_pressed
640                && local_y >= py + 3
641                && local_y <= py + 17
642                && local_x >= bx1
643                && local_x <= bx2
644            {
645                self.output_panel_open = false;
646                crate::kernel::window_mgr::get_instance().dirty = true;
647                return;
648            }
649        }
650
651        if just_pressed {
652            // ドロップダウンが開いている場合の処理
653            if let Some(menu_idx) = self.open_menu {
654                let mx = 10 + (menu_idx as i32 * 55) - 5;
655                let my = MENU_HEIGHT as i32;
656                let mw = 200;
657                let items_len: i32 = match menu_idx {
658                    0 => 4,
659                    1 => 4,
660                    2 => 0,
661                    3 => 1,
662                    4 => 3,
663                    5 => 1,
664                    _ => 0,
665                };
666                let mh = items_len * 24 + 4;
667
668                if items_len > 0
669                    && local_x >= mx
670                    && local_x <= mx + mw
671                    && local_y >= my
672                    && local_y <= my + mh
673                {
674                    let item_idx = (local_y - my - 2) / 24;
675                    if menu_idx == 0 {
676                        // File
677                        match item_idx {
678                            0 => self.new_tab_action(), // New Tab
679                            1 => self.open_panel(1),    // Open...
680                            2 => self.save_current(),   // Save
681                            3 => self.open_panel(2),    // Save As...
682                            _ => {}
683                        }
684                    } else if menu_idx == 3 {
685                        // Format
686                        if item_idx == 0 {
687                            self.engine.editor_wrap = !self.engine.editor_wrap;
688                            self.engine.dirty = true;
689                            let html = self.engine.last_html.clone();
690                            self.engine.parse_and_layout(
691                                &html,
692                                None,
693                                0,
694                                self.engine.win_w,
695                                self.engine.win_h,
696                            );
697                        }
698                    } else if menu_idx == 4 {
699                        // View
700                        if item_idx == 2 {
701                            self.output_panel_open = !self.output_panel_open;
702                            crate::kernel::window_mgr::get_instance().dirty = true;
703                        }
704                    }
705                }
706                self.open_menu = None;
707                return;
708            }
709
710            // メニューバークリック
711            if local_y < MENU_HEIGHT as i32 {
712                if (5..60).contains(&local_x) {
713                    self.open_menu = Some(0);
714                } else if (60..115).contains(&local_x) {
715                    self.open_menu = Some(1);
716                } else if (115..170).contains(&local_x) {
717                    self.open_menu = None;
718                    self.run_script();
719                } else if (170..225).contains(&local_x) {
720                    self.open_menu = Some(3);
721                } else if (225..280).contains(&local_x) {
722                    self.open_menu = Some(4);
723                } else if (280..335).contains(&local_x) {
724                    self.open_menu = Some(5);
725                }
726                return;
727            }
728        }
729
730        // テキストエリアへのイベント委譲
731        let editor_h = if self.output_panel_open {
732            self.last_win_h
733                .saturating_sub(MENU_HEIGHT)
734                .saturating_sub(self.output_panel_height)
735        } else {
736            self.last_win_h.saturating_sub(MENU_HEIGHT)
737        };
738        if self.open_menu.is_none()
739            && local_y >= MENU_HEIGHT as i32
740            && local_y < (MENU_HEIGHT + editor_h) as i32
741        {
742            self.engine.on_mouse(
743                local_x,
744                local_y - MENU_HEIGHT as i32,
745                btn_left,
746                btn_right,
747                wheel,
748                0,
749            );
750        }
751    }
752
753    fn on_key(&mut self, keycode: u8, pressed: bool, ascii: Option<char>) {
754        // Ctrl キー状態を追跡
755        if keycode == 0x1D {
756            self.ctrl_held = pressed;
757            return;
758        }
759
760        // Alt キー状態を追跡
761        if keycode == 0x38 {
762            self.alt_held = pressed;
763            return;
764        }
765
766        // Alt+P で出力ペインをトグル
767        if pressed && self.alt_held && keycode == 0x19 {
768            self.output_panel_open = !self.output_panel_open;
769            crate::kernel::window_mgr::get_instance().dirty = true;
770            return;
771        }
772
773        if self.panel_mode > 0 {
774            if !pressed {
775                return;
776            }
777            match keycode {
778                0x01 => {
779                    self.panel_mode = 0;
780                } // ESC
781                0x1C => {
782                    // Enter
783                    if !self.panel_input.is_empty() {
784                        if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
785                            tab.filename = self.panel_input.clone();
786                        }
787                        if self.panel_mode == 1 {
788                            self.load_file_into_current();
789                        } else {
790                            self.save_current();
791                        }
792                        self.panel_mode = 0;
793                    }
794                }
795                0x0E => {
796                    self.panel_input.pop();
797                } // Backspace
798                _ => {
799                    if let Some(ch) = ascii {
800                        if ch.is_ascii_alphanumeric()
801                            || ch == '.'
802                            || ch == '_'
803                            || ch == '-'
804                            || ch == '/'
805                        {
806                            self.panel_input.push(ch);
807                        }
808                    }
809                }
810            }
811            crate::kernel::window_mgr::get_instance().dirty = true;
812            return;
813        }
814
815        if self.open_menu.is_some() {
816            if pressed && keycode == 0x01 {
817                self.open_menu = None;
818            }
819            return;
820        }
821
822        // Ctrl+ショートカットはエディタ内操作(Emacs互換)に委ねる
823        // ファイル操作は Alt+O / Alt+S(OSグローバルショートカット)
824
825        self.engine.on_key(keycode, pressed, ascii);
826    }
827
828    fn open_file_dialog(&mut self) {
829        self.open_panel(1);
830    }
831
832    fn save_file(&mut self) {
833        if self
834            .tabs_data
835            .get(self.active_idx)
836            .map(|t| t.filename == "Untitled")
837            .unwrap_or(true)
838        {
839            self.open_panel(2); // ファイル名未設定なら Save As ダイアログへ
840        } else {
841            self.save_current();
842        }
843    }
844
845    fn tabs(&self) -> Vec<String> {
846        self.tabs_data.iter().map(|t| t.title()).collect()
847    }
848
849    fn active_tab(&self) -> usize {
850        self.active_idx
851    }
852
853    fn switch_tab(&mut self, idx: usize) {
854        if idx >= self.tabs_data.len() || idx == self.active_idx {
855            return;
856        }
857        self.flush_current_tab();
858        self.active_idx = idx;
859        self.load_tab_into_engine(idx);
860    }
861
862    fn add_tab(&mut self) {
863        self.new_tab_action();
864    }
865
866    fn close_tab(&mut self, idx: usize) -> bool {
867        if self.tabs_data.is_empty() {
868            return true;
869        }
870        self.flush_current_tab();
871        self.tabs_data.remove(idx);
872        if self.tabs_data.is_empty() {
873            self.engine.active = false;
874            return true;
875        }
876        self.active_idx = self.active_idx.min(self.tabs_data.len() - 1);
877        let new_idx = self.active_idx;
878        self.load_tab_into_engine(new_idx);
879        crate::kernel::window_mgr::get_instance().dirty = true;
880        false
881    }
882
883    fn get_dom_value(&self, id: &str) -> Option<String> {
884        if id == "filename" {
885            self.tabs_data
886                .get(self.active_idx)
887                .map(|t| t.filename.clone())
888        } else {
889            self.engine.form_values.get(id).cloned()
890        }
891    }
892
893    fn set_dom_value(&mut self, id: &str, val: &str) {
894        if id == "filename" {
895            if let Some(tab) = self.tabs_data.get_mut(self.active_idx) {
896                tab.filename = String::from(val);
897            }
898            self.engine
899                .form_values
900                .insert(String::from("filename"), String::from(val));
901        } else {
902            self.engine
903                .form_values
904                .insert(String::from(id), String::from(val));
905        }
906        self.engine.dirty = true;
907    }
908}