xref: /DragonOS/kernel/src/libs/lib_ui/textui.rs (revision 1074eb34e784aa2adfc5b9e0d89fa4b7e6ea03ef)
1 use crate::{
2     driver::{
3         serial::serial8250::send_to_default_serial8250_port,
4         tty::{tty_port::tty_port, virtual_terminal::virtual_console::CURRENT_VCNUM},
5         video::video_refresh_manager,
6     },
7     kdebug, kinfo,
8     libs::{
9         lib_ui::font::FONT_8x16,
10         rwlock::RwLock,
11         spinlock::{SpinLock, SpinLockGuard},
12     },
13 };
14 use alloc::{boxed::Box, collections::LinkedList, string::ToString};
15 use alloc::{sync::Arc, vec::Vec};
16 use core::{
17     fmt::Debug,
18     intrinsics::unlikely,
19     ops::{Add, AddAssign, Sub},
20     ptr::copy_nonoverlapping,
21     sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering},
22 };
23 use system_error::SystemError;
24 
25 use super::{
26     screen_manager::{
27         scm_register, ScmBuffer, ScmBufferInfo, ScmFramworkType, ScmUiFramework,
28         ScmUiFrameworkMetadata,
29     },
30     textui_no_alloc::no_init_textui_putchar_window,
31 };
32 
33 /// 声明全局的TEXTUI_FRAMEWORK
34 static mut __TEXTUI_FRAMEWORK: Option<Arc<TextUiFramework>> = None;
35 
36 /// 每个字符的宽度和高度(像素)
37 pub const TEXTUI_CHAR_WIDTH: u32 = 8;
38 
39 pub const TEXTUI_CHAR_HEIGHT: u32 = 16;
40 
41 pub static mut TEXTUI_IS_INIT: bool = false;
42 
43 static ENABLE_PUT_TO_WINDOW: AtomicBool = AtomicBool::new(false);
44 
45 /// 启用将文本输出到窗口的功能。
46 pub fn textui_enable_put_to_window() {
47     ENABLE_PUT_TO_WINDOW.store(true, Ordering::SeqCst);
48 }
49 
50 /// 禁用将文本输出到窗口的功能。
51 pub fn textui_disable_put_to_window() {
52     ENABLE_PUT_TO_WINDOW.store(false, Ordering::SeqCst);
53 }
54 
55 /// 检查是否启用了将文本输出到窗口的功能。
56 ///
57 /// # 返回
58 /// 如果启用了将文本输出到窗口的功能,则返回 `true`,否则返回 `false`。
59 pub fn textui_is_enable_put_to_window() -> bool {
60     ENABLE_PUT_TO_WINDOW.load(Ordering::SeqCst)
61 }
62 
63 /// 获取TEXTUI_FRAMEWORK的可变实例
64 pub fn textui_framework() -> Arc<TextUiFramework> {
65     unsafe {
66         return __TEXTUI_FRAMEWORK
67             .as_ref()
68             .expect("Textui framework has not been initialized yet!")
69             .clone();
70     }
71 }
72 
73 /// 初始化TEXTUI_FRAMEWORK
74 fn textui_framwork_init() {
75     if unsafe { __TEXTUI_FRAMEWORK.is_none() } {
76         kinfo!("textuiframework init");
77         let metadata = ScmUiFrameworkMetadata::new("TextUI".to_string(), ScmFramworkType::Text);
78         kdebug!("textui metadata: {:?}", metadata);
79         // 为textui框架生成第一个窗口
80         let vlines_num = (metadata.buf_info().height() / TEXTUI_CHAR_HEIGHT) as usize;
81 
82         let chars_num = (metadata.buf_info().width() / TEXTUI_CHAR_WIDTH) as usize;
83 
84         let initial_window = TextuiWindow::new(
85             WindowFlag::TEXTUI_CHROMATIC,
86             vlines_num as i32,
87             chars_num as i32,
88         );
89 
90         let current_window: Arc<SpinLock<TextuiWindow>> = Arc::new(SpinLock::new(initial_window));
91 
92         let default_window = current_window.clone();
93 
94         // 生成窗口链表,并把上面窗口添加进textui框架的窗口链表中
95         let window_list: Arc<SpinLock<LinkedList<Arc<SpinLock<TextuiWindow>>>>> =
96             Arc::new(SpinLock::new(LinkedList::new()));
97         window_list.lock().push_back(current_window.clone());
98 
99         unsafe {
100             __TEXTUI_FRAMEWORK = Some(Arc::new(TextUiFramework::new(
101                 metadata,
102                 window_list,
103                 current_window,
104                 default_window,
105             )))
106         };
107 
108         scm_register(textui_framework()).expect("register textui framework failed");
109         kdebug!("textui framework init success");
110 
111         send_to_default_serial8250_port("\ntext ui initialized\n\0".as_bytes());
112         unsafe { TEXTUI_IS_INIT = true };
113     } else {
114         panic!("Try to init TEXTUI_FRAMEWORK twice!");
115     }
116 }
117 // window标志位
118 bitflags! {
119     pub struct WindowFlag: u8 {
120         // 采用彩色字符
121         const TEXTUI_CHROMATIC = 1 << 0;
122     }
123 }
124 
125 /**
126  * @brief 黑白字符对象
127  *
128  */
129 #[derive(Clone, Debug)]
130 struct TextuiCharNormal {
131     _data: u8,
132 }
133 
134 #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Default)]
135 pub struct LineId(i32);
136 impl LineId {
137     pub fn new(num: i32) -> Self {
138         LineId(num)
139     }
140 
141     pub fn check(&self, max: i32) -> bool {
142         self.0 < max && self.0 >= 0
143     }
144 
145     pub fn data(&self) -> i32 {
146         self.0
147     }
148 }
149 impl Add<i32> for LineId {
150     type Output = LineId;
151     fn add(self, rhs: i32) -> Self::Output {
152         LineId::new(self.0 + rhs)
153     }
154 }
155 impl Sub<i32> for LineId {
156     type Output = LineId;
157 
158     fn sub(self, rhs: i32) -> Self::Output {
159         LineId::new(self.0 - rhs)
160     }
161 }
162 impl From<LineId> for i32 {
163     fn from(value: LineId) -> Self {
164         value.0
165     }
166 }
167 impl From<LineId> for u32 {
168     fn from(value: LineId) -> Self {
169         value.0 as u32
170     }
171 }
172 impl From<LineId> for usize {
173     fn from(value: LineId) -> Self {
174         value.0 as usize
175     }
176 }
177 impl Sub<LineId> for LineId {
178     type Output = LineId;
179 
180     fn sub(mut self, rhs: LineId) -> Self::Output {
181         self.0 -= rhs.0;
182         return self;
183     }
184 }
185 impl AddAssign<LineId> for LineId {
186     fn add_assign(&mut self, rhs: LineId) {
187         self.0 += rhs.0;
188     }
189 }
190 #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Default)]
191 pub struct LineIndex(i32);
192 impl LineIndex {
193     pub fn new(num: i32) -> Self {
194         LineIndex(num)
195     }
196     pub fn check(&self, chars_per_line: i32) -> bool {
197         self.0 < chars_per_line && self.0 >= 0
198     }
199 }
200 impl Add<LineIndex> for LineIndex {
201     type Output = LineIndex;
202 
203     fn add(self, rhs: LineIndex) -> Self::Output {
204         LineIndex::new(self.0 + rhs.0)
205     }
206 }
207 impl Add<i32> for LineIndex {
208     // type Output = Self;
209     type Output = LineIndex;
210 
211     fn add(self, rhs: i32) -> Self::Output {
212         LineIndex::new(self.0 + rhs)
213     }
214 }
215 impl Sub<i32> for LineIndex {
216     type Output = LineIndex;
217 
218     fn sub(self, rhs: i32) -> Self::Output {
219         LineIndex::new(self.0 - rhs)
220     }
221 }
222 
223 impl From<LineIndex> for i32 {
224     fn from(val: LineIndex) -> Self {
225         val.0
226     }
227 }
228 impl From<LineIndex> for u32 {
229     fn from(value: LineIndex) -> Self {
230         value.0 as u32
231     }
232 }
233 impl From<LineIndex> for usize {
234     fn from(value: LineIndex) -> Self {
235         value.0 as usize
236     }
237 }
238 #[derive(Copy, Clone, Debug)]
239 pub struct FontColor(u32);
240 #[allow(dead_code)]
241 impl FontColor {
242     pub const BLUE: FontColor = FontColor::new(0, 0, 0xff);
243     pub const RED: FontColor = FontColor::new(0xff, 0, 0);
244     pub const GREEN: FontColor = FontColor::new(0, 0xff, 0);
245     pub const WHITE: FontColor = FontColor::new(0xff, 0xff, 0xff);
246     pub const BLACK: FontColor = FontColor::new(0, 0, 0);
247     pub const YELLOW: FontColor = FontColor::new(0xff, 0xff, 0);
248     pub const ORANGE: FontColor = FontColor::new(0xff, 0x80, 0);
249     pub const INDIGO: FontColor = FontColor::new(0x00, 0xff, 0xff);
250     pub const PURPLE: FontColor = FontColor::new(0x80, 0x00, 0xff);
251 
252     pub const fn new(r: u8, g: u8, b: u8) -> Self {
253         let val = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
254         return FontColor(val & 0x00ffffff);
255     }
256 }
257 
258 impl From<u32> for FontColor {
259     fn from(value: u32) -> Self {
260         return Self(value & 0x00ffffff);
261     }
262 }
263 impl From<FontColor> for usize {
264     fn from(value: FontColor) -> Self {
265         value.0 as usize
266     }
267 }
268 impl From<FontColor> for u32 {
269     fn from(value: FontColor) -> Self {
270         value.0
271     }
272 }
273 impl From<FontColor> for u16 {
274     fn from(value: FontColor) -> Self {
275         value.0 as u16
276     }
277 }
278 impl From<FontColor> for u64 {
279     fn from(value: FontColor) -> Self {
280         value.0 as u64
281     }
282 }
283 
284 /// 彩色字符对象
285 
286 #[derive(Clone, Debug, Copy)]
287 pub struct TextuiCharChromatic {
288     c: Option<char>,
289 
290     // 前景色
291     frcolor: FontColor, // rgb
292 
293     // 背景色
294     bkcolor: FontColor, // rgb
295 }
296 
297 #[derive(Debug)]
298 pub struct TextuiBuf<'a> {
299     buf: Option<&'a mut [u8]>,
300 
301     guard: Option<SpinLockGuard<'a, Box<[u8]>>>,
302 
303     bit_depth: u32,
304 }
305 
306 impl TextuiBuf<'_> {
307     pub fn new(buf: &mut ScmBufferInfo) -> TextuiBuf {
308         let len = buf.buf_size() / 4;
309         let depth = video_refresh_manager().device_buffer().bit_depth();
310         match &buf.buf {
311             ScmBuffer::DeviceBuffer(vaddr) => {
312                 return TextuiBuf {
313                     buf: Some(unsafe {
314                         core::slice::from_raw_parts_mut(vaddr.data() as *mut u8, len)
315                     }),
316                     guard: None,
317                     bit_depth: depth,
318                 };
319             }
320 
321             ScmBuffer::DoubleBuffer(double_buffer) => {
322                 let guard: SpinLockGuard<'_, Box<[u8]>> = double_buffer.lock();
323 
324                 return TextuiBuf {
325                     buf: None,
326                     guard: Some(guard),
327                     bit_depth: depth,
328                 };
329             }
330         }
331     }
332 
333     pub fn buf_mut(&mut self) -> &mut [u8] {
334         if let Some(buf) = &mut self.buf {
335             return buf;
336         } else {
337             return self.guard.as_mut().unwrap().as_mut();
338         }
339     }
340 
341     pub fn put_color_in_pixel(&mut self, color: u32, index: usize) {
342         let index = index as isize;
343         match self.bit_depth {
344             32 => {
345                 let buf = self.buf_mut().as_mut_ptr() as *mut u32;
346                 unsafe {
347                     *buf.offset(index) = color;
348                 }
349             }
350             24 => {
351                 let buf = self.buf_mut().as_mut_ptr();
352                 unsafe {
353                     copy_nonoverlapping(&color as *const u32 as *const u8, buf.offset(index * 3), 3)
354                 };
355             }
356             16 => {
357                 let buf = self.buf_mut().as_mut_ptr();
358                 unsafe {
359                     copy_nonoverlapping(
360                         &color as *const u32 as *const u8,
361                         buf.offset(index * 2),
362                         2,
363                     );
364                 };
365             }
366             _ => {
367                 panic!("bidepth unsupported!")
368             }
369         }
370     }
371     pub fn get_index_of_next_line(now_index: usize) -> usize {
372         textui_framework().metadata.read().buf_info().width() as usize + now_index
373     }
374     pub fn get_index_by_x_y(x: usize, y: usize) -> usize {
375         textui_framework().metadata.read().buf_info().width() as usize * y + x
376     }
377 
378     pub fn get_start_index_by_lineid_lineindex(lineid: LineId, lineindex: LineIndex) -> usize {
379         //   x 左上角列像素点位置
380         //   y 左上角行像素点位置
381         let index_x: u32 = lineindex.into();
382         let x: u32 = index_x * TEXTUI_CHAR_WIDTH;
383 
384         let id_y: u32 = lineid.into();
385         let y: u32 = id_y * TEXTUI_CHAR_HEIGHT;
386 
387         TextuiBuf::get_index_by_x_y(x as usize, y as usize)
388     }
389 }
390 
391 #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
392 pub struct Font([u8; 16]);
393 impl Font {
394     #[inline]
395     pub fn get_font(character: char) -> Font {
396         let x = FONT_8x16.char_map(character);
397 
398         let mut data = [0u8; 16];
399         data.copy_from_slice(x);
400         return Font(data);
401     }
402     pub fn is_frcolor(&self, height: usize, width: usize) -> bool {
403         let w = self.0[height];
404         let testbit = 1 << (8 - width);
405         w & testbit != 0
406     }
407 }
408 
409 impl TextuiCharChromatic {
410     pub fn new(c: Option<char>, frcolor: FontColor, bkcolor: FontColor) -> Self {
411         TextuiCharChromatic {
412             c,
413             frcolor,
414             bkcolor,
415         }
416     }
417 
418     /// 将该字符对象输出到缓冲区
419     /// ## 参数
420     /// -line_id 要放入的真实行号
421     /// -index 要放入的真实列号
422     pub fn textui_refresh_character(
423         &self,
424         lineid: LineId,
425         lineindex: LineIndex,
426     ) -> Result<i32, SystemError> {
427         // 找到要渲染的字符的像素点数据
428 
429         let font: Font = Font::get_font(self.c.unwrap_or(' '));
430 
431         let mut count = TextuiBuf::get_start_index_by_lineid_lineindex(lineid, lineindex);
432 
433         let mut _binding = textui_framework().metadata.read().buf_info();
434 
435         let mut buf = TextuiBuf::new(&mut _binding);
436 
437         // 在缓冲区画出一个字体,每个字体有TEXTUI_CHAR_HEIGHT行,TEXTUI_CHAR_WIDTH列个像素点
438         for i in 0..TEXTUI_CHAR_HEIGHT {
439             let start = count;
440             for j in 0..TEXTUI_CHAR_WIDTH {
441                 if font.is_frcolor(i as usize, j as usize) {
442                     // 字,显示前景色
443                     buf.put_color_in_pixel(self.frcolor.into(), count);
444                 } else {
445                     // 背景色
446                     buf.put_color_in_pixel(self.bkcolor.into(), count);
447                 }
448                 count += 1;
449             }
450             count = TextuiBuf::get_index_of_next_line(start);
451         }
452 
453         return Ok(0);
454     }
455 
456     pub fn no_init_textui_render_chromatic(&self, lineid: LineId, lineindex: LineIndex) {
457         // 找到要渲染的字符的像素点数据
458         let font = Font::get_font(self.c.unwrap_or(' '));
459 
460         //   x 左上角列像素点位置
461         //   y 左上角行像素点位置
462         let index_x: u32 = lineindex.into();
463         let x: u32 = index_x * TEXTUI_CHAR_WIDTH;
464 
465         let id_y: u32 = lineid.into();
466         let y: u32 = id_y * TEXTUI_CHAR_HEIGHT;
467         let buf_depth = video_refresh_manager().device_buffer().bit_depth();
468         let buf_width = video_refresh_manager().device_buffer().width();
469         let byte_num_of_depth = (buf_depth / 8) as usize;
470 
471         // 找到输入缓冲区的起始地址位置
472         let buf_start =
473             if let ScmBuffer::DeviceBuffer(vaddr) = video_refresh_manager().device_buffer().buf {
474                 vaddr
475             } else {
476                 panic!("device buffer is not init");
477             };
478 
479         let mut testbit: u32; // 用来测试特定行的某列是背景还是字体本身
480 
481         // 在缓冲区画出一个字体,每个字体有TEXTUI_CHAR_HEIGHT行,TEXTUI_CHAR_WIDTH列个像素点
482         for i in 0..TEXTUI_CHAR_HEIGHT {
483             // 计算出帧缓冲区每一行打印的起始位置的地址(起始位置+(y+i)*缓冲区的宽度+x)
484 
485             let mut addr: *mut u8 = (buf_start
486                 + buf_width as usize * byte_num_of_depth * (y as usize + i as usize)
487                 + byte_num_of_depth * x as usize)
488                 .data() as *mut u8;
489 
490             testbit = 1 << (TEXTUI_CHAR_WIDTH + 1);
491 
492             for _j in 0..TEXTUI_CHAR_WIDTH {
493                 //该循环是渲染一行像素
494                 //从左往右逐个测试相应位
495                 testbit >>= 1;
496                 if (font.0[i as usize] & testbit as u8) != 0 {
497                     let color: u32 = self.frcolor.into();
498                     unsafe {
499                         copy_nonoverlapping(
500                             &color as *const u32 as *const u8,
501                             addr,
502                             byte_num_of_depth,
503                         )
504                     }; // 字,显示前景色
505                 } else {
506                     let color: u32 = self.bkcolor.into();
507                     unsafe {
508                         copy_nonoverlapping(
509                             &color as *const u32 as *const u8,
510                             addr,
511                             byte_num_of_depth,
512                         )
513                     };
514                 }
515 
516                 unsafe {
517                     addr = addr.offset(1);
518                 }
519             }
520         }
521     }
522 }
523 
524 /// 单色显示的虚拟行结构体
525 
526 #[derive(Clone, Debug, Default)]
527 pub struct TextuiVlineNormal {
528     _characters: Vec<TextuiCharNormal>, // 字符对象数组
529     _index: i16,                        // 当前操作的位置
530 }
531 /// 彩色显示的虚拟行结构体
532 
533 #[derive(Clone, Debug, Default)]
534 pub struct TextuiVlineChromatic {
535     chars: Vec<TextuiCharChromatic>, // 字符对象数组
536     index: LineIndex,                // 当前操作的位置
537 }
538 impl TextuiVlineChromatic {
539     pub fn new(char_num: usize) -> Self {
540         let mut r = TextuiVlineChromatic {
541             chars: Vec::with_capacity(char_num),
542             index: LineIndex::new(0),
543         };
544 
545         for _ in 0..char_num {
546             r.chars.push(TextuiCharChromatic::new(
547                 None,
548                 FontColor::BLACK,
549                 FontColor::BLACK,
550             ));
551         }
552 
553         return r;
554     }
555 }
556 
557 #[derive(Clone, Debug)]
558 pub enum TextuiVline {
559     Chromatic(TextuiVlineChromatic),
560     _Normal(TextuiVlineNormal),
561 }
562 
563 #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
564 pub struct WindowId(u32);
565 
566 impl WindowId {
567     pub fn new() -> Self {
568         static MAX_ID: AtomicU32 = AtomicU32::new(0);
569         return WindowId(MAX_ID.fetch_add(1, Ordering::SeqCst));
570     }
571 }
572 #[allow(dead_code)]
573 #[derive(Clone, Debug)]
574 pub struct TextuiWindow {
575     // 虚拟行是个循环表,头和尾相接
576     id: WindowId,
577     // 虚拟行总数
578     vline_sum: i32,
579     // 当前已经使用了的虚拟行总数(即在已经输入到缓冲区(之后显示在屏幕上)的虚拟行数量)
580     vlines_used: i32,
581     // 位于最顶上的那一个虚拟行的行号
582     top_vline: LineId,
583     // 储存虚拟行的数组
584     vlines: Vec<TextuiVline>,
585     // 正在操作的vline
586     vline_operating: LineId,
587     // 每行最大容纳的字符数
588     chars_per_line: i32,
589     // 窗口flag
590     flags: WindowFlag,
591 }
592 
593 impl TextuiWindow {
594     /// 使用参数初始化window对象
595     /// ## 参数
596     ///
597     /// -flags 标志位
598     /// -vlines_num 虚拟行的总数
599     /// -chars_num 每行最大的字符数
600 
601     pub fn new(flags: WindowFlag, vlines_num: i32, chars_num: i32) -> Self {
602         let mut initial_vlines = Vec::new();
603 
604         for _ in 0..vlines_num {
605             let vline = TextuiVlineChromatic::new(chars_num as usize);
606 
607             initial_vlines.push(TextuiVline::Chromatic(vline));
608         }
609         TextuiWindow {
610             id: WindowId::new(),
611             flags,
612             vline_sum: vlines_num,
613             vlines_used: 1,
614             top_vline: LineId::new(0),
615             vlines: initial_vlines,
616             vline_operating: LineId::new(0),
617             chars_per_line: chars_num,
618         }
619     }
620 
621     /// 刷新某个窗口的缓冲区的某个虚拟行的连续n个字符对象
622     /// ## 参数
623     /// - window 窗口结构体
624     /// - vline_id 要刷新的虚拟行号
625     /// - start 起始字符号
626     /// - count 要刷新的字符数量
627     fn textui_refresh_characters(
628         &mut self,
629         vline_id: LineId,
630         start: LineIndex,
631         count: i32,
632     ) -> Result<(), SystemError> {
633         let actual_line_sum = textui_framework().actual_line.load(Ordering::SeqCst);
634 
635         // 判断虚拟行参数是否合法
636         if unlikely(
637             !vline_id.check(self.vline_sum)
638                 || (<LineIndex as Into<i32>>::into(start) + count) > self.chars_per_line,
639         ) {
640             return Err(SystemError::EINVAL);
641         }
642         // 计算虚拟行对应的真实行(即要渲染的行)
643         let mut actual_line_id = vline_id - self.top_vline; //为正说明虚拟行不在真实行显示的区域上面
644 
645         if <LineId as Into<i32>>::into(actual_line_id) < 0 {
646             //真实行数小于虚拟行数,则需要加上真实行数的位置,以便正确计算真实行
647             actual_line_id = actual_line_id + actual_line_sum;
648         }
649 
650         // 将此窗口的某个虚拟行的连续n个字符对象往缓存区写入
651         if self.flags.contains(WindowFlag::TEXTUI_CHROMATIC) {
652             let vline = &mut self.vlines[<LineId as Into<usize>>::into(vline_id)];
653             let mut i = 0;
654             let mut index = start;
655 
656             while i < count {
657                 if let TextuiVline::Chromatic(vline) = vline {
658                     vline.chars[<LineIndex as Into<usize>>::into(index)]
659                         .textui_refresh_character(actual_line_id, index)?;
660 
661                     index = index + 1;
662                 }
663                 i += 1;
664             }
665         }
666 
667         return Ok(());
668     }
669 
670     /// 重新渲染某个窗口的某个虚拟行
671     /// ## 参数
672 
673     /// - window 窗口结构体
674     /// - vline_id 虚拟行号
675 
676     fn textui_refresh_vline(&mut self, vline_id: LineId) -> Result<(), SystemError> {
677         if self.flags.contains(WindowFlag::TEXTUI_CHROMATIC) {
678             return self.textui_refresh_characters(
679                 vline_id,
680                 LineIndex::new(0),
681                 self.chars_per_line,
682             );
683         } else {
684             //todo支持纯文本字符()
685             todo!();
686         }
687     }
688 
689     // 刷新某个窗口的start 到start + count行(即将这些行输入到缓冲区)
690     fn textui_refresh_vlines(&mut self, start: LineId, count: i32) -> Result<i32, SystemError> {
691         let mut refresh_count = count;
692         for i in <LineId as Into<i32>>::into(start)
693             ..(self.vline_sum).min(<LineId as Into<i32>>::into(start) + count)
694         {
695             self.textui_refresh_vline(LineId::new(i))?;
696             refresh_count -= 1;
697         }
698         //因为虚拟行是循环表
699         let mut refresh_start = 0;
700         while refresh_count > 0 {
701             self.textui_refresh_vline(LineId::new(refresh_start))?;
702             refresh_start += 1;
703             refresh_count -= 1;
704         }
705         return Ok(0);
706     }
707 
708     /// 往某个窗口的缓冲区的某个虚拟行插入换行
709     /// ## 参数
710     /// - window 窗口结构体
711     /// - vline_id 虚拟行号
712     fn textui_new_line(&mut self) -> Result<i32, SystemError> {
713         // todo: 支持在两个虚拟行之间插入一个新行
714         let actual_line_sum = textui_framework().actual_line.load(Ordering::SeqCst);
715         self.vline_operating = self.vline_operating + 1;
716         //如果已经到了最大行数,则重新从0开始
717         if !self.vline_operating.check(self.vline_sum) {
718             self.vline_operating = LineId::new(0);
719         }
720 
721         if let TextuiVline::Chromatic(vline) =
722             &mut (self.vlines[<LineId as Into<usize>>::into(self.vline_operating)])
723         {
724             for i in 0..self.chars_per_line {
725                 if let Some(v_char) = vline.chars.get_mut(i as usize) {
726                     v_char.c = None;
727                     v_char.frcolor = FontColor::BLACK;
728                     v_char.bkcolor = FontColor::BLACK;
729                 }
730             }
731             vline.index = LineIndex::new(0);
732         }
733         // 当已经使用的虚拟行总数等于真实行总数时,说明窗口中已经显示的文本行数已经达到了窗口的最大容量。这时,如果继续在窗口中添加新的文本,就会导致文本溢出窗口而无法显示。因此,需要往下滚动屏幕来显示更多的文本。
734 
735         if self.vlines_used == actual_line_sum {
736             self.top_vline = self.top_vline + 1;
737 
738             if !self.top_vline.check(self.vline_sum) {
739                 self.top_vline = LineId::new(0);
740             }
741 
742             // 刷新所有行
743             self.textui_refresh_vlines(self.top_vline, actual_line_sum)?;
744         } else {
745             //换行说明上一行已经在缓冲区中,所以已经使用的虚拟行总数+1
746             self.vlines_used += 1;
747         }
748 
749         return Ok(0);
750     }
751 
752     /// 真正向窗口的缓冲区上输入字符的函数(位置为window.vline_operating,window.vline_operating.index)
753     /// ## 参数
754     /// - window
755     /// - character
756     fn true_textui_putchar_window(
757         &mut self,
758         character: char,
759         frcolor: FontColor,
760         bkcolor: FontColor,
761     ) -> Result<(), SystemError> {
762         // 启用彩色字符
763         if self.flags.contains(WindowFlag::TEXTUI_CHROMATIC) {
764             let mut line_index = LineIndex::new(0); //操作的列号
765             if let TextuiVline::Chromatic(vline) =
766                 &mut (self.vlines[<LineId as Into<usize>>::into(self.vline_operating)])
767             {
768                 let index = <LineIndex as Into<usize>>::into(vline.index);
769 
770                 if let Some(v_char) = vline.chars.get_mut(index) {
771                     v_char.c = Some(character);
772                     v_char.frcolor = frcolor;
773                     v_char.bkcolor = bkcolor;
774                 }
775                 line_index = vline.index;
776                 vline.index = vline.index + 1;
777             }
778 
779             self.textui_refresh_characters(self.vline_operating, line_index, 1)?;
780 
781             // 加入光标后,因为会识别光标,所以需超过该行最大字符数才能创建新行
782             if !line_index.check(self.chars_per_line - 1) {
783                 self.textui_new_line()?;
784             }
785         } else {
786             // todo: 支持纯文本字符
787             todo!();
788         }
789         return Ok(());
790     }
791     /// 根据输入的一个字符在窗口上输出
792     /// ## 参数
793 
794     /// - window 窗口
795     /// - character 字符
796     /// - FRcolor 前景色(RGB)
797     /// - BKcolor 背景色(RGB)
798 
799     fn textui_putchar_window(
800         &mut self,
801         character: char,
802         frcolor: FontColor,
803         bkcolor: FontColor,
804         is_enable_window: bool,
805     ) -> Result<(), SystemError> {
806         let actual_line_sum = textui_framework().actual_line.load(Ordering::SeqCst);
807 
808         //字符'\0'代表ASCII码表中的空字符,表示字符串的结尾
809         if unlikely(character == '\0') {
810             return Ok(());
811         }
812 
813         if unlikely(character == '\r') {
814             return Ok(());
815         }
816 
817         // 暂不支持纯文本窗口
818         if !self.flags.contains(WindowFlag::TEXTUI_CHROMATIC) {
819             return Ok(());
820         }
821         send_to_default_serial8250_port(&[character as u8]);
822 
823         //进行换行操作
824         if character == '\n' {
825             // 换行时还需要输出\r
826             send_to_default_serial8250_port(&[b'\r']);
827             if is_enable_window {
828                 self.textui_new_line()?;
829             }
830             return Ok(());
831         }
832         // 输出制表符
833         else if character == '\t' {
834             if is_enable_window {
835                 if let TextuiVline::Chromatic(vline) =
836                     &self.vlines[<LineId as Into<usize>>::into(self.vline_operating)]
837                 {
838                     //打印的空格数(注意将每行分成一个个表格,每个表格为8个字符)
839                     let mut space_to_print = 8 - <LineIndex as Into<usize>>::into(vline.index) % 8;
840                     while space_to_print > 0 {
841                         self.true_textui_putchar_window(' ', frcolor, bkcolor)?;
842                         space_to_print -= 1;
843                     }
844                 }
845             }
846         }
847         // 字符 '\x08' 代表 ASCII 码中的退格字符。它在输出中的作用是将光标向左移动一个位置,并在该位置上输出后续的字符,从而实现字符的删除或替换。
848         else if character == '\x08' {
849             if is_enable_window {
850                 let mut tmp = LineIndex(0);
851                 if let TextuiVline::Chromatic(vline) =
852                     &mut self.vlines[<LineId as Into<usize>>::into(self.vline_operating)]
853                 {
854                     vline.index = vline.index - 1;
855                     tmp = vline.index;
856                 }
857                 if <LineIndex as Into<i32>>::into(tmp) >= 0 {
858                     if let TextuiVline::Chromatic(vline) =
859                         &mut self.vlines[<LineId as Into<usize>>::into(self.vline_operating)]
860                     {
861                         if let Some(v_char) =
862                             vline.chars.get_mut(<LineIndex as Into<usize>>::into(tmp))
863                         {
864                             v_char.c = Some(' ');
865 
866                             v_char.bkcolor = bkcolor;
867                         }
868                     }
869                     return self.textui_refresh_characters(self.vline_operating, tmp, 1);
870                 }
871                 // 需要向上缩一行
872                 if <LineIndex as Into<i32>>::into(tmp) < 0 {
873                     // 当前行为空,需要重新刷新
874                     if let TextuiVline::Chromatic(vline) =
875                         &mut self.vlines[<LineId as Into<usize>>::into(self.vline_operating)]
876                     {
877                         vline.index = LineIndex::new(0);
878                         for i in 0..self.chars_per_line {
879                             if let Some(v_char) = vline.chars.get_mut(i as usize) {
880                                 v_char.c = None;
881                                 v_char.frcolor = FontColor::BLACK;
882                                 v_char.bkcolor = FontColor::BLACK;
883                             }
884                         }
885                     }
886                     // 上缩一行
887                     self.vline_operating = self.vline_operating - 1;
888                     if self.vline_operating.data() < 0 {
889                         self.vline_operating = LineId(self.vline_sum - 1);
890                     }
891 
892                     // 考虑是否向上滚动(在top_vline上退格)
893                     if self.vlines_used > actual_line_sum {
894                         self.top_vline = self.top_vline - 1;
895                         if <LineId as Into<i32>>::into(self.top_vline) < 0 {
896                             self.top_vline = LineId(self.vline_sum - 1);
897                         }
898                     }
899                     //因为上缩一行所以显示在屏幕中的虚拟行少一
900                     self.vlines_used -= 1;
901                     self.textui_refresh_vlines(self.top_vline, actual_line_sum)?;
902                 }
903             }
904         } else if is_enable_window {
905             if let TextuiVline::Chromatic(vline) =
906                 &self.vlines[<LineId as Into<usize>>::into(self.vline_operating)]
907             {
908                 if !vline.index.check(self.chars_per_line) {
909                     self.textui_new_line()?;
910                 }
911 
912                 return self.true_textui_putchar_window(character, frcolor, bkcolor);
913             }
914         }
915 
916         return Ok(());
917     }
918 }
919 impl Default for TextuiWindow {
920     fn default() -> Self {
921         TextuiWindow {
922             id: WindowId(0),
923             flags: WindowFlag::TEXTUI_CHROMATIC,
924             vline_sum: 0,
925             vlines_used: 1,
926             top_vline: LineId::new(0),
927             vlines: Vec::new(),
928             vline_operating: LineId::new(0),
929             chars_per_line: 0,
930         }
931     }
932 }
933 #[allow(dead_code)]
934 #[derive(Debug)]
935 pub struct TextUiFramework {
936     metadata: RwLock<ScmUiFrameworkMetadata>,
937     window_list: Arc<SpinLock<LinkedList<Arc<SpinLock<TextuiWindow>>>>>,
938     actual_line: AtomicI32, // 真实行的数量(textui的帧缓冲区能容纳的内容的行数)
939     current_window: Arc<SpinLock<TextuiWindow>>, // 当前的主窗口
940     default_window: Arc<SpinLock<TextuiWindow>>, // 默认print到的窗口
941 }
942 
943 impl TextUiFramework {
944     pub fn new(
945         metadata: ScmUiFrameworkMetadata,
946         window_list: Arc<SpinLock<LinkedList<Arc<SpinLock<TextuiWindow>>>>>,
947         current_window: Arc<SpinLock<TextuiWindow>>,
948         default_window: Arc<SpinLock<TextuiWindow>>,
949     ) -> Self {
950         let actual_line =
951             AtomicI32::new((metadata.buf_info().height() / TEXTUI_CHAR_HEIGHT) as i32);
952         let inner = TextUiFramework {
953             metadata: RwLock::new(metadata),
954             window_list,
955             actual_line,
956             current_window,
957             default_window,
958         };
959         return inner;
960     }
961 }
962 
963 impl ScmUiFramework for TextUiFramework {
964     // 安装ui框架的回调函数
965     fn install(&self) -> Result<i32, SystemError> {
966         send_to_default_serial8250_port("\ntextui_install_handler\n\0".as_bytes());
967         return Ok(0);
968     }
969     // 卸载ui框架的回调函数
970     fn uninstall(&self) -> Result<i32, SystemError> {
971         return Ok(0);
972     }
973     // 启用ui框架的回调函数
974     fn enable(&self) -> Result<i32, SystemError> {
975         textui_enable_put_to_window();
976         return Ok(0);
977     }
978     // 禁用ui框架的回调函数
979     fn disable(&self) -> Result<i32, SystemError> {
980         textui_disable_put_to_window();
981 
982         return Ok(0);
983     }
984     // 改变ui框架的帧缓冲区的回调函数
985     fn change(&self, buf_info: ScmBufferInfo) -> Result<i32, SystemError> {
986         let old_buf = textui_framework().metadata.read().buf_info();
987 
988         textui_framework().metadata.write().set_buf_info(buf_info);
989 
990         let mut new_buf = textui_framework().metadata.read().buf_info();
991 
992         new_buf.copy_from_nonoverlapping(&old_buf);
993         kdebug!("textui change buf_info: old: {:?}", old_buf);
994         kdebug!("textui change buf_info: new: {:?}", new_buf);
995 
996         return Ok(0);
997     }
998     ///  获取ScmUiFramework的元数据
999     ///  ## 返回值
1000     ///
1001     ///  -成功:Ok(ScmUiFramework的元数据)
1002     ///  -失败:Err(错误码)
1003     fn metadata(&self) -> Result<ScmUiFrameworkMetadata, SystemError> {
1004         let metadata = self.metadata.read().clone();
1005 
1006         return Ok(metadata);
1007     }
1008 }
1009 
1010 /// Mapping from characters to glyph indices.
1011 pub trait GlyphMapping: Sync {
1012     /// Maps a character to a glyph index.
1013     ///
1014     /// If `c` isn't included in the font the index of a suitable replacement glyph is returned.
1015     fn index(&self, c: char) -> usize;
1016 }
1017 
1018 impl<F> GlyphMapping for F
1019 where
1020     F: Sync + Fn(char) -> usize,
1021 {
1022     fn index(&self, c: char) -> usize {
1023         self(c)
1024     }
1025 }
1026 
1027 /// 在默认窗口上输出一个字符
1028 /// ## 参数
1029 /// - character 字符
1030 /// - FRcolor 前景色(RGB)
1031 /// - BKcolor 背景色(RGB)
1032 
1033 #[no_mangle]
1034 pub extern "C" fn rs_textui_putchar(character: u8, fr_color: u32, bk_color: u32) -> i32 {
1035     let current_vcnum = CURRENT_VCNUM.load(Ordering::SeqCst);
1036     if current_vcnum != -1 {
1037         // tty已经初始化了之后才输出到屏幕
1038         let fr = (fr_color & 0x00ff0000) >> 16;
1039         let fg = (fr_color & 0x0000ff00) >> 8;
1040         let fb = fr_color & 0x000000ff;
1041         let br = (bk_color & 0x00ff0000) >> 16;
1042         let bg = (bk_color & 0x0000ff00) >> 8;
1043         let bb = bk_color & 0x000000ff;
1044         let buf = format!(
1045             "\x1B[38;2;{fr};{fg};{fb};48;2;{br};{bg};{bb}m{}\x1B[0m",
1046             character as char
1047         );
1048         let port = tty_port(current_vcnum as usize);
1049         let tty = port.port_data().internal_tty();
1050         if let Some(tty) = tty {
1051             send_to_default_serial8250_port(&[character]);
1052             return tty
1053                 .write_without_serial(buf.as_bytes(), buf.len())
1054                 .map(|_| 0)
1055                 .unwrap_or_else(|e| e.to_posix_errno());
1056         }
1057     }
1058     return textui_putchar(
1059         character as char,
1060         FontColor::from(fr_color),
1061         FontColor::from(bk_color),
1062     )
1063     .map(|_| 0)
1064     .unwrap_or_else(|e| e.to_posix_errno());
1065 }
1066 
1067 pub fn textui_putchar(
1068     character: char,
1069     fr_color: FontColor,
1070     bk_color: FontColor,
1071 ) -> Result<(), SystemError> {
1072     if unsafe { TEXTUI_IS_INIT } {
1073         return textui_framework()
1074             .current_window
1075             .lock_irqsave()
1076             .textui_putchar_window(
1077                 character,
1078                 fr_color,
1079                 bk_color,
1080                 textui_is_enable_put_to_window(),
1081             );
1082     } else {
1083         //未初始化暴力输出
1084         return no_init_textui_putchar_window(
1085             character,
1086             fr_color,
1087             bk_color,
1088             textui_is_enable_put_to_window(),
1089         );
1090     }
1091 }
1092 
1093 /// 向默认窗口输出一个字符串
1094 pub fn textui_putstr(
1095     string: &str,
1096     fr_color: FontColor,
1097     bk_color: FontColor,
1098 ) -> Result<(), SystemError> {
1099     let window = if unsafe { TEXTUI_IS_INIT } {
1100         let fw = textui_framework();
1101         let w = fw.current_window.clone();
1102         Some(w)
1103     } else {
1104         None
1105     };
1106 
1107     let mut guard = window.as_ref().map(|w| w.lock_irqsave());
1108 
1109     for character in string.chars() {
1110         if unsafe { TEXTUI_IS_INIT } {
1111             guard.as_mut().unwrap().textui_putchar_window(
1112                 character,
1113                 fr_color,
1114                 bk_color,
1115                 textui_is_enable_put_to_window(),
1116             )?;
1117         } else {
1118             no_init_textui_putchar_window(
1119                 character,
1120                 fr_color,
1121                 bk_color,
1122                 textui_is_enable_put_to_window(),
1123             )?;
1124         }
1125     }
1126 
1127     return Ok(());
1128 }
1129 
1130 /// 初始化text ui框架
1131 #[inline(never)]
1132 pub fn textui_init() -> Result<i32, SystemError> {
1133     #[cfg(target_arch = "x86_64")]
1134     textui_framwork_init();
1135 
1136     return Ok(0);
1137 }
1138