chore: merge release-v0.1.5 into main

This commit is contained in:
Jack Wills
2022-10-07 21:13:21 +00:00
19 changed files with 445 additions and 379 deletions
+12 -13
View File
@@ -1,22 +1,21 @@
### 2022-09-07 ### 2022-10-07
### Chores ### Chores
+ dependencies updated, [a3168daa3f769a6747dfbe61103073a7e80a1485], [78e59160bb6a978ee80e3a99eb72f051fb64e737] + Update clap to v4, [15597dbe6942ec053541398ce0e9dedc10a4d3ea]
### Docs
+ readme.md updated, [a05bf561cc6d96237f683ab0b3c782d6841974d9]
### Features ### Features
+ containerize self, github action to build and push to [Docker Hub](https://hub.docker.com/r/mrjackwills/oxker), [07f972022a69f22bac57925e6ad84234381f7890] + use newtype construct for container id, [41cbb84f2896f8be2c37eba87e390d998aff7382]
+ gui_state is_loading use a HashSet to enable multiple things be loading at the same time, [66583e1b037b7e2f3e47948d70d8a4c6f6a2f2d5]
+ github action publish to crates.io, [90b2e3f6db0d5f63840cd80888a30da6ecc22f20]
+ derive Eq where appropriate, [d7c2601f959bc12a64cd25cef59c837e1e8c2b2a]
+ ignore containers 'oxker' containers, [1be9f52ad4a68f93142784e9df630c59cdec0a79]
+ update container info if container is either running OR restarting, [5f12362db7cb61ca68f75b99ecfc9725380d87d2]
### Fixes
+ devcontainer updated, [3bde4f5629539cab3dbb57556663ab81685f9d7a]
+ Use Binate enum to enable two cycles of cpu/mem update to be executed (for each container) at the same time, refactor hashmap spawn insertions, [7ec58e79a1316ad1f7e50a2781dea0fe8422c588]
### Refactors ### Refactors
+ improved way to remove leading '/' of container name, [832e9782d7765872cbb84df6b3703fc08cb353c9] + Impl Copy where able to, [e76878f424d72b943713ef84e95e25fada77d79e]
+ replace async fn with just fn, [17dc604befac75cb9dc0311a0e43f9927fe0ca30]
+ remove pointless clone()'s & variable declarations, [6731002ee42c9460042c2c38aff5101b1bcebbe6]
+ replace String::from("") with String::new(), [62fb22478697cc9a7ab9fb562a724965b437233a]
+ replace map_or_else with map_or, [3e26f292c7dc5e13af4580952767ebe821aa5183], [5660b34d5149dce27706ff6daa90b854e6f84e14]
see <a href='https://github.com/mrjackwills/oxker/blob/main/CHANGELOG.md'>CHANGELOG.md</a> for more details see <a href='https://github.com/mrjackwills/oxker/blob/main/CHANGELOG.md'>CHANGELOG.md</a> for more details
@@ -46,7 +46,7 @@ jobs:
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: stable toolchain: stable
target: arm-unknown-linux-musleabihf target: arm-unknown-linux-musleabihf
override: true override: true
- uses: actions-rs/cargo@v1 - uses: actions-rs/cargo@v1
with: with:
@@ -61,7 +61,7 @@ jobs:
uses: actions-rs/toolchain@v1 uses: actions-rs/toolchain@v1
with: with:
toolchain: stable toolchain: stable
target: x86_64-pc-windows-gnu target: x86_64-pc-windows-gnu
override: true override: true
- uses: actions-rs/cargo@v1 - uses: actions-rs/cargo@v1
with: with:
@@ -86,7 +86,7 @@ jobs:
run: | run: |
docker build --platform linux/arm/v6,linux/arm64,linux/amd64 \ docker build --platform linux/arm/v6,linux/arm64,linux/amd64 \
-t ${{ secrets.DOCKERHUB_USERNAME }}/oxker:latest \ -t ${{ secrets.DOCKERHUB_USERNAME }}/oxker:latest \
--push \ --push \
-f containerised/Dockerfile . -f containerised/Dockerfile .
- name: Release - name: Release
+21 -1
View File
@@ -1,3 +1,23 @@
# <a href='https://github.com/mrjackwills/oxker/releases/tag/v0.1.5'>v0.1.5</a>
### 2022-10-07
### Chores
+ Update clap to v4, [15597dbe](https://github.com/mrjackwills/oxker/commit/15597dbe6942ec053541398ce0e9dedc10a4d3ea),
### Docs
+ readme.md updated, [a05bf561](https://github.com/mrjackwills/oxker/commit/a05bf561cc6d96237f683ab0b3c782d6841974d9),
### Features
+ use newtype construct for container id, [41cbb84f](https://github.com/mrjackwills/oxker/commit/41cbb84f2896f8be2c37eba87e390d998aff7382),
### Refactors
+ Impl Copy where able to, [e76878f4](https://github.com/mrjackwills/oxker/commit/e76878f424d72b943713ef84e95e25fada77d79e),
+ replace async fn with just fn, [17dc604b](https://github.com/mrjackwills/oxker/commit/17dc604befac75cb9dc0311a0e43f9927fe0ca30),
+ remove pointless clone()'s & variable declarations, [6731002e](https://github.com/mrjackwills/oxker/commit/6731002ee42c9460042c2c38aff5101b1bcebbe6),
+ replace String::from("") with String::new(), [62fb2247](https://github.com/mrjackwills/oxker/commit/62fb22478697cc9a7ab9fb562a724965b437233a),
+ replace map_or_else with map_or, [3e26f292](https://github.com/mrjackwills/oxker/commit/3e26f292c7dc5e13af4580952767ebe821aa5183),, [5660b34d](https://github.com/mrjackwills/oxker/commit/5660b34d5149dce27706ff6daa90b854e6f84e14),
# <a href='https://github.com/mrjackwills/oxker/releases/tag/v0.1.4'>v0.1.4</a> # <a href='https://github.com/mrjackwills/oxker/releases/tag/v0.1.4'>v0.1.4</a>
### 2022-09-07 ### 2022-09-07
@@ -118,7 +138,7 @@
### 2022-04-29 ### 2022-04-29
### Features ### Features
+ allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47), + allow toggling of mouse caputre, to select & copy text with mouse, closes #2, [aec184ea](https://github.com/mrjackwills/oxker/commit/aec184ea22b289e91942a4c3e6a415685884bc47),
+ show id column, [b10f9274](https://github.com/mrjackwills/oxker/commit/b10f927481c9e38a48c1d4b94e744ec48e8b6ba6), + show id column, [b10f9274](https://github.com/mrjackwills/oxker/commit/b10f927481c9e38a48c1d4b94e744ec48e8b6ba6),
+ draw_popup, using enum to draw in one of 9 areas, closes #6, [1017850a](https://github.com/mrjackwills/oxker/commit/1017850a6cc91328abc1127bdb117495f5e909d8), + draw_popup, using enum to draw in one of 9 areas, closes #6, [1017850a](https://github.com/mrjackwills/oxker/commit/1017850a6cc91328abc1127bdb117495f5e909d8),
+ use a message rx/sx for all docker commands, remove update loop, wait for update message from gui instead, [9b70fdfa](https://github.com/mrjackwills/oxker/commit/9b70fdfad7b38361ebee301bdc2545d3f0dfcf9e), + use a message rx/sx for all docker commands, remove update loop, wait for update message from gui instead, [9b70fdfa](https://github.com/mrjackwills/oxker/commit/9b70fdfad7b38361ebee301bdc2545d3f0dfcf9e),
+3 -3
View File
@@ -1,9 +1,9 @@
[package] [package]
name = "oxker" name = "oxker"
version = "0.1.4" version = "0.1.5"
edition = "2021" edition = "2021"
authors = ["Jack Wills <email@mrjackwills.com>"] authors = ["Jack Wills <email@mrjackwills.com>"]
description = "a simple tui to view & control docker containers" description = "A simple tui to view & control docker containers"
repository = "https://github.com/mrjackwills/oxker" repository = "https://github.com/mrjackwills/oxker"
homepage = "https://github.com/mrjackwills/oxker" homepage = "https://github.com/mrjackwills/oxker"
license = "MIT" license = "MIT"
@@ -15,7 +15,7 @@ categories = ["command-line-utilities"]
anyhow = "1.0" anyhow = "1.0"
bollard = "0.13" bollard = "0.13"
cansi = "2.2" cansi = "2.2"
clap={version="3.2", features = ["derive", "unicode"] } clap={version="4.0", features = ["derive", "unicode", "color"] }
crossterm = "0.25" crossterm = "0.25"
futures-util = "0.3" futures-util = "0.3"
parking_lot = {version= "0.12"} parking_lot = {version= "0.12"}
+1 -1
View File
@@ -18,7 +18,7 @@
Published on <a href='https://hub.docker.com/r/mrjackwills/oxker' target='_blank' rel='noopener noreferrer'>Docker Hub</a>, with images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6` Published on <a href='https://hub.docker.com/r/mrjackwills/oxker' target='_blank' rel='noopener noreferrer'>Docker Hub</a>, with images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6`
`docker run --rm -it --volume /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` `docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker`
## Download & install ## Download & install
+2 -2
View File
@@ -2,7 +2,7 @@
<p align="center"> <p align="center">
<img src='https://raw.githubusercontent.com/mrjackwills/oxker/main/.github/logo.svg' width='100px'/> <img src='https://raw.githubusercontent.com/mrjackwills/oxker/main/.github/logo.svg' width='100px'/>
<h1 align="center">oxker</h1> <h1 align="center">oxker</h1>
<div align="center"> <div align="center">
A simple tui to view & control docker containers A simple tui to view & control docker containers
</div> </div>
</p> </p>
@@ -17,7 +17,7 @@
Images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6` Images built for `linux/amd64`, `linux/arm64`, and `linux/arm/v6`
`docker run --rm -it --volume /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker` `docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock:ro --pull=always mrjackwills/oxker`
## Help ## Help
+94 -57
View File
@@ -7,11 +7,49 @@ use tui::{
use super::Header; use super::Header;
const ONE_KB: f64 = 1000.0; const ONE_KB: f64 = 1000.0;
const ONE_MB: f64 = ONE_KB * 1000.0; const ONE_MB: f64 = ONE_KB * 1000.0;
const ONE_GB: f64 = ONE_MB * 1000.0; const ONE_GB: f64 = ONE_MB * 1000.0;
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub struct ContainerId(String);
impl From<String> for ContainerId {
fn from(x: String) -> Self {
Self(x)
}
}
impl From<&String> for ContainerId {
fn from(x: &String) -> Self {
Self(x.clone())
}
}
impl From<&str> for ContainerId {
fn from(x: &str) -> Self {
Self(x.to_owned())
}
}
impl ContainerId {
pub fn get(&self) -> &str {
self.0.as_str()
}
}
impl Ord for ContainerId {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
impl PartialOrd for ContainerId {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct StatefulList<T> { pub struct StatefulList<T> {
pub state: ListState, pub state: ListState,
@@ -25,6 +63,7 @@ impl<T> StatefulList<T> {
items, items,
} }
} }
pub fn end(&mut self) { pub fn end(&mut self) {
let len = self.items.len(); let len = self.items.len();
if len > 0 { if len > 0 {
@@ -70,7 +109,7 @@ impl<T> StatefulList<T> {
pub fn get_state_title(&self) -> String { pub fn get_state_title(&self) -> String {
if self.items.is_empty() { if self.items.is_empty() {
String::from("") String::new()
} else { } else {
let len = self.items.len(); let len = self.items.len();
let c = self let c = self
@@ -83,7 +122,7 @@ impl<T> StatefulList<T> {
} }
/// States of the container /// States of the container
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] #[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd)]
pub enum State { pub enum State {
Dead, Dead,
Exited, Exited,
@@ -95,25 +134,25 @@ pub enum State {
} }
impl State { impl State {
pub const fn get_color(&self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Running => Color::Green, Self::Paused => Color::Yellow,
Self::Removing => Color::LightRed, Self::Removing => Color::LightRed,
Self::Restarting => Color::LightGreen, Self::Restarting => Color::LightGreen,
Self::Paused => Color::Yellow, Self::Running => Color::Green,
_ => Color::Red, _ => Color::Red,
} }
} }
// Dirty way to create order for the state, rather than impl Ord // Dirty way to create order for the state, rather than impl Ord
pub const fn order(&self) -> &'static str { pub const fn order(self) -> u8 {
match self { match self {
Self::Running => "a", Self::Running => 0,
Self::Paused => "b", Self::Paused => 1,
Self::Restarting => "c", Self::Restarting => 2,
Self::Removing => "d", Self::Removing => 3,
Self::Exited => "e", Self::Exited => 4,
Self::Dead => "f", Self::Dead => 5,
Self::Unknown => "g", Self::Unknown => 6,
} }
} }
} }
@@ -162,27 +201,28 @@ impl fmt::Display for State {
} }
/// Items for the container control list /// Items for the container control list
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum DockerControls { pub enum DockerControls {
Pause, Pause,
Unpause,
Restart, Restart,
Stop,
Start, Start,
Stop,
Unpause,
} }
impl DockerControls { impl DockerControls {
pub const fn get_color(&self) -> Color { pub const fn get_color(self) -> Color {
match self { match self {
Self::Pause => Color::Yellow,
Self::Restart => Color::Magenta,
Self::Start => Color::Green, Self::Start => Color::Green,
Self::Stop => Color::Red, Self::Stop => Color::Red,
Self::Restart => Color::Magenta,
Self::Pause => Color::Yellow,
Self::Unpause => Color::Blue, Self::Unpause => Color::Blue,
} }
} }
pub fn gen_vec(state: &State) -> Vec<Self> { /// Docker commands available depending on the containers state
pub fn gen_vec(state: State) -> Vec<Self> {
match state { match state {
State::Dead | State::Exited => vec![Self::Start, Self::Restart], State::Dead | State::Exited => vec![Self::Start, Self::Restart],
State::Paused => vec![Self::Unpause, Self::Stop], State::Paused => vec![Self::Unpause, Self::Stop],
@@ -197,10 +237,10 @@ impl fmt::Display for DockerControls {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let disp = match self { let disp = match self {
Self::Pause => "pause", Self::Pause => "pause",
Self::Unpause => "unpause",
Self::Restart => "restart", Self::Restart => "restart",
Self::Stop => "stop",
Self::Start => "start", Self::Start => "start",
Self::Stop => "stop",
Self::Unpause => "unpause",
}; };
write!(f, "{}", disp) write!(f, "{}", disp)
} }
@@ -213,7 +253,7 @@ pub trait Stats {
/// Struct for frequently updated CPU stats /// Struct for frequently updated CPU stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Clone, Debug)] #[derive(Debug, Default, Clone, Copy)]
pub struct CpuStats { pub struct CpuStats {
value: f64, value: f64,
} }
@@ -266,7 +306,7 @@ impl fmt::Display for CpuStats {
/// Struct for frequently updated memory usage stats /// Struct for frequently updated memory usage stats
/// So can use custom display formatter /// So can use custom display formatter
/// Use trait Stats for use as generic in draw_chart function /// Use trait Stats for use as generic in draw_chart function
#[derive(Clone, Debug, Eq)] #[derive(Debug, Default, Clone, Copy, Eq)]
pub struct ByteStats { pub struct ByteStats {
value: u64, value: u64,
} }
@@ -297,17 +337,18 @@ impl ByteStats {
self.value = value; self.value = value;
} }
} }
#[allow(clippy::cast_precision_loss)]
impl Stats for ByteStats { impl Stats for ByteStats {
fn get_value(&self) -> f64 { fn get_value(&self) -> f64 {
self.value as f64 self.value as f64
} }
} }
// convert from bytes to kB, MB, GB etc /// convert from bytes to kB, MB, GB etc
impl fmt::Display for ByteStats { impl fmt::Display for ByteStats {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO these can be consts outside of this definition let as_f64 = self.get_value();
let as_f64 = self.value as f64;
let p = match as_f64 { let p = match as_f64 {
x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB), x if x >= ONE_GB => format!("{y:.2} GB", y = as_f64 / ONE_GB),
x if x >= ONE_MB => format!("{y:.2} MB", y = as_f64 / ONE_MB), x if x >= ONE_MB => format!("{y:.2} MB", y = as_f64 / ONE_MB),
@@ -318,12 +359,15 @@ impl fmt::Display for ByteStats {
} }
} }
pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State);
pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State);
/// Info for each container /// Info for each container
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ContainerItem { pub struct ContainerItem {
pub cpu_stats: VecDeque<CpuStats>, pub cpu_stats: VecDeque<CpuStats>,
pub docker_controls: StatefulList<DockerControls>, pub docker_controls: StatefulList<DockerControls>,
pub id: String, pub id: ContainerId,
pub image: String, pub image: String,
pub last_updated: u64, pub last_updated: u64,
pub logs: StatefulList<ListItem<'static>>, pub logs: StatefulList<ListItem<'static>>,
@@ -336,57 +380,58 @@ pub struct ContainerItem {
pub status: String, pub status: String,
} }
pub type MemTuple = (Vec<(f64, f64)>, ByteStats, State);
pub type CpuTuple = (Vec<(f64, f64)>, CpuStats, State);
impl ContainerItem { impl ContainerItem {
/// Create a new container item /// Create a new container item
pub fn new(id: String, status: String, image: String, state: State, name: String) -> Self { pub fn new(id: ContainerId, status: String, image: String, state: State, name: String) -> Self {
let mut docker_controls = StatefulList::new(DockerControls::gen_vec(&state)); let mut docker_controls = StatefulList::new(DockerControls::gen_vec(state));
docker_controls.start(); docker_controls.start();
let mut logs = StatefulList::new(vec![]);
logs.end();
Self { Self {
cpu_stats: VecDeque::with_capacity(60), cpu_stats: VecDeque::with_capacity(60),
docker_controls, docker_controls,
id, id,
image, image,
last_updated: 0, last_updated: 0,
logs: StatefulList::new(vec![]), logs,
mem_limit: ByteStats::new(0), mem_limit: ByteStats::default(),
mem_stats: VecDeque::with_capacity(60), mem_stats: VecDeque::with_capacity(60),
name, name,
rx: ByteStats::new(0), rx: ByteStats::default(),
tx: ByteStats::new(0), tx: ByteStats::default(),
state, state,
status, status,
} }
} }
/// Find the max value in the last 30 items in the cpu stats vec /// Find the max value in the cpu stats VecDeque
fn max_cpu_stats(&self) -> CpuStats { fn max_cpu_stats(&self) -> CpuStats {
match self.cpu_stats.iter().max() { match self.cpu_stats.iter().max() {
Some(value) => value.clone(), Some(value) => *value,
None => CpuStats::new(0.0), None => CpuStats::default(),
} }
} }
/// Find the max value in the last 30 items in the mem stats vec /// Find the max value in the mem stats VecDeque
fn max_mem_stats(&self) -> ByteStats { fn max_mem_stats(&self) -> ByteStats {
match self.mem_stats.iter().max() { match self.mem_stats.iter().max() {
Some(value) => value.clone(), Some(value) => *value,
None => ByteStats::new(0), None => ByteStats::default(),
} }
} }
/// Convert cpu stats into a vec for the charts function /// Convert cpu stats into a vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_cpu_dataset(&self) -> Vec<(f64, f64)> { fn get_cpu_dataset(&self) -> Vec<(f64, f64)> {
self.cpu_stats self.cpu_stats
.iter() .iter()
.enumerate() .enumerate()
.map(|i| (i.0 as f64, i.1.value)) .map(|i| (i.0 as f64, i.1.value as f64))
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
/// Convert mem stats into a vec for the charts function /// Convert mem stats into a Vec for the charts function
#[allow(clippy::cast_precision_loss)]
fn get_mem_dataset(&self) -> Vec<(f64, f64)> { fn get_mem_dataset(&self) -> Vec<(f64, f64)> {
self.mem_stats self.mem_stats
.iter() .iter()
@@ -397,20 +442,12 @@ impl ContainerItem {
/// Get all cpu chart data /// Get all cpu chart data
fn get_cpu_chart_data(&self) -> CpuTuple { fn get_cpu_chart_data(&self) -> CpuTuple {
( (self.get_cpu_dataset(), self.max_cpu_stats(), self.state)
self.get_cpu_dataset(),
self.max_cpu_stats(),
self.state.clone(),
)
} }
/// Get all mem chart data /// Get all mem chart data
fn get_mem_chart_data(&self) -> MemTuple { fn get_mem_chart_data(&self) -> MemTuple {
( (self.get_mem_dataset(), self.max_mem_stats(), self.state)
self.get_mem_dataset(),
self.max_mem_stats(),
self.state.clone(),
)
} }
/// Get chart info for cpu & memory in one function /// Get chart info for cpu & memory in one function
@@ -421,7 +458,7 @@ impl ContainerItem {
} }
/// Container information panel headings + widths, for nice pretty formatting /// Container information panel headings + widths, for nice pretty formatting
#[derive(Debug)] #[derive(Debug, Clone, Copy)]
pub struct Columns { pub struct Columns {
pub state: (Header, usize), pub state: (Header, usize),
pub status: (Header, usize), pub status: (Header, usize),
+102 -99
View File
@@ -9,7 +9,7 @@ use crate::{app_error::AppError, parse_args::CliArgs, ui::log_sanitizer};
pub use container_state::*; pub use container_state::*;
/// Global app_state, stored in an Arc<Mutex> /// Global app_state, stored in an Arc<Mutex>
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct AppData { pub struct AppData {
args: CliArgs, args: CliArgs,
error: Option<AppError>, error: Option<AppError>,
@@ -20,13 +20,13 @@ pub struct AppData {
sorted_by: Option<(Header, SortedOrder)>, sorted_by: Option<(Header, SortedOrder)>,
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum SortedOrder { pub enum SortedOrder {
Asc, Asc,
Desc, Desc,
} }
#[derive(Debug, Clone, PartialEq, Hash, Eq)] #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum Header { pub enum Header {
State, State,
Status, Status,
@@ -58,21 +58,20 @@ impl fmt::Display for Header {
} }
impl AppData { impl AppData {
pub fn get_sorted(&self) -> Option<(Header, SortedOrder)> { pub const fn get_sorted(&self) -> Option<(Header, SortedOrder)> {
self.sorted_by.clone() self.sorted_by
} }
/// Change the sorted order, also set the selected container state to match new order /// Change the sorted order, also set the selected container state to match new order
pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) { pub fn set_sorted(&mut self, x: Option<(Header, SortedOrder)>) {
self.sorted_by = x; self.sorted_by = x;
let id = self.get_selected_container_id();
self.sort_containers(); self.sort_containers();
self.containers.state.select( self.containers
self.containers .state
.items .select(self.containers.items.iter().position(|i| {
.iter() self.get_selected_container_id()
.position(|i| Some(i.id.clone()) == id), .map_or(false, |id| i.id == id)
); }));
} }
/// Generate a default app_state /// Generate a default app_state
pub fn default(args: CliArgs) -> Self { pub fn default(args: CliArgs) -> Self {
@@ -106,8 +105,7 @@ impl AppData {
.state .state
.selected() .selected()
{ {
output = output = Some(self.containers.items[index].docker_controls.items[control_index]);
Some(self.containers.items[index].docker_controls.items[control_index].clone());
} }
} }
output output
@@ -116,34 +114,42 @@ impl AppData {
/// Change selected choice of docker commands of selected container /// Change selected choice of docker commands of selected container
pub fn docker_command_next(&mut self) { pub fn docker_command_next(&mut self) {
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
self.containers.items[index].docker_controls.next(); if let Some(i) = self.containers.items.get_mut(index) {
i.docker_controls.next();
}
} }
} }
/// Change selected choice of docker commands of selected container /// Change selected choice of docker commands of selected container
pub fn docker_command_previous(&mut self) { pub fn docker_command_previous(&mut self) {
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
self.containers.items[index].docker_controls.previous(); if let Some(i) = self.containers.items.get_mut(index) {
i.docker_controls.previous();
}
} }
} }
/// Change selected choice of docker commands of selected container /// Change selected choice of docker commands of selected container
pub fn docker_command_start(&mut self) { pub fn docker_command_start(&mut self) {
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
self.containers.items[index].docker_controls.start(); if let Some(i) = self.containers.items.get_mut(index) {
i.docker_controls.start();
}
} }
} }
/// Change selected choice of docker commands of selected container /// Change selected choice of docker commands of selected container
pub fn docker_command_end(&mut self) { pub fn docker_command_end(&mut self) {
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
self.containers.items[index].docker_controls.end(); if let Some(i) = self.containers.items.get_mut(index) {
i.docker_controls.end();
}
} }
} }
/// return single app_state error /// return single app_state error
pub fn get_error(&self) -> Option<AppError> { pub const fn get_error(&self) -> Option<AppError> {
self.error.clone() self.error
} }
/// remove single app_state error /// remove single app_state error
@@ -157,39 +163,33 @@ impl AppData {
} }
/// Find the id of the currently selected container. /// Find the id of the currently selected container.
/// If any containers on system, will always return a string. /// If any containers on system, will always return a ContainerId
/// Only returns None when no containers found. /// Only returns None when no containers found.
pub fn get_selected_container_id(&self) -> Option<String> { pub fn get_selected_container_id(&self) -> Option<ContainerId> {
let mut output = None; let mut output = None;
if let Some(index) = self.containers.state.selected() { if let Some(index) = self.containers.state.selected() {
let id = self if let Some(x) = self.containers.items.get(index) {
.containers output = Some(x.id.clone());
.items }
.iter()
.skip(index)
.take(1)
.map(|i| i.id.clone())
.collect::<String>();
output = Some(id);
} }
output output
} }
/// Sort the containers vec, based on a heading, either ascending or descending /// Sort the containers vec, based on a heading, either ascending or descending
pub fn sort_containers(&mut self) { pub fn sort_containers(&mut self) {
if let Some((head, so)) = self.sorted_by.as_ref() { if let Some((head, ord)) = self.sorted_by.as_ref() {
match head { match head {
Header::State => match so { Header::State => match ord {
SortedOrder::Desc => self SortedOrder::Desc => self
.containers .containers
.items .items
.sort_by(|a, b| a.state.order().cmp(b.state.order())), .sort_by(|a, b| a.state.order().cmp(&b.state.order())),
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
.sort_by(|a, b| b.state.order().cmp(a.state.order())), .sort_by(|a, b| b.state.order().cmp(&a.state.order())),
}, },
Header::Status => match so { Header::Status => match ord {
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
@@ -199,7 +199,7 @@ impl AppData {
.items .items
.sort_by(|a, b| b.status.cmp(&a.status)), .sort_by(|a, b| b.status.cmp(&a.status)),
}, },
Header::Cpu => match so { Header::Cpu => match ord {
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
@@ -209,7 +209,7 @@ impl AppData {
.items .items
.sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())), .sort_by(|a, b| b.cpu_stats.back().cmp(&a.cpu_stats.back())),
}, },
Header::Memory => match so { Header::Memory => match ord {
SortedOrder::Asc => self SortedOrder::Asc => self
.containers .containers
.items .items
@@ -219,25 +219,25 @@ impl AppData {
.items .items
.sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())), .sort_by(|a, b| b.mem_stats.back().cmp(&a.mem_stats.back())),
}, },
Header::Id => match so { Header::Id => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.id.cmp(&b.id)), SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.id.cmp(&b.id)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.id.cmp(&a.id)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.id.cmp(&a.id)),
}, },
Header::Image => match so { Header::Image => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)), SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.image.cmp(&b.image)),
SortedOrder::Desc => { SortedOrder::Desc => {
self.containers.items.sort_by(|a, b| b.image.cmp(&a.image)); self.containers.items.sort_by(|a, b| b.image.cmp(&a.image));
} }
}, },
Header::Name => match so { Header::Name => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.name.cmp(&b.name)), SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.name.cmp(&b.name)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.name.cmp(&a.name)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.name.cmp(&a.name)),
}, },
Header::Rx => match so { Header::Rx => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.rx.cmp(&b.rx)), SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.rx.cmp(&b.rx)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.rx.cmp(&a.rx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.rx.cmp(&a.rx)),
}, },
Header::Tx => match so { Header::Tx => match ord {
SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.tx.cmp(&b.tx)), SortedOrder::Asc => self.containers.items.sort_by(|a, b| a.tx.cmp(&b.tx)),
SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.tx.cmp(&a.tx)), SortedOrder::Desc => self.containers.items.sort_by(|a, b| b.tx.cmp(&a.tx)),
}, },
@@ -259,41 +259,50 @@ impl AppData {
/// Get the title for log panel for selected container /// Get the title for log panel for selected container
/// will be "logs x/x" /// will be "logs x/x"
pub fn get_log_title(&self) -> String { pub fn get_log_title(&self) -> String {
self.get_selected_log_index().map_or_else( self.get_selected_log_index()
|| String::from(""), .map_or("".to_owned(), |index| {
|index| self.containers.items[index].logs.get_state_title(), self.containers.items[index].logs.get_state_title()
) })
} }
/// select next selected log line /// select next selected log line
pub fn log_next(&mut self) { pub fn log_next(&mut self) {
if let Some(index) = self.get_selected_log_index() { if let Some(index) = self.get_selected_log_index() {
self.containers.items[index].logs.next(); if let Some(i) = self.containers.items.get_mut(index) {
i.logs.next();
}
} }
} }
/// select previous selected log line /// select previous selected log line
pub fn log_previous(&mut self) { pub fn log_previous(&mut self) {
if let Some(index) = self.get_selected_log_index() { if let Some(index) = self.get_selected_log_index() {
self.containers.items[index].logs.previous(); if let Some(i) = self.containers.items.get_mut(index) {
i.logs.previous();
}
} }
} }
/// select last selected log line /// select last selected log line
pub fn log_end(&mut self) { pub fn log_end(&mut self) {
if let Some(index) = self.get_selected_log_index() { if let Some(index) = self.get_selected_log_index() {
self.containers.items[index].logs.end(); if let Some(i) = self.containers.items.get_mut(index) {
i.logs.end();
}
} }
} }
/// select first selected log line /// select first selected log line
pub fn log_start(&mut self) { pub fn log_start(&mut self) {
if let Some(index) = self.get_selected_log_index() { if let Some(index) = self.get_selected_log_index() {
self.containers.items[index].logs.start(); if let Some(i) = self.containers.items.get_mut(index) {
i.logs.start();
}
} }
} }
pub fn initialised(&mut self, all_ids: &[(bool, String)]) -> bool { /// Check if the initial parsing has been completed, by making sure that all ids given (which are running) have a non empty cpu_stats vecdec
pub fn initialised(&mut self, all_ids: &[(bool, ContainerId)]) -> bool {
let count_is_running = all_ids.iter().filter(|i| i.0).count(); let count_is_running = all_ids.iter().filter(|i| i.0).count();
let number_with_cpu_status = self let number_with_cpu_status = self
.containers .containers
@@ -315,17 +324,18 @@ impl AppData {
let mut output = Columns::new(); let mut output = Columns::new();
let count = |x: &String| x.chars().count(); let count = |x: &String| x.chars().count();
// Should probably find a refactor here somewhere
for container in &self.containers.items { for container in &self.containers.items {
let cpu_count = count( let cpu_count = count(
&container &container
.cpu_stats .cpu_stats
.back() .back()
.unwrap_or(&CpuStats::new(0.0)) .unwrap_or(&CpuStats::default())
.to_string(), .to_string(),
); );
let mem_count = count(&format!( let mem_count = count(&format!(
"{} / {}", "{} / {}",
container.mem_stats.back().unwrap_or(&ByteStats::new(0)), container.mem_stats.back().unwrap_or(&ByteStats::default()),
container.mem_limit container.mem_limit
)); ));
@@ -365,7 +375,7 @@ impl AppData {
} }
/// Get all containers ids /// Get all containers ids
pub fn get_all_ids(&self) -> Vec<String> { pub fn get_all_ids(&self) -> Vec<ContainerId> {
self.containers self.containers
.items .items
.iter() .iter()
@@ -373,15 +383,15 @@ impl AppData {
.collect::<Vec<_>>() .collect::<Vec<_>>()
} }
/// find container given id /// return a mutable container by given id
fn get_container_by_id(&mut self, id: &str) -> Option<&mut ContainerItem> { fn get_container_by_id(&mut self, id: &ContainerId) -> Option<&mut ContainerItem> {
self.containers.items.iter_mut().find(|i| i.id == id) self.containers.items.iter_mut().find(|i| &i.id == id)
} }
/// Update container mem, cpu, & network stats, in single function so only need to call .lock() once /// Update container mem, cpu, & network stats, in single function so only need to call .lock() once
pub fn update_stats( pub fn update_stats(
&mut self, &mut self,
id: &str, id: &ContainerId,
cpu_stat: Option<f64>, cpu_stat: Option<f64>,
mem_stat: Option<u64>, mem_stat: Option<u64>,
mem_limit: u64, mem_limit: u64,
@@ -410,18 +420,18 @@ impl AppData {
} }
/// Update, or insert, containers /// Update, or insert, containers
pub fn update_containers(&mut self, containers: &mut [ContainerSummary]) { pub fn update_containers(&mut self, all_containers: &mut [ContainerSummary]) {
let all_ids = self.get_all_ids(); let all_ids = self.get_all_ids();
if !containers.is_empty() && self.containers.state.selected().is_none() { if !all_containers.is_empty() && self.containers.state.selected().is_none() {
self.containers.start(); self.containers.start();
} }
for (index, id) in all_ids.iter().enumerate() { for (index, id) in all_ids.iter().enumerate() {
if !containers if !all_containers
.iter() .iter()
.filter_map(|i| i.id.as_ref()) .filter_map(|i| i.id.as_ref())
.any(|x| x == id) .any(|x| x == id.get())
{ {
// If removed container is currently selected, then change selected to previous // If removed container is currently selected, then change selected to previous
// This will default to 0 in any edge cases // This will default to 0 in any edge cases
@@ -434,63 +444,54 @@ impl AppData {
} }
} }
} }
// Trim a &String and return String
let trim_owned = |x: &String| x.trim().to_owned();
for i in containers.iter_mut() { for i in all_containers {
if let Some(id) = i.id.as_ref() { if let Some(id) = i.id.as_ref() {
// maybe if no name then continue? let name = i.names.as_mut().map_or("".to_owned(), |names| {
let name = i.names.as_mut().map_or("".to_owned(), |n| { names.first_mut().map_or("".to_owned(), |f| {
n.get_mut(0).map_or("".to_owned(), |f| {
if f.starts_with('/') { if f.starts_with('/') {
f.remove(0); f.remove(0);
} }
f.clone() (*f).to_string()
}) })
}); });
let state = State::from( let state = State::from(i.state.as_ref().map_or("dead".to_owned(), trim_owned));
i.state let status = i.status.as_ref().map_or("".to_owned(), trim_owned);
.as_ref()
.map_or("dead".to_owned(), |f| f.trim().to_owned()),
);
let status = i
.status
.as_ref()
.map_or("".to_owned(), |f| f.trim().to_owned());
let image = i let image = i
.image .image
.as_ref() .as_ref()
.map_or("".to_owned(), std::clone::Clone::clone); .map_or("".to_owned(), std::clone::Clone::clone);
if let Some(current_container) = self.get_container_by_id(id) { let id = ContainerId::from(id);
if current_container.name != name { // If container info already in containers Vec, then just update details
current_container.name = name; if let Some(item) = self.get_container_by_id(&id) {
if item.name != name {
item.name = name;
}; };
if current_container.status != status { if item.status != status {
current_container.status = status; item.status = status;
}; };
if current_container.state != state { if item.state != state {
current_container.docker_controls.items = DockerControls::gen_vec(&state); item.docker_controls.items = DockerControls::gen_vec(state);
// Update the list state, needs to be None if the gen_vec returns an empty vec // Update the list state, needs to be None if the gen_vec returns an empty vec
match state { match state {
State::Removing | State::Restarting | State::Unknown => { State::Removing | State::Restarting | State::Unknown => {
current_container.docker_controls.state.select(None); item.docker_controls.state.select(None);
} }
_ => current_container.docker_controls.start(), _ => item.docker_controls.start(),
}; };
current_container.state = state; item.state = state;
}; };
if current_container.image != image { if item.image != image {
// limit image name to 64 chars? item.image = image;
// current_container.image = image.chars().into_iter().take(64).collect();
current_container.image = image;
}; };
// else container not known, so make new ContainerItem and push into containers Vec
} else { } else {
// limit image name to 64 chars? let container = ContainerItem::new(id, status, image, state, name);
// let mut container = ContainerItem::new(id.clone(), status, image.chars().into_iter().take(64).collect(), state, name);
let mut container = ContainerItem::new(id.clone(), status, image, state, name);
container.logs.end();
self.containers.items.push(container); self.containers.items.push(container);
} }
} }
@@ -498,7 +499,7 @@ impl AppData {
} }
/// update logs of a given container, based on id /// update logs of a given container, based on id
pub fn update_log_by_id(&mut self, output: &[String], id: &str) { pub fn update_log_by_id(&mut self, output: &[String], id: &ContainerId) {
let tz = Self::get_systemtime(); let tz = Self::get_systemtime();
let color = self.args.color; let color = self.args.color;
let raw = self.args.raw; let raw = self.args.raw;
@@ -507,17 +508,19 @@ impl AppData {
container.last_updated = tz; container.last_updated = tz;
let current_len = container.logs.items.len(); let current_len = container.logs.items.len();
for i in output.iter() { for i in output {
let lines = if color { let lines = if color {
log_sanitizer::colorize_logs(i) log_sanitizer::colorize_logs(i)
} else if raw { } else if raw {
log_sanitizer::raw(i.clone()) log_sanitizer::raw(i)
} else { } else {
log_sanitizer::remove_ansi(i) log_sanitizer::remove_ansi(i)
}; };
container.logs.items.push(ListItem::new(lines)); container.logs.items.push(ListItem::new(lines));
} }
// Set the logs selected row for each container
// Either when no long currently selected, or currently selected (before updated) is already at end
if container.logs.state.selected().is_none() if container.logs.state.selected().is_none()
|| container.logs.state.selected().map_or(1, |f| f + 1) == current_len || container.logs.state.selected().map_or(1, |f| f + 1) == current_len
{ {
+4 -4
View File
@@ -3,12 +3,12 @@ use std::fmt;
/// app errors to set in global state /// app errors to set in global state
#[allow(unused)] #[allow(unused)]
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum AppError { pub enum AppError {
DockerCommand(DockerControls),
DockerConnect, DockerConnect,
DockerInterval, DockerInterval,
InputPoll, InputPoll,
DockerCommand(DockerControls),
MouseCapture(bool), MouseCapture(bool),
Terminal, Terminal,
} }
@@ -17,15 +17,15 @@ pub enum AppError {
impl fmt::Display for AppError { impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
Self::DockerCommand(s) => write!(f, "Unable to {} container", s),
Self::DockerConnect => write!(f, "Unable to access docker daemon"), Self::DockerConnect => write!(f, "Unable to access docker daemon"),
Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"), Self::DockerInterval => write!(f, "Docker update interval needs to be greater than 0"),
Self::InputPoll => write!(f, "Unable to poll user input"), Self::InputPoll => write!(f, "Unable to poll user input"),
Self::Terminal => write!(f, "Unable to draw to terminal"),
Self::DockerCommand(s) => write!(f, "Unable to {} container", s),
Self::MouseCapture(x) => { Self::MouseCapture(x) => {
let reason = if *x { "en" } else { "dis" }; let reason = if *x { "en" } else { "dis" };
write!(f, "Unbale to {}able mouse capture", reason) write!(f, "Unbale to {}able mouse capture", reason)
} }
Self::Terminal => write!(f, "Unable to draw to terminal"),
} }
} }
} }
+7 -5
View File
@@ -1,10 +1,12 @@
use crate::app_data::ContainerId;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum DockerMessage { pub enum DockerMessage {
Update, Update,
Start(String), Start(ContainerId),
Restart(String), Restart(ContainerId),
Pause(String), Pause(ContainerId),
Unpause(String), Unpause(ContainerId),
Stop(String), Stop(ContainerId),
Quit, Quit,
} }
+66 -65
View File
@@ -16,7 +16,7 @@ use tokio::{sync::mpsc::Receiver, task::JoinHandle};
use uuid::Uuid; use uuid::Uuid;
use crate::{ use crate::{
app_data::{AppData, DockerControls}, app_data::{AppData, ContainerId, DockerControls},
app_error::AppError, app_error::AppError,
parse_args::CliArgs, parse_args::CliArgs,
ui::GuiState, ui::GuiState,
@@ -24,16 +24,17 @@ use crate::{
mod message; mod message;
pub use message::DockerMessage; pub use message::DockerMessage;
#[derive(Debug, Hash, Clone, PartialEq, Eq)] #[derive(Debug, Clone, Eq, Hash, PartialEq)]
enum SpawnId { enum SpawnId {
Stats((String, Binate)), Stats((ContainerId, Binate)),
Log(String), Log(ContainerId),
} }
/// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time /// Cpu & Mem stats take twice as long as the update interval to get a value, so will have two being executed at the same time
/// SpawnId::Stats takes container_id and binate value to enable both cycles of the same container_id to be inserted into the hashmap /// SpawnId::Stats takes container_id and binate value to enable both cycles of the same container_id to be inserted into the hashmap
/// Binate value is toggled when all join handles have been spawned off /// Binate value is toggled when all join handles have been spawned off
#[derive(Debug, Hash, Clone, PartialEq, Eq, Copy)] /// Also effectively means that if the docker_update interval minimum will be 1000ms
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
enum Binate { enum Binate {
One, One,
Two, Two,
@@ -61,7 +62,8 @@ pub struct DockerData {
} }
impl DockerData { impl DockerData {
/// Use docker stats for work out current cpu usage /// Use docker stats to caluclate current cpu usage
#[allow(clippy::cast_precision_loss)]
fn calculate_usage(stats: &Stats) -> f64 { fn calculate_usage(stats: &Stats) -> f64 {
let mut cpu_percentage = 0.0; let mut cpu_percentage = 0.0;
let previous_cpu = stats.precpu_stats.cpu_usage.total_usage; let previous_cpu = stats.precpu_stats.cpu_usage.total_usage;
@@ -77,9 +79,8 @@ impl DockerData {
.cpu_stats .cpu_stats
.cpu_usage .cpu_usage
.percpu_usage .percpu_usage
.clone() .as_ref()
.unwrap_or_default() .map_or(0, std::vec::Vec::len) as u64
.len() as u64
}) as f64; }) as f64;
if system_delta > 0.0 && cpu_delta > 0.0 { if system_delta > 0.0 && cpu_delta > 0.0 {
cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0; cpu_percentage = (cpu_delta / system_delta) * online_cpus * 100.0;
@@ -93,7 +94,7 @@ impl DockerData {
/// remove if from spawns hashmap when complete /// remove if from spawns hashmap when complete
async fn update_container_stat( async fn update_container_stat(
docker: Arc<Docker>, docker: Arc<Docker>,
id: String, id: ContainerId,
app_data: Arc<Mutex<AppData>>, app_data: Arc<Mutex<AppData>>,
is_running: bool, is_running: bool,
spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>, spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>,
@@ -101,7 +102,7 @@ impl DockerData {
) { ) {
let mut stream = docker let mut stream = docker
.stats( .stats(
&id, id.get(),
Some(StatsOptions { Some(StatsOptions {
stream: false, stream: false,
one_shot: !is_running, one_shot: !is_running,
@@ -113,22 +114,21 @@ impl DockerData {
let mem_stat = stats.memory_stats.usage.unwrap_or(0); let mem_stat = stats.memory_stats.usage.unwrap_or(0);
let mem_limit = stats.memory_stats.limit.unwrap_or(0); let mem_limit = stats.memory_stats.limit.unwrap_or(0);
let some_key = stats let op_key = stats
.networks .networks
.as_ref() .as_ref()
.and_then(|networks| networks.keys().next().cloned()); .and_then(|networks| networks.keys().next().cloned());
let cpu_stats = Self::calculate_usage(&stats); let cpu_stats = Self::calculate_usage(&stats);
let no_bytes = || (0, 0); let (rx, tx) = if let Some(key) = op_key {
stats
let (rx, tx) = if let Some(key) = some_key { .networks
match stats.networks.unwrap_or_default().get(&key) { .unwrap_or_default()
Some(data) => (data.rx_bytes, data.tx_bytes), .get(&key)
None => no_bytes(), .map_or((0, 0), |f| (f.rx_bytes, f.tx_bytes))
}
} else { } else {
no_bytes() (0, 0)
}; };
if is_running { if is_running {
@@ -150,15 +150,12 @@ impl DockerData {
} }
/// Update all stats, spawn each container into own tokio::spawn thread /// Update all stats, spawn each container into own tokio::spawn thread
async fn update_all_container_stats(&mut self, all_ids: &[(bool, String)]) { fn update_all_container_stats(&mut self, all_ids: &[(bool, ContainerId)]) {
for (is_running, id) in all_ids.iter() { for (is_running, id) in all_ids {
let docker = Arc::clone(&self.docker); let docker = Arc::clone(&self.docker);
let app_data = Arc::clone(&self.app_data); let app_data = Arc::clone(&self.app_data);
let spawns = Arc::clone(&self.spawns); let spawns = Arc::clone(&self.spawns);
let id = id.clone();
let key = SpawnId::Stats((id.clone(), self.binate)); let key = SpawnId::Stats((id.clone(), self.binate));
let spawn_key = key.clone(); let spawn_key = key.clone();
self.spawns.lock().entry(key).or_insert_with(|| { self.spawns.lock().entry(key).or_insert_with(|| {
tokio::spawn(Self::update_container_stat( tokio::spawn(Self::update_container_stat(
@@ -177,7 +174,7 @@ impl DockerData {
/// Get all current containers, handle into ContainerItem in the app_data struct rather than here /// Get all current containers, handle into ContainerItem in the app_data struct rather than here
/// Just make sure that items sent are guaranteed to have an id /// Just make sure that items sent are guaranteed to have an id
/// Will ignore any container that contains `oxker` as an entry point /// Will ignore any container that contains `oxker` as an entry point
pub async fn update_all_containers(&mut self) -> Vec<(bool, String)> { pub async fn update_all_containers(&mut self) -> Vec<(bool, ContainerId)> {
let containers = self let containers = self
.docker .docker
.list_containers(Some(ListContainersOptions::<String> { .list_containers(Some(ListContainersOptions::<String> {
@@ -188,13 +185,13 @@ impl DockerData {
.unwrap_or_default(); .unwrap_or_default();
let mut output = containers let mut output = containers
.iter() .into_iter()
.filter_map(|f| match f.id { .filter_map(|f| match f.id {
Some(_) => { Some(_) => {
if f.command.as_ref().map_or(false, |c| c.contains("oxker")) { if f.command.as_ref().map_or(false, |c| c.contains("oxker")) {
None None
} else { } else {
Some(f.clone()) Some(f)
} }
} }
None => None, None => None,
@@ -208,13 +205,13 @@ impl DockerData {
// Just get the containers that are currently running, or being restarted, no point updating info on paused or dead containers // Just get the containers that are currently running, or being restarted, no point updating info on paused or dead containers
output output
.iter() .into_iter()
.filter_map(|i| { .filter_map(|i| {
i.id.as_ref().map(|id| { i.id.map(|id| {
( (
i.state == Some("running".to_owned()) i.state == Some("running".to_owned())
|| i.state == Some("restarting".to_owned()), || i.state == Some("restarting".to_owned()),
id.clone(), ContainerId::from(id),
) )
}) })
}) })
@@ -226,21 +223,20 @@ impl DockerData {
/// remove if from spawns hashmap when complete /// remove if from spawns hashmap when complete
async fn update_log( async fn update_log(
docker: Arc<Docker>, docker: Arc<Docker>,
id: String, id: ContainerId,
timestamps: bool, timestamps: bool,
since: i64, since: u64,
app_data: Arc<Mutex<AppData>>, app_data: Arc<Mutex<AppData>>,
spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>, spawns: Arc<Mutex<HashMap<SpawnId, JoinHandle<()>>>>,
) { ) {
let options = Some(LogsOptions::<String> { let options = Some(LogsOptions::<String> {
stdout: true, stdout: true,
timestamps, timestamps,
since, since: i64::try_from(since).unwrap_or_default(),
..Default::default() ..Default::default()
}); });
let mut logs = docker.logs(&id, options); let mut logs = docker.logs(id.get(), options);
let mut output = vec![]; let mut output = vec![];
while let Some(value) = logs.next().await { while let Some(value) = logs.next().await {
@@ -256,18 +252,21 @@ impl DockerData {
} }
/// Update all logs, spawn each container into own tokio::spawn thread /// Update all logs, spawn each container into own tokio::spawn thread
async fn init_all_logs(&mut self, all_ids: &[(bool, String)]) { fn init_all_logs(&mut self, all_ids: &[(bool, ContainerId)]) {
for (_, id) in all_ids.iter() { for (_, id) in all_ids {
let docker = Arc::clone(&self.docker); let docker = Arc::clone(&self.docker);
let timestamps = self.timestamps;
let id = id.clone();
let app_data = Arc::clone(&self.app_data); let app_data = Arc::clone(&self.app_data);
let spawns = Arc::clone(&self.spawns); let spawns = Arc::clone(&self.spawns);
let key = SpawnId::Log(id.clone()); let key = SpawnId::Log(id.clone());
self.spawns.lock().insert( self.spawns.lock().insert(
key, key,
tokio::spawn(Self::update_log( tokio::spawn(Self::update_log(
docker, id, timestamps, 0, app_data, spawns, docker,
id.clone(),
self.timestamps,
0,
app_data,
spawns,
)), )),
); );
} }
@@ -278,22 +277,26 @@ impl DockerData {
let all_ids = self.update_all_containers().await; let all_ids = self.update_all_containers().await;
let optional_index = self.app_data.lock().get_selected_log_index(); let optional_index = self.app_data.lock().get_selected_log_index();
if let Some(index) = optional_index { if let Some(index) = optional_index {
// this could be neater if let Some(container) = self.app_data.lock().containers.items.get(index) {
let id = self.app_data.lock().containers.items[index].id.clone(); self.spawns
let key = SpawnId::Log(id.clone()); .lock()
.entry(SpawnId::Log(container.id.clone()))
self.spawns.lock().entry(key).or_insert_with(|| { .or_insert_with(|| {
let since = self.app_data.lock().containers.items[index].last_updated as i64; let docker = Arc::clone(&self.docker);
let docker = Arc::clone(&self.docker); let app_data = Arc::clone(&self.app_data);
let timestamps = self.timestamps; let spawns = Arc::clone(&self.spawns);
let app_data = Arc::clone(&self.app_data); tokio::spawn(Self::update_log(
let spawns = Arc::clone(&self.spawns); docker,
tokio::spawn(Self::update_log( container.id.clone(),
docker, id, timestamps, since, app_data, spawns, self.timestamps,
)) container.last_updated,
}); app_data,
spawns,
))
});
}
}; };
self.update_all_container_stats(&all_ids).await; self.update_all_container_stats(&all_ids);
} }
/// Animate the loading icon /// Animate the loading icon
@@ -319,10 +322,10 @@ impl DockerData {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
let all_ids = self.update_all_containers().await; let all_ids = self.update_all_containers().await;
self.update_all_container_stats(&all_ids).await; self.update_all_container_stats(&all_ids);
// Maybe only do a single one at first? // Maybe only do a single one at first?
self.init_all_logs(&all_ids).await; self.init_all_logs(&all_ids);
if all_ids.is_empty() { if all_ids.is_empty() {
self.initialised = true; self.initialised = true;
@@ -346,7 +349,7 @@ impl DockerData {
match message { match message {
DockerMessage::Pause(id) => { DockerMessage::Pause(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.pause_container(&id).await.is_err() { if docker.pause_container(id.get()).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Pause)); .set_error(AppError::DockerCommand(DockerControls::Pause));
@@ -355,7 +358,7 @@ impl DockerData {
} }
DockerMessage::Restart(id) => { DockerMessage::Restart(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.restart_container(&id, None).await.is_err() { if docker.restart_container(id.get(), None).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Restart)); .set_error(AppError::DockerCommand(DockerControls::Restart));
@@ -365,7 +368,7 @@ impl DockerData {
DockerMessage::Start(id) => { DockerMessage::Start(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker if docker
.start_container(&id, None::<StartContainerOptions<String>>) .start_container(id.get(), None::<StartContainerOptions<String>>)
.await .await
.is_err() .is_err()
{ {
@@ -377,7 +380,7 @@ impl DockerData {
} }
DockerMessage::Stop(id) => { DockerMessage::Stop(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.stop_container(&id, None).await.is_err() { if docker.stop_container(id.get(), None).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Stop)); .set_error(AppError::DockerCommand(DockerControls::Stop));
@@ -386,13 +389,11 @@ impl DockerData {
} }
DockerMessage::Unpause(id) => { DockerMessage::Unpause(id) => {
let loading_spin = self.loading_spin(loading_uuid).await; let loading_spin = self.loading_spin(loading_uuid).await;
if docker.unpause_container(&id).await.is_err() { if docker.unpause_container(id.get()).await.is_err() {
app_data app_data
.lock() .lock()
.set_error(AppError::DockerCommand(DockerControls::Unpause)); .set_error(AppError::DockerCommand(DockerControls::Unpause));
}; };
// loading sping take uuid to remove
// stop_loading_sping(uuid)
self.stop_loading_spin(&loading_spin, loading_uuid); self.stop_loading_spin(&loading_spin, loading_uuid);
self.update_everything().await; self.update_everything().await;
} }
+1 -1
View File
@@ -1,6 +1,6 @@
use crossterm::event::{KeyCode, MouseEvent}; use crossterm::event::{KeyCode, MouseEvent};
#[derive(Debug, Clone)] #[derive(Debug, Clone, Copy)]
pub enum InputMessages { pub enum InputMessages {
ButtonPress(KeyCode), ButtonPress(KeyCode),
MouseEvent(MouseEvent), MouseEvent(MouseEvent),
+7 -6
View File
@@ -77,8 +77,8 @@ impl InputHandler {
} }
} }
/// Mouse button /// Toggle the mouse capture (via input of the 'm' key)
fn m_button(&mut self) { fn m_key(&mut self) {
if self.mouse_capture { if self.mouse_capture {
match execute!(std::io::stdout(), DisableMouseCapture) { match execute!(std::io::stdout(), DisableMouseCapture) {
Ok(_) => self Ok(_) => self
@@ -118,7 +118,7 @@ impl InputHandler {
/// Sort containers based on a given header, switch asc to desc if already sorted, else always desc /// Sort containers based on a given header, switch asc to desc if already sorted, else always desc
fn sort(&self, header: Header) { fn sort(&self, header: Header) {
let mut output = Some((header.clone(), SortedOrder::Desc)); let mut output = Some((header, SortedOrder::Desc));
let mut locked_data = self.app_data.lock(); let mut locked_data = self.app_data.lock();
if let Some((h, order)) = locked_data.get_sorted().as_ref() { if let Some((h, order)) = locked_data.get_sorted().as_ref() {
if &SortedOrder::Desc == order && h == &header { if &SortedOrder::Desc == order && h == &header {
@@ -128,7 +128,7 @@ impl InputHandler {
locked_data.set_sorted(output); locked_data.set_sorted(output);
} }
/// Send a quit message to docker, to abort all spawns, if error, quit here instead /// Send a quit message to docker, to abort all spawns, if an error is return, set is_running to false here instead
async fn quit(&self) { async fn quit(&self) {
match self.docker_sender.send(DockerMessage::Quit).await { match self.docker_sender.send(DockerMessage::Quit).await {
Ok(_) => (), Ok(_) => (),
@@ -137,6 +137,7 @@ impl InputHandler {
} }
/// Handle any keyboard button events /// Handle any keyboard button events
#[allow(clippy::too_many_lines)]
async fn button_press(&mut self, key_code: KeyCode) { async fn button_press(&mut self, key_code: KeyCode) {
let show_error = self.app_data.lock().show_error; let show_error = self.app_data.lock().show_error;
let show_info = self.gui_state.lock().show_help; let show_info = self.gui_state.lock().show_help;
@@ -154,7 +155,7 @@ impl InputHandler {
match key_code { match key_code {
KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('q' | 'Q') => self.quit().await,
KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = false, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = false,
KeyCode::Char('m' | 'M') => self.m_button(), KeyCode::Char('m' | 'M') => self.m_key(),
_ => (), _ => (),
} }
} else { } else {
@@ -171,7 +172,7 @@ impl InputHandler {
KeyCode::Char('9') => self.sort(Header::Tx), KeyCode::Char('9') => self.sort(Header::Tx),
KeyCode::Char('q' | 'Q') => self.quit().await, KeyCode::Char('q' | 'Q') => self.quit().await,
KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = true, KeyCode::Char('h' | 'H') => self.gui_state.lock().show_help = true,
KeyCode::Char('m' | 'M') => self.m_button(), KeyCode::Char('m' | 'M') => self.m_key(),
KeyCode::Tab => { KeyCode::Tab => {
// Skip control panel if no containers, could be refactored // Skip control panel if no containers, could be refactored
let has_containers = self.app_data.lock().get_container_len() == 0; let has_containers = self.app_data.lock().get_container_len() == 0;
+17 -22
View File
@@ -35,37 +35,32 @@ fn setup_tracing() {
async fn main() { async fn main() {
setup_tracing(); setup_tracing();
let args = CliArgs::new(); let args = CliArgs::new();
let app_data = Arc::new(Mutex::new(AppData::default(args.clone()))); let app_data = Arc::new(Mutex::new(AppData::default(args)));
let gui_state = Arc::new(Mutex::new(GuiState::default())); let gui_state = Arc::new(Mutex::new(GuiState::default()));
let is_running = Arc::new(AtomicBool::new(true)); let is_running = Arc::new(AtomicBool::new(true));
let docker_args = args.clone();
let docker_app_data = Arc::clone(&app_data); let docker_app_data = Arc::clone(&app_data);
let docker_gui_state = Arc::clone(&gui_state); let docker_gui_state = Arc::clone(&gui_state);
let (docker_sx, docker_rx) = tokio::sync::mpsc::channel(16); let (docker_sx, docker_rx) = tokio::sync::mpsc::channel(16);
// Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error // Create docker daemon handler, and only spawn up the docker data handler if ping returns non-error
match Docker::connect_with_socket_defaults() { match Docker::connect_with_socket_defaults() {
Ok(docker) => { Ok(docker) => match docker.ping().await {
let docker = Arc::new(docker); Ok(_) => {
match docker.ping().await { let docker = Arc::new(docker);
Ok(_) => { let is_running = Arc::clone(&is_running);
let docker = Arc::clone(&docker); tokio::spawn(DockerData::init(
let is_running = Arc::clone(&is_running); args,
tokio::spawn(DockerData::init( docker_app_data,
docker_args, docker,
docker_app_data, docker_gui_state,
docker, docker_rx,
docker_gui_state, is_running,
docker_rx, ));
is_running,
));
}
Err(_) => app_data.lock().set_error(AppError::DockerConnect),
} }
} Err(_) => app_data.lock().set_error(AppError::DockerConnect),
},
Err(_) => app_data.lock().set_error(AppError::DockerConnect), Err(_) => app_data.lock().set_error(AppError::DockerConnect),
} }
let input_app_data = Arc::clone(&app_data); let input_app_data = Arc::clone(&app_data);
@@ -85,7 +80,6 @@ async fn main() {
input_is_running, input_is_running,
)); ));
// Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui
if args.gui { if args.gui {
let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval)); let update_duration = std::time::Duration::from_millis(u64::from(args.docker_interval));
create_ui( create_ui(
@@ -99,8 +93,9 @@ async fn main() {
.await .await
.unwrap_or(()); .unwrap_or(());
} else { } else {
// Debug mode for testing, mostly pointless, doesn't take terminal nor draw gui
// TODO this needs to be improved to display something actually useful
loop { loop {
// TODO this needs to be improved to display something useful
info!("in debug mode"); info!("in debug mode");
tokio::time::sleep(std::time::Duration::from_millis(5000)).await; tokio::time::sleep(std::time::Duration::from_millis(5000)).await;
} }
+12 -12
View File
@@ -3,29 +3,29 @@ use std::process;
use clap::Parser; use clap::Parser;
use tracing::error; use tracing::error;
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone, Copy)]
#[clap(about, version, author)] #[allow(clippy::struct_excessive_bools)]
#[command(version, about)]
pub struct CliArgs { pub struct CliArgs {
/// Docker update interval in ms, minimum 1, reccomended 500+ /// Docker update interval in ms, minimum effectively 1000
#[clap(short = 'd', value_name = "ms", default_value_t = 1000)] #[clap(short = 'd', value_name = "ms", default_value_t = 1000)]
pub docker_interval: u32, pub docker_interval: u32,
/// Don't draw gui - for debugging - mostly pointless
#[clap(short = 'g')]
pub gui: bool,
/// Remove timestamps from Docker logs /// Remove timestamps from Docker logs
#[clap(short = 't')] #[clap(short = 't')]
pub timestamp: bool, pub timestamp: bool,
/// Show raw logs, default is to remove ansi formatting /// Attempt to colorize the logs, conflicts with "-r"
#[clap(short = 'c', conflicts_with = "raw")]
pub color: bool,
/// Show raw logs, default is to remove ansi formatting, conflicts with "-c"
#[clap(short = 'r', conflicts_with = "color")] #[clap(short = 'r', conflicts_with = "color")]
pub raw: bool, pub raw: bool,
/// Attempt to colorize the logs /// Don't draw gui - for debugging - mostly pointless
#[clap(short = 'c', conflicts_with = "raw")] #[clap(short = 'g')]
pub color: bool, pub gui: bool,
} }
impl CliArgs { impl CliArgs {
+10 -10
View File
@@ -7,14 +7,14 @@ pub mod log_sanitizer {
}; };
/// Attempt to colorize the given string to tui-rs standards /// Attempt to colorize the given string to tui-rs standards
pub fn colorize_logs(input: &str) -> Vec<Spans<'static>> { pub fn colorize_logs<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from( vec![Spans::from(
categorise_text(input) categorise_text(input)
.into_iter() .iter()
.map(|i| { .map(|i| {
let fg_color = color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)); let style = Style::default()
let bg_color = color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)); .bg(color_ansi_to_tui(i.bg.unwrap_or(CansiColor::Black)))
let style = Style::default().bg(bg_color).fg(fg_color); .fg(color_ansi_to_tui(i.fg.unwrap_or(CansiColor::White)));
if i.blink.is_some() { if i.blink.is_some() {
style.add_modifier(Modifier::SLOW_BLINK); style.add_modifier(Modifier::SLOW_BLINK);
} }
@@ -40,17 +40,17 @@ pub mod log_sanitizer {
} }
/// Remove all ansi formatting from a given string and create tui-rs spans /// Remove all ansi formatting from a given string and create tui-rs spans
pub fn remove_ansi(input: &str) -> Vec<Spans<'static>> { pub fn remove_ansi<'a>(input: &str) -> Vec<Spans<'a>> {
let mut output = String::from(""); let mut output = String::new();
for i in categorise_text(input) { for i in categorise_text(input) {
output.push_str(i.text); output.push_str(i.text);
} }
raw(output) raw(&output)
} }
/// create tui-rs spans that exactly match the given strings /// create tui-rs spans that exactly match the given strings
pub fn raw(input: String) -> Vec<Spans<'static>> { pub fn raw<'a>(input: &str) -> Vec<Spans<'a>> {
vec![Spans::from(Span::raw(input))] vec![Spans::from(Span::raw(input.to_owned()))]
} }
/// Change from ansi to tui colors /// Change from ansi to tui colors
+61 -62
View File
@@ -39,6 +39,8 @@ const REPO: &str = env!("CARGO_PKG_REPOSITORY");
const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
const ORANGE: Color = Color::Rgb(255, 178, 36); const ORANGE: Color = Color::Rgb(255, 178, 36);
const MARGIN: &str = " "; const MARGIN: &str = " ";
const ARROW: &str = "";
const CIRCLE: &str = "";
/// Generate block, add a border if is the selected panel, /// Generate block, add a border if is the selected panel,
/// add custom title based on state of each panel /// add custom title based on state of each panel
@@ -49,9 +51,6 @@ fn generate_block<'a>(
panel: SelectablePanel, panel: SelectablePanel,
) -> Block<'a> { ) -> Block<'a> {
gui_state.lock().update_map(Region::Panel(panel), area); gui_state.lock().update_map(Region::Panel(panel), area);
let mut block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded);
let current_selected_panel = gui_state.lock().selected_panel; let current_selected_panel = gui_state.lock().selected_panel;
let title = match panel { let title = match panel {
SelectablePanel::Containers => { SelectablePanel::Containers => {
@@ -64,9 +63,12 @@ fn generate_block<'a>(
SelectablePanel::Logs => { SelectablePanel::Logs => {
format!(" {} {} ", panel.title(), app_data.lock().get_log_title()) format!(" {} {} ", panel.title(), app_data.lock().get_log_title())
} }
SelectablePanel::Commands => String::from(""), SelectablePanel::Commands => String::new(),
}; };
block = block.title(title); let mut block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.title(title);
if current_selected_panel == panel { if current_selected_panel == panel {
block = block.border_style(Style::default().fg(Color::LightCyan)); block = block.border_style(Style::default().fg(Color::LightCyan));
} }
@@ -99,7 +101,7 @@ pub fn commands<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)) .highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol(""); .highlight_symbol(ARROW);
f.render_stateful_widget( f.render_stateful_widget(
items, items,
@@ -107,10 +109,7 @@ pub fn commands<B: Backend>(
&mut app_data.lock().containers.items[i].docker_controls.state, &mut app_data.lock().containers.items[i].docker_controls.state,
); );
} else { } else {
let debug_text = String::from(""); let paragraph = Paragraph::new("").block(block).alignment(Alignment::Center);
let paragraph = Paragraph::new(debug_text)
.block(block)
.alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
} }
@@ -136,7 +135,7 @@ pub fn containers<B: Backend>(
let mems = format!( let mems = format!(
"{:>1} / {:>1}", "{:>1} / {:>1}",
i.mem_stats.back().unwrap_or(&ByteStats::new(0)), i.mem_stats.back().unwrap_or(&ByteStats::default()),
i.mem_limit i.mem_limit
); );
@@ -153,7 +152,7 @@ pub fn containers<B: Backend>(
format!( format!(
"{}{:>width$}", "{}{:>width$}",
MARGIN, MARGIN,
i.cpu_stats.back().unwrap_or(&CpuStats::new(0.0)), i.cpu_stats.back().unwrap_or(&CpuStats::default()),
width = &widths.cpu.1 width = &widths.cpu.1
), ),
state_style, state_style,
@@ -166,7 +165,7 @@ pub fn containers<B: Backend>(
format!( format!(
"{}{:>width$}", "{}{:>width$}",
MARGIN, MARGIN,
i.id.chars().take(8).collect::<String>(), i.id.get().chars().take(8).collect::<String>(),
width = &widths.id.1 width = &widths.id.1
), ),
blue, blue,
@@ -192,8 +191,7 @@ pub fn containers<B: Backend>(
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if items.is_empty() { if items.is_empty() {
let debug_text = String::from("no containers running"); let paragraph = Paragraph::new("no containers running")
let paragraph = Paragraph::new(debug_text)
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
@@ -201,7 +199,7 @@ pub fn containers<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)) .highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol(""); .highlight_symbol(CIRCLE);
f.render_stateful_widget(items, area, &mut app_data.lock().containers.state); f.render_stateful_widget(items, area, &mut app_data.lock().containers.state);
} }
@@ -220,8 +218,7 @@ pub fn logs<B: Backend>(
let init = app_data.lock().init; let init = app_data.lock().init;
if !init { if !init {
let parsing_logs = format!("parsing logs {}", loading_icon); let paragraph = Paragraph::new(format!("parsing logs {}", loading_icon))
let paragraph = Paragraph::new(parsing_logs)
.style(Style::default()) .style(Style::default())
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
@@ -237,7 +234,7 @@ pub fn logs<B: Backend>(
let items = List::new(items) let items = List::new(items)
.block(block) .block(block)
.highlight_symbol("") .highlight_symbol(ARROW)
.highlight_style(Style::default().add_modifier(Modifier::BOLD)); .highlight_style(Style::default().add_modifier(Modifier::BOLD));
f.render_stateful_widget( f.render_stateful_widget(
items, items,
@@ -245,8 +242,7 @@ pub fn logs<B: Backend>(
&mut app_data.lock().containers.items[index].logs.state, &mut app_data.lock().containers.items[index].logs.state,
); );
} else { } else {
let debug_text = String::from("no logs found"); let paragraph = Paragraph::new("no logs found")
let paragraph = Paragraph::new(debug_text)
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
@@ -281,8 +277,8 @@ pub fn chart<B: Backend>(
.data(&mem.0)]; .data(&mem.0)];
let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1)); let cpu_stats = CpuStats::new(cpu.0.last().map_or(0.00, |f| f.1));
let mem_stats = ByteStats::new(mem.0.last().map_or(0, |f| f.1 as u64)); let mem_stats = ByteStats::new(mem.0.last().map_or(0, |f| f.1 as u64));
let cpu_chart = make_chart(&cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1); let cpu_chart = make_chart(cpu.2, "cpu", cpu_dataset, &cpu_stats, &cpu.1);
let mem_chart = make_chart(&mem.2, "memory", mem_dataset, &mem_stats, &mem.1); let mem_chart = make_chart(mem.2, "memory", mem_dataset, &mem_stats, &mem.1);
f.render_widget(cpu_chart, area[0]); f.render_widget(cpu_chart, area[0]);
f.render_widget(mem_chart, area[1]); f.render_widget(mem_chart, area[1]);
@@ -292,7 +288,7 @@ pub fn chart<B: Backend>(
/// Create charts /// Create charts
fn make_chart<'a, T: Stats + Display>( fn make_chart<'a, T: Stats + Display>(
state: &State, state: State,
name: &'a str, name: &'a str,
dataset: Vec<Dataset<'a>>, dataset: Vec<Dataset<'a>>,
current: &'a T, current: &'a T,
@@ -340,14 +336,15 @@ fn make_chart<'a, T: Stats + Display>(
) )
} }
/// Draw heading bar at top of program, always visible /// Draw heading bar at top of program, always visible
#[allow(clippy::too_many_lines)]
pub fn heading_bar<B: Backend>( pub fn heading_bar<B: Backend>(
area: Rect, area: Rect,
columns: &Columns, columns: &Columns,
f: &mut Frame<'_, B>, f: &mut Frame<'_, B>,
has_containers: bool, has_containers: bool,
loading_icon: &str, loading_icon: &str,
sorted_by: &Option<(Header, SortedOrder)>, sorted_by: Option<(Header, SortedOrder)>,
gui_state: &Arc<Mutex<GuiState>>, gui_state: &Arc<Mutex<GuiState>>,
) { ) {
let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black)); let block = || Block::default().style(Style::default().bg(Color::Magenta).fg(Color::Black));
@@ -405,14 +402,14 @@ pub fn heading_bar<B: Backend>(
width = width - block.2 width = width - block.2
), ),
}; };
let count = text.chars().count() as u16; let count = u16::try_from(text.chars().count()).unwrap_or_default();
let status = Paragraph::new(text) let status = Paragraph::new(text)
.block(block.0) .block(block.0)
.alignment(Alignment::Left); .alignment(Alignment::Left);
(status, count) (status, count)
}; };
// Meta data for iterate over to create blocks and correct widths // Meta data to iterate over to create blocks with correct widths
let header_meta = [ let header_meta = [
(Header::State, columns.state.1), (Header::State, columns.state.1),
(Header::Status, columns.status.1), (Header::Status, columns.status.1),
@@ -429,18 +426,21 @@ pub fn heading_bar<B: Backend>(
.iter() .iter()
.map(|i| { .map(|i| {
let header_block = gen_header(&i.0, i.1); let header_block = gen_header(&i.0, i.1);
(header_block.0, i.0.clone(), Constraint::Max(header_block.1)) (header_block.0, i.0, Constraint::Max(header_block.1))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let suffix = if info_visible { "exit" } else { "show" }; let suffix = if info_visible { "exit" } else { "show" };
let info_text = format!("( h ) {} help {}", suffix, MARGIN); let info_text = format!("( h ) {} help {}", suffix, MARGIN);
let info_width = info_text.chars().count() as u16; let info_width = info_text.chars().count();
let column_width = area.width - info_width; let column_width = usize::from(area.width) - info_width;
let column_width = if column_width > 0 { column_width } else { 1 }; let column_width = if column_width > 0 { column_width } else { 1 };
let splits = if has_containers { let splits = if has_containers {
vec![Constraint::Min(column_width), Constraint::Min(info_width)] vec![
Constraint::Min(column_width.try_into().unwrap_or_default()),
Constraint::Min(info_width.try_into().unwrap_or_default()),
]
} else { } else {
vec![Constraint::Percentage(100)] vec![Constraint::Percentage(100)]
}; };
@@ -469,11 +469,12 @@ pub fn heading_bar<B: Backend>(
.block(block()) .block(block())
.alignment(Alignment::Right); .alignment(Alignment::Right);
// If no containers, don't display the headers, could maybe do this first?
let index = if has_containers { 1 } else { 0 }; let index = if has_containers { 1 } else { 0 };
f.render_widget(paragraph, split_bar[index]); f.render_widget(paragraph, split_bar[index]);
} }
/// From a given &String, return the maximum number of chars on a single line /// From a given &str, return the maximum number of chars on a single line
fn max_line_width(text: &str) -> usize { fn max_line_width(text: &str) -> usize {
let mut max_line_width = 0; let mut max_line_width = 0;
text.lines().into_iter().for_each(|line| { text.lines().into_iter().for_each(|line| {
@@ -486,6 +487,7 @@ fn max_line_width(text: &str) -> usize {
} }
/// Draw the help box in the centre of the screen /// Draw the help box in the centre of the screen
/// TODO this is message, should make every line it's own renderable span
pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) { pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
let title = format!(" {} ", VERSION); let title = format!(" {} ", VERSION);
@@ -536,20 +538,21 @@ pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
.border_style(Style::default().fg(Color::Black)); .border_style(Style::default().fg(Color::Black));
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::MiddleCentre,
);
let split_popup = Layout::default() let split_popup = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints( .constraints(
[ [
Constraint::Max(NAME_TEXT.lines().count() as u16), Constraint::Max(NAME_TEXT.lines().count().try_into().unwrap_or_default()),
Constraint::Max(description_text.lines().count() as u16), Constraint::Max(
Constraint::Max(help_text.lines().count() as u16), description_text
.lines()
.count()
.try_into()
.unwrap_or_default(),
),
Constraint::Max(help_text.lines().count().try_into().unwrap_or_default()),
] ]
.as_ref(), .as_ref(),
) )
@@ -564,7 +567,7 @@ pub fn help_box<B: Backend>(f: &mut Frame<'_, B>) {
} }
/// Draw an error popup over whole screen /// Draw an error popup over whole screen
pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: &AppError, seconds: Option<u8>) { pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: AppError, seconds: Option<u8>) {
let block = Block::default() let block = Block::default()
.title(" Error ") .title(" Error ")
.border_type(BorderType::Rounded) .border_type(BorderType::Rounded)
@@ -600,12 +603,7 @@ pub fn error<B: Backend>(f: &mut Frame<'_, B>, error: &AppError, seconds: Option
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::MiddleCentre);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::MiddleCentre,
);
f.render_widget(Clear, area); f.render_widget(Clear, area);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
@@ -629,32 +627,33 @@ pub fn info<B: Backend>(f: &mut Frame<'_, B>, text: String) {
.block(block) .block(block)
.alignment(Alignment::Center); .alignment(Alignment::Center);
let area = popup( let area = popup(lines, max_line_width, f.size(), BoxLocation::BottomRight);
lines as u16,
max_line_width as u16,
f.size(),
BoxLocation::BottomRight,
);
f.render_widget(Clear, area); f.render_widget(Clear, area);
f.render_widget(paragraph, area); f.render_widget(paragraph, area);
} }
/// draw a box in the one of the BoxLocations, based on max line width + number of lines /// draw a box in the one of the BoxLocations, based on max line width + number of lines
fn popup(text_lines: u16, text_width: u16, r: Rect, box_location: BoxLocation) -> Rect { fn popup(text_lines: usize, text_width: usize, r: Rect, box_location: BoxLocation) -> Rect {
// Make sure blank_space can't be an negative, as will crash // Make sure blank_space can't be an negative, as will crash
let blank_vertical = if r.height > text_lines { let blank_vertical = if usize::from(r.height) > text_lines {
(r.height - text_lines) / 2 (usize::from(r.height) - text_lines) / 2
} else { } else {
1 1
}; };
let blank_horizontal = if r.width > text_width { let blank_horizontal = if usize::from(r.width) > text_width {
(r.width - text_width) / 2 (usize::from(r.width) - text_width) / 2
} else { } else {
1 1
}; };
let v_constraints = box_location.get_vertical_constraints(blank_vertical, text_lines); let v_constraints = box_location.get_vertical_constraints(
let h_constraints = box_location.get_horizontal_constraints(blank_horizontal, text_width); blank_vertical.try_into().unwrap_or_default(),
text_lines.try_into().unwrap_or_default(),
);
let h_constraints = box_location.get_horizontal_constraints(
blank_horizontal.try_into().unwrap_or_default(),
text_width.try_into().unwrap_or_default(),
);
let indexes = box_location.get_indexes(); let indexes = box_location.get_indexes();
+9 -8
View File
@@ -7,7 +7,7 @@ use uuid::Uuid;
use crate::app_data::Header; use crate::app_data::Header;
#[derive(Debug, PartialEq, std::hash::Hash, std::cmp::Eq, Clone, Copy)] #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum SelectablePanel { pub enum SelectablePanel {
Containers, Containers,
Commands, Commands,
@@ -38,6 +38,7 @@ impl SelectablePanel {
} }
} }
#[derive(Debug, Copy, Clone)]
pub enum Region { pub enum Region {
Panel(SelectablePanel), Panel(SelectablePanel),
Header(Header), Header(Header),
@@ -72,7 +73,7 @@ impl BoxLocation {
} }
} }
// Should combine and just return a tuple? // Should combine with get_vertical_constraints and just return a tuple of (vc, hc)?
pub const fn get_horizontal_constraints( pub const fn get_horizontal_constraints(
self, self,
blank_vertical: u16, blank_vertical: u16,
@@ -221,7 +222,7 @@ impl GuiState {
.filter(|i| i.1.intersects(rect)) .filter(|i| i.1.intersects(rect))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.get(0) .get(0)
.map(|data| data.0.clone()) .map(|data| *data.0)
} }
/// Insert, or updates header area panel into heading_map /// Insert, or updates header area panel into heading_map
@@ -250,22 +251,22 @@ impl GuiState {
self.selected_panel = self.selected_panel.prev(); self.selected_panel = self.selected_panel.prev();
} }
/// Advance loading animation /// Insert a new loading_uuid into hashset, and advance the animation by one frame
pub fn next_loading(&mut self, uuid: Uuid) { pub fn next_loading(&mut self, uuid: Uuid) {
self.loading_icon = self.loading_icon.next(); self.loading_icon = self.loading_icon.next();
self.is_loading.insert(uuid); self.is_loading.insert(uuid);
} }
/// if is_loading, return loading animation frame, else single space /// If is_loading has any entries, return the current loading_icon, else an emtpy string
pub fn get_loading(&mut self) -> String { pub fn get_loading(&mut self) -> String {
if self.is_loading.is_empty() { if self.is_loading.is_empty() {
String::from(" ") String::new()
} else { } else {
self.loading_icon.to_string() self.loading_icon.to_string()
} }
} }
/// set is_loading to false, but keep animation frame at same state /// Remove a loading_uuid from the is_loading hashset
pub fn remove_loading(&mut self, uuid: Uuid) { pub fn remove_loading(&mut self, uuid: Uuid) {
self.is_loading.remove(&uuid); self.is_loading.remove(&uuid);
} }
+13 -5
View File
@@ -93,7 +93,7 @@ async fn run_app<B: Backend + Send>(
break; break;
} }
if terminal if terminal
.draw(|f| draw_blocks::error(f, &AppError::DockerConnect, Some(seconds))) .draw(|f| draw_blocks::error(f, AppError::DockerConnect, Some(seconds)))
.is_err() .is_err()
{ {
return Err(AppError::Terminal); return Err(AppError::Terminal);
@@ -107,6 +107,8 @@ async fn run_app<B: Backend + Send>(
if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() { if terminal.draw(|f| ui(f, &app_data, &gui_state)).is_err() {
return Err(AppError::Terminal); return Err(AppError::Terminal);
} }
// TODO could only draw if in gui mode, that way all inputs & docker commands will run, and can just trace!("{event"}) all over the place
// refactor this into own function, so can be called without drawing to the terminal
if crossterm::event::poll(input_poll_rate).unwrap_or(false) { if crossterm::event::poll(input_poll_rate).unwrap_or(false) {
if let Ok(event) = event::read() { if let Ok(event) = event::read() {
if let Event::Key(key) = event { if let Event::Key(key) = event {
@@ -146,7 +148,7 @@ fn ui<B: Backend>(
) { ) {
// set max height for container section, needs +4 to deal with docker commands list and borders // set max height for container section, needs +4 to deal with docker commands list and borders
let height = app_data.lock().get_container_len(); let height = app_data.lock().get_container_len();
let height = if height < 12 { (height + 4) as u16 } else { 12 }; let height = if height < 12 { height + 4 } else { 12 };
let column_widths = app_data.lock().get_width(); let column_widths = app_data.lock().get_width();
let has_containers = !app_data.lock().containers.items.is_empty(); let has_containers = !app_data.lock().containers.items.is_empty();
@@ -166,7 +168,13 @@ fn ui<B: Backend>(
// Split into 3, containers+controls, logs, then graphs // Split into 3, containers+controls, logs, then graphs
let upper_main = Layout::default() let upper_main = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints([Constraint::Max(height as u16), Constraint::Percentage(50)].as_ref()) .constraints(
[
Constraint::Max(height.try_into().unwrap_or_default()),
Constraint::Percentage(50),
]
.as_ref(),
)
.split(whole_layout[1]); .split(whole_layout[1]);
let top_split = if has_containers { let top_split = if has_containers {
@@ -213,7 +221,7 @@ fn ui<B: Backend>(
f, f,
has_containers, has_containers,
&loading_icon, &loading_icon,
&sorted_by, sorted_by,
gui_state, gui_state,
); );
@@ -233,6 +241,6 @@ fn ui<B: Backend>(
if let Some(error) = has_error { if let Some(error) = has_error {
app_data.lock().show_error = true; app_data.lock().show_error = true;
draw_blocks::error(f, &error, None); draw_blocks::error(f, error, None);
} }
} }