1pub 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 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 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 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 self.scroll_offset = self.scroll_offset.saturating_sub(lines as usize);
150 } else if lines < 0 {
151 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; self.dirty = true;
164
165 if c == '\x03' {
166 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 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 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 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 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 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 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 screen.boxfill(ux0, uy0, ux1, uy1, self.bg_color);
376
377 let line_height = 20; let padding_x = 10;
379 let max_width = ((ww - padding_x * 2 - 12) / 8) as usize; let mut display_lines: Vec<String> = Vec::new();
383 let mut current_line = String::from("> ");
384 let mut current_width = 2; 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(" "); current_width = 2;
405 } else {
406 if current_width + char_w > max_width {
407 display_lines.push(current_line);
408 current_line = String::from(" "); 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 self.launcher_regions.clear();
430
431 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 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), None,
446 Some(String::from(app_name)),
447 ));
448 }
449 }
450 continue;
451 }
452
453 let is_input = raw_log.starts_with("> ");
454 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) } else if is_error {
464 Color(config.theme.error_fg) } else {
466 self.fg_color };
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 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 let lines_to_draw = end_idx - start_idx;
508
509 let sep_y = wy + wh as i32 - input_area_height as i32;
511
512 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 if target_line_idx >= start_line_idx {
701 let relative_line_idx = target_line_idx - start_line_idx;
702
703 let mut prefix_w = 0;
705 if target_line_idx == 0 {
706 if target_string.len() >= 2 {
707 prefix_w += 16; 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 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}