Skip to main content

atmos/apps/terminal/
mod.rs

1//! CUI ターミナルアプリ(Aura REPL ホスト)。
2//!
3//! チャット型のコマンド入力・実行結果表示を提供する。実際の言語処理は
4//! [`crate::os_lib::aura`] に委譲し、本モジュールはバックグラウンドスレッドとの
5//! コマンド/結果のやり取り([`AuraThreadContext`]、[`SafeQueue`])と画面描画・
6//! 履歴管理(`shell` サブモジュール)を担う。
7pub mod shell;
8
9use crate::kernel::draw::{Color, Screen};
10use alloc::collections::VecDeque;
11use alloc::string::String;
12use alloc::sync::Arc;
13use alloc::vec::Vec;
14use core::sync::atomic::{AtomicBool, Ordering};
15use spin::Mutex;
16
17pub struct SafeQueue<T> {
18    queue: Mutex<VecDeque<T>>,
19}
20
21impl<T> SafeQueue<T> {
22    pub fn new() -> Self {
23        Self {
24            queue: Mutex::new(VecDeque::new()),
25        }
26    }
27    pub fn push(&self, value: T) {
28        self.queue.lock().push_back(value);
29    }
30    pub fn pop(&self) -> Option<T> {
31        self.queue.lock().pop_front()
32    }
33    /// 非破壊の空判定(メインループが未処理結果の有無を見て再描画を促すのに使う)。
34    pub fn is_empty(&self) -> bool {
35        self.queue.lock().is_empty()
36    }
37}
38
39impl<T> Default for SafeQueue<T> {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45pub struct AuraThreadContext {
46    pub cmd_queue: SafeQueue<String>,
47    pub result_queue: SafeQueue<String>,
48    pub exit_flag: AtomicBool,
49}
50
51impl AuraThreadContext {
52    pub fn new() -> Self {
53        Self {
54            cmd_queue: SafeQueue::new(),
55            result_queue: SafeQueue::new(),
56            exit_flag: AtomicBool::new(false),
57        }
58    }
59}
60
61impl Default for AuraThreadContext {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67pub struct Terminal {
68    logs: Vec<String>,
69    input_buffer: String,
70    bg_color: Color,
71    fg_color: Color,
72    pub(super) history: Vec<String>,
73    pub(super) history_index: usize,
74    pub dirty: bool,
75    pub input_dirty: bool,
76    pub cursor_char_idx: usize,
77    pub env: Option<crate::os_lib::aura::eval::Env>,
78    pub scroll_offset: usize,
79    pub context: Option<Arc<AuraThreadContext>>,
80    /// アプリランチャーのクリック領域 (x, y, w, h, app_name) — draw() 内で更新される
81    pub launcher_regions: Vec<(i32, i32, u32, u32, String)>,
82}
83
84impl Default for Terminal {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90fn aura_thread_entry(ctx_ptr: usize) {
91    let ctx = unsafe { Arc::from_raw(ctx_ptr as *const AuraThreadContext) };
92    let mut env = crate::os_lib::aura::eval::setup_global_env(core::ptr::null_mut());
93
94    while !ctx.exit_flag.load(Ordering::Relaxed) {
95        if let Some(cmd) = ctx.cmd_queue.pop() {
96            let res = crate::os_lib::aura::eval_string(&cmd, &mut env);
97            ctx.result_queue.push(res);
98            crate::kernel::scheduler::yield_now();
99        } else {
100            // 命令が無いときは 1 tick(10ms)眠る。【2026-11-04】`yield_now` だけで回しており、ほかに動くスレッドが
101            // 無いコアでは空回りしてコアを 1 つ半分ほど使い続けていた(`[PCPROF]`、コア 3)。
102            crate::kernel::scheduler::sleep(1);
103        }
104    }
105}
106
107impl Drop for Terminal {
108    fn drop(&mut self) {
109        if let Some(ctx) = &self.context {
110            ctx.exit_flag.store(true, Ordering::Relaxed);
111        }
112    }
113}
114
115impl Terminal {
116    pub fn new() -> Self {
117        let context = Arc::new(AuraThreadContext::new());
118        let ctx_clone = context.clone();
119        let raw_ptr = Arc::into_raw(ctx_clone) as usize;
120
121        let pid = crate::kernel::scheduler::spawn_with_arg(
122            aura_thread_entry,
123            raw_ptr,
124            crate::kernel::scheduler::Priority::Normal,
125            "aura_shell",
126        );
127        crate::info!("[Terminal] Aura shell thread spawned pid={}", pid);
128
129        Self {
130            logs: Vec::new(),
131            input_buffer: String::new(),
132            launcher_regions: Vec::new(),
133            bg_color: Color(crate::kernel::config::get_config().theme.terminal_bg),
134            fg_color: Color(crate::kernel::config::get_config().theme.terminal_fg),
135            history: Vec::new(),
136            history_index: 0,
137            dirty: true,
138            input_dirty: true,
139            cursor_char_idx: 0,
140            env: None,
141            scroll_offset: 0,
142            context: Some(context),
143        }
144    }
145
146    pub fn scroll(&mut self, lines: i32) {
147        if lines > 0 {
148            // スクロールダウン(下へ、新しいログへ)
149            self.scroll_offset = self.scroll_offset.saturating_sub(lines as usize);
150        } else if lines < 0 {
151            // スクロールアップ(上へ、古いログへ)
152            let max_offset = self.logs.len();
153            self.scroll_offset = self
154                .scroll_offset
155                .saturating_add((-lines) as usize)
156                .min(max_offset);
157        }
158        self.dirty = true;
159    }
160
161    pub fn input_char(&mut self, c: char) {
162        self.scroll_offset = 0; // 入力時は最新行までスクロールを戻す
163        self.dirty = true;
164
165        if c == '\x03' {
166            // Ctrl+C: 入力バッファをクリアして改行風に表示
167            self.logs.push(alloc::format!("> {}^C", self.input_buffer));
168            self.input_buffer.clear();
169            self.cursor_char_idx = 0;
170            self.input_dirty = true;
171            return;
172        }
173
174        let chars: Vec<char> = self.input_buffer.chars().collect();
175        let count = chars.len();
176
177        if c == '\x08' {
178            if self.cursor_char_idx > 0 && self.cursor_char_idx <= count {
179                let mut new_chars = chars;
180                new_chars.remove(self.cursor_char_idx - 1);
181                self.input_buffer = new_chars.into_iter().collect();
182                self.cursor_char_idx -= 1;
183            }
184        } else if c.is_ascii_control() {
185            // 他の制御文字(Ctrl+A / Ctrl+E / Ctrl+K などの処理)
186            match c {
187                '\x01' => self.move_cursor_to_start(),
188                '\x05' => self.move_cursor_to_end(),
189                '\x10' => self.history_up(),
190                '\x0E' => self.history_down(),
191                '\x0B' => {
192                    // Ctrl+K: カーソルから行末までの削除
193                    let chars: Vec<char> = self.input_buffer.chars().collect();
194                    if self.cursor_char_idx <= chars.len() {
195                        self.input_buffer = chars[0..self.cursor_char_idx].iter().collect();
196                        self.input_dirty = true;
197                    }
198                }
199                _ => {}
200            }
201        } else {
202            let mut new_chars = chars;
203            if self.cursor_char_idx <= count {
204                new_chars.insert(self.cursor_char_idx, c);
205                self.input_buffer = new_chars.into_iter().collect();
206                self.cursor_char_idx += 1;
207            }
208        }
209        self.input_dirty = true;
210    }
211
212    pub fn delete_char(&mut self) {
213        let chars: Vec<char> = self.input_buffer.chars().collect();
214        let count = chars.len();
215        if self.cursor_char_idx < count {
216            let mut new_chars = chars;
217            new_chars.remove(self.cursor_char_idx);
218            self.input_buffer = new_chars.into_iter().collect();
219            self.input_dirty = true;
220        }
221    }
222
223    pub fn move_cursor_left(&mut self) {
224        if self.cursor_char_idx > 0 {
225            self.cursor_char_idx -= 1;
226            self.input_dirty = true;
227        }
228    }
229
230    pub fn move_cursor_right(&mut self) {
231        let count = self.input_buffer.chars().count();
232        if self.cursor_char_idx < count {
233            self.cursor_char_idx += 1;
234            self.input_dirty = true;
235        }
236    }
237
238    pub fn move_cursor_to_start(&mut self) {
239        self.cursor_char_idx = 0;
240        self.input_dirty = true;
241    }
242
243    /// Ctrl+K (KillLine): カーソル位置から現在行の行末までを削除する(OS 共通)。
244    pub fn kill_line(&mut self) {
245        let chars: Vec<char> = self.input_buffer.chars().collect();
246        let mut end = self.cursor_char_idx;
247        while end < chars.len() && chars[end] != '\n' {
248            end += 1;
249        }
250        if end > self.cursor_char_idx {
251            let mut new_chars = chars;
252            new_chars.drain(self.cursor_char_idx..end);
253            self.input_buffer = new_chars.into_iter().collect();
254            self.input_dirty = true;
255        }
256    }
257
258    pub fn move_cursor_to_end(&mut self) {
259        self.cursor_char_idx = self.input_buffer.chars().count();
260        self.input_dirty = true;
261    }
262
263    pub fn submit(&mut self) -> Option<String> {
264        if !self.input_buffer.is_empty() {
265            // 入力された文字列をログに追加。実行時刻を '\x00' 区切りで末尾に埋め込み、
266            // 描画時に右端(時計と同じ x)へ分離表示する。
267            let mut log_line = String::from("> ");
268            log_line.push_str(&self.input_buffer);
269            if let Some(t) = crate::kernel::timer::format_time_hms_jst() {
270                log_line.push('\x00');
271                log_line.push_str(&t);
272            }
273            self.logs.push(log_line);
274
275            let command = self.input_buffer.clone();
276
277            if self.history.last() != Some(&command) {
278                self.history.push(command.clone());
279            }
280            self.history_index = self.history.len();
281
282            self.input_buffer.clear();
283            self.cursor_char_idx = 0;
284            self.dirty = true;
285            Some(command)
286        } else {
287            None
288        }
289    }
290
291    pub fn history_up(&mut self) {
292        self.scroll_offset = 0;
293        if self.history_index > 0 {
294            self.history_index -= 1;
295            self.input_buffer = self.history[self.history_index].clone();
296            self.cursor_char_idx = self.input_buffer.chars().count();
297            self.dirty = true;
298            self.input_dirty = true;
299        }
300    }
301
302    pub fn history_down(&mut self) {
303        self.scroll_offset = 0;
304        if self.history_index < self.history.len() {
305            self.history_index += 1;
306            if self.history_index == self.history.len() {
307                self.input_buffer.clear();
308            } else {
309                self.input_buffer = self.history[self.history_index].clone();
310            }
311            self.cursor_char_idx = self.input_buffer.chars().count();
312            self.dirty = true;
313            self.input_dirty = true;
314        }
315    }
316
317    pub fn print_line(&mut self, msg: String) {
318        self.logs.push(msg);
319        self.dirty = true;
320    }
321
322    pub fn clear_logs(&mut self) {
323        self.logs.clear();
324        self.dirty = true;
325    }
326
327    /// 非同期 Aura スレッドの実行結果(result_queue)が未処理で残っているか。
328    /// メインループはこれを見て `dirty` を立て、draw() に結果を吸い出させる。
329    /// (draw() 内でしか result_queue を消費しないため、結果到着時に再描画を促す必要がある)
330    pub fn has_pending_results(&self) -> bool {
331        self.context
332            .as_ref()
333            .map(|c| !c.result_queue.is_empty())
334            .unwrap_or(false)
335    }
336
337    pub fn show_history(&mut self) {
338        let history = self.history.clone();
339        for (i, cmd) in history.iter().enumerate() {
340            self.print_line(alloc::format!("  {}  {}", i + 1, cmd));
341        }
342    }
343
344    /// クリック座標がランチャー領域に当たればアプリ名を返す
345    pub fn handle_click(&self, x: i32, y: i32) -> Option<String> {
346        for (rx, ry, rw, rh, name) in &self.launcher_regions {
347            if x >= *rx && x < rx + *rw as i32 && y >= *ry && y < ry + *rh as i32 {
348                return Some(name.clone());
349            }
350        }
351        None
352    }
353
354    pub fn draw(&mut self, screen: &Screen, wx: i32, wy: i32, ww: u32, wh: u32) {
355        if let Some(ctx) = self.context.clone() {
356            while let Some(res) = ctx.result_queue.pop() {
357                if !res.is_empty() {
358                    for line in res.split('\n') {
359                        self.print_line(String::from(line));
360                    }
361                }
362            }
363        }
364
365        let config = crate::kernel::config::get_config();
366        self.bg_color = Color(config.theme.terminal_bg);
367        self.fg_color = Color(config.theme.terminal_fg);
368
369        let ux0 = wx.max(0) as u32;
370        let uy0 = wy.max(0) as u32;
371        let ux1 = (wx + ww as i32).max(0) as u32;
372        let uy1 = (wy + wh as i32).max(0) as u32;
373
374        // 1. ウィンドウ領域を背景色でクリア
375        screen.boxfill(ux0, uy0, ux1, uy1, self.bg_color);
376
377        let line_height = 20; // 1行の高さ(余白込み)
378        let padding_x = 10;
379        let max_width = ((ww - padding_x * 2 - 12) / 8) as usize; // 半角文字数としての最大幅(スクロールバー余白12px考慮)
380
381        // 2. 入力バッファを論理表示行リストに分割 (改行・自動折り返し対応)
382        let mut display_lines: Vec<String> = Vec::new();
383        let mut current_line = String::from("> ");
384        let mut current_width = 2; // "> " の幅は2
385
386        let mut target_line_idx = 0;
387        let mut cursor_found = false;
388
389        let chars_list: Vec<char> = self.input_buffer.chars().collect();
390
391        let mut target_string = String::new();
392
393        if self.cursor_char_idx == 0 {
394            target_line_idx = 0;
395            target_string = String::from("> ");
396            cursor_found = true;
397        }
398
399        for (idx, &c) in chars_list.iter().enumerate() {
400            let char_w = if (c as u32) < 128 { 1 } else { 2 };
401            if c == '\n' {
402                display_lines.push(current_line);
403                current_line = String::from("  "); // 改行後のインデント
404                current_width = 2;
405            } else {
406                if current_width + char_w > max_width {
407                    display_lines.push(current_line);
408                    current_line = String::from("  "); // 自動折り返し後のインデント
409                    current_width = 2;
410                }
411                current_line.push(c);
412                current_width += char_w;
413            }
414
415            if idx + 1 == self.cursor_char_idx {
416                target_line_idx = display_lines.len();
417                target_string = current_line.clone();
418                cursor_found = true;
419            }
420        }
421        display_lines.push(current_line.clone());
422
423        if !cursor_found {
424            target_line_idx = display_lines.len() - 1;
425            target_string = current_line.clone();
426        }
427
428        // ランチャー領域をリセット(draw のたびに再計算)
429        self.launcher_regions.clear();
430
431        // 2.5 ログを論理表示行リストに分割 (改行・自動折り返し対応、色付け)
432        // 要素: (text, color, timestamp_opt, launcher_app_name_opt)
433        // launcher_app_name_opt が Some のとき SVG アイコン付きのランチャー行として描画する
434        let mut display_logs: alloc::vec::Vec<(String, Color, Option<String>, Option<String>)> =
435            alloc::vec::Vec::new();
436        for raw_log in &self.logs {
437            // ランチャーマーカー: "\x02LAUNCHER:appname:display\x02"
438            if raw_log.starts_with('\x02') {
439                let inner = raw_log.trim_matches('\x02');
440                if let Some(rest) = inner.strip_prefix("LAUNCHER:") {
441                    if let Some((app_name, display)) = rest.split_once(':') {
442                        display_logs.push((
443                            String::from(display),
444                            Color(config.theme.fn_bar_key_fg), // ランチャー色
445                            None,
446                            Some(String::from(app_name)),
447                        ));
448                    }
449                }
450                continue;
451            }
452
453            let is_input = raw_log.starts_with("> ");
454            // 実行時刻('\x00' 区切りで埋め込み)を分離
455            let (log, mut timestamp): (&str, Option<String>) = match raw_log.split_once('\x00') {
456                Some((cmd, ts)) => (cmd, Some(String::from(ts))),
457                None => (raw_log.as_str(), None),
458            };
459            let is_error = log.to_lowercase().contains("error");
460
461            let color = if is_input {
462                Color(config.theme.success_fg) // 入力
463            } else if is_error {
464                Color(config.theme.error_fg) // エラー
465            } else {
466                self.fg_color // 出力は通常色
467            };
468
469            let mut current_line = String::new();
470            let mut current_width = 0;
471            for c in log.chars() {
472                let char_w = if (c as u32) < 128 { 1 } else { 2 };
473                if c == '\n' {
474                    display_logs.push((current_line.clone(), color, timestamp.take(), None));
475                    current_line.clear();
476                    current_width = 0;
477                } else {
478                    if current_width + char_w > max_width {
479                        display_logs.push((current_line.clone(), color, timestamp.take(), None));
480                        current_line.clear();
481                        current_width = 0;
482                    }
483                    current_line.push(c);
484                    current_width += char_w;
485                }
486            }
487            display_logs.push((current_line, color, timestamp.take(), None));
488        }
489
490        let total_lines = display_lines.len();
491        let visible_lines_count = total_lines.min(5);
492
493        let input_area_height = visible_lines_count as u32 * line_height + 15;
494        let log_area_height = wh.saturating_sub(input_area_height);
495        let max_log_lines = log_area_height / line_height;
496
497        // 3. ログエリアの描画 (タイプライター風: 下から上へ押し上げる)
498        let max_possible_start = if display_logs.len() as u32 > max_log_lines {
499            display_logs.len() - max_log_lines as usize
500        } else {
501            0
502        };
503        let start_idx = max_possible_start.saturating_sub(self.scroll_offset);
504        let end_idx = (start_idx + max_log_lines as usize).min(display_logs.len());
505
506        // 描画すべき行数
507        let lines_to_draw = end_idx - start_idx;
508
509        // 入力エリアの境界線 y座標
510        let sep_y = wy + wh as i32 - input_area_height as i32;
511
512        // 最新の行が sep_y の直上にくるように current_y を逆算
513        let mut current_y = sep_y - (lines_to_draw as i32 * line_height as i32) - 5;
514
515        static DEFAULT_APP_ICON: &[u8] =
516            include_bytes!("../../../icons/ic_app_default.svg");
517
518        for i in start_idx..end_idx {
519            let (text, color, ts, launcher_app) = &display_logs[i];
520
521            if let Some(app_name) = launcher_app {
522                // ランチャー行: アイコン + テキスト + クリック領域
523                let icon_size = 16u32;
524                let icon_x = (wx + padding_x as i32) as u32;
525                let icon_y = if current_y >= 0 { current_y as u32 } else { 0 };
526                let text_x = icon_x + icon_size + 6;
527                let row_h = line_height;
528
529                // ホバー背景(薄いハイライト)
530                let hl_y = if current_y >= 0 { current_y as u32 } else { 0 };
531                screen.boxfill(
532                    (wx + 2) as u32,
533                    hl_y,
534                    (wx + ww as i32 - 20) as u32,
535                    hl_y + row_h,
536                    Color(config.theme.ui_overlay_bg),
537                );
538
539                // SVGアイコン: /apps/<name>/icon.svg をFS から読む、なければデフォルト
540                let icon_path = alloc::format!("/apps/{}/icon.svg", app_name);
541                let fs = crate::kernel::fs::get_fs();
542                let icon_bytes_owned: Option<alloc::vec::Vec<u8>> = match fs.read_file_checked(&icon_path) {
543                    Ok(v) => v.map(|(_m, b)| b),
544                    Err(e) => {
545                        crate::warn!("[SYS] Terminal: failed to read app icon '{}': {}", icon_path, e);
546                        None
547                    }
548                };
549                let icon_data: &[u8] = match &icon_bytes_owned {
550                    Some(b) => b.as_slice(),
551                    None => DEFAULT_APP_ICON,
552                };
553                if icon_y + icon_size < (wy + wh as i32) as u32 {
554                    screen.draw_svg_icon(icon_x, icon_y, icon_data, icon_size, *color);
555                }
556
557                // アプリ名テキスト
558                screen.draw_string_monospace_bg(
559                    text_x,
560                    icon_y,
561                    text,
562                    *color,
563                    Color(config.theme.ui_overlay_bg),
564                );
565
566                // クリック領域を登録
567                self.launcher_regions.push((
568                    wx + 2,
569                    current_y,
570                    ww - 22,
571                    row_h,
572                    app_name.clone(),
573                ));
574            } else {
575                screen.draw_string_monospace_bg(
576                    (wx + padding_x as i32) as u32,
577                    current_y as u32,
578                    text,
579                    *color,
580                    self.bg_color,
581                );
582                // コマンド実行時刻を右端(時計と同じ右基準)に表示
583                if let Some(t) = ts {
584                    let tw = screen.measure_string_monospace(t);
585                    let tx = (wx + ww as i32 - padding_x as i32 - tw as i32).max(wx + padding_x as i32);
586                    screen.draw_string_monospace_bg(
587                        tx as u32,
588                        current_y as u32,
589                        t,
590                        Color(config.theme.fn_bar_dim_fg),
591                        self.bg_color,
592                    );
593                }
594            }
595            current_y += line_height as i32;
596        }
597
598        // 3.5 ログエリア右下に時計またはNTPステータスを表示
599        let clock_str = crate::kernel::timer::format_datetime_jst()
600            .unwrap_or_else(|| alloc::string::String::from("NTP Syncing..."));
601        
602        let clock_w = screen.measure_string_monospace(&clock_str);
603        let clock_x =
604            (wx + ww as i32 - padding_x as i32 - clock_w as i32).max(wx + padding_x as i32);
605        let clock_y = sep_y - line_height as i32 + 2;
606        screen.draw_string_monospace_bg(
607            clock_x as u32,
608            clock_y as u32,
609            &clock_str,
610            Color(config.theme.fn_bar_dim_fg),
611            self.bg_color,
612        );
613
614        // 3.6 縦スクロールバーの描画
615        let total_log_lines = display_logs.len();
616        if total_log_lines > max_log_lines as usize {
617            let bar_w = 6u32;
618            let bar_padding = 2u32;
619            let rail_x = wx + ww as i32 - bar_w as i32 - bar_padding as i32;
620            let rail_y = wy + 5;
621            let rail_h = log_area_height.saturating_sub(10);
622
623            // スクロールバーの背景レール
624            screen.boxfill(
625                rail_x as u32,
626                rail_y as u32,
627                (rail_x + bar_w as i32) as u32,
628                (rail_y + rail_h as i32) as u32,
629                Color(config.theme.tab_area_bg),
630            );
631
632            // つまみの高さと位置の計算
633            let thumb_h = ((rail_h * max_log_lines) / total_log_lines as u32).max(15);
634            let max_possible_start = total_log_lines.saturating_sub(max_log_lines as usize);
635            if max_possible_start > 0 {
636                let scroll_y_offset =
637                    ((rail_h - thumb_h) * start_idx as u32) / max_possible_start as u32;
638                let thumb_y = rail_y + scroll_y_offset as i32;
639                // スクロールバーのつまみ
640                screen.boxfill(
641                    rail_x as u32,
642                    thumb_y as u32,
643                    (rail_x + bar_w as i32) as u32,
644                    (thumb_y + thumb_h as i32) as u32,
645                    Color(config.theme.tab_area_border),
646                );
647            }
648        }
649
650        // 4. 入力エリアの境界線
651        let sep_y = wy + wh as i32 - input_area_height as i32;
652        screen.boxfill(
653            ux0,
654            sep_y as u32,
655            ux1,
656            (sep_y + 1) as u32,
657            Color(config.theme.tab_area_border),
658        );
659
660        // 5. 入力バッファの描画 (スライド窓スクロール)
661        let start_line_idx = total_lines.saturating_sub(5);
662        let mut cur_y = sep_y + 10;
663
664        for i in start_line_idx..total_lines {
665            let line = &display_lines[i];
666
667            // 最初の行はプロンプト "> " (2文字分) をエメラルドグリーンにする
668            if i == 0 {
669                screen.draw_string_monospace_bg(
670                    (wx + padding_x as i32) as u32,
671                    cur_y as u32,
672                    "> ",
673                    Color(config.theme.success_fg),
674                    self.bg_color,
675                );
676                if line.len() > 2 {
677                    let text = line.get(2..).unwrap_or("");
678                    screen.draw_string_monospace_bg(
679                        (wx + padding_x as i32 + 16) as u32,
680                        cur_y as u32,
681                        text,
682                        self.fg_color,
683                        self.bg_color,
684                    );
685                }
686            } else {
687                screen.draw_string_monospace_bg(
688                    (wx + padding_x as i32) as u32,
689                    cur_y as u32,
690                    line,
691                    self.fg_color,
692                    self.bg_color,
693                );
694            }
695
696            cur_y += line_height as i32;
697        }
698
699        // 6. カーソルの描画
700        if target_line_idx >= start_line_idx {
701            let relative_line_idx = target_line_idx - start_line_idx;
702
703            // target_string の幅を等幅フォントで計算
704            let mut prefix_w = 0;
705            if target_line_idx == 0 {
706                if target_string.len() >= 2 {
707                    prefix_w += 16; // "> " のプロンプト幅 (1文字8px*2=16px)
708                    let text = target_string.get(2..).unwrap_or("");
709                    prefix_w += screen.measure_string_monospace(text);
710                } else {
711                    prefix_w += screen.measure_string_monospace(&target_string);
712                }
713            } else {
714                prefix_w += screen.measure_string_monospace(&target_string);
715            }
716
717            let cursor_x = wx + padding_x as i32 + prefix_w as i32;
718            let cursor_y = sep_y + 10 + (relative_line_idx as i32) * line_height as i32;
719
720            if cursor_x + 2 <= wx + ww as i32 - padding_x as i32 {
721                // 縦棒カーソル (幅2px)。半角=青系 / 全角(FEP)=赤系。
722                screen.boxfill(
723                    cursor_x as u32,
724                    cursor_y as u32 + 2,
725                    (cursor_x + 2) as u32,
726                    (cursor_y + 14) as u32,
727                    Color(crate::kernel::ime::cursor_color()),
728                );
729            }
730        }
731
732        self.dirty = false;
733        self.input_dirty = false;
734    }
735}