// // Copyright (C) <2026> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see . use ratatui::{Frame, Terminal, backend::TermionBackend}; use ratatui::{ layout::{Constraint, Layout}, style::{Color, Style, Stylize}, text::{Line, Span}, widgets::{Block, Borders, Gauge, List, ListItem, ListState, Padding, Paragraph, Wrap}, }; use ratatui_textarea::TextArea; use std::io::{self, stdout}; use std::process::ExitCode; use std::thread; use std::time::Duration; use termion::event::Key; use termion::input::TermRead; use termion::raw::IntoRawMode; mod nyan_system; use nyan_system::ExecCommandError; const BEE_CAT: &str = include_str!("bee_cat.txt"); const SNAP_CHOOSE_LIST_CAPTION: &str = "Select snapshot to rollback or \"bzz current\" to boot current system state"; const CONFIRM_TEXT1: &str = "You going to roll back system statate to "; const CONFIRM_TEXT2: &str = "This action cannot be undone!"; const TICK_TIME_MILLS: u64 = 27u64; const WAIT_FOR_F2_SEC: u64 = 3u64; //const ROOT_PARTLABEL: &str = "bee-root"; const ROOT_PARTLABEL: &str = "bee-root"; const TMP_ROOT: &str = "/mnt/bee-root"; const TMP_ROOT_SNAPS: &str = "/mnt/bee-root/bzz-snaps"; const SYS_INIT: &str = "/sbin/init"; const CURRENT_BOOT_LIST_TEXT: &str = "bzz current"; // fn bee_root_is_present() -> bool { // nyan_system::list_gpt_labeled_devs().iter().filter(|s| s.ends_with(ROOT_PARTLABEL)).count() > 0 // } // fn main() -> ExitCode { // println!("Looking for {}", ROOT_PARTLABEL); // if bee_root_is_present() { // println!("{} found!", ROOT_PARTLABEL); // } // else { // print!("Cannot find {}!", ROOT_PARTLABEL); // print!("Exiting..."); // return ExitCode::FAILURE; // } // // 1 get labels and see if there is bzzpss-root in them // ExitCode::SUCCESS // } // #[derive(Debug, PartialEq)] // struct RollbackState { // progress: f64, // progress_text: String, // snapshot_date_time: String, // roll_iter: nyan_system::RollBackIterator, // } // impl RollbackState { // // Constructor function // pub fn new(snaps_list: Vec, snap_date_time: String) -> Self { // RollbackState { // progress: 0.0, // progress_text: "".into(), // snapshot_date_time: snap_date_time.clone(), // roll_iter: nyan_system::RollBackIterator::new(snaps_list, snap_date_time) // } // } // } #[derive(Debug, PartialEq)] enum NyanitState { Init, RollBack, ConfirmRollback(String), WaitForF2, /// list of snapshoots ChooseSnapshot, EnterPassword, Error(String), HandOff, } /// /// Generates confirm dialog paragraph /// fn gen_conf_par<'a>(snap_dt: String) -> Paragraph<'a> { let first_line = Line::from(vec![Span::raw(CONFIRM_TEXT1), Span::raw(snap_dt).bold()]); let confirm_line = Line::from(vec![ Span::raw("Press ("), Span::raw("Y").bold(), Span::raw(") to confirm or ("), Span::raw("N").bold(), Span::raw(") to decline."), ]); let conf_lines: Vec = vec![ first_line, Line::default(), Line::from(CONFIRM_TEXT2).bold(), Line::default(), confirm_line, ]; Paragraph::new(conf_lines) .centered() .wrap(Wrap::default()) .light_red() } struct NyanitTUI<'a> { exit: bool, state: NyanitState, bee_root_dev: nyan_system::BlkIdRes, list_state: ListState, /// time counter manly for F2 waiting in mills time_counter: u64, /// time counter manly for F2 waiting in seconds time_counter_sec: u64, textarea: Option>, snaps_list: Vec, roll_state: Option, } impl NyanitTUI<'_> { pub fn new() -> io::Result { Ok(Self { exit: false, state: NyanitState::Init, bee_root_dev: nyan_system::BlkIdRes { fs_type: String::new(), dev_node: String::new(), }, list_state: ListState::default().with_selected(Some(0)), time_counter: 0, time_counter_sec: 0, textarea: None, snaps_list: Vec::new(), roll_state: None, }) } /// Mounting bee-root and chiking if there any snapshots fn mount_and_check_snaps(&mut self) -> Result { // mount bee-root nyan_system::mount_bee_root(&self.bee_root_dev, TMP_ROOT)?; // let root_list = nyan_system::list_dir(TMP_ROOT)?; // return Err(ExecCommandError::Other(root_list)); if self.bee_root_dev.is_bcachefs() { // list snaps if any self.snaps_list = nyan_system::list_bzzpss_snaps(TMP_ROOT_SNAPS)?; // if any snaps detected check hive DB update_status if self.snaps_list.len() > 0 { // if pac_lock accessible and exist - rolling back if let Ok(Some(snap_date_time)) = nyan_system::check_pac_lock() && self.snaps_list.contains(&snap_date_time) { Ok(NyanitState::ConfirmRollback(snap_date_time)) } // else user choose what to do else { Ok(NyanitState::WaitForF2) } } // else tell to finish boot else { Ok(NyanitState::HandOff) } } else { Ok(NyanitState::HandOff) } } fn init_stage(&mut self) -> Result { // mount sysfss nyan_system::prepare_env().map_err(|ex| format!("prepare_env error: {}", ex))?; // get bee-root device name aka /dev/sda1 // trying for max 3 sec self.bee_root_dev = nyan_system::try_find_partlabel(ROOT_PARTLABEL, 3) .ok_or_else(|| "Timed out trying to find dev by partlabel.".to_string())?; if self.bee_root_dev.is_bcachefs() { // check if device is encrypted if nyan_system::bzzpss_dev_encrypted(&self.bee_root_dev.dev_node) .map_err(|ex| format!("Error checking if device is encrypted: {}", ex))? { // if encrypted return EnterPassword so user get promted for pass return Ok(NyanitState::EnterPassword); } } // if unencrypted let check_res = self.mount_and_check_snaps()?; Ok(check_res) } /// runs the application's main loop until the user quits pub fn run(&mut self) -> io::Result<()> { self.state = match self.init_stage() { Ok(res) => res, Err(ex) => { NyanitState::Error(format!("Error while trying to bzzz-pss things:\n{}", ex)) } }; // if drive unencrypted and there is no root snapshots finish boot match &self.state { // if drive unencrypted and there is no root snapshots finish boot NyanitState::HandOff => { if let Err(ex) = nyan_system::hand_off_control(TMP_ROOT, SYS_INIT) { self.state = NyanitState::Error(ex.to_string()) } } // init password input NyanitState::EnterPassword => { let mut textarea: TextArea<'_> = TextArea::default(); textarea.set_cursor_line_style(Style::default()); textarea.set_mask_char('\u{1F41D}'); //U+2022 BULLET (•) textarea.set_placeholder_text("Please enter your disk unlock password"); textarea.set_style(Style::default().fg(Color::LightYellow)); textarea.set_block( Block::default() .borders(Borders::ALL) .title(" System disk unlock password "), ); self.textarea = Some(textarea); } _ => (), } // Init terminal // 1. Enable raw mode let stdout = stdout().into_raw_mode()?; // 2. Setup Terminal let backend = TermionBackend::new(stdout); let mut terminal = Terminal::new(backend)?; // init tty async input and start actually drawing things now! let mut tty_input_async = termion::async_stdin().keys(); self.time_counter = 0; while !self.exit { terminal.draw(|frame| self.draw(frame))?; self.handle_events(&mut tty_input_async)?; } Ok(()) } fn draw(&mut self, frame: &mut Frame) { let area = frame.area(); // 1. Create the outer block with borders let outer_block = Block::bordered() .title(Line::from(" BZZ-PSS ").centered()) .light_yellow(); // 2. Calculate the inner area excluding the borders let inner_area = outer_block.inner(area); // 3. Render the border block itself frame.render_widget(outer_block, area); // 1. Create vertical layout: Top (flexible), Center (fixed height), Bottom (flexible) let vertical_chunks = Layout::vertical([ Constraint::Length(7), // logo top part Constraint::Percentage(80), // Height of the paragraph block Constraint::Length(3), // footer ]) .split(inner_area); // 2. Create horizontal layout inside the center chunk: Left (flexible), Center (fixed width), Right (flexible) let horizontal_chunks = Layout::horizontal([ Constraint::Fill(2), Constraint::Length(11), Constraint::Fill(2), ]) .split(vertical_chunks[0]); // 3. Render the logo in the upper chunk let paragraph = Paragraph::new(BEE_CAT).left_aligned().light_yellow(); frame.render_widget(paragraph, horizontal_chunks[1]); // now check app state match &self.state { NyanitState::Error(ex) => { // render big red wolf in the center with err messaghe let err_paragraph = Paragraph::new(ex.as_str()) .centered() .wrap(Wrap::default()) .light_red() .bold(); frame.render_widget(err_paragraph, vertical_chunks[1]); } NyanitState::WaitForF2 => { // show press F2 for options text let f2_lines: Vec = vec![ Line::from("Press F2 for options"), Line::default(), Line::from((WAIT_FOR_F2_SEC.saturating_sub(self.time_counter)).to_string()), ]; let f2_paragraph = Paragraph::new(f2_lines).centered().magenta().bold(); frame.render_widget(f2_paragraph, vertical_chunks[1]); } NyanitState::ChooseSnapshot => { // 1. Split main chank to make space for description let snap_list_chunks = Layout::vertical([ Constraint::Length(2), // Description test Constraint::Fill(1), // to shrink unused space ]) .split(vertical_chunks[1]); let caption_paragraph = Paragraph::new(SNAP_CHOOSE_LIST_CAPTION) .centered() .wrap(Wrap::default()) .light_red() .bold(); frame.render_widget(caption_paragraph, snap_list_chunks[0]); // construct items list to get proper text size let mut list_items: Vec = vec![ListItem::new(CURRENT_BOOT_LIST_TEXT)]; self.snaps_list .iter() .for_each(|s| list_items.push(ListItem::new(s.as_str()))); let max_width = 2 + list_items.iter().map(|i| i.width()).max().unwrap_or(0) as u16; let render_list = List::new(list_items) .highlight_symbol(">>") .highlight_style(Style::new().bold().on_light_red()); frame.render_stateful_widget( render_list, snap_list_chunks[1].centered_horizontally(Constraint::Max(max_width)), &mut self.list_state, ); } NyanitState::ConfirmRollback(snap_dt) => { let par1 = gen_conf_par(snap_dt.clone()); frame.render_widget(par1, vertical_chunks[1]); } NyanitState::RollBack => { let centered = vertical_chunks[1].centered_vertically(Constraint::Length(9)); // 1. Create the outer block let block = Block::default() .padding(Padding::proportional(1)) .borders(Borders::ALL) .light_red() .title(" Rolling back system state "); // 2. Get the inner area of the block let block_inner_area = block.inner(centered); frame.render_widget(block, centered); // 3. Split the inner area into two parts: top for text, bottom for gauge let chunks = Layout::vertical([ Constraint::Length(3), // gauge Constraint::Length(1), // spacing Constraint::Length(1), // Height of the text paragraph ]) .split(block_inner_area); let gauge = Gauge::default() .gauge_style(Style::default().fg(Color::LightRed)) .ratio(self.roll_state.as_ref().unwrap().progress); frame.render_widget(gauge, chunks[0]); let text = Paragraph::new(self.roll_state.as_ref().unwrap().progress_text.clone()) .centered(); frame.render_widget(text, chunks[2]); } NyanitState::EnterPassword => { frame.render_widget( self.textarea.as_ref().unwrap(), vertical_chunks[1] .centered_vertically(Constraint::Max(3)) .centered_horizontally(Constraint::Percentage(75)), ); } NyanitState::HandOff => { let ok_text = Paragraph::new("Booting\nKira Linux\n\u{1F41D} \u{1F41D} :3") .centered() .light_green(); frame.render_widget( ok_text, vertical_chunks[1].centered_vertically(Constraint::Length(3)), ); // just some time to look at beez thread::sleep(Duration::from_millis(1000)) } _ => (), }; } fn handle_events( &mut self, tty_input: &mut termion::input::Keys, ) -> io::Result<()> { // cheking if there is any input to read if let Some(item) = tty_input.next() { let e = item?; match &self.state { // finishing boot // we allways booting to mnt rootnow NyanitState::HandOff => { if let Err(ex) = nyan_system::hand_off_control(TMP_ROOT, SYS_INIT) { self.state = NyanitState::Error(ex.to_string()) } } NyanitState::WaitForF2 => { if e == Key::F(2) { self.state = NyanitState::ChooseSnapshot; } } NyanitState::ChooseSnapshot => match e { Key::Down => self.list_state.select_next(), Key::Up => self.list_state.select_previous(), Key::Char('\n') => { if let Some(idx) = self.list_state.selected() { // if try to boot into current state if idx == 0 { self.state = NyanitState::HandOff; } // else we going to restore selected snapshoot as current state else { // idx-1 because self.snaps_list do not contains current system, only snapshots date time self.state = NyanitState::ConfirmRollback(self.snaps_list[idx - 1].clone()); } } } _ => (), }, NyanitState::EnterPassword => { match e { // try to unlock if enter pressed Key::Char('\n') => { let password = self.textarea.as_ref().unwrap().lines()[0].clone(); match nyan_system::bcachefs_unlock( password, &self.bee_root_dev.dev_node, ) { Ok(unlocked) => { if unlocked { // need to check for subvolumes and stuff self.state = match self.mount_and_check_snaps() { Ok(st) => { self.time_counter = 0; st } Err(ex) => NyanitState::Error(ex.to_string()), } } // ask to enter password again else { self.textarea .as_mut() .unwrap() .set_placeholder_text("Wrong password, try again"); self.textarea .as_mut() .unwrap() .set_style(Style::default().fg(Color::LightRed)); self.textarea.as_mut().unwrap().clear(); } } Err(ex) => { self.state = NyanitState::Error(ex.to_string()); } } } _ => { self.textarea .as_mut() .unwrap() .set_style(Style::default().fg(Color::LightYellow)); self.textarea.as_mut().unwrap().input(e); } } } NyanitState::ConfirmRollback(snap_dt) => match e { Key::Char('Y') | Key::Char('y') => { self.roll_state = Some(nyan_system::RollBackIterator::new( self.snaps_list.clone(), snap_dt.clone(), )); self.state = NyanitState::RollBack; } Key::Char(_) => self.state = NyanitState::ChooseSnapshot, _ => (), }, _ => (), } } else { // Tick time thread::sleep(Duration::from_millis(TICK_TIME_MILLS)); match self.state { NyanitState::WaitForF2 => { self.time_counter = self.time_counter.wrapping_add(TICK_TIME_MILLS); self.time_counter_sec = self.time_counter / 1000; // wait for F2 if self.time_counter_sec > WAIT_FOR_F2_SEC { // boot from root self.state = NyanitState::HandOff; } } NyanitState::RollBack => match self.roll_state.as_mut().unwrap().next() { Some(Err(ex)) => { self.state = NyanitState::Error(format!("ROLL BACK ERROR!: {}", ex)); } None => { self.state = NyanitState::HandOff; } _ => (), }, _ => (), } } Ok(()) } } fn main() -> ExitCode { // nyan_system::set_env_vars_unsafe(); let mut app = NyanitTUI::new().unwrap(); app.run().unwrap(); // Terminal restores automatically when `stdout` (RawTerminal) is dropped ExitCode::SUCCESS }