Compare commits
23 commits
76a27cd179
...
83b01a1230
| Author | SHA1 | Date | |
|---|---|---|---|
| 83b01a1230 | |||
| 9addea0676 | |||
| 8be96d21b9 | |||
| 5c0c47cc0f | |||
| b8403d6f52 | |||
| 833223b7ad | |||
| 1373d33f42 | |||
| 51610fdc23 | |||
| 6b2eb8155f | |||
| e26a83299c | |||
| 14a8ea7429 | |||
| 6ea2df892f | |||
| 5343912699 | |||
| e029e02cc2 | |||
| a77bf0c9c6 | |||
| 3c0c12fa7a | |||
| 9d6fa954b2 | |||
| 253385c2a7 | |||
| fc0b82418b | |||
| 608f07d445 | |||
| 828a2736be | |||
| 81aa7a8984 | |||
| da1892710f |
57 changed files with 3281 additions and 2649 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,2 +1,3 @@
|
|||
/target
|
||||
/*/target
|
||||
.data/*.log
|
||||
|
|
|
|||
1398
Cargo.lock
generated
1398
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -14,6 +14,6 @@
|
|||
# along with Deja-vu. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
[workspace]
|
||||
members = ["deja_vu", "pe_menu"]
|
||||
description = "Clone/Install Windows, create/edit boot files, and troubleshoot boot issues."
|
||||
members = ["core", "boot_diags", "deja_vu", "pe_menu"]
|
||||
default-members = ["boot_diags", "deja_vu", "pe_menu"]
|
||||
resolver = "2"
|
||||
|
|
|
|||
46
boot_diags/Cargo.toml
Normal file
46
boot_diags/Cargo.toml
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# 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/>.
|
||||
|
||||
[package]
|
||||
name = "boot-diags"
|
||||
authors = ["2Shirt <2xShirt@gmail.com>"]
|
||||
edition = "2021"
|
||||
license = "GPL"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies]
|
||||
core = { path = "../core" }
|
||||
clap = { version = "4.4.5", features = [
|
||||
"derive",
|
||||
"cargo",
|
||||
"wrap_help",
|
||||
"unicode",
|
||||
"string",
|
||||
"unstable-styles",
|
||||
] }
|
||||
color-eyre = "0.6.3"
|
||||
crossterm = { version = "0.28.1", features = ["event-stream"] }
|
||||
futures = "0.3.30"
|
||||
ratatui = "0.29.0"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
toml = "0.8.13"
|
||||
tracing = "0.1.41"
|
||||
tracing-error = "0.2.0"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = "1.0.86"
|
||||
vergen-gix = { version = "1.0.0", features = ["build", "cargo"] }
|
||||
28
boot_diags/build.rs
Normal file
28
boot_diags/build.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// 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 anyhow::Result;
|
||||
use vergen_gix::{BuildBuilder, CargoBuilder, Emitter, GixBuilder};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let build = BuildBuilder::all_build()?;
|
||||
let gix = GixBuilder::all_git()?;
|
||||
let cargo = CargoBuilder::all_cargo()?;
|
||||
Emitter::default()
|
||||
.add_instructions(&build)?
|
||||
.add_instructions(&gix)?
|
||||
.add_instructions(&cargo)?
|
||||
.emit()
|
||||
}
|
||||
579
boot_diags/src/app.rs
Normal file
579
boot_diags/src/app.rs
Normal file
|
|
@ -0,0 +1,579 @@
|
|||
// 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 core::{
|
||||
action::Action,
|
||||
components::{
|
||||
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::{cpu::get_cpu_name, drivers},
|
||||
tasks::{Task, Tasks},
|
||||
tui::{Event, Tui},
|
||||
};
|
||||
use std::{
|
||||
iter::zip,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use color_eyre::Result;
|
||||
use ratatui::{
|
||||
crossterm::event::KeyEvent,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
prelude::Rect,
|
||||
style::Color,
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, info};
|
||||
|
||||
pub struct App {
|
||||
// TUI
|
||||
action_rx: mpsc::UnboundedReceiver<Action>,
|
||||
action_tx: mpsc::UnboundedSender<Action>,
|
||||
components: Vec<Box<dyn Component>>,
|
||||
config: Config,
|
||||
frame_rate: f64,
|
||||
last_tick_key_events: Vec<KeyEvent>,
|
||||
should_quit: bool,
|
||||
should_suspend: bool,
|
||||
tick_rate: f64,
|
||||
// App
|
||||
clone: CloneSettings,
|
||||
cur_mode: Mode,
|
||||
list: StatefulList<Mode>,
|
||||
selections: Vec<Option<usize>>,
|
||||
tasks: Tasks,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
|
||||
let (action_tx, action_rx) = mpsc::unbounded_channel();
|
||||
let disk_list_arc = Arc::new(Mutex::new(Vec::new()));
|
||||
let tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
|
||||
let mut list = StatefulList::default();
|
||||
list.set_items(vec![
|
||||
Mode::BootDiags,
|
||||
Mode::BootSetup,
|
||||
Mode::InjectDrivers,
|
||||
Mode::ToggleSafeMode,
|
||||
]);
|
||||
Ok(Self {
|
||||
// TUI
|
||||
action_rx,
|
||||
action_tx,
|
||||
components: vec![
|
||||
Box::new(Title::new("Boot Diagnostics")),
|
||||
Box::new(FpsCounter::new()),
|
||||
Box::new(Left::new()),
|
||||
Box::new(Right::new()),
|
||||
Box::new(Footer::new()),
|
||||
Box::new(popup::Popup::new()),
|
||||
],
|
||||
config: Config::new()?,
|
||||
frame_rate,
|
||||
last_tick_key_events: Vec::new(),
|
||||
should_quit: false,
|
||||
should_suspend: false,
|
||||
tick_rate,
|
||||
// App
|
||||
clone: CloneSettings::new(disk_list_arc),
|
||||
cur_mode: Mode::Home,
|
||||
list,
|
||||
selections: vec![None, None],
|
||||
tasks,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn next_mode(&mut self) -> Mode {
|
||||
match self.cur_mode {
|
||||
Mode::Home => Mode::ScanDisks,
|
||||
Mode::InstallDrivers => Mode::ScanDisks,
|
||||
Mode::ScanDisks => Mode::SelectDisks,
|
||||
Mode::SelectDisks => Mode::SelectParts,
|
||||
Mode::SelectParts => Mode::DiagMenu,
|
||||
Mode::DiagMenu => {
|
||||
// Use highlighted entry
|
||||
if let Some(new_mode) = self.list.get_selected() {
|
||||
new_mode
|
||||
} else {
|
||||
self.cur_mode
|
||||
}
|
||||
}
|
||||
Mode::Failed => Mode::Failed,
|
||||
// Default to current mode
|
||||
_ => self.cur_mode,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_mode(&mut self, new_mode: Mode) -> Result<()> {
|
||||
info!("Setting mode to {new_mode:?}");
|
||||
self.cur_mode = new_mode;
|
||||
match new_mode {
|
||||
Mode::InjectDrivers | Mode::InstallDrivers => self.clone.scan_drivers(),
|
||||
Mode::ScanDisks => {
|
||||
if self.tasks.idle() {
|
||||
self.tasks.add(Task::ScanDisks);
|
||||
}
|
||||
self.action_tx.send(Action::DisplayPopup(
|
||||
popup::Type::Info,
|
||||
String::from("Scanning Disks..."),
|
||||
))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Result<()> {
|
||||
let mut tui = Tui::new()?
|
||||
// .mouse(true) // uncomment this line to enable mouse support
|
||||
.tick_rate(self.tick_rate)
|
||||
.frame_rate(self.frame_rate);
|
||||
tui.enter()?;
|
||||
|
||||
for component in &mut self.components {
|
||||
component.register_action_handler(self.action_tx.clone())?;
|
||||
}
|
||||
for component in &mut self.components {
|
||||
component.register_config_handler(self.config.clone())?;
|
||||
}
|
||||
for component in &mut self.components {
|
||||
component.init(tui.size()?)?;
|
||||
}
|
||||
|
||||
let action_tx = self.action_tx.clone();
|
||||
action_tx.send(Action::SetMode(Mode::ScanDisks))?;
|
||||
loop {
|
||||
self.handle_events(&mut tui).await?;
|
||||
self.handle_actions(&mut tui)?;
|
||||
if self.should_suspend {
|
||||
tui.suspend()?;
|
||||
action_tx.send(Action::Resume)?;
|
||||
action_tx.send(Action::ClearScreen)?;
|
||||
// tui.mouse(true);
|
||||
tui.enter()?;
|
||||
} else if self.should_quit {
|
||||
tui.stop()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
tui.exit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_events(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
let Some(event) = tui.next_event().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let action_tx = self.action_tx.clone();
|
||||
match event {
|
||||
Event::Quit => action_tx.send(Action::Quit)?,
|
||||
Event::Tick => action_tx.send(Action::Tick)?,
|
||||
Event::Render => action_tx.send(Action::Render)?,
|
||||
Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
|
||||
Event::Key(key) => self.handle_key_event(key)?,
|
||||
_ => {}
|
||||
}
|
||||
for component in &mut self.components {
|
||||
if let Some(action) = component.handle_events(Some(event.clone()))? {
|
||||
action_tx.send(action)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<()> {
|
||||
let action_tx = self.action_tx.clone();
|
||||
let Some(keymap) = self.config.keybindings.get(&self.cur_mode) else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(action) = keymap.get(&vec![key]) {
|
||||
info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
} else {
|
||||
// If the key was not handled as a single key action,
|
||||
// then consider it for multi-key combinations.
|
||||
self.last_tick_key_events.push(key);
|
||||
|
||||
// Check for multi-key combinations
|
||||
if let Some(action) = keymap.get(&self.last_tick_key_events) {
|
||||
info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_actions(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
while let Ok(action) = self.action_rx.try_recv() {
|
||||
if action != Action::Tick && action != Action::Render {
|
||||
debug!("{action:?}");
|
||||
}
|
||||
match action {
|
||||
Action::Tick => {
|
||||
self.last_tick_key_events.drain(..);
|
||||
// Check background task(s)
|
||||
match self.cur_mode {
|
||||
Mode::ScanDisks => {
|
||||
// Check background task
|
||||
self.tasks.poll()?; // Once all are complete Action::NextScreen is sent
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Action::Quit => self.should_quit = true,
|
||||
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()))?;
|
||||
self.action_tx.send(Action::SetMode(Mode::Failed))?;
|
||||
}
|
||||
Action::Process => match self.cur_mode {
|
||||
Mode::DiagMenu => {
|
||||
let new_mode = self.next_mode();
|
||||
self.action_tx.send(Action::SetMode(new_mode))?;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Action::Resize(w, h) => self.handle_resize(tui, w, h)?,
|
||||
Action::Render => self.render(tui)?,
|
||||
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_dest = one;
|
||||
}
|
||||
Mode::SelectParts => {
|
||||
self.clone.part_index_boot = one;
|
||||
self.clone.part_index_os = two;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.selections[0] = one;
|
||||
self.selections[1] = two;
|
||||
}
|
||||
Action::SetMode(new_mode) => {
|
||||
self.cur_mode = new_mode;
|
||||
self.set_mode(new_mode)?;
|
||||
self.action_tx
|
||||
.send(Action::UpdateFooter(build_footer_string(self.cur_mode)))?;
|
||||
self.action_tx.send(build_left_items(self))?;
|
||||
self.action_tx.send(build_right_items(self))?;
|
||||
self.action_tx.send(Action::Select(None, None))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for component in &mut self.components {
|
||||
if let Some(action) = component.update(action.clone())? {
|
||||
self.action_tx.send(action)?;
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_resize(&mut self, tui: &mut Tui, w: u16, h: u16) -> Result<()> {
|
||||
tui.resize(Rect::new(0, 0, w, h))?;
|
||||
self.render(tui)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
tui.draw(|frame| {
|
||||
if let [header, _body, footer, left, right, popup] = get_chunks(frame.area())[..] {
|
||||
let component_areas = vec![
|
||||
header, // Title Bar
|
||||
header, // FPS Counter
|
||||
left, right, footer, popup,
|
||||
];
|
||||
for (component, area) in zip(self.components.iter_mut(), component_areas) {
|
||||
if let Err(err) = component.draw(frame, area) {
|
||||
let _ = self
|
||||
.action_tx
|
||||
.send(Action::Error(format!("Failed to draw: {err:?}")));
|
||||
}
|
||||
}
|
||||
};
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
// Cut the given rectangle into three vertical pieces
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
// Then cut the middle vertical piece into three width-wise pieces
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1] // Return the middle chunk
|
||||
}
|
||||
|
||||
fn get_chunks(r: Rect) -> Vec<Rect> {
|
||||
let mut chunks: Vec<Rect> = Vec::with_capacity(6);
|
||||
|
||||
// Main sections
|
||||
chunks.extend(
|
||||
Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(3),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(r)
|
||||
.to_vec(),
|
||||
);
|
||||
|
||||
// Left/Right
|
||||
chunks.extend(
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||
.split(centered_rect(90, 90, chunks[1]))
|
||||
.to_vec(),
|
||||
);
|
||||
|
||||
// Popup
|
||||
chunks.push(centered_rect(60, 25, r));
|
||||
|
||||
// Done
|
||||
chunks
|
||||
}
|
||||
|
||||
fn build_footer_string(cur_mode: Mode) -> String {
|
||||
match cur_mode {
|
||||
// Boot Diags
|
||||
Mode::BootSetup
|
||||
| Mode::DiagMenu
|
||||
| Mode::InjectDrivers
|
||||
| Mode::PEMenu
|
||||
| Mode::ToggleSafeMode => String::from("(Enter) or (q) to quit"),
|
||||
// Copied from Clone
|
||||
Mode::Home | Mode::ScanDisks | Mode::BootDiags => 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"),
|
||||
// Invalid states
|
||||
Mode::Clone | Mode::PreClone | Mode::PostClone => panic!("This shouldn't happen?"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_left_items(app: &App) -> Action {
|
||||
let mut items = Vec::new();
|
||||
let mut labels = vec![String::new(), String::new()];
|
||||
let select_num: usize;
|
||||
let title: String;
|
||||
match app.cur_mode {
|
||||
Mode::Home => {
|
||||
select_num = 0;
|
||||
title = String::from("Home");
|
||||
}
|
||||
Mode::DiagMenu => {
|
||||
select_num = 0;
|
||||
title = String::from("Troubleshooting");
|
||||
app.list.items.iter().for_each(|mode| {
|
||||
let (name, _) = get_mode_strings(*mode);
|
||||
items.push(name);
|
||||
});
|
||||
}
|
||||
Mode::InstallDrivers => {
|
||||
select_num = 1;
|
||||
title = String::from("Install Drivers");
|
||||
app.clone
|
||||
.driver_list
|
||||
.iter()
|
||||
.for_each(|driver| items.push(driver.to_string()));
|
||||
}
|
||||
Mode::InjectDrivers => {
|
||||
select_num = 1;
|
||||
title = String::from("Select Drivers");
|
||||
app.clone
|
||||
.driver_list
|
||||
.iter()
|
||||
.for_each(|driver| items.push(driver.to_string()));
|
||||
}
|
||||
Mode::SelectDisks => {
|
||||
select_num = 1;
|
||||
title = String::from("Select Disk");
|
||||
let disk_list = app.clone.disk_list.lock().unwrap();
|
||||
disk_list
|
||||
.iter()
|
||||
.for_each(|disk| items.push(disk.description.to_string()));
|
||||
}
|
||||
Mode::ScanDisks => {
|
||||
select_num = 0;
|
||||
title = String::from("Processing");
|
||||
}
|
||||
Mode::SelectParts => {
|
||||
select_num = 2;
|
||||
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::BootDiags | Mode::BootSetup | Mode::ToggleSafeMode => {
|
||||
select_num = 0;
|
||||
let (new_title, _) = get_mode_strings(app.cur_mode);
|
||||
title = new_title;
|
||||
}
|
||||
Mode::Done | Mode::Failed => {
|
||||
select_num = 0;
|
||||
title = String::from("Done");
|
||||
}
|
||||
// Invalid states
|
||||
Mode::SelectTableType
|
||||
| Mode::PEMenu
|
||||
| Mode::Confirm
|
||||
| Mode::PreClone
|
||||
| Mode::Clone
|
||||
| Mode::PostClone => {
|
||||
panic!("This shouldn't happen?")
|
||||
}
|
||||
};
|
||||
Action::UpdateLeft(title, labels, items, select_num)
|
||||
}
|
||||
|
||||
fn build_right_items(app: &App) -> Action {
|
||||
let mut items = Vec::new();
|
||||
let mut labels: Vec<Vec<DVLine>> = Vec::new();
|
||||
let mut start_index = 0;
|
||||
match app.cur_mode {
|
||||
Mode::DiagMenu => {
|
||||
app.list.items.iter().for_each(|mode| {
|
||||
let (name, description) = get_mode_strings(*mode);
|
||||
items.push(vec![
|
||||
DVLine {
|
||||
line_parts: vec![name],
|
||||
line_colors: vec![Color::Cyan],
|
||||
},
|
||||
DVLine {
|
||||
line_parts: vec![String::new()],
|
||||
line_colors: vec![Color::Reset],
|
||||
},
|
||||
DVLine {
|
||||
line_parts: vec![description],
|
||||
line_colors: vec![Color::Reset],
|
||||
},
|
||||
]);
|
||||
});
|
||||
}
|
||||
Mode::InjectDrivers | 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 => {
|
||||
let dest_dv_line = DVLine {
|
||||
line_parts: vec![String::from("Disk")],
|
||||
line_colors: vec![Color::Cyan, Color::Red],
|
||||
};
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Action::UpdateRight(labels, start_index, items)
|
||||
}
|
||||
|
||||
fn get_mode_strings(mode: Mode) -> (String, String) {
|
||||
match mode {
|
||||
Mode::BootDiags => (
|
||||
String::from("Boot Diagnostics"),
|
||||
String::from("Check for common Windows boot issues"),
|
||||
),
|
||||
Mode::BootSetup => (
|
||||
String::from("Boot Setup"),
|
||||
String::from("Create or recreate boot files"),
|
||||
),
|
||||
Mode::InjectDrivers => (
|
||||
String::from("Inject Drivers"),
|
||||
String::from("Inject drivers into existing Windows environment"),
|
||||
),
|
||||
Mode::ToggleSafeMode => (
|
||||
String::from("Toggle Safe Mode"),
|
||||
String::from("Enable or disable safe mode"),
|
||||
),
|
||||
_ => panic!("This shouldn't happen"),
|
||||
}
|
||||
}
|
||||
33
boot_diags/src/main.rs
Normal file
33
boot_diags/src/main.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// 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 clap::Parser;
|
||||
use color_eyre::Result;
|
||||
use core;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
mod app;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
core::errors::init()?;
|
||||
core::logging::init()?;
|
||||
|
||||
let args = core::cli::Cli::parse();
|
||||
let mut app = App::new(args.tick_rate, args.frame_rate)?;
|
||||
app.run().await?;
|
||||
Ok(())
|
||||
}
|
||||
154
config/config.json5
Normal file
154
config/config.json5
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
{
|
||||
"app_title": "Deja-vu",
|
||||
"clone_app_path": "C:/Program Files/Some Clone Tool/app.exe",
|
||||
"conemu_path": "C:/Program Files/ConEmu/ConEmu64.exe",
|
||||
"keybindings": {
|
||||
"Home": {
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"ScanDisks": {
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"InstallDrivers": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"SelectDisks": {
|
||||
"<i>": "InstallDriver",
|
||||
"<r>": "ScanDisks",
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"SelectTableType": {
|
||||
"<b>": "PrevScreen",
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"Confirm": {
|
||||
"<b>": "PrevScreen",
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"PreClone": {
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"Clone": {
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"SelectParts": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<s>": "ScanDisks",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"PostClone": {
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"Done": {
|
||||
"<Enter>": "Quit",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"Failed": {
|
||||
"<Enter>": "Quit",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"DiagMenu": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"BootDiags": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"BootSetup": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"InjectDrivers": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"ToggleSafeMode": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
"PEMenu": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<t>": "OpenTerminal",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
},
|
||||
},
|
||||
}
|
||||
63
core/Cargo.toml
Normal file
63
core/Cargo.toml
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# 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/>.
|
||||
|
||||
[package]
|
||||
name = "core"
|
||||
authors = ["2Shirt <2xShirt@gmail.com>"]
|
||||
edition = "2021"
|
||||
license = "GPL"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies]
|
||||
better-panic = "0.3.0"
|
||||
clap = { version = "4.4.5", features = [
|
||||
"derive",
|
||||
"cargo",
|
||||
"wrap_help",
|
||||
"unicode",
|
||||
"string",
|
||||
"unstable-styles",
|
||||
] }
|
||||
color-eyre = "0.6.3"
|
||||
config = "0.15.6"
|
||||
crossterm = { version = "0.28.1", features = ["serde", "event-stream"] }
|
||||
derive_deref = "1.1.1"
|
||||
directories = "6.0.0"
|
||||
futures = "0.3.30"
|
||||
human-panic = "2.0.1"
|
||||
json5 = "0.4.1"
|
||||
lazy_static = "1.5.0"
|
||||
libc = "0.2.158"
|
||||
once_cell = "1.20.2"
|
||||
pretty_assertions = "1.4.0"
|
||||
ratatui = { version = "0.29.0", features = ["serde", "macros"] }
|
||||
raw-cpuid = "11.2.0"
|
||||
regex = "1.11.1"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
serde_json = "1.0.125"
|
||||
signal-hook = "0.3.17"
|
||||
strip-ansi-escapes = "0.2.0"
|
||||
strum = { version = "0.26.3", features = ["derive"] }
|
||||
tempfile = "3.13.0"
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
tokio-util = "0.7.11"
|
||||
tracing = "0.1.41"
|
||||
tracing-error = "0.2.0"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
|
||||
walkdir = "2.5.0"
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = "1.0.86"
|
||||
vergen-gix = { version = "1.0.0", features = ["build", "cargo"] }
|
||||
28
core/build.rs
Normal file
28
core/build.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// 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 anyhow::Result;
|
||||
use vergen_gix::{BuildBuilder, CargoBuilder, Emitter, GixBuilder};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let build = BuildBuilder::all_build()?;
|
||||
let gix = GixBuilder::all_git()?;
|
||||
let cargo = CargoBuilder::all_cargo()?;
|
||||
Emitter::default()
|
||||
.add_instructions(&build)?
|
||||
.add_instructions(&gix)?
|
||||
.add_instructions(&cargo)?
|
||||
.emit()
|
||||
}
|
||||
|
|
@ -16,26 +16,29 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
use strum::Display;
|
||||
|
||||
use crate::{
|
||||
app::Mode,
|
||||
components::popup::Type,
|
||||
system::{
|
||||
disk::{Disk, PartitionTableType},
|
||||
drivers::Driver,
|
||||
},
|
||||
};
|
||||
use crate::{components::popup::Type, line::DVLine, state::Mode, system::disk::Disk};
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
|
||||
pub enum Action {
|
||||
// App
|
||||
// App (Boot-Diags)
|
||||
// TODO: Add actions?
|
||||
// App (Clone)
|
||||
Highlight(usize),
|
||||
InstallDriver,
|
||||
#[default]
|
||||
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>, usize), // (title, labels, items, select_num)
|
||||
// NOTE: select_num should be set to 0, 1, or 2.
|
||||
// 0: For repeating selections
|
||||
// 1: For a single choice
|
||||
// 2: For two selections (obviously)
|
||||
UpdateRight(Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>), // (labels, start_index, items) - items before start are always shown
|
||||
// App (PE-Menu)
|
||||
OpenTerminal,
|
||||
// Screens
|
||||
DismissPopup,
|
||||
DisplayPopup(Type, String),
|
||||
|
|
@ -13,17 +13,13 @@
|
|||
// 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 clap::{Parser, Subcommand};
|
||||
use clap::Parser;
|
||||
|
||||
use crate::config::{get_config_dir, get_data_dir};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version = version(), about)]
|
||||
pub struct Cli {
|
||||
/// App mode
|
||||
#[command(subcommand)]
|
||||
pub cli_cmd: Command,
|
||||
|
||||
/// Tick rate, i.e. number of ticks per second
|
||||
#[arg(short, long, value_name = "FLOAT", default_value_t = 4.0)]
|
||||
pub tick_rate: f64,
|
||||
|
|
@ -33,15 +29,6 @@ pub struct Cli {
|
|||
pub frame_rate: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Subcommand)]
|
||||
pub enum Command {
|
||||
/// Clone Windows from one disk to another
|
||||
Clone,
|
||||
|
||||
/// Diagnose Windows boot issues
|
||||
Diagnose,
|
||||
}
|
||||
|
||||
const VERSION_MESSAGE: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
"-",
|
||||
|
|
@ -21,7 +21,7 @@ use ratatui::{
|
|||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::Component;
|
||||
use crate::{action::Action, app::Mode, config::Config};
|
||||
use crate::{action::Action, config::Config};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Footer {
|
||||
|
|
@ -51,33 +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 {
|
||||
// Clone modes
|
||||
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")
|
||||
}
|
||||
|
||||
// Diagnostic modes
|
||||
Mode::DiagMenu
|
||||
| Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::InjectDrivers
|
||||
| Mode::ToggleSafeBoot => String::from("(q) to quit"),
|
||||
}
|
||||
match action {
|
||||
Action::UpdateFooter(text) => self.text = text,
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
208
core/src/components/left.rs
Normal file
208
core/src/components/left.rs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// 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 color_eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
widgets::{Block, Borders, HighlightSpacing, List, ListItem, Padding, Paragraph},
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::{state::StatefulList, Component};
|
||||
use crate::{action::Action, config::Config};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Left {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
config: Config,
|
||||
labels: Vec<String>,
|
||||
list: StatefulList<String>,
|
||||
select_num: usize,
|
||||
selections: Vec<Option<usize>>,
|
||||
selections_saved: Vec<Option<usize>>,
|
||||
title_text: String,
|
||||
}
|
||||
|
||||
impl Left {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
select_num: 0,
|
||||
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 {
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
|
||||
let _ = key; // to appease clippy
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
self.command_tx = Some(tx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_config_handler(&mut self, config: Config) -> Result<()> {
|
||||
self.config = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
match action {
|
||||
Action::Highlight(index) => self.set_highlight(index),
|
||||
Action::KeyUp => self.list.previous(),
|
||||
Action::KeyDown => self.list.next(),
|
||||
Action::Process => {
|
||||
if self.select_num == 0 {
|
||||
// Selections aren't being used so this is a no-op
|
||||
} else 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_num == 1 {
|
||||
// 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)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => 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::SetMode(_) => {
|
||||
self.selections[0] = None;
|
||||
self.selections[1] = None;
|
||||
}
|
||||
Action::UpdateLeft(title, labels, items, select_num) => {
|
||||
self.title_text = title;
|
||||
self.labels = labels
|
||||
.iter()
|
||||
.map(|label| format!(" ~{}~", label.to_lowercase()))
|
||||
.collect();
|
||||
self.list.set_items(items);
|
||||
self.select_num = select_num;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
let [title_area, body_area] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(1), Constraint::Min(1)])
|
||||
.areas(area);
|
||||
|
||||
// Title
|
||||
let title_text = if self.selections[1].is_some() || self.select_num == 1 {
|
||||
"Confirm Selections"
|
||||
} else {
|
||||
self.title_text.as_str()
|
||||
};
|
||||
let title =
|
||||
Paragraph::new(Line::from(Span::styled(title_text, Style::default())).centered())
|
||||
.block(Block::default().borders(Borders::NONE));
|
||||
frame.render_widget(title, title_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(());
|
||||
}
|
||||
|
||||
// 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(())
|
||||
}
|
||||
}
|
||||
|
|
@ -23,7 +23,7 @@ use strum::Display;
|
|||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::Component;
|
||||
use crate::{action::Action, app::Mode, config::Config};
|
||||
use crate::{action::Action, config::Config};
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
|
||||
pub enum Type {
|
||||
|
|
@ -37,17 +37,13 @@ pub enum Type {
|
|||
pub struct Popup {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
config: Config,
|
||||
mode: Mode,
|
||||
popup_type: Type,
|
||||
popup_text: String,
|
||||
}
|
||||
|
||||
impl Popup {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
popup_text: String::new(),
|
||||
..Default::default()
|
||||
}
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -67,13 +63,7 @@ impl Component for Popup {
|
|||
Action::DismissPopup => self.popup_text.clear(),
|
||||
Action::DisplayPopup(new_type, new_text) => {
|
||||
self.popup_type = new_type;
|
||||
self.popup_text = new_text;
|
||||
}
|
||||
Action::SetMode(mode) => {
|
||||
if mode == Mode::ScanDisks {
|
||||
self.popup_text = String::from("Scanning Disks...");
|
||||
}
|
||||
self.mode = mode;
|
||||
self.popup_text = format!("\n{new_text}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
198
core/src/components/right.rs
Normal file
198
core/src/components/right.rs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
// 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 color_eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
widgets::{Block, Borders, Padding, Paragraph, Wrap},
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::{state::StatefulList, Component};
|
||||
use crate::{action::Action, config::Config, line::DVLine};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Right {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
config: Config,
|
||||
list_header: Vec<DVLine>,
|
||||
list_labels: Vec<Vec<DVLine>>,
|
||||
list: StatefulList<Vec<DVLine>>,
|
||||
selections: Vec<Option<usize>>,
|
||||
selections_saved: Vec<Option<usize>>,
|
||||
title: String,
|
||||
}
|
||||
|
||||
impl Right {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
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 {
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
|
||||
let _ = key; // to appease clippy
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
self.command_tx = Some(tx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_config_handler(&mut self, config: Config) -> Result<()> {
|
||||
self.config = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
match action {
|
||||
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;
|
||||
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::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());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
let [title_area, body_area] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(1), Constraint::Min(1)])
|
||||
.areas(area);
|
||||
|
||||
// Title
|
||||
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<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 })
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.padding(Padding::new(1, 1, 1, 1)),
|
||||
);
|
||||
frame.render_widget(body, body_area);
|
||||
|
||||
// Done
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -21,23 +21,19 @@ use ratatui::{
|
|||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
use super::Component;
|
||||
use crate::{action::Action, cli, config::Config};
|
||||
use crate::{action::Action, config::Config};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Title {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
config: Config,
|
||||
title_text: String,
|
||||
text: String,
|
||||
}
|
||||
|
||||
impl Title {
|
||||
pub fn new(cli_cmd: cli::Command) -> Self {
|
||||
let title_text = match cli_cmd {
|
||||
cli::Command::Clone => String::from("Deja-Vu: Clone"),
|
||||
cli::Command::Diagnose => String::from("Deja-Vu: Diagnostics"),
|
||||
};
|
||||
pub fn new(text: &str) -> Self {
|
||||
Self {
|
||||
title_text,
|
||||
text: String::from(text),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
|
@ -54,16 +50,19 @@ impl Component for Title {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
// fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
// match action {
|
||||
// _ => {}
|
||||
// }
|
||||
// Ok(None)
|
||||
// }
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
match action {
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
// Title Block
|
||||
let title_text = Span::styled(&self.title_text, Style::default().fg(Color::LightCyan));
|
||||
let title_text = Span::styled(
|
||||
format!("{}: {}", self.config.app_title.as_str(), self.text),
|
||||
Style::default().fg(Color::LightCyan),
|
||||
);
|
||||
let title = Paragraph::new(Line::from(title_text).centered())
|
||||
.block(Block::default().borders(Borders::ALL));
|
||||
frame.render_widget(title, area);
|
||||
|
|
@ -26,9 +26,9 @@ use ratatui::style::{Color, Modifier, Style};
|
|||
use serde::{de::Deserializer, Deserialize};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{action::Action, app::Mode};
|
||||
use crate::{action::Action, state::Mode};
|
||||
|
||||
const CONFIG: &str = include_str!("../config/config.json5");
|
||||
const CONFIG: &str = include_str!("../../config/config.json5");
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Default)]
|
||||
pub struct AppConfig {
|
||||
|
|
@ -40,8 +40,12 @@ pub struct AppConfig {
|
|||
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub app_title: String,
|
||||
#[serde(default)]
|
||||
pub clone_app_path: PathBuf,
|
||||
#[serde(default)]
|
||||
pub conemu_path: PathBuf,
|
||||
#[serde(default, flatten)]
|
||||
pub config: AppConfig,
|
||||
#[serde(default)]
|
||||
|
|
@ -50,14 +54,15 @@ pub struct Config {
|
|||
pub styles: Styles,
|
||||
}
|
||||
|
||||
pub static PROJECT_NAME: &'static str = "DEJA-VU";
|
||||
lazy_static! {
|
||||
pub static ref PROJECT_NAME: String = env!("CARGO_CRATE_NAME").to_uppercase().to_string();
|
||||
//pub static ref PROJECT_NAME: String = env!("CARGO_PKG_NAME").to_uppercase().to_string();
|
||||
pub static ref DATA_FOLDER: Option<PathBuf> =
|
||||
env::var(format!("{}_DATA", PROJECT_NAME.clone()))
|
||||
env::var(format!("{}_DATA", PROJECT_NAME))
|
||||
.ok()
|
||||
.map(PathBuf::from);
|
||||
pub static ref CONFIG_FOLDER: Option<PathBuf> =
|
||||
env::var(format!("{}_CONFIG", PROJECT_NAME.clone()))
|
||||
env::var(format!("{}_CONFIG", PROJECT_NAME))
|
||||
.ok()
|
||||
.map(PathBuf::from);
|
||||
}
|
||||
|
|
@ -68,12 +73,17 @@ impl Config {
|
|||
let data_dir = get_data_dir();
|
||||
let config_dir = get_config_dir();
|
||||
let mut builder = config::Config::builder()
|
||||
.set_default("data_dir", data_dir.to_str().unwrap())?
|
||||
.set_default("config_dir", config_dir.to_str().unwrap())?
|
||||
.set_default("app_title", default_config.app_title.as_str())?
|
||||
.set_default(
|
||||
"clone_app_path",
|
||||
String::from("C:\\Program Files\\Some Clone Tool\\app.exe"),
|
||||
)?;
|
||||
)?
|
||||
.set_default(
|
||||
"conemu_path",
|
||||
String::from("C:\\Program Files\\ConEmu\\ConEmu64.exe"),
|
||||
)?
|
||||
.set_default("config_dir", config_dir.to_str().unwrap())?
|
||||
.set_default("data_dir", data_dir.to_str().unwrap())?;
|
||||
|
||||
let config_files = [
|
||||
("config.json5", config::FileFormat::Json5),
|
||||
|
|
@ -95,7 +105,6 @@ impl Config {
|
|||
if !found_config {
|
||||
error!("No configuration file found. Application may not behave as expected");
|
||||
}
|
||||
|
||||
let mut cfg: Self = builder.build()?.try_deserialize()?;
|
||||
|
||||
for (mode, default_bindings) in default_config.keybindings.iter() {
|
||||
|
|
@ -140,7 +149,8 @@ pub fn get_config_dir() -> PathBuf {
|
|||
}
|
||||
|
||||
fn project_directory() -> Option<ProjectDirs> {
|
||||
ProjectDirs::from("com", "WizardKit", env!("CARGO_PKG_NAME"))
|
||||
ProjectDirs::from("com", "Deja-vu", "deja-vu")
|
||||
//ProjectDirs::from("com", "Deja-vu", env!("CARGO_PKG_NAME"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deref, DerefMut)]
|
||||
|
|
@ -525,7 +535,7 @@ mod tests {
|
|||
let c = Config::new()?;
|
||||
assert_eq!(
|
||||
c.keybindings
|
||||
.get(&Mode::ScanDisks) // i.e. Home
|
||||
.get(&Mode::Home) // i.e. Home
|
||||
.unwrap()
|
||||
.get(&parse_key_sequence("<q>").unwrap_or_default())
|
||||
.unwrap(),
|
||||
|
|
@ -13,17 +13,14 @@
|
|||
// You should have received a copy of the GNU General Public License
|
||||
// along with Deja-vu. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
/// Application.
|
||||
pub mod app;
|
||||
|
||||
/// Terminal events handler.
|
||||
pub mod event;
|
||||
|
||||
/// Widget renderer.
|
||||
pub mod ui;
|
||||
|
||||
/// Terminal user interface.
|
||||
pub mod action;
|
||||
pub mod cli;
|
||||
pub mod components;
|
||||
pub mod config;
|
||||
pub mod errors;
|
||||
pub mod line;
|
||||
pub mod logging;
|
||||
pub mod state;
|
||||
pub mod system;
|
||||
pub mod tasks;
|
||||
pub mod tui;
|
||||
|
||||
/// Event handler.
|
||||
pub mod handler;
|
||||
94
core/src/line.rs
Normal file
94
core/src/line.rs
Normal 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
|
||||
}
|
||||
|
|
@ -20,8 +20,9 @@ use tracing_subscriber::{fmt, prelude::*, EnvFilter};
|
|||
use crate::config;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref LOG_ENV: String = format!("{}_LOG_LEVEL", config::PROJECT_NAME.clone());
|
||||
pub static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
|
||||
pub static ref LOG_ENV: String = format!("{}_LOG_LEVEL", config::PROJECT_NAME);
|
||||
pub static ref LOG_FILE: String = format!("{}.log", config::PROJECT_NAME.to_lowercase());
|
||||
//pub static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
|
||||
}
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
76
core/src/state.rs
Normal file
76
core/src/state.rs
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
// 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 std::sync::{Arc, Mutex};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::system::{
|
||||
disk::{Disk, PartitionTableType},
|
||||
drivers,
|
||||
};
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Mode {
|
||||
// Core
|
||||
#[default]
|
||||
Home,
|
||||
Done,
|
||||
Failed,
|
||||
// Boot Diags
|
||||
DiagMenu,
|
||||
BootDiags,
|
||||
BootSetup,
|
||||
InjectDrivers,
|
||||
ToggleSafeMode,
|
||||
// Clone
|
||||
ScanDisks,
|
||||
InstallDrivers,
|
||||
SelectDisks,
|
||||
SelectTableType,
|
||||
Confirm,
|
||||
PreClone,
|
||||
Clone,
|
||||
SelectParts,
|
||||
PostClone,
|
||||
// WinPE
|
||||
PEMenu,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
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<drivers::Driver>,
|
||||
pub table_type: Option<PartitionTableType>,
|
||||
}
|
||||
|
||||
impl CloneSettings {
|
||||
pub fn new(disk_list: Arc<Mutex<Vec<Disk>>>) -> Self {
|
||||
CloneSettings {
|
||||
disk_list,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scan_drivers(&mut self) {
|
||||
self.driver_list = drivers::scan();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
export DEJA_VU_CONFIG=`pwd`/config
|
||||
export DEJA_VU_DATA=`pwd`/data
|
||||
export DEJA_VU_LOG_LEVEL=debug
|
||||
|
|
@ -16,51 +16,30 @@
|
|||
[package]
|
||||
name = "deja-vu"
|
||||
authors = ["2Shirt <2xShirt@gmail.com>"]
|
||||
description = "Clone Windows."
|
||||
edition = "2021"
|
||||
license = "GPL"
|
||||
version = "0.2.0"
|
||||
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
better-panic = "0.3.0"
|
||||
clap = { version = "4.4.5", features = [
|
||||
"derive",
|
||||
"cargo",
|
||||
"wrap_help",
|
||||
"unicode",
|
||||
"string",
|
||||
"unstable-styles",
|
||||
] }
|
||||
core = { path = "../core" }
|
||||
color-eyre = "0.6.3"
|
||||
config = "0.14.0"
|
||||
crossterm = { version = "0.28.1", features = ["serde", "event-stream"] }
|
||||
derive_deref = "1.1.1"
|
||||
directories = "5.0.1"
|
||||
futures = "0.3.30"
|
||||
human-panic = "2.0.1"
|
||||
json5 = "0.4.1"
|
||||
lazy_static = "1.5.0"
|
||||
libc = "0.2.158"
|
||||
once_cell = "1.20.2"
|
||||
pretty_assertions = "1.4.0"
|
||||
ratatui = { version = "0.28.1", features = ["serde", "macros"] }
|
||||
raw-cpuid = "11.2.0"
|
||||
regex = "1.11.1"
|
||||
serde = { version = "1.0.208", features = ["derive"] }
|
||||
clap = { version = "4.4.5", features = [
|
||||
"derive",
|
||||
"cargo",
|
||||
"wrap_help",
|
||||
"unicode",
|
||||
"string",
|
||||
"unstable-styles",
|
||||
] }
|
||||
ratatui = { version = "0.29.0", features = ["serde", "macros"] }
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
serde_json = "1.0.125"
|
||||
signal-hook = "0.3.17"
|
||||
strip-ansi-escapes = "0.2.0"
|
||||
strum = { version = "0.26.3", features = ["derive"] }
|
||||
tempfile = "3.13.0"
|
||||
tokio = { version = "1.39.3", features = ["full"] }
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
tokio-util = "0.7.11"
|
||||
tracing = "0.1.40"
|
||||
tracing = "0.1.41"
|
||||
tracing-error = "0.2.0"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
|
||||
walkdir = "2.5.0"
|
||||
rand = "0.8.5"
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = "1.0.86"
|
||||
|
|
|
|||
|
|
@ -1,130 +0,0 @@
|
|||
{
|
||||
"clone_app_path": "C:/Program Files/Some Clone Tool/app.exe",
|
||||
"keybindings": {
|
||||
"ScanDisks": {
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"InstallDrivers": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"SelectDisks": {
|
||||
"<i>": "InstallDriver",
|
||||
"<r>": "ScanDisks",
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"SelectTableType": {
|
||||
"<b>": "PrevScreen",
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"Confirm": {
|
||||
"<b>": "PrevScreen",
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"PreClone": {
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"Clone": {
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"SelectParts": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<s>": "ScanDisks", // Start over
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"PostClone": {
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"Done": {
|
||||
"<Enter>": "Quit",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"Failed": {
|
||||
"<Enter>": "Quit",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
// Diagnostic modes
|
||||
"DiagMenu": {
|
||||
"<Enter>": "Process",
|
||||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<i>": "InstallDriver",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"BootDiags": {
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"BootSetup": {
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"InjectDrivers": {
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
"ToggleSafeBoot": {
|
||||
"<Enter>": "Process",
|
||||
"<q>": "Quit", // Quit the application
|
||||
"<Ctrl-d>": "Quit", // Another way to quit
|
||||
"<Ctrl-c>": "Quit", // Yet another way to quit
|
||||
"<Ctrl-z>": "Suspend" // Suspend the application
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -12,7 +12,23 @@
|
|||
//
|
||||
// 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 core::{
|
||||
action::Action,
|
||||
components::{
|
||||
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, cpu::get_cpu_name, disk::PartitionTableType, diskpart::build_dest_format_script,
|
||||
drivers,
|
||||
},
|
||||
tasks::{Task, Tasks},
|
||||
tui::{Event, Tui},
|
||||
};
|
||||
use std::{
|
||||
env,
|
||||
iter::zip,
|
||||
|
|
@ -20,32 +36,16 @@ use std::{
|
|||
};
|
||||
|
||||
use color_eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use rand::random;
|
||||
use ratatui::{
|
||||
crossterm::event::KeyEvent,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
prelude::Rect,
|
||||
style::Color,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, info};
|
||||
|
||||
use crate::{
|
||||
action::Action,
|
||||
cli,
|
||||
components::{
|
||||
footer::Footer, fps::FpsCounter, left::Left, popup, right::Right, title::Title, Component,
|
||||
},
|
||||
config::Config,
|
||||
system::{
|
||||
boot,
|
||||
disk::{Disk, PartitionTableType},
|
||||
diskpart::build_dest_format_script,
|
||||
drivers::{self, Driver},
|
||||
},
|
||||
tasks::{Task, Tasks},
|
||||
tui::{Event, Tui},
|
||||
};
|
||||
|
||||
pub struct App {
|
||||
// TUI
|
||||
action_rx: mpsc::UnboundedReceiver<Action>,
|
||||
|
|
@ -58,61 +58,31 @@ pub struct App {
|
|||
should_suspend: bool,
|
||||
tick_rate: f64,
|
||||
// App
|
||||
cli_cmd: cli::Command,
|
||||
clone: CloneSettings,
|
||||
cur_mode: Mode,
|
||||
disk_index_dest: Option<usize>,
|
||||
disk_index_source: Option<usize>,
|
||||
disk_list: Arc<Mutex<Vec<Disk>>>,
|
||||
part_index_boot: Option<usize>,
|
||||
part_index_os: Option<usize>,
|
||||
driver: Option<Driver>,
|
||||
list: StatefulList<usize>,
|
||||
prev_mode: Mode,
|
||||
selections: Vec<Option<usize>>,
|
||||
table_type: Option<PartitionTableType>,
|
||||
tasks: Tasks,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Mode {
|
||||
#[default]
|
||||
ScanDisks,
|
||||
InstallDrivers,
|
||||
SelectDisks,
|
||||
SelectTableType,
|
||||
Confirm,
|
||||
PreClone,
|
||||
Clone,
|
||||
SelectParts,
|
||||
PostClone,
|
||||
Done,
|
||||
Failed,
|
||||
// Diagnostic modes
|
||||
DiagMenu,
|
||||
BootDiags,
|
||||
BootSetup,
|
||||
InjectDrivers,
|
||||
ToggleSafeBoot,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(cli_cmd: cli::Command, tick_rate: f64, frame_rate: f64) -> Result<Self> {
|
||||
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
|
||||
let (action_tx, action_rx) = mpsc::unbounded_channel();
|
||||
let disk_list_arc = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
|
||||
tasks.add(Task::ScanDisks);
|
||||
let tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
|
||||
Ok(Self {
|
||||
// TUI
|
||||
action_rx,
|
||||
action_tx,
|
||||
components: vec![
|
||||
Box::new(Title::new(cli_cmd)),
|
||||
Box::new(Title::new("Clone Tool")),
|
||||
Box::new(FpsCounter::new()),
|
||||
Box::new(Left::new()),
|
||||
Box::new(Right::new()),
|
||||
Box::new(Footer::new()),
|
||||
Box::new(popup::Popup::new()),
|
||||
],
|
||||
cli_cmd,
|
||||
config: Config::new()?,
|
||||
frame_rate,
|
||||
last_tick_key_events: Vec::new(),
|
||||
|
|
@ -120,73 +90,67 @@ impl App {
|
|||
should_suspend: false,
|
||||
tick_rate,
|
||||
// App
|
||||
cur_mode: match cli_cmd {
|
||||
cli::Command::Clone => Mode::ScanDisks,
|
||||
cli::Command::Diagnose => Mode::DiagMenu,
|
||||
},
|
||||
disk_index_dest: None,
|
||||
disk_index_source: None,
|
||||
disk_list: disk_list_arc,
|
||||
driver: None,
|
||||
part_index_boot: None,
|
||||
part_index_os: None,
|
||||
prev_mode: Mode::ScanDisks,
|
||||
clone: CloneSettings::new(disk_list_arc),
|
||||
cur_mode: Mode::default(),
|
||||
list: StatefulList::default(),
|
||||
prev_mode: Mode::default(),
|
||||
selections: vec![None, None],
|
||||
table_type: None,
|
||||
tasks,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn next_mode(&mut self) -> Option<Mode> {
|
||||
info!(
|
||||
"Prev Mode: {:?} // Cur Mode: {:?}",
|
||||
self.prev_mode, self.cur_mode
|
||||
);
|
||||
let new_mode = match (self.prev_mode, self.cur_mode) {
|
||||
// Clone states
|
||||
(_, Mode::InstallDrivers) => self.prev_mode,
|
||||
(_, 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,
|
||||
|
||||
// Diagnostic states
|
||||
(
|
||||
_,
|
||||
Mode::DiagMenu
|
||||
| Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::InjectDrivers
|
||||
| Mode::ToggleSafeBoot,
|
||||
) => Mode::DiagMenu,
|
||||
|
||||
pub fn prev_mode(&mut self) -> Option<Mode> {
|
||||
let new_mode = match self.cur_mode {
|
||||
Mode::Home => Some(Mode::Home),
|
||||
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),
|
||||
// Disallowed moves
|
||||
Mode::InstallDrivers
|
||||
| Mode::ScanDisks
|
||||
| Mode::PreClone
|
||||
| Mode::Clone
|
||||
| Mode::PostClone => None,
|
||||
// Invalid states
|
||||
(_, Mode::Confirm) => panic!("This shouldn't happen."),
|
||||
Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::DiagMenu
|
||||
| Mode::InjectDrivers
|
||||
| Mode::PEMenu
|
||||
| Mode::ToggleSafeMode => panic!("This shouldn't happen?"),
|
||||
};
|
||||
new_mode
|
||||
}
|
||||
|
||||
pub fn next_mode(&mut self) -> Option<Mode> {
|
||||
let new_mode = match self.cur_mode {
|
||||
Mode::Home => Mode::ScanDisks,
|
||||
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,
|
||||
// Invalid states
|
||||
Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::DiagMenu
|
||||
| Mode::InjectDrivers
|
||||
| Mode::PEMenu
|
||||
| Mode::ToggleSafeMode => panic!("This shouldn't happen?"),
|
||||
};
|
||||
|
||||
if new_mode == self.cur_mode {
|
||||
// No mode change needed
|
||||
None
|
||||
} else {
|
||||
match self.cur_mode {
|
||||
// Update prev_mode if appropriate
|
||||
Mode::Confirm => {}
|
||||
Mode::PreClone | Mode::Clone | Mode::PostClone | Mode::Done => {
|
||||
// Override since we're past the point of no return
|
||||
self.prev_mode = self.cur_mode;
|
||||
}
|
||||
_ => self.prev_mode = self.cur_mode,
|
||||
}
|
||||
Some(new_mode)
|
||||
}
|
||||
}
|
||||
|
|
@ -195,11 +159,16 @@ 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() {
|
||||
self.tasks.add(Task::ScanDisks);
|
||||
}
|
||||
self.action_tx.send(Action::DisplayPopup(
|
||||
popup::Type::Info,
|
||||
String::from("Scanning Disks..."),
|
||||
))?;
|
||||
}
|
||||
Mode::PreClone => {
|
||||
self.action_tx.send(Action::DisplayPopup(
|
||||
|
|
@ -208,10 +177,10 @@ impl App {
|
|||
))?;
|
||||
|
||||
// Build Diskpart script to format destination disk
|
||||
let disk_list = self.disk_list.lock().unwrap();
|
||||
if let Some(disk_index) = self.disk_index_dest {
|
||||
let disk_list = self.clone.disk_list.lock().unwrap();
|
||||
if let Some(disk_index) = self.clone.disk_index_dest {
|
||||
if let Some(disk) = disk_list.get(disk_index) {
|
||||
let table_type = self.table_type.clone().unwrap();
|
||||
let table_type = self.clone.table_type.clone().unwrap();
|
||||
let diskpart_script = build_dest_format_script(disk.id, &table_type);
|
||||
self.tasks.add(Task::Diskpart(diskpart_script));
|
||||
}
|
||||
|
|
@ -226,7 +195,7 @@ impl App {
|
|||
self.config.clone_app_path.clone(),
|
||||
Vec::new(),
|
||||
));
|
||||
if let Some(dest_index) = self.disk_index_dest {
|
||||
if let Some(dest_index) = self.clone.disk_index_dest {
|
||||
self.tasks.add(Task::UpdateDestDisk(dest_index));
|
||||
}
|
||||
}
|
||||
|
|
@ -251,12 +220,12 @@ impl App {
|
|||
};
|
||||
|
||||
// Add actions
|
||||
let disk_list = self.disk_list.lock().unwrap();
|
||||
if let Some(disk_index) = self.disk_index_dest {
|
||||
let disk_list = self.clone.disk_list.lock().unwrap();
|
||||
if let Some(disk_index) = self.clone.disk_index_dest {
|
||||
if let Some(disk) = disk_list.get(disk_index) {
|
||||
let table_type = self.table_type.clone().unwrap();
|
||||
let letter_boot = disk.get_part_letter(self.part_index_boot.unwrap());
|
||||
let letter_os = disk.get_part_letter(self.part_index_os.unwrap());
|
||||
let table_type = self.clone.table_type.clone().unwrap();
|
||||
let letter_boot = disk.get_part_letter(self.clone.part_index_boot.unwrap());
|
||||
let letter_os = disk.get_part_letter(self.clone.part_index_os.unwrap());
|
||||
|
||||
// Safety check
|
||||
if letter_boot.is_empty() || letter_os.is_empty() {
|
||||
|
|
@ -274,7 +243,7 @@ impl App {
|
|||
}
|
||||
|
||||
// Inject driver(s) (if selected)
|
||||
if let Some(driver) = &self.driver {
|
||||
if let Some(driver) = &self.clone.driver {
|
||||
if let Ok(task) = boot::inject_driver(driver, &letter_os, &system32) {
|
||||
self.tasks.add(task);
|
||||
} else {
|
||||
|
|
@ -288,10 +257,8 @@ impl App {
|
|||
}
|
||||
}
|
||||
Mode::Done => {
|
||||
self.action_tx.send(Action::DisplayPopup(
|
||||
popup::Type::Success,
|
||||
String::from("COMPLETE\n\n\nThank you for using this tool!"),
|
||||
))?;
|
||||
self.action_tx
|
||||
.send(Action::DisplayPopup(popup::Type::Success, fortune()))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -316,17 +283,7 @@ impl App {
|
|||
}
|
||||
|
||||
let action_tx = self.action_tx.clone();
|
||||
// Init based on cli::Command
|
||||
match self.cli_cmd {
|
||||
cli::Command::Clone => {
|
||||
action_tx.send(Action::SetMode(Mode::ScanDisks))?;
|
||||
}
|
||||
cli::Command::Diagnose => {
|
||||
self.prev_mode = Mode::DiagMenu;
|
||||
action_tx.send(Action::SetMode(Mode::DiagMenu))?;
|
||||
}
|
||||
}
|
||||
|
||||
action_tx.send(Action::SetMode(Mode::ScanDisks))?;
|
||||
loop {
|
||||
self.handle_events(&mut tui).await?;
|
||||
self.handle_actions(&mut tui)?;
|
||||
|
|
@ -408,6 +365,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()))?;
|
||||
|
|
@ -416,47 +375,109 @@ impl App {
|
|||
Action::InstallDriver => {
|
||||
self.action_tx.send(Action::SetMode(Mode::InstallDrivers))?;
|
||||
}
|
||||
Action::SelectDriver(ref driver) => {
|
||||
self.driver = Some(driver.clone());
|
||||
drivers::load(&driver.inf_paths);
|
||||
self.action_tx.send(Action::NextScreen)?;
|
||||
}
|
||||
Action::SelectTableType(ref table_type) => {
|
||||
self.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))?;
|
||||
}
|
||||
Action::NextScreen => {
|
||||
if let Some(mode) = self.next_mode() {
|
||||
self.action_tx.send(Action::DismissPopup)?;
|
||||
self.action_tx.send(Action::SetMode(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 => {}
|
||||
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))?;
|
||||
}
|
||||
},
|
||||
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.disk_index_source = one;
|
||||
self.disk_index_dest = two;
|
||||
self.clone.disk_index_source = one;
|
||||
self.clone.disk_index_dest = two;
|
||||
}
|
||||
Mode::SelectParts => {
|
||||
self.part_index_boot = one;
|
||||
self.part_index_os = two;
|
||||
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) => {
|
||||
// Clear TableType selection
|
||||
match new_mode {
|
||||
Mode::SelectDisks | Mode::SelectTableType => {
|
||||
self.clone.table_type = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.set_mode(new_mode)?;
|
||||
self.action_tx
|
||||
.send(Action::UpdateFooter(build_footer_string(self.cur_mode)))?;
|
||||
self.action_tx.send(build_left_items(self, self.cur_mode))?;
|
||||
self.action_tx
|
||||
.send(build_right_items(self, self.cur_mode))?;
|
||||
match new_mode {
|
||||
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 {
|
||||
|
|
@ -548,3 +569,188 @@ fn get_chunks(r: Rect) -> Vec<Rect> {
|
|||
// Done
|
||||
chunks
|
||||
}
|
||||
|
||||
fn build_footer_string(cur_mode: Mode) -> String {
|
||||
match cur_mode {
|
||||
Mode::Home | 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"),
|
||||
// Invalid states
|
||||
Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::DiagMenu
|
||||
| Mode::InjectDrivers
|
||||
| Mode::PEMenu
|
||||
| Mode::ToggleSafeMode => panic!("This shouldn't happen?"),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_left_items(app: &App, cur_mode: Mode) -> Action {
|
||||
let select_num: usize;
|
||||
let title: String;
|
||||
let mut items = Vec::new();
|
||||
let mut labels: Vec<String> = Vec::new();
|
||||
match cur_mode {
|
||||
Mode::Home => {
|
||||
select_num = 0;
|
||||
title = String::from("Home");
|
||||
}
|
||||
Mode::InstallDrivers => {
|
||||
select_num = 1;
|
||||
title = String::from("Install Drivers");
|
||||
app.clone
|
||||
.driver_list
|
||||
.iter()
|
||||
.for_each(|driver| items.push(driver.to_string()));
|
||||
}
|
||||
Mode::SelectDisks => {
|
||||
select_num = 2;
|
||||
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 => {
|
||||
select_num = 1;
|
||||
title = String::from("Select Partition Table Type");
|
||||
items.push(format!("{}", PartitionTableType::Guid));
|
||||
items.push(format!("{}", PartitionTableType::Legacy));
|
||||
}
|
||||
Mode::Confirm => {
|
||||
select_num = 0;
|
||||
title = String::from("Confirm Selections");
|
||||
}
|
||||
Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => {
|
||||
select_num = 0;
|
||||
title = String::from("Processing");
|
||||
}
|
||||
Mode::SelectParts => {
|
||||
select_num = 2;
|
||||
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 => {
|
||||
select_num = 0;
|
||||
title = String::from("Done");
|
||||
}
|
||||
// Invalid states
|
||||
Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::DiagMenu
|
||||
| Mode::InjectDrivers
|
||||
| Mode::PEMenu
|
||||
| Mode::ToggleSafeMode => panic!("This shouldn't happen?"),
|
||||
};
|
||||
Action::UpdateLeft(title, labels, items, select_num)
|
||||
}
|
||||
|
||||
fn build_right_items(app: &App, cur_mode: Mode) -> Action {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Action::UpdateRight(labels, start_index, items)
|
||||
}
|
||||
|
||||
fn fortune() -> String {
|
||||
String::from(match random::<u8>() / 4 {
|
||||
0 => "FUN FACT\n\n\nComputers barely work.",
|
||||
1 => "CRASH OVERRIDE\n\n\n\"Hack the planet!\"",
|
||||
2 => "CATS\n\n\n\"All your base are belong to us!\"",
|
||||
3 => "HMM\n\n\nThis has all happened before...\n\nThis will all happen again.",
|
||||
4 => "CYPHER\n\n\n\"I don’t even see the code. All I see is blonde, brunette, red-head.\"",
|
||||
5 => "CONGRATULATIONS\n\n\nYour did it!",
|
||||
6 => "DID YOU KNOW?\n\n\nmacOS includes a built-in screen reader!",
|
||||
7 => "TIP OF THE DAY\n\n\nNever go full Snappy!",
|
||||
8 => "WORDS OF WISDOM\n\n\n\nIt’s not DNS,\n\nThere’s no way it’s DNS,\n\nIt was DNS.",
|
||||
9 => "HAL 9000\n\n\n\"I'm sorry Dave, I'm afraid I can't do that.\"",
|
||||
_ => "COMPLETE\n\n\nThank you for using this tool!",
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,464 +0,0 @@
|
|||
use std::fmt;
|
||||
|
||||
// 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 color_eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
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,
|
||||
app::Mode,
|
||||
config::Config,
|
||||
system::{
|
||||
disk::{Disk, Partition, PartitionTableType},
|
||||
drivers::{self, Driver},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DiagMenu {
|
||||
name: String,
|
||||
action: Action,
|
||||
}
|
||||
|
||||
impl fmt::Display for DiagMenu {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", &self.name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Left {
|
||||
command_tx: Option<UnboundedSender<Action>>,
|
||||
config: Config,
|
||||
diag_menu: StatefulList<DiagMenu>,
|
||||
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,
|
||||
selections: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
impl Left {
|
||||
pub fn new() -> Self {
|
||||
let menu_entries = vec![
|
||||
DiagMenu {
|
||||
name: String::from("Boot Diagnostics"),
|
||||
action: Action::SetMode(Mode::BootDiags),
|
||||
},
|
||||
DiagMenu {
|
||||
name: String::from("Boot Setup"),
|
||||
action: Action::SetMode(Mode::BootSetup),
|
||||
},
|
||||
DiagMenu {
|
||||
name: String::from("Inject Drivers"),
|
||||
action: Action::SetMode(Mode::InjectDrivers),
|
||||
},
|
||||
DiagMenu {
|
||||
name: String::from("Toggle Safe Mode"),
|
||||
action: Action::SetMode(Mode::ToggleSafeBoot),
|
||||
},
|
||||
];
|
||||
let mut diag_menu = StatefulList::default();
|
||||
diag_menu.set_items(menu_entries);
|
||||
Self {
|
||||
diag_menu,
|
||||
selections: vec![None, None],
|
||||
title_text: String::from("Home"),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Left {
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
|
||||
let _ = key; // to appease clippy
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
self.command_tx = Some(tx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_config_handler(&mut self, config: Config) -> Result<()> {
|
||||
self.config = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update(&mut self, action: Action) -> Result<Option<Action>> {
|
||||
match action {
|
||||
Action::KeyUp => match self.mode {
|
||||
Mode::DiagMenu => self.diag_menu.previous(),
|
||||
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::DiagMenu => self.diag_menu.next(),
|
||||
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::DiagMenu
|
||||
| Mode::InstallDrivers
|
||||
| Mode::SelectDisks
|
||||
| Mode::SelectTableType
|
||||
| Mode::SelectParts => {
|
||||
// Menu selection sections
|
||||
let selection: Option<usize> = match self.mode {
|
||||
Mode::DiagMenu => self.diag_menu.selected(),
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send selection(s) if needed
|
||||
// NOTE: This is needed to keep the app and all components in sync
|
||||
match self.mode {
|
||||
Mode::DiagMenu => {
|
||||
// Only need to select one entry
|
||||
if let Some(entry) = self.diag_menu.get_selected() {
|
||||
command_tx.send(entry.action)?;
|
||||
}
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Mode::BootDiags | Mode::BootSetup | Mode::InjectDrivers | Mode::ToggleSafeBoot => {
|
||||
if let Some(command_tx) = self.command_tx.clone() {
|
||||
command_tx.send(Action::NextScreen)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
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"),
|
||||
// Diagnostic states
|
||||
(_, Mode::DiagMenu) => self.title_text = String::from("Main Menu"),
|
||||
(_, Mode::BootDiags) => self.title_text = String::from("Boot Diagnostics"),
|
||||
(_, Mode::BootSetup) => self.title_text = String::from("Boot Setup"),
|
||||
(_, Mode::InjectDrivers) => self.title_text = String::from("Inject Drivers"),
|
||||
(_, Mode::ToggleSafeBoot) => self.title_text = String::from("Toggle Safe Mode"),
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
let [title_area, body_area] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(1), Constraint::Min(1)])
|
||||
.areas(area);
|
||||
|
||||
// Title
|
||||
let title =
|
||||
Paragraph::new(Line::from(Span::styled(&self.title_text, Style::default())).centered())
|
||||
.block(Block::default().borders(Borders::NONE));
|
||||
frame.render_widget(title, title_area);
|
||||
|
||||
// Body
|
||||
match self.mode {
|
||||
// Clone modes
|
||||
Mode::ScanDisks
|
||||
| Mode::PreClone
|
||||
| Mode::Clone
|
||||
| Mode::PostClone
|
||||
// Diagnostic modes
|
||||
| Mode::BootDiags
|
||||
| Mode::BootSetup
|
||||
| Mode::InjectDrivers
|
||||
| Mode::ToggleSafeBoot
|
||||
// Done
|
||||
| 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);
|
||||
|
||||
// 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::DiagMenu
|
||||
| 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::DiagMenu=> self
|
||||
.diag_menu
|
||||
.items
|
||||
.iter()
|
||||
.map(|i| format!("{i}"))
|
||||
.collect(),
|
||||
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::DiagMenu=> {
|
||||
frame.render_stateful_widget(list, body_area, &mut self.diag_menu.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
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,401 +0,0 @@
|
|||
// 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 color_eyre::Result;
|
||||
use crossterm::event::KeyEvent;
|
||||
use ratatui::{
|
||||
prelude::*,
|
||||
widgets::{Block, Borders, Padding, Paragraph, Wrap},
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tracing::info;
|
||||
|
||||
use super::{state::StatefulList, Component};
|
||||
use crate::{
|
||||
action::Action,
|
||||
app::Mode,
|
||||
config::Config,
|
||||
system::{
|
||||
cpu::get_cpu_name,
|
||||
disk::{Disk, Partition, PartitionTableType},
|
||||
},
|
||||
};
|
||||
|
||||
#[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>>,
|
||||
selections: Vec<Option<usize>>,
|
||||
table_type: Option<PartitionTableType>,
|
||||
}
|
||||
|
||||
impl Right {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
selected_disks: vec![None, None],
|
||||
selections: vec![None, None],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Right {
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
|
||||
let _ = key; // to appease clippy
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
|
||||
self.command_tx = Some(tx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn register_config_handler(&mut self, config: Config) -> Result<()> {
|
||||
self.config = config;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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.clone_from(&self.selections);
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
|
||||
let [title_area, body_area] = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([Constraint::Length(1), Constraint::Min(1)])
|
||||
.areas(area);
|
||||
|
||||
// Title
|
||||
let title_text = String::from("Info");
|
||||
let title = Paragraph::new(Line::from(title_text).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 body = Paragraph::new(body_text)
|
||||
.style(Style::default().fg(Color::Gray))
|
||||
.wrap(Wrap { trim: false })
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.padding(Padding::new(1, 1, 1, 1)),
|
||||
);
|
||||
frame.render_widget(body, body_area);
|
||||
|
||||
// Done
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -14,30 +14,20 @@
|
|||
// along with Deja-vu. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
use clap::Parser;
|
||||
use cli::Cli;
|
||||
use color_eyre::Result;
|
||||
use core;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
mod action;
|
||||
mod app;
|
||||
mod cli;
|
||||
mod components;
|
||||
mod config;
|
||||
mod errors;
|
||||
mod logging;
|
||||
mod system;
|
||||
mod tasks;
|
||||
mod tests;
|
||||
mod tui;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
crate::errors::init()?;
|
||||
crate::logging::init()?;
|
||||
core::errors::init()?;
|
||||
core::logging::init()?;
|
||||
|
||||
let args = Cli::parse();
|
||||
let mut app = App::new(args.cli_cmd, args.tick_rate, args.frame_rate)?;
|
||||
let args = core::cli::Cli::parse();
|
||||
let mut app = App::new(args.tick_rate, args.frame_rate)?;
|
||||
app.run().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
name = 'Deja-Vu'
|
||||
command = 'X:\tools\deja-vu.exe'
|
||||
description = "Windows clone assistant tool"
|
||||
use_conemu = true
|
||||
separator = false
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
name = ''
|
||||
command = ''
|
||||
description = ''
|
||||
use_conemu = false
|
||||
separator = true
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
name = 'NTPWEdit'
|
||||
command = 'X:\Program Files\NTPWEdit\ntpwedit.exe'
|
||||
description = 'Mostly used to unlock the built-in admin account'
|
||||
use_conemu = false
|
||||
separator = false
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
name = 'Some Clone Tool'
|
||||
command = 'X:\Program Files\Some\Tool.exe'
|
||||
description = 'Run Some Clone tool'
|
||||
use_conemu = false
|
||||
separator = false
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
name = 'Task Manager'
|
||||
command = 'X:\Windows\System32\taskmgr.exe'
|
||||
description = 'Manage those tasks'
|
||||
use_conemu = false
|
||||
separator = false
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
# 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/>.
|
||||
|
||||
con_emu = 'X:\Program Files\ConEmu\ConEmu64.exe'
|
||||
tools = []
|
||||
|
|
@ -16,15 +16,31 @@
|
|||
[package]
|
||||
name = "pe-menu"
|
||||
authors = ["2Shirt <2xShirt@gmail.com>"]
|
||||
description = "Menu for WinPE."
|
||||
edition = "2021"
|
||||
license = "GPL"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
|
||||
[dependencies]
|
||||
crossterm = { version = "0.27.0", features = ["event-stream"] }
|
||||
core = { path = "../core" }
|
||||
clap = { version = "4.4.5", features = [
|
||||
"derive",
|
||||
"cargo",
|
||||
"wrap_help",
|
||||
"unicode",
|
||||
"string",
|
||||
"unstable-styles",
|
||||
] }
|
||||
color-eyre = "0.6.3"
|
||||
crossterm = { version = "0.28.1", features = ["event-stream"] }
|
||||
futures = "0.3.30"
|
||||
ratatui = "0.26.0"
|
||||
serde = { version = "1.0.202", features = ["derive"] }
|
||||
tokio = { version = "1.35.1", features = ["full"] }
|
||||
ratatui = "0.29.0"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
tokio = { version = "1.43.0", features = ["full"] }
|
||||
toml = "0.8.13"
|
||||
tracing = "0.1.41"
|
||||
tracing-error = "0.2.0"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "serde"] }
|
||||
|
||||
[build-dependencies]
|
||||
anyhow = "1.0.86"
|
||||
vergen-gix = { version = "1.0.0", features = ["build", "cargo"] }
|
||||
|
|
|
|||
28
pe_menu/build.rs
Normal file
28
pe_menu/build.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
// 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 anyhow::Result;
|
||||
use vergen_gix::{BuildBuilder, CargoBuilder, Emitter, GixBuilder};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let build = BuildBuilder::all_build()?;
|
||||
let gix = GixBuilder::all_git()?;
|
||||
let cargo = CargoBuilder::all_cargo()?;
|
||||
Emitter::default()
|
||||
.add_instructions(&build)?
|
||||
.add_instructions(&gix)?
|
||||
.add_instructions(&cargo)?
|
||||
.emit()
|
||||
}
|
||||
|
|
@ -13,354 +13,418 @@
|
|||
// 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::widgets::ListState;
|
||||
use serde::Deserialize;
|
||||
use core::{
|
||||
action::Action,
|
||||
components::{
|
||||
footer::Footer, fps::FpsCounter, left::Left, popup, right::Right, state::StatefulList,
|
||||
title::Title, Component,
|
||||
},
|
||||
config::Config,
|
||||
line::DVLine,
|
||||
state::Mode,
|
||||
tasks::{Task, Tasks},
|
||||
tui::{Event, Tui},
|
||||
};
|
||||
use std::{
|
||||
env, error, fs, io,
|
||||
env, fs,
|
||||
iter::zip,
|
||||
path::PathBuf,
|
||||
process::{Command, Output},
|
||||
thread::{self, JoinHandle},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
/// Application result type.
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
|
||||
use color_eyre::Result;
|
||||
use ratatui::{
|
||||
crossterm::event::KeyEvent,
|
||||
layout::{Constraint, Direction, Layout},
|
||||
prelude::Rect,
|
||||
style::Color,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// Application exit reasons
|
||||
#[derive(Debug, Default)]
|
||||
pub enum QuitReason {
|
||||
#[default]
|
||||
Exit,
|
||||
Poweroff,
|
||||
Restart,
|
||||
}
|
||||
|
||||
/// Config
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Config {
|
||||
con_emu: String,
|
||||
tools: Vec<Tool>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic for many reasons
|
||||
#[must_use]
|
||||
pub fn load() -> Option<Config> {
|
||||
// Main config
|
||||
let exe_path = env::current_exe().expect("Failed to find main executable");
|
||||
let contents = fs::read_to_string(exe_path.with_file_name("pe-menu.toml"))
|
||||
.expect("Failed to load config file");
|
||||
let mut new_config: Config =
|
||||
toml::from_str(&contents).expect("Failed to parse config file");
|
||||
|
||||
// Tools
|
||||
let tool_config_path = exe_path.parent().unwrap().join("menu_entries");
|
||||
let mut entries: Vec<PathBuf> = std::fs::read_dir(tool_config_path)
|
||||
.expect("Failed to find any tool configs")
|
||||
.map(|res| res.map(|e| e.path()))
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
entries.sort();
|
||||
for entry in entries {
|
||||
let contents = fs::read_to_string(&entry).expect("Failed to read tool config file");
|
||||
let tool: Tool = toml::from_str(&contents).expect("Failed to parse tool config file");
|
||||
new_config.tools.push(tool);
|
||||
}
|
||||
|
||||
// Done
|
||||
Some(new_config)
|
||||
}
|
||||
}
|
||||
|
||||
/// `PopUp`
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct PopUp {
|
||||
pub title: String,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl PopUp {
|
||||
#[must_use]
|
||||
pub fn new(title: &str, body: &str) -> PopUp {
|
||||
PopUp {
|
||||
title: String::from(title),
|
||||
body: String::from(body),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Tool`
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, Deserialize)]
|
||||
pub struct Tool {
|
||||
name: String,
|
||||
command: String,
|
||||
description: String,
|
||||
args: Option<Vec<String>>,
|
||||
use_conemu: bool,
|
||||
separator: bool,
|
||||
}
|
||||
|
||||
/// `MenuEntry`
|
||||
#[derive(Default, Debug, Clone, PartialEq)]
|
||||
pub struct MenuEntry {
|
||||
pub name: String,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
pub use_conemu: bool,
|
||||
pub separator: bool,
|
||||
}
|
||||
|
||||
impl MenuEntry {
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
name: &str,
|
||||
command: &str,
|
||||
args: Option<Vec<String>>,
|
||||
use_conemu: bool,
|
||||
separator: bool,
|
||||
) -> MenuEntry {
|
||||
let mut my_args = Vec::new();
|
||||
if let Some(a) = args {
|
||||
my_args.clone_from(&a);
|
||||
}
|
||||
MenuEntry {
|
||||
name: String::from(name),
|
||||
command: String::from(command),
|
||||
args: my_args,
|
||||
use_conemu,
|
||||
separator,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `StatefulList`
|
||||
#[derive(Default, Debug, Clone, PartialEq)]
|
||||
pub struct StatefulList<T> {
|
||||
pub state: ListState,
|
||||
pub items: Vec<T>,
|
||||
pub last_selected: Option<usize>,
|
||||
}
|
||||
|
||||
impl<T: Clone> StatefulList<T> {
|
||||
#[must_use]
|
||||
pub fn new() -> StatefulList<T> {
|
||||
StatefulList {
|
||||
state: ListState::default(),
|
||||
items: Vec::new(),
|
||||
last_selected: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn get_selected(&self) -> Option<&T> {
|
||||
if let Some(i) = self.state.selected() {
|
||||
self.items.get(i)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pop_selected(&mut self) -> Option<T> {
|
||||
if let Some(i) = self.state.selected() {
|
||||
Some(self.items[i].clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn select_first_item(&mut self) {
|
||||
if self.items.is_empty() {
|
||||
self.state.select(None);
|
||||
} else {
|
||||
self.state.select(Some(0));
|
||||
}
|
||||
self.last_selected = None;
|
||||
}
|
||||
|
||||
pub fn set_items(&mut self, items: Vec<T>) {
|
||||
// Clear list and rebuild with provided items
|
||||
self.items.clear();
|
||||
for item in items {
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
// Reset state and select first item (if available)
|
||||
self.state = ListState::default();
|
||||
self.select_first_item();
|
||||
}
|
||||
|
||||
pub fn next(&mut self) {
|
||||
if self.items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let i = match self.state.selected() {
|
||||
Some(i) => {
|
||||
if i >= self.items.len() - 1 {
|
||||
0
|
||||
} else {
|
||||
i + 1
|
||||
}
|
||||
}
|
||||
None => self.last_selected.unwrap_or(0),
|
||||
};
|
||||
self.state.select(Some(i));
|
||||
}
|
||||
|
||||
pub fn previous(&mut self) {
|
||||
if self.items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let i = match self.state.selected() {
|
||||
Some(i) => {
|
||||
if i == 0 {
|
||||
self.items.len() - 1
|
||||
} else {
|
||||
i - 1
|
||||
}
|
||||
}
|
||||
None => self.last_selected.unwrap_or(0),
|
||||
};
|
||||
self.state.select(Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// Application.
|
||||
#[derive(Debug)]
|
||||
pub struct App {
|
||||
pub config: Config,
|
||||
pub main_menu: StatefulList<MenuEntry>,
|
||||
pub popup: Option<PopUp>,
|
||||
pub quit_reason: QuitReason,
|
||||
pub running: bool,
|
||||
pub thread_pool: Vec<JoinHandle<Result<Output, io::Error>>>,
|
||||
}
|
||||
|
||||
impl Default for App {
|
||||
fn default() -> Self {
|
||||
let config = Config::load();
|
||||
Self {
|
||||
config: config.unwrap(),
|
||||
running: true,
|
||||
quit_reason: QuitReason::Exit,
|
||||
main_menu: StatefulList::new(),
|
||||
popup: None,
|
||||
thread_pool: Vec::new(),
|
||||
}
|
||||
}
|
||||
// TUI
|
||||
action_rx: mpsc::UnboundedReceiver<Action>,
|
||||
action_tx: mpsc::UnboundedSender<Action>,
|
||||
components: Vec<Box<dyn Component>>,
|
||||
config: Config,
|
||||
frame_rate: f64,
|
||||
last_tick_key_events: Vec<KeyEvent>,
|
||||
should_quit: bool,
|
||||
should_suspend: bool,
|
||||
tick_rate: f64,
|
||||
// App
|
||||
list: StatefulList<Tool>,
|
||||
mode: Mode,
|
||||
tasks: Tasks,
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Constructs a new instance of [`App`].
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
let mut app = Self::default();
|
||||
|
||||
// Add MenuEntries
|
||||
for tool in &app.config.tools {
|
||||
app.main_menu.items.push(MenuEntry::new(
|
||||
&tool.name,
|
||||
&tool.command,
|
||||
tool.args.clone(),
|
||||
tool.use_conemu,
|
||||
tool.separator,
|
||||
));
|
||||
}
|
||||
app.main_menu.select_first_item();
|
||||
|
||||
// Done
|
||||
app
|
||||
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
|
||||
let (action_tx, action_rx) = mpsc::unbounded_channel();
|
||||
let disk_list_arc = Arc::new(Mutex::new(Vec::new()));
|
||||
let tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
|
||||
let mut list = StatefulList::default();
|
||||
list.set_items(load_tools());
|
||||
Ok(Self {
|
||||
// TUI
|
||||
action_rx,
|
||||
action_tx,
|
||||
components: vec![
|
||||
Box::new(Title::new("PE Menu")),
|
||||
Box::new(FpsCounter::new()),
|
||||
Box::new(Left::new()),
|
||||
Box::new(Right::new()),
|
||||
Box::new(Footer::new()),
|
||||
Box::new(popup::Popup::new()),
|
||||
],
|
||||
config: Config::new()?,
|
||||
frame_rate,
|
||||
last_tick_key_events: Vec::new(),
|
||||
should_quit: false,
|
||||
should_suspend: false,
|
||||
tick_rate,
|
||||
// App
|
||||
list,
|
||||
mode: Mode::default(),
|
||||
tasks,
|
||||
})
|
||||
}
|
||||
|
||||
/// Handles the tick event of the terminal.
|
||||
pub fn tick(&self) {}
|
||||
pub async fn run(&mut self) -> Result<()> {
|
||||
let mut tui = Tui::new()?
|
||||
// .mouse(true) // uncomment this line to enable mouse support
|
||||
.tick_rate(self.tick_rate)
|
||||
.frame_rate(self.frame_rate);
|
||||
tui.enter()?;
|
||||
|
||||
/// Actually exit application
|
||||
///
|
||||
/// # Errors
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if wpeutil fails to reboot or shutdown
|
||||
pub fn exit(&self) -> Result<(), &'static str> {
|
||||
let mut argument: Option<String> = None;
|
||||
match self.quit_reason {
|
||||
QuitReason::Exit => {}
|
||||
QuitReason::Poweroff => argument = Some(String::from("shutdown")),
|
||||
QuitReason::Restart => argument = Some(String::from("reboot")),
|
||||
for component in &mut self.components {
|
||||
component.register_action_handler(self.action_tx.clone())?;
|
||||
}
|
||||
if let Some(a) = argument {
|
||||
Command::new("wpeutil")
|
||||
.arg(a)
|
||||
.output()
|
||||
.expect("Failed to run exit command");
|
||||
for component in &mut self.components {
|
||||
component.register_config_handler(self.config.clone())?;
|
||||
}
|
||||
for component in &mut self.components {
|
||||
component.init(tui.size()?)?;
|
||||
}
|
||||
|
||||
let action_tx = self.action_tx.clone();
|
||||
action_tx.send(Action::SetMode(Mode::PEMenu))?;
|
||||
loop {
|
||||
self.handle_events(&mut tui).await?;
|
||||
self.handle_actions(&mut tui)?;
|
||||
if self.should_suspend {
|
||||
tui.suspend()?;
|
||||
action_tx.send(Action::Resume)?;
|
||||
action_tx.send(Action::ClearScreen)?;
|
||||
// tui.mouse(true);
|
||||
tui.enter()?;
|
||||
} else if self.should_quit {
|
||||
tui.stop()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
tui.exit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_events(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
let Some(event) = tui.next_event().await else {
|
||||
return Ok(());
|
||||
};
|
||||
let action_tx = self.action_tx.clone();
|
||||
match event {
|
||||
Event::Quit => action_tx.send(Action::Quit)?,
|
||||
Event::Tick => action_tx.send(Action::Tick)?,
|
||||
Event::Render => action_tx.send(Action::Render)?,
|
||||
Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
|
||||
Event::Key(key) => self.handle_key_event(key)?,
|
||||
_ => {}
|
||||
}
|
||||
for component in &mut self.components {
|
||||
if let Some(action) = component.handle_events(Some(event.clone()))? {
|
||||
action_tx.send(action)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set running to false to quit the application.
|
||||
pub fn quit(&mut self, reason: QuitReason) {
|
||||
self.running = false;
|
||||
self.quit_reason = reason;
|
||||
}
|
||||
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if command fails to run
|
||||
pub fn open_terminal(&mut self) {
|
||||
Command::new("cmd.exe")
|
||||
.arg("-new_console:n")
|
||||
.output()
|
||||
.expect("Failed to run command");
|
||||
}
|
||||
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if menu entry isn't found
|
||||
pub fn run_tool(&mut self) {
|
||||
// Command
|
||||
let tool: &MenuEntry;
|
||||
if let Some(index) = self.main_menu.state.selected() {
|
||||
tool = &self.main_menu.items[index];
|
||||
} else {
|
||||
self.popup = Some(PopUp::new(
|
||||
"Failed to find menu entry",
|
||||
"Check for an updated version of Deja-Vu",
|
||||
));
|
||||
return;
|
||||
}
|
||||
let command = if tool.use_conemu {
|
||||
self.config.con_emu.clone()
|
||||
} else {
|
||||
tool.command.clone()
|
||||
fn handle_key_event(&mut self, key: KeyEvent) -> Result<()> {
|
||||
let action_tx = self.action_tx.clone();
|
||||
let Some(keymap) = self.config.keybindings.get(&self.mode) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Separators
|
||||
if tool.separator {
|
||||
return;
|
||||
}
|
||||
|
||||
// Args
|
||||
let mut args = tool.args.clone();
|
||||
if tool.use_conemu {
|
||||
args.insert(0, tool.command.clone());
|
||||
args.push(String::from("-new_console:n"));
|
||||
}
|
||||
|
||||
// Check path
|
||||
let command_path = PathBuf::from(&command);
|
||||
if let Ok(true) = command_path.try_exists() {
|
||||
// File path exists
|
||||
if let Some(action) = keymap.get(&vec![key]) {
|
||||
info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
} else {
|
||||
// File path doesn't exist or is a broken symlink/etc
|
||||
// The latter case would be Ok(false) rather than Err(_)
|
||||
self.popup = Some(PopUp::new("Tool Missing", &format!("Tool path: {command}")));
|
||||
return;
|
||||
}
|
||||
// If the key was not handled as a single key action,
|
||||
// then consider it for multi-key combinations.
|
||||
self.last_tick_key_events.push(key);
|
||||
|
||||
// Run
|
||||
// TODO: This really needs refactored to use channels so we can properly check if the
|
||||
// command fails.
|
||||
let new_thread = thread::spawn(move || Command::new(command_path).args(args).output());
|
||||
self.thread_pool.push(new_thread);
|
||||
// Check for multi-key combinations
|
||||
if let Some(action) = keymap.get(&self.last_tick_key_events) {
|
||||
info!("Got action: {action:?}");
|
||||
action_tx.send(action.clone())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_actions(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
while let Ok(action) = self.action_rx.try_recv() {
|
||||
if action != Action::Tick && action != Action::Render {
|
||||
debug!("{action:?}");
|
||||
}
|
||||
match action {
|
||||
Action::Tick => {
|
||||
self.last_tick_key_events.drain(..);
|
||||
// Check background task(s)
|
||||
self.tasks.poll()?;
|
||||
}
|
||||
Action::Quit => self.should_quit = true,
|
||||
Action::Suspend => self.should_suspend = true,
|
||||
Action::Resume => self.should_suspend = false,
|
||||
Action::ClearScreen => tui.terminal.clear()?,
|
||||
Action::KeyUp => {
|
||||
self.list.previous();
|
||||
if let Some(tool) = self.list.get_selected() {
|
||||
if tool.separator {
|
||||
// Skip over separator
|
||||
self.list.previous();
|
||||
if let Some(index) = self.list.selected() {
|
||||
self.action_tx.send(Action::Highlight(index))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Action::KeyDown => {
|
||||
self.list.next();
|
||||
if let Some(tool) = self.list.get_selected() {
|
||||
if tool.separator {
|
||||
// Skip over separator
|
||||
self.list.next();
|
||||
if let Some(index) = self.list.selected() {
|
||||
self.action_tx.send(Action::Highlight(index))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Action::Error(ref msg) => {
|
||||
self.action_tx
|
||||
.send(Action::DisplayPopup(popup::Type::Error, msg.clone()))?;
|
||||
self.action_tx.send(Action::SetMode(Mode::Failed))?;
|
||||
}
|
||||
Action::Process => {
|
||||
// Run selected tool
|
||||
if let Some(tool) = self.list.get_selected() {
|
||||
info!("Run tool: {:?}", &tool);
|
||||
self.tasks.add(build_command(&self, &tool));
|
||||
}
|
||||
}
|
||||
Action::Resize(w, h) => self.handle_resize(tui, w, h)?,
|
||||
Action::Render => self.render(tui)?,
|
||||
Action::SetMode(mode) => {
|
||||
self.mode = mode;
|
||||
self.action_tx
|
||||
.send(Action::UpdateFooter(String::from("(Enter) to select")))?;
|
||||
self.action_tx.send(build_left_items(self))?;
|
||||
self.action_tx.send(build_right_items(self))?;
|
||||
self.action_tx.send(Action::Select(None, None))?;
|
||||
}
|
||||
Action::OpenTerminal => {
|
||||
self.tasks.add(Task::Command(
|
||||
PathBuf::from("cmd.exe"),
|
||||
vec![String::from("-new_console:n")],
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for component in &mut self.components {
|
||||
if let Some(action) = component.update(action.clone())? {
|
||||
self.action_tx.send(action)?;
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_resize(&mut self, tui: &mut Tui, w: u16, h: u16) -> Result<()> {
|
||||
tui.resize(Rect::new(0, 0, w, h))?;
|
||||
self.render(tui)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&mut self, tui: &mut Tui) -> Result<()> {
|
||||
tui.draw(|frame| {
|
||||
if let [header, _body, footer, left, right, popup] = get_chunks(frame.area())[..] {
|
||||
let component_areas = vec![
|
||||
header, // Title Bar
|
||||
header, // FPS Counter
|
||||
left, right, footer, popup,
|
||||
];
|
||||
for (component, area) in zip(self.components.iter_mut(), component_areas) {
|
||||
if let Err(err) = component.draw(frame, area) {
|
||||
let _ = self
|
||||
.action_tx
|
||||
.send(Action::Error(format!("Failed to draw: {err:?}")));
|
||||
}
|
||||
}
|
||||
};
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
// Cut the given rectangle into three vertical pieces
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
// Then cut the middle vertical piece into three width-wise pieces
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1] // Return the middle chunk
|
||||
}
|
||||
|
||||
fn get_chunks(r: Rect) -> Vec<Rect> {
|
||||
let mut chunks: Vec<Rect> = Vec::with_capacity(6);
|
||||
|
||||
// Main sections
|
||||
chunks.extend(
|
||||
Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(3),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(r)
|
||||
.to_vec(),
|
||||
);
|
||||
|
||||
// Left/Right
|
||||
chunks.extend(
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
|
||||
.split(centered_rect(90, 90, chunks[1]))
|
||||
.to_vec(),
|
||||
);
|
||||
|
||||
// Popup
|
||||
chunks.push(centered_rect(60, 25, r));
|
||||
|
||||
// Done
|
||||
chunks
|
||||
}
|
||||
|
||||
pub fn build_command(app: &App, tool: &Tool) -> Task {
|
||||
let cmd_path: PathBuf;
|
||||
let mut cmd_args: Vec<String> = Vec::new();
|
||||
let start_index: usize;
|
||||
if tool.use_conemu {
|
||||
cmd_path = app.config.conemu_path.clone();
|
||||
cmd_args.push(String::from("-new_console:n"));
|
||||
cmd_args.push(tool.command.clone());
|
||||
start_index = 1;
|
||||
} else {
|
||||
cmd_path = PathBuf::from(tool.command.clone());
|
||||
start_index = 0;
|
||||
}
|
||||
if let Some(args) = &tool.args {
|
||||
if args.len() > start_index {
|
||||
args[start_index..].iter().for_each(|a| {
|
||||
cmd_args.push(a.clone());
|
||||
});
|
||||
}
|
||||
}
|
||||
Task::Command(cmd_path, cmd_args)
|
||||
}
|
||||
|
||||
fn build_left_items(app: &App) -> Action {
|
||||
let title = String::from("Tools");
|
||||
let labels = vec![String::new(), String::new()];
|
||||
let items = app
|
||||
.list
|
||||
.items
|
||||
.iter()
|
||||
.map(|tool| {
|
||||
if tool.separator {
|
||||
String::from("──────────────")
|
||||
} else {
|
||||
tool.name.clone()
|
||||
}
|
||||
})
|
||||
// ─
|
||||
.collect();
|
||||
Action::UpdateLeft(title, labels, items, 0)
|
||||
}
|
||||
|
||||
fn build_right_items(app: &App) -> Action {
|
||||
let labels: Vec<Vec<DVLine>> = Vec::new();
|
||||
let items = app
|
||||
.list
|
||||
.items
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
vec![
|
||||
DVLine {
|
||||
line_parts: vec![entry.name.clone()],
|
||||
line_colors: vec![Color::Cyan],
|
||||
},
|
||||
DVLine {
|
||||
line_parts: vec![String::new()],
|
||||
line_colors: vec![Color::Reset],
|
||||
},
|
||||
DVLine {
|
||||
line_parts: vec![entry.description.clone()],
|
||||
line_colors: vec![Color::Reset],
|
||||
},
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
let start_index = 0;
|
||||
Action::UpdateRight(labels, start_index, items)
|
||||
}
|
||||
|
||||
pub fn load_tools() -> Vec<Tool> {
|
||||
let exe_path = env::current_exe().expect("Failed to find main executable");
|
||||
let tool_config_path = exe_path.parent().unwrap().join("menu_entries");
|
||||
let mut entries: Vec<PathBuf> = std::fs::read_dir(tool_config_path)
|
||||
.expect("Failed to find any tool configs")
|
||||
.map(|res| res.map(|e| e.path()))
|
||||
.filter_map(Result::ok)
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let contents = fs::read_to_string(&entry).expect("Failed to read tool config file");
|
||||
let tool: Tool = toml::from_str(&contents).expect("Failed to parse tool config file");
|
||||
tool
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,116 +0,0 @@
|
|||
// 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 std::time::Duration;
|
||||
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyEvent, MouseEvent};
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::app::AppResult;
|
||||
|
||||
/// Terminal events.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Event {
|
||||
/// Terminal tick.
|
||||
Tick,
|
||||
/// Key press.
|
||||
Key(KeyEvent),
|
||||
/// Mouse click/scroll.
|
||||
Mouse(MouseEvent),
|
||||
/// Terminal resize.
|
||||
Resize(u16, u16),
|
||||
}
|
||||
|
||||
/// Terminal event handler.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub struct Handler {
|
||||
/// Event sender channel.
|
||||
sender: mpsc::UnboundedSender<Event>,
|
||||
/// Event receiver channel.
|
||||
receiver: mpsc::UnboundedReceiver<Event>,
|
||||
/// Event handler thread.
|
||||
handler: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Handler {
|
||||
/// Constructs a new instance of [`Handler`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if `sender_clone ` doesn't unwrap
|
||||
#[must_use]
|
||||
pub fn new(tick_rate: u64) -> Self {
|
||||
let tick_rate = Duration::from_millis(tick_rate);
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
let sender_clone = sender.clone();
|
||||
let handler = tokio::spawn(async move {
|
||||
let mut reader = crossterm::event::EventStream::new();
|
||||
let mut tick = tokio::time::interval(tick_rate);
|
||||
loop {
|
||||
let tick_delay = tick.tick();
|
||||
let crossterm_event = reader.next().fuse();
|
||||
tokio::select! {
|
||||
() = sender_clone.closed() => {
|
||||
break;
|
||||
}
|
||||
_ = tick_delay => {
|
||||
sender_clone.send(Event::Tick).unwrap();
|
||||
}
|
||||
Some(Ok(evt)) = crossterm_event => {
|
||||
match evt {
|
||||
CrosstermEvent::Key(key) => {
|
||||
if key.kind == crossterm::event::KeyEventKind::Press {
|
||||
sender_clone.send(Event::Key(key)).unwrap();
|
||||
}
|
||||
},
|
||||
CrosstermEvent::Mouse(mouse) => {
|
||||
sender_clone.send(Event::Mouse(mouse)).unwrap();
|
||||
},
|
||||
CrosstermEvent::Resize(x, y) => {
|
||||
sender_clone.send(Event::Resize(x, y)).unwrap();
|
||||
},
|
||||
CrosstermEvent::FocusGained | CrosstermEvent::FocusLost | CrosstermEvent::Paste(_) => {},
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
Self {
|
||||
sender,
|
||||
receiver,
|
||||
handler,
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive the next event from the handler thread.
|
||||
///
|
||||
/// This function will always block the current thread if
|
||||
/// there is no data available and it's possible for more data to be sent.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Will return error if a event is not found
|
||||
pub async fn next(&mut self) -> AppResult<Event> {
|
||||
self.receiver
|
||||
.recv()
|
||||
.await
|
||||
.ok_or(Box::new(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"This is an IO error",
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
// 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 crate::app::{App, QuitReason};
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
|
||||
/// Handles the key events and updates the state of [`App`].
|
||||
pub fn handle_key_events(key_event: KeyEvent, app: &mut App) {
|
||||
match key_event.code {
|
||||
KeyCode::F(5) => app.quit(QuitReason::Exit),
|
||||
KeyCode::Char('p' | 'P') => app.quit(QuitReason::Poweroff),
|
||||
KeyCode::Char('r' | 'R') => app.quit(QuitReason::Restart),
|
||||
KeyCode::Char('t' | 'T') => app.open_terminal(),
|
||||
KeyCode::Up => {
|
||||
if app.popup.is_none() {
|
||||
app.main_menu.previous();
|
||||
if let Some(e) = app.main_menu.get_selected() {
|
||||
if e.separator {
|
||||
// Skip over separators
|
||||
app.main_menu.previous();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Down => {
|
||||
if app.popup.is_none() {
|
||||
app.main_menu.next();
|
||||
if let Some(e) = app.main_menu.get_selected() {
|
||||
if e.separator {
|
||||
// Skip over separators
|
||||
app.main_menu.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if app.popup.is_some() {
|
||||
// Clear popup and return to main menu
|
||||
app.popup = None;
|
||||
} else {
|
||||
app.run_tool();
|
||||
}
|
||||
}
|
||||
KeyCode::Esc | KeyCode::Char('q' | 'Q') => {
|
||||
app.popup = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
@ -13,40 +13,21 @@
|
|||
// 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 pe_menu::app::{App, AppResult};
|
||||
use pe_menu::event::{Event, Handler};
|
||||
use pe_menu::handler::handle_key_events;
|
||||
use pe_menu::tui::Tui;
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::Terminal;
|
||||
use std::io;
|
||||
use clap::Parser;
|
||||
use color_eyre::Result;
|
||||
use core;
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
mod app;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> AppResult<()> {
|
||||
// Create an application.
|
||||
let mut app = App::new();
|
||||
async fn main() -> Result<()> {
|
||||
core::errors::init()?;
|
||||
core::logging::init()?;
|
||||
|
||||
// Initialize the terminal user interface.
|
||||
let backend = CrosstermBackend::new(io::stderr());
|
||||
let terminal = Terminal::new(backend)?;
|
||||
let events = Handler::new(250);
|
||||
let mut tui = Tui::new(terminal, events);
|
||||
tui.init()?;
|
||||
|
||||
// Start the main loop.
|
||||
while app.running {
|
||||
// Render the user interface.
|
||||
tui.draw(&mut app)?;
|
||||
// Handle events.
|
||||
match tui.events.next().await? {
|
||||
Event::Tick => app.tick(),
|
||||
Event::Key(key_event) => handle_key_events(key_event, &mut app),
|
||||
Event::Mouse(_) | Event::Resize(_, _) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Exit the user interface.
|
||||
tui.exit()?;
|
||||
app.exit()?;
|
||||
let args = core::cli::Cli::parse();
|
||||
let mut app = App::new(args.tick_rate, args.frame_rate)?;
|
||||
app.run().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,111 +0,0 @@
|
|||
// 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 crate::app::{App, AppResult};
|
||||
use crate::event::Handler;
|
||||
use crate::ui;
|
||||
use crossterm::event::{DisableMouseCapture, EnableMouseCapture};
|
||||
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
|
||||
use ratatui::backend::Backend;
|
||||
use ratatui::Terminal;
|
||||
use std::io;
|
||||
use std::panic;
|
||||
|
||||
/// Representation of a terminal user interface.
|
||||
///
|
||||
/// It is responsible for setting up the terminal,
|
||||
/// initializing the interface and handling the draw events.
|
||||
#[derive(Debug)]
|
||||
pub struct Tui<B: Backend> {
|
||||
/// Interface to the Terminal.
|
||||
terminal: Terminal<B>,
|
||||
/// Terminal event handler.
|
||||
pub events: Handler,
|
||||
}
|
||||
|
||||
impl<B: Backend> Tui<B> {
|
||||
/// Constructs a new instance of [`Tui`].
|
||||
pub fn new(terminal: Terminal<B>, events: Handler) -> Self {
|
||||
Self { terminal, events }
|
||||
}
|
||||
|
||||
/// Initializes the terminal interface.
|
||||
///
|
||||
/// It enables the raw mode and sets terminal properties.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Will return error if `enable_raw_mode` fails
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if `reset` fails
|
||||
pub fn init(&mut self) -> AppResult<()> {
|
||||
terminal::enable_raw_mode()?;
|
||||
crossterm::execute!(io::stderr(), EnterAlternateScreen, EnableMouseCapture)?;
|
||||
|
||||
// Define a custom panic hook to reset the terminal properties.
|
||||
// This way, you won't have your terminal messed up if an unexpected error happens.
|
||||
let panic_hook = panic::take_hook();
|
||||
panic::set_hook(Box::new(move |panic| {
|
||||
Self::reset().expect("failed to reset the terminal");
|
||||
panic_hook(panic);
|
||||
}));
|
||||
|
||||
self.terminal.hide_cursor()?;
|
||||
self.terminal.clear()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Draw`] the terminal interface by [`rendering`] the widgets.
|
||||
///
|
||||
/// [`Draw`]: ratatui::Terminal::draw
|
||||
/// [`rendering`]: crate::ui::render
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Will return error if `draw` fails
|
||||
pub fn draw(&mut self, app: &mut App) -> AppResult<()> {
|
||||
self.terminal.draw(|frame| ui::render(app, frame))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resets the terminal interface.
|
||||
///
|
||||
/// This function is also used for the panic hook to revert
|
||||
/// the terminal properties if unexpected errors occur.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Will return error if `disable_raw_mode` fails
|
||||
fn reset() -> AppResult<()> {
|
||||
terminal::disable_raw_mode()?;
|
||||
crossterm::execute!(io::stderr(), LeaveAlternateScreen, DisableMouseCapture)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Exits the terminal interface.
|
||||
///
|
||||
/// It disables the raw mode and reverts back the terminal properties.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Will return error if either `reset` or `show_cursor` fails
|
||||
pub fn exit(&mut self) -> AppResult<()> {
|
||||
Self::reset()?;
|
||||
self.terminal.show_cursor()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,127 +0,0 @@
|
|||
// 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 crate::app::App;
|
||||
use ratatui::{
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Style, Stylize},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Clear, HighlightSpacing, List, ListItem, Padding, Paragraph, Wrap},
|
||||
Frame,
|
||||
};
|
||||
|
||||
/// Renders the user interface widgets.
|
||||
pub fn render(app: &mut App, frame: &mut Frame) {
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Length(3),
|
||||
Constraint::Min(1),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(frame.size());
|
||||
|
||||
// Title Block
|
||||
let title_text = Span::styled("WizardKit: PE Menu", Style::default().fg(Color::LightCyan));
|
||||
let title = Paragraph::new(Line::from(title_text).centered())
|
||||
.block(Block::default().borders(Borders::ALL));
|
||||
frame.render_widget(title, chunks[0]);
|
||||
|
||||
// Main Block
|
||||
let main_chunk = centered_rect(65, 90, chunks[1]);
|
||||
render_main_pane(frame, app, main_chunk);
|
||||
|
||||
// Bottom Block
|
||||
let footer_text = Span::styled(
|
||||
"(Enter) to select / (p) to poweroff / (r) to restart / (t) for terminal",
|
||||
Style::default().fg(Color::DarkGray),
|
||||
);
|
||||
let footer = Paragraph::new(Line::from(footer_text).centered())
|
||||
.block(Block::default().borders(Borders::ALL));
|
||||
frame.render_widget(footer, chunks[2]);
|
||||
|
||||
// Popup blocks
|
||||
if app.popup.is_some() {
|
||||
render_popup_pane(frame, app);
|
||||
}
|
||||
}
|
||||
|
||||
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
|
||||
// Cut the given rectangle into three vertical pieces
|
||||
let popup_layout = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
Constraint::Percentage(percent_y),
|
||||
Constraint::Percentage((100 - percent_y) / 2),
|
||||
])
|
||||
.split(r);
|
||||
|
||||
// Then cut the middle vertical piece into three width-wise pieces
|
||||
Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
Constraint::Percentage(percent_x),
|
||||
Constraint::Percentage((100 - percent_x) / 2),
|
||||
])
|
||||
.split(popup_layout[1])[1] // Return the middle chunk
|
||||
}
|
||||
|
||||
fn render_main_pane(frame: &mut Frame, app: &mut App, chunk: Rect) {
|
||||
let mut list_items = Vec::<ListItem>::new();
|
||||
for entry in &app.main_menu.items {
|
||||
let text = if entry.separator {
|
||||
if entry.name.is_empty() {
|
||||
String::from("....................")
|
||||
} else {
|
||||
entry.name.clone()
|
||||
}
|
||||
} else {
|
||||
entry.name.clone()
|
||||
};
|
||||
list_items.push(ListItem::new(format!(" {text}\n\n\n")));
|
||||
}
|
||||
let list = List::new(list_items)
|
||||
.block(
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.padding(Padding::new(20, 20, 5, 5)),
|
||||
)
|
||||
.highlight_spacing(HighlightSpacing::Always)
|
||||
.highlight_style(Style::new().green().bold())
|
||||
.highlight_symbol(" --> ")
|
||||
.repeat_highlight_symbol(false);
|
||||
frame.render_stateful_widget(list, chunk, &mut app.main_menu.state);
|
||||
}
|
||||
|
||||
fn render_popup_pane(frame: &mut Frame, app: &mut App) {
|
||||
let popup_block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.style(Style::default().red().bold());
|
||||
if let Some(popup) = &app.popup {
|
||||
let scan_paragraph = Paragraph::new(vec![
|
||||
Line::from(Span::raw(&popup.title)),
|
||||
Line::default(),
|
||||
Line::from(Span::raw(&popup.body)),
|
||||
])
|
||||
.block(popup_block)
|
||||
.centered()
|
||||
.wrap(Wrap { trim: false });
|
||||
let area = centered_rect(60, 25, frame.size());
|
||||
frame.render_widget(Clear, area);
|
||||
frame.render_widget(scan_paragraph, area);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue