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