xref: /DragonOS/kernel/src/driver/tty/virtual_terminal/mod.rs (revision 840045af94ea3391f29e87e968db5d9c48316981)
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 impl TtyConsoleDriverInner {
100     pub fn new() -> Result<Self, SystemError> {
101         Ok(Self {
102             console: Arc::new(BlittingFbConsole::new()?),
103         })
104     }
105 }
106 
107 impl TtyOperation for TtyConsoleDriverInner {
108     fn install(&self, _driver: Arc<TtyDriver>, tty: Arc<TtyCore>) -> Result<(), SystemError> {
109         let tty_core = tty.core();
110         let mut vc_data = VIRT_CONSOLES[tty_core.index()].lock();
111 
112         self.console.con_init(&mut vc_data, true)?;
113         if vc_data.complement_mask == 0 {
114             vc_data.complement_mask = if vc_data.color_mode { 0x7700 } else { 0x0800 };
115         }
116         vc_data.s_complement_mask = vc_data.complement_mask;
117         // vc_data.bytes_per_row = vc_data.cols << 1;
118         vc_data.index = tty_core.index();
119         vc_data.bottom = vc_data.rows;
120         vc_data.set_driver_funcs(Arc::downgrade(
121             &(self.console.clone() as Arc<dyn ConsoleSwitch>),
122         ));
123 
124         // todo: unicode字符集处理?
125 
126         if vc_data.cols > VC_MAXCOL || vc_data.rows > VC_MAXROW {
127             return Err(SystemError::EINVAL);
128         }
129 
130         vc_data.init(None, None, true);
131         vc_data.update_attr();
132 
133         let window_size = tty_core.window_size_upgradeable();
134         if window_size.col == 0 && window_size.row == 0 {
135             let mut window_size = window_size.upgrade();
136             window_size.col = vc_data.cols as u16;
137             window_size.row = vc_data.rows as u16;
138         }
139 
140         if vc_data.utf {
141             tty_core.termios_write().input_mode.insert(InputMode::IUTF8);
142         } else {
143             tty_core.termios_write().input_mode.remove(InputMode::IUTF8);
144         }
145 
146         // 加入sysfs?
147 
148         Ok(())
149     }
150 
151     fn open(&self, _tty: &TtyCoreData) -> Result<(), SystemError> {
152         Ok(())
153     }
154 
155     fn write_room(&self, _tty: &TtyCoreData) -> usize {
156         32768
157     }
158 
159     /// 参考: https://code.dragonos.org.cn/xref/linux-6.1.9/drivers/tty/vt/vt.c#2894
160     fn write(&self, tty: &TtyCoreData, buf: &[u8], mut nr: usize) -> Result<usize, SystemError> {
161         // 关闭中断
162         let mut vc_data = tty.vc_data_irqsave();
163 
164         let mut offset = 0;
165 
166         // 这个参数是用来扫描unicode字符的,但是这部分目前未完成,先写着
167         let mut rescan = false;
168         let mut ch: u32 = 0;
169 
170         let mut draw = DrawRegion::default();
171 
172         // 首先隐藏光标再写
173         vc_data.hide_cursor();
174 
175         while nr != 0 {
176             if !rescan {
177                 ch = buf[offset] as u32;
178                 offset += 1;
179                 nr -= 1;
180             }
181 
182             let (tc, rescan_last) = vc_data.translate(&mut ch);
183             if tc.is_none() {
184                 // 表示未转换完成
185                 continue;
186             }
187 
188             let tc = tc.unwrap();
189             rescan = rescan_last;
190 
191             if vc_data.is_control(tc, ch) {
192                 vc_data.flush(&mut draw);
193                 vc_data.do_control(ch);
194                 continue;
195             }
196 
197             if !vc_data.console_write_normal(tc, ch, &mut draw) {
198                 continue;
199             }
200         }
201 
202         vc_data.flush(&mut draw);
203 
204         // TODO: notify update
205         return Ok(offset);
206     }
207 
208     fn flush_chars(&self, tty: &TtyCoreData) {
209         let mut vc_data = tty.vc_data_irqsave();
210         vc_data.set_cursor();
211     }
212 
213     fn put_char(&self, tty: &TtyCoreData, ch: u8) -> Result<(), SystemError> {
214         self.write(tty, &[ch], 1)?;
215         Ok(())
216     }
217 
218     fn ioctl(&self, _tty: Arc<TtyCore>, _cmd: u32, _arg: usize) -> Result<(), SystemError> {
219         // TODO
220         Err(SystemError::ENOIOCTLCMD)
221     }
222 }
223 
224 #[derive(Debug, Clone)]
225 pub struct VtModeData {
226     mode: VtMode,
227     /// 释放请求时触发的信号
228     relsig: u16,
229     /// 获取请求时触发的信号
230     acqsig: u16,
231 }
232 
233 #[allow(dead_code)]
234 #[derive(Debug, Clone)]
235 pub enum VtMode {
236     /// 自动切换模式,即在请求输入时自动切换到终端
237     Auto,
238     /// 手动切换模式,需要通过 ioctl 请求切换到终端
239     Process,
240     /// 等待终端确认,即在切换到终端时等待终端的确认信号
241     Ackacq,
242 }
243 
244 /// 用于给vc确定要写入的buf位置
245 #[derive(Debug, Default)]
246 pub struct DrawRegion {
247     /// 偏移量
248     pub offset: usize,
249     /// 写入数量
250     pub size: usize,
251     pub x: Option<u32>,
252 }
253 
254 // 初始化虚拟终端
255 #[inline(never)]
256 pub fn vty_init() -> Result<(), SystemError> {
257     // 注册虚拟终端设备并将虚拟终端设备加入到文件系统
258     let vc0 = TtyDevice::new(
259         "vc0",
260         IdTable::new(
261             String::from("vc0"),
262             Some(DeviceNumber::new(Major::TTY_MAJOR, 0)),
263         ),
264     );
265     // 注册tty设备
266     // CharDevOps::cdev_add(
267     //     vc0.clone() as Arc<dyn CharDevice>,
268     //     IdTable::new(
269     //         String::from("vc0"),
270     //         Some(DeviceNumber::new(Major::TTY_MAJOR, 0)),
271     //     ),
272     //     1,
273     // )?;
274 
275     // CharDevOps::register_chardev_region(DeviceNumber::new(Major::TTY_MAJOR, 0), 1, "/dev/vc/0")?;
276     device_register(vc0.clone())?;
277     devfs_register("vc0", vc0)?;
278 
279     // vcs_init?
280 
281     let console_driver = TtyDriver::new(
282         MAX_NR_CONSOLES,
283         "tty",
284         1,
285         Major::TTY_MAJOR,
286         0,
287         TtyDriverType::Console,
288         TTY_STD_TERMIOS.clone(),
289         Arc::new(TtyConsoleDriverInner::new()?),
290     );
291 
292     TtyDriverManager::tty_register_driver(console_driver)?;
293 
294     CURRENT_VCNUM.store(0, Ordering::SeqCst);
295 
296     // 初始化键盘?
297 
298     // TODO: 为vc
299 
300     Ok(())
301 }
302