Compare commits

...

3 commits

Author SHA1 Message Date
e029e02cc2
Refactor footer text 2025-01-19 14:07:34 -08:00
a77bf0c9c6
Refactor left pane
Just use Strings instead of the various structs
2025-01-19 14:01:17 -08:00
3c0c12fa7a
Refactor right pane
Added DVLine struct to use instead of passing an Arc<Mutex>>.
This allows the right into pane to be agnostic of any app details.
2025-01-18 14:10:52 -08:00
8 changed files with 590 additions and 690 deletions

View file

@ -16,25 +16,21 @@
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
components::popup::Type,
state::Mode,
system::{
disk::{Disk, PartitionTableType},
drivers::Driver,
},
};
use crate::{components::popup::Type, line::DVLine, state::Mode, system::disk::Disk};
#[derive(Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
pub enum Action {
// App
Highlight(usize),
InstallDriver,
Process,
ScanDisks,
Select(Option<usize>, Option<usize>), // indicies for (source, dest) or (boot, os)
SelectDriver(Driver),
SelectTableType(PartitionTableType),
Select(Option<usize>, Option<usize>), // indicies for (source, dest) etc
SelectRight(Option<usize>, Option<usize>), // indicies for right info pane
UpdateDiskList(Vec<Disk>),
UpdateFooter(String),
UpdateLeft(String, Vec<String>, Vec<String>, bool), // (title, labels, items, select_one)
UpdateRight(Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>), // (labels, start_index, items) - items before start are always shown
// Screens
DismissPopup,
DisplayPopup(Type, String),

View file

@ -25,6 +25,7 @@ use crossterm::event::KeyEvent;
use ratatui::{
layout::{Constraint, Direction, Layout},
prelude::Rect,
style::Color,
};
use tokio::sync::mpsc;
use tracing::{debug, info};
@ -32,14 +33,15 @@ use tracing::{debug, info};
use crate::{
action::Action,
components::{
footer::Footer, fps::FpsCounter, left::Left, popup, right::Right, title::Title, Component,
footer::Footer, fps::FpsCounter, left::Left, popup, right::Right, state::StatefulList,
title::Title, Component,
},
config::Config,
line::{get_disk_description_right, get_part_description, DVLine},
state::{CloneSettings, Mode},
system::{
boot,
diskpart::build_dest_format_script,
drivers::{self},
boot, cpu::get_cpu_name, disk::PartitionTableType, diskpart::build_dest_format_script,
drivers,
},
tasks::{Task, Tasks},
tui::{Event, Tui},
@ -59,6 +61,7 @@ pub struct App {
// App
clone: CloneSettings,
cur_mode: Mode,
list: StatefulList<usize>,
prev_mode: Mode,
selections: Vec<Option<usize>>,
tasks: Tasks,
@ -91,50 +94,50 @@ impl App {
// App
clone: CloneSettings::new(disk_list_arc),
cur_mode: Mode::ScanDisks,
list: StatefulList::default(),
prev_mode: Mode::ScanDisks,
selections: vec![None, None],
tasks,
})
}
pub fn next_mode(&mut self) -> (Option<Mode>, Option<Mode>) {
let new_mode = match (self.prev_mode, self.cur_mode) {
(_, Mode::InstallDrivers) => Mode::ScanDisks,
(_, Mode::ScanDisks) => Mode::SelectDisks,
(_, Mode::SelectDisks | Mode::SelectTableType | Mode::SelectParts) => {
if self.selections[1].is_some() {
Mode::Confirm
} else {
self.cur_mode
}
}
(Mode::SelectDisks, Mode::Confirm) => Mode::SelectTableType,
(Mode::SelectTableType, Mode::Confirm) => Mode::PreClone,
(_, Mode::PreClone) => Mode::Clone,
(_, Mode::Clone) => Mode::SelectParts,
(Mode::SelectParts, Mode::Confirm) => Mode::PostClone,
(_, Mode::PostClone | Mode::Done) => Mode::Done,
(_, Mode::Failed) => Mode::Failed,
// Invalid states
(_, Mode::Confirm) => panic!("This shouldn't happen."),
pub fn prev_mode(&mut self) -> Option<Mode> {
let new_mode = match self.cur_mode {
Mode::Failed => Some(Mode::Failed),
Mode::Done => Some(Mode::Done),
Mode::SelectParts => Some(Mode::SelectParts),
Mode::Confirm => Some(Mode::SelectTableType),
Mode::SelectTableType => Some(Mode::SelectDisks),
Mode::SelectDisks => Some(Mode::ScanDisks),
//
Mode::InstallDrivers
| Mode::ScanDisks
| Mode::PreClone
| Mode::Clone
| Mode::PostClone => None,
};
new_mode
}
let prev_mode = {
match self.cur_mode {
Mode::Confirm => Some(self.prev_mode),
Mode::PreClone | Mode::Clone | Mode::PostClone | Mode::Done => {
// Override since we're past the point of no return
Some(self.cur_mode)
}
_ => Some(self.cur_mode),
}
pub fn next_mode(&mut self) -> Option<Mode> {
let new_mode = match self.cur_mode {
Mode::InstallDrivers => Mode::ScanDisks,
Mode::ScanDisks => Mode::SelectDisks,
Mode::SelectDisks => Mode::SelectTableType,
Mode::SelectTableType => Mode::Confirm,
Mode::Confirm => Mode::PreClone,
Mode::PreClone => Mode::Clone,
Mode::Clone => Mode::SelectParts,
Mode::SelectParts => Mode::PostClone,
Mode::PostClone | Mode::Done => Mode::Done,
Mode::Failed => Mode::Failed,
};
if new_mode == self.cur_mode {
// No mode change needed
(None, None)
None
} else {
(prev_mode, Some(new_mode))
Some(new_mode)
}
}
@ -142,6 +145,7 @@ impl App {
info!("Setting mode to {new_mode:?}");
self.cur_mode = new_mode;
match new_mode {
Mode::InstallDrivers => self.clone.scan_drivers(),
Mode::ScanDisks => {
self.prev_mode = self.cur_mode;
if self.tasks.idle() {
@ -344,6 +348,8 @@ impl App {
Action::Suspend => self.should_suspend = true,
Action::Resume => self.should_suspend = false,
Action::ClearScreen => tui.terminal.clear()?,
Action::KeyUp => self.list.previous(),
Action::KeyDown => self.list.next(),
Action::Error(ref msg) => {
self.action_tx
.send(Action::DisplayPopup(popup::Type::Error, msg.clone()))?;
@ -352,37 +358,41 @@ impl App {
Action::InstallDriver => {
self.action_tx.send(Action::SetMode(Mode::InstallDrivers))?;
}
Action::SelectDriver(ref driver) => {
self.clone.driver = Some(driver.clone());
drivers::load(&driver.inf_paths);
self.action_tx.send(Action::NextScreen)?;
}
Action::SelectTableType(ref table_type) => {
self.clone.table_type = Some(table_type.clone());
self.action_tx.send(Action::NextScreen)?;
}
Action::Process => match self.cur_mode {
Mode::Confirm => {
self.action_tx.send(Action::NextScreen)?;
}
_ => {}
},
Action::Resize(w, h) => self.handle_resize(tui, w, h)?,
Action::Render => self.render(tui)?,
Action::PrevScreen => {
let new_mode = match (self.prev_mode, self.cur_mode) {
(Mode::SelectTableType, Mode::SelectTableType) => Mode::SelectDisks,
(_, _) => self.prev_mode,
};
self.action_tx.send(Action::SetMode(new_mode))?;
if let Some(new_mode) = self.prev_mode() {
self.prev_mode = new_mode;
self.cur_mode = new_mode;
self.action_tx.send(Action::SetMode(new_mode))?;
}
}
Action::NextScreen => match self.next_mode() {
(None, None) => {}
(Some(prev), Some(next)) => {
self.prev_mode = prev;
None => {}
Some(next) => {
self.prev_mode = self.cur_mode;
self.cur_mode = next;
self.action_tx.send(Action::DismissPopup)?;
self.action_tx.send(Action::SetMode(next))?;
}
_ => panic!("Failed to determine next mode"),
},
Action::ScanDisks => self.action_tx.send(Action::SetMode(Mode::ScanDisks))?,
Action::Select(one, two) => {
match self.cur_mode {
Mode::InstallDrivers => {
if let Some(index) = one {
if let Some(driver) = self.clone.driver_list.get(index).cloned() {
drivers::load(&driver.inf_paths);
self.clone.driver = Some(driver);
}
}
}
Mode::SelectDisks => {
self.clone.disk_index_source = one;
self.clone.disk_index_dest = two;
@ -391,12 +401,65 @@ impl App {
self.clone.part_index_boot = one;
self.clone.part_index_os = two;
}
Mode::SelectTableType => {
self.clone.table_type = {
if let Some(index) = one {
match index {
0 => Some(PartitionTableType::Guid),
1 => Some(PartitionTableType::Legacy),
index => {
panic!("Failed to select PartitionTableType: {}", index)
}
}
} else {
None
}
}
}
_ => {}
}
self.selections[0] = one;
self.selections[1] = two;
}
Action::SetMode(new_mode) => self.set_mode(new_mode)?,
Action::SetMode(new_mode) => {
self.set_mode(new_mode)?;
self.action_tx
.send(Action::UpdateFooter(build_footer_string(self.cur_mode)))?;
let (title, labels, items, select_one) = build_left_items(self, self.cur_mode);
self.action_tx
.send(Action::UpdateLeft(title, labels, items, select_one))?;
let (labels, start, items) = build_right_items(self, self.cur_mode);
self.action_tx
.send(Action::UpdateRight(labels, start, items))?;
match new_mode {
// Mode::InstallDrivers | Mode::SelectDisks => {
// self.action_tx.send(Action::Select(None, None))?
// }
Mode::SelectTableType | Mode::Confirm => {
// Select source/dest disks
self.action_tx.send(Action::SelectRight(
self.clone.disk_index_source,
self.clone.disk_index_dest,
))?;
}
Mode::SelectParts => {
// Select first partition as boot partition
self.action_tx.send(Action::Select(Some(0), None))?;
// Highlight 2nd or 3rd partition as OS partition
let index = if let Some(table_type) = &self.clone.table_type {
match table_type {
PartitionTableType::Guid => 2,
PartitionTableType::Legacy => 1,
}
} else {
1
};
self.action_tx.send(Action::Highlight(index))?;
}
_ => {}
};
}
_ => {}
}
for component in &mut self.components {
@ -488,3 +551,146 @@ fn get_chunks(r: Rect) -> Vec<Rect> {
// Done
chunks
}
fn build_footer_string(cur_mode: Mode) -> String {
match cur_mode {
Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => {
String::from("(q) to quit")
}
Mode::SelectParts => String::from("(Enter) to select / (s) to start over / (q) to quit"),
Mode::SelectDisks => String::from(
"(Enter) to select / / (i) to install driver / (r) to rescan / (q) to quit",
),
Mode::SelectTableType => String::from("(Enter) to select / (b) to go back / (q) to quit"),
Mode::Confirm => String::from("(Enter) to confirm / (b) to go back / (q) to quit"),
Mode::Done | Mode::Failed | Mode::InstallDrivers => String::from("(Enter) or (q) to quit"),
}
}
fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<String>, bool) {
let title: String;
let mut items = Vec::new();
let mut labels: Vec<String> = Vec::new();
let mut select_one = false;
match cur_mode {
Mode::InstallDrivers => {
title = String::from("Install Drivers");
select_one = true;
app.clone
.driver_list
.iter()
.for_each(|driver| items.push(driver.to_string()));
}
Mode::SelectDisks => {
title = String::from("Select Source and Destination Disks");
labels.push(String::from("source"));
labels.push(String::from("dest"));
let disk_list = app.clone.disk_list.lock().unwrap();
disk_list
.iter()
.for_each(|disk| items.push(disk.description.to_string()));
}
Mode::SelectTableType => {
title = String::from("Select Partition Table Type");
select_one = true;
items.push(format!("{}", PartitionTableType::Guid));
items.push(format!("{}", PartitionTableType::Legacy));
}
Mode::Confirm => {
title = String::from("Confirm Selections");
}
Mode::PreClone | Mode::Clone | Mode::PostClone | Mode::ScanDisks => {
title = String::from("Processing");
}
Mode::SelectParts => {
title = String::from("Select Boot and OS Partitions");
labels.push(String::from("boot"));
labels.push(String::from("os"));
let disk_list = app.clone.disk_list.lock().unwrap();
if let Some(index) = app.clone.disk_index_dest {
if let Some(disk) = disk_list.get(index) {
disk.get_parts().iter().for_each(|part| {
items.push(part.to_string());
});
}
}
}
Mode::Done | Mode::Failed => title = String::from("Done"),
};
(title, labels, items, select_one)
}
fn build_right_items(app: &App, cur_mode: Mode) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) {
let mut items = Vec::new();
let mut labels: Vec<Vec<DVLine>> = Vec::new();
let mut start_index = 0;
match cur_mode {
Mode::InstallDrivers => {
items.push(vec![DVLine {
line_parts: vec![String::from("CPU")],
line_colors: vec![Color::Cyan],
}]);
items.push(vec![DVLine {
line_parts: vec![get_cpu_name()],
line_colors: vec![Color::Reset],
}]);
start_index = 2;
}
Mode::SelectDisks | Mode::SelectTableType | Mode::Confirm => {
// Labels
labels.push(vec![DVLine {
line_parts: vec![String::from("Source")],
line_colors: vec![Color::Cyan],
}]);
let dest_dv_line = DVLine {
line_parts: vec![
String::from("Dest"),
String::from(" (WARNING: ALL DATA WILL BE DELETED!)"),
],
line_colors: vec![Color::Cyan, Color::Red],
};
if let Some(table_type) = &app.clone.table_type {
// Show table type
let type_str = match table_type {
PartitionTableType::Guid => "GPT",
PartitionTableType::Legacy => "MBR",
};
labels.push(vec![
dest_dv_line,
DVLine {
line_parts: vec![format!(" (Will be formatted {type_str})")],
line_colors: vec![Color::Yellow],
},
]);
} else {
labels.push(vec![dest_dv_line]);
}
let disk_list = app.clone.disk_list.lock().unwrap();
disk_list
.iter()
.for_each(|disk| items.push(get_disk_description_right(&disk)));
}
Mode::SelectParts => {
vec!["Boot", "OS"].iter().for_each(|s| {
labels.push(vec![DVLine {
line_parts: vec![String::from(*s)],
line_colors: vec![Color::Cyan],
}])
});
if let Some(index) = app.clone.disk_index_dest {
start_index = 1;
let disk_list = app.clone.disk_list.lock().unwrap();
if let Some(disk) = disk_list.get(index) {
// Disk Details
items.push(get_disk_description_right(&disk));
// Partition Details
disk.parts
.iter()
.for_each(|part| items.push(get_part_description(&part)));
}
}
}
_ => {}
}
(labels, start_index, items)
}

View file

@ -51,25 +51,9 @@ impl Component for Footer {
}
fn update(&mut self, action: Action) -> Result<Option<Action>> {
if let Action::SetMode(new_mode) = action {
self.text = match new_mode {
Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => {
String::from("(q) to quit")
}
Mode::SelectParts => {
String::from("(Enter) to select / (s) to start over / (q) to quit")
}
Mode::SelectDisks => String::from(
"(Enter) to select / / (i) to install driver / (r) to rescan / (q) to quit",
),
Mode::SelectTableType => {
String::from("(Enter) to select / (b) to go back / (q) to quit")
}
Mode::Confirm => String::from("(Enter) to confirm / (b) to go back / (q) to quit"),
Mode::Done | Mode::Failed | Mode::InstallDrivers => {
String::from("(Enter) or (q) to quit")
}
}
match action {
Action::UpdateFooter(text) => self.text = text,
_ => {}
}
Ok(None)
}

View file

@ -20,42 +20,37 @@ use ratatui::{
widgets::{Block, Borders, HighlightSpacing, List, ListItem, Padding, Paragraph},
};
use tokio::sync::mpsc::UnboundedSender;
use tracing::info;
use super::{popup, state::StatefulList, Component};
use crate::{
action::Action,
config::Config,
state::Mode,
system::{
disk::{Disk, Partition, PartitionTableType},
drivers::{self, Driver},
},
};
use super::{state::StatefulList, Component};
use crate::{action::Action, config::Config};
#[derive(Default)]
pub struct Left {
command_tx: Option<UnboundedSender<Action>>,
config: Config,
disk_id_dest: Option<usize>,
table_type: Option<PartitionTableType>,
title_text: String,
list_disks: StatefulList<Disk>,
list_drivers: StatefulList<Driver>,
list_parts: StatefulList<Partition>,
list_table_types: StatefulList<PartitionTableType>,
mode: Mode,
labels: Vec<String>,
list: StatefulList<String>,
select_one: bool,
selections: Vec<Option<usize>>,
selections_saved: Vec<Option<usize>>,
title_text: String,
}
impl Left {
pub fn new() -> Self {
Self {
select_one: false,
labels: vec![String::from("one"), String::from("two")],
selections: vec![None, None],
selections_saved: vec![None, None],
title_text: String::from("Home"),
..Default::default()
}
}
fn set_highlight(&mut self, index: usize) {
self.list.select(index);
}
}
impl Component for Left {
@ -76,180 +71,58 @@ impl Component for Left {
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::KeyUp => match self.mode {
Mode::InstallDrivers => self.list_drivers.previous(),
Mode::SelectDisks => self.list_disks.previous(),
Mode::SelectTableType => self.list_table_types.previous(),
Mode::SelectParts => self.list_parts.previous(),
_ => {}
},
Action::KeyDown => match self.mode {
Mode::InstallDrivers => self.list_drivers.next(),
Mode::SelectDisks => self.list_disks.next(),
Mode::SelectTableType => self.list_table_types.next(),
Mode::SelectParts => self.list_parts.next(),
_ => {}
},
Action::Process => match self.mode {
// NOTE: Remove all variants except Mode::Confirm?
Mode::Confirm => {
if let Some(command_tx) = self.command_tx.clone() {
command_tx.send(Action::NextScreen)?;
}
}
Mode::InstallDrivers
| Mode::SelectDisks
| Mode::SelectTableType
| Mode::SelectParts => {
// Menu selection sections
let selection: Option<usize> = match self.mode {
Mode::InstallDrivers => self.list_drivers.selected(),
Mode::SelectDisks => self.list_disks.selected(),
Mode::SelectTableType => self.list_table_types.selected(),
Mode::SelectParts => self.list_parts.selected(),
_ => panic!("This shouldn't happen!"),
};
if let Some(index) = selection {
if let Some(command_tx) = self.command_tx.clone() {
let mut selection_one: Option<usize> = None;
let mut selection_two: Option<usize> = None;
// Get selection(s)
if self.selections[0].is_none() {
// First selection
selection_one = Some(index);
selection_two = None;
} else {
// Second selection
if let Some(source_index) = self.selections[0] {
if index == source_index {
// Toggle first selection
selection_one = None;
self.selections[0] = None;
} else {
selection_one = self.selections[0];
selection_two = Some(index);
}
Action::Highlight(index) => self.set_highlight(index),
Action::KeyUp => self.list.previous(),
Action::KeyDown => self.list.next(),
Action::Process => {
if let Some(command_tx) = self.command_tx.clone() {
match (self.selections[0], self.selections[1]) {
(None, None) => {
// Making first selection
command_tx.send(Action::Select(self.list.selected(), None))?;
if self.select_one {
// Confirm selection
command_tx.send(Action::NextScreen)?;
}
}
(Some(first_index), None) => {
if let Some(second_index) = self.list.selected() {
// Making second selection
if first_index == second_index {
// Toggle first selection
command_tx.send(Action::Select(None, None))?;
} else {
// Both selections made, proceed to next screen
command_tx.send(Action::Select(
Some(first_index),
Some(second_index),
))?;
command_tx.send(Action::NextScreen)?;
}
}
// Send selection(s) if needed
// NOTE: This is needed to keep the app and all components in sync
match self.mode {
Mode::InstallDrivers => {
// Only need to select one entry
if let Some(driver) = self.list_drivers.get_selected() {
command_tx.send(Action::SelectDriver(driver.clone()))?;
}
}
Mode::SelectTableType => {
// Only need to select one entry
if let Some(table_type) = self.list_table_types.get_selected() {
self.table_type = Some(table_type.clone());
command_tx.send(Action::SelectTableType(table_type))?;
}
}
Mode::SelectDisks | Mode::SelectParts => {
command_tx
.send(Action::Select(selection_one, selection_two))?;
// Advance screen if both selections made
if selection_two.is_some() {
command_tx.send(Action::NextScreen)?;
}
}
_ => {}
};
}
_ => panic!("This shouldn't happen?"),
}
}
_ => {}
},
Action::Select(Some(index), None) => self.selections[0] = Some(index),
Action::Select(_, Some(index)) => {
if self.mode == Mode::SelectDisks {
self.disk_id_dest = Some(index);
}
}
Action::SetMode(new_mode) => {
let prev_mode = self.mode;
self.mode = new_mode;
match (prev_mode, new_mode) {
(_, Mode::ScanDisks) => {
self.list_disks.clear_items();
self.title_text = String::new();
}
(_, Mode::InstallDrivers) => {
self.list_drivers.set_items(drivers::scan());
self.selections[0] = None;
self.selections[1] = None;
self.title_text = String::from("Install Drivers");
if self.list_drivers.is_empty() {
if let Some(command_tx) = self.command_tx.clone() {
command_tx.send(Action::DisplayPopup(
popup::Type::Error,
String::from("No drivers available to install"),
))?;
}
}
}
(_, Mode::SelectDisks) => {
self.selections[0] = None;
self.selections[1] = None;
self.title_text = String::from("Select Source and Destination Disks");
}
(_, Mode::SelectTableType) => {
self.list_table_types
.set_items(vec![PartitionTableType::Guid, PartitionTableType::Legacy]);
self.selections[0] = None;
self.selections[1] = None;
self.title_text = String::from("Select Partition Table Type");
}
(_, Mode::PreClone | Mode::Clone | Mode::PostClone) => {
self.title_text = String::from("Processing");
}
(_, Mode::SelectParts) => {
self.title_text = String::from("Select Boot and OS Partitions");
}
(Mode::SelectDisks | Mode::SelectParts, Mode::Confirm) => {
self.title_text = String::from("Confirm Selections");
}
(Mode::SelectTableType, Mode::Confirm) => {
self.title_text = String::from("Confirm Selections (Again)");
}
(_, Mode::Done | Mode::Failed) => self.title_text = String::from("Done"),
// Invalid states
(_, Mode::Confirm) => panic!("This shouldn't happen."),
}
Action::Select(one, two) => {
self.selections[0] = one;
self.selections[1] = two;
self.selections_saved[0] = one;
self.selections_saved[1] = two;
}
Action::UpdateDiskList(disks) => {
info!("Updating disk list");
self.list_disks.set_items(disks);
if self.mode == Mode::Clone {
if let Some(index) = self.disk_id_dest {
if let Some(disk) = self.list_disks.get(index) {
self.list_parts.set_items(disk.get_parts());
// Auto-select first partition and highlight likely OS partition
if let Some(table_type) = &self.table_type {
match table_type {
PartitionTableType::Guid => {
if disk.num_parts() >= 3 {
self.selections[0] = Some(0);
self.list_parts.select(2);
}
}
PartitionTableType::Legacy => {
if disk.num_parts() >= 2 {
self.selections[0] = Some(0);
self.list_parts.select(1);
}
}
}
}
}
}
}
Action::SetMode(_) => {
self.selections[0] = None;
self.selections[1] = None;
}
Action::UpdateLeft(title, labels, items, select_one) => {
self.title_text = title;
self.labels = labels
.iter()
.map(|label| format!(" ~{}~", label.to_lowercase()))
.collect();
self.list.set_items(items);
self.select_one = select_one;
}
_ => {}
}
@ -263,126 +136,70 @@ impl Component for Left {
.areas(area);
// Title
let title_text = if self.selections[1].is_some() || self.select_one {
"Confirm Selections"
} else {
self.title_text.as_str()
};
let title =
Paragraph::new(Line::from(Span::styled(&self.title_text, Style::default())).centered())
Paragraph::new(Line::from(Span::styled(title_text, Style::default())).centered())
.block(Block::default().borders(Borders::NONE));
frame.render_widget(title, title_area);
// Body
match self.mode {
Mode::ScanDisks
| Mode::PreClone
| Mode::Clone
| Mode::PostClone
| Mode::Done
| Mode::Failed => {
// Leave blank
let paragraph = Paragraph::new(String::new()).block(
Block::default()
.borders(Borders::ALL)
.padding(Padding::new(1, 1, 1, 1)),
);
frame.render_widget(paragraph, body_area);
// Body (Blank)
if self.list.is_empty() {
// Leave blank
let paragraph = Paragraph::new(String::new()).block(
Block::default()
.borders(Borders::ALL)
.padding(Padding::new(1, 1, 1, 1)),
);
frame.render_widget(paragraph, body_area);
// Bail early
return Ok(());
}
Mode::Confirm => {
// Nag the user
let paragraph = Paragraph::new(String::from("Are the listed selections correct?"))
.block(
Block::default()
.borders(Borders::ALL)
.padding(Padding::new(1, 1, 1, 1)),
);
frame.render_widget(paragraph, body_area);
// Bail early
return Ok(());
}
Mode::InstallDrivers
| Mode::SelectDisks
| Mode::SelectTableType
| Mode::SelectParts => {
// List modes
let mut list_items = Vec::<ListItem>::new();
let list_items_strings: Vec<String> = match self.mode {
Mode::InstallDrivers => self
.list_drivers
.items
.iter()
.map(|i| format!("{i}"))
.collect(),
Mode::SelectDisks => self
.list_disks
.items
.iter()
.map(|i| format!("{i}"))
.collect(),
Mode::SelectTableType => self
.list_table_types
.items
.iter()
.map(|i| format!("{i}"))
.collect(),
Mode::SelectParts => self
.list_parts
.items
.iter()
.map(|i| format!("{i}"))
.collect(),
_ => panic!("This shouldn't happen."),
};
if !list_items_strings.is_empty() {
for (index, item) in list_items_strings.iter().enumerate() {
let mut item_style = Style::default();
let mut item_text_tail = "";
if let Some(selection_one) = self.selections[0] {
if selection_one == index {
item_style = Style::new().yellow();
item_text_tail = match self.mode {
Mode::SelectDisks => " ~source disk~",
Mode::SelectParts => " ~boot volume~",
_ => "",
}
}
}
list_items.push(
ListItem::new(format!(" {item}\n{item_text_tail}\n\n"))
.style(item_style),
);
}
}
let list = List::new(list_items)
.block(
Block::default()
.borders(Borders::ALL)
.padding(Padding::new(1, 1, 1, 1)),
)
.highlight_spacing(HighlightSpacing::Always)
.highlight_style(Style::new().green().bold())
.highlight_symbol(" --> ")
.repeat_highlight_symbol(false);
match self.mode {
Mode::InstallDrivers => {
frame.render_stateful_widget(list, body_area, &mut self.list_drivers.state);
}
Mode::SelectDisks => {
frame.render_stateful_widget(list, body_area, &mut self.list_disks.state);
}
Mode::SelectTableType => frame.render_stateful_widget(
list,
body_area,
&mut self.list_table_types.state,
),
Mode::SelectParts => {
frame.render_stateful_widget(list, body_area, &mut self.list_parts.state);
}
_ => panic!("This shouldn't happen."),
}
}
// Bail early
return Ok(());
}
// Body
let list_items: Vec<ListItem> = self
.list
.items
.iter()
.enumerate()
.map(|(index, item)| {
let mut style = Style::default();
let text = if self.selections[0].is_some_and(|first_index| first_index == index) {
if let Some(label) = self.labels.get(0) {
style = style.yellow();
label.as_str()
} else {
""
}
} else if self.selections[1].is_some_and(|second_index| second_index == index) {
if let Some(label) = self.labels.get(1) {
style = style.yellow();
label.as_str()
} else {
""
}
} else {
""
};
ListItem::new(format!(" {item}\n{text}\n\n")).style(style)
})
.collect();
let list = List::new(list_items)
.block(
Block::default()
.borders(Borders::ALL)
.padding(Padding::new(1, 1, 1, 1)),
)
.highlight_spacing(HighlightSpacing::Always)
.highlight_style(Style::new().green().bold())
.highlight_symbol(" --> ")
.repeat_highlight_symbol(false);
frame.render_stateful_widget(list, body_area, &mut self.list.state);
// Done
Ok(())
}

View file

@ -20,40 +20,57 @@ use ratatui::{
widgets::{Block, Borders, Padding, Paragraph, Wrap},
};
use tokio::sync::mpsc::UnboundedSender;
use tracing::info;
use super::{state::StatefulList, Component};
use crate::{
action::Action,
config::Config,
state::Mode,
system::{
cpu::get_cpu_name,
disk::{Disk, Partition, PartitionTableType},
},
};
use crate::{action::Action, config::Config, line::DVLine};
#[derive(Default)]
pub struct Right {
command_tx: Option<UnboundedSender<Action>>,
config: Config,
cur_mode: Mode,
list_disks: StatefulList<Disk>,
list_parts: StatefulList<Partition>,
prev_mode: Mode,
selected_disks: Vec<Option<usize>>,
list_header: Vec<DVLine>,
list_labels: Vec<Vec<DVLine>>,
list: StatefulList<Vec<DVLine>>,
selections: Vec<Option<usize>>,
table_type: Option<PartitionTableType>,
selections_saved: Vec<Option<usize>>,
title: String,
}
impl Right {
pub fn new() -> Self {
Self {
selected_disks: vec![None, None],
selections: vec![None, None],
selections_saved: vec![None, None],
title: String::from("Info"),
..Default::default()
}
}
fn get_first(&self) -> Option<usize> {
if self.selections_saved[0].is_some() {
self.selections_saved[0]
} else if self.selections[0].is_some() {
self.selections[0]
} else {
self.list.selected()
}
}
fn get_second(&self) -> Option<usize> {
if self.selections_saved[1].is_some() {
self.selections_saved[1]
} else if self.selections[1].is_some() {
self.selections[1]
} else if self.selections[0].is_some() && self.selections[0] != self.list.selected() {
self.list.selected()
} else {
None
}
}
fn set_highlight(&mut self, index: usize) {
self.list.select(index);
}
}
impl Component for Right {
@ -74,80 +91,33 @@ impl Component for Right {
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::KeyUp => match self.cur_mode {
Mode::SelectDisks => self.list_disks.previous(),
Mode::SelectParts => self.list_parts.previous(),
_ => {}
},
Action::KeyDown => match self.cur_mode {
Mode::SelectDisks => self.list_disks.next(),
Mode::SelectParts => self.list_parts.next(),
_ => {}
},
Action::Process => {
if self.prev_mode == Mode::SelectDisks && self.cur_mode == Mode::Confirm {
self.selected_disks = self.selections.clone();
}
}
Action::Highlight(index) => self.set_highlight(index),
Action::KeyUp => self.list.previous(),
Action::KeyDown => self.list.next(),
Action::Select(one, two) => {
self.selections[0] = one;
self.selections[1] = two;
}
Action::SelectTableType(table_type) => self.table_type = Some(table_type),
Action::SetMode(new_mode) => {
self.prev_mode = self.cur_mode;
self.cur_mode = new_mode;
match self.cur_mode {
Mode::SelectDisks => {
self.selections[0] = None;
self.selections[1] = None;
self.selected_disks[0] = None;
self.selected_disks[1] = None;
}
Mode::SelectParts => {
self.selections[0] = None;
self.selections[1] = None;
}
Mode::SelectTableType => {
self.selections[0] = None;
self.selections[1] = None;
self.table_type = None;
}
_ => {}
if self.selections_saved[1].is_none() {
// Update selections_saved
// Conversely, if both selections set then preserve previous choices
self.selections_saved[0] = one;
self.selections_saved[1] = two;
}
}
Action::UpdateDiskList(disks) => {
info!("Updating disk list");
self.list_disks.set_items(disks);
if self.cur_mode == Mode::Clone {
if let Some(index) = self.selected_disks[1] {
if let Some(disk) = self.list_disks.get(index) {
self.list_parts.set_items(disk.get_parts());
// Auto-select first partition and highlight likely OS partition
if let Some(index) = self.selected_disks[1] {
if let Some(disk) = self.list_disks.get(index) {
if let Some(table_type) = &self.table_type {
match table_type {
PartitionTableType::Guid => {
if disk.num_parts() >= 3 {
self.selections[0] = Some(0);
self.list_parts.select(2);
}
}
PartitionTableType::Legacy => {
if disk.num_parts() >= 2 {
self.selections[0] = Some(0);
self.list_parts.select(1);
}
}
}
}
}
}
}
}
}
Action::SelectRight(one, two) => {
self.selections_saved[0] = one;
self.selections_saved[1] = two;
}
Action::SetMode(_) => {
self.selections[0] = None;
self.selections[1] = None;
self.selections_saved[0] = None;
self.selections_saved[1] = None;
}
Action::UpdateRight(labels, start_index, list) => {
self.list_header = list[..start_index].iter().flatten().cloned().collect();
self.list_labels = labels;
self.list.set_items(list[start_index..].to_vec());
}
_ => {}
}
@ -161,230 +131,57 @@ impl Component for Right {
.areas(area);
// Title
let title_text = String::from("Info");
let title = Paragraph::new(Line::from(title_text).centered())
let title = Paragraph::new(Line::from(self.title.as_str()).centered())
.block(Block::default().borders(Borders::NONE));
frame.render_widget(title, title_area);
// Body
let mut body_text = Vec::new();
match (self.prev_mode, self.cur_mode) {
(_, Mode::InstallDrivers) => {
body_text.push(Line::from(Span::raw(format!("CPU: {}", get_cpu_name()))));
}
(_, Mode::SelectDisks | Mode::SelectTableType)
| (Mode::SelectDisks | Mode::SelectTableType, Mode::Confirm) => {
// Source Disk
body_text.push(Line::from(Span::styled(
"Source:",
Style::default().cyan().bold(),
)));
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<4} {:<4} {}",
"Disk ID", "Size", "Conn", "Type", "Model (Serial)"
),
Style::new().green().bold(),
)));
let index = if self.selected_disks[0].is_some() {
// Selected in prior mode
self.selected_disks[0]
} else if self.selections[0].is_some() {
// Selected in this mode
self.selections[0]
} else {
// Highlighted entry
self.list_disks.selected()
};
if let Some(i) = index {
if let Some(disk) = self.list_disks.get(i) {
body_text.push(Line::from(Span::raw(&disk.description)));
// Source parts
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
),
Style::new().blue().bold(),
)));
for line in &disk.parts_description {
body_text.push(Line::from(Span::raw(line)));
}
}
}
// Destination Disk
let index = if self.selected_disks[1].is_some() {
// Selected in prior mode
self.selected_disks[1]
} else {
// Select(ed) in this mode
match (self.selections[0], self.selections[1]) {
(Some(one), None) => {
// First selected
if let Some(two) = self.selections[1] {
if one == two {
None
} else {
self.selections[1]
}
} else {
self.list_disks.selected()
}
}
(Some(_), Some(_)) => {
// Both selected
self.selections[1]
}
(_, _) => None,
}
};
if let Some(i) = index {
// Divider
body_text.push(Line::from(""));
body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize)));
body_text.push(Line::from(""));
// Disk
if let Some(disk) = self.list_disks.get(i) {
body_text.push(Line::from(vec![
Span::styled("Dest:", Style::default().cyan().bold()),
Span::styled(
" (WARNING: ALL DATA WILL BE DELETED!)",
Style::default().red().bold(),
),
]));
if let Some(table_type) = &self.table_type {
body_text.push(Line::from(Span::styled(
format!(" (Will be formatted {table_type})"),
Style::default().yellow().bold(),
)));
}
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<4} {:<4} {}",
"Disk ID", "Size", "Conn", "Type", "Model (Serial)"
),
Style::new().green().bold(),
)));
body_text.push(Line::from(Span::raw(&disk.description)));
// Destination parts
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
),
Style::new().blue().bold(),
)));
for line in &disk.parts_description {
body_text.push(Line::from(Span::raw(line)));
}
}
}
}
(_, Mode::SelectParts) | (Mode::SelectParts, Mode::Confirm) => {
// Disk
if let Some(index) = self.selected_disks[1] {
if let Some(disk) = self.list_disks.get(index) {
body_text.push(Line::from(Span::styled(
"Dest:",
Style::default().cyan().bold(),
)));
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<4} {:<4} {}",
"Disk ID", "Size", "Conn", "Type", "Model (Serial)"
),
Style::new().green().bold(),
)));
body_text.push(Line::from(Span::raw(&disk.description)));
// Destination parts
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
),
Style::new().blue().bold(),
)));
for line in &disk.parts_description {
body_text.push(Line::from(Span::raw(line)));
}
}
// Divider
body_text.push(Line::from(""));
body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize)));
body_text.push(Line::from(""));
// Boot Partition
// i.e. either the previously selected part or the highlighted one (if possible)
let mut boot_index = self.selections[0];
if boot_index.is_none() {
if let Some(i) = self.list_parts.selected() {
boot_index = Some(i);
}
}
if let Some(i) = boot_index {
if let Some(part) = self.list_parts.get(i) {
body_text.push(Line::from(Span::styled(
"Boot:",
Style::default().cyan().bold(),
)));
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
),
Style::new().blue().bold(),
)));
body_text.push(Line::from(Span::raw(format!("{part}"))));
}
}
// OS Partition
// i.e. either the previously selected part or the highlighted one (if needed)
let mut os_index = self.selections[1];
if os_index.is_none() {
if let Some(boot_index) = self.selections[0] {
if let Some(i) = self.list_parts.selected() {
if boot_index != i {
os_index = Some(i);
}
}
}
}
if let Some(i) = os_index {
if let Some(part) = self.list_parts.get(i) {
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
"OS:",
Style::default().cyan().bold(),
)));
body_text.push(Line::from(""));
body_text.push(Line::from(Span::styled(
format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
),
Style::new().blue().bold(),
)));
body_text.push(Line::from(Span::raw(format!("{part}"))));
}
}
}
}
_ => {}
let mut body_text: Vec<Line> = Vec::new();
if !self.list_header.is_empty() {
// Static Header
self.list_header
.iter()
.for_each(|dv| body_text.push(dv.as_line()));
body_text.push(Line::from(""));
body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize)));
body_text.push(Line::from(""));
}
// First selection
if let Some(first_index) = self.get_first() {
if let Some(first_desc) = self.list.get(first_index) {
if let Some(label) = self.list_labels.get(0) {
label
.iter()
.for_each(|dv| body_text.push(dv.as_line().bold()));
}
body_text.push(Line::from(""));
first_desc
.iter()
.for_each(|dv| body_text.push(dv.as_line()));
}
}
// Second selection
if let Some(second_index) = self.get_second() {
if let Some(second_desc) = self.list.get(second_index) {
// Divider
body_text.push(Line::from(""));
body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize)));
body_text.push(Line::from(""));
if let Some(label) = self.list_labels.get(1) {
label
.iter()
.for_each(|dv| body_text.push(dv.as_line().bold()));
}
body_text.push(Line::from(""));
second_desc
.iter()
.for_each(|dv| body_text.push(dv.as_line()));
}
}
// Build Paragraph
let body = Paragraph::new(body_text)
.style(Style::default().fg(Color::Gray))
.wrap(Wrap { trim: false })

94
deja_vu/src/line.rs Normal file
View file

@ -0,0 +1,94 @@
// This file is part of Deja-vu.
//
// Deja-vu 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.
//
// Deja-vu 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 Deja-vu. If not, see <https://www.gnu.org/licenses/>.
//
use ratatui::{
style::{Color, Style},
text::{Line, Span},
};
use serde::{Deserialize, Serialize};
use std::iter::zip;
use crate::system::disk::{Disk, Partition};
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DVLine {
pub line_parts: Vec<String>,
pub line_colors: Vec<Color>,
}
impl DVLine {
/// Convert to Line with colored span(s)
pub fn as_line(&self) -> Line {
let mut spans = Vec::new();
zip(self.line_parts.clone(), self.line_colors.clone())
.for_each(|(part, color)| spans.push(Span::styled(part, Style::default().fg(color))));
Line::from(spans)
}
pub fn blank() -> Self {
Self {
line_parts: vec![String::new()],
line_colors: vec![Color::Reset],
}
}
}
pub fn get_disk_description_right(disk: &Disk) -> Vec<DVLine> {
let mut description: Vec<DVLine> = vec![
DVLine {
line_parts: vec![format!(
"{:<8} {:>11} {:<4} {:<4} {}",
"Disk ID", "Size", "Conn", "Type", "Model (Serial)"
)],
line_colors: vec![Color::Green],
},
DVLine {
line_parts: vec![disk.description.clone()],
line_colors: vec![Color::Reset],
},
DVLine::blank(),
DVLine {
line_parts: vec![format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
)],
line_colors: vec![Color::Blue],
},
];
for line in &disk.parts_description {
description.push(DVLine {
line_parts: vec![line.clone()],
line_colors: vec![Color::Reset],
});
}
description
}
pub fn get_part_description(part: &Partition) -> Vec<DVLine> {
let description: Vec<DVLine> = vec![
DVLine {
line_parts: vec![format!(
"{:<8} {:>11} {:<7} {}",
"Part ID", "Size", "(FS)", "\"Label\""
)],
line_colors: vec![Color::Blue],
},
DVLine {
line_parts: vec![format!("{part}")],
line_colors: vec![Color::Reset],
},
];
description
}

View file

@ -25,6 +25,7 @@ mod cli;
mod components;
mod config;
mod errors;
mod line;
mod logging;
mod state;
mod system;

View file

@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize};
use crate::system::{
disk::{Disk, PartitionTableType},
drivers::Driver,
drivers,
};
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
@ -44,9 +44,10 @@ pub struct CloneSettings {
pub disk_index_dest: Option<usize>,
pub disk_index_source: Option<usize>,
pub disk_list: Arc<Mutex<Vec<Disk>>>,
pub driver_list: Vec<drivers::Driver>,
pub part_index_boot: Option<usize>,
pub part_index_os: Option<usize>,
pub driver: Option<Driver>,
pub driver: Option<drivers::Driver>,
pub table_type: Option<PartitionTableType>,
}
@ -57,4 +58,8 @@ impl CloneSettings {
..Default::default()
}
}
pub fn scan_drivers(&mut self) {
self.driver_list = drivers::scan();
}
}