1 use core::{ 2 fmt::Debug, 3 intrinsics::unlikely, 4 sync::atomic::{AtomicBool, AtomicU32, Ordering}, 5 }; 6 7 use alloc::{boxed::Box, collections::LinkedList, string::String, sync::Arc}; 8 use system_error::SystemError; 9 10 use crate::{ 11 driver::{serial::serial8250::send_to_default_serial8250_port, video::video_refresh_manager}, 12 libs::{lib_ui::textui::textui_is_enable_put_to_window, rwlock::RwLock, spinlock::SpinLock}, 13 mm::VirtAddr, 14 }; 15 16 use super::{ 17 textui::{textui_disable_put_to_window, textui_enable_put_to_window}, 18 textui_no_alloc::textui_init_no_alloc, 19 }; 20 21 /// 全局的UI框架列表 22 pub static SCM_FRAMEWORK_LIST: SpinLock<LinkedList<Arc<dyn ScmUiFramework>>> = 23 SpinLock::new(LinkedList::new()); 24 25 /// 当前在使用的UI框架 26 pub static CURRENT_FRAMEWORK: RwLock<Option<Arc<dyn ScmUiFramework>>> = RwLock::new(None); 27 28 /// 是否启用双缓冲 29 pub static SCM_DOUBLE_BUFFER_ENABLED: AtomicBool = AtomicBool::new(false); 30 31 bitflags! { 32 pub struct ScmBufferFlag:u8 { 33 // 帧缓冲区标志位 34 const SCM_BF_FB = 1 << 0; // 当前buffer是设备显存中的帧缓冲区 35 const SCM_BF_DB = 1 << 1; // 当前buffer是双缓冲 36 const SCM_BF_TEXT = 1 << 2; // 使用文本模式 37 const SCM_BF_PIXEL = 1 << 3; // 使用图像模式 38 } 39 } 40 #[derive(Clone, Debug)] 41 #[allow(dead_code)] 42 pub enum ScmFramworkType { 43 Text, 44 Gui, 45 Unused, 46 } 47 #[derive(Debug, Clone)] 48 pub enum ScmBuffer { 49 DeviceBuffer(VirtAddr), 50 DoubleBuffer(Arc<SpinLock<Box<[u8]>>>), 51 } 52 53 #[derive(Debug, Clone)] 54 pub struct ScmBufferInfo { 55 width: u32, // 帧缓冲区宽度(pixel或columns) 56 height: u32, // 帧缓冲区高度(pixel或lines) 57 size: u32, // 帧缓冲区大小(bytes) 58 bit_depth: u32, // 像素点位深度 59 pub buf: ScmBuffer, 60 flags: ScmBufferFlag, // 帧缓冲区标志位 61 } 62 63 #[allow(dead_code)] 64 impl ScmBufferInfo { 65 /// 创建新的帧缓冲区信息 66 /// 67 /// ## 参数 68 /// 69 /// - `buf_type` 帧缓冲区类型 70 /// 71 /// ## 返回值 72 /// 73 /// - `Result<Self, SystemError>` 创建成功返回新的帧缓冲区结构体,创建失败返回错误码 74 pub fn new(mut buf_type: ScmBufferFlag) -> Result<Self, SystemError> { 75 if unlikely(!SCM_DOUBLE_BUFFER_ENABLED.load(Ordering::SeqCst)) { 76 let mut device_buffer = video_refresh_manager().device_buffer().clone(); 77 buf_type.remove(ScmBufferFlag::SCM_BF_DB); 78 buf_type.insert(ScmBufferFlag::SCM_BF_FB); 79 device_buffer.flags = buf_type; 80 return Ok(device_buffer); 81 } else { 82 let device_buffer_guard = video_refresh_manager().device_buffer(); 83 84 let buf_space: Arc<SpinLock<Box<[u8]>>> = Arc::new(SpinLock::new( 85 vec![0u8; (device_buffer_guard.size / 4) as usize].into_boxed_slice(), 86 )); 87 88 assert!(buf_type.contains(ScmBufferFlag::SCM_BF_DB)); 89 90 assert_eq!( 91 device_buffer_guard.size as usize, 92 buf_space.lock().len() * core::mem::size_of::<u8>() 93 ); 94 95 // 创建双缓冲区 96 let buffer = Self { 97 width: device_buffer_guard.width, 98 height: device_buffer_guard.height, 99 size: device_buffer_guard.size, 100 bit_depth: device_buffer_guard.bit_depth, 101 flags: buf_type, 102 buf: ScmBuffer::DoubleBuffer(buf_space), 103 }; 104 drop(device_buffer_guard); 105 106 return Ok(buffer); 107 } 108 } 109 110 pub unsafe fn new_device_buffer( 111 width: u32, 112 height: u32, 113 size: u32, 114 bit_depth: u32, 115 buf_type: ScmBufferFlag, 116 vaddr: VirtAddr, 117 ) -> Result<Self, SystemError> { 118 let buffer = Self { 119 width, 120 height, 121 size, 122 bit_depth, 123 flags: buf_type, 124 buf: ScmBuffer::DeviceBuffer(vaddr), 125 }; 126 return Ok(buffer); 127 } 128 129 pub fn buf_size(&self) -> usize { 130 self.size as usize 131 } 132 133 pub fn bit_depth(&self) -> u32 { 134 self.bit_depth 135 } 136 137 pub fn height(&self) -> u32 { 138 self.height 139 } 140 141 pub fn width(&self) -> u32 { 142 self.width 143 } 144 145 pub fn is_double_buffer(&self) -> bool { 146 matches!(&self.buf, ScmBuffer::DoubleBuffer(_)) 147 } 148 pub fn is_device_buffer(&self) -> bool { 149 matches!(&self.buf, ScmBuffer::DeviceBuffer(_)) 150 } 151 152 pub fn copy_from_nonoverlapping(&mut self, src: &ScmBufferInfo) { 153 assert!(self.buf_size() == src.buf_size()); 154 match &self.buf { 155 ScmBuffer::DeviceBuffer(vaddr) => { 156 let len = self.buf_size() / core::mem::size_of::<u32>(); 157 let self_buf_guard = 158 unsafe { core::slice::from_raw_parts_mut(vaddr.data() as *mut u8, len) }; 159 match &src.buf { 160 ScmBuffer::DeviceBuffer(vaddr) => { 161 let src_buf_guard = 162 unsafe { core::slice::from_raw_parts(vaddr.data() as *const u8, len) }; 163 self_buf_guard.copy_from_slice(src_buf_guard); 164 } 165 ScmBuffer::DoubleBuffer(double_buffer) => { 166 let src_buf_guard = double_buffer.lock(); 167 self_buf_guard.copy_from_slice(src_buf_guard.as_ref()); 168 } 169 }; 170 } 171 172 ScmBuffer::DoubleBuffer(double_buffer) => { 173 let mut double_buffer_guard = double_buffer.lock(); 174 match &src.buf { 175 ScmBuffer::DeviceBuffer(vaddr) => { 176 let len = src.buf_size() / core::mem::size_of::<u8>(); 177 double_buffer_guard.as_mut().copy_from_slice(unsafe { 178 core::slice::from_raw_parts(vaddr.data() as *const u8, len) 179 }); 180 } 181 ScmBuffer::DoubleBuffer(double_buffer) => { 182 let x = double_buffer.lock(); 183 double_buffer_guard.as_mut().copy_from_slice(x.as_ref()); 184 } 185 }; 186 } 187 } 188 } 189 } 190 191 #[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] 192 pub struct ScmUiFrameworkId(u32); 193 194 impl ScmUiFrameworkId { 195 /// 分配一个新的框架id 196 pub fn new() -> Self { 197 static MAX_ID: AtomicU32 = AtomicU32::new(0); 198 return ScmUiFrameworkId(MAX_ID.fetch_add(1, Ordering::SeqCst)); 199 } 200 } 201 #[allow(dead_code)] 202 #[derive(Debug, Clone)] 203 pub struct ScmUiFrameworkMetadata { 204 id: ScmUiFrameworkId, 205 name: String, 206 framework_type: ScmFramworkType, 207 pub buf_info: ScmBufferInfo, 208 } 209 210 impl ScmUiFrameworkMetadata { 211 pub fn new(name: String, framework_type: ScmFramworkType) -> Self { 212 match framework_type { 213 ScmFramworkType::Text => { 214 let result = ScmUiFrameworkMetadata { 215 id: ScmUiFrameworkId::new(), 216 name, 217 framework_type: ScmFramworkType::Text, 218 buf_info: ScmBufferInfo::new( 219 ScmBufferFlag::SCM_BF_TEXT | ScmBufferFlag::SCM_BF_DB, 220 ) 221 .unwrap(), 222 }; 223 224 return result; 225 } 226 ScmFramworkType::Gui => todo!(), 227 ScmFramworkType::Unused => todo!(), 228 } 229 } 230 pub fn buf_info(&self) -> ScmBufferInfo { 231 return self.buf_info.clone(); 232 } 233 pub fn set_buf_info(&mut self, buf_info: ScmBufferInfo) { 234 self.buf_info = buf_info; 235 } 236 } 237 pub trait ScmUiFramework: Sync + Send + Debug { 238 // 安装ui框架的回调函数 239 fn install(&self) -> Result<i32, SystemError> { 240 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 241 } 242 // 卸载ui框架的回调函数 243 fn uninstall(&self) -> Result<i32, SystemError> { 244 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 245 } 246 // 启用ui框架的回调函数 247 fn enable(&self) -> Result<i32, SystemError> { 248 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 249 } 250 // 禁用ui框架的回调函数 251 fn disable(&self) -> Result<i32, SystemError> { 252 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 253 } 254 // 改变ui框架的帧缓冲区的回调函数 255 fn change(&self, _buf: ScmBufferInfo) -> Result<i32, SystemError> { 256 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 257 } 258 /// @brief 获取ScmUiFramework的元数据 259 /// @return 成功:Ok(ScmUiFramework的元数据) 260 /// 失败:Err(错误码) 261 fn metadata(&self) -> Result<ScmUiFrameworkMetadata, SystemError> { 262 // 若文件系统没有实现此方法,则返回“不支持” 263 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 264 } 265 } 266 267 /// 初始化屏幕控制模块 268 /// 269 /// ## 调用时机 270 /// 271 /// 该函数在内核启动的早期进行调用。调用时,内存管理模块尚未初始化。 272 pub fn scm_init(enable_put_to_window: bool) { 273 SCM_DOUBLE_BUFFER_ENABLED.store(false, Ordering::SeqCst); // 禁用双缓冲 274 if enable_put_to_window { 275 textui_enable_put_to_window(); 276 } else { 277 textui_disable_put_to_window(); 278 } 279 textui_init_no_alloc(enable_put_to_window); 280 281 send_to_default_serial8250_port("\nfinish_scm_init\n\0".as_bytes()); 282 } 283 284 /// 启用某个ui框架,将它的帧缓冲区渲染到屏幕上 285 /// ## 参数 286 /// 287 /// - framework 要启动的ui框架 288 289 pub fn scm_framework_enable(framework: Arc<dyn ScmUiFramework>) -> Result<i32, SystemError> { 290 // 获取信息 291 let metadata = framework.metadata()?; 292 293 // if metadata.buf_info.buf.is_null() { 294 // return Err(SystemError::EINVAL); 295 // } 296 let mut current_framework = CURRENT_FRAMEWORK.write(); 297 298 if SCM_DOUBLE_BUFFER_ENABLED.load(Ordering::SeqCst) { 299 video_refresh_manager().set_refresh_target(&metadata.buf_info)?; 300 } 301 302 framework.enable()?; 303 current_framework.replace(framework); 304 305 return Ok(0); 306 } 307 /// 向屏幕管理器注册UI框架 308 /// 309 /// ## 参数 310 /// - framework 框架结构体 311 312 pub fn scm_register(framework: Arc<dyn ScmUiFramework>) -> Result<i32, SystemError> { 313 // 把ui框架加入链表 314 315 SCM_FRAMEWORK_LIST.lock().push_back(framework.clone()); 316 // 调用ui框架的回调函数以安装ui框架,并将其激活 317 framework.install()?; 318 319 // 如果当前还没有框架获得了屏幕的控制权,就让其拿去 320 if CURRENT_FRAMEWORK.read().is_none() { 321 return scm_framework_enable(framework); 322 } 323 return Ok(0); 324 } 325 326 /// 屏幕管理器启用双缓冲区 327 #[allow(dead_code)] 328 pub fn scm_enable_double_buffer() -> Result<i32, SystemError> { 329 if SCM_DOUBLE_BUFFER_ENABLED.load(Ordering::SeqCst) { 330 // 已经开启了双缓冲区了, 直接退出 331 return Ok(0); 332 } 333 let scm_list = SCM_FRAMEWORK_LIST.lock(); 334 if scm_list.is_empty() { 335 // scm 框架链表为空 336 return Ok(0); 337 } 338 drop(scm_list); 339 SCM_DOUBLE_BUFFER_ENABLED.store(true, Ordering::SeqCst); 340 // 创建双缓冲区 341 let buf_info = ScmBufferInfo::new(ScmBufferFlag::SCM_BF_DB | ScmBufferFlag::SCM_BF_PIXEL)?; 342 343 // 设置定时刷新的对象 344 video_refresh_manager() 345 .set_refresh_target(&buf_info) 346 .expect("set refresh target failed"); 347 348 // 设置当前框架的帧缓冲区 349 CURRENT_FRAMEWORK 350 .write() 351 .as_ref() 352 .unwrap() 353 .change(buf_info)?; 354 // 遍历当前所有使用帧缓冲区的框架,更新为双缓冲区 355 for framework in SCM_FRAMEWORK_LIST.lock().iter_mut() { 356 if !(*framework).metadata()?.buf_info.is_double_buffer() { 357 let new_buf_info = 358 ScmBufferInfo::new(ScmBufferFlag::SCM_BF_DB | ScmBufferFlag::SCM_BF_PIXEL)?; 359 (*framework).change(new_buf_info)?; 360 } 361 } 362 // 通知显示驱动,启动双缓冲 363 video_refresh_manager().video_reinitialize(true)?; 364 365 return Ok(0); 366 } 367 368 /// 允许往窗口打印信息 369 pub fn scm_enable_put_to_window() { 370 // mm之前要继续往窗口打印信息时,因为没有动态内存分配(textui并没有往scm注册),且使用的是textui,要直接修改textui里面的值 371 if CURRENT_FRAMEWORK.read().is_none() { 372 textui_enable_put_to_window(); 373 } else { 374 let r = CURRENT_FRAMEWORK 375 .write() 376 .as_ref() 377 .unwrap() 378 .enable() 379 .unwrap_or_else(|e| e.to_posix_errno()); 380 if r.is_negative() { 381 send_to_default_serial8250_port("scm_enable_put_to_window() failed.\n\0".as_bytes()); 382 } 383 } 384 } 385 /// 禁止往窗口打印信息 386 pub fn scm_disable_put_to_window() { 387 // mm之前要停止往窗口打印信息时,因为没有动态内存分配(rwlock与otion依然能用,但是textui并没有往scm注册),且使用的是textui,要直接修改textui里面的值 388 if CURRENT_FRAMEWORK.read().is_none() { 389 textui_disable_put_to_window(); 390 assert!(!textui_is_enable_put_to_window()); 391 } else { 392 let r = CURRENT_FRAMEWORK 393 .write() 394 .as_ref() 395 .unwrap() 396 .disable() 397 .unwrap_or_else(|e| e.to_posix_errno()); 398 if r.is_negative() { 399 send_to_default_serial8250_port("scm_disable_put_to_window() failed.\n\0".as_bytes()); 400 } 401 } 402 } 403 /// 当内存管理单元被初始化之后,重新处理帧缓冲区问题 404 #[inline(never)] 405 pub fn scm_reinit() -> Result<(), SystemError> { 406 #[cfg(target_arch = "x86_64")] 407 { 408 let r = true_scm_reinit(); 409 if r.is_err() { 410 send_to_default_serial8250_port("scm reinit failed.\n\0".as_bytes()); 411 } 412 return r; 413 } 414 415 #[cfg(not(target_arch = "x86_64"))] 416 { 417 return Ok(()); 418 } 419 } 420 421 #[allow(dead_code)] 422 fn true_scm_reinit() -> Result<(), SystemError> { 423 video_refresh_manager() 424 .video_reinitialize(false) 425 .expect("video reinitialize failed"); 426 427 // 遍历当前所有使用帧缓冲区的框架,更新地址 428 let device_buffer = video_refresh_manager().device_buffer().clone(); 429 for framework in SCM_FRAMEWORK_LIST.lock().iter_mut() { 430 if framework.metadata()?.buf_info().is_device_buffer() { 431 framework.change(device_buffer.clone())?; 432 } 433 } 434 435 scm_enable_put_to_window(); 436 437 return Ok(()); 438 } 439