Huge refactor, quicksave

This commit is contained in:
kira committed 2026-09-17 21:54:20 +02:00
1 parent d2ddceb1a2
commit e4febb1e60
4 files changed
+571 -139

No files matched your search

+265 -104
View File
@@ -18,18 +18,19 @@ use ratatui::{Frame, Terminal, backend::TermionBackend};
use ratatui::{
layout::{Constraint, Layout},
style::{Color, Style, Stylize},
text::Line,
widgets::{Block, Borders, List, ListState, Paragraph},
text::{Line, Span},
widgets::{Block, Borders, Gauge, List, ListItem, ListState, Padding, Paragraph, Wrap},
};
use ratatui_textarea::TextArea;
use std::io::{self, Read, stdout};
use std::io::{self, stdout};
use std::process::ExitCode;
use std::thread;
use std::time::Duration;
use termion::event::{self, Event};
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
mod nyan_system;
@@ -37,15 +38,23 @@ 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_REAL_ROOT: &str = "/mnt/real-bee";
const TMP_REAL_ROOT_SNAPS: &str = "/mnt/real-bee/bzz-snaps";
const TMP_ROOT: &str = "/mnt/real-bee/bee-root";
const TMP_ROOT_SNAPS: &str = "/mnt/real-bee/bee-root/bzz-snaps";
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
// }
@@ -65,57 +74,57 @@ const SYS_INIT: &str = "/sbin/init";
// ExitCode::SUCCESS
// }
#[derive(Debug, PartialEq)]
struct RollbackState {
progress: f64,
progress_text: String,
snapshot_date_time: String,
}
impl RollbackState {
// Constructor function
pub fn new(snap_date_time: String) -> Self {
RollbackState {
progress: 0.0,
progress_text: "".into(),
snapshot_date_time: snap_date_time,
}
}
}
#[derive(Debug, PartialEq)]
enum NyanitState {
Init,
WaitForF2(Vec<String>),
ChooseSnapshot(Vec<String>),
RollBack(RollbackState),
ConfirmRollback(String),
WaitForF2,
/// list of snapshoots
ChooseSnapshot,
EnterPassword,
Error(String),
HandOff(String),
HandOff,
}
/// Mounting bee-root and chiking if there any snapshots
fn mount_and_check_snaps(bee_root_dev: &str) -> Result<NyanitState, ExecCommandError> {
// mount bee-root
nyan_system::mount_bee_root(bee_root_dev, TMP_REAL_ROOT)?;
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 root_list = nyan_system::list_dir(TMP_ROOT)?;
// return Err(ExecCommandError::Other(root_list));
// list snaps if any
let mut snaps_list = nyan_system::list_bzzpss_snaps(TMP_REAL_ROOT_SNAPS)?;
// if any snaps detected whait for user to press F2
if snaps_list.len() > 0 {
snaps_list.insert(0, TMP_ROOT.to_string());
return Ok(NyanitState::WaitForF2(snaps_list));
}
// else tell to finish boot
Ok(NyanitState::HandOff(TMP_ROOT.into()))
}
fn init_stage() -> Result<(String, NyanitState), ExecCommandError> {
// 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
let bee_root_dev = nyan_system::try_find_partlabel(ROOT_PARTLABEL, 3)
.ok_or_else(|| "Timed out trying to find dev by partlabel.".to_string())?;
// works until this point!!!!
// check if device is encrypted
if nyan_system::bzzpss_dev_encrypted(&bee_root_dev)
.map_err(|ex| format!("Error checking if device is encrypted: {}", ex))?
{
// if encrypted return EnterPassword so used get promted for pass
return Ok((bee_root_dev, NyanitState::EnterPassword));
}
// if unencrypted
let check_res = mount_and_check_snaps(&bee_root_dev)?;
Ok((bee_root_dev, check_res))
let conf_lines: Vec<Line> = 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> {
@@ -123,8 +132,12 @@ struct NyanitTUI<'a> {
state: NyanitState,
bee_root_dev: String,
list_state: ListState,
time_counter: u32,
/// 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<TextArea<'a>>,
snaps_list: Vec<String>,
}
impl NyanitTUI<'_> {
@@ -135,17 +148,70 @@ impl NyanitTUI<'_> {
bee_root_dev: String::new(),
list_state: ListState::default().with_selected(Some(0)),
time_counter: 0,
time_counter_sec: 0,
textarea: None,
snaps_list: Vec::new(),
})
}
/// Mounting bee-root and chiking if there any snapshots
fn mount_and_check_snaps(&mut self) -> Result<NyanitState, ExecCommandError> {
// 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));
// 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)
}
}
fn init_stage(&mut self) -> Result<NyanitState, ExecCommandError> {
// 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())?;
// works until this point!!!!
// check if device is encrypted
if nyan_system::bzzpss_dev_encrypted(&self.bee_root_dev)
.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 init_stage() {
Ok(res) => {
self.bee_root_dev = res.0;
res.1
}
self.state = match self.init_stage() {
Ok(res) => res,
Err(ex) => {
NyanitState::Error(format!("Error while trying to bzzz-pss things:\n{}", ex))
}
@@ -154,8 +220,8 @@ impl NyanitTUI<'_> {
// 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(root_mnt) => {
if let Err(ex) = nyan_system::hand_off_control(root_mnt, SYS_INIT) {
NyanitState::HandOff => {
if let Err(ex) = nyan_system::hand_off_control(TMP_ROOT, SYS_INIT) {
self.state = NyanitState::Error(ex.to_string())
}
}
@@ -164,9 +230,13 @@ impl NyanitTUI<'_> {
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 password");
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("Password"));
textarea.set_block(
Block::default()
.borders(Borders::ALL)
.title(" System disk unlock password "),
);
self.textarea = Some(textarea);
}
_ => (),
@@ -180,7 +250,7 @@ impl NyanitTUI<'_> {
let mut terminal = Terminal::new(backend)?;
// init tty async input and start actually drawing things now!
let mut tty_input_async = termion::async_stdin().bytes();
let mut tty_input_async = termion::async_stdin().keys();
self.time_counter = 0;
while !self.exit {
@@ -225,67 +295,150 @@ impl NyanitTUI<'_> {
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().light_red().bold();
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(_) => {
NyanitState::WaitForF2 => {
// show press F2 for options text
let f2_paragraph = Paragraph::new("Press F2 for options")
.centered()
.magenta()
.bold();
let f2_lines: Vec<Line> = 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(snaps_list) => {
// render menu for snap choosing
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<ListItem> = 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(
List::new(snaps_list.iter().map(String::as_str))
.block(Block::default().borders(Borders::ALL))
.highlight_symbol(">>")
.highlight_style(Style::new().bold()),
vertical_chunks[1],
render_list,
snap_list_chunks[1].centered_horizontally(Constraint::Max(max_width)),
&mut self.list_state,
);
}
NyanitState::EnterPassword => {
frame.render_widget(self.textarea.as_ref().unwrap(), vertical_chunks[1]);
NyanitState::ConfirmRollback(snap_dt) => {
let par1 = gen_conf_par(snap_dt.clone());
frame.render_widget(par1, vertical_chunks[1]);
}
NyanitState::HandOff(_) => {
let ok_text = Paragraph::new("Booting\nKira Linux\n \u{1F41D} \u{1F41D} :3")
.block(Block::bordered().light_green())
NyanitState::RollBack(roll_state) => {
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(roll_state.progress);
frame.render_widget(gauge, chunks[0]);
let text = Paragraph::new(roll_state.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]);
// just some time to look at message
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 io::Bytes<termion::AsyncReader>) -> io::Result<()> {
fn handle_events(
&mut self,
tty_input: &mut termion::input::Keys<termion::AsyncReader>,
) -> io::Result<()> {
// cheking if there is any input to read
if let Some(item) = tty_input.next() {
let read_byte = item?;
let e = item?;
let e = event::parse_event(read_byte, tty_input)?;
match &self.state {
// finishing boot
NyanitState::HandOff(root_mnt) => {
if let Err(ex) = nyan_system::hand_off_control(root_mnt, SYS_INIT) {
// 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(vol_list) => {
if e == Event::Key(event::Key::F(2)) {
self.state = NyanitState::ChooseSnapshot(vol_list.clone());
NyanitState::WaitForF2 => {
if e == Key::F(2) {
self.state = NyanitState::ChooseSnapshot;
}
}
NyanitState::ChooseSnapshot(vol_list) => match e {
Event::Key(event::Key::Down) => self.list_state.select_next(),
Event::Key(event::Key::Up) => self.list_state.select_previous(),
Event::Key(event::Key::Char('\n')) => {
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() {
self.state = NyanitState::HandOff(vol_list[idx].clone());
// 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());
}
}
}
_ => (),
@@ -293,14 +446,13 @@ impl NyanitTUI<'_> {
NyanitState::EnterPassword => {
match e {
// try to unlock if enter pressed
Event::Key(event::Key::Char('\n')) => {
Key::Char('\n') => {
let password = self.textarea.as_ref().unwrap().lines()[0].clone();
match nyan_system::bcachefs_unlock(password, &self.bee_root_dev) {
Ok(unlocked) => {
if unlocked {
// need to check for subvolumes and stuff
self.state = match mount_and_check_snaps(&self.bee_root_dev)
{
self.state = match self.mount_and_check_snaps() {
Ok(st) => {
self.time_counter = 0;
st
@@ -335,18 +487,27 @@ impl NyanitTUI<'_> {
}
}
}
NyanitState::ConfirmRollback(snap_dt) => match e {
Key::Char('Y') | Key::Char('y') => {
let roll_state = RollbackState::new(snap_dt.clone());
self.state = NyanitState::RollBack(roll_state);
}
Key::Char(_) => self.state = NyanitState::ChooseSnapshot,
_ => (),
},
_ => (),
}
} else {
// Tick time
thread::sleep(Duration::from_millis(500));
thread::sleep(Duration::from_millis(TICK_TIME_MILLS));
if let NyanitState::WaitForF2(_) = self.state {
self.time_counter = self.time_counter.wrapping_add(1u32);
// 2.5 sec wait
if self.time_counter > 5 {
if let NyanitState::WaitForF2 = self.state {
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(TMP_ROOT.into());
self.state = NyanitState::HandOff;
}
}
}