xref: /DragonOS/kernel/src/driver/tty/virtual_terminal/mod.rs (revision 52da9a59374752b4d01907b052135a0d317781dd)
1 use core::sync::atomic::Ordering;
2 
3 use alloc::{string::String, sync::Arc, vec::Vec};
4 use system_error::SystemError;
5 
6 use crate::{
7     driver::{
8         base::device::{
9             device_number::{DeviceNumber, Major},
10             device_register, IdTable,
11         },
12         video::fbdev::base::fbcon::framebuffer_console::BlittingFbConsole,
13     },
14     filesystem::devfs::devfs_register,
15     libs::spinlock::SpinLock,
16 };
17 
18 use self::virtual_console::{VirtualConsoleData, CURRENT_VCNUM};
19 
20 use super::{
21     console::ConsoleSwitch,
22     termios::{InputMode, TTY_STD_TERMIOS},
23     tty_core::{TtyCore, TtyCoreData},
24     tty_device::TtyDevice,
25     tty_driver::{TtyDriver, TtyDriverManager, TtyDriverType, TtyOperation},
26 };
27 
28 pub mod console_map;
29 pub mod virtual_console;
30 
31 pub const MAX_NR_CONSOLES: u32 = 63;
32 pub const VC_MAXCOL: usize = 32767;
33 pub const VC_MAXROW: usize = 32767;
34 
35 pub const DEFAULT_RED: [u16; 16] = [
36     0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x55, 0xff, 0x55, 0xff, 0x55, 0xff, 0x55, 0xff,
37 ];
38 
39 pub const DEFAULT_GREEN: [u16; 16] = [
40     0x00, 0x00, 0xaa, 0x55, 0x00, 0x00, 0xaa, 0xaa, 0x55, 0x55, 0xff, 0xff, 0x55, 0x55, 0xff, 0xff,
41 ];
42 
43 pub const DEFAULT_BLUE: [u16; 16] = [
44     0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff, 0xff,
45 ];
46 
47 pub const COLOR_TABLE: &'static [u8] = &[0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15];
48 
49 lazy_static! {
50     pub static ref VIRT_CONSOLES: Vec<Arc<SpinLock<VirtualConsoleData>>> = {
51         let mut v = Vec::with_capacity(MAX_NR_CONSOLES as usize);
52         for i in 0..MAX_NR_CONSOLES as usize {
53             v.push(Arc::new(SpinLock::new(VirtualConsoleData::new(i))));
54         }
55 
56         v
57     };
58 }
59 
60 #[derive(Debug, Clone, Copy, Default)]
61 pub struct Color {
62     pub red: u16,
63     pub green: u16,
64     pub blue: u16,
65     pub transp: u16,
66 }
67 
68 impl Color {
69     pub fn from_256(col: u32) -> Self {
70         let mut color = Self::default();
71         if col < 8 {
72             color.red = if col & 1 != 0 { 0xaa } else { 0x00 };
73             color.green = if col & 2 != 0 { 0xaa } else { 0x00 };
74             color.blue = if col & 4 != 0 { 0xaa } else { 0x00 };
75         } else if col < 16 {
76             color.red = if col & 1 != 0 { 0xff } else { 0x55 };
77             color.green = if col & 2 != 0 { 0xff } else { 0x55 };
78             color.blue = if col & 4 != 0 { 0xff } else { 0x55 };
79         } else if col < 232 {
80             color.red = ((col - 16) / 36 * 85 / 2) as u16;
81             color.green = ((col - 16) / 6 % 6 * 85 / 2) as u16;
82             color.blue = ((col - 16) % 6 * 85 / 2) as u16;
83         } else {
84             let col = (col * 10 - 2312) as u16;
85             color.red = col;
86             color.green = col;
87             color.blue = col;
88         }
89 
90         color
91     }
92 }
93 
94 #[derive(Debug)]
95 pub struct TtyConsoleDriverInner {
96     console: Arc<BlittingFbConsole>,
97 }
98 
99 unsafe impl Sync for TtyConsoleDriverInner {}
100 
101 impl TtyConsoleDriverInner {
102     pub fn new() -> Result<Self, SystemError> {
103         Ok(Self {
104             console: Arc::new(BlittingFbConsole::new()?),
105         })
106     }
107 }
108 
109 impl TtyOperation for TtyConsoleDriverInner {
110     fn install(&self, _driver: Arc<TtyDriver>, tty: Arc<TtyCore>) -> Result<(), SystemError> {
111         let tty_core = tty.core();
112         let mut vc_data = VIRT_CONSOLES[tty_core.index()].lock();
113 
114         self.console.con_init(&mut vc_data, true)?;
115         if vc_data.complement_mask == 0 {
116             vc_data.complement_mask = if vc_data.color_mode { 0x7700 } else { 0x0800 };
117         }
118         vc_data.s_complement_mask = vc_data.complement_mask;
119         // vc_data.bytes_per_row = vc_data.cols << 1;
120         vc_data.index = tty_core.index();
121         vc_data.bottom = vc_data.rows;
122         vc_data.set_driver_funcs(Arc::downgrade(
123             &(self.console.clone() as Arc<dyn ConsoleSwitch>),
124         ));
125 
126         // todo: unicode字符集处理?
127 
128         if vc_data.cols > VC_MAXCOL || vc_data.rows > VC_MAXROW {
129             return Err(SystemError::EINVAL);
130         }
131 
132         vc_data.init(None, None, true);
133         vc_data.update_attr();
134 
135         let window_size = tty_core.window_size_upgradeable();
136         if window_size.col == 0 && window_size.row == 0 {
137             let mut window_size = window_size.upgrade();
138             window_size.col = vc_data.cols as u16;
139             window_size.row = vc_data.rows as u16;
140         }
141 
142         if vc_data.utf {
143             tty_core.termios_write().input_mode.insert(InputMode::IUTF8);
144         } else {
145             tty_core.termios_write().input_mode.remove(InputMode::IUTF8);
146         }
147 
148         // 加入sysfs?
149 
150         Ok(())
151     }
152 
153     fn open(&self, _tty: &TtyCoreData) -> Result<(), SystemError> {
154         Ok(())
155     }
156 
157     fn write_room(&self, _tty: &TtyCoreData) -> usize {
158         32768
159     }
160 
161     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/tty/vt/vt.c#2894
162     fn write(&self, tty: &TtyCoreData, buf: &[u8], mut nr: usize) -> Result<usize, SystemError> {
163         // 关闭中断
164         let mut vc_data = tty.vc_data_irqsave();
165 
166         let mut offset = 0;
167 
168         // 这个参数是用来扫描unicode字符的,但是这部分目前未完成,先写着
169         let mut rescan = false;
170         let mut ch: u32 = 0;
171 
172         let mut draw = DrawRegion::default();
173 
174         // 首先隐藏光标再写
175         vc_data.hide_cursor();
176 
177         while nr != 0 {
178             if !rescan {
179                 ch = buf[offset] as u32;
180                 offset += 1;
181                 nr -= 1;
182             }
183 
184             let (tc, rescan_last) = vc_data.translate(&mut ch);
185             if tc.is_none() {
186                 // 表示未转换完成
187                 continue;
188             }
189 
190             let tc = tc.unwrap();
191             rescan = rescan_last;
192 
193             if vc_data.is_control(tc, ch) {
194                 vc_data.flush(&mut draw);
195                 vc_data.do_control(ch);
196                 continue;
197             }
198 
199             if !vc_data.console_write_normal(tc, ch, &mut draw) {
200                 continue;
201             }
202         }
203 
204         vc_data.flush(&mut draw);
205 
206         // TODO: notify update
207         return Ok(offset);
208     }
209 
210     fn flush_chars(&self, tty: &TtyCoreData) {
211         let mut vc_data = tty.vc_data_irqsave();
212         vc_data.set_cursor();
213     }
214 
215     fn put_char(&self, tty: &TtyCoreData, ch: u8) -> Result<(), SystemError> {
216         self.write(tty, &[ch], 1)?;
217         Ok(())
218     }
219 
220     fn ioctl(&self, _tty: Arc<TtyCore>, _cmd: u32, _arg: usize) -> Result<(), SystemError> {
221         // TODO
222         Err(SystemError::ENOIOCTLCMD)
223     }
224 }
225 
226 #[derive(Debug, Clone)]
227 pub struct VtModeData {
228     mode: VtMode,
229     /// 释放请求时触发的信号
230     relsig: u16,
231     /// 获取请求时触发的信号
232     acqsig: u16,
233 }
234 
235 #[allow(dead_code)]
236 #[derive(Debug, Clone)]
237 pub enum VtMode {
238     /// 自动切换模式,即在请求输入时自动切换到终端
239     Auto,
240     /// 手动切换模式,需要通过 ioctl 请求切换到终端
241     Process,
242     /// 等待终端确认,即在切换到终端时等待终端的确认信号
243     Ackacq,
244 }
245 
246 /// 用于给vc确定要写入的buf位置
247 #[derive(Debug, Default)]
248 pub struct DrawRegion {
249     /// 偏移量
250     pub offset: usize,
251     /// 写入数量
252     pub size: usize,
253     pub x: Option<u32>,
254 }
255 
256 // 初始化虚拟终端
257 #[inline(never)]
258 pub fn vty_init() -> Result<(), SystemError> {
259     // 注册虚拟终端设备并将虚拟终端设备加入到文件系统
260     let vc0 = TtyDevice::new(
261         "vc0",
262         IdTable::new(
263             String::from("vc0"),
264             Some(DeviceNumber::new(Major::TTY_MAJOR, 0)),
265         ),
266     );
267     // 注册tty设备
268     // CharDevOps::cdev_add(
269     //     vc0.clone() as Arc<dyn CharDevice>,
270     //     IdTable::new(
271     //         String::from("vc0"),
272     //         Some(DeviceNumber::new(Major::TTY_MAJOR, 0)),
273     //     ),
274     //     1,
275     // )?;
276 
277     // CharDevOps::register_chardev_region(DeviceNumber::new(Major::TTY_MAJOR, 0), 1, "/dev/vc/0")?;
278     device_register(vc0.clone())?;
279     devfs_register("vc0", vc0)?;
280 
281     // vcs_init?
282 
283     let console_driver = TtyDriver::new(
284         MAX_NR_CONSOLES,
285         "tty",
286         1,
287         Major::TTY_MAJOR,
288         0,
289         TtyDriverType::Console,
290         TTY_STD_TERMIOS.clone(),
291         Arc::new(TtyConsoleDriverInner::new()?),
292     );
293 
294     TtyDriverManager::tty_register_driver(console_driver)?;
295 
296     CURRENT_VCNUM.store(0, Ordering::SeqCst);
297 
298     // 初始化键盘?
299 
300     // TODO: 为vc
301 
302     Ok(())
303 }
304