Compare commits
3 commits
086946b357
...
5c0c47cc0f
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c0c47cc0f | |||
| b8403d6f52 | |||
| 833223b7ad |
12 changed files with 31 additions and 891 deletions
|
|
@ -100,6 +100,7 @@
|
|||
"<Up>": "KeyUp",
|
||||
"<Down>": "KeyDown",
|
||||
"<q>": "Quit",
|
||||
"<t>": "OpenTerminal",
|
||||
"<Ctrl-d>": "Quit",
|
||||
"<Ctrl-c>": "Quit",
|
||||
"<Ctrl-z>": "Suspend"
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ use crate::{components::popup::Type, line::DVLine, state::Mode, system::disk::Di
|
|||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
|
||||
pub enum Action {
|
||||
// App
|
||||
// App (Clone)
|
||||
Highlight(usize),
|
||||
InstallDriver,
|
||||
Process,
|
||||
|
|
@ -35,6 +35,8 @@ pub enum Action {
|
|||
// 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 (PEMenu)
|
||||
OpenTerminal,
|
||||
// Screens
|
||||
DismissPopup,
|
||||
DisplayPopup(Type, String),
|
||||
|
|
|
|||
|
|
@ -154,8 +154,8 @@ impl Component for Right {
|
|||
label
|
||||
.iter()
|
||||
.for_each(|dv| body_text.push(dv.as_line().bold()));
|
||||
body_text.push(Line::from(""));
|
||||
}
|
||||
body_text.push(Line::from(""));
|
||||
first_desc
|
||||
.iter()
|
||||
.for_each(|dv| body_text.push(dv.as_line()));
|
||||
|
|
|
|||
|
|
@ -430,19 +430,20 @@ impl App {
|
|||
self.selections[1] = two;
|
||||
}
|
||||
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)))?;
|
||||
let (title, labels, items, select_num) = build_left_items(self, self.cur_mode);
|
||||
self.action_tx.send(build_left_items(self, self.cur_mode))?;
|
||||
self.action_tx
|
||||
.send(Action::UpdateLeft(title, labels, items, select_num))?;
|
||||
let (labels, start, items) = build_right_items(self, self.cur_mode);
|
||||
self.action_tx
|
||||
.send(Action::UpdateRight(labels, start, items))?;
|
||||
.send(build_right_items(self, self.cur_mode))?;
|
||||
match new_mode {
|
||||
// Mode::InstallDrivers | Mode::SelectDisks => {
|
||||
// self.action_tx.send(Action::Select(None, None))?
|
||||
// }
|
||||
Mode::SelectTableType | Mode::Confirm => {
|
||||
// Select source/dest disks
|
||||
self.action_tx.send(Action::SelectRight(
|
||||
|
|
@ -577,7 +578,7 @@ fn build_footer_string(cur_mode: Mode) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<String>, usize) {
|
||||
fn build_left_items(app: &App, cur_mode: Mode) -> Action {
|
||||
let select_num: usize;
|
||||
let title: String;
|
||||
let mut items = Vec::new();
|
||||
|
|
@ -640,10 +641,10 @@ fn build_left_items(app: &App, cur_mode: Mode) -> (String, Vec<String>, Vec<Stri
|
|||
// Invalid states
|
||||
Mode::PEMenu => panic!("This shouldn't happen?"),
|
||||
};
|
||||
(title, labels, items, select_num)
|
||||
Action::UpdateLeft(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) -> Action {
|
||||
let mut items = Vec::new();
|
||||
let mut labels: Vec<Vec<DVLine>> = Vec::new();
|
||||
let mut start_index = 0;
|
||||
|
|
@ -716,5 +717,5 @@ fn build_right_items(app: &App, cur_mode: Mode) -> (Vec<Vec<DVLine>>, usize, Vec
|
|||
}
|
||||
_ => {}
|
||||
}
|
||||
(labels, start_index, items)
|
||||
Action::UpdateRight(labels, start_index, items)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -190,6 +190,8 @@ impl App {
|
|||
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,
|
||||
|
|
@ -237,19 +239,15 @@ impl App {
|
|||
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(build_left_items(self))?;
|
||||
self.action_tx.send(build_right_items(self))?;
|
||||
self.action_tx.send(Action::Select(None, None))?;
|
||||
}
|
||||
Action::UpdateFooter(_)
|
||||
| Action::UpdateLeft(_, _, _, _)
|
||||
| Action::UpdateRight(_, _, _)
|
||||
| Action::Highlight(_) => {
|
||||
info!("Processing Action: {:?}", action);
|
||||
Action::OpenTerminal => {
|
||||
self.tasks.add(Task::Command(
|
||||
PathBuf::from("cmd.exe"),
|
||||
vec![String::from("-new_console:n")],
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -366,7 +364,7 @@ pub fn build_command(app: &App, tool: &Tool) -> Task {
|
|||
Task::Command(cmd_path, cmd_args)
|
||||
}
|
||||
|
||||
fn build_left_items(app: &App) -> (String, Vec<String>, Vec<String>, usize) {
|
||||
fn build_left_items(app: &App) -> Action {
|
||||
let title = String::from("Tools");
|
||||
let labels = vec![String::new(), String::new()];
|
||||
let items = app
|
||||
|
|
@ -382,10 +380,10 @@ fn build_left_items(app: &App) -> (String, Vec<String>, Vec<String>, usize) {
|
|||
})
|
||||
// ─
|
||||
.collect();
|
||||
(title, labels, items, 0)
|
||||
Action::UpdateLeft(title, labels, items, 0)
|
||||
}
|
||||
|
||||
fn build_right_items(app: &App) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) {
|
||||
fn build_right_items(app: &App) -> Action {
|
||||
let labels: Vec<Vec<DVLine>> = Vec::new();
|
||||
let items = app
|
||||
.list
|
||||
|
|
@ -409,7 +407,7 @@ fn build_right_items(app: &App) -> (Vec<Vec<DVLine>>, usize, Vec<Vec<DVLine>>) {
|
|||
})
|
||||
.collect();
|
||||
let start_index = 0;
|
||||
(labels, start_index, items)
|
||||
Action::UpdateRight(labels, start_index, items)
|
||||
}
|
||||
|
||||
pub fn load_tools() -> Vec<Tool> {
|
||||
|
|
|
|||
|
|
@ -1,366 +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 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +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/>.
|
||||
//
|
||||
/// Application.
|
||||
pub mod app;
|
||||
|
||||
/// Terminal events handler.
|
||||
pub mod event;
|
||||
|
||||
/// Widget renderer.
|
||||
pub mod ui;
|
||||
|
||||
/// Terminal user interface.
|
||||
pub mod tui;
|
||||
|
||||
/// Event handler.
|
||||
pub mod handler;
|
||||
|
|
@ -1,52 +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 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(())
|
||||
}
|
||||
|
|
@ -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.area());
|
||||
|
||||
// Title Block
|
||||
let title_text = Span::styled("Deja-vu: 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.area());
|
||||
frame.render_widget(Clear, area);
|
||||
frame.render_widget(scan_paragraph, area);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue