use anyhow::Result;
use crossterm::{
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout, Rect},
text::Text,
widgets::ListState,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
io,
sync::{
Arc, Once,
atomic::{AtomicBool, Ordering},
},
time::Instant,
};
use tokio::io::{AsyncBufReadExt, AsyncReadExt};
use tokio::sync::mpsc;
pub const NEWS_PAGE_SIZE: usize = 25;
pub mod browser;
pub mod dashboard;
pub mod groups;
pub mod help;
pub mod history;
pub mod news;
pub mod stats;
pub mod theme;
pub mod transaction;
#[derive(PartialEq, Clone, Copy)]
pub enum BrowserTab {
Overview,
Dependencies,
Files,
Queue,
}
#[derive(Clone, Debug)]
pub struct BrowserCache {
pub info: String,
pub files: Vec<String>,
pub dependencies: Vec<String>,
pub loading_info: bool,
pub loading_files: bool,
}
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum SelectionMode {
Explicit,
AllVisible,
}
#[derive(PartialEq)]
pub enum CurrentScreen {
Dashboard,
Browser,
News,
Stats,
History,
Groups,
}
#[derive(PartialEq, Clone, Copy)]
pub enum DashboardWidget {
Blahaj,
News,
}
#[derive(PartialEq)]
pub enum InputMode {
Normal,
Editing,
}
#[derive(PartialEq)]
pub enum NewsFocus {
List,
Article,
}
#[derive(Clone, PartialEq, Debug)]
pub enum PackageFilter {
All,
Installed,
NotInstalled,
Updates,
Aur,
Repositories,
Group(String),
}
#[derive(Clone)]
pub struct GroupInfo {
pub name: String,
pub packages: Vec<(String, bool)>,
pub description: String,
pub is_favorite: bool,
}
#[derive(Clone, PartialEq, Debug)]
pub enum GroupSortMode {
Alphabetical,
PackageCount,
InstallCompletion,
}
impl std::fmt::Display for PackageFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::All => write!(f, "all"),
Self::Installed => write!(f, "installed"),
Self::NotInstalled => write!(f, "not installed"),
Self::Updates => write!(f, "updates"),
Self::Aur => write!(f, "aur"),
Self::Repositories => write!(f, "repositories"),
Self::Group(name) => write!(f, "group:{name}"),
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub enum SortMode {
Alphabetical,
Installed,
Repository,
Relevance,
}
impl std::fmt::Display for SortMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Alphabetical => write!(f, "alphabetical"),
Self::Installed => write!(f, "installed"),
Self::Repository => write!(f, "repository"),
Self::Relevance => write!(f, "relevance"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NewsItem {
pub title: String,
pub link: String,
pub pub_date: String,
pub description: String,
pub is_critical: bool,
}
pub enum TuiEvent {
_Tick,
Key(crossterm::event::KeyEvent),
PacmanLog(String),
UpdateAction(String),
PacmanProgress(u16),
TransactionComplete,
TransactionFailed,
CloseTransaction,
DashboardArtFrame(Text<'static>),
NewsFetched(Vec<NewsItem>, String),
NewsFetchFailed(String),
NewsBodyFetched(String, String),
NewsTotalCount(usize),
BrowserInfoLoaded(String, String, Vec<String>),
BrowserFilesLoaded(String, Vec<String>),
AurResultsLoaded(String, Vec<crate::core::package::PackageModel>),
StateRefreshed(Box<RefreshSnapshot>),
CatalogCacheLoaded(Box<CachedCatalog>),
ExternalUpdatesReady(Vec<(String, String, String)>),
OrphanListReady(Vec<crate::core::package::PackageModel>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CachedCatalog {
pub backend: String,
pub packages: Vec<crate::core::package::PackageModel>,
pub installed_count: usize,
pub updates_count: usize,
pub explicit_count: usize,
pub orphan_count: usize,
}
fn catalog_cache_path(scope_key: &str) -> std::path::PathBuf {
let home = std::env::var("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default();
let filename = if matches!(scope_key, "pacman" | "apt" | "dnf") {
"catalog.json".to_string()
} else {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for b in scope_key.as_bytes() {
hash ^= u64::from(*b);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
format!("catalog-{hash:016x}.json")
};
home.join(".cache/haj").join(filename)
}
pub(crate) fn load_cached_catalog(
scope_key: &str,
expected_backend: &str,
) -> Option<CachedCatalog> {
let data = std::fs::read(catalog_cache_path(scope_key)).ok()?;
let cat: CachedCatalog = serde_json::from_slice(&data).ok()?;
(cat.backend == expected_backend).then_some(cat)
}
pub(crate) fn save_cached_catalog(scope_key: &str, cat: &CachedCatalog) {
let path = catalog_cache_path(scope_key);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let tmp = path.with_extension("json.tmp");
if let Ok(bytes) = serde_json::to_vec(cat)
&& std::fs::write(&tmp, bytes).is_ok()
{
let _ = std::fs::rename(tmp, path);
}
}
pub struct RefreshSnapshot {
pub orphan_count: usize,
pub package_list: Vec<crate::core::package::PackageModel>,
pub installed_count: usize,
pub updates_count: usize,
pub transactions: Vec<Transaction>,
pub groups: Vec<GroupInfo>,
pub cache_size: String,
pub explicit_count: usize,
pub kernel: String,
pub uptime: String,
pub free_space: String,
pub last_sync: String,
pub last_refreshed: String,
}
impl RefreshSnapshot {
pub(crate) fn to_cached_catalog(&self, backend_name: &str) -> CachedCatalog {
CachedCatalog {
backend: backend_name.to_string(),
packages: self.package_list.clone(),
installed_count: self.installed_count,
updates_count: self.updates_count,
explicit_count: self.explicit_count,
orphan_count: self.orphan_count,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum TxAction {
Install,
Upgrade,
Remove,
Unknown,
}
#[derive(Clone, Debug)]
pub struct PkgChange {
pub name: String,
pub old_version: Option<String>,
pub new_version: String,
pub action: TxAction,
}
#[derive(Clone, Debug)]
pub struct Transaction {
pub timestamp: String,
pub is_success: bool,
pub primary_action: TxAction,
pub packages: Vec<PkgChange>,
pub hooks: Vec<String>,
pub warnings: Vec<String>,
pub raw_log: Vec<String>,
}
#[derive(Clone, PartialEq, Debug)]
pub enum HistoryFilter {
All,
Installs,
Upgrades,
Removals,
Failures,
}
pub struct App {
pub should_quit: bool,
pub screen: CurrentScreen,
pub input_mode: InputMode,
pub last_activity: Instant,
pub orphan_count: usize,
pub installed_count: usize,
pub updates_count: usize,
pub show_help: bool,
pub active_widget: DashboardWidget,
pub backend_name: &'static str,
pub cache_scope: String,
pub supports_external: bool,
pub filters: Vec<PackageFilter>,
pub filter_idx: usize,
pub sort_mode: SortMode,
pub package_list: Vec<crate::core::package::PackageModel>,
pub remote_aur_packages: Vec<crate::core::package::PackageModel>,
pub aur_last_query: String,
pub filtered_packages: Vec<crate::core::package::PackageModel>,
pub search_query: String,
pub list_state: ListState,
pub selected_packages: HashSet<String>,
pub show_prompt: bool,
pub prompt_type: String,
pub prompt_targets: Vec<String>,
pub is_installing: bool,
pub current_action: String,
pub progress: u16,
pub transaction_logs: Vec<String>,
pub dashboard_art: Text<'static>,
pub abort_tx: Option<mpsc::Sender<()>>,
pub news_items: Vec<NewsItem>,
pub filtered_news: Vec<NewsItem>,
pub read_news: HashSet<String>,
pub news_list_state: ListState,
pub news_scroll: u16,
pub news_search_query: String,
pub news_focus: NewsFocus,
pub is_fetching_news: bool,
pub news_last_updated: String,
pub news_error: String,
pub news_page: usize,
pub news_total_count: usize,
pub transactions: Vec<Transaction>,
pub filtered_transactions: Vec<Transaction>,
pub history_state: ListState,
pub history_search_query: String,
pub history_filter: HistoryFilter,
pub history_expanded: bool,
pub history_scroll: u16,
pub history_input_mode: InputMode,
pub group_state: ListState,
pub cache_size: String,
pub groups: Vec<GroupInfo>,
pub filtered_groups: Vec<GroupInfo>,
pub group_search_query: String,
pub group_sort_mode: GroupSortMode,
pub group_input_mode: InputMode,
pub explicit_count: usize,
pub kernel: String,
pub uptime: String,
pub free_space: String,
pub last_sync: String,
pub last_refreshed: String,
pub browser_tab: BrowserTab,
pub browser_pkg_name: String,
pub browser_caches: std::collections::HashMap<String, BrowserCache>,
pub browser_scroll: u16,
pub deselected_packages: HashSet<String>,
pub selection_mode: SelectionMode,
pub needs_refresh: bool,
pub is_refreshing: bool,
pub tx_failed: bool,
pub pending_external_updates: Option<Vec<(String, String, String)>>,
pub theme: theme::Theme,
}
impl App {
pub fn new(backend_name: &'static str, supports_external: bool) -> Self {
let mut dynamic_filters = vec![
PackageFilter::All,
PackageFilter::Installed,
PackageFilter::NotInstalled,
PackageFilter::Updates,
];
if supports_external {
dynamic_filters.push(PackageFilter::Aur);
}
dynamic_filters.push(PackageFilter::Repositories);
let is_arch_news = backend_name == "pacman";
let home = std::env::var("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default();
let cache_dir = home.join(".cache/haj");
let _ = std::fs::create_dir_all(&cache_dir);
let read_news: HashSet<String> = std::fs::read_to_string(cache_dir.join("read_news.json"))
.ok()
.and_then(|data| serde_json::from_str(&data).ok())
.unwrap_or_default();
let mut list_state = ListState::default();
list_state.select(Some(0));
let mut app = Self {
should_quit: false,
screen: CurrentScreen::Dashboard,
input_mode: InputMode::Normal,
last_activity: Instant::now(),
show_help: false,
active_widget: DashboardWidget::Blahaj,
backend_name,
cache_scope: backend_name.to_string(),
supports_external,
filters: dynamic_filters,
filter_idx: 0,
sort_mode: SortMode::Relevance,
orphan_count: 0,
package_list: Vec::new(),
remote_aur_packages: Vec::new(),
aur_last_query: String::new(),
filtered_packages: Vec::new(),
search_query: String::new(),
list_state: ListState::default(),
selected_packages: HashSet::new(),
show_prompt: false,
prompt_type: String::new(),
prompt_targets: Vec::new(),
is_installing: false,
current_action: String::from("idle"),
progress: 0,
transaction_logs: Vec::new(),
dashboard_art: Text::raw(" loading art... "),
abort_tx: None,
news_items: Vec::new(),
filtered_news: Vec::new(),
read_news,
news_list_state: list_state,
news_scroll: 0,
news_search_query: String::new(),
news_focus: NewsFocus::List,
is_fetching_news: is_arch_news,
news_last_updated: if is_arch_news {
"checking...".to_string()
} else {
"distro feed n/a".to_string()
},
news_error: if is_arch_news {
String::new()
} else {
format!("arch news feed disabled on {backend_name} backend")
},
news_page: 1,
news_total_count: 50,
transactions: Vec::new(),
filtered_transactions: Vec::new(),
history_state: ListState::default(),
history_search_query: String::new(),
history_filter: HistoryFilter::All,
history_expanded: false,
history_scroll: 0,
history_input_mode: InputMode::Normal,
cache_size: "unknown".into(),
explicit_count: 0,
kernel: "unknown".into(),
uptime: "unknown".into(),
free_space: "unknown".into(),
last_sync: "unknown".into(),
last_refreshed: "never".into(),
groups: Vec::new(),
filtered_groups: Vec::new(),
group_state: ListState::default(),
group_search_query: String::new(),
group_sort_mode: GroupSortMode::Alphabetical,
group_input_mode: InputMode::Normal,
installed_count: 0,
updates_count: 0,
browser_tab: BrowserTab::Overview,
browser_pkg_name: String::new(),
browser_caches: std::collections::HashMap::new(),
browser_scroll: 0,
deselected_packages: HashSet::new(),
selection_mode: SelectionMode::Explicit,
needs_refresh: true,
is_refreshing: false,
tx_failed: false,
pending_external_updates: None,
theme: theme::Theme::from_config(&crate::config::load_config().colors),
};
app.refresh_state();
app
}
pub fn is_text_input_active(&self) -> bool {
matches!(
(
&self.screen,
&self.input_mode,
&self.history_input_mode,
&self.group_input_mode,
),
(
CurrentScreen::Browser | CurrentScreen::News,
InputMode::Editing,
_,
_
) | (CurrentScreen::History, _, InputMode::Editing, _)
| (CurrentScreen::Groups, _, _, InputMode::Editing)
)
}
pub fn get_selected_count(&self) -> usize {
match self.selection_mode {
SelectionMode::Explicit => self.selected_packages.len(),
SelectionMode::AllVisible => self
.filtered_packages
.len()
.saturating_sub(self.deselected_packages.len()),
}
}
pub fn is_package_selected(&self, name: &str) -> bool {
match self.selection_mode {
SelectionMode::Explicit => self.selected_packages.contains(name),
SelectionMode::AllVisible => !self.deselected_packages.contains(name),
}
}
pub fn update_history_filter(&mut self) {
let query = self.history_search_query.to_lowercase();
self.filtered_transactions = self
.transactions
.iter()
.filter(|tx| {
let matches_query = query.is_empty()
|| tx.timestamp.to_lowercase().contains(&query)
|| tx
.packages
.iter()
.any(|p| p.name.to_lowercase().contains(&query));
let matches_filter = match self.history_filter {
HistoryFilter::All => true,
HistoryFilter::Installs => tx.primary_action == TxAction::Install,
HistoryFilter::Upgrades => tx.primary_action == TxAction::Upgrade,
HistoryFilter::Removals => tx.primary_action == TxAction::Remove,
HistoryFilter::Failures => !tx.is_success,
};
matches_query && matches_filter
})
.cloned()
.collect();
if self.filtered_transactions.is_empty() {
self.history_state.select(None);
} else {
let idx = self
.history_state
.selected()
.unwrap_or(0)
.min(self.filtered_transactions.len() - 1);
self.history_state.select(Some(idx));
}
}
pub fn update_group_filter(&mut self) {
let query = self.group_search_query.to_lowercase();
self.filtered_groups = self
.groups
.iter()
.filter(|g| query.is_empty() || g.name.to_lowercase().contains(&query))
.cloned()
.collect();
self.filtered_groups.sort_by(|a, b| {
b.is_favorite
.cmp(&a.is_favorite)
.then_with(|| match self.group_sort_mode {
GroupSortMode::Alphabetical => a.name.cmp(&b.name),
GroupSortMode::PackageCount => b.packages.len().cmp(&a.packages.len()),
GroupSortMode::InstallCompletion => {
let a_inst = a.packages.iter().filter(|p| p.1).count() as f64
/ a.packages.len().max(1) as f64;
let b_inst = b.packages.iter().filter(|p| p.1).count() as f64
/ b.packages.len().max(1) as f64;
b_inst
.partial_cmp(&a_inst)
.unwrap_or(std::cmp::Ordering::Equal)
}
})
});
if self.filtered_groups.is_empty() {
self.group_state.select(None);
} else {
let idx = self
.group_state
.selected()
.unwrap_or(0)
.min(self.filtered_groups.len() - 1);
self.group_state.select(Some(idx));
}
}
pub fn mark_news_read(&mut self, link: String) {
if self.read_news.insert(link) {
let home = std::env::var("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default();
let data = serde_json::to_string(&self.read_news).unwrap_or_default();
tokio::spawn(async move {
let _ = tokio::fs::create_dir_all(home.join(".cache/haj")).await;
let _ = tokio::fs::write(home.join(".cache/haj/read_news.json"), data).await;
});
}
}
pub fn update_news_search(&mut self, reset_page: bool) {
let query = self.news_search_query.to_lowercase();
self.filtered_news = self
.news_items
.iter()
.filter(|n| {
query.is_empty()
|| n.title.to_lowercase().contains(&query)
|| n.description.to_lowercase().contains(&query)
})
.cloned()
.collect();
if reset_page {
self.news_page = 1;
self.news_list_state
.select(if self.filtered_news.is_empty() {
None
} else {
Some(0)
});
self.news_scroll = 0;
} else if let Some(idx) = self.news_list_state.selected() {
let page_size = NEWS_PAGE_SIZE;
let start_idx = (self.news_page.saturating_sub(1)) * page_size;
let end_idx = (start_idx + page_size).min(self.filtered_news.len());
let displayed_count = end_idx.saturating_sub(start_idx);
if idx >= displayed_count {
self.news_list_state.select(if displayed_count > 0 {
Some(displayed_count - 1)
} else {
None
});
}
} else if !self.filtered_news.is_empty() {
self.news_list_state.select(Some(0));
}
}
pub fn refresh_state(&mut self) {
self.needs_refresh = true;
}
pub fn is_package_external(&self, name: &str) -> bool {
self.package_list
.iter()
.chain(self.remote_aur_packages.iter())
.find(|p| p.name == name)
.is_some_and(crate::core::package::PackageModel::is_external)
}
pub fn apply_external_updates(&mut self, ext: Vec<(String, String, String)>) {
self.updates_count =
merge_external_updates(&mut self.package_list, self.updates_count, &ext);
self.update_search();
}
pub fn apply_cached_catalog(&mut self, cat: CachedCatalog) {
if self.last_refreshed != "never" {
return;
}
self.package_list = cat.packages;
self.installed_count = cat.installed_count;
self.updates_count = cat.updates_count;
self.explicit_count = cat.explicit_count;
self.orphan_count = cat.orphan_count;
self.update_search();
}
pub fn cached_catalog_snapshot(&self) -> CachedCatalog {
CachedCatalog {
backend: self.backend_name.to_string(),
packages: self.package_list.clone(),
installed_count: self.installed_count,
updates_count: self.updates_count,
explicit_count: self.explicit_count,
orphan_count: self.orphan_count,
}
}
pub fn apply_refresh(&mut self, snap: RefreshSnapshot) {
self.orphan_count = snap.orphan_count;
self.package_list = snap.package_list;
self.installed_count = snap.installed_count;
self.updates_count = snap.updates_count;
self.transactions = snap.transactions;
self.update_history_filter();
let prev_favs: HashSet<String> = self
.groups
.iter()
.filter(|g| g.is_favorite)
.map(|g| g.name.clone())
.collect();
self.groups = snap.groups;
for g in &mut self.groups {
if prev_favs.contains(&g.name) {
g.is_favorite = true;
}
}
self.cache_size = snap.cache_size;
self.browser_caches.clear();
self.browser_pkg_name.clear();
if !self.transactions.is_empty() {
self.history_state.select(Some(0));
}
if !self.groups.is_empty() {
self.group_state.select(Some(0));
}
self.explicit_count = snap.explicit_count;
if !snap.kernel.is_empty() {
self.kernel = snap.kernel;
}
if !snap.uptime.is_empty() {
self.uptime = snap.uptime;
}
if !snap.free_space.is_empty() {
self.free_space = snap.free_space;
}
self.last_sync = snap.last_sync;
self.last_refreshed = snap.last_refreshed;
self.update_search();
self.update_group_filter();
}
pub fn reset_selection_if_all_visible(&mut self) {
if self.selection_mode == SelectionMode::AllVisible {
self.selection_mode = SelectionMode::Explicit;
self.deselected_packages.clear();
}
}
pub fn update_search(&mut self) {
let query = self.search_query.to_lowercase();
let current_filter = &self.filters[self.filter_idx];
let known_names: HashSet<&str> =
self.package_list.iter().map(|p| p.name.as_str()).collect();
self.filtered_packages = self
.package_list
.iter()
.chain(
self.remote_aur_packages
.iter()
.filter(|p| !known_names.contains(p.name.as_str())),
)
.filter(|p| {
let matches_query = query.is_empty() || p.name.to_lowercase().contains(&query);
let matches_filter = match current_filter {
PackageFilter::All => true,
PackageFilter::Installed => p.is_installed,
PackageFilter::NotInstalled => !p.is_installed,
PackageFilter::Updates => p.is_upgradable,
PackageFilter::Aur => p.is_external(),
PackageFilter::Repositories => !p.is_external(),
PackageFilter::Group(gname) => {
if let Some(g) = self.groups.iter().find(|x| &x.name == gname) {
g.packages.iter().any(|pkg| pkg.0 == p.name)
} else {
false
}
}
};
matches_query && matches_filter
})
.cloned()
.collect();
match self.sort_mode {
SortMode::Alphabetical => {
self.filtered_packages.sort_by(|a, b| a.name.cmp(&b.name));
}
SortMode::Repository => {
self.filtered_packages
.sort_by(|a, b| a.repo.cmp(&b.repo).then(a.name.cmp(&b.name)));
}
SortMode::Installed => {
self.filtered_packages.sort_by(|a, b| {
b.is_installed
.cmp(&a.is_installed)
.then(a.name.cmp(&b.name))
});
}
SortMode::Relevance => {
if query.is_empty() {
self.filtered_packages.sort_by(|a, b| a.name.cmp(&b.name));
} else {
self.filtered_packages.sort_by(|a, b| {
let a_name = a.name.to_lowercase();
let b_name = b.name.to_lowercase();
let a_exact = a_name == query;
let b_exact = b_name == query;
let a_starts = a_name.starts_with(&query);
let b_starts = b_name.starts_with(&query);
b_exact
.cmp(&a_exact)
.then(b_starts.cmp(&a_starts))
.then(a_name.len().cmp(&b_name.len()))
.then(a.name.cmp(&b_name))
});
}
}
}
if self.filtered_packages.is_empty() {
self.list_state.select(None);
} else {
let current_idx = self.list_state.selected().unwrap_or(0);
if current_idx >= self.filtered_packages.len() {
self.list_state
.select(Some(self.filtered_packages.len() - 1));
} else {
self.list_state.select(Some(current_idx));
}
}
}
pub fn next_item(&mut self) {
if self.filtered_packages.is_empty() {
return;
}
let i = match self.list_state.selected() {
Some(i) => {
if i >= self.filtered_packages.len() - 1 {
0
} else {
i + 1
}
}
None => 0,
};
self.list_state.select(Some(i));
}
pub fn previous_item(&mut self) {
if self.filtered_packages.is_empty() {
return;
}
let i = match self.list_state.selected() {
Some(i) => {
if i == 0 {
self.filtered_packages.len() - 1
} else {
i - 1
}
}
None => 0,
};
self.list_state.select(Some(i));
}
pub fn go_to_top(&mut self) {
if !self.filtered_packages.is_empty() {
self.list_state.select(Some(0));
}
}
pub fn go_to_bottom(&mut self) {
if !self.filtered_packages.is_empty() {
self.list_state
.select(Some(self.filtered_packages.len() - 1));
}
}
}
pub mod events;
pub mod news_fetch;
use events::run_app;
use news_fetch::{fetch_arch_news, fetch_article_body};
pub(crate) fn transactions_from_history(
entries: Vec<crate::backend::traits::HistoryEntry>,
) -> Vec<Transaction> {
let mut txs: Vec<Transaction> = Vec::new();
for entry in entries {
let ts: String = entry.timestamp.chars().take(16).collect();
let action = match entry.action.as_str() {
"installed" | "install" => TxAction::Install,
"upgraded" | "upgrade" => TxAction::Upgrade,
"removed" | "remove" => TxAction::Remove,
_ => TxAction::Unknown,
};
let raw = format!(
"[{}] {} {} {}",
entry.timestamp, entry.action, entry.package, entry.version
);
let change = PkgChange {
name: entry.package,
old_version: None,
new_version: entry.version,
action: action.clone(),
};
if let Some(last) = txs.last_mut()
&& last.timestamp == ts
{
last.packages.push(change);
last.raw_log.push(raw);
continue;
}
txs.push(Transaction {
timestamp: ts,
is_success: true,
primary_action: action,
packages: vec![change],
hooks: Vec::new(),
warnings: Vec::new(),
raw_log: vec![raw],
});
}
txs
}
pub(crate) async fn fetch_refresh_snapshot(
backend: Arc<dyn crate::backend::traits::PackageManager>,
backend_name: &'static str,
) -> RefreshSnapshot {
let log_fut = async {
if backend_name == "pacman" {
backend.get_log(5000).await.ok()
} else {
None
}
};
let meta_backend = Arc::clone(&backend);
let meta_fut = tokio::task::spawn_blocking(move || {
(
meta_backend.cache_size(),
meta_backend.last_sync_timestamp(),
)
});
let (local_snap, log_res, meta_res, uname_res, uptime_res, df_res) = tokio::join!(
backend.get_tui_local_snapshot(),
log_fut,
meta_fut,
tokio::process::Command::new("uname").arg("-r").output(),
tokio::process::Command::new("uptime").arg("-p").output(),
tokio::process::Command::new("df")
.args(["-h", "/"])
.output(),
);
let local = local_snap.unwrap_or_default();
let orphan_count = local.orphan_count;
let package_list = local.packages;
let installed_count = local.installed_count;
let updates_count = local.updates_count;
let explicit_count = local.explicit_count;
let installed_set: std::collections::HashSet<&str> = package_list
.iter()
.filter(|p| p.is_installed)
.map(|p| p.name.as_str())
.collect();
let groups: Vec<GroupInfo> = local
.groups
.into_iter()
.map(|(name, pkg_names)| {
let packages: Vec<(String, bool)> = pkg_names
.into_iter()
.map(|p| {
let inst = installed_set.contains(p.as_str());
(p, inst)
})
.collect();
let inst_count = packages.iter().filter(|(_, inst)| *inst).count();
let total = packages.len();
GroupInfo {
name,
packages,
description: format!(
"Package group containing {total} packages ({inst_count} installed)"
),
is_favorite: false,
}
})
.collect();
let mut transactions = Vec::new();
if let Some(lines) = log_res {
let mut current_tx: Option<Transaction> = None;
for entry in lines {
let line = entry.message.as_str();
let ts = if !entry.timestamp.is_empty() {
entry.timestamp.chars().take(16).collect()
} else if line.starts_with('[') && line.len() > 18 {
line[1..17].to_string()
} else {
"unknown".to_string()
};
if line.contains("transaction started") {
current_tx = Some(Transaction {
timestamp: ts,
is_success: false,
primary_action: TxAction::Unknown,
packages: Vec::new(),
hooks: Vec::new(),
warnings: Vec::new(),
raw_log: vec![line.to_string()],
});
} else if line.contains("transaction completed") || line.contains("transaction failed")
{
if let Some(mut tx) = current_tx.take() {
tx.raw_log.push(line.to_string());
tx.is_success = line.contains("transaction completed");
let installs = tx
.packages
.iter()
.filter(|p| p.action == TxAction::Install)
.count();
let upgrades = tx
.packages
.iter()
.filter(|p| p.action == TxAction::Upgrade)
.count();
let removals = tx
.packages
.iter()
.filter(|p| p.action == TxAction::Remove)
.count();
tx.primary_action = if upgrades > installs && upgrades > removals {
TxAction::Upgrade
} else if removals > installs && removals > upgrades {
TxAction::Remove
} else if installs > 0 {
TxAction::Install
} else {
TxAction::Unknown
};
transactions.push(tx);
}
} else if let Some(ref mut tx) = current_tx {
tx.raw_log.push(line.to_string());
let alpm_body = line.split("[ALPM] ").nth(1).unwrap_or(line);
if let Some(rest) = alpm_body.strip_prefix("installed ") {
let parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 2 {
tx.packages.push(PkgChange {
name: parts[0].to_string(),
old_version: None,
new_version: parts[1].replace(['(', ')'], ""),
action: TxAction::Install,
});
}
} else if let Some(rest) = alpm_body.strip_prefix("upgraded ") {
let parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 4 {
tx.packages.push(PkgChange {
name: parts[0].to_string(),
old_version: Some(parts[1].replace('(', "")),
new_version: parts[3].replace(')', ""),
action: TxAction::Upgrade,
});
}
} else if let Some(rest) = alpm_body.strip_prefix("removed ") {
let parts: Vec<&str> = rest.split_whitespace().collect();
if parts.len() >= 2 {
tx.packages.push(PkgChange {
name: parts[0].to_string(),
old_version: None,
new_version: parts[1].replace(['(', ')'], ""),
action: TxAction::Remove,
});
}
} else if line.contains("warning:") {
tx.warnings.push(
line.split("warning:")
.last()
.unwrap_or("")
.trim()
.to_string(),
);
} else if line.contains("Running") && line.contains("hook") {
tx.hooks.push(
line.split("Running")
.last()
.unwrap_or("")
.replace("hook...", "")
.trim()
.to_string(),
);
}
}
}
transactions.reverse();
}
if transactions.is_empty()
&& let Ok(history) = backend.get_history(500).await
{
transactions = transactions_from_history(history);
}
let (cache_size_opt, last_sync_ts) = meta_res.unwrap_or((None, None));
let cache_size = cache_size_opt.unwrap_or_else(|| "unknown".to_string());
let kernel = uname_res
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_default();
let uptime = uptime_res
.map(|o| String::from_utf8_lossy(&o.stdout).trim().replace("up ", ""))
.unwrap_or_default();
let free_space = df_res
.map(|o| parse_df_available(&String::from_utf8_lossy(&o.stdout)))
.unwrap_or_default();
let last_sync = if let Some(ts) = last_sync_ts {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
format_elapsed_ago(ts, now)
} else {
"unknown".to_string()
};
let last_refreshed = chrono::Local::now().format("%H:%M:%S").to_string();
RefreshSnapshot {
orphan_count,
package_list,
installed_count,
updates_count,
transactions,
groups,
cache_size,
explicit_count,
kernel,
uptime,
free_space,
last_sync,
last_refreshed,
}
}
static TUI_ACTIVE: AtomicBool = AtomicBool::new(false);
static TUI_PANIC_HOOK: Once = Once::new();
pub fn restore_terminal() {
if TUI_ACTIVE.swap(false, Ordering::SeqCst) {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen, crossterm::cursor::Show);
}
}
struct TerminalGuard;
impl Drop for TerminalGuard {
fn drop(&mut self) {
restore_terminal();
}
}
pub(crate) fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
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),
]
.as_ref(),
)
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
]
.as_ref(),
)
.split(popup_layout[1])[1]
}
pub(crate) fn draw_bar(pct: f64, width: usize) -> String {
let filled = ((pct / 100.0) * width as f64).round() as usize;
let filled = filled.min(width);
let empty = width.saturating_sub(filled);
format!("{}{}", "█".repeat(filled), "░".repeat(empty))
}
pub async fn run(backend_pkg_mgr: Arc<dyn crate::backend::traits::PackageManager>) -> Result<()> {
TUI_PANIC_HOOK.call_once(|| {
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
restore_terminal();
prev(info);
}));
});
TUI_ACTIVE.store(true, Ordering::SeqCst);
let _guard = TerminalGuard;
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut app = App::new(
backend_pkg_mgr.name(),
backend_pkg_mgr.capabilities().supports_external,
);
let res = run_app(&mut terminal, &mut app, backend_pkg_mgr).await;
drop(_guard);
res
}
fn format_elapsed_ago(ts: i64, now: i64) -> String {
let diff = (now - ts).max(0);
if diff < 60 {
"just now".to_string()
} else if diff < 3600 {
format!("{} min ago", diff / 60)
} else if diff < 86400 {
format!("{} hrs ago", diff / 3600)
} else {
format!("{} days ago", diff / 86400)
}
}
fn parse_df_available(df_stdout: &str) -> String {
df_stdout
.lines()
.nth(1)
.and_then(|line| line.split_whitespace().nth(3))
.unwrap_or("")
.to_string()
}
fn merge_external_updates(
packages: &mut [crate::core::package::PackageModel],
base_updates: usize,
ext_updates: &[(String, String, String)],
) -> usize {
let mut count = base_updates;
for (name, _, _) in ext_updates {
if let Some(pkg) = packages
.iter_mut()
.find(|p| p.name == *name && p.is_external())
&& !pkg.is_upgradable
{
pkg.is_upgradable = true;
count += 1;
}
}
count
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::traits::HistoryEntry;
#[test]
fn test_transactions_from_history_grouping() {
let entries = vec![
HistoryEntry {
timestamp: "2026-10-01 12:00:01".into(),
action: "installed".into(),
package: "ripgrep".into(),
version: "14.1.0".into(),
},
HistoryEntry {
timestamp: "2026-10-01 12:00:05".into(),
action: "installed".into(),
package: "fd".into(),
version: "10.0.0".into(),
},
HistoryEntry {
timestamp: "2026-09-29 09:30:00".into(),
action: "upgraded".into(),
package: "curl".into(),
version: "8.5.0".into(),
},
];
let txs = transactions_from_history(entries);
assert_eq!(txs.len(), 2);
assert_eq!(txs[0].packages.len(), 2);
assert_eq!(txs[0].primary_action, TxAction::Install);
assert_eq!(txs[1].primary_action, TxAction::Upgrade);
}
#[test]
fn test_app_new_filters_by_backend_capabilities() {
let pac_app = App::new("pacman", true);
assert_eq!(pac_app.backend_name, "pacman");
assert!(pac_app.filters.contains(&PackageFilter::Aur));
assert!(pac_app.is_fetching_news);
let dnf_app = App::new("dnf", false);
assert_eq!(dnf_app.backend_name, "dnf");
assert!(!dnf_app.filters.contains(&PackageFilter::Aur));
assert!(!dnf_app.is_fetching_news);
}
#[test]
fn test_format_elapsed_ago() {
assert_eq!(format_elapsed_ago(1000, 1005), "just now");
assert_eq!(format_elapsed_ago(1050, 1000), "just now");
assert_eq!(format_elapsed_ago(1000, 1600), "10 min ago");
assert_eq!(format_elapsed_ago(1000, 8200), "2 hrs ago");
assert_eq!(format_elapsed_ago(0, 3 * 86400), "3 days ago");
}
#[test]
fn test_parse_df_available_and_merge_external_updates() {
let df_sample = "Filesystem Size Used Avail Use% Mounted on\n/dev/nvme0n1p2 450G 120G 310G 28% /\n";
assert_eq!(parse_df_available(df_sample), "310G");
let mut pkgs = vec![crate::core::package::PackageModel {
name: "yay-bin".into(),
version: "12.0-1".into(),
repo: "local/aur".into(),
is_installed: true,
is_upgradable: false,
size_mb: 5.0,
desc: None,
}];
let ext = vec![("yay-bin".into(), "12.0-1".into(), "12.1-1".into())];
assert_eq!(merge_external_updates(&mut pkgs, 2, &ext), 3);
assert!(pkgs[0].is_upgradable);
}
#[test]
fn test_apply_cached_catalog_stale_guard() {
let mut app = App::new("pacman", true);
assert_eq!(app.last_refreshed, "never");
let cached = CachedCatalog {
backend: "pacman".into(),
packages: vec![crate::core::package::PackageModel {
name: "ripgrep".into(),
version: "14.1.0-1".into(),
repo: "extra".into(),
is_installed: true,
is_upgradable: false,
size_mb: 1.5,
desc: None,
}],
installed_count: 1,
updates_count: 0,
explicit_count: 1,
orphan_count: 0,
};
app.apply_cached_catalog(cached);
assert_eq!(app.package_list.len(), 1);
assert_eq!(app.filtered_packages.len(), 1);
app.last_refreshed = "12:00:00".into();
let stale = CachedCatalog {
backend: "pacman".into(),
packages: Vec::new(),
installed_count: 99,
updates_count: 9,
explicit_count: 9,
orphan_count: 9,
};
app.apply_cached_catalog(stale);
assert_eq!(app.package_list.len(), 1);
assert_eq!(app.installed_count, 1);
}
#[test]
fn test_is_text_input_active_and_draw_bar() {
let mut app = App::new("pacman", true);
assert!(!app.is_text_input_active());
app.screen = CurrentScreen::Browser;
app.input_mode = InputMode::Editing;
assert!(app.is_text_input_active());
app.screen = CurrentScreen::History;
assert!(!app.is_text_input_active());
app.history_input_mode = InputMode::Editing;
assert!(app.is_text_input_active());
assert_eq!(draw_bar(50.0, 10), "█████░░░░░");
assert_eq!(draw_bar(150.0, 4), "████");
}
}