1984a200eSGnoCiYeH use std::{io, sync::Arc}; 2984a200eSGnoCiYeH 3984a200eSGnoCiYeH use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; 4984a200eSGnoCiYeH 5984a200eSGnoCiYeH use crate::{ 6984a200eSGnoCiYeH config::appconfig::AppSetting, 7984a200eSGnoCiYeH utils::{file::FileManager, ui::uicore::Ui}, 8984a200eSGnoCiYeH }; 9984a200eSGnoCiYeH 10984a200eSGnoCiYeH pub struct Application { 11984a200eSGnoCiYeH file_manager: FileManager, 12984a200eSGnoCiYeH bak: bool, 13984a200eSGnoCiYeH ui: Arc<Ui>, 14984a200eSGnoCiYeH } 15984a200eSGnoCiYeH 16984a200eSGnoCiYeH impl Application { new(file_path: Option<String>, setting: AppSetting) -> io::Result<Self>17984a200eSGnoCiYeH pub fn new(file_path: Option<String>, setting: AppSetting) -> io::Result<Self> { 18984a200eSGnoCiYeH let bak; 19984a200eSGnoCiYeH let mut file = if file_path.is_some() { 20984a200eSGnoCiYeH bak = true; 21984a200eSGnoCiYeH FileManager::new(file_path.unwrap())? 22984a200eSGnoCiYeH } else { 23984a200eSGnoCiYeH bak = false; 24984a200eSGnoCiYeH FileManager::new("held.tmp".to_string())? 25984a200eSGnoCiYeH }; 26984a200eSGnoCiYeH 27984a200eSGnoCiYeH // 将文件数据读入buf 28984a200eSGnoCiYeH let buf = file.init(bak)?; 29984a200eSGnoCiYeH 30984a200eSGnoCiYeH Ok(Self { 31984a200eSGnoCiYeH file_manager: file, 32984a200eSGnoCiYeH bak, 33984a200eSGnoCiYeH ui: Ui::new(Arc::new(buf), setting), 34984a200eSGnoCiYeH }) 35984a200eSGnoCiYeH } 36984a200eSGnoCiYeH init(&mut self) -> io::Result<()>37984a200eSGnoCiYeH fn init(&mut self) -> io::Result<()> { 38984a200eSGnoCiYeH Ui::init_ui()?; 39984a200eSGnoCiYeH 40984a200eSGnoCiYeH if !self.bak { 41984a200eSGnoCiYeH self.ui.start_page_ui()?; 42984a200eSGnoCiYeH } 43984a200eSGnoCiYeH 44984a200eSGnoCiYeH Ok(()) 45984a200eSGnoCiYeH } 46984a200eSGnoCiYeH run(&mut self) -> io::Result<()>47984a200eSGnoCiYeH pub fn run(&mut self) -> io::Result<()> { 48984a200eSGnoCiYeH enable_raw_mode()?; 49984a200eSGnoCiYeH self.init()?; 50984a200eSGnoCiYeH match self.ui.ui_loop() { 51984a200eSGnoCiYeH Ok(store) => { 52984a200eSGnoCiYeH if store { 53984a200eSGnoCiYeH let buffer = &self.ui.core.lock().unwrap().buffer; 54984a200eSGnoCiYeH self.file_manager.store(buffer)? 55*f192df42SWeihao Zhu } else if self.file_manager.is_first_open() { 56*f192df42SWeihao Zhu self.file_manager.delete_files()?; 57984a200eSGnoCiYeH } 58984a200eSGnoCiYeH } 59984a200eSGnoCiYeH Err(_) => { 60984a200eSGnoCiYeH // 补救措施:恢复备份文件 61984a200eSGnoCiYeH todo!() 62984a200eSGnoCiYeH } 63984a200eSGnoCiYeH } 64984a200eSGnoCiYeH disable_raw_mode()?; 65984a200eSGnoCiYeH Ok(()) 66984a200eSGnoCiYeH } 67984a200eSGnoCiYeH } 68