Compare commits

...

4 commits

Author SHA1 Message Date
086946b357
WIP #43 2025-01-23 00:00:05 -08:00
00bc5bc607
WIP: Compiles and probably working? 2025-01-22 23:03:37 -08:00
408de46e73
WIP
Re-added-again-added Mode::Home
Now lists tools on left and descriptions on the right
2025-01-21 22:09:26 -08:00
de214dae2e
WIP: Initial pe-menu refactor
Not currently working
2025-01-19 19:31:57 -08:00
25 changed files with 1004 additions and 447 deletions

8
Cargo.lock generated
View file

@ -2024,12 +2024,20 @@ checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
name = "pe-menu" name = "pe-menu"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow",
"clap",
"color-eyre",
"core",
"crossterm", "crossterm",
"futures", "futures",
"ratatui", "ratatui",
"serde", "serde",
"tokio", "tokio",
"toml", "toml",
"tracing",
"tracing-error",
"tracing-subscriber",
"vergen-gix",
] ]
[[package]] [[package]]

View file

@ -1,21 +1,28 @@
{ {
"app_title": "Deja-vu", "app_title": "Deja-vu",
"clone_app_path": "C:/Program Files/Some Clone Tool/app.exe", "clone_app_path": "C:/Program Files/Some Clone Tool/app.exe",
"conemu_path": "C:/Program Files/ConEmu/ConEmu64.exe",
"keybindings": { "keybindings": {
"Home": {
"<q>": "Quit",
"<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend"
},
"ScanDisks": { "ScanDisks": {
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"InstallDrivers": { "InstallDrivers": {
"<Enter>": "Process", "<Enter>": "Process",
"<Up>": "KeyUp", "<Up>": "KeyUp",
"<Down>": "KeyDown", "<Down>": "KeyDown",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"SelectDisks": { "SelectDisks": {
"<i>": "InstallDriver", "<i>": "InstallDriver",
@ -23,70 +30,79 @@
"<Enter>": "Process", "<Enter>": "Process",
"<Up>": "KeyUp", "<Up>": "KeyUp",
"<Down>": "KeyDown", "<Down>": "KeyDown",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"SelectTableType": { "SelectTableType": {
"<b>": "PrevScreen", "<b>": "PrevScreen",
"<Enter>": "Process", "<Enter>": "Process",
"<Up>": "KeyUp", "<Up>": "KeyUp",
"<Down>": "KeyDown", "<Down>": "KeyDown",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"Confirm": { "Confirm": {
"<b>": "PrevScreen", "<b>": "PrevScreen",
"<Enter>": "Process", "<Enter>": "Process",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"PreClone": { "PreClone": {
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"Clone": { "Clone": {
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"SelectParts": { "SelectParts": {
"<Enter>": "Process", "<Enter>": "Process",
"<Up>": "KeyUp", "<Up>": "KeyUp",
"<Down>": "KeyDown", "<Down>": "KeyDown",
"<s>": "ScanDisks", // Start over "<s>": "ScanDisks",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"PostClone": { "PostClone": {
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"Done": { "Done": {
"<Enter>": "Quit", "<Enter>": "Quit",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
"Failed": { "Failed": {
"<Enter>": "Quit", "<Enter>": "Quit",
"<q>": "Quit", // Quit the application "<q>": "Quit",
"<Ctrl-d>": "Quit", // Another way to quit "<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit", // Yet another way to quit "<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend" // Suspend the application "<Ctrl-z>": "Suspend"
}, },
} "PEMenu": {
"<Enter>": "Process",
"<Up>": "KeyUp",
"<Down>": "KeyDown",
"<q>": "Quit",
"<Ctrl-d>": "Quit",
"<Ctrl-c>": "Quit",
"<Ctrl-z>": "Suspend"
},
},
} }

View file

@ -29,7 +29,11 @@ pub enum Action {
SelectRight(Option<usize>, Option<usize>), // indicies for right info pane SelectRight(Option<usize>, Option<usize>), // indicies for right info pane
UpdateDiskList(Vec<Disk>), UpdateDiskList(Vec<Disk>),
UpdateFooter(String), UpdateFooter(String),
UpdateLeft(String, Vec<String>, Vec<String>, bool), // (title, labels, items, select_one) 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 UpdateRight(Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>), // (labels, start_index, items) - items before start are always shown
// Screens // Screens
DismissPopup, DismissPopup,

View file

@ -30,7 +30,7 @@ pub struct Left {
config: Config, config: Config,
labels: Vec<String>, labels: Vec<String>,
list: StatefulList<String>, list: StatefulList<String>,
select_one: bool, select_num: usize,
selections: Vec<Option<usize>>, selections: Vec<Option<usize>>,
selections_saved: Vec<Option<usize>>, selections_saved: Vec<Option<usize>>,
title_text: String, title_text: String,
@ -39,7 +39,7 @@ pub struct Left {
impl Left { impl Left {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
select_one: false, select_num: 0,
labels: vec![String::from("one"), String::from("two")], labels: vec![String::from("one"), String::from("two")],
selections: vec![None, None], selections: vec![None, None],
selections_saved: vec![None, None], selections_saved: vec![None, None],
@ -75,12 +75,14 @@ impl Component for Left {
Action::KeyUp => self.list.previous(), Action::KeyUp => self.list.previous(),
Action::KeyDown => self.list.next(), Action::KeyDown => self.list.next(),
Action::Process => { Action::Process => {
if let Some(command_tx) = self.command_tx.clone() { 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]) { match (self.selections[0], self.selections[1]) {
(None, None) => { (None, None) => {
// Making first selection // Making first selection
command_tx.send(Action::Select(self.list.selected(), None))?; command_tx.send(Action::Select(self.list.selected(), None))?;
if self.select_one { if self.select_num == 1 {
// Confirm selection // Confirm selection
command_tx.send(Action::NextScreen)?; command_tx.send(Action::NextScreen)?;
} }
@ -115,14 +117,14 @@ impl Component for Left {
self.selections[0] = None; self.selections[0] = None;
self.selections[1] = None; self.selections[1] = None;
} }
Action::UpdateLeft(title, labels, items, select_one) => { Action::UpdateLeft(title, labels, items, select_num) => {
self.title_text = title; self.title_text = title;
self.labels = labels self.labels = labels
.iter() .iter()
.map(|label| format!(" ~{}~", label.to_lowercase())) .map(|label| format!(" ~{}~", label.to_lowercase()))
.collect(); .collect();
self.list.set_items(items); self.list.set_items(items);
self.select_one = select_one; self.select_num = select_num;
} }
_ => {} _ => {}
} }
@ -136,7 +138,7 @@ impl Component for Left {
.areas(area); .areas(area);
// Title // Title
let title_text = if self.selections[1].is_some() || self.select_one { let title_text = if self.selections[1].is_some() || self.select_num == 1 {
"Confirm Selections" "Confirm Selections"
} else { } else {
self.title_text.as_str() self.title_text.as_str()

View file

@ -44,6 +44,8 @@ pub struct Config {
pub app_title: String, pub app_title: String,
#[serde(default)] #[serde(default)]
pub clone_app_path: PathBuf, pub clone_app_path: PathBuf,
#[serde(default)]
pub conemu_path: PathBuf,
#[serde(default, flatten)] #[serde(default, flatten)]
pub config: AppConfig, pub config: AppConfig,
#[serde(default)] #[serde(default)]
@ -76,6 +78,10 @@ impl Config {
"clone_app_path", "clone_app_path",
String::from("C:\\Program Files\\Some Clone Tool\\app.exe"), 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("config_dir", config_dir.to_str().unwrap())?
.set_default("data_dir", data_dir.to_str().unwrap())?; .set_default("data_dir", data_dir.to_str().unwrap())?;
@ -529,7 +535,7 @@ mod tests {
let c = Config::new()?; let c = Config::new()?;
assert_eq!( assert_eq!(
c.keybindings c.keybindings
.get(&Mode::ScanDisks) // i.e. Home .get(&Mode::Home) // i.e. Home
.unwrap() .unwrap()
.get(&parse_key_sequence("<q>").unwrap_or_default()) .get(&parse_key_sequence("<q>").unwrap_or_default())
.unwrap(), .unwrap(),

View file

@ -21,7 +21,7 @@ use crate::config;
lazy_static::lazy_static! { lazy_static::lazy_static! {
pub static ref LOG_ENV: String = format!("{}_LOG_LEVEL", config::PROJECT_NAME); pub static ref LOG_ENV: String = format!("{}_LOG_LEVEL", config::PROJECT_NAME);
pub static ref LOG_FILE: String = format!("{}.log", 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 static ref LOG_FILE: String = format!("{}.log", env!("CARGO_PKG_NAME"));
} }

View file

@ -25,7 +25,12 @@ use crate::system::{
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Mode { pub enum Mode {
// Core
#[default] #[default]
Home,
Done,
Failed,
// Clone
ScanDisks, ScanDisks,
InstallDrivers, InstallDrivers,
SelectDisks, SelectDisks,
@ -35,8 +40,8 @@ pub enum Mode {
Clone, Clone,
SelectParts, SelectParts,
PostClone, PostClone,
Done, // WinPE
Failed, PEMenu,
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]

View file

@ -69,8 +69,7 @@ impl App {
pub fn new(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 (action_tx, action_rx) = mpsc::unbounded_channel();
let disk_list_arc = Arc::new(Mutex::new(Vec::new())); let disk_list_arc = Arc::new(Mutex::new(Vec::new()));
let mut tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone()); let tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
tasks.add(Task::ScanDisks);
Ok(Self { Ok(Self {
// TUI // TUI
action_rx, action_rx,
@ -91,9 +90,9 @@ impl App {
tick_rate, tick_rate,
// App // App
clone: CloneSettings::new(disk_list_arc), clone: CloneSettings::new(disk_list_arc),
cur_mode: Mode::ScanDisks, cur_mode: Mode::default(),
list: StatefulList::default(), list: StatefulList::default(),
prev_mode: Mode::ScanDisks, prev_mode: Mode::default(),
selections: vec![None, None], selections: vec![None, None],
tasks, tasks,
}) })
@ -101,24 +100,28 @@ impl App {
pub fn prev_mode(&mut self) -> Option<Mode> { pub fn prev_mode(&mut self) -> Option<Mode> {
let new_mode = match self.cur_mode { let new_mode = match self.cur_mode {
Mode::Home => Some(Mode::Home),
Mode::Failed => Some(Mode::Failed), Mode::Failed => Some(Mode::Failed),
Mode::Done => Some(Mode::Done), Mode::Done => Some(Mode::Done),
Mode::SelectParts => Some(Mode::SelectParts), Mode::SelectParts => Some(Mode::SelectParts),
Mode::Confirm => Some(Mode::SelectTableType), Mode::Confirm => Some(Mode::SelectTableType),
Mode::SelectTableType => Some(Mode::SelectDisks), Mode::SelectTableType => Some(Mode::SelectDisks),
Mode::SelectDisks => Some(Mode::ScanDisks), Mode::SelectDisks => Some(Mode::ScanDisks),
// // Disallowed moves
Mode::InstallDrivers Mode::InstallDrivers
| Mode::ScanDisks | Mode::ScanDisks
| Mode::PreClone | Mode::PreClone
| Mode::Clone | Mode::Clone
| Mode::PostClone => None, | Mode::PostClone => None,
// Invalid states
Mode::PEMenu => panic!("This shouldn't happen?"),
}; };
new_mode new_mode
} }
pub fn next_mode(&mut self) -> Option<Mode> { pub fn next_mode(&mut self) -> Option<Mode> {
let new_mode = match self.cur_mode { let new_mode = match self.cur_mode {
Mode::Home => Mode::ScanDisks,
Mode::InstallDrivers => Mode::ScanDisks, Mode::InstallDrivers => Mode::ScanDisks,
Mode::ScanDisks => Mode::SelectDisks, Mode::ScanDisks => Mode::SelectDisks,
Mode::SelectDisks => Mode::SelectTableType, Mode::SelectDisks => Mode::SelectTableType,
@ -129,6 +132,8 @@ impl App {
Mode::SelectParts => Mode::PostClone, Mode::SelectParts => Mode::PostClone,
Mode::PostClone | Mode::Done => Mode::Done, Mode::PostClone | Mode::Done => Mode::Done,
Mode::Failed => Mode::Failed, Mode::Failed => Mode::Failed,
// Invalid states
Mode::PEMenu => panic!("This shouldn't happen?"),
}; };
if new_mode == self.cur_mode { if new_mode == self.cur_mode {
@ -269,10 +274,7 @@ impl App {
} }
let action_tx = self.action_tx.clone(); let action_tx = self.action_tx.clone();
action_tx.send(Action::DisplayPopup( action_tx.send(Action::SetMode(Mode::ScanDisks))?;
popup::Type::Info,
String::from("Scanning Disks..."),
))?;
loop { loop {
self.handle_events(&mut tui).await?; self.handle_events(&mut tui).await?;
self.handle_actions(&mut tui)?; self.handle_actions(&mut tui)?;
@ -431,9 +433,9 @@ impl App {
self.set_mode(new_mode)?; self.set_mode(new_mode)?;
self.action_tx self.action_tx
.send(Action::UpdateFooter(build_footer_string(self.cur_mode)))?; .send(Action::UpdateFooter(build_footer_string(self.cur_mode)))?;
let (title, labels, items, select_one) = build_left_items(self, self.cur_mode); let (title, labels, items, select_num) = build_left_items(self, self.cur_mode);
self.action_tx self.action_tx
.send(Action::UpdateLeft(title, labels, items, select_one))?; .send(Action::UpdateLeft(title, labels, items, select_num))?;
let (labels, start, items) = build_right_items(self, self.cur_mode); let (labels, start, items) = build_right_items(self, self.cur_mode);
self.action_tx self.action_tx
.send(Action::UpdateRight(labels, start, items))?; .send(Action::UpdateRight(labels, start, items))?;
@ -560,7 +562,7 @@ fn get_chunks(r: Rect) -> Vec<Rect> {
fn build_footer_string(cur_mode: Mode) -> String { fn build_footer_string(cur_mode: Mode) -> String {
match cur_mode { match cur_mode {
Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => { Mode::Home | Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => {
String::from("(q) to quit") String::from("(q) to quit")
} }
Mode::SelectParts => String::from("(Enter) to select / (s) to start over / (q) to quit"), Mode::SelectParts => String::from("(Enter) to select / (s) to start over / (q) to quit"),
@ -570,23 +572,31 @@ fn build_footer_string(cur_mode: Mode) -> String {
Mode::SelectTableType => String::from("(Enter) to select / (b) to go back / (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::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"), Mode::Done | Mode::Failed | Mode::InstallDrivers => String::from("(Enter) or (q) to quit"),
// Invalid states
Mode::PEMenu => panic!("This shouldn't happen?"),
} }
} }
fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<String>, bool) {
fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<String>, usize) {
let select_num: usize;
let title: String; let title: String;
let mut items = Vec::new(); let mut items = Vec::new();
let mut labels: Vec<String> = Vec::new(); let mut labels: Vec<String> = Vec::new();
let mut select_one = false;
match cur_mode { match cur_mode {
Mode::Home => {
select_num = 0;
title = String::from("Home");
}
Mode::InstallDrivers => { Mode::InstallDrivers => {
select_num = 1;
title = String::from("Install Drivers"); title = String::from("Install Drivers");
select_one = true;
app.clone app.clone
.driver_list .driver_list
.iter() .iter()
.for_each(|driver| items.push(driver.to_string())); .for_each(|driver| items.push(driver.to_string()));
} }
Mode::SelectDisks => { Mode::SelectDisks => {
select_num = 2;
title = String::from("Select Source and Destination Disks"); title = String::from("Select Source and Destination Disks");
labels.push(String::from("source")); labels.push(String::from("source"));
labels.push(String::from("dest")); labels.push(String::from("dest"));
@ -596,18 +606,21 @@ fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<Stri
.for_each(|disk| items.push(disk.description.to_string())); .for_each(|disk| items.push(disk.description.to_string()));
} }
Mode::SelectTableType => { Mode::SelectTableType => {
select_num = 1;
title = String::from("Select Partition Table Type"); title = String::from("Select Partition Table Type");
select_one = true;
items.push(format!("{}", PartitionTableType::Guid)); items.push(format!("{}", PartitionTableType::Guid));
items.push(format!("{}", PartitionTableType::Legacy)); items.push(format!("{}", PartitionTableType::Legacy));
} }
Mode::Confirm => { Mode::Confirm => {
select_num = 0;
title = String::from("Confirm Selections"); title = String::from("Confirm Selections");
} }
Mode::PreClone | Mode::Clone | Mode::PostClone | Mode::ScanDisks => { Mode::ScanDisks | Mode::PreClone | Mode::Clone | Mode::PostClone => {
select_num = 0;
title = String::from("Processing"); title = String::from("Processing");
} }
Mode::SelectParts => { Mode::SelectParts => {
select_num = 2;
title = String::from("Select Boot and OS Partitions"); title = String::from("Select Boot and OS Partitions");
labels.push(String::from("boot")); labels.push(String::from("boot"));
labels.push(String::from("os")); labels.push(String::from("os"));
@ -620,9 +633,14 @@ fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<Stri
} }
} }
} }
Mode::Done | Mode::Failed => title = String::from("Done"), Mode::Done | Mode::Failed => {
select_num = 0;
title = String::from("Done");
}
// Invalid states
Mode::PEMenu => panic!("This shouldn't happen?"),
}; };
(title, labels, items, select_one) (title, labels, items, select_num)
} }
fn build_right_items(app: &App, cur_mode: Mode) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) { fn build_right_items(app: &App, cur_mode: Mode) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) {

View file

@ -1,4 +1,5 @@
name = 'Deja-Vu' name = 'Deja-Vu'
command = 'X:\tools\deja-vu.exe' command = 'X:\tools\deja-vu.exe'
description = "Windows clone assistant tool"
use_conemu = true use_conemu = true
separator = false separator = false

View file

@ -1,4 +1,5 @@
name = '' name = ''
command = '' command = ''
description = ''
use_conemu = false use_conemu = false
separator = true separator = true

View file

@ -1,4 +1,5 @@
name = 'NTPWEdit' name = 'NTPWEdit'
command = 'X:\Program Files\NTPWEdit\ntpwedit.exe' command = 'X:\Program Files\NTPWEdit\ntpwedit.exe'
description = 'Mostly used to unlock the built-in admin account'
use_conemu = false use_conemu = false
separator = false separator = false

View file

@ -1,4 +1,5 @@
name = 'Some Clone Tool' name = 'Some Clone Tool'
command = 'X:\Program Files\Some\Tool.exe' command = 'X:\Program Files\Some\Tool.exe'
description = 'Run Some Clone tool'
use_conemu = false use_conemu = false
separator = false separator = false

View file

@ -1,4 +1,5 @@
name = 'Task Manager' name = 'Task Manager'
command = 'X:\Windows\System32\taskmgr.exe' command = 'X:\Windows\System32\taskmgr.exe'
description = 'Manage those tasks'
use_conemu = false use_conemu = false
separator = false separator = false

View file

@ -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 = []

View file

@ -21,9 +21,26 @@ license = "GPL"
version = "0.2.0" version = "0.2.0"
[dependencies] [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"] } crossterm = { version = "0.28.1", features = ["event-stream"] }
futures = "0.3.30" futures = "0.3.30"
ratatui = "0.29.0" ratatui = "0.29.0"
serde = { version = "1.0.217", features = ["derive"] } serde = { version = "1.0.217", features = ["derive"] }
tokio = { version = "1.43.0", features = ["full"] } tokio = { version = "1.43.0", features = ["full"] }
toml = "0.8.13" 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
View 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()
}

View file

@ -13,354 +13,420 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Deja-vu. If not, see <https://www.gnu.org/licenses/>. // along with Deja-vu. If not, see <https://www.gnu.org/licenses/>.
// //
use ratatui::widgets::ListState; use core::{
use serde::Deserialize; 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::{ use std::{
env, error, fs, io, env, fs,
iter::zip,
path::PathBuf, path::PathBuf,
process::{Command, Output}, sync::{Arc, Mutex},
thread::{self, JoinHandle},
}; };
/// Application result type. use color_eyre::Result;
#[allow(clippy::module_name_repetitions)] use ratatui::{
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>; 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(Clone, Debug, Default, Deserialize)]
#[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)]
pub struct Tool { pub struct Tool {
name: String, name: String,
command: String, command: String,
description: String,
args: Option<Vec<String>>, args: Option<Vec<String>>,
use_conemu: bool, use_conemu: bool,
separator: 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 struct App {
pub config: Config, // TUI
pub main_menu: StatefulList<MenuEntry>, action_rx: mpsc::UnboundedReceiver<Action>,
pub popup: Option<PopUp>, action_tx: mpsc::UnboundedSender<Action>,
pub quit_reason: QuitReason, components: Vec<Box<dyn Component>>,
pub running: bool, config: Config,
pub thread_pool: Vec<JoinHandle<Result<Output, io::Error>>>, frame_rate: f64,
} last_tick_key_events: Vec<KeyEvent>,
should_quit: bool,
impl Default for App { should_suspend: bool,
fn default() -> Self { tick_rate: f64,
let config = Config::load(); // App
Self { list: StatefulList<Tool>,
config: config.unwrap(), mode: Mode,
running: true, tasks: Tasks,
quit_reason: QuitReason::Exit,
main_menu: StatefulList::new(),
popup: None,
thread_pool: Vec::new(),
}
}
} }
impl App { impl App {
/// Constructs a new instance of [`App`]. pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
#[must_use] let (action_tx, action_rx) = mpsc::unbounded_channel();
pub fn new() -> Self { let disk_list_arc = Arc::new(Mutex::new(Vec::new()));
let mut app = Self::default(); let tasks = Tasks::new(action_tx.clone(), disk_list_arc.clone());
let mut list = StatefulList::default();
// Add MenuEntries list.set_items(load_tools());
for tool in &app.config.tools { Ok(Self {
app.main_menu.items.push(MenuEntry::new( // TUI
&tool.name, action_rx,
&tool.command, action_tx,
tool.args.clone(), components: vec![
tool.use_conemu, Box::new(Title::new("PE Menu")),
tool.separator, Box::new(FpsCounter::new()),
)); Box::new(Left::new()),
} Box::new(Right::new()),
app.main_menu.select_first_item(); Box::new(Footer::new()),
Box::new(popup::Popup::new()),
// Done ],
app 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 async fn run(&mut self) -> Result<()> {
pub fn tick(&self) {} 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 for component in &mut self.components {
/// component.register_action_handler(self.action_tx.clone())?;
/// # 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")),
} }
if let Some(a) = argument { for component in &mut self.components {
Command::new("wpeutil") component.register_config_handler(self.config.clone())?;
.arg(a) }
.output() for component in &mut self.components {
.expect("Failed to run exit command"); 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(()) Ok(())
} }
/// Set running to false to quit the application. fn handle_key_event(&mut self, key: KeyEvent) -> Result<()> {
pub fn quit(&mut self, reason: QuitReason) { let action_tx = self.action_tx.clone();
self.running = false; let Some(keymap) = self.config.keybindings.get(&self.mode) else {
self.quit_reason = reason; return Ok(());
}
/// # 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()
}; };
if let Some(action) = keymap.get(&vec![key]) {
// Separators info!("Got action: {action:?}");
if tool.separator { action_tx.send(action.clone())?;
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
} else { } else {
// File path doesn't exist or is a broken symlink/etc // If the key was not handled as a single key action,
// The latter case would be Ok(false) rather than Err(_) // then consider it for multi-key combinations.
self.popup = Some(PopUp::new("Tool Missing", &format!("Tool path: {command}"))); self.last_tick_key_events.push(key);
return;
}
// Run // Check for multi-key combinations
// TODO: This really needs refactored to use channels so we can properly check if the if let Some(action) = keymap.get(&self.last_tick_key_events) {
// command fails. info!("Got action: {action:?}");
let new_thread = thread::spawn(move || Command::new(command_path).args(args).output()); action_tx.send(action.clone())?;
self.thread_pool.push(new_thread); }
}
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(..);
}
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")))?;
let (title, labels, items, select_num) = build_left_items(self);
self.action_tx
.send(Action::UpdateLeft(title, labels, items, select_num))?;
let (labels, start, items) = build_right_items(self);
self.action_tx
.send(Action::UpdateRight(labels, start, items))?;
self.action_tx.send(Action::Select(None, None))?;
}
Action::UpdateFooter(_)
| Action::UpdateLeft(_, _, _, _)
| Action::UpdateRight(_, _, _)
| Action::Highlight(_) => {
info!("Processing Action: {:?}", action);
}
_ => {}
}
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) -> (String, Vec<String>, Vec<String>, usize) {
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();
(title, labels, items, 0)
}
fn build_right_items(app: &App) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) {
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;
(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()
}

View file

@ -13,40 +13,21 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Deja-vu. If not, see <https://www.gnu.org/licenses/>. // along with Deja-vu. If not, see <https://www.gnu.org/licenses/>.
// //
use pe_menu::app::{App, AppResult}; use clap::Parser;
use pe_menu::event::{Event, Handler}; use color_eyre::Result;
use pe_menu::handler::handle_key_events; use core;
use pe_menu::tui::Tui;
use ratatui::backend::CrosstermBackend; use crate::app::App;
use ratatui::Terminal;
use std::io; mod app;
#[tokio::main] #[tokio::main]
async fn main() -> AppResult<()> { async fn main() -> Result<()> {
// Create an application. core::errors::init()?;
let mut app = App::new(); core::logging::init()?;
// Initialize the terminal user interface. let args = core::cli::Cli::parse();
let backend = CrosstermBackend::new(io::stderr()); let mut app = App::new(args.tick_rate, args.frame_rate)?;
let terminal = Terminal::new(backend)?; app.run().await?;
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()?;
Ok(()) Ok(())
} }

366
pe_menu/src/old/app.rs Normal file
View file

@ -0,0 +1,366 @@
// 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::widgets::ListState;
use serde::Deserialize;
use std::{
env, error, fs, io,
path::PathBuf,
process::{Command, Output},
thread::{self, JoinHandle},
};
/// Application result type.
#[allow(clippy::module_name_repetitions)]
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
/// 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)]
pub struct Tool {
name: String,
command: 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(),
}
}
}
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
}
/// Handles the tick event of the terminal.
pub fn tick(&self) {}
/// 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")),
}
if let Some(a) = argument {
Command::new("wpeutil")
.arg(a)
.output()
.expect("Failed to run exit command");
}
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()
};
// 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
} 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;
}
// 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);
}
}

52
pe_menu/src/old/main.rs Normal file
View file

@ -0,0 +1,52 @@
// 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 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;
#[tokio::main]
async fn main() -> AppResult<()> {
// Create an application.
let mut app = App::new();
// 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()?;
Ok(())
}