1*984a200eSGnoCiYeH use std::{io, sync::Arc}; 2*984a200eSGnoCiYeH 3*984a200eSGnoCiYeH use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; 4*984a200eSGnoCiYeH 5*984a200eSGnoCiYeH use crate::{ 6*984a200eSGnoCiYeH config::appconfig::AppSetting, 7*984a200eSGnoCiYeH utils::{file::FileManager, ui::uicore::Ui}, 8*984a200eSGnoCiYeH }; 9*984a200eSGnoCiYeH 10*984a200eSGnoCiYeH pub struct Application { 11*984a200eSGnoCiYeH file_manager: FileManager, 12*984a200eSGnoCiYeH bak: bool, 13*984a200eSGnoCiYeH ui: Arc<Ui>, 14*984a200eSGnoCiYeH } 15*984a200eSGnoCiYeH 16*984a200eSGnoCiYeH impl Application { 17*984a200eSGnoCiYeH pub fn new(file_path: Option<String>, setting: AppSetting) -> io::Result<Self> { 18*984a200eSGnoCiYeH let bak; 19*984a200eSGnoCiYeH let mut file = if file_path.is_some() { 20*984a200eSGnoCiYeH bak = true; 21*984a200eSGnoCiYeH FileManager::new(file_path.unwrap())? 22*984a200eSGnoCiYeH } else { 23*984a200eSGnoCiYeH bak = false; 24*984a200eSGnoCiYeH FileManager::new("held.tmp".to_string())? 25*984a200eSGnoCiYeH }; 26*984a200eSGnoCiYeH 27*984a200eSGnoCiYeH // 将文件数据读入buf 28*984a200eSGnoCiYeH let buf = file.init(bak)?; 29*984a200eSGnoCiYeH 30*984a200eSGnoCiYeH Ok(Self { 31*984a200eSGnoCiYeH file_manager: file, 32*984a200eSGnoCiYeH bak, 33*984a200eSGnoCiYeH ui: Ui::new(Arc::new(buf), setting), 34*984a200eSGnoCiYeH }) 35*984a200eSGnoCiYeH } 36*984a200eSGnoCiYeH 37*984a200eSGnoCiYeH fn init(&mut self) -> io::Result<()> { 38*984a200eSGnoCiYeH Ui::init_ui()?; 39*984a200eSGnoCiYeH 40*984a200eSGnoCiYeH if !self.bak { 41*984a200eSGnoCiYeH self.ui.start_page_ui()?; 42*984a200eSGnoCiYeH } 43*984a200eSGnoCiYeH 44*984a200eSGnoCiYeH Ok(()) 45*984a200eSGnoCiYeH } 46*984a200eSGnoCiYeH 47*984a200eSGnoCiYeH pub fn run(&mut self) -> io::Result<()> { 48*984a200eSGnoCiYeH enable_raw_mode()?; 49*984a200eSGnoCiYeH self.init()?; 50*984a200eSGnoCiYeH match self.ui.ui_loop() { 51*984a200eSGnoCiYeH Ok(store) => { 52*984a200eSGnoCiYeH if store { 53*984a200eSGnoCiYeH let buffer = &self.ui.core.lock().unwrap().buffer; 54*984a200eSGnoCiYeH self.file_manager.store(buffer)? 55*984a200eSGnoCiYeH } 56*984a200eSGnoCiYeH } 57*984a200eSGnoCiYeH Err(_) => { 58*984a200eSGnoCiYeH // 补救措施:恢复备份文件 59*984a200eSGnoCiYeH todo!() 60*984a200eSGnoCiYeH } 61*984a200eSGnoCiYeH } 62*984a200eSGnoCiYeH disable_raw_mode()?; 63*984a200eSGnoCiYeH Ok(()) 64*984a200eSGnoCiYeH } 65*984a200eSGnoCiYeH } 66