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
7 changed files with 420 additions and 561 deletions

View file

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

View file

@ -101,102 +101,43 @@ impl App {
}) })
} }
pub fn get_boot_part_index(&self) -> usize { pub fn prev_mode(&mut self) -> Option<Mode> {
if let Some(index) = self.clone.part_index_boot { let new_mode = match self.cur_mode {
index Mode::Failed => Some(Mode::Failed),
} else if let Some(index) = self.selections[0] { Mode::Done => Some(Mode::Done),
index Mode::SelectParts => Some(Mode::SelectParts),
} else { Mode::Confirm => Some(Mode::SelectTableType),
self.list.selected().unwrap() Mode::SelectTableType => Some(Mode::SelectDisks),
} Mode::SelectDisks => Some(Mode::ScanDisks),
} //
Mode::InstallDrivers
pub fn get_os_part_index(&self) -> Option<usize> { | Mode::ScanDisks
let mut os_part_index = None; | Mode::PreClone
if let Some(index) = self.clone.part_index_os { | Mode::Clone
os_part_index = Some(index); | Mode::PostClone => None,
} else if let Some(index) = self.selections[1] {
os_part_index = Some(index);
} else {
// Highlighted entry
if let Some(index) = self.list.selected() {
if index != self.get_boot_part_index() {
os_part_index = Some(index)
}
}
}
os_part_index
}
pub fn get_dest_index(&self) -> Option<usize> {
let mut dest_index = None;
if let Some(index) = self.clone.disk_index_dest {
// Selected in prior mode
dest_index = Some(index);
} else if let Some(index) = self.selections[1] {
// Selected in this mode
dest_index = Some(index);
} else if let Some(index) = self.list.selected() {
// Highlighted entry
if let Some(source_index) = self.get_source_index() {
if index != source_index {
dest_index = Some(index)
}
}
}
dest_index
}
pub fn get_source_index(&self) -> Option<usize> {
if let Some(index) = self.clone.disk_index_source {
// Selected in prior mode
Some(index)
} else if let Some(index) = self.selections[0] {
// Selected in this mode
Some(index)
} else {
self.list.selected()
}
}
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."),
}; };
new_mode
}
let prev_mode = { pub fn next_mode(&mut self) -> Option<Mode> {
match self.cur_mode { let new_mode = match self.cur_mode {
Mode::Confirm => Some(self.prev_mode), Mode::InstallDrivers => Mode::ScanDisks,
Mode::PreClone | Mode::Clone | Mode::PostClone | Mode::Done => { Mode::ScanDisks => Mode::SelectDisks,
// Override since we're past the point of no return Mode::SelectDisks => Mode::SelectTableType,
Some(self.cur_mode) Mode::SelectTableType => Mode::Confirm,
} Mode::Confirm => Mode::PreClone,
_ => Some(self.cur_mode), 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 { if new_mode == self.cur_mode {
// No mode change needed // No mode change needed
(None, None) None
} else { } else {
(prev_mode, Some(new_mode)) Some(new_mode)
} }
} }
@ -204,6 +145,7 @@ impl App {
info!("Setting mode to {new_mode:?}"); info!("Setting mode to {new_mode:?}");
self.cur_mode = new_mode; self.cur_mode = new_mode;
match new_mode { match new_mode {
Mode::InstallDrivers => self.clone.scan_drivers(),
Mode::ScanDisks => { Mode::ScanDisks => {
self.prev_mode = self.cur_mode; self.prev_mode = self.cur_mode;
if self.tasks.idle() { if self.tasks.idle() {
@ -302,10 +244,7 @@ impl App {
String::from("COMPLETE\n\n\nThank you for using this tool!"), String::from("COMPLETE\n\n\nThank you for using this tool!"),
))?; ))?;
} }
_ => { _ => {}
//TODO
//FIXME
}
} }
Ok(()) Ok(())
} }
@ -419,37 +358,41 @@ impl App {
Action::InstallDriver => { Action::InstallDriver => {
self.action_tx.send(Action::SetMode(Mode::InstallDrivers))?; self.action_tx.send(Action::SetMode(Mode::InstallDrivers))?;
} }
Action::SelectDriver(ref driver) => { Action::Process => match self.cur_mode {
self.clone.driver = Some(driver.clone()); Mode::Confirm => {
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)?; self.action_tx.send(Action::NextScreen)?;
} }
_ => {}
},
Action::Resize(w, h) => self.handle_resize(tui, w, h)?, Action::Resize(w, h) => self.handle_resize(tui, w, h)?,
Action::Render => self.render(tui)?, Action::Render => self.render(tui)?,
Action::PrevScreen => { Action::PrevScreen => {
let new_mode = match (self.prev_mode, self.cur_mode) { if let Some(new_mode) = self.prev_mode() {
(Mode::SelectTableType, Mode::SelectTableType) => Mode::SelectDisks, self.prev_mode = new_mode;
(_, _) => self.prev_mode, self.cur_mode = new_mode;
};
self.action_tx.send(Action::SetMode(new_mode))?; self.action_tx.send(Action::SetMode(new_mode))?;
} }
}
Action::NextScreen => match self.next_mode() { Action::NextScreen => match self.next_mode() {
(None, None) => {} None => {}
(Some(prev), Some(next)) => { Some(next) => {
self.prev_mode = prev; self.prev_mode = self.cur_mode;
self.cur_mode = next; self.cur_mode = next;
self.action_tx.send(Action::DismissPopup)?; self.action_tx.send(Action::DismissPopup)?;
self.action_tx.send(Action::SetMode(next))?; self.action_tx.send(Action::SetMode(next))?;
} }
_ => panic!("Failed to determine next mode"),
}, },
Action::ScanDisks => self.action_tx.send(Action::SetMode(Mode::ScanDisks))?, Action::ScanDisks => self.action_tx.send(Action::SetMode(Mode::ScanDisks))?,
Action::Select(one, two) => { Action::Select(one, two) => {
match self.cur_mode { 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 => { Mode::SelectDisks => {
self.clone.disk_index_source = one; self.clone.disk_index_source = one;
self.clone.disk_index_dest = two; self.clone.disk_index_dest = two;
@ -458,6 +401,21 @@ impl App {
self.clone.part_index_boot = one; self.clone.part_index_boot = one;
self.clone.part_index_os = two; 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[0] = one;
@ -465,8 +423,42 @@ impl App {
} }
Action::SetMode(new_mode) => { Action::SetMode(new_mode) => {
self.set_mode(new_mode)?; self.set_mode(new_mode)?;
let (start, lines) = get_right_selections(self, self.prev_mode, self.cur_mode); self.action_tx
self.action_tx.send(Action::UpdateRight(start, lines))?; .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))?;
}
_ => {}
};
} }
_ => {} _ => {}
} }
@ -560,88 +552,145 @@ fn get_chunks(r: Rect) -> Vec<Rect> {
chunks chunks
} }
fn get_right_selections(app: &App, prev_mode: Mode, cur_mode: Mode) -> (usize, Vec<Vec<DVLine>>) { fn build_footer_string(cur_mode: Mode) -> String {
let mut selections = Vec::new(); 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; let mut start_index = 0;
match (prev_mode, cur_mode) { match cur_mode {
(_, Mode::InstallDrivers) => { Mode::InstallDrivers => {
info!("get_right_selections: InstallDrivers"); items.push(vec![DVLine {
selections.push(vec![DVLine {
line_parts: vec![String::from("CPU")], line_parts: vec![String::from("CPU")],
line_colors: vec![Color::Cyan], line_colors: vec![Color::Cyan],
}]); }]);
selections.push(vec![DVLine { items.push(vec![DVLine {
line_parts: vec![get_cpu_name()], line_parts: vec![get_cpu_name()],
line_colors: vec![Color::Reset], line_colors: vec![Color::Reset],
}]); }]);
start_index = 2; start_index = 2;
} }
(_, Mode::SelectDisks | Mode::SelectTableType) Mode::SelectDisks | Mode::SelectTableType | Mode::Confirm => {
| (Mode::SelectDisks | Mode::SelectTableType, Mode::Confirm) => { // Labels
info!("get_right_selections: SelectDisks"); labels.push(vec![DVLine {
// Source Disk Details line_parts: vec![String::from("Source")],
if let Some(index) = app.get_source_index() { line_colors: vec![Color::Cyan],
info!("get_right_selections: Source Disk Index: {}", index); }]);
let disk_list = app.clone.disk_list.lock().unwrap(); let dest_dv_line = DVLine {
if let Some(disk) = disk_list.get(index) { line_parts: vec![
selections.push(get_disk_description_right(&disk, "Source")); String::from("Dest"),
} String::from(" (WARNING: ALL DATA WILL BE DELETED!)"),
} ],
// Dest Disk Details line_colors: vec![Color::Cyan, Color::Red],
if let Some(index) = app.get_dest_index() { };
let disk_list = app.clone.disk_list.lock().unwrap();
if let Some(disk) = disk_list.get(index) {
let mut disk_description = get_disk_description_right(&disk, "Dest");
// Add format warning
disk_description[0] // i.e. "Dest:"
.line_parts
.push(" (WARNING: ALL DATA WILL BE DELETED!)".to_string());
disk_description[0].line_colors.push(Color::Red);
if let Some(table_type) = &app.clone.table_type { if let Some(table_type) = &app.clone.table_type {
// Show table type // Show table type
let type_str = match table_type { let type_str = match table_type {
PartitionTableType::Guid => "GPT", PartitionTableType::Guid => "GPT",
PartitionTableType::Legacy => "MBR", PartitionTableType::Legacy => "MBR",
}; };
disk_description.insert( labels.push(vec![
1, dest_dv_line,
DVLine { DVLine {
line_parts: vec![format!(" (Will be formatted {type_str}")], line_parts: vec![format!(" (Will be formatted {type_str})")],
line_colors: vec![Color::Yellow], line_colors: vec![Color::Yellow],
}, },
); ]);
} else {
labels.push(vec![dest_dv_line]);
} }
selections.push(disk_description) 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| {
(_, Mode::SelectParts) | (Mode::SelectParts, Mode::Confirm) => { labels.push(vec![DVLine {
info!("get_right_selections: SelectParts"); line_parts: vec![String::from(*s)],
if let Some(index) = app.get_dest_index() { line_colors: vec![Color::Cyan],
}])
});
if let Some(index) = app.clone.disk_index_dest {
start_index = 1; start_index = 1;
let disk_list = app.clone.disk_list.lock().unwrap(); let disk_list = app.clone.disk_list.lock().unwrap();
if let Some(disk) = disk_list.get(index) { if let Some(disk) = disk_list.get(index) {
// Disk Details // Disk Details
selections.push(get_disk_description_right(&disk, "Disk")); items.push(get_disk_description_right(&disk));
// Boot Partition // Partition Details
let index = app.get_boot_part_index(); disk.parts
if let Some(part) = disk.parts.get(index) { .iter()
selections.push(get_part_description(&part, "Boot")); .for_each(|part| items.push(get_part_description(&part)));
}
// OS Partition
if let Some(index) = app.get_os_part_index() {
if let Some(part) = disk.parts.get(index) {
selections.push(get_part_description(&part, "OS"));
}
}
} }
} }
} }
_ => {} _ => {}
} }
info!("Right Selections: {:?}", &selections); (labels, start_index, items)
(start_index, selections)
} }

View file

@ -51,25 +51,9 @@ impl Component for Footer {
} }
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
if let Action::SetMode(new_mode) = action { match action {
self.text = match new_mode { Action::UpdateFooter(text) => self.text = text,
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")
}
}
} }
Ok(None) Ok(None)
} }

View file

@ -20,42 +20,37 @@ use ratatui::{
widgets::{Block, Borders, HighlightSpacing, List, ListItem, Padding, Paragraph}, widgets::{Block, Borders, HighlightSpacing, List, ListItem, Padding, Paragraph},
}; };
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
use tracing::info;
use super::{popup, state::StatefulList, Component}; use super::{state::StatefulList, Component};
use crate::{ use crate::{action::Action, config::Config};
action::Action,
config::Config,
state::Mode,
system::{
disk::{Disk, Partition, PartitionTableType},
drivers::{self, Driver},
},
};
#[derive(Default)] #[derive(Default)]
pub struct Left { pub struct Left {
command_tx: Option<UnboundedSender<Action>>, command_tx: Option<UnboundedSender<Action>>,
config: Config, config: Config,
disk_id_dest: Option<usize>, labels: Vec<String>,
table_type: Option<PartitionTableType>, list: StatefulList<String>,
title_text: String, select_one: bool,
list_disks: StatefulList<Disk>,
list_drivers: StatefulList<Driver>,
list_parts: StatefulList<Partition>,
list_table_types: StatefulList<PartitionTableType>,
mode: Mode,
selections: Vec<Option<usize>>, selections: Vec<Option<usize>>,
selections_saved: Vec<Option<usize>>,
title_text: String,
} }
impl Left { impl Left {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
select_one: false,
labels: vec![String::from("one"), String::from("two")],
selections: vec![None, None], selections: vec![None, None],
selections_saved: vec![None, None],
title_text: String::from("Home"), title_text: String::from("Home"),
..Default::default() ..Default::default()
} }
} }
fn set_highlight(&mut self, index: usize) {
self.list.select(index);
}
} }
impl Component for Left { impl Component for Left {
@ -76,180 +71,58 @@ impl Component for Left {
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action { match action {
Action::KeyUp => match self.mode { Action::Highlight(index) => self.set_highlight(index),
Mode::InstallDrivers => self.list_drivers.previous(), Action::KeyUp => self.list.previous(),
Mode::SelectDisks => self.list_disks.previous(), Action::KeyDown => self.list.next(),
Mode::SelectTableType => self.list_table_types.previous(), Action::Process => {
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() { 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)?; command_tx.send(Action::NextScreen)?;
} }
} }
Mode::InstallDrivers (Some(first_index), None) => {
| Mode::SelectDisks if let Some(second_index) = self.list.selected() {
| Mode::SelectTableType // Making second selection
| Mode::SelectParts => { if first_index == second_index {
// 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 // Toggle first selection
selection_one = None; command_tx.send(Action::Select(None, None))?;
self.selections[0] = None;
} else { } else {
selection_one = self.selections[0]; // Both selections made, proceed to next screen
selection_two = Some(index); command_tx.send(Action::Select(
} Some(first_index),
} Some(second_index),
} ))?;
// 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)?; command_tx.send(Action::NextScreen)?;
} }
} }
_ => {} }
}; _ => panic!("This shouldn't happen?"),
} }
} }
} }
_ => {} Action::Select(one, two) => {
}, self.selections[0] = one;
Action::Select(Some(index), None) => self.selections[0] = Some(index), self.selections[1] = two;
Action::Select(_, Some(index)) => { self.selections_saved[0] = one;
if self.mode == Mode::SelectDisks { self.selections_saved[1] = two;
self.disk_id_dest = Some(index);
} }
} Action::SetMode(_) => {
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[0] = None;
self.selections[1] = 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::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::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,19 +136,18 @@ impl Component for Left {
.areas(area); .areas(area);
// Title // Title
let title_text = if self.selections[1].is_some() || self.select_one {
"Confirm Selections"
} else {
self.title_text.as_str()
};
let title = 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)); .block(Block::default().borders(Borders::NONE));
frame.render_widget(title, title_area); frame.render_widget(title, title_area);
// Body // Body (Blank)
match self.mode { if self.list.is_empty() {
Mode::ScanDisks
| Mode::PreClone
| Mode::Clone
| Mode::PostClone
| Mode::Done
| Mode::Failed => {
// Leave blank // Leave blank
let paragraph = Paragraph::new(String::new()).block( let paragraph = Paragraph::new(String::new()).block(
Block::default() Block::default()
@ -287,72 +159,35 @@ impl Component for Left {
// Bail early // Bail early
return Ok(()); 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 // Body
return Ok(()); 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 {
""
} }
Mode::InstallDrivers } else if self.selections[1].is_some_and(|second_index| second_index == index) {
| Mode::SelectDisks if let Some(label) = self.labels.get(1) {
| Mode::SelectTableType style = style.yellow();
| Mode::SelectParts => { label.as_str()
// List modes } else {
let mut list_items = Vec::<ListItem>::new(); ""
let list_items_strings: Vec<String> = match self.mode { }
Mode::InstallDrivers => self } else {
.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() { ListItem::new(format!(" {item}\n{text}\n\n")).style(style)
for (index, item) in list_items_strings.iter().enumerate() { })
let mut item_style = Style::default(); .collect();
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) let list = List::new(list_items)
.block( .block(
Block::default() Block::default()
@ -363,25 +198,7 @@ impl Component for Left {
.highlight_style(Style::new().green().bold()) .highlight_style(Style::new().green().bold())
.highlight_symbol(" --> ") .highlight_symbol(" --> ")
.repeat_highlight_symbol(false); .repeat_highlight_symbol(false);
match self.mode { frame.render_stateful_widget(list, body_area, &mut self.list.state);
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."),
}
}
}
// Done // Done
Ok(()) Ok(())

View file

@ -22,16 +22,17 @@ use ratatui::{
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
use super::{state::StatefulList, Component}; use super::{state::StatefulList, Component};
use crate::{action::Action, config::Config, line::DVLine, state::Mode}; use crate::{action::Action, config::Config, line::DVLine};
#[derive(Default)] #[derive(Default)]
pub struct Right { pub struct Right {
command_tx: Option<UnboundedSender<Action>>, command_tx: Option<UnboundedSender<Action>>,
config: Config, config: Config,
cur_mode: Mode,
list_header: Vec<DVLine>, list_header: Vec<DVLine>,
list_labels: Vec<Vec<DVLine>>,
list: StatefulList<Vec<DVLine>>, list: StatefulList<Vec<DVLine>>,
selections: Vec<Option<usize>>, selections: Vec<Option<usize>>,
selections_saved: Vec<Option<usize>>,
title: String, title: String,
} }
@ -39,10 +40,37 @@ impl Right {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
selections: vec![None, None], selections: vec![None, None],
selections_saved: vec![None, None],
title: String::from("Info"), title: String::from("Info"),
..Default::default() ..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 { impl Component for Right {
@ -63,51 +91,32 @@ impl Component for Right {
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action { match action {
Action::Highlight(index) => self.set_highlight(index),
Action::KeyUp => self.list.previous(), Action::KeyUp => self.list.previous(),
Action::KeyDown => self.list.next(), Action::KeyDown => self.list.next(),
Action::Select(one, two) => { Action::Select(one, two) => {
self.selections[0] = one; self.selections[0] = one;
self.selections[1] = two; self.selections[1] = two;
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::SetMode(new_mode) => { }
self.cur_mode = new_mode; Action::SelectRight(one, two) => {
self.selections_saved[0] = one;
self.selections_saved[1] = two;
}
Action::SetMode(_) => {
self.selections[0] = None; self.selections[0] = None;
self.selections[1] = None; self.selections[1] = None;
self.selections_saved[0] = None;
self.selections_saved[1] = None;
} }
// Action::UpdateDiskList(disks) => { Action::UpdateRight(labels, start_index, list) => {
// 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::UpdateRight(start_index, list) => {
self.list_header = list[..start_index].iter().flatten().cloned().collect(); self.list_header = list[..start_index].iter().flatten().cloned().collect();
self.list_labels = labels;
self.list.set_items(list[start_index..].to_vec()); self.list.set_items(list[start_index..].to_vec());
} }
_ => {} _ => {}
@ -139,8 +148,14 @@ impl Component for Right {
} }
// First selection // First selection
if let Some(first_index) = self.selections[0] { if let Some(first_index) = self.get_first() {
if let Some(first_desc) = self.list.get(first_index) { 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 first_desc
.iter() .iter()
.for_each(|dv| body_text.push(dv.as_line())); .for_each(|dv| body_text.push(dv.as_line()));
@ -148,12 +163,18 @@ impl Component for Right {
} }
// Second selection // Second selection
if let Some(second_index) = self.selections[1] { if let Some(second_index) = self.get_second() {
if let Some(second_desc) = self.list.get(second_index) { if let Some(second_desc) = self.list.get(second_index) {
// Divider // Divider
body_text.push(Line::from("")); body_text.push(Line::from(""));
body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize))); body_text.push(Line::from(str::repeat("", (body_area.width - 4) as usize)));
body_text.push(Line::from("")); 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 second_desc
.iter() .iter()
.for_each(|dv| body_text.push(dv.as_line())); .for_each(|dv| body_text.push(dv.as_line()));

View file

@ -45,13 +45,8 @@ impl DVLine {
} }
} }
pub fn get_disk_description_right(disk: &Disk, label: &str) -> Vec<DVLine> { pub fn get_disk_description_right(disk: &Disk) -> Vec<DVLine> {
let mut description: Vec<DVLine> = vec![ let mut description: Vec<DVLine> = vec![
DVLine {
line_parts: vec![String::from(label)],
line_colors: vec![Color::Cyan],
},
DVLine::blank(),
DVLine { DVLine {
line_parts: vec![format!( line_parts: vec![format!(
"{:<8} {:>11} {:<4} {:<4} {}", "{:<8} {:>11} {:<4} {:<4} {}",
@ -81,13 +76,8 @@ pub fn get_disk_description_right(disk: &Disk, label: &str) -> Vec<DVLine> {
description description
} }
pub fn get_part_description(part: &Partition, label: &str) -> Vec<DVLine> { pub fn get_part_description(part: &Partition) -> Vec<DVLine> {
let description: Vec<DVLine> = vec![ let description: Vec<DVLine> = vec![
DVLine {
line_parts: vec![String::from(label)],
line_colors: vec![Color::Cyan],
},
DVLine::blank(),
DVLine { DVLine {
line_parts: vec![format!( line_parts: vec![format!(
"{:<8} {:>11} {:<7} {}", "{:<8} {:>11} {:<7} {}",

View file

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