repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/util.rs | src/util.rs | use std::{io::stdin, sync::mpsc, thread, time::Duration};
use termion::{event::Key, input::TermRead};
pub enum Event<I> {
Input(I),
Tick,
}
/// A small event handler that wrap termion input and tick events. Each event
/// type is handled in its own thread and returned to a common `Receiver`
pub struct Events {
rx: mpsc::Receiver<Event<Key>>,
}
#[derive(Debug, Clone, Copy)]
pub struct Config {
pub exit_key: Key,
pub tick_rate: Duration,
}
impl Default for Config {
fn default() -> Config {
Config {
exit_key: Key::Ctrl('c'),
tick_rate: Duration::from_millis(250),
}
}
}
impl Events {
pub fn new() -> Events {
Events::with_config(Config::default())
}
pub fn with_config(config: Config) -> Events {
let (tx, rx) = mpsc::channel();
let _input_handle = {
let tx = tx.clone();
thread::spawn(move || {
let stdin_result = stdin();
for evt in stdin_result.keys() {
if let Ok(key) = evt {
if tx.send(Event::Input(key)).is_err() {
return;
}
if key == config.exit_key {
return;
}
}
}
})
};
let _tick_handle = {
let tx = tx;
thread::spawn(move || {
let tx = tx.clone();
loop {
tx.send(Event::Tick).unwrap();
thread::sleep(config.tick_rate);
}
})
};
Events { rx }
}
pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> {
self.rx.recv()
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/redirect_uri.rs | src/redirect_uri.rs | use rspotify::{oauth2::SpotifyOAuth, util::request_token};
use std::{
io::prelude::*,
net::{TcpListener, TcpStream},
};
pub fn redirect_uri_web_server(spotify_oauth: &mut SpotifyOAuth, port: u16) -> Result<String, ()> {
let listener = TcpListener::bind(format!("127.0.0.1:{}", port));
match listener {
Ok(listener) => {
request_token(spotify_oauth);
for stream in listener.incoming() {
match stream {
Ok(stream) => {
if let Some(url) = handle_connection(stream) {
return Ok(url);
}
}
Err(e) => {
println!("Error: {}", e);
}
};
}
}
Err(e) => {
println!("Error: {}", e);
}
}
Err(())
}
fn handle_connection(mut stream: TcpStream) -> Option<String> {
// The request will be quite large (> 512) so just assign plenty just in case
let mut buffer = [0; 1000];
let _ = stream.read(&mut buffer).unwrap();
// convert buffer into string and 'parse' the URL
match String::from_utf8(buffer.to_vec()) {
Ok(request) => {
let split: Vec<&str> = request.split_whitespace().collect();
if split.len() > 1 {
respond_with_success(stream);
return Some(split[1].to_string());
}
respond_with_error("Malformed request".to_string(), stream);
}
Err(e) => {
respond_with_error(format!("Invalid UTF-8 sequence: {}", e), stream);
}
};
None
}
fn respond_with_success(mut stream: TcpStream) {
let contents = include_str!("redirect_uri.html");
let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
fn respond_with_error(error_message: String, mut stream: TcpStream) {
println!("Error: {}", error_message);
let response = format!(
"HTTP/1.1 400 Bad Request\r\n\r\n400 - Bad Request - {}",
error_message
);
stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/main.rs | src/main.rs | mod app;
mod banner;
mod cli;
mod config;
mod event;
mod handlers;
mod network;
mod redirect_uri;
mod ui;
mod user_config;
use crate::app::RouteId;
use crate::event::Key;
use anyhow::{anyhow, Result};
use app::{ActiveBlock, App};
use backtrace::Backtrace;
use banner::BANNER;
use clap::{App as ClapApp, Arg, Shell};
use config::ClientConfig;
use crossterm::{
cursor::MoveTo,
event::{DisableMouseCapture, EnableMouseCapture},
execute,
style::Print,
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, SetTitle,
},
ExecutableCommand,
};
use network::{get_spotify, IoEvent, Network};
use redirect_uri::redirect_uri_web_server;
use rspotify::{
oauth2::{SpotifyOAuth, TokenInfo},
util::{process_token, request_token},
};
use std::{
cmp::{max, min},
io::{self, stdout},
panic::{self, PanicInfo},
path::PathBuf,
sync::Arc,
time::SystemTime,
};
use tokio::sync::Mutex;
use tui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use user_config::{UserConfig, UserConfigPaths};
const SCOPES: [&str; 14] = [
"playlist-read-collaborative",
"playlist-read-private",
"playlist-modify-private",
"playlist-modify-public",
"user-follow-read",
"user-follow-modify",
"user-library-modify",
"user-library-read",
"user-modify-playback-state",
"user-read-currently-playing",
"user-read-playback-state",
"user-read-playback-position",
"user-read-private",
"user-read-recently-played",
];
/// get token automatically with local webserver
pub async fn get_token_auto(spotify_oauth: &mut SpotifyOAuth, port: u16) -> Option<TokenInfo> {
match spotify_oauth.get_cached_token().await {
Some(token_info) => Some(token_info),
None => match redirect_uri_web_server(spotify_oauth, port) {
Ok(mut url) => process_token(spotify_oauth, &mut url).await,
Err(()) => {
println!("Starting webserver failed. Continuing with manual authentication");
request_token(spotify_oauth);
println!("Enter the URL you were redirected to: ");
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => process_token(spotify_oauth, &mut input).await,
Err(_) => None,
}
}
},
}
}
fn close_application() -> Result<()> {
disable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, LeaveAlternateScreen, DisableMouseCapture)?;
Ok(())
}
fn panic_hook(info: &PanicInfo<'_>) {
if cfg!(debug_assertions) {
let location = info.location().unwrap();
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => *s,
None => match info.payload().downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
},
};
let stacktrace: String = format!("{:?}", Backtrace::new()).replace('\n', "\n\r");
disable_raw_mode().unwrap();
execute!(
io::stdout(),
LeaveAlternateScreen,
Print(format!(
"thread '<unnamed>' panicked at '{}', {}\n\r{}",
msg, location, stacktrace
)),
DisableMouseCapture
)
.unwrap();
}
}
#[tokio::main]
async fn main() -> Result<()> {
panic::set_hook(Box::new(|info| {
panic_hook(info);
}));
let mut clap_app = ClapApp::new(env!("CARGO_PKG_NAME"))
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about(env!("CARGO_PKG_DESCRIPTION"))
.usage("Press `?` while running the app to see keybindings")
.before_help(BANNER)
.after_help(
"Your spotify Client ID and Client Secret are stored in $HOME/.config/spotify-tui/client.yml",
)
.arg(
Arg::with_name("tick-rate")
.short("t")
.long("tick-rate")
.help("Set the tick rate (milliseconds): the lower the number the higher the FPS.")
.long_help(
"Specify the tick rate in milliseconds: the lower the number the \
higher the FPS. It can be nicer to have a lower value when you want to use the audio analysis view \
of the app. Beware that this comes at a CPU cost!",
)
.takes_value(true),
)
.arg(
Arg::with_name("config")
.short("c")
.long("config")
.help("Specify configuration file path.")
.takes_value(true),
)
.arg(
Arg::with_name("completions")
.long("completions")
.help("Generates completions for your preferred shell")
.takes_value(true)
.possible_values(&["bash", "zsh", "fish", "power-shell", "elvish"])
.value_name("SHELL"),
)
// Control spotify from the command line
.subcommand(cli::playback_subcommand())
.subcommand(cli::play_subcommand())
.subcommand(cli::list_subcommand())
.subcommand(cli::search_subcommand());
let matches = clap_app.clone().get_matches();
// Shell completions don't need any spotify work
if let Some(s) = matches.value_of("completions") {
let shell = match s {
"fish" => Shell::Fish,
"bash" => Shell::Bash,
"zsh" => Shell::Zsh,
"power-shell" => Shell::PowerShell,
"elvish" => Shell::Elvish,
_ => return Err(anyhow!("no completions avaible for '{}'", s)),
};
clap_app.gen_completions_to("spt", shell, &mut io::stdout());
return Ok(());
}
let mut user_config = UserConfig::new();
if let Some(config_file_path) = matches.value_of("config") {
let config_file_path = PathBuf::from(config_file_path);
let path = UserConfigPaths { config_file_path };
user_config.path_to_config.replace(path);
}
user_config.load_config()?;
if let Some(tick_rate) = matches
.value_of("tick-rate")
.and_then(|tick_rate| tick_rate.parse().ok())
{
if tick_rate >= 1000 {
panic!("Tick rate must be below 1000");
} else {
user_config.behavior.tick_rate_milliseconds = tick_rate;
}
}
let mut client_config = ClientConfig::new();
client_config.load_config()?;
let config_paths = client_config.get_or_build_paths()?;
// Start authorization with spotify
let mut oauth = SpotifyOAuth::default()
.client_id(&client_config.client_id)
.client_secret(&client_config.client_secret)
.redirect_uri(&client_config.get_redirect_uri())
.cache_path(config_paths.token_cache_path)
.scope(&SCOPES.join(" "))
.build();
let config_port = client_config.get_port();
match get_token_auto(&mut oauth, config_port).await {
Some(token_info) => {
let (sync_io_tx, sync_io_rx) = std::sync::mpsc::channel::<IoEvent>();
let (spotify, token_expiry) = get_spotify(token_info);
// Initialise app state
let app = Arc::new(Mutex::new(App::new(
sync_io_tx,
user_config.clone(),
token_expiry,
)));
// Work with the cli (not really async)
if let Some(cmd) = matches.subcommand_name() {
// Save, because we checked if the subcommand is present at runtime
let m = matches.subcommand_matches(cmd).unwrap();
let network = Network::new(oauth, spotify, client_config, &app);
println!(
"{}",
cli::handle_matches(m, cmd.to_string(), network, user_config).await?
);
// Launch the UI (async)
} else {
let cloned_app = Arc::clone(&app);
std::thread::spawn(move || {
let mut network = Network::new(oauth, spotify, client_config, &app);
start_tokio(sync_io_rx, &mut network);
});
// The UI must run in the "main" thread
start_ui(user_config, &cloned_app).await?;
}
}
None => println!("\nSpotify auth failed"),
}
Ok(())
}
#[tokio::main]
async fn start_tokio<'a>(io_rx: std::sync::mpsc::Receiver<IoEvent>, network: &mut Network) {
while let Ok(io_event) = io_rx.recv() {
network.handle_network_event(io_event).await;
}
}
async fn start_ui(user_config: UserConfig, app: &Arc<Mutex<App>>) -> Result<()> {
// Terminal initialization
let mut stdout = stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
enable_raw_mode()?;
let mut backend = CrosstermBackend::new(stdout);
if user_config.behavior.set_window_title {
backend.execute(SetTitle("spt - Spotify TUI"))?;
}
let mut terminal = Terminal::new(backend)?;
terminal.hide_cursor()?;
let events = event::Events::new(user_config.behavior.tick_rate_milliseconds);
// play music on, if not send them to the device selection view
let mut is_first_render = true;
loop {
let mut app = app.lock().await;
// Get the size of the screen on each loop to account for resize event
if let Ok(size) = terminal.backend().size() {
// Reset the help menu is the terminal was resized
if is_first_render || app.size != size {
app.help_menu_max_lines = 0;
app.help_menu_offset = 0;
app.help_menu_page = 0;
app.size = size;
// Based on the size of the terminal, adjust the search limit.
let potential_limit = max((app.size.height as i32) - 13, 0) as u32;
let max_limit = min(potential_limit, 50);
let large_search_limit = min((f32::from(size.height) / 1.4) as u32, max_limit);
let small_search_limit = min((f32::from(size.height) / 2.85) as u32, max_limit / 2);
app.dispatch(IoEvent::UpdateSearchLimits(
large_search_limit,
small_search_limit,
));
// Based on the size of the terminal, adjust how many lines are
// displayed in the help menu
if app.size.height > 8 {
app.help_menu_max_lines = (app.size.height as u32) - 8;
} else {
app.help_menu_max_lines = 0;
}
}
};
let current_route = app.get_current_route();
terminal.draw(|mut f| match current_route.active_block {
ActiveBlock::HelpMenu => {
ui::draw_help_menu(&mut f, &app);
}
ActiveBlock::Error => {
ui::draw_error_screen(&mut f, &app);
}
ActiveBlock::SelectDevice => {
ui::draw_device_list(&mut f, &app);
}
ActiveBlock::Analysis => {
ui::audio_analysis::draw(&mut f, &app);
}
ActiveBlock::BasicView => {
ui::draw_basic_view(&mut f, &app);
}
_ => {
ui::draw_main_layout(&mut f, &app);
}
})?;
if current_route.active_block == ActiveBlock::Input {
terminal.show_cursor()?;
} else {
terminal.hide_cursor()?;
}
let cursor_offset = if app.size.height > ui::util::SMALL_TERMINAL_HEIGHT {
2
} else {
1
};
// Put the cursor back inside the input box
terminal.backend_mut().execute(MoveTo(
cursor_offset + app.input_cursor_position,
cursor_offset,
))?;
// Handle authentication refresh
if SystemTime::now() > app.spotify_token_expiry {
app.dispatch(IoEvent::RefreshAuthentication);
}
match events.next()? {
event::Event::Input(key) => {
if key == Key::Ctrl('c') {
break;
}
let current_active_block = app.get_current_route().active_block;
// To avoid swallowing the global key presses `q` and `-` make a special
// case for the input handler
if current_active_block == ActiveBlock::Input {
handlers::input_handler(key, &mut app);
} else if key == app.user_config.keys.back {
if app.get_current_route().active_block != ActiveBlock::Input {
// Go back through navigation stack when not in search input mode and exit the app if there are no more places to back to
let pop_result = match app.pop_navigation_stack() {
Some(ref x) if x.id == RouteId::Search => app.pop_navigation_stack(),
Some(x) => Some(x),
None => None,
};
if pop_result.is_none() {
break; // Exit application
}
}
} else {
handlers::handle_app(key, &mut app);
}
}
event::Event::Tick => {
app.update_on_tick();
}
}
// Delay spotify request until first render, will have the effect of improving
// startup speed
if is_first_render {
app.dispatch(IoEvent::GetPlaylists);
app.dispatch(IoEvent::GetUser);
app.dispatch(IoEvent::GetCurrentPlayback);
app.help_docs_size = ui::help::get_help_docs(&app.user_config.keys).len() as u32;
is_first_render = false;
}
}
terminal.show_cursor()?;
close_application()?;
Ok(())
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/event/key.rs | src/event/key.rs | use crossterm::event;
use std::fmt;
/// Represents an key.
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum Key {
/// Both Enter (or Return) and numpad Enter
Enter,
/// Tabulation key
Tab,
/// Backspace key
Backspace,
/// Escape key
Esc,
/// Left arrow
Left,
/// Right arrow
Right,
/// Up arrow
Up,
/// Down arrow
Down,
/// Insert key
Ins,
/// Delete key
Delete,
/// Home key
Home,
/// End key
End,
/// Page Up key
PageUp,
/// Page Down key
PageDown,
/// F0 key
F0,
/// F1 key
F1,
/// F2 key
F2,
/// F3 key
F3,
/// F4 key
F4,
/// F5 key
F5,
/// F6 key
F6,
/// F7 key
F7,
/// F8 key
F8,
/// F9 key
F9,
/// F10 key
F10,
/// F11 key
F11,
/// F12 key
F12,
Char(char),
Ctrl(char),
Alt(char),
Unknown,
}
impl Key {
/// Returns the function key corresponding to the given number
///
/// 1 -> F1, etc...
///
/// # Panics
///
/// If `n == 0 || n > 12`
pub fn from_f(n: u8) -> Key {
match n {
0 => Key::F0,
1 => Key::F1,
2 => Key::F2,
3 => Key::F3,
4 => Key::F4,
5 => Key::F5,
6 => Key::F6,
7 => Key::F7,
8 => Key::F8,
9 => Key::F9,
10 => Key::F10,
11 => Key::F11,
12 => Key::F12,
_ => panic!("unknown function key: F{}", n),
}
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Key::Alt(' ') => write!(f, "<Alt+Space>"),
Key::Ctrl(' ') => write!(f, "<Ctrl+Space>"),
Key::Char(' ') => write!(f, "<Space>"),
Key::Alt(c) => write!(f, "<Alt+{}>", c),
Key::Ctrl(c) => write!(f, "<Ctrl+{}>", c),
Key::Char(c) => write!(f, "{}", c),
Key::Left | Key::Right | Key::Up | Key::Down => write!(f, "<{:?} Arrow Key>", self),
Key::Enter
| Key::Tab
| Key::Backspace
| Key::Esc
| Key::Ins
| Key::Delete
| Key::Home
| Key::End
| Key::PageUp
| Key::PageDown => write!(f, "<{:?}>", self),
_ => write!(f, "{:?}", self),
}
}
}
impl From<event::KeyEvent> for Key {
fn from(key_event: event::KeyEvent) -> Self {
match key_event {
event::KeyEvent {
code: event::KeyCode::Esc,
..
} => Key::Esc,
event::KeyEvent {
code: event::KeyCode::Backspace,
..
} => Key::Backspace,
event::KeyEvent {
code: event::KeyCode::Left,
..
} => Key::Left,
event::KeyEvent {
code: event::KeyCode::Right,
..
} => Key::Right,
event::KeyEvent {
code: event::KeyCode::Up,
..
} => Key::Up,
event::KeyEvent {
code: event::KeyCode::Down,
..
} => Key::Down,
event::KeyEvent {
code: event::KeyCode::Home,
..
} => Key::Home,
event::KeyEvent {
code: event::KeyCode::End,
..
} => Key::End,
event::KeyEvent {
code: event::KeyCode::PageUp,
..
} => Key::PageUp,
event::KeyEvent {
code: event::KeyCode::PageDown,
..
} => Key::PageDown,
event::KeyEvent {
code: event::KeyCode::Delete,
..
} => Key::Delete,
event::KeyEvent {
code: event::KeyCode::Insert,
..
} => Key::Ins,
event::KeyEvent {
code: event::KeyCode::F(n),
..
} => Key::from_f(n),
event::KeyEvent {
code: event::KeyCode::Enter,
..
} => Key::Enter,
event::KeyEvent {
code: event::KeyCode::Tab,
..
} => Key::Tab,
// First check for char + modifier
event::KeyEvent {
code: event::KeyCode::Char(c),
modifiers: event::KeyModifiers::ALT,
} => Key::Alt(c),
event::KeyEvent {
code: event::KeyCode::Char(c),
modifiers: event::KeyModifiers::CONTROL,
} => Key::Ctrl(c),
event::KeyEvent {
code: event::KeyCode::Char(c),
..
} => Key::Char(c),
_ => Key::Unknown,
}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/event/mod.rs | src/event/mod.rs | mod events;
mod key;
pub use self::{
events::{Event, Events},
key::Key,
};
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/event/events.rs | src/event/events.rs | use crate::event::Key;
use crossterm::event;
use std::{sync::mpsc, thread, time::Duration};
#[derive(Debug, Clone, Copy)]
/// Configuration for event handling.
pub struct EventConfig {
/// The key that is used to exit the application.
pub exit_key: Key,
/// The tick rate at which the application will sent an tick event.
pub tick_rate: Duration,
}
impl Default for EventConfig {
fn default() -> EventConfig {
EventConfig {
exit_key: Key::Ctrl('c'),
tick_rate: Duration::from_millis(250),
}
}
}
/// An occurred event.
pub enum Event<I> {
/// An input event occurred.
Input(I),
/// An tick event occurred.
Tick,
}
/// A small event handler that wrap crossterm input and tick event. Each event
/// type is handled in its own thread and returned to a common `Receiver`
pub struct Events {
rx: mpsc::Receiver<Event<Key>>,
// Need to be kept around to prevent disposing the sender side.
_tx: mpsc::Sender<Event<Key>>,
}
impl Events {
/// Constructs an new instance of `Events` with the default config.
pub fn new(tick_rate: u64) -> Events {
Events::with_config(EventConfig {
tick_rate: Duration::from_millis(tick_rate),
..Default::default()
})
}
/// Constructs an new instance of `Events` from given config.
pub fn with_config(config: EventConfig) -> Events {
let (tx, rx) = mpsc::channel();
let event_tx = tx.clone();
thread::spawn(move || {
loop {
// poll for tick rate duration, if no event, sent tick event.
if event::poll(config.tick_rate).unwrap() {
if let event::Event::Key(key) = event::read().unwrap() {
let key = Key::from(key);
event_tx.send(Event::Input(key)).unwrap();
}
}
event_tx.send(Event::Tick).unwrap();
}
});
Events { rx, _tx: tx }
}
/// Attempts to read an event.
/// This function will block the current thread.
pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> {
self.rx.recv()
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/select_device.rs | src/handlers/select_device.rs | use super::{
super::app::{ActiveBlock, App},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
pub fn handler(key: Key, app: &mut App) {
match key {
Key::Esc => {
app.set_current_route_state(Some(ActiveBlock::Library), None);
}
k if common_key_events::down_event(k) => {
match &app.devices {
Some(p) => {
if let Some(selected_device_index) = app.selected_device_index {
let next_index =
common_key_events::on_down_press_handler(&p.devices, Some(selected_device_index));
app.selected_device_index = Some(next_index);
}
}
None => {}
};
}
k if common_key_events::up_event(k) => {
match &app.devices {
Some(p) => {
if let Some(selected_device_index) = app.selected_device_index {
let next_index =
common_key_events::on_up_press_handler(&p.devices, Some(selected_device_index));
app.selected_device_index = Some(next_index);
}
}
None => {}
};
}
k if common_key_events::high_event(k) => {
match &app.devices {
Some(_p) => {
if let Some(_selected_device_index) = app.selected_device_index {
let next_index = common_key_events::on_high_press_handler();
app.selected_device_index = Some(next_index);
}
}
None => {}
};
}
k if common_key_events::middle_event(k) => {
match &app.devices {
Some(p) => {
if let Some(_selected_device_index) = app.selected_device_index {
let next_index = common_key_events::on_middle_press_handler(&p.devices);
app.selected_device_index = Some(next_index);
}
}
None => {}
};
}
k if common_key_events::low_event(k) => {
match &app.devices {
Some(p) => {
if let Some(_selected_device_index) = app.selected_device_index {
let next_index = common_key_events::on_low_press_handler(&p.devices);
app.selected_device_index = Some(next_index);
}
}
None => {}
};
}
Key::Enter => {
if let (Some(devices), Some(index)) = (app.devices.clone(), app.selected_device_index) {
if let Some(device) = &devices.devices.get(index) {
app.dispatch(IoEvent::TransferPlaybackToDevice(device.id.clone()));
}
};
}
_ => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/recently_played.rs | src/handlers/recently_played.rs | use super::{super::app::App, common_key_events};
use crate::{app::RecommendationsContext, event::Key, network::IoEvent};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(recently_played_result) = &app.recently_played.result {
let next_index = common_key_events::on_down_press_handler(
&recently_played_result.items,
Some(app.recently_played.index),
);
app.recently_played.index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(recently_played_result) = &app.recently_played.result {
let next_index = common_key_events::on_up_press_handler(
&recently_played_result.items,
Some(app.recently_played.index),
);
app.recently_played.index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_recently_played_result) = &app.recently_played.result {
let next_index = common_key_events::on_high_press_handler();
app.recently_played.index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(recently_played_result) = &app.recently_played.result {
let next_index = common_key_events::on_middle_press_handler(&recently_played_result.items);
app.recently_played.index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(recently_played_result) = &app.recently_played.result {
let next_index = common_key_events::on_low_press_handler(&recently_played_result.items);
app.recently_played.index = next_index;
}
}
Key::Char('s') => {
if let Some(recently_played_result) = &app.recently_played.result.clone() {
if let Some(selected_track) = recently_played_result.items.get(app.recently_played.index) {
if let Some(track_id) = &selected_track.track.id {
app.dispatch(IoEvent::ToggleSaveTrack(track_id.to_string()));
};
};
};
}
Key::Enter => {
if let Some(recently_played_result) = &app.recently_played.result.clone() {
let track_uris: Vec<String> = recently_played_result
.items
.iter()
.map(|item| item.track.uri.to_owned())
.collect();
app.dispatch(IoEvent::StartPlayback(
None,
Some(track_uris),
Some(app.recently_played.index),
));
};
}
Key::Char('r') => {
if let Some(recently_played_result) = &app.recently_played.result.clone() {
let selected_track_history_item =
recently_played_result.items.get(app.recently_played.index);
if let Some(item) = selected_track_history_item {
if let Some(id) = &item.track.id {
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = item.track.name.clone();
app.get_recommendations_for_track_id(id.to_string());
}
}
}
}
_ if key == app.user_config.keys.add_item_to_queue => {
if let Some(recently_played_result) = &app.recently_played.result.clone() {
if let Some(history) = recently_played_result.items.get(app.recently_played.index) {
app.dispatch(IoEvent::AddItemToQueue(history.track.uri.clone()))
}
};
}
_ => {}
};
}
#[cfg(test)]
mod tests {
use super::{super::super::app::ActiveBlock, *};
#[test]
fn on_left_press() {
let mut app = App::default();
app.set_current_route_state(
Some(ActiveBlock::AlbumTracks),
Some(ActiveBlock::AlbumTracks),
);
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_esc() {
let mut app = App::default();
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/track_table.rs | src/handlers/track_table.rs | use super::{
super::app::{App, RecommendationsContext, TrackTable, TrackTableContext},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
use rand::{thread_rng, Rng};
use serde_json::from_value;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
let next_index = common_key_events::on_down_press_handler(
&app.track_table.tracks,
Some(app.track_table.selected_index),
);
app.track_table.selected_index = next_index;
}
k if common_key_events::up_event(k) => {
let next_index = common_key_events::on_up_press_handler(
&app.track_table.tracks,
Some(app.track_table.selected_index),
);
app.track_table.selected_index = next_index;
}
k if common_key_events::high_event(k) => {
let next_index = common_key_events::on_high_press_handler();
app.track_table.selected_index = next_index;
}
k if common_key_events::middle_event(k) => {
let next_index = common_key_events::on_middle_press_handler(&app.track_table.tracks);
app.track_table.selected_index = next_index;
}
k if common_key_events::low_event(k) => {
let next_index = common_key_events::on_low_press_handler(&app.track_table.tracks);
app.track_table.selected_index = next_index;
}
Key::Enter => {
on_enter(app);
}
// Scroll down
k if k == app.user_config.keys.next_page => {
match &app.track_table.context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let (Some(playlists), Some(selected_playlist_index)) =
(&app.playlists, &app.selected_playlist_index)
{
if let Some(selected_playlist) =
playlists.items.get(selected_playlist_index.to_owned())
{
if let Some(playlist_tracks) = &app.playlist_tracks {
if app.playlist_offset + app.large_search_limit < playlist_tracks.total {
app.playlist_offset += app.large_search_limit;
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
}
}
}
};
}
TrackTableContext::RecommendedTracks => {}
TrackTableContext::SavedTracks => {
app.get_current_user_saved_tracks_next();
}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {}
TrackTableContext::MadeForYou => {
let (playlists, selected_playlist_index) =
(&app.library.made_for_you_playlists, &app.made_for_you_index);
if let Some(selected_playlist) = playlists
.get_results(Some(0))
.unwrap()
.items
.get(selected_playlist_index.to_owned())
{
if let Some(playlist_tracks) = &app.made_for_you_tracks {
if app.made_for_you_offset + app.large_search_limit < playlist_tracks.total {
app.made_for_you_offset += app.large_search_limit;
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetMadeForYouPlaylistTracks(
playlist_id,
app.made_for_you_offset,
));
}
}
}
}
},
None => {}
};
}
// Scroll up
k if k == app.user_config.keys.previous_page => {
match &app.track_table.context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let (Some(playlists), Some(selected_playlist_index)) =
(&app.playlists, &app.selected_playlist_index)
{
if app.playlist_offset >= app.large_search_limit {
app.playlist_offset -= app.large_search_limit;
};
if let Some(selected_playlist) =
playlists.items.get(selected_playlist_index.to_owned())
{
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
}
};
}
TrackTableContext::RecommendedTracks => {}
TrackTableContext::SavedTracks => {
app.get_current_user_saved_tracks_previous();
}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {}
TrackTableContext::MadeForYou => {
let (playlists, selected_playlist_index) = (
&app
.library
.made_for_you_playlists
.get_results(Some(0))
.unwrap(),
app.made_for_you_index,
);
if app.made_for_you_offset >= app.large_search_limit {
app.made_for_you_offset -= app.large_search_limit;
}
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index) {
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetMadeForYouPlaylistTracks(
playlist_id,
app.made_for_you_offset,
));
}
}
},
None => {}
};
}
Key::Char('s') => handle_save_track_event(app),
Key::Char('S') => play_random_song(app),
k if k == app.user_config.keys.jump_to_end => jump_to_end(app),
k if k == app.user_config.keys.jump_to_start => jump_to_start(app),
//recommended song radio
Key::Char('r') => {
handle_recommended_tracks(app);
}
_ if key == app.user_config.keys.add_item_to_queue => on_queue(app),
_ => {}
}
}
fn play_random_song(app: &mut App) {
if let Some(context) = &app.track_table.context {
match context {
TrackTableContext::MyPlaylists => {
let (context_uri, track_json) = match (&app.selected_playlist_index, &app.playlists) {
(Some(selected_playlist_index), Some(playlists)) => {
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index.to_owned())
{
(
Some(selected_playlist.uri.to_owned()),
selected_playlist.tracks.get("total"),
)
} else {
(None, None)
}
}
_ => (None, None),
};
if let Some(val) = track_json {
let num_tracks: usize = from_value(val.clone()).unwrap();
app.dispatch(IoEvent::StartPlayback(
context_uri,
None,
Some(thread_rng().gen_range(0..num_tracks)),
));
}
}
TrackTableContext::RecommendedTracks => {}
TrackTableContext::SavedTracks => {
if let Some(saved_tracks) = &app.library.saved_tracks.get_results(None) {
let track_uris: Vec<String> = saved_tracks
.items
.iter()
.map(|item| item.track.uri.to_owned())
.collect();
let rand_idx = thread_rng().gen_range(0..track_uris.len());
app.dispatch(IoEvent::StartPlayback(
None,
Some(track_uris),
Some(rand_idx),
))
}
}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {
let (context_uri, playlist_track_json) = match (
&app.search_results.selected_playlists_index,
&app.search_results.playlists,
) {
(Some(selected_playlist_index), Some(playlist_result)) => {
if let Some(selected_playlist) = playlist_result
.items
.get(selected_playlist_index.to_owned())
{
(
Some(selected_playlist.uri.to_owned()),
selected_playlist.tracks.get("total"),
)
} else {
(None, None)
}
}
_ => (None, None),
};
if let Some(val) = playlist_track_json {
let num_tracks: usize = from_value(val.clone()).unwrap();
app.dispatch(IoEvent::StartPlayback(
context_uri,
None,
Some(thread_rng().gen_range(0..num_tracks)),
))
}
}
TrackTableContext::MadeForYou => {
if let Some(playlist) = &app
.library
.made_for_you_playlists
.get_results(Some(0))
.and_then(|playlist| playlist.items.get(app.made_for_you_index))
{
if let Some(num_tracks) = &playlist
.tracks
.get("total")
.and_then(|total| -> Option<usize> { from_value(total.clone()).ok() })
{
let uri = Some(playlist.uri.clone());
app.dispatch(IoEvent::StartPlayback(
uri,
None,
Some(thread_rng().gen_range(0..*num_tracks)),
))
};
};
}
}
};
}
fn handle_save_track_event(app: &mut App) {
let (selected_index, tracks) = (&app.track_table.selected_index, &app.track_table.tracks);
if let Some(track) = tracks.get(*selected_index) {
if let Some(id) = &track.id {
let id = id.to_string();
app.dispatch(IoEvent::ToggleSaveTrack(id));
};
};
}
fn handle_recommended_tracks(app: &mut App) {
let (selected_index, tracks) = (&app.track_table.selected_index, &app.track_table.tracks);
if let Some(track) = tracks.get(*selected_index) {
let first_track = track.clone();
let track_id_list = track.id.as_ref().map(|id| vec![id.to_string()]);
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = first_track.name.clone();
app.get_recommendations_for_seed(None, track_id_list, Some(first_track));
};
}
fn jump_to_end(app: &mut App) {
match &app.track_table.context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let (Some(playlists), Some(selected_playlist_index)) =
(&app.playlists, &app.selected_playlist_index)
{
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index.to_owned()) {
let total_tracks = selected_playlist
.tracks
.get("total")
.and_then(|total| total.as_u64())
.expect("playlist.tracks object should have a total field")
as u32;
if app.large_search_limit < total_tracks {
app.playlist_offset = total_tracks - (total_tracks % app.large_search_limit);
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
}
}
}
}
TrackTableContext::RecommendedTracks => {}
TrackTableContext::SavedTracks => {}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {}
TrackTableContext::MadeForYou => {}
},
None => {}
}
}
fn on_enter(app: &mut App) {
let TrackTable {
context,
selected_index,
tracks,
} = &app.track_table;
match &context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let Some(_track) = tracks.get(*selected_index) {
let context_uri = match (&app.active_playlist_index, &app.playlists) {
(Some(active_playlist_index), Some(playlists)) => playlists
.items
.get(active_playlist_index.to_owned())
.map(|selected_playlist| selected_playlist.uri.to_owned()),
_ => None,
};
app.dispatch(IoEvent::StartPlayback(
context_uri,
None,
Some(app.track_table.selected_index + app.playlist_offset as usize),
));
};
}
TrackTableContext::RecommendedTracks => {
app.dispatch(IoEvent::StartPlayback(
None,
Some(
app
.recommended_tracks
.iter()
.map(|x| x.uri.clone())
.collect::<Vec<String>>(),
),
Some(app.track_table.selected_index),
));
}
TrackTableContext::SavedTracks => {
if let Some(saved_tracks) = &app.library.saved_tracks.get_results(None) {
let track_uris: Vec<String> = saved_tracks
.items
.iter()
.map(|item| item.track.uri.to_owned())
.collect();
app.dispatch(IoEvent::StartPlayback(
None,
Some(track_uris),
Some(app.track_table.selected_index),
));
};
}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {
let TrackTable {
selected_index,
tracks,
..
} = &app.track_table;
if let Some(_track) = tracks.get(*selected_index) {
let context_uri = match (
&app.search_results.selected_playlists_index,
&app.search_results.playlists,
) {
(Some(selected_playlist_index), Some(playlist_result)) => playlist_result
.items
.get(selected_playlist_index.to_owned())
.map(|selected_playlist| selected_playlist.uri.to_owned()),
_ => None,
};
app.dispatch(IoEvent::StartPlayback(
context_uri,
None,
Some(app.track_table.selected_index),
));
};
}
TrackTableContext::MadeForYou => {
if let Some(_track) = tracks.get(*selected_index) {
let context_uri = Some(
app
.library
.made_for_you_playlists
.get_results(Some(0))
.unwrap()
.items
.get(app.made_for_you_index)
.unwrap()
.uri
.to_owned(),
);
app.dispatch(IoEvent::StartPlayback(
context_uri,
None,
Some(app.track_table.selected_index + app.made_for_you_offset as usize),
));
}
}
},
None => {}
};
}
fn on_queue(app: &mut App) {
let TrackTable {
context,
selected_index,
tracks,
} = &app.track_table;
match &context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let Some(track) = tracks.get(*selected_index) {
let uri = track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
};
}
TrackTableContext::RecommendedTracks => {
if let Some(full_track) = app.recommended_tracks.get(app.track_table.selected_index) {
let uri = full_track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
}
}
TrackTableContext::SavedTracks => {
if let Some(page) = app.library.saved_tracks.get_results(None) {
if let Some(saved_track) = page.items.get(app.track_table.selected_index) {
let uri = saved_track.track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
}
}
}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {
let TrackTable {
selected_index,
tracks,
..
} = &app.track_table;
if let Some(track) = tracks.get(*selected_index) {
let uri = track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
};
}
TrackTableContext::MadeForYou => {
if let Some(track) = tracks.get(*selected_index) {
let uri = track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
}
}
},
None => {}
};
}
fn jump_to_start(app: &mut App) {
match &app.track_table.context {
Some(context) => match context {
TrackTableContext::MyPlaylists => {
if let (Some(playlists), Some(selected_playlist_index)) =
(&app.playlists, &app.selected_playlist_index)
{
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index.to_owned()) {
app.playlist_offset = 0;
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
}
}
}
TrackTableContext::RecommendedTracks => {}
TrackTableContext::SavedTracks => {}
TrackTableContext::AlbumSearch => {}
TrackTableContext::PlaylistSearch => {}
TrackTableContext::MadeForYou => {}
},
None => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/playbar.rs | src/handlers/playbar.rs | use super::{
super::app::{ActiveBlock, App},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
use rspotify::model::{context::CurrentlyPlaybackContext, PlayingItem};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::up_event(k) => {
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::MyPlaylists));
}
Key::Char('s') => {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = app.current_playback_context.to_owned()
{
match item {
PlayingItem::Track(track) => {
if let Some(track_id) = track.id {
app.dispatch(IoEvent::ToggleSaveTrack(track_id));
}
}
PlayingItem::Episode(episode) => {
app.dispatch(IoEvent::ToggleSaveTrack(episode.id));
}
};
};
}
_ => {}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_left_press() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::PlayBar), Some(ActiveBlock::PlayBar));
handler(Key::Up, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::MyPlaylists);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/common_key_events.rs | src/handlers/common_key_events.rs | use super::super::app::{ActiveBlock, App, RouteId};
use crate::event::Key;
pub fn down_event(key: Key) -> bool {
matches!(key, Key::Down | Key::Char('j') | Key::Ctrl('n'))
}
pub fn up_event(key: Key) -> bool {
matches!(key, Key::Up | Key::Char('k') | Key::Ctrl('p'))
}
pub fn left_event(key: Key) -> bool {
matches!(key, Key::Left | Key::Char('h') | Key::Ctrl('b'))
}
pub fn right_event(key: Key) -> bool {
matches!(key, Key::Right | Key::Char('l') | Key::Ctrl('f'))
}
pub fn high_event(key: Key) -> bool {
matches!(key, Key::Char('H'))
}
pub fn middle_event(key: Key) -> bool {
matches!(key, Key::Char('M'))
}
pub fn low_event(key: Key) -> bool {
matches!(key, Key::Char('L'))
}
pub fn on_down_press_handler<T>(selection_data: &[T], selection_index: Option<usize>) -> usize {
match selection_index {
Some(selection_index) => {
if !selection_data.is_empty() {
let next_index = selection_index + 1;
if next_index > selection_data.len() - 1 {
return 0;
} else {
return next_index;
}
}
0
}
None => 0,
}
}
pub fn on_up_press_handler<T>(selection_data: &[T], selection_index: Option<usize>) -> usize {
match selection_index {
Some(selection_index) => {
if !selection_data.is_empty() {
if selection_index > 0 {
return selection_index - 1;
} else {
return selection_data.len() - 1;
}
}
0
}
None => 0,
}
}
pub fn on_high_press_handler() -> usize {
0
}
pub fn on_middle_press_handler<T>(selection_data: &[T]) -> usize {
let mut index = selection_data.len() / 2;
if selection_data.len() % 2 == 0 {
index -= 1;
}
index
}
pub fn on_low_press_handler<T>(selection_data: &[T]) -> usize {
selection_data.len() - 1
}
pub fn handle_right_event(app: &mut App) {
match app.get_current_route().hovered_block {
ActiveBlock::MyPlaylists | ActiveBlock::Library => match app.get_current_route().id {
RouteId::AlbumTracks => {
app.set_current_route_state(
Some(ActiveBlock::AlbumTracks),
Some(ActiveBlock::AlbumTracks),
);
}
RouteId::TrackTable => {
app.set_current_route_state(Some(ActiveBlock::TrackTable), Some(ActiveBlock::TrackTable));
}
RouteId::Podcasts => {
app.set_current_route_state(Some(ActiveBlock::Podcasts), Some(ActiveBlock::Podcasts));
}
RouteId::Recommendations => {
app.set_current_route_state(Some(ActiveBlock::TrackTable), Some(ActiveBlock::TrackTable));
}
RouteId::AlbumList => {
app.set_current_route_state(Some(ActiveBlock::AlbumList), Some(ActiveBlock::AlbumList));
}
RouteId::PodcastEpisodes => {
app.set_current_route_state(
Some(ActiveBlock::EpisodeTable),
Some(ActiveBlock::EpisodeTable),
);
}
RouteId::MadeForYou => {
app.set_current_route_state(Some(ActiveBlock::MadeForYou), Some(ActiveBlock::MadeForYou));
}
RouteId::Artists => {
app.set_current_route_state(Some(ActiveBlock::Artists), Some(ActiveBlock::Artists));
}
RouteId::RecentlyPlayed => {
app.set_current_route_state(
Some(ActiveBlock::RecentlyPlayed),
Some(ActiveBlock::RecentlyPlayed),
);
}
RouteId::Search => {
app.set_current_route_state(
Some(ActiveBlock::SearchResultBlock),
Some(ActiveBlock::SearchResultBlock),
);
}
RouteId::Artist => app.set_current_route_state(
Some(ActiveBlock::ArtistBlock),
Some(ActiveBlock::ArtistBlock),
),
RouteId::Home => {
app.set_current_route_state(Some(ActiveBlock::Home), Some(ActiveBlock::Home));
}
RouteId::SelectedDevice => {}
RouteId::Error => {}
RouteId::Analysis => {}
RouteId::BasicView => {}
RouteId::Dialog => {}
},
_ => {}
};
}
pub fn handle_left_event(app: &mut App) {
// TODO: This should send you back to either library or playlist based on last selection
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_on_down_press_handler() {
let data = vec!["Choice 1", "Choice 2", "Choice 3"];
let index = 0;
let next_index = on_down_press_handler(&data, Some(index));
assert_eq!(next_index, 1);
// Selection wrap if on last item
let index = data.len() - 1;
let next_index = on_down_press_handler(&data, Some(index));
assert_eq!(next_index, 0);
}
#[test]
fn test_on_up_press_handler() {
let data = vec!["Choice 1", "Choice 2", "Choice 3"];
let index = data.len() - 1;
let next_index = on_up_press_handler(&data, Some(index));
assert_eq!(next_index, index - 1);
// Selection wrap if on first item
let index = 0;
let next_index = on_up_press_handler(&data, Some(index));
assert_eq!(next_index, data.len() - 1);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/dialog.rs | src/handlers/dialog.rs | use super::super::app::{ActiveBlock, App, DialogContext};
use crate::event::Key;
pub fn handler(key: Key, app: &mut App) {
match key {
Key::Enter => {
if let Some(route) = app.pop_navigation_stack() {
if app.confirm {
if let ActiveBlock::Dialog(d) = route.active_block {
match d {
DialogContext::PlaylistWindow => handle_playlist_dialog(app),
DialogContext::PlaylistSearch => handle_playlist_search_dialog(app),
}
}
}
}
}
Key::Char('q') => {
app.pop_navigation_stack();
}
Key::Right => app.confirm = !app.confirm,
Key::Left => app.confirm = !app.confirm,
_ => {}
}
}
fn handle_playlist_dialog(app: &mut App) {
app.user_unfollow_playlist()
}
fn handle_playlist_search_dialog(app: &mut App) {
app.user_unfollow_playlist_search_result()
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/empty.rs | src/handlers/empty.rs | use super::common_key_events;
use crate::{
app::{ActiveBlock, App},
event::Key,
};
// When no block is actively selected, just handle regular event
pub fn handler(key: Key, app: &mut App) {
match key {
Key::Enter => {
let current_hovered = app.get_current_route().hovered_block;
app.set_current_route_state(Some(current_hovered), None);
}
k if common_key_events::down_event(k) => match app.get_current_route().hovered_block {
ActiveBlock::Library => {
app.set_current_route_state(None, Some(ActiveBlock::MyPlaylists));
}
ActiveBlock::ArtistBlock
| ActiveBlock::AlbumList
| ActiveBlock::AlbumTracks
| ActiveBlock::Artists
| ActiveBlock::Podcasts
| ActiveBlock::EpisodeTable
| ActiveBlock::Home
| ActiveBlock::MadeForYou
| ActiveBlock::MyPlaylists
| ActiveBlock::RecentlyPlayed
| ActiveBlock::TrackTable => {
app.set_current_route_state(None, Some(ActiveBlock::PlayBar));
}
_ => {}
},
k if common_key_events::up_event(k) => match app.get_current_route().hovered_block {
ActiveBlock::MyPlaylists => {
app.set_current_route_state(None, Some(ActiveBlock::Library));
}
ActiveBlock::PlayBar => {
app.set_current_route_state(None, Some(ActiveBlock::MyPlaylists));
}
_ => {}
},
k if common_key_events::left_event(k) => match app.get_current_route().hovered_block {
ActiveBlock::ArtistBlock
| ActiveBlock::AlbumList
| ActiveBlock::AlbumTracks
| ActiveBlock::Artists
| ActiveBlock::Podcasts
| ActiveBlock::EpisodeTable
| ActiveBlock::Home
| ActiveBlock::MadeForYou
| ActiveBlock::RecentlyPlayed
| ActiveBlock::TrackTable => {
app.set_current_route_state(None, Some(ActiveBlock::Library));
}
_ => {}
},
k if common_key_events::right_event(k) => common_key_events::handle_right_event(app),
_ => (),
};
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::RouteId;
#[test]
fn on_enter() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
handler(Key::Enter, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Library);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_down_press() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
handler(Key::Down, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::MyPlaylists);
// TODO: test the other cases when they are implemented
}
#[test]
fn on_up_press() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::MyPlaylists));
handler(Key::Up, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_left_press() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::AlbumTracks));
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
app.set_current_route_state(None, Some(ActiveBlock::Home));
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
app.set_current_route_state(None, Some(ActiveBlock::TrackTable));
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_right_press() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
handler(Key::Right, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::AlbumTracks);
assert_eq!(current_route.hovered_block, ActiveBlock::AlbumTracks);
app.push_navigation_stack(RouteId::Search, ActiveBlock::Empty);
app.set_current_route_state(None, Some(ActiveBlock::MyPlaylists));
handler(Key::Right, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::SearchResultBlock);
assert_eq!(current_route.hovered_block, ActiveBlock::SearchResultBlock);
app.set_current_route_state(None, Some(ActiveBlock::Library));
app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
handler(Key::Right, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::TrackTable);
assert_eq!(current_route.hovered_block, ActiveBlock::TrackTable);
app.set_current_route_state(None, Some(ActiveBlock::Library));
app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
handler(Key::Right, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::TrackTable);
assert_eq!(current_route.hovered_block, ActiveBlock::TrackTable);
app.push_navigation_stack(RouteId::Home, ActiveBlock::Home);
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
handler(Key::Right, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Home);
assert_eq!(current_route.hovered_block, ActiveBlock::Home);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/analysis.rs | src/handlers/analysis.rs | use crate::{app::App, event::Key};
pub fn handler(_key: Key, _app: &mut App) {}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/search_results.rs | src/handlers/search_results.rs | use super::{
super::app::{
ActiveBlock, App, DialogContext, RecommendationsContext, RouteId, SearchResultBlock,
TrackTableContext,
},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
fn handle_down_press_on_selected_block(app: &mut App) {
// Start selecting within the selected block
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let Some(result) = &app.search_results.albums {
let next_index = common_key_events::on_down_press_handler(
&result.items,
app.search_results.selected_album_index,
);
app.search_results.selected_album_index = Some(next_index);
}
}
SearchResultBlock::SongSearch => {
if let Some(result) = &app.search_results.tracks {
let next_index = common_key_events::on_down_press_handler(
&result.items,
app.search_results.selected_tracks_index,
);
app.search_results.selected_tracks_index = Some(next_index);
}
}
SearchResultBlock::ArtistSearch => {
if let Some(result) = &app.search_results.artists {
let next_index = common_key_events::on_down_press_handler(
&result.items,
app.search_results.selected_artists_index,
);
app.search_results.selected_artists_index = Some(next_index);
}
}
SearchResultBlock::PlaylistSearch => {
if let Some(result) = &app.search_results.playlists {
let next_index = common_key_events::on_down_press_handler(
&result.items,
app.search_results.selected_playlists_index,
);
app.search_results.selected_playlists_index = Some(next_index);
}
}
SearchResultBlock::ShowSearch => {
if let Some(result) = &app.search_results.shows {
let next_index = common_key_events::on_down_press_handler(
&result.items,
app.search_results.selected_shows_index,
);
app.search_results.selected_shows_index = Some(next_index);
}
}
SearchResultBlock::Empty => {}
}
}
fn handle_down_press_on_hovered_block(app: &mut App) {
match app.search_results.hovered_block {
SearchResultBlock::AlbumSearch => {
app.search_results.hovered_block = SearchResultBlock::ShowSearch;
}
SearchResultBlock::SongSearch => {
app.search_results.hovered_block = SearchResultBlock::AlbumSearch;
}
SearchResultBlock::ArtistSearch => {
app.search_results.hovered_block = SearchResultBlock::PlaylistSearch;
}
SearchResultBlock::PlaylistSearch => {
app.search_results.hovered_block = SearchResultBlock::ShowSearch;
}
SearchResultBlock::ShowSearch => {
app.search_results.hovered_block = SearchResultBlock::SongSearch;
}
SearchResultBlock::Empty => {}
}
}
fn handle_up_press_on_selected_block(app: &mut App) {
// Start selecting within the selected block
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let Some(result) = &app.search_results.albums {
let next_index = common_key_events::on_up_press_handler(
&result.items,
app.search_results.selected_album_index,
);
app.search_results.selected_album_index = Some(next_index);
}
}
SearchResultBlock::SongSearch => {
if let Some(result) = &app.search_results.tracks {
let next_index = common_key_events::on_up_press_handler(
&result.items,
app.search_results.selected_tracks_index,
);
app.search_results.selected_tracks_index = Some(next_index);
}
}
SearchResultBlock::ArtistSearch => {
if let Some(result) = &app.search_results.artists {
let next_index = common_key_events::on_up_press_handler(
&result.items,
app.search_results.selected_artists_index,
);
app.search_results.selected_artists_index = Some(next_index);
}
}
SearchResultBlock::PlaylistSearch => {
if let Some(result) = &app.search_results.playlists {
let next_index = common_key_events::on_up_press_handler(
&result.items,
app.search_results.selected_playlists_index,
);
app.search_results.selected_playlists_index = Some(next_index);
}
}
SearchResultBlock::ShowSearch => {
if let Some(result) = &app.search_results.shows {
let next_index = common_key_events::on_up_press_handler(
&result.items,
app.search_results.selected_shows_index,
);
app.search_results.selected_shows_index = Some(next_index);
}
}
SearchResultBlock::Empty => {}
}
}
fn handle_up_press_on_hovered_block(app: &mut App) {
match app.search_results.hovered_block {
SearchResultBlock::AlbumSearch => {
app.search_results.hovered_block = SearchResultBlock::SongSearch;
}
SearchResultBlock::SongSearch => {
app.search_results.hovered_block = SearchResultBlock::ShowSearch;
}
SearchResultBlock::ArtistSearch => {
app.search_results.hovered_block = SearchResultBlock::ShowSearch;
}
SearchResultBlock::PlaylistSearch => {
app.search_results.hovered_block = SearchResultBlock::ArtistSearch;
}
SearchResultBlock::ShowSearch => {
app.search_results.hovered_block = SearchResultBlock::AlbumSearch;
}
SearchResultBlock::Empty => {}
}
}
fn handle_high_press_on_selected_block(app: &mut App) {
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let Some(_result) = &app.search_results.albums {
let next_index = common_key_events::on_high_press_handler();
app.search_results.selected_album_index = Some(next_index);
}
}
SearchResultBlock::SongSearch => {
if let Some(_result) = &app.search_results.tracks {
let next_index = common_key_events::on_high_press_handler();
app.search_results.selected_tracks_index = Some(next_index);
}
}
SearchResultBlock::ArtistSearch => {
if let Some(_result) = &app.search_results.artists {
let next_index = common_key_events::on_high_press_handler();
app.search_results.selected_artists_index = Some(next_index);
}
}
SearchResultBlock::PlaylistSearch => {
if let Some(_result) = &app.search_results.playlists {
let next_index = common_key_events::on_high_press_handler();
app.search_results.selected_playlists_index = Some(next_index);
}
}
SearchResultBlock::ShowSearch => {
if let Some(_result) = &app.search_results.shows {
let next_index = common_key_events::on_high_press_handler();
app.search_results.selected_shows_index = Some(next_index);
}
}
SearchResultBlock::Empty => {}
}
}
fn handle_middle_press_on_selected_block(app: &mut App) {
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let Some(result) = &app.search_results.albums {
let next_index = common_key_events::on_middle_press_handler(&result.items);
app.search_results.selected_album_index = Some(next_index);
}
}
SearchResultBlock::SongSearch => {
if let Some(result) = &app.search_results.tracks {
let next_index = common_key_events::on_middle_press_handler(&result.items);
app.search_results.selected_tracks_index = Some(next_index);
}
}
SearchResultBlock::ArtistSearch => {
if let Some(result) = &app.search_results.artists {
let next_index = common_key_events::on_middle_press_handler(&result.items);
app.search_results.selected_artists_index = Some(next_index);
}
}
SearchResultBlock::PlaylistSearch => {
if let Some(result) = &app.search_results.playlists {
let next_index = common_key_events::on_middle_press_handler(&result.items);
app.search_results.selected_playlists_index = Some(next_index);
}
}
SearchResultBlock::ShowSearch => {
if let Some(result) = &app.search_results.shows {
let next_index = common_key_events::on_middle_press_handler(&result.items);
app.search_results.selected_shows_index = Some(next_index);
}
}
SearchResultBlock::Empty => {}
}
}
fn handle_low_press_on_selected_block(app: &mut App) {
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let Some(result) = &app.search_results.albums {
let next_index = common_key_events::on_low_press_handler(&result.items);
app.search_results.selected_album_index = Some(next_index);
}
}
SearchResultBlock::SongSearch => {
if let Some(result) = &app.search_results.tracks {
let next_index = common_key_events::on_low_press_handler(&result.items);
app.search_results.selected_tracks_index = Some(next_index);
}
}
SearchResultBlock::ArtistSearch => {
if let Some(result) = &app.search_results.artists {
let next_index = common_key_events::on_low_press_handler(&result.items);
app.search_results.selected_artists_index = Some(next_index);
}
}
SearchResultBlock::PlaylistSearch => {
if let Some(result) = &app.search_results.playlists {
let next_index = common_key_events::on_low_press_handler(&result.items);
app.search_results.selected_playlists_index = Some(next_index);
}
}
SearchResultBlock::ShowSearch => {
if let Some(result) = &app.search_results.shows {
let next_index = common_key_events::on_low_press_handler(&result.items);
app.search_results.selected_shows_index = Some(next_index);
}
}
SearchResultBlock::Empty => {}
}
}
fn handle_add_item_to_queue(app: &mut App) {
match &app.search_results.selected_block {
SearchResultBlock::SongSearch => {
if let (Some(index), Some(tracks)) = (
app.search_results.selected_tracks_index,
&app.search_results.tracks,
) {
if let Some(track) = tracks.items.get(index) {
let uri = track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
}
}
}
SearchResultBlock::ArtistSearch => {}
SearchResultBlock::PlaylistSearch => {}
SearchResultBlock::AlbumSearch => {}
SearchResultBlock::ShowSearch => {}
SearchResultBlock::Empty => {}
};
}
fn handle_enter_event_on_selected_block(app: &mut App) {
match &app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
if let (Some(index), Some(albums_result)) = (
&app.search_results.selected_album_index,
&app.search_results.albums,
) {
if let Some(album) = albums_result.items.get(index.to_owned()).cloned() {
app.track_table.context = Some(TrackTableContext::AlbumSearch);
app.dispatch(IoEvent::GetAlbumTracks(Box::new(album)));
};
}
}
SearchResultBlock::SongSearch => {
let index = app.search_results.selected_tracks_index;
let tracks = app.search_results.tracks.clone();
let track_uris = tracks.map(|tracks| {
tracks
.items
.into_iter()
.map(|track| track.uri)
.collect::<Vec<String>>()
});
app.dispatch(IoEvent::StartPlayback(None, track_uris, index));
}
SearchResultBlock::ArtistSearch => {
if let Some(index) = &app.search_results.selected_artists_index {
if let Some(result) = app.search_results.artists.clone() {
if let Some(artist) = result.items.get(index.to_owned()) {
app.get_artist(artist.id.clone(), artist.name.clone());
app.push_navigation_stack(RouteId::Artist, ActiveBlock::ArtistBlock);
};
};
};
}
SearchResultBlock::PlaylistSearch => {
if let (Some(index), Some(playlists_result)) = (
app.search_results.selected_playlists_index,
&app.search_results.playlists,
) {
if let Some(playlist) = playlists_result.items.get(index) {
// Go to playlist tracks table
app.track_table.context = Some(TrackTableContext::PlaylistSearch);
let playlist_id = playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
};
}
}
SearchResultBlock::ShowSearch => {
if let (Some(index), Some(shows_result)) = (
app.search_results.selected_shows_index,
&app.search_results.shows,
) {
if let Some(show) = shows_result.items.get(index).cloned() {
// Go to show tracks table
app.dispatch(IoEvent::GetShowEpisodes(Box::new(show)));
};
}
}
SearchResultBlock::Empty => {}
};
}
fn handle_enter_event_on_hovered_block(app: &mut App) {
match app.search_results.hovered_block {
SearchResultBlock::AlbumSearch => {
let next_index = app.search_results.selected_album_index.unwrap_or(0);
app.search_results.selected_album_index = Some(next_index);
app.search_results.selected_block = SearchResultBlock::AlbumSearch;
}
SearchResultBlock::SongSearch => {
let next_index = app.search_results.selected_tracks_index.unwrap_or(0);
app.search_results.selected_tracks_index = Some(next_index);
app.search_results.selected_block = SearchResultBlock::SongSearch;
}
SearchResultBlock::ArtistSearch => {
let next_index = app.search_results.selected_artists_index.unwrap_or(0);
app.search_results.selected_artists_index = Some(next_index);
app.search_results.selected_block = SearchResultBlock::ArtistSearch;
}
SearchResultBlock::PlaylistSearch => {
let next_index = app.search_results.selected_playlists_index.unwrap_or(0);
app.search_results.selected_playlists_index = Some(next_index);
app.search_results.selected_block = SearchResultBlock::PlaylistSearch;
}
SearchResultBlock::ShowSearch => {
let next_index = app.search_results.selected_shows_index.unwrap_or(0);
app.search_results.selected_shows_index = Some(next_index);
app.search_results.selected_block = SearchResultBlock::ShowSearch;
}
SearchResultBlock::Empty => {}
};
}
fn handle_recommended_tracks(app: &mut App) {
match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {}
SearchResultBlock::SongSearch => {
if let Some(index) = &app.search_results.selected_tracks_index {
if let Some(result) = app.search_results.tracks.clone() {
if let Some(track) = result.items.get(index.to_owned()) {
let track_id_list: Option<Vec<String>> =
track.id.as_ref().map(|id| vec![id.to_string()]);
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = track.name.clone();
app.get_recommendations_for_seed(None, track_id_list, Some(track.clone()));
};
};
};
}
SearchResultBlock::ArtistSearch => {
if let Some(index) = &app.search_results.selected_artists_index {
if let Some(result) = app.search_results.artists.clone() {
if let Some(artist) = result.items.get(index.to_owned()) {
let artist_id_list: Option<Vec<String>> = Some(vec![artist.id.clone()]);
app.recommendations_context = Some(RecommendationsContext::Artist);
app.recommendations_seed = artist.name.clone();
app.get_recommendations_for_seed(artist_id_list, None, None);
};
};
};
}
SearchResultBlock::PlaylistSearch => {}
SearchResultBlock::ShowSearch => {}
SearchResultBlock::Empty => {}
}
}
pub fn handler(key: Key, app: &mut App) {
match key {
Key::Esc => {
app.search_results.selected_block = SearchResultBlock::Empty;
}
k if common_key_events::down_event(k) => {
if app.search_results.selected_block != SearchResultBlock::Empty {
handle_down_press_on_selected_block(app);
} else {
handle_down_press_on_hovered_block(app);
}
}
k if common_key_events::up_event(k) => {
if app.search_results.selected_block != SearchResultBlock::Empty {
handle_up_press_on_selected_block(app);
} else {
handle_up_press_on_hovered_block(app);
}
}
k if common_key_events::left_event(k) => {
app.search_results.selected_block = SearchResultBlock::Empty;
match app.search_results.hovered_block {
SearchResultBlock::AlbumSearch => {
common_key_events::handle_left_event(app);
}
SearchResultBlock::SongSearch => {
common_key_events::handle_left_event(app);
}
SearchResultBlock::ArtistSearch => {
app.search_results.hovered_block = SearchResultBlock::SongSearch;
}
SearchResultBlock::PlaylistSearch => {
app.search_results.hovered_block = SearchResultBlock::AlbumSearch;
}
SearchResultBlock::ShowSearch => {
common_key_events::handle_left_event(app);
}
SearchResultBlock::Empty => {}
}
}
k if common_key_events::right_event(k) => {
app.search_results.selected_block = SearchResultBlock::Empty;
match app.search_results.hovered_block {
SearchResultBlock::AlbumSearch => {
app.search_results.hovered_block = SearchResultBlock::PlaylistSearch;
}
SearchResultBlock::SongSearch => {
app.search_results.hovered_block = SearchResultBlock::ArtistSearch;
}
SearchResultBlock::ArtistSearch => {
app.search_results.hovered_block = SearchResultBlock::SongSearch;
}
SearchResultBlock::PlaylistSearch => {
app.search_results.hovered_block = SearchResultBlock::AlbumSearch;
}
SearchResultBlock::ShowSearch => {}
SearchResultBlock::Empty => {}
}
}
k if common_key_events::high_event(k) => {
if app.search_results.selected_block != SearchResultBlock::Empty {
handle_high_press_on_selected_block(app);
}
}
k if common_key_events::middle_event(k) => {
if app.search_results.selected_block != SearchResultBlock::Empty {
handle_middle_press_on_selected_block(app);
}
}
k if common_key_events::low_event(k) => {
if app.search_results.selected_block != SearchResultBlock::Empty {
handle_low_press_on_selected_block(app)
}
}
// Handle pressing enter when block is selected to start playing track
Key::Enter => match app.search_results.selected_block {
SearchResultBlock::Empty => handle_enter_event_on_hovered_block(app),
SearchResultBlock::PlaylistSearch => {
app.playlist_offset = 0;
handle_enter_event_on_selected_block(app);
}
_ => handle_enter_event_on_selected_block(app),
},
Key::Char('w') => match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
app.current_user_saved_album_add(ActiveBlock::SearchResultBlock)
}
SearchResultBlock::SongSearch => {}
SearchResultBlock::ArtistSearch => app.user_follow_artists(ActiveBlock::SearchResultBlock),
SearchResultBlock::PlaylistSearch => {
app.user_follow_playlist();
}
SearchResultBlock::ShowSearch => app.user_follow_show(ActiveBlock::SearchResultBlock),
SearchResultBlock::Empty => {}
},
Key::Char('D') => match app.search_results.selected_block {
SearchResultBlock::AlbumSearch => {
app.current_user_saved_album_delete(ActiveBlock::SearchResultBlock)
}
SearchResultBlock::SongSearch => {}
SearchResultBlock::ArtistSearch => app.user_unfollow_artists(ActiveBlock::SearchResultBlock),
SearchResultBlock::PlaylistSearch => {
if let (Some(playlists), Some(selected_index)) = (
&app.search_results.playlists,
app.search_results.selected_playlists_index,
) {
let selected_playlist = &playlists.items[selected_index].name;
app.dialog = Some(selected_playlist.clone());
app.confirm = false;
app.push_navigation_stack(
RouteId::Dialog,
ActiveBlock::Dialog(DialogContext::PlaylistSearch),
);
}
}
SearchResultBlock::ShowSearch => app.user_unfollow_show(ActiveBlock::SearchResultBlock),
SearchResultBlock::Empty => {}
},
Key::Char('r') => handle_recommended_tracks(app),
_ if key == app.user_config.keys.add_item_to_queue => handle_add_item_to_queue(app),
// Add `s` to "see more" on each option
_ => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/episode_table.rs | src/handlers/episode_table.rs | use super::{
super::app::{App, EpisodeTableContext},
common_key_events,
};
use crate::app::ActiveBlock;
use crate::event::Key;
use crate::network::IoEvent;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(episodes) = &mut app.library.show_episodes.get_results(None) {
let next_index =
common_key_events::on_down_press_handler(&episodes.items, Some(app.episode_list_index));
app.episode_list_index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(episodes) = &mut app.library.show_episodes.get_results(None) {
let next_index =
common_key_events::on_up_press_handler(&episodes.items, Some(app.episode_list_index));
app.episode_list_index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_episodes) = app.library.show_episodes.get_results(None) {
let next_index = common_key_events::on_high_press_handler();
app.episode_list_index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(episodes) = app.library.show_episodes.get_results(None) {
let next_index = common_key_events::on_middle_press_handler(&episodes.items);
app.episode_list_index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(episodes) = app.library.show_episodes.get_results(None) {
let next_index = common_key_events::on_low_press_handler(&episodes.items);
app.episode_list_index = next_index;
}
}
Key::Enter => {
on_enter(app);
}
// Scroll down
k if k == app.user_config.keys.next_page => handle_next_event(app),
// Scroll up
k if k == app.user_config.keys.previous_page => handle_prev_event(app),
Key::Char('S') => toggle_sort_by_date(app),
Key::Char('s') => handle_follow_event(app),
Key::Char('D') => handle_unfollow_event(app),
Key::Ctrl('e') => jump_to_end(app),
Key::Ctrl('a') => jump_to_start(app),
_ => {}
}
}
fn jump_to_end(app: &mut App) {
if let Some(episodes) = app.library.show_episodes.get_results(None) {
let last_idx = episodes.items.len() - 1;
app.episode_list_index = last_idx;
}
}
fn on_enter(app: &mut App) {
if let Some(episodes) = app.library.show_episodes.get_results(None) {
let episode_uris = episodes
.items
.iter()
.map(|episode| episode.uri.to_owned())
.collect::<Vec<String>>();
app.dispatch(IoEvent::StartPlayback(
None,
Some(episode_uris),
Some(app.episode_list_index),
));
}
}
fn handle_prev_event(app: &mut App) {
app.get_episode_table_previous();
}
fn handle_next_event(app: &mut App) {
match app.episode_table_context {
EpisodeTableContext::Full => {
if let Some(selected_episode) = app.selected_show_full.clone() {
let show_id = selected_episode.show.id;
app.get_episode_table_next(show_id)
}
}
EpisodeTableContext::Simplified => {
if let Some(selected_episode) = app.selected_show_simplified.clone() {
let show_id = selected_episode.show.id;
app.get_episode_table_next(show_id)
}
}
}
}
fn handle_follow_event(app: &mut App) {
app.user_follow_show(ActiveBlock::EpisodeTable);
}
fn handle_unfollow_event(app: &mut App) {
app.user_unfollow_show(ActiveBlock::EpisodeTable);
}
fn jump_to_start(app: &mut App) {
app.episode_list_index = 0;
}
fn toggle_sort_by_date(app: &mut App) {
//TODO: reverse whole list and not just currently visible episodes
let selected_id = match app.library.show_episodes.get_results(None) {
Some(episodes) => episodes
.items
.get(app.episode_list_index)
.map(|e| e.id.clone()),
None => None,
};
if let Some(episodes) = app.library.show_episodes.get_mut_results(None) {
episodes.items.reverse();
}
if let Some(id) = selected_id {
if let Some(episodes) = app.library.show_episodes.get_results(None) {
app.episode_list_index = episodes.items.iter().position(|e| e.id == id).unwrap_or(0);
}
} else {
app.episode_list_index = 0;
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/made_for_you.rs | src/handlers/made_for_you.rs | use super::{
super::app::{App, TrackTableContext},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::up_event(k) => {
if let Some(playlists) = &mut app.library.made_for_you_playlists.get_results(None) {
let next_index =
common_key_events::on_up_press_handler(&playlists.items, Some(app.made_for_you_index));
app.made_for_you_index = next_index;
}
}
k if common_key_events::down_event(k) => {
if let Some(playlists) = &mut app.library.made_for_you_playlists.get_results(None) {
let next_index =
common_key_events::on_down_press_handler(&playlists.items, Some(app.made_for_you_index));
app.made_for_you_index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_playlists) = &mut app.library.made_for_you_playlists.get_results(None) {
let next_index = common_key_events::on_high_press_handler();
app.made_for_you_index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(playlists) = &mut app.library.made_for_you_playlists.get_results(None) {
let next_index = common_key_events::on_middle_press_handler(&playlists.items);
app.made_for_you_index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(playlists) = &mut app.library.made_for_you_playlists.get_results(None) {
let next_index = common_key_events::on_low_press_handler(&playlists.items);
app.made_for_you_index = next_index;
}
}
Key::Enter => {
if let (Some(playlists), selected_playlist_index) = (
&app.library.made_for_you_playlists.get_results(Some(0)),
&app.made_for_you_index,
) {
app.track_table.context = Some(TrackTableContext::MadeForYou);
app.playlist_offset = 0;
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index.to_owned()) {
app.made_for_you_offset = 0;
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetMadeForYouPlaylistTracks(
playlist_id,
app.made_for_you_offset,
));
}
};
}
_ => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/home.rs | src/handlers/home.rs | use super::{super::app::App, common_key_events};
use crate::event::Key;
const LARGE_SCROLL: u16 = 10;
const SMALL_SCROLL: u16 = 1;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
app.home_scroll += SMALL_SCROLL;
}
k if common_key_events::up_event(k) => {
if app.home_scroll > 0 {
app.home_scroll -= SMALL_SCROLL;
}
}
k if k == app.user_config.keys.next_page => {
app.home_scroll += LARGE_SCROLL;
}
k if k == app.user_config.keys.previous_page => {
if app.home_scroll > LARGE_SCROLL {
app.home_scroll -= LARGE_SCROLL;
} else {
app.home_scroll = 0;
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_small_down_press() {
let mut app = App::default();
handler(Key::Down, &mut app);
assert_eq!(app.home_scroll, SMALL_SCROLL);
handler(Key::Down, &mut app);
assert_eq!(app.home_scroll, SMALL_SCROLL * 2);
}
#[test]
fn on_small_up_press() {
let mut app = App::default();
handler(Key::Up, &mut app);
assert_eq!(app.home_scroll, 0);
app.home_scroll = 1;
handler(Key::Up, &mut app);
assert_eq!(app.home_scroll, 0);
// Check that smashing the up button doesn't go to negative scroll (which would cause a crash)
handler(Key::Up, &mut app);
handler(Key::Up, &mut app);
handler(Key::Up, &mut app);
assert_eq!(app.home_scroll, 0);
}
#[test]
fn on_large_down_press() {
let mut app = App::default();
handler(Key::Ctrl('d'), &mut app);
assert_eq!(app.home_scroll, LARGE_SCROLL);
handler(Key::Ctrl('d'), &mut app);
assert_eq!(app.home_scroll, LARGE_SCROLL * 2);
}
#[test]
fn on_large_up_press() {
let mut app = App::default();
let scroll = 37;
app.home_scroll = scroll;
handler(Key::Ctrl('u'), &mut app);
assert_eq!(app.home_scroll, scroll - LARGE_SCROLL);
handler(Key::Ctrl('u'), &mut app);
assert_eq!(app.home_scroll, scroll - LARGE_SCROLL * 2);
// Check that smashing the up button doesn't go to negative scroll (which would cause a crash)
handler(Key::Ctrl('u'), &mut app);
handler(Key::Ctrl('u'), &mut app);
handler(Key::Ctrl('u'), &mut app);
assert_eq!(app.home_scroll, 0);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/album_tracks.rs | src/handlers/album_tracks.rs | use super::common_key_events;
use crate::{
app::{AlbumTableContext, App, RecommendationsContext},
event::Key,
network::IoEvent,
};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = &app.selected_album_full {
let next_index = common_key_events::on_down_press_handler(
&selected_album.album.tracks.items,
Some(app.saved_album_tracks_index),
);
app.saved_album_tracks_index = next_index;
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
let next_index = common_key_events::on_down_press_handler(
&selected_album_simplified.tracks.items,
Some(selected_album_simplified.selected_index),
);
selected_album_simplified.selected_index = next_index;
}
}
},
k if common_key_events::up_event(k) => match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = &app.selected_album_full {
let next_index = common_key_events::on_up_press_handler(
&selected_album.album.tracks.items,
Some(app.saved_album_tracks_index),
);
app.saved_album_tracks_index = next_index;
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
let next_index = common_key_events::on_up_press_handler(
&selected_album_simplified.tracks.items,
Some(selected_album_simplified.selected_index),
);
selected_album_simplified.selected_index = next_index;
}
}
},
k if common_key_events::high_event(k) => handle_high_event(app),
k if common_key_events::middle_event(k) => handle_middle_event(app),
k if common_key_events::low_event(k) => handle_low_event(app),
Key::Char('s') => handle_save_event(app),
Key::Char('w') => handle_save_album_event(app),
Key::Enter => match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = app.selected_album_full.clone() {
app.dispatch(IoEvent::StartPlayback(
Some(selected_album.album.uri),
None,
Some(app.saved_album_tracks_index),
));
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &app.selected_album_simplified.clone() {
app.dispatch(IoEvent::StartPlayback(
selected_album_simplified.album.uri.clone(),
None,
Some(selected_album_simplified.selected_index),
));
};
}
},
//recommended playlist based on selected track
Key::Char('r') => {
handle_recommended_tracks(app);
}
_ if key == app.user_config.keys.add_item_to_queue => match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = app.selected_album_full.clone() {
if let Some(track) = selected_album
.album
.tracks
.items
.get(app.saved_album_tracks_index)
{
app.dispatch(IoEvent::AddItemToQueue(track.uri.clone()));
}
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &app.selected_album_simplified.clone() {
if let Some(track) = selected_album_simplified
.tracks
.items
.get(selected_album_simplified.selected_index)
{
app.dispatch(IoEvent::AddItemToQueue(track.uri.clone()));
}
};
}
},
_ => {}
};
}
fn handle_high_event(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
let next_index = common_key_events::on_high_press_handler();
app.saved_album_tracks_index = next_index;
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
let next_index = common_key_events::on_high_press_handler();
selected_album_simplified.selected_index = next_index;
}
}
}
}
fn handle_middle_event(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = &app.selected_album_full {
let next_index =
common_key_events::on_middle_press_handler(&selected_album.album.tracks.items);
app.saved_album_tracks_index = next_index;
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
let next_index =
common_key_events::on_middle_press_handler(&selected_album_simplified.tracks.items);
selected_album_simplified.selected_index = next_index;
}
}
}
}
fn handle_low_event(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = &app.selected_album_full {
let next_index =
common_key_events::on_low_press_handler(&selected_album.album.tracks.items);
app.saved_album_tracks_index = next_index;
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &mut app.selected_album_simplified {
let next_index =
common_key_events::on_low_press_handler(&selected_album_simplified.tracks.items);
selected_album_simplified.selected_index = next_index;
}
}
}
}
fn handle_recommended_tracks(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
if let Some(albums) = &app.library.clone().saved_albums.get_results(None) {
if let Some(selected_album) = albums.items.get(app.album_list_index) {
if let Some(track) = &selected_album
.album
.tracks
.items
.get(app.saved_album_tracks_index)
{
if let Some(id) = &track.id {
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = track.name.clone();
app.get_recommendations_for_track_id(id.to_string());
}
}
}
}
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = &app.selected_album_simplified.clone() {
if let Some(track) = &selected_album_simplified
.tracks
.items
.get(selected_album_simplified.selected_index)
{
if let Some(id) = &track.id {
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = track.name.clone();
app.get_recommendations_for_track_id(id.to_string());
}
}
};
}
}
}
fn handle_save_event(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = app.selected_album_full.clone() {
if let Some(selected_track) = selected_album
.album
.tracks
.items
.get(app.saved_album_tracks_index)
{
if let Some(track_id) = &selected_track.id {
app.dispatch(IoEvent::ToggleSaveTrack(track_id.to_string()));
};
};
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = app.selected_album_simplified.clone() {
if let Some(selected_track) = selected_album_simplified
.tracks
.items
.get(selected_album_simplified.selected_index)
{
if let Some(track_id) = &selected_track.id {
app.dispatch(IoEvent::ToggleSaveTrack(track_id.to_string()));
};
};
};
}
}
}
fn handle_save_album_event(app: &mut App) {
match app.album_table_context {
AlbumTableContext::Full => {
if let Some(selected_album) = app.selected_album_full.clone() {
let album_id = &selected_album.album.id;
app.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id.to_string()));
};
}
AlbumTableContext::Simplified => {
if let Some(selected_album_simplified) = app.selected_album_simplified.clone() {
if let Some(album_id) = selected_album_simplified.album.id {
app.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id));
};
};
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::ActiveBlock;
#[test]
fn on_left_press() {
let mut app = App::default();
app.set_current_route_state(
Some(ActiveBlock::AlbumTracks),
Some(ActiveBlock::AlbumTracks),
);
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_esc() {
let mut app = App::default();
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/library.rs | src/handlers/library.rs | use super::{
super::app::{ActiveBlock, App, RouteId, LIBRARY_OPTIONS},
common_key_events,
};
use crate::event::Key;
use crate::network::IoEvent;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::right_event(k) => common_key_events::handle_right_event(app),
k if common_key_events::down_event(k) => {
let next_index = common_key_events::on_down_press_handler(
&LIBRARY_OPTIONS,
Some(app.library.selected_index),
);
app.library.selected_index = next_index;
}
k if common_key_events::up_event(k) => {
let next_index =
common_key_events::on_up_press_handler(&LIBRARY_OPTIONS, Some(app.library.selected_index));
app.library.selected_index = next_index;
}
k if common_key_events::high_event(k) => {
let next_index = common_key_events::on_high_press_handler();
app.library.selected_index = next_index;
}
k if common_key_events::middle_event(k) => {
let next_index = common_key_events::on_middle_press_handler(&LIBRARY_OPTIONS);
app.library.selected_index = next_index;
}
k if common_key_events::low_event(k) => {
let next_index = common_key_events::on_low_press_handler(&LIBRARY_OPTIONS);
app.library.selected_index = next_index
}
// `library` should probably be an array of structs with enums rather than just using indexes
// like this
Key::Enter => match app.library.selected_index {
// Made For You,
0 => {
app.get_made_for_you();
app.push_navigation_stack(RouteId::MadeForYou, ActiveBlock::MadeForYou);
}
// Recently Played,
1 => {
app.dispatch(IoEvent::GetRecentlyPlayed);
app.push_navigation_stack(RouteId::RecentlyPlayed, ActiveBlock::RecentlyPlayed);
}
// Liked Songs,
2 => {
app.dispatch(IoEvent::GetCurrentSavedTracks(None));
app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
}
// Albums,
3 => {
app.dispatch(IoEvent::GetCurrentUserSavedAlbums(None));
app.push_navigation_stack(RouteId::AlbumList, ActiveBlock::AlbumList);
}
// Artists,
4 => {
app.dispatch(IoEvent::GetFollowedArtists(None));
app.push_navigation_stack(RouteId::Artists, ActiveBlock::Artists);
}
// Podcasts,
5 => {
app.dispatch(IoEvent::GetCurrentUserSavedShows(None));
app.push_navigation_stack(RouteId::Podcasts, ActiveBlock::Podcasts);
}
// This is required because Rust can't tell if this pattern in exhaustive
_ => {}
},
_ => (),
};
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/artist.rs | src/handlers/artist.rs | use super::common_key_events;
use crate::app::{ActiveBlock, App, ArtistBlock, RecommendationsContext, TrackTableContext};
use crate::event::Key;
use crate::network::IoEvent;
fn handle_down_press_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let next_index = common_key_events::on_down_press_handler(
&artist.top_tracks,
Some(artist.selected_top_track_index),
);
artist.selected_top_track_index = next_index;
}
ArtistBlock::Albums => {
let next_index = common_key_events::on_down_press_handler(
&artist.albums.items,
Some(artist.selected_album_index),
);
artist.selected_album_index = next_index;
}
ArtistBlock::RelatedArtists => {
let next_index = common_key_events::on_down_press_handler(
&artist.related_artists,
Some(artist.selected_related_artist_index),
);
artist.selected_related_artist_index = next_index;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_down_press_on_hovered_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_hovered_block {
ArtistBlock::TopTracks => {
artist.artist_hovered_block = ArtistBlock::Albums;
}
ArtistBlock::Albums => {
artist.artist_hovered_block = ArtistBlock::RelatedArtists;
}
ArtistBlock::RelatedArtists => {
artist.artist_hovered_block = ArtistBlock::TopTracks;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_up_press_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let next_index = common_key_events::on_up_press_handler(
&artist.top_tracks,
Some(artist.selected_top_track_index),
);
artist.selected_top_track_index = next_index;
}
ArtistBlock::Albums => {
let next_index = common_key_events::on_up_press_handler(
&artist.albums.items,
Some(artist.selected_album_index),
);
artist.selected_album_index = next_index;
}
ArtistBlock::RelatedArtists => {
let next_index = common_key_events::on_up_press_handler(
&artist.related_artists,
Some(artist.selected_related_artist_index),
);
artist.selected_related_artist_index = next_index;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_up_press_on_hovered_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_hovered_block {
ArtistBlock::TopTracks => {
artist.artist_hovered_block = ArtistBlock::RelatedArtists;
}
ArtistBlock::Albums => {
artist.artist_hovered_block = ArtistBlock::TopTracks;
}
ArtistBlock::RelatedArtists => {
artist.artist_hovered_block = ArtistBlock::Albums;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_high_press_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let next_index = common_key_events::on_high_press_handler();
artist.selected_top_track_index = next_index;
}
ArtistBlock::Albums => {
let next_index = common_key_events::on_high_press_handler();
artist.selected_album_index = next_index;
}
ArtistBlock::RelatedArtists => {
let next_index = common_key_events::on_high_press_handler();
artist.selected_related_artist_index = next_index;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_middle_press_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let next_index = common_key_events::on_middle_press_handler(&artist.top_tracks);
artist.selected_top_track_index = next_index;
}
ArtistBlock::Albums => {
let next_index = common_key_events::on_middle_press_handler(&artist.albums.items);
artist.selected_album_index = next_index;
}
ArtistBlock::RelatedArtists => {
let next_index = common_key_events::on_middle_press_handler(&artist.related_artists);
artist.selected_related_artist_index = next_index;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_low_press_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let next_index = common_key_events::on_low_press_handler(&artist.top_tracks);
artist.selected_top_track_index = next_index;
}
ArtistBlock::Albums => {
let next_index = common_key_events::on_low_press_handler(&artist.albums.items);
artist.selected_album_index = next_index;
}
ArtistBlock::RelatedArtists => {
let next_index = common_key_events::on_low_press_handler(&artist.related_artists);
artist.selected_related_artist_index = next_index;
}
ArtistBlock::Empty => {}
}
}
}
fn handle_recommend_event_on_selected_block(app: &mut App) {
//recommendations.
if let Some(artist) = &mut app.artist.clone() {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let selected_index = artist.selected_top_track_index;
if let Some(track) = artist.top_tracks.get(selected_index) {
let track_id_list: Option<Vec<String>> = track.id.as_ref().map(|id| vec![id.to_string()]);
app.recommendations_context = Some(RecommendationsContext::Song);
app.recommendations_seed = track.name.clone();
app.get_recommendations_for_seed(None, track_id_list, Some(track.clone()));
}
}
ArtistBlock::RelatedArtists => {
let selected_index = artist.selected_related_artist_index;
let artist_id = &artist.related_artists[selected_index].id;
let artist_name = &artist.related_artists[selected_index].name;
let artist_id_list: Option<Vec<String>> = Some(vec![artist_id.clone()]);
app.recommendations_context = Some(RecommendationsContext::Artist);
app.recommendations_seed = artist_name.clone();
app.get_recommendations_for_seed(artist_id_list, None, None);
}
_ => {}
}
}
}
fn handle_enter_event_on_selected_block(app: &mut App) {
if let Some(artist) = &mut app.artist.clone() {
match artist.artist_selected_block {
ArtistBlock::TopTracks => {
let selected_index = artist.selected_top_track_index;
let top_tracks = artist
.top_tracks
.iter()
.map(|track| track.uri.to_owned())
.collect();
app.dispatch(IoEvent::StartPlayback(
None,
Some(top_tracks),
Some(selected_index),
));
}
ArtistBlock::Albums => {
if let Some(selected_album) = artist
.albums
.items
.get(artist.selected_album_index)
.cloned()
{
app.track_table.context = Some(TrackTableContext::AlbumSearch);
app.dispatch(IoEvent::GetAlbumTracks(Box::new(selected_album)));
}
}
ArtistBlock::RelatedArtists => {
let selected_index = artist.selected_related_artist_index;
let artist_id = artist.related_artists[selected_index].id.clone();
let artist_name = artist.related_artists[selected_index].name.clone();
app.get_artist(artist_id, artist_name);
}
ArtistBlock::Empty => {}
}
}
}
fn handle_enter_event_on_hovered_block(app: &mut App) {
if let Some(artist) = &mut app.artist {
match artist.artist_hovered_block {
ArtistBlock::TopTracks => artist.artist_selected_block = ArtistBlock::TopTracks,
ArtistBlock::Albums => artist.artist_selected_block = ArtistBlock::Albums,
ArtistBlock::RelatedArtists => artist.artist_selected_block = ArtistBlock::RelatedArtists,
ArtistBlock::Empty => {}
}
}
}
pub fn handler(key: Key, app: &mut App) {
if let Some(artist) = &mut app.artist {
match key {
Key::Esc => {
artist.artist_selected_block = ArtistBlock::Empty;
}
k if common_key_events::down_event(k) => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_down_press_on_selected_block(app);
} else {
handle_down_press_on_hovered_block(app);
}
}
k if common_key_events::up_event(k) => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_up_press_on_selected_block(app);
} else {
handle_up_press_on_hovered_block(app);
}
}
k if common_key_events::left_event(k) => {
artist.artist_selected_block = ArtistBlock::Empty;
match artist.artist_hovered_block {
ArtistBlock::TopTracks => common_key_events::handle_left_event(app),
ArtistBlock::Albums => {
artist.artist_hovered_block = ArtistBlock::TopTracks;
}
ArtistBlock::RelatedArtists => {
artist.artist_hovered_block = ArtistBlock::Albums;
}
ArtistBlock::Empty => {}
}
}
k if common_key_events::right_event(k) => {
artist.artist_selected_block = ArtistBlock::Empty;
handle_down_press_on_hovered_block(app);
}
k if common_key_events::high_event(k) => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_high_press_on_selected_block(app);
}
}
k if common_key_events::middle_event(k) => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_middle_press_on_selected_block(app);
}
}
k if common_key_events::low_event(k) => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_low_press_on_selected_block(app);
}
}
Key::Enter => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_enter_event_on_selected_block(app);
} else {
handle_enter_event_on_hovered_block(app);
}
}
Key::Char('r') => {
if artist.artist_selected_block != ArtistBlock::Empty {
handle_recommend_event_on_selected_block(app);
}
}
Key::Char('w') => match artist.artist_selected_block {
ArtistBlock::Albums => app.current_user_saved_album_add(ActiveBlock::ArtistBlock),
ArtistBlock::RelatedArtists => app.user_follow_artists(ActiveBlock::ArtistBlock),
_ => (),
},
Key::Char('D') => match artist.artist_selected_block {
ArtistBlock::Albums => app.current_user_saved_album_delete(ActiveBlock::ArtistBlock),
ArtistBlock::RelatedArtists => app.user_unfollow_artists(ActiveBlock::ArtistBlock),
_ => (),
},
_ if key == app.user_config.keys.add_item_to_queue => {
if let ArtistBlock::TopTracks = artist.artist_selected_block {
if let Some(track) = artist.top_tracks.get(artist.selected_top_track_index) {
let uri = track.uri.clone();
app.dispatch(IoEvent::AddItemToQueue(uri));
};
}
}
_ => {}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::ActiveBlock;
#[test]
fn on_esc() {
let mut app = App::default();
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/playlist.rs | src/handlers/playlist.rs | use super::{
super::app::{App, DialogContext, TrackTableContext},
common_key_events,
};
use crate::app::{ActiveBlock, RouteId};
use crate::event::Key;
use crate::network::IoEvent;
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::right_event(k) => common_key_events::handle_right_event(app),
k if common_key_events::down_event(k) => {
match &app.playlists {
Some(p) => {
if let Some(selected_playlist_index) = app.selected_playlist_index {
let next_index =
common_key_events::on_down_press_handler(&p.items, Some(selected_playlist_index));
app.selected_playlist_index = Some(next_index);
}
}
None => {}
};
}
k if common_key_events::up_event(k) => {
match &app.playlists {
Some(p) => {
let next_index =
common_key_events::on_up_press_handler(&p.items, app.selected_playlist_index);
app.selected_playlist_index = Some(next_index);
}
None => {}
};
}
k if common_key_events::high_event(k) => {
match &app.playlists {
Some(_p) => {
let next_index = common_key_events::on_high_press_handler();
app.selected_playlist_index = Some(next_index);
}
None => {}
};
}
k if common_key_events::middle_event(k) => {
match &app.playlists {
Some(p) => {
let next_index = common_key_events::on_middle_press_handler(&p.items);
app.selected_playlist_index = Some(next_index);
}
None => {}
};
}
k if common_key_events::low_event(k) => {
match &app.playlists {
Some(p) => {
let next_index = common_key_events::on_low_press_handler(&p.items);
app.selected_playlist_index = Some(next_index);
}
None => {}
};
}
Key::Enter => {
if let (Some(playlists), Some(selected_playlist_index)) =
(&app.playlists, &app.selected_playlist_index)
{
app.active_playlist_index = Some(selected_playlist_index.to_owned());
app.track_table.context = Some(TrackTableContext::MyPlaylists);
app.playlist_offset = 0;
if let Some(selected_playlist) = playlists.items.get(selected_playlist_index.to_owned()) {
let playlist_id = selected_playlist.id.to_owned();
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, app.playlist_offset));
}
};
}
Key::Char('D') => {
if let (Some(playlists), Some(selected_index)) = (&app.playlists, app.selected_playlist_index)
{
let selected_playlist = &playlists.items[selected_index].name;
app.dialog = Some(selected_playlist.clone());
app.confirm = false;
app.push_navigation_stack(
RouteId::Dialog,
ActiveBlock::Dialog(DialogContext::PlaylistWindow),
);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test() {}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/artist_albums.rs | src/handlers/artist_albums.rs | use super::common_key_events;
use crate::{
app::{App, TrackTableContext},
event::Key,
};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(artist_albums) = &mut app.artist_albums {
let next_index = common_key_events::on_down_press_handler(
&artist_albums.albums.items,
Some(artist_albums.selected_index),
);
artist_albums.selected_index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(artist_albums) = &mut app.artist_albums {
let next_index = common_key_events::on_up_press_handler(
&artist_albums.albums.items,
Some(artist_albums.selected_index),
);
artist_albums.selected_index = next_index;
}
}
Key::Enter => {
if let Some(artist_albums) = &mut app.artist_albums {
if let Some(selected_album) = artist_albums
.albums
.items
.get(artist_albums.selected_index)
.cloned()
{
app.track_table.context = Some(TrackTableContext::AlbumSearch);
app.get_album_tracks(selected_album);
}
};
}
_ => {}
};
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::ActiveBlock;
#[test]
fn on_left_press() {
let mut app = App::new();
app.set_current_route_state(
Some(ActiveBlock::AlbumTracks),
Some(ActiveBlock::AlbumTracks),
);
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_esc() {
let mut app = App::new();
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/mod.rs | src/handlers/mod.rs | mod album_list;
mod album_tracks;
mod analysis;
mod artist;
mod artists;
mod basic_view;
mod common_key_events;
mod dialog;
mod empty;
mod episode_table;
mod error_screen;
mod help_menu;
mod home;
mod input;
mod library;
mod made_for_you;
mod playbar;
mod playlist;
mod podcasts;
mod recently_played;
mod search_results;
mod select_device;
mod track_table;
use super::app::{ActiveBlock, App, ArtistBlock, RouteId, SearchResultBlock};
use crate::event::Key;
use crate::network::IoEvent;
use rspotify::model::{context::CurrentlyPlaybackContext, PlayingItem};
pub use input::handler as input_handler;
pub fn handle_app(key: Key, app: &mut App) {
// First handle any global event and then move to block event
match key {
Key::Esc => {
handle_escape(app);
}
_ if key == app.user_config.keys.jump_to_album => {
handle_jump_to_album(app);
}
_ if key == app.user_config.keys.jump_to_artist_album => {
handle_jump_to_artist_album(app);
}
_ if key == app.user_config.keys.jump_to_context => {
handle_jump_to_context(app);
}
_ if key == app.user_config.keys.manage_devices => {
app.dispatch(IoEvent::GetDevices);
}
_ if key == app.user_config.keys.decrease_volume => {
app.decrease_volume();
}
_ if key == app.user_config.keys.increase_volume => {
app.increase_volume();
}
// Press space to toggle playback
_ if key == app.user_config.keys.toggle_playback => {
app.toggle_playback();
}
_ if key == app.user_config.keys.seek_backwards => {
app.seek_backwards();
}
_ if key == app.user_config.keys.seek_forwards => {
app.seek_forwards();
}
_ if key == app.user_config.keys.next_track => {
app.dispatch(IoEvent::NextTrack);
}
_ if key == app.user_config.keys.previous_track => {
app.previous_track();
}
_ if key == app.user_config.keys.help => {
app.set_current_route_state(Some(ActiveBlock::HelpMenu), None);
}
_ if key == app.user_config.keys.shuffle => {
app.shuffle();
}
_ if key == app.user_config.keys.repeat => {
app.repeat();
}
_ if key == app.user_config.keys.search => {
app.set_current_route_state(Some(ActiveBlock::Input), Some(ActiveBlock::Input));
}
_ if key == app.user_config.keys.copy_song_url => {
app.copy_song_url();
}
_ if key == app.user_config.keys.copy_album_url => {
app.copy_album_url();
}
_ if key == app.user_config.keys.audio_analysis => {
app.get_audio_analysis();
}
_ if key == app.user_config.keys.basic_view => {
app.push_navigation_stack(RouteId::BasicView, ActiveBlock::BasicView);
}
_ => handle_block_events(key, app),
}
}
// Handle event for the current active block
fn handle_block_events(key: Key, app: &mut App) {
let current_route = app.get_current_route();
match current_route.active_block {
ActiveBlock::Analysis => {
analysis::handler(key, app);
}
ActiveBlock::ArtistBlock => {
artist::handler(key, app);
}
ActiveBlock::Input => {
input::handler(key, app);
}
ActiveBlock::MyPlaylists => {
playlist::handler(key, app);
}
ActiveBlock::TrackTable => {
track_table::handler(key, app);
}
ActiveBlock::EpisodeTable => {
episode_table::handler(key, app);
}
ActiveBlock::HelpMenu => {
help_menu::handler(key, app);
}
ActiveBlock::Error => {
error_screen::handler(key, app);
}
ActiveBlock::SelectDevice => {
select_device::handler(key, app);
}
ActiveBlock::SearchResultBlock => {
search_results::handler(key, app);
}
ActiveBlock::Home => {
home::handler(key, app);
}
ActiveBlock::AlbumList => {
album_list::handler(key, app);
}
ActiveBlock::AlbumTracks => {
album_tracks::handler(key, app);
}
ActiveBlock::Library => {
library::handler(key, app);
}
ActiveBlock::Empty => {
empty::handler(key, app);
}
ActiveBlock::RecentlyPlayed => {
recently_played::handler(key, app);
}
ActiveBlock::Artists => {
artists::handler(key, app);
}
ActiveBlock::MadeForYou => {
made_for_you::handler(key, app);
}
ActiveBlock::Podcasts => {
podcasts::handler(key, app);
}
ActiveBlock::PlayBar => {
playbar::handler(key, app);
}
ActiveBlock::BasicView => {
basic_view::handler(key, app);
}
ActiveBlock::Dialog(_) => {
dialog::handler(key, app);
}
}
}
fn handle_escape(app: &mut App) {
match app.get_current_route().active_block {
ActiveBlock::SearchResultBlock => {
app.search_results.selected_block = SearchResultBlock::Empty;
}
ActiveBlock::ArtistBlock => {
if let Some(artist) = &mut app.artist {
artist.artist_selected_block = ArtistBlock::Empty;
}
}
ActiveBlock::Error => {
app.pop_navigation_stack();
}
ActiveBlock::Dialog(_) => {
app.pop_navigation_stack();
}
// These are global views that have no active/inactive distinction so do nothing
ActiveBlock::SelectDevice | ActiveBlock::Analysis => {}
_ => {
app.set_current_route_state(Some(ActiveBlock::Empty), None);
}
}
}
fn handle_jump_to_context(app: &mut App) {
if let Some(current_playback_context) = &app.current_playback_context {
if let Some(play_context) = current_playback_context.context.clone() {
match play_context._type {
rspotify::senum::Type::Album => handle_jump_to_album(app),
rspotify::senum::Type::Artist => handle_jump_to_artist_album(app),
rspotify::senum::Type::Playlist => {
app.dispatch(IoEvent::GetPlaylistTracks(play_context.uri, 0))
}
_ => {}
}
}
}
}
fn handle_jump_to_album(app: &mut App) {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = app.current_playback_context.to_owned()
{
match item {
PlayingItem::Track(track) => {
app.dispatch(IoEvent::GetAlbumTracks(Box::new(track.album)));
}
PlayingItem::Episode(episode) => {
app.dispatch(IoEvent::GetShowEpisodes(Box::new(episode.show)));
}
};
}
}
// NOTE: this only finds the first artist of the song and jumps to their albums
fn handle_jump_to_artist_album(app: &mut App) {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = app.current_playback_context.to_owned()
{
match item {
PlayingItem::Track(track) => {
if let Some(artist) = track.artists.first() {
if let Some(artist_id) = artist.id.clone() {
app.get_artist(artist_id, artist.name.clone());
app.push_navigation_stack(RouteId::Artist, ActiveBlock::ArtistBlock);
}
}
}
PlayingItem::Episode(_episode) => {
// Do nothing for episode (yet!)
}
}
};
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/album_list.rs | src/handlers/album_list.rs | use super::common_key_events;
use crate::{
app::{ActiveBlock, AlbumTableContext, App, RouteId, SelectedFullAlbum},
event::Key,
};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(albums) = &mut app.library.saved_albums.get_results(None) {
let next_index =
common_key_events::on_down_press_handler(&albums.items, Some(app.album_list_index));
app.album_list_index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(albums) = &mut app.library.saved_albums.get_results(None) {
let next_index =
common_key_events::on_up_press_handler(&albums.items, Some(app.album_list_index));
app.album_list_index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_albums) = app.library.saved_albums.get_results(None) {
let next_index = common_key_events::on_high_press_handler();
app.album_list_index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(albums) = app.library.saved_albums.get_results(None) {
let next_index = common_key_events::on_middle_press_handler(&albums.items);
app.album_list_index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(albums) = app.library.saved_albums.get_results(None) {
let next_index = common_key_events::on_low_press_handler(&albums.items);
app.album_list_index = next_index;
}
}
Key::Enter => {
if let Some(albums) = app.library.saved_albums.get_results(None) {
if let Some(selected_album) = albums.items.get(app.album_list_index) {
app.selected_album_full = Some(SelectedFullAlbum {
album: selected_album.album.clone(),
selected_index: 0,
});
app.album_table_context = AlbumTableContext::Full;
app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
};
}
}
k if k == app.user_config.keys.next_page => app.get_current_user_saved_albums_next(),
k if k == app.user_config.keys.previous_page => app.get_current_user_saved_albums_previous(),
Key::Char('D') => app.current_user_saved_album_delete(ActiveBlock::AlbumList),
_ => {}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_left_press() {
let mut app = App::default();
app.set_current_route_state(
Some(ActiveBlock::AlbumTracks),
Some(ActiveBlock::AlbumTracks),
);
handler(Key::Left, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
assert_eq!(current_route.hovered_block, ActiveBlock::Library);
}
#[test]
fn on_esc() {
let mut app = App::default();
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/basic_view.rs | src/handlers/basic_view.rs | use crate::{app::App, event::Key, network::IoEvent};
use rspotify::model::{context::CurrentlyPlaybackContext, PlayingItem};
pub fn handler(key: Key, app: &mut App) {
if let Key::Char('s') = key {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = app.current_playback_context.to_owned()
{
match item {
PlayingItem::Track(track) => {
if let Some(track_id) = track.id {
app.dispatch(IoEvent::ToggleSaveTrack(track_id));
}
}
PlayingItem::Episode(episode) => {
app.dispatch(IoEvent::ToggleSaveTrack(episode.id));
}
};
};
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/artists.rs | src/handlers/artists.rs | use super::common_key_events;
use crate::{
app::{ActiveBlock, App, RecommendationsContext, RouteId},
event::Key,
network::IoEvent,
};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(artists) = &mut app.library.saved_artists.get_results(None) {
let next_index =
common_key_events::on_down_press_handler(&artists.items, Some(app.artists_list_index));
app.artists_list_index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(artists) = &mut app.library.saved_artists.get_results(None) {
let next_index =
common_key_events::on_up_press_handler(&artists.items, Some(app.artists_list_index));
app.artists_list_index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_artists) = &mut app.library.saved_artists.get_results(None) {
let next_index = common_key_events::on_high_press_handler();
app.artists_list_index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(artists) = &mut app.library.saved_artists.get_results(None) {
let next_index = common_key_events::on_middle_press_handler(&artists.items);
app.artists_list_index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(artists) = &mut app.library.saved_artists.get_results(None) {
let next_index = common_key_events::on_low_press_handler(&artists.items);
app.artists_list_index = next_index;
}
}
Key::Enter => {
let artists = app.artists.to_owned();
if !artists.is_empty() {
let artist = &artists[app.artists_list_index];
app.get_artist(artist.id.clone(), artist.name.clone());
app.push_navigation_stack(RouteId::Artist, ActiveBlock::ArtistBlock);
}
}
Key::Char('D') => app.user_unfollow_artists(ActiveBlock::AlbumList),
Key::Char('e') => {
let artists = app.artists.to_owned();
let artist = artists.get(app.artists_list_index);
if let Some(artist) = artist {
app.dispatch(IoEvent::StartPlayback(
Some(artist.uri.to_owned()),
None,
None,
));
}
}
Key::Char('r') => {
let artists = app.artists.to_owned();
let artist = artists.get(app.artists_list_index);
if let Some(artist) = artist {
let artist_name = artist.name.clone();
let artist_id_list: Option<Vec<String>> = Some(vec![artist.id.clone()]);
app.recommendations_context = Some(RecommendationsContext::Artist);
app.recommendations_seed = artist_name;
app.get_recommendations_for_seed(artist_id_list, None, None);
}
}
k if k == app.user_config.keys.next_page => app.get_current_user_saved_artists_next(),
k if k == app.user_config.keys.previous_page => app.get_current_user_saved_artists_previous(),
_ => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/help_menu.rs | src/handlers/help_menu.rs | use super::common_key_events;
use crate::{app::App, event::Key};
#[derive(PartialEq)]
enum Direction {
Up,
Down,
}
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::down_event(k) => {
move_page(Direction::Down, app);
}
k if common_key_events::up_event(k) => {
move_page(Direction::Up, app);
}
Key::Ctrl('d') => {
move_page(Direction::Down, app);
}
Key::Ctrl('u') => {
move_page(Direction::Up, app);
}
_ => {}
};
}
fn move_page(direction: Direction, app: &mut App) {
if direction == Direction::Up {
if app.help_menu_page > 0 {
app.help_menu_page -= 1;
}
} else if direction == Direction::Down {
app.help_menu_page += 1;
}
app.calculate_help_menu_offset();
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/input.rs | src/handlers/input.rs | extern crate unicode_width;
use super::super::app::{ActiveBlock, App, RouteId};
use crate::event::Key;
use crate::network::IoEvent;
use std::convert::TryInto;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
// Handle event when the search input block is active
pub fn handler(key: Key, app: &mut App) {
match key {
Key::Ctrl('k') => {
app.input.drain(app.input_idx..app.input.len());
}
Key::Ctrl('u') => {
app.input.drain(..app.input_idx);
app.input_idx = 0;
app.input_cursor_position = 0;
}
Key::Ctrl('l') => {
app.input = vec![];
app.input_idx = 0;
app.input_cursor_position = 0;
}
Key::Ctrl('w') => {
if app.input_cursor_position == 0 {
return;
}
let word_end = match app.input[..app.input_idx].iter().rposition(|&x| x != ' ') {
Some(index) => index + 1,
None => 0,
};
let word_start = match app.input[..word_end].iter().rposition(|&x| x == ' ') {
Some(index) => index + 1,
None => 0,
};
let deleted: String = app.input[word_start..app.input_idx].iter().collect();
let deleted_len: u16 = UnicodeWidthStr::width(deleted.as_str()).try_into().unwrap();
app.input.drain(word_start..app.input_idx);
app.input_idx = word_start;
app.input_cursor_position -= deleted_len;
}
Key::End | Key::Ctrl('e') => {
app.input_idx = app.input.len();
let input_string: String = app.input.iter().collect();
app.input_cursor_position = UnicodeWidthStr::width(input_string.as_str())
.try_into()
.unwrap();
}
Key::Home | Key::Ctrl('a') => {
app.input_idx = 0;
app.input_cursor_position = 0;
}
Key::Left | Key::Ctrl('b') => {
if !app.input.is_empty() && app.input_idx > 0 {
let last_c = app.input[app.input_idx - 1];
app.input_idx -= 1;
app.input_cursor_position -= compute_character_width(last_c);
}
}
Key::Right | Key::Ctrl('f') => {
if app.input_idx < app.input.len() {
let next_c = app.input[app.input_idx];
app.input_idx += 1;
app.input_cursor_position += compute_character_width(next_c);
}
}
Key::Esc => {
app.set_current_route_state(Some(ActiveBlock::Empty), Some(ActiveBlock::Library));
}
Key::Enter => {
let input_str: String = app.input.iter().collect();
process_input(app, input_str);
}
Key::Char(c) => {
app.input.insert(app.input_idx, c);
app.input_idx += 1;
app.input_cursor_position += compute_character_width(c);
}
Key::Backspace | Key::Ctrl('h') => {
if !app.input.is_empty() && app.input_idx > 0 {
let last_c = app.input.remove(app.input_idx - 1);
app.input_idx -= 1;
app.input_cursor_position -= compute_character_width(last_c);
}
}
Key::Delete | Key::Ctrl('d') => {
if !app.input.is_empty() && app.input_idx < app.input.len() {
app.input.remove(app.input_idx);
}
}
_ => {}
}
}
fn process_input(app: &mut App, input: String) {
// Don't do anything if there is no input
if input.is_empty() {
return;
}
// On searching for a track, clear the playlist selection
app.selected_playlist_index = Some(0);
if attempt_process_uri(app, &input, "https://open.spotify.com/", "/")
|| attempt_process_uri(app, &input, "spotify:", ":")
{
return;
}
// Default fallback behavior: treat the input as a raw search phrase.
app.dispatch(IoEvent::GetSearchResults(input, app.get_user_country()));
app.push_navigation_stack(RouteId::Search, ActiveBlock::SearchResultBlock);
}
fn spotify_resource_id(base: &str, uri: &str, sep: &str, resource_type: &str) -> (String, bool) {
let uri_prefix = format!("{}{}{}", base, resource_type, sep);
let id_string_with_query_params = uri.trim_start_matches(&uri_prefix);
let query_idx = id_string_with_query_params
.find('?')
.unwrap_or_else(|| id_string_with_query_params.len());
let id_string = id_string_with_query_params[0..query_idx].to_string();
// If the lengths aren't equal, we must have found a match.
let matched = id_string_with_query_params.len() != uri.len() && id_string.len() != uri.len();
(id_string, matched)
}
// Returns true if the input was successfully processed as a Spotify URI.
fn attempt_process_uri(app: &mut App, input: &str, base: &str, sep: &str) -> bool {
let (album_id, matched) = spotify_resource_id(base, input, sep, "album");
if matched {
app.dispatch(IoEvent::GetAlbum(album_id));
return true;
}
let (artist_id, matched) = spotify_resource_id(base, input, sep, "artist");
if matched {
app.get_artist(artist_id, "".to_string());
app.push_navigation_stack(RouteId::Artist, ActiveBlock::ArtistBlock);
return true;
}
let (track_id, matched) = spotify_resource_id(base, input, sep, "track");
if matched {
app.dispatch(IoEvent::GetAlbumForTrack(track_id));
return true;
}
let (playlist_id, matched) = spotify_resource_id(base, input, sep, "playlist");
if matched {
app.dispatch(IoEvent::GetPlaylistTracks(playlist_id, 0));
return true;
}
let (show_id, matched) = spotify_resource_id(base, input, sep, "show");
if matched {
app.dispatch(IoEvent::GetShow(show_id));
return true;
}
false
}
fn compute_character_width(character: char) -> u16 {
UnicodeWidthChar::width(character)
.unwrap()
.try_into()
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
fn str_to_vec_char(s: &str) -> Vec<char> {
String::from(s).chars().collect()
}
#[test]
fn test_compute_character_width_with_multiple_characters() {
assert_eq!(1, compute_character_width('a'));
assert_eq!(1, compute_character_width('ß'));
assert_eq!(1, compute_character_width('ç'));
}
#[test]
fn test_input_handler_clear_input_on_ctrl_l() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
handler(Key::Ctrl('l'), &mut app);
assert_eq!(app.input, str_to_vec_char(""));
}
#[test]
fn test_input_handler_ctrl_u() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
handler(Key::Ctrl('u'), &mut app);
assert_eq!(app.input, str_to_vec_char("My text"));
app.input_cursor_position = 3;
app.input_idx = 3;
handler(Key::Ctrl('u'), &mut app);
assert_eq!(app.input, str_to_vec_char("text"));
}
#[test]
fn test_input_handler_ctrl_k() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
handler(Key::Ctrl('k'), &mut app);
assert_eq!(app.input, str_to_vec_char(""));
app.input = str_to_vec_char("My text");
app.input_cursor_position = 2;
app.input_idx = 2;
handler(Key::Ctrl('k'), &mut app);
assert_eq!(app.input, str_to_vec_char("My"));
handler(Key::Ctrl('k'), &mut app);
assert_eq!(app.input, str_to_vec_char("My"));
}
#[test]
fn test_input_handler_ctrl_w() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
handler(Key::Ctrl('w'), &mut app);
assert_eq!(app.input, str_to_vec_char("My text"));
app.input_cursor_position = 3;
app.input_idx = 3;
handler(Key::Ctrl('w'), &mut app);
assert_eq!(app.input, str_to_vec_char("text"));
assert_eq!(app.input_cursor_position, 0);
assert_eq!(app.input_idx, 0);
app.input = str_to_vec_char(" ");
app.input_cursor_position = 3;
app.input_idx = 3;
handler(Key::Ctrl('w'), &mut app);
assert_eq!(app.input, str_to_vec_char(" "));
assert_eq!(app.input_cursor_position, 0);
assert_eq!(app.input_idx, 0);
app.input_cursor_position = 1;
app.input_idx = 1;
handler(Key::Ctrl('w'), &mut app);
assert_eq!(app.input, str_to_vec_char(""));
assert_eq!(app.input_cursor_position, 0);
assert_eq!(app.input_idx, 0);
app.input = str_to_vec_char("Hello there ");
app.input_cursor_position = 13;
app.input_idx = 13;
handler(Key::Ctrl('w'), &mut app);
assert_eq!(app.input, str_to_vec_char("Hello "));
assert_eq!(app.input_cursor_position, 6);
assert_eq!(app.input_idx, 6);
}
#[test]
fn test_input_handler_esc_back_to_playlist() {
let mut app = App::default();
app.set_current_route_state(Some(ActiveBlock::MyPlaylists), None);
handler(Key::Esc, &mut app);
let current_route = app.get_current_route();
assert_eq!(current_route.active_block, ActiveBlock::Empty);
}
#[test]
fn test_input_handler_on_enter_text() {
let mut app = App::default();
app.input = str_to_vec_char("My tex");
app.input_cursor_position = app.input.len().try_into().unwrap();
app.input_idx = app.input.len();
handler(Key::Char('t'), &mut app);
assert_eq!(app.input, str_to_vec_char("My text"));
}
#[test]
fn test_input_handler_backspace() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
app.input_cursor_position = app.input.len().try_into().unwrap();
app.input_idx = app.input.len();
handler(Key::Backspace, &mut app);
assert_eq!(app.input, str_to_vec_char("My tex"));
// Test that backspace deletes from the cursor position
app.input_idx = 2;
app.input_cursor_position = 2;
handler(Key::Backspace, &mut app);
assert_eq!(app.input, str_to_vec_char("M tex"));
app.input_idx = 1;
app.input_cursor_position = 1;
handler(Key::Ctrl('h'), &mut app);
assert_eq!(app.input, str_to_vec_char(" tex"));
}
#[test]
fn test_input_handler_delete() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
app.input_idx = 3;
app.input_cursor_position = 3;
handler(Key::Delete, &mut app);
assert_eq!(app.input, str_to_vec_char("My ext"));
app.input = str_to_vec_char("ラスト");
app.input_idx = 1;
app.input_cursor_position = 1;
handler(Key::Delete, &mut app);
assert_eq!(app.input, str_to_vec_char("ラト"));
app.input = str_to_vec_char("Rust");
app.input_idx = 2;
app.input_cursor_position = 2;
handler(Key::Ctrl('d'), &mut app);
assert_eq!(app.input, str_to_vec_char("Rut"));
}
#[test]
fn test_input_handler_left_event() {
let mut app = App::default();
app.input = str_to_vec_char("My text");
let input_len = app.input.len().try_into().unwrap();
app.input_idx = app.input.len();
app.input_cursor_position = input_len;
handler(Key::Left, &mut app);
assert_eq!(app.input_cursor_position, input_len - 1);
handler(Key::Left, &mut app);
assert_eq!(app.input_cursor_position, input_len - 2);
handler(Key::Left, &mut app);
assert_eq!(app.input_cursor_position, input_len - 3);
handler(Key::Ctrl('b'), &mut app);
assert_eq!(app.input_cursor_position, input_len - 4);
handler(Key::Ctrl('b'), &mut app);
assert_eq!(app.input_cursor_position, input_len - 5);
// Pretend to smash the left event to test the we have no out-of-bounds crash
for _ in 0..20 {
handler(Key::Left, &mut app);
}
assert_eq!(app.input_cursor_position, 0);
}
#[test]
fn test_input_handler_on_enter_text_non_english_char() {
let mut app = App::default();
app.input = str_to_vec_char("ыа");
app.input_cursor_position = app.input.len().try_into().unwrap();
app.input_idx = app.input.len();
handler(Key::Char('ы'), &mut app);
assert_eq!(app.input, str_to_vec_char("ыаы"));
}
#[test]
fn test_input_handler_on_enter_text_wide_char() {
let mut app = App::default();
app.input = str_to_vec_char("你");
app.input_cursor_position = 2; // 你 is 2 char wide
app.input_idx = 1; // 1 char
handler(Key::Char('好'), &mut app);
assert_eq!(app.input, str_to_vec_char("你好"));
assert_eq!(app.input_idx, 2);
assert_eq!(app.input_cursor_position, 4);
}
mod test_uri_parsing {
use super::*;
const URI_BASE: &str = "spotify:";
const URL_BASE: &str = "https://open.spotify.com/";
fn check_uri_parse(expected_id: &str, parsed: (String, bool)) {
assert_eq!(parsed.1, true);
assert_eq!(parsed.0, expected_id);
}
fn run_test_for_id_and_resource_type(id: &str, resource_type: &str) {
check_uri_parse(
id,
spotify_resource_id(
URI_BASE,
&format!("spotify:{}:{}", resource_type, id),
":",
resource_type,
),
);
check_uri_parse(
id,
spotify_resource_id(
URL_BASE,
&format!("https://open.spotify.com/{}/{}", resource_type, id),
"/",
resource_type,
),
)
}
#[test]
fn artist() {
let expected_artist_id = "2ye2Wgw4gimLv2eAKyk1NB";
run_test_for_id_and_resource_type(expected_artist_id, "artist");
}
#[test]
fn album() {
let expected_album_id = "5gzLOflH95LkKYE6XSXE9k";
run_test_for_id_and_resource_type(expected_album_id, "album");
}
#[test]
fn playlist() {
let expected_playlist_id = "1cJ6lPBYj2fscs0kqBHsVV";
run_test_for_id_and_resource_type(expected_playlist_id, "playlist");
}
#[test]
fn show() {
let expected_show_id = "3aNsrV6lkzmcU1w8u8kA7N";
run_test_for_id_and_resource_type(expected_show_id, "show");
}
#[test]
fn track() {
let expected_track_id = "10igKaIKsSB6ZnWxPxPvKO";
run_test_for_id_and_resource_type(expected_track_id, "track");
}
#[test]
fn invalid_format_doesnt_match() {
let swapped = "show:spotify:3aNsrV6lkzmcU1w8u8kA7N";
let totally_wrong = "hehe-haha-3aNsrV6lkzmcU1w8u8kA7N";
let random = "random string";
let (_, matched) = spotify_resource_id(URI_BASE, swapped, ":", "track");
assert_eq!(matched, false);
let (_, matched) = spotify_resource_id(URI_BASE, totally_wrong, ":", "track");
assert_eq!(matched, false);
let (_, matched) = spotify_resource_id(URL_BASE, totally_wrong, "/", "track");
assert_eq!(matched, false);
let (_, matched) = spotify_resource_id(URL_BASE, random, "/", "track");
assert_eq!(matched, false);
}
#[test]
fn parse_with_query_parameters() {
// If this test ever fails due to some change to the parsing logic, it is likely a sign we
// should just integrate the url crate instead of trying to do things ourselves.
let playlist_url_with_query =
"https://open.spotify.com/playlist/1cJ6lPBYj2fscs0kqBHsVV?si=OdwuJsbsSeuUAOadehng3A";
let playlist_url = "https://open.spotify.com/playlist/1cJ6lPBYj2fscs0kqBHsVV";
let expected_id = "1cJ6lPBYj2fscs0kqBHsVV";
let (actual_id, matched) = spotify_resource_id(URL_BASE, playlist_url, "/", "playlist");
assert_eq!(matched, true);
assert_eq!(actual_id, expected_id);
let (actual_id, matched) =
spotify_resource_id(URL_BASE, playlist_url_with_query, "/", "playlist");
assert_eq!(matched, true);
assert_eq!(actual_id, expected_id);
}
#[test]
fn mismatched_resource_types_do_not_match() {
let playlist_url =
"https://open.spotify.com/playlist/1cJ6lPBYj2fscs0kqBHsVV?si=OdwuJsbsSeuUAOadehng3A";
let (_, matched) = spotify_resource_id(URL_BASE, playlist_url, "/", "album");
assert_eq!(matched, false);
}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/podcasts.rs | src/handlers/podcasts.rs | use super::common_key_events;
use crate::{
app::{ActiveBlock, App},
event::Key,
network::IoEvent,
};
pub fn handler(key: Key, app: &mut App) {
match key {
k if common_key_events::left_event(k) => common_key_events::handle_left_event(app),
k if common_key_events::down_event(k) => {
if let Some(shows) = &mut app.library.saved_shows.get_results(None) {
let next_index =
common_key_events::on_down_press_handler(&shows.items, Some(app.shows_list_index));
app.shows_list_index = next_index;
}
}
k if common_key_events::up_event(k) => {
if let Some(shows) = &mut app.library.saved_shows.get_results(None) {
let next_index =
common_key_events::on_up_press_handler(&shows.items, Some(app.shows_list_index));
app.shows_list_index = next_index;
}
}
k if common_key_events::high_event(k) => {
if let Some(_shows) = app.library.saved_shows.get_results(None) {
let next_index = common_key_events::on_high_press_handler();
app.shows_list_index = next_index;
}
}
k if common_key_events::middle_event(k) => {
if let Some(shows) = app.library.saved_shows.get_results(None) {
let next_index = common_key_events::on_middle_press_handler(&shows.items);
app.shows_list_index = next_index;
}
}
k if common_key_events::low_event(k) => {
if let Some(shows) = app.library.saved_shows.get_results(None) {
let next_index = common_key_events::on_low_press_handler(&shows.items);
app.shows_list_index = next_index;
}
}
Key::Enter => {
if let Some(shows) = app.library.saved_shows.get_results(None) {
if let Some(selected_show) = shows.items.get(app.shows_list_index).cloned() {
app.dispatch(IoEvent::GetShowEpisodes(Box::new(selected_show.show)));
};
}
}
k if k == app.user_config.keys.next_page => app.get_current_user_saved_shows_next(),
k if k == app.user_config.keys.previous_page => app.get_current_user_saved_shows_previous(),
Key::Char('D') => app.user_unfollow_show(ActiveBlock::Podcasts),
_ => {}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/handlers/error_screen.rs | src/handlers/error_screen.rs | use crate::{app::App, event::Key};
pub fn handler(_key: Key, _app: &mut App) {}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/cli/clap.rs | src/cli/clap.rs | use clap::{App, Arg, ArgGroup, SubCommand};
fn device_arg() -> Arg<'static, 'static> {
Arg::with_name("device")
.short("d")
.long("device")
.takes_value(true)
.value_name("DEVICE")
.help("Specifies the spotify device to use")
}
fn format_arg() -> Arg<'static, 'static> {
Arg::with_name("format")
.short("f")
.long("format")
.takes_value(true)
.value_name("FORMAT")
.help("Specifies the output format")
.long_help(
"There are multiple format specifiers you can use: %a: artist, %b: album, %p: playlist, \
%t: track, %h: show, %f: flags (shuffle, repeat, like), %s: playback status, %v: volume, %d: current device. \
Example: spt pb -s -f 'playing on %d at %v%'",
)
}
pub fn playback_subcommand() -> App<'static, 'static> {
SubCommand::with_name("playback")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Interacts with the playback of a device")
.long_about(
"Use `playback` to interact with the playback of the current or any other device. \
You can specify another device with `--device`. If no options were provided, spt \
will default to just displaying the current playback. Actually, after every action \
spt will display the updated playback. The output format is configurable with the \
`--format` flag. Some options can be used together, other options have to be alone.
Here's a list:
* `--next` and `--previous` cannot be used with other options
* `--status`, `--toggle`, `--transfer`, `--volume`, `--like`, `--repeat` and `--shuffle` \
can be used together
* `--share-track` and `--share-album` cannot be used with other options",
)
.visible_alias("pb")
.arg(device_arg())
.arg(
format_arg()
.default_value("%f %s %t - %a")
.default_value_ifs(&[
("seek", None, "%f %s %t - %a %r"),
("volume", None, "%v% %f %s %t - %a"),
("transfer", None, "%f %s %t - %a on %d"),
]),
)
.arg(
Arg::with_name("toggle")
.short("t")
.long("toggle")
.help("Pauses/resumes the playback of a device"),
)
.arg(
Arg::with_name("status")
.short("s")
.long("status")
.help("Prints out the current status of a device (default)"),
)
.arg(
Arg::with_name("share-track")
.long("share-track")
.help("Returns the url to the current track"),
)
.arg(
Arg::with_name("share-album")
.long("share-album")
.help("Returns the url to the album of the current track"),
)
.arg(
Arg::with_name("transfer")
.long("transfer")
.takes_value(true)
.value_name("DEVICE")
.help("Transfers the playback to new DEVICE"),
)
.arg(
Arg::with_name("like")
.long("like")
.help("Likes the current song if possible"),
)
.arg(
Arg::with_name("dislike")
.long("dislike")
.help("Dislikes the current song if possible"),
)
.arg(
Arg::with_name("shuffle")
.long("shuffle")
.help("Toggles shuffle mode"),
)
.arg(
Arg::with_name("repeat")
.long("repeat")
.help("Switches between repeat modes"),
)
.arg(
Arg::with_name("next")
.short("n")
.long("next")
.multiple(true)
.help("Jumps to the next song")
.long_help(
"This jumps to the next song if specied once. If you want to jump, let's say 3 songs \
forward, you can use `--next` 3 times: `spt pb -nnn`.",
),
)
.arg(
Arg::with_name("previous")
.short("p")
.long("previous")
.multiple(true)
.help("Jumps to the previous song")
.long_help(
"This jumps to the beginning of the current song if specied once. You probably want to \
jump to the previous song though, so you can use the previous flag twice: `spt pb -pp`. To jump \
two songs back, you can use `spt pb -ppp` and so on.",
),
)
.arg(
Arg::with_name("seek")
.long("seek")
.takes_value(true)
.value_name("±SECONDS")
.allow_hyphen_values(true)
.help("Jumps SECONDS forwards (+) or backwards (-)")
.long_help(
"For example: `spt pb --seek +10` jumps ten second forwards, `spt pb --seek -10` ten \
seconds backwards and `spt pb --seek 10` to the tenth second of the track.",
),
)
.arg(
Arg::with_name("volume")
.short("v")
.long("volume")
.takes_value(true)
.value_name("VOLUME")
.help("Sets the volume of a device to VOLUME (1 - 100)"),
)
.group(
ArgGroup::with_name("jumps")
.args(&["next", "previous"])
.multiple(false)
.conflicts_with_all(&["single", "flags", "actions"]),
)
.group(
ArgGroup::with_name("likes")
.args(&["like", "dislike"])
.multiple(false),
)
.group(
ArgGroup::with_name("flags")
.args(&["like", "dislike", "shuffle", "repeat"])
.multiple(true)
.conflicts_with_all(&["single", "jumps"]),
)
.group(
ArgGroup::with_name("actions")
.args(&["toggle", "status", "transfer", "volume"])
.multiple(true)
.conflicts_with_all(&["single", "jumps"]),
)
.group(
ArgGroup::with_name("single")
.args(&["share-track", "share-album"])
.multiple(false)
.conflicts_with_all(&["actions", "flags", "jumps"]),
)
}
pub fn play_subcommand() -> App<'static, 'static> {
SubCommand::with_name("play")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Plays a uri or another spotify item by name")
.long_about(
"If you specify a uri, the type can be inferred. If you want to play something by \
name, you have to specify the type: `--track`, `--album`, `--artist`, `--playlist` \
or `--show`. The first item which was found will be played without confirmation. \
To add a track to the queue, use `--queue`. To play a random song from a playlist, \
use `--random`. Again, with `--format` you can specify how the output will look. \
The same function as found in `playback` will be called.",
)
.visible_alias("p")
.arg(device_arg())
.arg(format_arg().default_value("%f %s %t - %a"))
.arg(
Arg::with_name("uri")
.short("u")
.long("uri")
.takes_value(true)
.value_name("URI")
.help("Plays the URI"),
)
.arg(
Arg::with_name("name")
.short("n")
.long("name")
.takes_value(true)
.value_name("NAME")
.requires("contexts")
.help("Plays the first match with NAME from the specified category"),
)
.arg(
Arg::with_name("queue")
.short("q")
.long("queue")
// Only works with tracks
.conflicts_with_all(&["album", "artist", "playlist", "show"])
.help("Adds track to queue instead of playing it directly"),
)
.arg(
Arg::with_name("random")
.short("r")
.long("random")
// Only works with playlists
.conflicts_with_all(&["track", "album", "artist", "show"])
.help("Plays a random track (only works with playlists)"),
)
.arg(
Arg::with_name("album")
.short("b")
.long("album")
.help("Looks for an album"),
)
.arg(
Arg::with_name("artist")
.short("a")
.long("artist")
.help("Looks for an artist"),
)
.arg(
Arg::with_name("track")
.short("t")
.long("track")
.help("Looks for a track"),
)
.arg(
Arg::with_name("show")
.short("w")
.long("show")
.help("Looks for a show"),
)
.arg(
Arg::with_name("playlist")
.short("p")
.long("playlist")
.help("Looks for a playlist"),
)
.group(
ArgGroup::with_name("contexts")
.args(&["track", "artist", "playlist", "album", "show"])
.multiple(false),
)
.group(
ArgGroup::with_name("actions")
.args(&["uri", "name"])
.multiple(false)
.required(true),
)
}
pub fn list_subcommand() -> App<'static, 'static> {
SubCommand::with_name("list")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Lists devices, liked songs and playlists")
.long_about(
"This will list devices, liked songs or playlists. With the `--limit` flag you are \
able to specify the amount of results (between 1 and 50). Here, the `--format` is \
even more awesome, get your output exactly the way you want. The format option will \
be applied to every item found.",
)
.visible_alias("l")
.arg(format_arg().default_value_ifs(&[
("devices", None, "%v% %d"),
("liked", None, "%t - %a (%u)"),
("playlists", None, "%p (%u)"),
]))
.arg(
Arg::with_name("devices")
.short("d")
.long("devices")
.help("Lists devices"),
)
.arg(
Arg::with_name("playlists")
.short("p")
.long("playlists")
.help("Lists playlists"),
)
.arg(
Arg::with_name("liked")
.long("liked")
.help("Lists liked songs"),
)
.arg(
Arg::with_name("limit")
.long("limit")
.takes_value(true)
.help("Specifies the maximum number of results (1 - 50)"),
)
.group(
ArgGroup::with_name("listable")
.args(&["devices", "playlists", "liked"])
.required(true)
.multiple(false),
)
}
pub fn search_subcommand() -> App<'static, 'static> {
SubCommand::with_name("search")
.version(env!("CARGO_PKG_VERSION"))
.author(env!("CARGO_PKG_AUTHORS"))
.about("Searches for tracks, albums and more")
.long_about(
"This will search for something on spotify and displays you the items. The output \
format can be changed with the `--format` flag and the limit can be changed with \
the `--limit` flag (between 1 and 50). The type can't be inferred, so you have to \
specify it.",
)
.visible_alias("s")
.arg(format_arg().default_value_ifs(&[
("tracks", None, "%t - %a (%u)"),
("playlists", None, "%p (%u)"),
("artists", None, "%a (%u)"),
("albums", None, "%b - %a (%u)"),
("shows", None, "%h - %a (%u)"),
]))
.arg(
Arg::with_name("search")
.required(true)
.takes_value(true)
.value_name("SEARCH")
.help("Specifies the search query"),
)
.arg(
Arg::with_name("albums")
.short("b")
.long("albums")
.help("Looks for albums"),
)
.arg(
Arg::with_name("artists")
.short("a")
.long("artists")
.help("Looks for artists"),
)
.arg(
Arg::with_name("playlists")
.short("p")
.long("playlists")
.help("Looks for playlists"),
)
.arg(
Arg::with_name("tracks")
.short("t")
.long("tracks")
.help("Looks for tracks"),
)
.arg(
Arg::with_name("shows")
.short("w")
.long("shows")
.help("Looks for shows"),
)
.arg(
Arg::with_name("limit")
.long("limit")
.takes_value(true)
.help("Specifies the maximum number of results (1 - 50)"),
)
.group(
ArgGroup::with_name("searchable")
.args(&["playlists", "tracks", "albums", "artists", "shows"])
.required(true)
.multiple(false),
)
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/cli/util.rs | src/cli/util.rs | use clap::ArgMatches;
use rspotify::{
model::{
album::SimplifiedAlbum, artist::FullArtist, artist::SimplifiedArtist,
playlist::SimplifiedPlaylist, show::FullEpisode, show::SimplifiedShow, track::FullTrack,
},
senum::RepeatState,
};
use crate::user_config::UserConfig;
// Possible types to list or search
#[derive(Debug)]
pub enum Type {
Playlist,
Track,
Artist,
Album,
Show,
Device,
Liked,
}
impl Type {
pub fn play_from_matches(m: &ArgMatches<'_>) -> Self {
if m.is_present("playlist") {
Self::Playlist
} else if m.is_present("track") {
Self::Track
} else if m.is_present("artist") {
Self::Artist
} else if m.is_present("album") {
Self::Album
} else if m.is_present("show") {
Self::Show
}
// Enforced by clap
else {
unreachable!()
}
}
pub fn search_from_matches(m: &ArgMatches<'_>) -> Self {
if m.is_present("playlists") {
Self::Playlist
} else if m.is_present("tracks") {
Self::Track
} else if m.is_present("artists") {
Self::Artist
} else if m.is_present("albums") {
Self::Album
} else if m.is_present("shows") {
Self::Show
}
// Enforced by clap
else {
unreachable!()
}
}
pub fn list_from_matches(m: &ArgMatches<'_>) -> Self {
if m.is_present("playlists") {
Self::Playlist
} else if m.is_present("devices") {
Self::Device
} else if m.is_present("liked") {
Self::Liked
}
// Enforced by clap
else {
unreachable!()
}
}
}
//
// Possible flags to set
//
pub enum Flag {
// Does not get toggled
// * User chooses like -> Flag::Like(true)
// * User chooses dislike -> Flag::Like(false)
Like(bool),
Shuffle,
Repeat,
}
impl Flag {
pub fn from_matches(m: &ArgMatches<'_>) -> Vec<Self> {
// Multiple flags are possible
let mut flags = Vec::new();
// Only one of these two
if m.is_present("like") {
flags.push(Self::Like(true));
} else if m.is_present("dislike") {
flags.push(Self::Like(false));
}
if m.is_present("shuffle") {
flags.push(Self::Shuffle);
}
if m.is_present("repeat") {
flags.push(Self::Repeat);
}
flags
}
}
// Possible directions to jump to
pub enum JumpDirection {
Next,
Previous,
}
impl JumpDirection {
pub fn from_matches(m: &ArgMatches<'_>) -> (Self, u64) {
if m.is_present("next") {
(Self::Next, m.occurrences_of("next"))
} else if m.is_present("previous") {
(Self::Previous, m.occurrences_of("previous"))
// Enforced by clap
} else {
unreachable!()
}
}
}
// For fomatting (-f / --format flag)
// Types to create a Format enum from
// Boxing was proposed by cargo clippy
// to reduce the size of this enum
pub enum FormatType {
Album(Box<SimplifiedAlbum>),
Artist(Box<FullArtist>),
Playlist(Box<SimplifiedPlaylist>),
Track(Box<FullTrack>),
Episode(Box<FullEpisode>),
Show(Box<SimplifiedShow>),
}
// Types that can be formatted
#[derive(Clone)]
pub enum Format {
Album(String),
Artist(String),
Playlist(String),
Track(String),
Show(String),
Uri(String),
Device(String),
Volume(u32),
// Current position, duration
Position((u32, u32)),
// This is a bit long, should it be splitted up?
Flags((RepeatState, bool, bool)),
Playing(bool),
}
pub fn join_artists(a: Vec<SimplifiedArtist>) -> String {
a.iter()
.map(|l| l.name.clone())
.collect::<Vec<String>>()
.join(", ")
}
impl Format {
// Extract important information from types
pub fn from_type(t: FormatType) -> Vec<Self> {
match t {
FormatType::Album(a) => {
let joined_artists = join_artists(a.artists.clone());
let mut vec = vec![Self::Album(a.name), Self::Artist(joined_artists)];
if let Some(uri) = a.uri {
vec.push(Self::Uri(uri));
}
vec
}
FormatType::Artist(a) => vec![Self::Artist(a.name), Self::Uri(a.uri)],
FormatType::Playlist(p) => vec![Self::Playlist(p.name), Self::Uri(p.uri)],
FormatType::Track(t) => {
let joined_artists = join_artists(t.artists.clone());
vec![
Self::Album(t.album.name),
Self::Artist(joined_artists),
Self::Track(t.name),
Self::Uri(t.uri),
]
}
FormatType::Show(r) => vec![
Self::Artist(r.publisher),
Self::Show(r.name),
Self::Uri(r.uri),
],
FormatType::Episode(e) => vec![
Self::Show(e.show.name),
Self::Artist(e.show.publisher),
Self::Track(e.name),
Self::Uri(e.uri),
],
}
}
// Is there a better way?
pub fn inner(&self, conf: UserConfig) -> String {
match self {
Self::Album(s) => s.clone(),
Self::Artist(s) => s.clone(),
Self::Playlist(s) => s.clone(),
Self::Track(s) => s.clone(),
Self::Show(s) => s.clone(),
Self::Uri(s) => s.clone(),
Self::Device(s) => s.clone(),
// Because this match statements
// needs to return a &String, I have to do it this way
Self::Volume(s) => s.to_string(),
Self::Position((curr, duration)) => {
crate::ui::util::display_track_progress(*curr as u128, *duration)
}
Self::Flags((r, s, l)) => {
let like = if *l {
conf.behavior.liked_icon
} else {
String::new()
};
let shuffle = if *s {
conf.behavior.shuffle_icon
} else {
String::new()
};
let repeat = match r {
RepeatState::Off => String::new(),
RepeatState::Track => conf.behavior.repeat_track_icon,
RepeatState::Context => conf.behavior.repeat_context_icon,
};
// Add them together (only those that aren't empty)
[shuffle, repeat, like]
.iter()
.filter(|a| !a.is_empty())
// Convert &String to String to join them
.map(|s| s.to_string())
.collect::<Vec<String>>()
.join(" ")
}
Self::Playing(s) => {
if *s {
conf.behavior.playing_icon
} else {
conf.behavior.paused_icon
}
}
}
}
pub fn get_placeholder(&self) -> &str {
match self {
Self::Album(_) => "%b",
Self::Artist(_) => "%a",
Self::Playlist(_) => "%p",
Self::Track(_) => "%t",
Self::Show(_) => "%h",
Self::Uri(_) => "%u",
Self::Device(_) => "%d",
Self::Volume(_) => "%v",
Self::Position(_) => "%r",
Self::Flags(_) => "%f",
Self::Playing(_) => "%s",
}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/cli/mod.rs | src/cli/mod.rs | mod clap;
mod cli_app;
mod handle;
mod util;
pub use self::clap::{list_subcommand, play_subcommand, playback_subcommand, search_subcommand};
use cli_app::CliApp;
pub use handle::handle_matches;
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/cli/cli_app.rs | src/cli/cli_app.rs | use crate::network::{IoEvent, Network};
use crate::user_config::UserConfig;
use super::util::{Flag, Format, FormatType, JumpDirection, Type};
use anyhow::{anyhow, Result};
use rand::{thread_rng, Rng};
use rspotify::model::{context::CurrentlyPlaybackContext, PlayingItem};
pub struct CliApp<'a> {
pub net: Network<'a>,
pub config: UserConfig,
}
// Non-concurrent functions
// I feel that async in a cli is not working
// I just .await all processes and directly interact
// by calling network.handle_network_event
impl<'a> CliApp<'a> {
pub fn new(net: Network<'a>, config: UserConfig) -> Self {
Self { net, config }
}
async fn is_a_saved_track(&mut self, id: &str) -> bool {
// Update the liked_song_ids_set
self
.net
.handle_network_event(IoEvent::CurrentUserSavedTracksContains(
vec![id.to_string()],
))
.await;
self.net.app.lock().await.liked_song_ids_set.contains(id)
}
pub fn format_output(&self, mut format: String, values: Vec<Format>) -> String {
for val in values {
format = format.replace(val.get_placeholder(), &val.inner(self.config.clone()));
}
// Replace unsupported flags with 'None'
for p in &["%a", "%b", "%t", "%p", "%h", "%u", "%d", "%v", "%f", "%s"] {
format = format.replace(p, "None");
}
format.trim().to_string()
}
// spt playback -t
pub async fn toggle_playback(&mut self) {
let context = self.net.app.lock().await.current_playback_context.clone();
if let Some(c) = context {
if c.is_playing {
self.net.handle_network_event(IoEvent::PausePlayback).await;
return;
}
}
self
.net
.handle_network_event(IoEvent::StartPlayback(None, None, None))
.await;
}
// spt pb --share-track (share the current playing song)
// Basically copy-pasted the 'copy_song_url' function
pub async fn share_track_or_episode(&mut self) -> Result<String> {
let app = self.net.app.lock().await;
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &app.current_playback_context
{
match item {
PlayingItem::Track(track) => Ok(format!(
"https://open.spotify.com/track/{}",
track.id.to_owned().unwrap_or_default()
)),
PlayingItem::Episode(episode) => Ok(format!(
"https://open.spotify.com/episode/{}",
episode.id.to_owned()
)),
}
} else {
Err(anyhow!(
"failed to generate a shareable url for the current song"
))
}
}
// spt pb --share-album (share the current album)
// Basically copy-pasted the 'copy_album_url' function
pub async fn share_album_or_show(&mut self) -> Result<String> {
let app = self.net.app.lock().await;
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &app.current_playback_context
{
match item {
PlayingItem::Track(track) => Ok(format!(
"https://open.spotify.com/album/{}",
track.album.id.to_owned().unwrap_or_default()
)),
PlayingItem::Episode(episode) => Ok(format!(
"https://open.spotify.com/show/{}",
episode.show.id.to_owned()
)),
}
} else {
Err(anyhow!(
"failed to generate a shareable url for the current song"
))
}
}
// spt ... -d ... (specify device to control)
pub async fn set_device(&mut self, name: String) -> Result<()> {
// Change the device if specified by user
let mut app = self.net.app.lock().await;
let mut device_index = 0;
if let Some(dp) = &app.devices {
for (i, d) in dp.devices.iter().enumerate() {
if d.name == name {
device_index = i;
// Save the id of the device
self
.net
.client_config
.set_device_id(d.id.clone())
.map_err(|_e| anyhow!("failed to use device with name '{}'", d.name))?;
}
}
} else {
// Error out if no device is available
return Err(anyhow!("no device available"));
}
app.selected_device_index = Some(device_index);
Ok(())
}
// spt query ... --limit LIMIT (set max search limit)
pub async fn update_query_limits(&mut self, max: String) -> Result<()> {
let num = max
.parse::<u32>()
.map_err(|_e| anyhow!("limit must be between 1 and 50"))?;
// 50 seems to be the maximum limit
if num > 50 || num == 0 {
return Err(anyhow!("limit must be between 1 and 50"));
};
self
.net
.handle_network_event(IoEvent::UpdateSearchLimits(num, num))
.await;
Ok(())
}
pub async fn volume(&mut self, vol: String) -> Result<()> {
let num = vol
.parse::<u32>()
.map_err(|_e| anyhow!("volume must be between 0 and 100"))?;
// Check if it's in range
if num > 100 {
return Err(anyhow!("volume must be between 0 and 100"));
};
self
.net
.handle_network_event(IoEvent::ChangeVolume(num as u8))
.await;
Ok(())
}
// spt playback --next / --previous
pub async fn jump(&mut self, d: &JumpDirection) {
match d {
JumpDirection::Next => self.net.handle_network_event(IoEvent::NextTrack).await,
JumpDirection::Previous => self.net.handle_network_event(IoEvent::PreviousTrack).await,
}
}
// spt query -l ...
pub async fn list(&mut self, item: Type, format: &str) -> String {
match item {
Type::Device => {
if let Some(devices) = &self.net.app.lock().await.devices {
devices
.devices
.iter()
.map(|d| {
self.format_output(
format.to_string(),
vec![
Format::Device(d.name.clone()),
Format::Volume(d.volume_percent),
],
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
"No devices available".to_string()
}
}
Type::Playlist => {
self.net.handle_network_event(IoEvent::GetPlaylists).await;
if let Some(playlists) = &self.net.app.lock().await.playlists {
playlists
.items
.iter()
.map(|p| {
self.format_output(
format.to_string(),
Format::from_type(FormatType::Playlist(Box::new(p.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
"No playlists found".to_string()
}
}
Type::Liked => {
self
.net
.handle_network_event(IoEvent::GetCurrentSavedTracks(None))
.await;
let liked_songs = self
.net
.app
.lock()
.await
.track_table
.tracks
.iter()
.map(|t| {
self.format_output(
format.to_string(),
Format::from_type(FormatType::Track(Box::new(t.clone()))),
)
})
.collect::<Vec<String>>();
// Check if there are any liked songs
if liked_songs.is_empty() {
"No liked songs found".to_string()
} else {
liked_songs.join("\n")
}
}
// Enforced by clap
_ => unreachable!(),
}
}
// spt playback --transfer DEVICE
pub async fn transfer_playback(&mut self, device: &str) -> Result<()> {
// Get the device id by name
let mut id = String::new();
if let Some(devices) = &self.net.app.lock().await.devices {
for d in &devices.devices {
if d.name == device {
id.push_str(d.id.as_str());
break;
}
}
};
if id.is_empty() {
Err(anyhow!("no device with name '{}'", device))
} else {
self
.net
.handle_network_event(IoEvent::TransferPlaybackToDevice(id.to_string()))
.await;
Ok(())
}
}
pub async fn seek(&mut self, seconds_str: String) -> Result<()> {
let seconds = match seconds_str.parse::<i32>() {
Ok(s) => s.abs() as u32,
Err(_) => return Err(anyhow!("failed to convert seconds to i32")),
};
let (current_pos, duration) = {
self
.net
.handle_network_event(IoEvent::GetCurrentPlayback)
.await;
let app = self.net.app.lock().await;
if let Some(CurrentlyPlaybackContext {
progress_ms: Some(ms),
item: Some(item),
..
}) = &app.current_playback_context
{
let duration = match item {
PlayingItem::Track(track) => track.duration_ms,
PlayingItem::Episode(episode) => episode.duration_ms,
};
(*ms as u32, duration)
} else {
return Err(anyhow!("no context available"));
}
};
// Convert secs to ms
let ms = seconds * 1000;
// Calculate new positon
let position_to_seek = if seconds_str.starts_with('+') {
current_pos + ms
} else if seconds_str.starts_with('-') {
// Jump to the beginning if the position_to_seek would be
// negative, must be checked before the calculation to avoid
// an 'underflow'
if ms > current_pos {
0u32
} else {
current_pos - ms
}
} else {
// Absolute value of the track
seconds * 1000
};
// Check if position_to_seek is greater than duration (next track)
if position_to_seek > duration {
self.jump(&JumpDirection::Next).await;
} else {
// This seeks to a position in the current song
self
.net
.handle_network_event(IoEvent::Seek(position_to_seek))
.await;
}
Ok(())
}
// spt playback --like / --dislike / --shuffle / --repeat
pub async fn mark(&mut self, flag: Flag) -> Result<()> {
let c = {
let app = self.net.app.lock().await;
app
.current_playback_context
.clone()
.ok_or_else(|| anyhow!("no context available"))?
};
match flag {
Flag::Like(s) => {
// Get the id of the current song
let id = match c.item {
Some(i) => match i {
PlayingItem::Track(t) => t.id.ok_or_else(|| anyhow!("item has no id")),
PlayingItem::Episode(_) => Err(anyhow!("saving episodes not yet implemented")),
},
None => Err(anyhow!("no item playing")),
}?;
// Want to like but is already liked -> do nothing
// Want to like and is not liked yet -> like
if s && !self.is_a_saved_track(&id).await {
self
.net
.handle_network_event(IoEvent::ToggleSaveTrack(id))
.await;
// Want to dislike but is already disliked -> do nothing
// Want to dislike and is liked currently -> remove like
} else if !s && self.is_a_saved_track(&id).await {
self
.net
.handle_network_event(IoEvent::ToggleSaveTrack(id))
.await;
}
}
Flag::Shuffle => {
self
.net
.handle_network_event(IoEvent::Shuffle(c.shuffle_state))
.await
}
Flag::Repeat => {
self
.net
.handle_network_event(IoEvent::Repeat(c.repeat_state))
.await;
}
}
Ok(())
}
// spt playback -s
pub async fn get_status(&mut self, format: String) -> Result<String> {
// Update info on current playback
self
.net
.handle_network_event(IoEvent::GetCurrentPlayback)
.await;
self
.net
.handle_network_event(IoEvent::GetCurrentSavedTracks(None))
.await;
let context = self
.net
.app
.lock()
.await
.current_playback_context
.clone()
.ok_or_else(|| anyhow!("no context available"))?;
let playing_item = context.item.ok_or_else(|| anyhow!("no track playing"))?;
let mut hs = match playing_item {
PlayingItem::Track(track) => {
let id = track.id.clone().unwrap_or_default();
let mut hs = Format::from_type(FormatType::Track(Box::new(track.clone())));
if let Some(ms) = context.progress_ms {
hs.push(Format::Position((ms, track.duration_ms)))
}
hs.push(Format::Flags((
context.repeat_state,
context.shuffle_state,
self.is_a_saved_track(&id).await,
)));
hs
}
PlayingItem::Episode(episode) => {
let mut hs = Format::from_type(FormatType::Episode(Box::new(episode.clone())));
if let Some(ms) = context.progress_ms {
hs.push(Format::Position((ms, episode.duration_ms)))
}
hs.push(Format::Flags((
context.repeat_state,
context.shuffle_state,
false,
)));
hs
}
};
hs.push(Format::Device(context.device.name));
hs.push(Format::Volume(context.device.volume_percent));
hs.push(Format::Playing(context.is_playing));
Ok(self.format_output(format, hs))
}
// spt play -u URI
pub async fn play_uri(&mut self, uri: String, queue: bool, random: bool) {
let offset = if random {
// Only works with playlists for now
if uri.contains("spotify:playlist:") {
let id = uri.split(':').last().unwrap();
match self.net.spotify.playlist(id, None, None).await {
Ok(p) => {
let num = p.tracks.total;
Some(thread_rng().gen_range(0..num) as usize)
}
Err(e) => {
self
.net
.app
.lock()
.await
.handle_error(anyhow!(e.to_string()));
return;
}
}
} else {
None
}
} else {
None
};
if uri.contains("spotify:track:") {
if queue {
self
.net
.handle_network_event(IoEvent::AddItemToQueue(uri))
.await;
} else {
self
.net
.handle_network_event(IoEvent::StartPlayback(
None,
Some(vec![uri.clone()]),
Some(0),
))
.await;
}
} else {
self
.net
.handle_network_event(IoEvent::StartPlayback(Some(uri.clone()), None, offset))
.await;
}
}
// spt play -n NAME ...
pub async fn play(&mut self, name: String, item: Type, queue: bool, random: bool) -> Result<()> {
self
.net
.handle_network_event(IoEvent::GetSearchResults(name.clone(), None))
.await;
// Get the uri of the first found
// item + the offset or return an error message
let uri = {
let results = &self.net.app.lock().await.search_results;
match item {
Type::Track => {
if let Some(r) = &results.tracks {
r.items[0].uri.clone()
} else {
return Err(anyhow!("no tracks with name '{}'", name));
}
}
Type::Album => {
if let Some(r) = &results.albums {
let album = &r.items[0];
if let Some(uri) = &album.uri {
uri.clone()
} else {
return Err(anyhow!("album {} has no uri", album.name));
}
} else {
return Err(anyhow!("no albums with name '{}'", name));
}
}
Type::Artist => {
if let Some(r) = &results.artists {
r.items[0].uri.clone()
} else {
return Err(anyhow!("no artists with name '{}'", name));
}
}
Type::Show => {
if let Some(r) = &results.shows {
r.items[0].uri.clone()
} else {
return Err(anyhow!("no shows with name '{}'", name));
}
}
Type::Playlist => {
if let Some(r) = &results.playlists {
let p = &r.items[0];
// For a random song, create a random offset
p.uri.clone()
} else {
return Err(anyhow!("no playlists with name '{}'", name));
}
}
_ => unreachable!(),
}
};
// Play or queue the uri
self.play_uri(uri, queue, random).await;
Ok(())
}
// spt query -s SEARCH ...
pub async fn query(&mut self, search: String, format: String, item: Type) -> String {
self
.net
.handle_network_event(IoEvent::GetSearchResults(search.clone(), None))
.await;
let app = self.net.app.lock().await;
match item {
Type::Playlist => {
if let Some(results) = &app.search_results.playlists {
results
.items
.iter()
.map(|r| {
self.format_output(
format.clone(),
Format::from_type(FormatType::Playlist(Box::new(r.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
format!("no playlists with name '{}'", search)
}
}
Type::Track => {
if let Some(results) = &app.search_results.tracks {
results
.items
.iter()
.map(|r| {
self.format_output(
format.clone(),
Format::from_type(FormatType::Track(Box::new(r.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
format!("no tracks with name '{}'", search)
}
}
Type::Artist => {
if let Some(results) = &app.search_results.artists {
results
.items
.iter()
.map(|r| {
self.format_output(
format.clone(),
Format::from_type(FormatType::Artist(Box::new(r.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
format!("no artists with name '{}'", search)
}
}
Type::Show => {
if let Some(results) = &app.search_results.shows {
results
.items
.iter()
.map(|r| {
self.format_output(
format.clone(),
Format::from_type(FormatType::Show(Box::new(r.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
format!("no shows with name '{}'", search)
}
}
Type::Album => {
if let Some(results) = &app.search_results.albums {
results
.items
.iter()
.map(|r| {
self.format_output(
format.clone(),
Format::from_type(FormatType::Album(Box::new(r.clone()))),
)
})
.collect::<Vec<String>>()
.join("\n")
} else {
format!("no albums with name '{}'", search)
}
}
// Enforced by clap
_ => unreachable!(),
}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/cli/handle.rs | src/cli/handle.rs | use crate::network::{IoEvent, Network};
use crate::user_config::UserConfig;
use super::{
util::{Flag, JumpDirection, Type},
CliApp,
};
use anyhow::{anyhow, Result};
use clap::ArgMatches;
// Handle the different subcommands
pub async fn handle_matches(
matches: &ArgMatches<'_>,
cmd: String,
net: Network<'_>,
config: UserConfig,
) -> Result<String> {
let mut cli = CliApp::new(net, config);
cli.net.handle_network_event(IoEvent::GetDevices).await;
cli
.net
.handle_network_event(IoEvent::GetCurrentPlayback)
.await;
let devices_list = match &cli.net.app.lock().await.devices {
Some(p) => p
.devices
.iter()
.map(|d| d.id.clone())
.collect::<Vec<String>>(),
None => Vec::new(),
};
// If the device_id is not specified, select the first available device
let device_id = cli.net.client_config.device_id.clone();
if device_id.is_none() || !devices_list.contains(&device_id.unwrap()) {
// Select the first device available
if let Some(d) = devices_list.get(0) {
cli.net.client_config.set_device_id(d.clone())?;
}
}
if let Some(d) = matches.value_of("device") {
cli.set_device(d.to_string()).await?;
}
// Evalute the subcommand
let output = match cmd.as_str() {
"playback" => {
let format = matches.value_of("format").unwrap();
// Commands that are 'single'
if matches.is_present("share-track") {
return cli.share_track_or_episode().await;
} else if matches.is_present("share-album") {
return cli.share_album_or_show().await;
}
// Run the action, and print out the status
// No 'else if's because multiple different commands are possible
if matches.is_present("toggle") {
cli.toggle_playback().await;
}
if let Some(d) = matches.value_of("transfer") {
cli.transfer_playback(d).await?;
}
// Multiple flags are possible
if matches.is_present("flags") {
let flags = Flag::from_matches(matches);
for f in flags {
cli.mark(f).await?;
}
}
if matches.is_present("jumps") {
let (direction, amount) = JumpDirection::from_matches(matches);
for _ in 0..amount {
cli.jump(&direction).await;
}
}
if let Some(vol) = matches.value_of("volume") {
cli.volume(vol.to_string()).await?;
}
if let Some(secs) = matches.value_of("seek") {
cli.seek(secs.to_string()).await?;
}
// Print out the status if no errors were found
cli.get_status(format.to_string()).await
}
"play" => {
let queue = matches.is_present("queue");
let random = matches.is_present("random");
let format = matches.value_of("format").unwrap();
if let Some(uri) = matches.value_of("uri") {
cli.play_uri(uri.to_string(), queue, random).await;
} else if let Some(name) = matches.value_of("name") {
let category = Type::play_from_matches(matches);
cli.play(name.to_string(), category, queue, random).await?;
}
cli.get_status(format.to_string()).await
}
"list" => {
let format = matches.value_of("format").unwrap().to_string();
// Update the limits for the list and search functions
// I think the small and big search limits are very confusing
// so I just set them both to max, is this okay?
if let Some(max) = matches.value_of("limit") {
cli.update_query_limits(max.to_string()).await?;
}
let category = Type::list_from_matches(matches);
Ok(cli.list(category, &format).await)
}
"search" => {
let format = matches.value_of("format").unwrap().to_string();
// Update the limits for the list and search functions
// I think the small and big search limits are very confusing
// so I just set them both to max, is this okay?
if let Some(max) = matches.value_of("limit") {
cli.update_query_limits(max.to_string()).await?;
}
let category = Type::search_from_matches(matches);
Ok(
cli
.query(
matches.value_of("search").unwrap().to_string(),
format,
category,
)
.await,
)
}
// Clap enforces that one of the things above is specified
_ => unreachable!(),
};
// Check if there was an error
let api_error = cli.net.app.lock().await.api_error.clone();
if api_error.is_empty() {
output
} else {
Err(anyhow!("{}", api_error))
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/ui/audio_analysis.rs | src/ui/audio_analysis.rs | use super::util;
use crate::app::App;
use tui::{
backend::Backend,
layout::{Constraint, Direction, Layout},
style::Style,
text::{Span, Spans},
widgets::{BarChart, Block, Borders, Paragraph},
Frame,
};
const PITCHES: [&str; 12] = [
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B",
];
pub fn draw<B>(f: &mut Frame<B>, app: &App)
where
B: Backend,
{
let margin = util::get_main_layout_margin(app);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(5), Constraint::Length(95)].as_ref())
.margin(margin)
.split(f.size());
let analysis_block = Block::default()
.title(Span::styled(
"Analysis",
Style::default().fg(app.user_config.theme.inactive),
))
.borders(Borders::ALL)
.border_style(Style::default().fg(app.user_config.theme.inactive));
let white = Style::default().fg(app.user_config.theme.text);
let gray = Style::default().fg(app.user_config.theme.inactive);
let width = (chunks[1].width) as f32 / (1 + PITCHES.len()) as f32;
let tick_rate = app.user_config.behavior.tick_rate_milliseconds;
let bar_chart_title = &format!("Pitches | Tick Rate {} {}FPS", tick_rate, 1000 / tick_rate);
let bar_chart_block = Block::default()
.borders(Borders::ALL)
.style(white)
.title(Span::styled(bar_chart_title, gray))
.border_style(gray);
let empty_analysis_block = || {
Paragraph::new("No analysis available")
.block(analysis_block.clone())
.style(Style::default().fg(app.user_config.theme.text))
};
let empty_pitches_block = || {
Paragraph::new("No pitch information available")
.block(bar_chart_block.clone())
.style(Style::default().fg(app.user_config.theme.text))
};
if let Some(analysis) = &app.audio_analysis {
let progress_seconds = (app.song_progress_ms as f32) / 1000.0;
let beat = analysis
.beats
.iter()
.find(|beat| beat.start >= progress_seconds);
let beat_offset = beat
.map(|beat| beat.start - progress_seconds)
.unwrap_or(0.0);
let segment = analysis
.segments
.iter()
.find(|segment| segment.start >= progress_seconds);
let section = analysis
.sections
.iter()
.find(|section| section.start >= progress_seconds);
if let (Some(segment), Some(section)) = (segment, section) {
let texts = vec![
Spans::from(format!(
"Tempo: {} (confidence {:.0}%)",
section.tempo,
section.tempo_confidence * 100.0
)),
Spans::from(format!(
"Key: {} (confidence {:.0}%)",
PITCHES.get(section.key as usize).unwrap_or(&PITCHES[0]),
section.key_confidence * 100.0
)),
Spans::from(format!(
"Time Signature: {}/4 (confidence {:.0}%)",
section.time_signature,
section.time_signature_confidence * 100.0
)),
];
let p = Paragraph::new(texts)
.block(analysis_block)
.style(Style::default().fg(app.user_config.theme.text));
f.render_widget(p, chunks[0]);
let data: Vec<(&str, u64)> = segment
.clone()
.pitches
.iter()
.enumerate()
.map(|(index, pitch)| {
let display_pitch = *PITCHES.get(index).unwrap_or(&PITCHES[0]);
let bar_value = ((pitch * 1000.0) as u64)
// Add a beat offset to make the bar animate between beats
.checked_add((beat_offset * 3000.0) as u64)
.unwrap_or(0);
(display_pitch, bar_value)
})
.collect();
let analysis_bar = BarChart::default()
.block(bar_chart_block)
.data(&data)
.bar_width(width as u16)
.bar_style(Style::default().fg(app.user_config.theme.analysis_bar))
.value_style(
Style::default()
.fg(app.user_config.theme.analysis_bar_text)
.bg(app.user_config.theme.analysis_bar),
);
f.render_widget(analysis_bar, chunks[1]);
} else {
f.render_widget(empty_analysis_block(), chunks[0]);
f.render_widget(empty_pitches_block(), chunks[1]);
};
} else {
f.render_widget(empty_analysis_block(), chunks[0]);
f.render_widget(empty_pitches_block(), chunks[1]);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/ui/help.rs | src/ui/help.rs | use crate::user_config::KeyBindings;
pub fn get_help_docs(key_bindings: &KeyBindings) -> Vec<Vec<String>> {
vec![
vec![
String::from("Scroll down to next result page"),
key_bindings.next_page.to_string(),
String::from("Pagination"),
],
vec![
String::from("Scroll up to previous result page"),
key_bindings.previous_page.to_string(),
String::from("Pagination"),
],
vec![
String::from("Jump to start of playlist"),
key_bindings.jump_to_start.to_string(),
String::from("Pagination"),
],
vec![
String::from("Jump to end of playlist"),
key_bindings.jump_to_end.to_string(),
String::from("Pagination"),
],
vec![
String::from("Jump to currently playing album"),
key_bindings.jump_to_album.to_string(),
String::from("General"),
],
vec![
String::from("Jump to currently playing artist's album list"),
key_bindings.jump_to_artist_album.to_string(),
String::from("General"),
],
vec![
String::from("Jump to current play context"),
key_bindings.jump_to_context.to_string(),
String::from("General"),
],
vec![
String::from("Increase volume by 10%"),
key_bindings.increase_volume.to_string(),
String::from("General"),
],
vec![
String::from("Decrease volume by 10%"),
key_bindings.decrease_volume.to_string(),
String::from("General"),
],
vec![
String::from("Skip to next track"),
key_bindings.next_track.to_string(),
String::from("General"),
],
vec![
String::from("Skip to previous track"),
key_bindings.previous_track.to_string(),
String::from("General"),
],
vec![
String::from("Seek backwards 5 seconds"),
key_bindings.seek_backwards.to_string(),
String::from("General"),
],
vec![
String::from("Seek forwards 5 seconds"),
key_bindings.seek_forwards.to_string(),
String::from("General"),
],
vec![
String::from("Toggle shuffle"),
key_bindings.shuffle.to_string(),
String::from("General"),
],
vec![
String::from("Copy url to currently playing song/episode"),
key_bindings.copy_song_url.to_string(),
String::from("General"),
],
vec![
String::from("Copy url to currently playing album/show"),
key_bindings.copy_album_url.to_string(),
String::from("General"),
],
vec![
String::from("Cycle repeat mode"),
key_bindings.repeat.to_string(),
String::from("General"),
],
vec![
String::from("Move selection left"),
String::from("h | <Left Arrow Key> | <Ctrl+b>"),
String::from("General"),
],
vec![
String::from("Move selection down"),
String::from("j | <Down Arrow Key> | <Ctrl+n>"),
String::from("General"),
],
vec![
String::from("Move selection up"),
String::from("k | <Up Arrow Key> | <Ctrl+p>"),
String::from("General"),
],
vec![
String::from("Move selection right"),
String::from("l | <Right Arrow Key> | <Ctrl+f>"),
String::from("General"),
],
vec![
String::from("Move selection to top of list"),
String::from("H"),
String::from("General"),
],
vec![
String::from("Move selection to middle of list"),
String::from("M"),
String::from("General"),
],
vec![
String::from("Move selection to bottom of list"),
String::from("L"),
String::from("General"),
],
vec![
String::from("Enter input for search"),
key_bindings.search.to_string(),
String::from("General"),
],
vec![
String::from("Pause/Resume playback"),
key_bindings.toggle_playback.to_string(),
String::from("General"),
],
vec![
String::from("Enter active mode"),
String::from("<Enter>"),
String::from("General"),
],
vec![
String::from("Go to audio analysis screen"),
key_bindings.audio_analysis.to_string(),
String::from("General"),
],
vec![
String::from("Go to playbar only screen (basic view)"),
key_bindings.basic_view.to_string(),
String::from("General"),
],
vec![
String::from("Go back or exit when nowhere left to back to"),
key_bindings.back.to_string(),
String::from("General"),
],
vec![
String::from("Select device to play music on"),
key_bindings.manage_devices.to_string(),
String::from("General"),
],
vec![
String::from("Enter hover mode"),
String::from("<Esc>"),
String::from("Selected block"),
],
vec![
String::from("Save track in list or table"),
String::from("s"),
String::from("Selected block"),
],
vec![
String::from("Start playback or enter album/artist/playlist"),
key_bindings.submit.to_string(),
String::from("Selected block"),
],
vec![
String::from("Play recommendations for song/artist"),
String::from("r"),
String::from("Selected block"),
],
vec![
String::from("Play all tracks for artist"),
String::from("e"),
String::from("Library -> Artists"),
],
vec![
String::from("Search with input text"),
String::from("<Enter>"),
String::from("Search input"),
],
vec![
String::from("Move cursor one space left"),
String::from("<Left Arrow Key>"),
String::from("Search input"),
],
vec![
String::from("Move cursor one space right"),
String::from("<Right Arrow Key>"),
String::from("Search input"),
],
vec![
String::from("Delete entire input"),
String::from("<Ctrl+l>"),
String::from("Search input"),
],
vec![
String::from("Delete text from cursor to start of input"),
String::from("<Ctrl+u>"),
String::from("Search input"),
],
vec![
String::from("Delete text from cursor to end of input"),
String::from("<Ctrl+k>"),
String::from("Search input"),
],
vec![
String::from("Delete previous word"),
String::from("<Ctrl+w>"),
String::from("Search input"),
],
vec![
String::from("Jump to start of input"),
String::from("<Ctrl+a>"),
String::from("Search input"),
],
vec![
String::from("Jump to end of input"),
String::from("<Ctrl+e>"),
String::from("Search input"),
],
vec![
String::from("Escape from the input back to hovered block"),
String::from("<Esc>"),
String::from("Search input"),
],
vec![
String::from("Delete saved album"),
String::from("D"),
String::from("Library -> Albums"),
],
vec![
String::from("Delete saved playlist"),
String::from("D"),
String::from("Playlist"),
],
vec![
String::from("Follow an artist/playlist"),
String::from("w"),
String::from("Search result"),
],
vec![
String::from("Save (like) album to library"),
String::from("w"),
String::from("Search result"),
],
vec![
String::from("Play random song in playlist"),
String::from("S"),
String::from("Selected Playlist"),
],
vec![
String::from("Toggle sort order of podcast episodes"),
String::from("S"),
String::from("Selected Show"),
],
vec![
String::from("Add track to queue"),
key_bindings.add_item_to_queue.to_string(),
String::from("Hovered over track"),
],
]
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/ui/util.rs | src/ui/util.rs | use super::super::app::{ActiveBlock, App, ArtistBlock, SearchResultBlock};
use crate::user_config::Theme;
use rspotify::model::artist::SimplifiedArtist;
use tui::style::Style;
pub const BASIC_VIEW_HEIGHT: u16 = 6;
pub const SMALL_TERMINAL_WIDTH: u16 = 150;
pub const SMALL_TERMINAL_HEIGHT: u16 = 45;
pub fn get_search_results_highlight_state(
app: &App,
block_to_match: SearchResultBlock,
) -> (bool, bool) {
let current_route = app.get_current_route();
(
app.search_results.selected_block == block_to_match,
current_route.hovered_block == ActiveBlock::SearchResultBlock
&& app.search_results.hovered_block == block_to_match,
)
}
pub fn get_artist_highlight_state(app: &App, block_to_match: ArtistBlock) -> (bool, bool) {
let current_route = app.get_current_route();
if let Some(artist) = &app.artist {
let is_hovered = artist.artist_selected_block == block_to_match;
let is_selected = current_route.hovered_block == ActiveBlock::ArtistBlock
&& artist.artist_hovered_block == block_to_match;
(is_hovered, is_selected)
} else {
(false, false)
}
}
pub fn get_color((is_active, is_hovered): (bool, bool), theme: Theme) -> Style {
match (is_active, is_hovered) {
(true, _) => Style::default().fg(theme.selected),
(false, true) => Style::default().fg(theme.hovered),
_ => Style::default().fg(theme.inactive),
}
}
pub fn create_artist_string(artists: &[SimplifiedArtist]) -> String {
artists
.iter()
.map(|artist| artist.name.to_string())
.collect::<Vec<String>>()
.join(", ")
}
pub fn millis_to_minutes(millis: u128) -> String {
let minutes = millis / 60000;
let seconds = (millis % 60000) / 1000;
let seconds_display = if seconds < 10 {
format!("0{}", seconds)
} else {
format!("{}", seconds)
};
if seconds == 60 {
format!("{}:00", minutes + 1)
} else {
format!("{}:{}", minutes, seconds_display)
}
}
pub fn display_track_progress(progress: u128, track_duration: u32) -> String {
let duration = millis_to_minutes(u128::from(track_duration));
let progress_display = millis_to_minutes(progress);
let remaining = millis_to_minutes(u128::from(track_duration).saturating_sub(progress));
format!("{}/{} (-{})", progress_display, duration, remaining,)
}
// `percentage` param needs to be between 0 and 1
pub fn get_percentage_width(width: u16, percentage: f32) -> u16 {
let padding = 3;
let width = width - padding;
(f32::from(width) * percentage) as u16
}
// Ensure track progress percentage is between 0 and 100 inclusive
pub fn get_track_progress_percentage(song_progress_ms: u128, track_duration_ms: u32) -> u16 {
let min_perc = 0_f64;
let track_progress = std::cmp::min(song_progress_ms, track_duration_ms.into());
let track_perc = (track_progress as f64 / f64::from(track_duration_ms)) * 100_f64;
min_perc.max(track_perc) as u16
}
// Make better use of space on small terminals
pub fn get_main_layout_margin(app: &App) -> u16 {
if app.size.height > SMALL_TERMINAL_HEIGHT {
1
} else {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn millis_to_minutes_test() {
assert_eq!(millis_to_minutes(0), "0:00");
assert_eq!(millis_to_minutes(1000), "0:01");
assert_eq!(millis_to_minutes(1500), "0:01");
assert_eq!(millis_to_minutes(1900), "0:01");
assert_eq!(millis_to_minutes(60 * 1000), "1:00");
assert_eq!(millis_to_minutes(60 * 1500), "1:30");
}
#[test]
fn display_track_progress_test() {
assert_eq!(
display_track_progress(0, 2 * 60 * 1000),
"0:00/2:00 (-2:00)"
);
assert_eq!(
display_track_progress(60 * 1000, 2 * 60 * 1000),
"1:00/2:00 (-1:00)"
);
}
#[test]
fn get_track_progress_percentage_test() {
let track_length = 60 * 1000;
assert_eq!(get_track_progress_percentage(0, track_length), 0);
assert_eq!(
get_track_progress_percentage((60 * 1000) / 2, track_length),
50
);
// If progress is somehow higher than total duration, 100 should be max
assert_eq!(
get_track_progress_percentage(60 * 1000 * 2, track_length),
100
);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/ui/mod.rs | src/ui/mod.rs | pub mod audio_analysis;
pub mod help;
pub mod util;
use super::{
app::{
ActiveBlock, AlbumTableContext, App, ArtistBlock, EpisodeTableContext, RecommendationsContext,
RouteId, SearchResultBlock, LIBRARY_OPTIONS,
},
banner::BANNER,
};
use help::get_help_docs;
use rspotify::model::show::ResumePoint;
use rspotify::model::PlayingItem;
use rspotify::senum::RepeatState;
use tui::{
backend::Backend,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Span, Spans, Text},
widgets::{Block, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph, Row, Table, Wrap},
Frame,
};
use util::{
create_artist_string, display_track_progress, get_artist_highlight_state, get_color,
get_percentage_width, get_search_results_highlight_state, get_track_progress_percentage,
millis_to_minutes, BASIC_VIEW_HEIGHT, SMALL_TERMINAL_WIDTH,
};
pub enum TableId {
Album,
AlbumList,
Artist,
Podcast,
Song,
RecentlyPlayed,
MadeForYou,
PodcastEpisodes,
}
#[derive(PartialEq)]
pub enum ColumnId {
None,
Title,
Liked,
}
impl Default for ColumnId {
fn default() -> Self {
ColumnId::None
}
}
pub struct TableHeader<'a> {
id: TableId,
items: Vec<TableHeaderItem<'a>>,
}
impl TableHeader<'_> {
pub fn get_index(&self, id: ColumnId) -> Option<usize> {
self.items.iter().position(|item| item.id == id)
}
}
#[derive(Default)]
pub struct TableHeaderItem<'a> {
id: ColumnId,
text: &'a str,
width: u16,
}
pub struct TableItem {
id: String,
format: Vec<String>,
}
pub fn draw_help_menu<B>(f: &mut Frame<B>, app: &App)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(100)].as_ref())
.margin(2)
.split(f.size());
// Create a one-column table to avoid flickering due to non-determinism when
// resolving constraints on widths of table columns.
let format_row =
|r: Vec<String>| -> Vec<String> { vec![format!("{:50}{:40}{:20}", r[0], r[1], r[2])] };
let help_menu_style = Style::default().fg(app.user_config.theme.text);
let header = ["Description", "Event", "Context"];
let header = format_row(header.iter().map(|s| s.to_string()).collect());
let help_docs = get_help_docs(&app.user_config.keys);
let help_docs = help_docs
.into_iter()
.map(format_row)
.collect::<Vec<Vec<String>>>();
let help_docs = &help_docs[app.help_menu_offset as usize..];
let rows = help_docs
.iter()
.map(|item| Row::new(item.clone()).style(help_menu_style));
let help_menu = Table::new(rows)
.header(Row::new(header))
.block(
Block::default()
.borders(Borders::ALL)
.style(help_menu_style)
.title(Span::styled(
"Help (press <Esc> to go back)",
help_menu_style,
))
.border_style(help_menu_style),
)
.style(help_menu_style)
.widths(&[Constraint::Percentage(100)]);
f.render_widget(help_menu, chunks[0]);
}
pub fn draw_input_and_help_box<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
// Check for the width and change the contraints accordingly
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
if app.size.width >= SMALL_TERMINAL_WIDTH && !app.user_config.behavior.enforce_wide_search_bar
{
[Constraint::Percentage(65), Constraint::Percentage(35)].as_ref()
} else {
[Constraint::Percentage(90), Constraint::Percentage(10)].as_ref()
},
)
.split(layout_chunk);
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::Input,
current_route.hovered_block == ActiveBlock::Input,
);
let input_string: String = app.input.iter().collect();
let lines = Text::from((&input_string).as_str());
let input = Paragraph::new(lines).block(
Block::default()
.borders(Borders::ALL)
.title(Span::styled(
"Search",
get_color(highlight_state, app.user_config.theme),
))
.border_style(get_color(highlight_state, app.user_config.theme)),
);
f.render_widget(input, chunks[0]);
let show_loading = app.is_loading && app.user_config.behavior.show_loading_indicator;
let help_block_text = if show_loading {
(app.user_config.theme.hint, "Loading...")
} else {
(app.user_config.theme.inactive, "Type ?")
};
let block = Block::default()
.title(Span::styled("Help", Style::default().fg(help_block_text.0)))
.borders(Borders::ALL)
.border_style(Style::default().fg(help_block_text.0));
let lines = Text::from(help_block_text.1);
let help = Paragraph::new(lines)
.block(block)
.style(Style::default().fg(help_block_text.0));
f.render_widget(help, chunks[1]);
}
pub fn draw_main_layout<B>(f: &mut Frame<B>, app: &App)
where
B: Backend,
{
let margin = util::get_main_layout_margin(app);
// Responsive layout: new one kicks in at width 150 or higher
if app.size.width >= SMALL_TERMINAL_WIDTH && !app.user_config.behavior.enforce_wide_search_bar {
let parent_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1), Constraint::Length(6)].as_ref())
.margin(margin)
.split(f.size());
// Nested main block with potential routes
draw_routes(f, app, parent_layout[0]);
// Currently playing
draw_playbar(f, app, parent_layout[1]);
} else {
let parent_layout = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(3),
Constraint::Min(1),
Constraint::Length(6),
]
.as_ref(),
)
.margin(margin)
.split(f.size());
// Search input and help
draw_input_and_help_box(f, app, parent_layout[0]);
// Nested main block with potential routes
draw_routes(f, app, parent_layout[1]);
// Currently playing
draw_playbar(f, app, parent_layout[2]);
}
// Possibly draw confirm dialog
draw_dialog(f, app);
}
pub fn draw_routes<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(20), Constraint::Percentage(80)].as_ref())
.split(layout_chunk);
draw_user_block(f, app, chunks[0]);
let current_route = app.get_current_route();
match current_route.id {
RouteId::Search => {
draw_search_results(f, app, chunks[1]);
}
RouteId::TrackTable => {
draw_song_table(f, app, chunks[1]);
}
RouteId::AlbumTracks => {
draw_album_table(f, app, chunks[1]);
}
RouteId::RecentlyPlayed => {
draw_recently_played_table(f, app, chunks[1]);
}
RouteId::Artist => {
draw_artist_albums(f, app, chunks[1]);
}
RouteId::AlbumList => {
draw_album_list(f, app, chunks[1]);
}
RouteId::PodcastEpisodes => {
draw_show_episodes(f, app, chunks[1]);
}
RouteId::Home => {
draw_home(f, app, chunks[1]);
}
RouteId::MadeForYou => {
draw_made_for_you(f, app, chunks[1]);
}
RouteId::Artists => {
draw_artist_table(f, app, chunks[1]);
}
RouteId::Podcasts => {
draw_podcast_table(f, app, chunks[1]);
}
RouteId::Recommendations => {
draw_recommendations_table(f, app, chunks[1]);
}
RouteId::Error => {} // This is handled as a "full screen" route in main.rs
RouteId::SelectedDevice => {} // This is handled as a "full screen" route in main.rs
RouteId::Analysis => {} // This is handled as a "full screen" route in main.rs
RouteId::BasicView => {} // This is handled as a "full screen" route in main.rs
RouteId::Dialog => {} // This is handled in the draw_dialog function in mod.rs
};
}
pub fn draw_library_block<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::Library,
current_route.hovered_block == ActiveBlock::Library,
);
draw_selectable_list(
f,
app,
layout_chunk,
"Library",
&LIBRARY_OPTIONS,
highlight_state,
Some(app.library.selected_index),
);
}
pub fn draw_playlist_block<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let playlist_items = match &app.playlists {
Some(p) => p.items.iter().map(|item| item.name.to_owned()).collect(),
None => vec![],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::MyPlaylists,
current_route.hovered_block == ActiveBlock::MyPlaylists,
);
draw_selectable_list(
f,
app,
layout_chunk,
"Playlists",
&playlist_items,
highlight_state,
app.selected_playlist_index,
);
}
pub fn draw_user_block<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
// Check for width to make a responsive layout
if app.size.width >= SMALL_TERMINAL_WIDTH && !app.user_config.behavior.enforce_wide_search_bar {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(3),
Constraint::Percentage(30),
Constraint::Percentage(70),
]
.as_ref(),
)
.split(layout_chunk);
// Search input and help
draw_input_and_help_box(f, app, chunks[0]);
draw_library_block(f, app, chunks[1]);
draw_playlist_block(f, app, chunks[2]);
} else {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(30), Constraint::Percentage(70)].as_ref())
.split(layout_chunk);
// Search input and help
draw_library_block(f, app, chunks[0]);
draw_playlist_block(f, app, chunks[1]);
}
}
pub fn draw_search_results<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Percentage(35),
Constraint::Percentage(35),
Constraint::Percentage(25),
]
.as_ref(),
)
.split(layout_chunk);
{
let song_artist_block = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[0]);
let currently_playing_id = app
.current_playback_context
.clone()
.and_then(|context| {
context.item.and_then(|item| match item {
PlayingItem::Track(track) => track.id,
PlayingItem::Episode(episode) => Some(episode.id),
})
})
.unwrap_or_else(|| "".to_string());
let songs = match &app.search_results.tracks {
Some(tracks) => tracks
.items
.iter()
.map(|item| {
let mut song_name = "".to_string();
let id = item.clone().id.unwrap_or_else(|| "".to_string());
if currently_playing_id == id {
song_name += "▶ "
}
if app.liked_song_ids_set.contains(&id) {
song_name += &app.user_config.padded_liked_icon();
}
song_name += &item.name;
song_name += &format!(" - {}", &create_artist_string(&item.artists));
song_name
})
.collect(),
None => vec![],
};
draw_selectable_list(
f,
app,
song_artist_block[0],
"Songs",
&songs,
get_search_results_highlight_state(app, SearchResultBlock::SongSearch),
app.search_results.selected_tracks_index,
);
let artists = match &app.search_results.artists {
Some(artists) => artists
.items
.iter()
.map(|item| {
let mut artist = String::new();
if app.followed_artist_ids_set.contains(&item.id.to_owned()) {
artist.push_str(&app.user_config.padded_liked_icon());
}
artist.push_str(&item.name.to_owned());
artist
})
.collect(),
None => vec![],
};
draw_selectable_list(
f,
app,
song_artist_block[1],
"Artists",
&artists,
get_search_results_highlight_state(app, SearchResultBlock::ArtistSearch),
app.search_results.selected_artists_index,
);
}
{
let albums_playlist_block = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
.split(chunks[1]);
let albums = match &app.search_results.albums {
Some(albums) => albums
.items
.iter()
.map(|item| {
let mut album_artist = String::new();
if let Some(album_id) = &item.id {
if app.saved_album_ids_set.contains(&album_id.to_owned()) {
album_artist.push_str(&app.user_config.padded_liked_icon());
}
}
album_artist.push_str(&format!(
"{} - {} ({})",
item.name.to_owned(),
create_artist_string(&item.artists),
item.album_type.as_deref().unwrap_or("unknown")
));
album_artist
})
.collect(),
None => vec![],
};
draw_selectable_list(
f,
app,
albums_playlist_block[0],
"Albums",
&albums,
get_search_results_highlight_state(app, SearchResultBlock::AlbumSearch),
app.search_results.selected_album_index,
);
let playlists = match &app.search_results.playlists {
Some(playlists) => playlists
.items
.iter()
.map(|item| item.name.to_owned())
.collect(),
None => vec![],
};
draw_selectable_list(
f,
app,
albums_playlist_block[1],
"Playlists",
&playlists,
get_search_results_highlight_state(app, SearchResultBlock::PlaylistSearch),
app.search_results.selected_playlists_index,
);
}
{
let podcasts_block = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(100)].as_ref())
.split(chunks[2]);
let podcasts = match &app.search_results.shows {
Some(podcasts) => podcasts
.items
.iter()
.map(|item| {
let mut show_name = String::new();
if app.saved_show_ids_set.contains(&item.id.to_owned()) {
show_name.push_str(&app.user_config.padded_liked_icon());
}
show_name.push_str(&format!("{:} - {}", item.name, item.publisher));
show_name
})
.collect(),
None => vec![],
};
draw_selectable_list(
f,
app,
podcasts_block[0],
"Podcasts",
&podcasts,
get_search_results_highlight_state(app, SearchResultBlock::ShowSearch),
app.search_results.selected_shows_index,
);
}
}
struct AlbumUi {
selected_index: usize,
items: Vec<TableItem>,
title: String,
}
pub fn draw_artist_table<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let header = TableHeader {
id: TableId::Artist,
items: vec![TableHeaderItem {
text: "Artist",
width: get_percentage_width(layout_chunk.width, 1.0),
..Default::default()
}],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::Artists,
current_route.hovered_block == ActiveBlock::Artists,
);
let items = app
.artists
.iter()
.map(|item| TableItem {
id: item.id.clone(),
format: vec![item.name.to_owned()],
})
.collect::<Vec<TableItem>>();
draw_table(
f,
app,
layout_chunk,
("Artists", &header),
&items,
app.artists_list_index,
highlight_state,
)
}
pub fn draw_podcast_table<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let header = TableHeader {
id: TableId::Podcast,
items: vec![
TableHeaderItem {
text: "Name",
width: get_percentage_width(layout_chunk.width, 2.0 / 5.0),
..Default::default()
},
TableHeaderItem {
text: "Publisher(s)",
width: get_percentage_width(layout_chunk.width, 2.0 / 5.0),
..Default::default()
},
],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::Podcasts,
current_route.hovered_block == ActiveBlock::Podcasts,
);
if let Some(saved_shows) = app.library.saved_shows.get_results(None) {
let items = saved_shows
.items
.iter()
.map(|show_page| TableItem {
id: show_page.show.id.to_owned(),
format: vec![
show_page.show.name.to_owned(),
show_page.show.publisher.to_owned(),
],
})
.collect::<Vec<TableItem>>();
draw_table(
f,
app,
layout_chunk,
("Podcasts", &header),
&items,
app.shows_list_index,
highlight_state,
)
};
}
pub fn draw_album_table<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let header = TableHeader {
id: TableId::Album,
items: vec![
TableHeaderItem {
id: ColumnId::Liked,
text: "",
width: 2,
},
TableHeaderItem {
text: "#",
width: 3,
..Default::default()
},
TableHeaderItem {
id: ColumnId::Title,
text: "Title",
width: get_percentage_width(layout_chunk.width, 2.0 / 5.0) - 5,
},
TableHeaderItem {
text: "Artist",
width: get_percentage_width(layout_chunk.width, 2.0 / 5.0),
..Default::default()
},
TableHeaderItem {
text: "Length",
width: get_percentage_width(layout_chunk.width, 1.0 / 5.0),
..Default::default()
},
],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::AlbumTracks,
current_route.hovered_block == ActiveBlock::AlbumTracks,
);
let album_ui = match &app.album_table_context {
AlbumTableContext::Simplified => {
app
.selected_album_simplified
.as_ref()
.map(|selected_album_simplified| AlbumUi {
items: selected_album_simplified
.tracks
.items
.iter()
.map(|item| TableItem {
id: item.id.clone().unwrap_or_else(|| "".to_string()),
format: vec![
"".to_string(),
item.track_number.to_string(),
item.name.to_owned(),
create_artist_string(&item.artists),
millis_to_minutes(u128::from(item.duration_ms)),
],
})
.collect::<Vec<TableItem>>(),
title: format!(
"{} by {}",
selected_album_simplified.album.name,
create_artist_string(&selected_album_simplified.album.artists)
),
selected_index: selected_album_simplified.selected_index,
})
}
AlbumTableContext::Full => match app.selected_album_full.clone() {
Some(selected_album) => Some(AlbumUi {
items: selected_album
.album
.tracks
.items
.iter()
.map(|item| TableItem {
id: item.id.clone().unwrap_or_else(|| "".to_string()),
format: vec![
"".to_string(),
item.track_number.to_string(),
item.name.to_owned(),
create_artist_string(&item.artists),
millis_to_minutes(u128::from(item.duration_ms)),
],
})
.collect::<Vec<TableItem>>(),
title: format!(
"{} by {}",
selected_album.album.name,
create_artist_string(&selected_album.album.artists)
),
selected_index: app.saved_album_tracks_index,
}),
None => None,
},
};
if let Some(album_ui) = album_ui {
draw_table(
f,
app,
layout_chunk,
(&album_ui.title, &header),
&album_ui.items,
album_ui.selected_index,
highlight_state,
);
};
}
pub fn draw_recommendations_table<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let header = TableHeader {
id: TableId::Song,
items: vec![
TableHeaderItem {
id: ColumnId::Liked,
text: "",
width: 2,
},
TableHeaderItem {
id: ColumnId::Title,
text: "Title",
width: get_percentage_width(layout_chunk.width, 0.3),
},
TableHeaderItem {
text: "Artist",
width: get_percentage_width(layout_chunk.width, 0.3),
..Default::default()
},
TableHeaderItem {
text: "Album",
width: get_percentage_width(layout_chunk.width, 0.3),
..Default::default()
},
TableHeaderItem {
text: "Length",
width: get_percentage_width(layout_chunk.width, 0.1),
..Default::default()
},
],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::TrackTable,
current_route.hovered_block == ActiveBlock::TrackTable,
);
let items = app
.track_table
.tracks
.iter()
.map(|item| TableItem {
id: item.id.clone().unwrap_or_else(|| "".to_string()),
format: vec![
"".to_string(),
item.name.to_owned(),
create_artist_string(&item.artists),
item.album.name.to_owned(),
millis_to_minutes(u128::from(item.duration_ms)),
],
})
.collect::<Vec<TableItem>>();
// match RecommendedContext
let recommendations_ui = match &app.recommendations_context {
Some(RecommendationsContext::Song) => format!(
"Recommendations based on Song \'{}\'",
&app.recommendations_seed
),
Some(RecommendationsContext::Artist) => format!(
"Recommendations based on Artist \'{}\'",
&app.recommendations_seed
),
None => "Recommendations".to_string(),
};
draw_table(
f,
app,
layout_chunk,
(&recommendations_ui[..], &header),
&items,
app.track_table.selected_index,
highlight_state,
)
}
pub fn draw_song_table<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let header = TableHeader {
id: TableId::Song,
items: vec![
TableHeaderItem {
id: ColumnId::Liked,
text: "",
width: 2,
},
TableHeaderItem {
id: ColumnId::Title,
text: "Title",
width: get_percentage_width(layout_chunk.width, 0.3),
},
TableHeaderItem {
text: "Artist",
width: get_percentage_width(layout_chunk.width, 0.3),
..Default::default()
},
TableHeaderItem {
text: "Album",
width: get_percentage_width(layout_chunk.width, 0.3),
..Default::default()
},
TableHeaderItem {
text: "Length",
width: get_percentage_width(layout_chunk.width, 0.1),
..Default::default()
},
],
};
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::TrackTable,
current_route.hovered_block == ActiveBlock::TrackTable,
);
let items = app
.track_table
.tracks
.iter()
.map(|item| TableItem {
id: item.id.clone().unwrap_or_else(|| "".to_string()),
format: vec![
"".to_string(),
item.name.to_owned(),
create_artist_string(&item.artists),
item.album.name.to_owned(),
millis_to_minutes(u128::from(item.duration_ms)),
],
})
.collect::<Vec<TableItem>>();
draw_table(
f,
app,
layout_chunk,
("Songs", &header),
&items,
app.track_table.selected_index,
highlight_state,
)
}
pub fn draw_basic_view<B>(f: &mut Frame<B>, app: &App)
where
B: Backend,
{
// If space is negative, do nothing because the widget would not fit
if let Some(s) = app.size.height.checked_sub(BASIC_VIEW_HEIGHT) {
let space = s / 2;
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(space),
Constraint::Length(BASIC_VIEW_HEIGHT),
Constraint::Length(space),
]
.as_ref(),
)
.split(f.size());
draw_playbar(f, app, chunks[1]);
}
}
pub fn draw_playbar<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Percentage(50),
Constraint::Percentage(25),
Constraint::Percentage(25),
]
.as_ref(),
)
.margin(1)
.split(layout_chunk);
// If no track is playing, render paragraph showing which device is selected, if no selected
// give hint to choose a device
if let Some(current_playback_context) = &app.current_playback_context {
if let Some(track_item) = ¤t_playback_context.item {
let play_title = if current_playback_context.is_playing {
"Playing"
} else {
"Paused"
};
let shuffle_text = if current_playback_context.shuffle_state {
"On"
} else {
"Off"
};
let repeat_text = match current_playback_context.repeat_state {
RepeatState::Off => "Off",
RepeatState::Track => "Track",
RepeatState::Context => "All",
};
let title = format!(
"{:-7} ({} | Shuffle: {:-3} | Repeat: {:-5} | Volume: {:-2}%)",
play_title,
current_playback_context.device.name,
shuffle_text,
repeat_text,
current_playback_context.device.volume_percent
);
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::PlayBar,
current_route.hovered_block == ActiveBlock::PlayBar,
);
let title_block = Block::default()
.borders(Borders::ALL)
.title(Span::styled(
&title,
get_color(highlight_state, app.user_config.theme),
))
.border_style(get_color(highlight_state, app.user_config.theme));
f.render_widget(title_block, layout_chunk);
let (item_id, name, duration_ms) = match track_item {
PlayingItem::Track(track) => (
track.id.to_owned().unwrap_or_else(|| "".to_string()),
track.name.to_owned(),
track.duration_ms,
),
PlayingItem::Episode(episode) => (
episode.id.to_owned(),
episode.name.to_owned(),
episode.duration_ms,
),
};
let track_name = if app.liked_song_ids_set.contains(&item_id) {
format!("{}{}", &app.user_config.padded_liked_icon(), name)
} else {
name
};
let play_bar_text = match track_item {
PlayingItem::Track(track) => create_artist_string(&track.artists),
PlayingItem::Episode(episode) => format!("{} - {}", episode.name, episode.show.name),
};
let lines = Text::from(Span::styled(
play_bar_text,
Style::default().fg(app.user_config.theme.playbar_text),
));
let artist = Paragraph::new(lines)
.style(Style::default().fg(app.user_config.theme.playbar_text))
.block(
Block::default().title(Span::styled(
&track_name,
Style::default()
.fg(app.user_config.theme.selected)
.add_modifier(Modifier::BOLD),
)),
);
f.render_widget(artist, chunks[0]);
let progress_ms = match app.seek_ms {
Some(seek_ms) => seek_ms,
None => app.song_progress_ms,
};
let perc = get_track_progress_percentage(progress_ms, duration_ms);
let song_progress_label = display_track_progress(progress_ms, duration_ms);
let modifier = if app.user_config.behavior.enable_text_emphasis {
Modifier::ITALIC | Modifier::BOLD
} else {
Modifier::empty()
};
let song_progress = Gauge::default()
.gauge_style(
Style::default()
.fg(app.user_config.theme.playbar_progress)
.bg(app.user_config.theme.playbar_background)
.add_modifier(modifier),
)
.percent(perc)
.label(Span::styled(
&song_progress_label,
Style::default().fg(app.user_config.theme.playbar_progress_text),
));
f.render_widget(song_progress, chunks[2]);
}
}
}
pub fn draw_error_screen<B>(f: &mut Frame<B>, app: &App)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(100)].as_ref())
.margin(5)
.split(f.size());
let playing_text = vec![
Spans::from(vec![
Span::raw("Api response: "),
Span::styled(
&app.api_error,
Style::default().fg(app.user_config.theme.error_text),
),
]),
Spans::from(Span::styled(
"If you are trying to play a track, please check that",
Style::default().fg(app.user_config.theme.text),
)),
Spans::from(Span::styled(
" 1. You have a Spotify Premium Account",
Style::default().fg(app.user_config.theme.text),
)),
Spans::from(Span::styled(
" 2. Your playback device is active and selected - press `d` to go to device selection menu",
Style::default().fg(app.user_config.theme.text),
)),
Spans::from(Span::styled(
" 3. If you're using spotifyd as a playback device, your device name must not contain spaces",
Style::default().fg(app.user_config.theme.text),
)),
Spans::from(Span::styled("Hint: a playback device must be either an official spotify client or a light weight alternative such as spotifyd",
Style::default().fg(app.user_config.theme.hint)
),
),
Spans::from(
Span::styled(
"\nPress <Esc> to return",
Style::default().fg(app.user_config.theme.inactive),
),
)
];
let playing_paragraph = Paragraph::new(playing_text)
.wrap(Wrap { trim: true })
.style(Style::default().fg(app.user_config.theme.text))
.block(
Block::default()
.borders(Borders::ALL)
.title(Span::styled(
"Error",
Style::default().fg(app.user_config.theme.error_border),
))
.border_style(Style::default().fg(app.user_config.theme.error_border)),
);
f.render_widget(playing_paragraph, chunks[0]);
}
fn draw_home<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(7), Constraint::Length(93)].as_ref())
.margin(2)
.split(layout_chunk);
let current_route = app.get_current_route();
let highlight_state = (
current_route.active_block == ActiveBlock::Home,
current_route.hovered_block == ActiveBlock::Home,
);
let welcome = Block::default()
.title(Span::styled(
"Welcome!",
get_color(highlight_state, app.user_config.theme),
))
.borders(Borders::ALL)
.border_style(get_color(highlight_state, app.user_config.theme));
f.render_widget(welcome, layout_chunk);
let changelog = include_str!("../../CHANGELOG.md").to_string();
// If debug mode show the "Unreleased" header. Otherwise it is a release so there should be no
// unreleased features
let clean_changelog = if cfg!(debug_assertions) {
changelog
} else {
changelog.replace("\n## [Unreleased]\n", "")
};
// Banner text with correct styling
let mut top_text = Text::from(BANNER);
top_text.patch_style(Style::default().fg(app.user_config.theme.banner));
let bottom_text_raw = format!(
"{}{}",
"\nPlease report any bugs or missing features to https://github.com/Rigellute/spotify-tui\n\n",
clean_changelog
);
let bottom_text = Text::from(bottom_text_raw.as_str());
// Contains the banner
let top_text = Paragraph::new(top_text)
.style(Style::default().fg(app.user_config.theme.text))
.block(Block::default());
f.render_widget(top_text, chunks[0]);
// CHANGELOG
let bottom_text = Paragraph::new(bottom_text)
.style(Style::default().fg(app.user_config.theme.text))
.block(Block::default())
.wrap(Wrap { trim: false })
.scroll((app.home_scroll, 0));
f.render_widget(bottom_text, chunks[1]);
}
fn draw_artist_albums<B>(f: &mut Frame<B>, app: &App, layout_chunk: Rect)
where
B: Backend,
{
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | true |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/build.rs | build.rs | use chrono::TimeZone;
fn get_git_hash() -> String {
use std::process::Command;
// Allow builds from `git archive` generated tarballs if output of `git get-tar-commit-id` is
// set in an env var.
if let Ok(commit) = std::env::var("BUILD_GIT_COMMIT_ID") {
return commit[..7].to_string();
};
let commit = Command::new("git")
.arg("rev-parse")
.arg("--short=7")
.arg("--verify")
.arg("HEAD")
.output();
if let Ok(commit_output) = commit {
let commit_string =
String::from_utf8_lossy(&commit_output.stdout);
return commit_string.lines().next().unwrap_or("").into();
}
panic!("Can not get git commit: {}", commit.unwrap_err());
}
fn main() {
let now = match std::env::var("SOURCE_DATE_EPOCH") {
Ok(val) => chrono::Local
.timestamp_opt(val.parse::<i64>().unwrap(), 0)
.unwrap(),
Err(_) => chrono::Local::now(),
};
let build_date = now.date_naive();
let build_name = if std::env::var("GITUI_RELEASE").is_ok() {
format!(
"{} {} ({})",
env!("CARGO_PKG_VERSION"),
build_date,
get_git_hash()
)
} else {
format!("nightly {} ({})", build_date, get_git_hash())
};
println!("cargo:warning=buildname '{build_name}'");
println!("cargo:rustc-env=GITUI_BUILD_NAME={build_name}");
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/scopetime/src/lib.rs | scopetime/src/lib.rs | //! simple macro to insert a scope based runtime measure that logs the result
#![forbid(unsafe_code)]
#![deny(mismatched_lifetime_syntaxes, unused_imports)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::perf)]
use std::time::Instant;
pub struct ScopeTimeLog<'a> {
title: &'a str,
mod_path: &'a str,
file: &'a str,
line: u32,
time: Instant,
}
impl<'a> ScopeTimeLog<'a> {
pub fn new(
mod_path: &'a str,
title: &'a str,
file: &'a str,
line: u32,
) -> Self {
Self {
title,
mod_path,
file,
line,
time: Instant::now(),
}
}
}
impl Drop for ScopeTimeLog<'_> {
fn drop(&mut self) {
log::trace!(
"scopetime: {:?} ms [{}::{}] @{}:{}",
self.time.elapsed().as_millis(),
self.mod_path,
self.title,
self.file,
self.line,
);
}
}
/// measures runtime of scope and prints it into log
#[cfg(feature = "enabled")]
#[macro_export]
macro_rules! scope_time {
($target:literal) => {
#[allow(unused_variables)]
let time = $crate::ScopeTimeLog::new(
module_path!(),
$target,
file!(),
line!(),
);
};
}
#[doc(hidden)]
#[cfg(not(feature = "enabled"))]
#[macro_export]
macro_rules! scope_time {
($target:literal) => {};
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/git2-testing/src/lib.rs | git2-testing/src/lib.rs | #![deny(mismatched_lifetime_syntaxes)]
use git2::Repository;
use tempfile::TempDir;
/// initialize test repo in temp path
pub fn repo_init_empty() -> (TempDir, Repository) {
init_log();
sandbox_config_files();
let td = TempDir::new().unwrap();
let repo = Repository::init(td.path()).unwrap();
{
let mut config = repo.config().unwrap();
config.set_str("user.name", "name").unwrap();
config.set_str("user.email", "email").unwrap();
}
(td, repo)
}
/// initialize test repo in temp path with an empty first commit
pub fn repo_init() -> (TempDir, Repository) {
init_log();
sandbox_config_files();
let td = TempDir::new().unwrap();
let repo = Repository::init(td.path()).unwrap();
{
let mut config = repo.config().unwrap();
config.set_str("user.name", "name").unwrap();
config.set_str("user.email", "email").unwrap();
let mut index = repo.index().unwrap();
let id = index.write_tree().unwrap();
let tree = repo.find_tree(id).unwrap();
let sig = repo.signature().unwrap();
repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
.unwrap();
}
(td, repo)
}
// init log
fn init_log() {
let _ = env_logger::builder()
.is_test(true)
.filter_level(log::LevelFilter::Trace)
.try_init();
}
/// Same as `repo_init`, but the repo is a bare repo (--bare)
pub fn repo_init_bare() -> (TempDir, Repository) {
init_log();
let tmp_repo_dir = TempDir::new().unwrap();
let bare_repo =
Repository::init_bare(tmp_repo_dir.path()).unwrap();
(tmp_repo_dir, bare_repo)
}
/// Calling `set_search_path` with an empty directory makes sure that there
/// is no git config interfering with our tests (for example user-local
/// `.gitconfig`).
#[allow(unsafe_code)]
fn sandbox_config_files() {
use git2::{opts::set_search_path, ConfigLevel};
use std::sync::Once;
static INIT: Once = Once::new();
// Adapted from https://github.com/rust-lang/cargo/pull/9035
INIT.call_once(|| unsafe {
let temp_dir = TempDir::new().unwrap();
let path = temp_dir.path();
set_search_path(ConfigLevel::System, path).unwrap();
set_search_path(ConfigLevel::Global, path).unwrap();
set_search_path(ConfigLevel::XDG, path).unwrap();
set_search_path(ConfigLevel::ProgramData, path).unwrap();
});
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/git2-hooks/src/lib.rs | git2-hooks/src/lib.rs | //! git2-rs addon supporting git hooks
//!
//! we look for hooks in the following locations:
//! * whatever `config.hooksPath` points to
//! * `.git/hooks/`
//! * whatever list of paths provided as `other_paths` (in order)
//!
//! most basic hook is: [`hooks_pre_commit`]. see also other `hooks_*` functions.
//!
//! [`create_hook`] is useful to create git hooks from code (unittest make heavy usage of it)
#![forbid(unsafe_code)]
#![deny(
mismatched_lifetime_syntaxes,
unused_imports,
unused_must_use,
dead_code,
unstable_name_collisions,
unused_assignments
)]
#![deny(clippy::all, clippy::perf, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::missing_errors_doc,
clippy::must_use_candidate,
clippy::module_name_repetitions
)]
mod error;
mod hookspath;
use std::{
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
};
pub use error::HooksError;
use error::Result;
use hookspath::HookPaths;
use git2::Repository;
pub const HOOK_POST_COMMIT: &str = "post-commit";
pub const HOOK_PRE_COMMIT: &str = "pre-commit";
pub const HOOK_COMMIT_MSG: &str = "commit-msg";
pub const HOOK_PREPARE_COMMIT_MSG: &str = "prepare-commit-msg";
pub const HOOK_PRE_PUSH: &str = "pre-push";
const HOOK_COMMIT_MSG_TEMP_FILE: &str = "COMMIT_EDITMSG";
#[derive(Debug, PartialEq, Eq)]
pub enum HookResult {
/// No hook found
NoHookFound,
/// Hook executed with non error return code
Ok {
/// path of the hook that was run
hook: PathBuf,
},
/// Hook executed and returned an error code
RunNotSuccessful {
/// exit code as reported back from process calling the hook
code: Option<i32>,
/// stderr output emitted by hook
stdout: String,
/// stderr output emitted by hook
stderr: String,
/// path of the hook that was run
hook: PathBuf,
},
}
impl HookResult {
/// helper to check if result is ok
pub const fn is_ok(&self) -> bool {
matches!(self, Self::Ok { .. })
}
/// helper to check if result was run and not rejected
pub const fn is_not_successful(&self) -> bool {
matches!(self, Self::RunNotSuccessful { .. })
}
}
/// helper method to create git hooks programmatically (heavy used in unittests)
///
/// # Panics
/// Panics if hook could not be created
pub fn create_hook(
r: &Repository,
hook: &str,
hook_script: &[u8],
) -> PathBuf {
let hook = HookPaths::new(r, None, hook).unwrap();
let path = hook.hook.clone();
create_hook_in_path(&hook.hook, hook_script);
path
}
fn create_hook_in_path(path: &Path, hook_script: &[u8]) {
File::create(path).unwrap().write_all(hook_script).unwrap();
#[cfg(unix)]
{
std::process::Command::new("chmod")
.arg("+x")
.arg(path)
// .current_dir(path)
.output()
.unwrap();
}
}
/// Git hook: `commit_msg`
///
/// This hook is documented here <https://git-scm.com/docs/githooks#_commit_msg>.
/// We use the same convention as other git clients to create a temp file containing
/// the commit message at `<.git|hooksPath>/COMMIT_EDITMSG` and pass it's relative path as the only
/// parameter to the hook script.
pub fn hooks_commit_msg(
repo: &Repository,
other_paths: Option<&[&str]>,
msg: &mut String,
) -> Result<HookResult> {
let hook = HookPaths::new(repo, other_paths, HOOK_COMMIT_MSG)?;
if !hook.found() {
return Ok(HookResult::NoHookFound);
}
let temp_file = hook.git.join(HOOK_COMMIT_MSG_TEMP_FILE);
File::create(&temp_file)?.write_all(msg.as_bytes())?;
let res = hook.run_hook_os_str([&temp_file])?;
// load possibly altered msg
msg.clear();
File::open(temp_file)?.read_to_string(msg)?;
Ok(res)
}
/// this hook is documented here <https://git-scm.com/docs/githooks#_pre_commit>
pub fn hooks_pre_commit(
repo: &Repository,
other_paths: Option<&[&str]>,
) -> Result<HookResult> {
let hook = HookPaths::new(repo, other_paths, HOOK_PRE_COMMIT)?;
if !hook.found() {
return Ok(HookResult::NoHookFound);
}
hook.run_hook(&[])
}
/// this hook is documented here <https://git-scm.com/docs/githooks#_post_commit>
pub fn hooks_post_commit(
repo: &Repository,
other_paths: Option<&[&str]>,
) -> Result<HookResult> {
let hook = HookPaths::new(repo, other_paths, HOOK_POST_COMMIT)?;
if !hook.found() {
return Ok(HookResult::NoHookFound);
}
hook.run_hook(&[])
}
/// this hook is documented here <https://git-scm.com/docs/githooks#_pre_push>
pub fn hooks_pre_push(
repo: &Repository,
other_paths: Option<&[&str]>,
) -> Result<HookResult> {
let hook = HookPaths::new(repo, other_paths, HOOK_PRE_PUSH)?;
if !hook.found() {
return Ok(HookResult::NoHookFound);
}
hook.run_hook(&[])
}
pub enum PrepareCommitMsgSource {
Message,
Template,
Merge,
Squash,
Commit(git2::Oid),
}
/// this hook is documented here <https://git-scm.com/docs/githooks#_prepare_commit_msg>
#[allow(clippy::needless_pass_by_value)]
pub fn hooks_prepare_commit_msg(
repo: &Repository,
other_paths: Option<&[&str]>,
source: PrepareCommitMsgSource,
msg: &mut String,
) -> Result<HookResult> {
let hook =
HookPaths::new(repo, other_paths, HOOK_PREPARE_COMMIT_MSG)?;
if !hook.found() {
return Ok(HookResult::NoHookFound);
}
let temp_file = hook.git.join(HOOK_COMMIT_MSG_TEMP_FILE);
File::create(&temp_file)?.write_all(msg.as_bytes())?;
let temp_file_path = temp_file.as_os_str().to_string_lossy();
let vec = vec![
temp_file_path.as_ref(),
match source {
PrepareCommitMsgSource::Message => "message",
PrepareCommitMsgSource::Template => "template",
PrepareCommitMsgSource::Merge => "merge",
PrepareCommitMsgSource::Squash => "squash",
PrepareCommitMsgSource::Commit(_) => "commit",
},
];
let mut args = vec;
let id = if let PrepareCommitMsgSource::Commit(id) = &source {
Some(id.to_string())
} else {
None
};
if let Some(id) = &id {
args.push(id);
}
let res = hook.run_hook(args.as_slice())?;
// load possibly altered msg
msg.clear();
File::open(temp_file)?.read_to_string(msg)?;
Ok(res)
}
#[cfg(test)]
mod tests {
use super::*;
use git2_testing::{repo_init, repo_init_bare};
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn test_smoke() {
let (_td, repo) = repo_init();
let mut msg = String::from("test");
let res = hooks_commit_msg(&repo, None, &mut msg).unwrap();
assert_eq!(res, HookResult::NoHookFound);
let hook = b"#!/bin/sh
exit 0
";
create_hook(&repo, HOOK_POST_COMMIT, hook);
let res = hooks_post_commit(&repo, None).unwrap();
assert!(res.is_ok());
}
#[test]
fn test_hooks_commit_msg_ok() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
exit 0
";
create_hook(&repo, HOOK_COMMIT_MSG, hook);
let mut msg = String::from("test");
let res = hooks_commit_msg(&repo, None, &mut msg).unwrap();
assert!(res.is_ok());
assert_eq!(msg, String::from("test"));
}
#[test]
fn test_hooks_commit_msg_with_shell_command_ok() {
let (_td, repo) = repo_init();
let hook = br#"#!/bin/sh
COMMIT_MSG="$(cat "$1")"
printf "$COMMIT_MSG" | sed 's/sth/shell_command/g' > "$1"
exit 0
"#;
create_hook(&repo, HOOK_COMMIT_MSG, hook);
let mut msg = String::from("test_sth");
let res = hooks_commit_msg(&repo, None, &mut msg).unwrap();
assert!(res.is_ok());
assert_eq!(msg, String::from("test_shell_command"));
}
#[test]
fn test_pre_commit_sh() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
exit 0
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
assert!(res.is_ok());
}
#[test]
fn test_hook_with_missing_shebang() {
const TEXT: &str = "Hello, world!";
let (_td, repo) = repo_init();
let hook = b"echo \"$@\"\nexit 42";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let hook =
HookPaths::new(&repo, None, HOOK_PRE_COMMIT).unwrap();
assert!(hook.found());
let result = hook.run_hook(&[TEXT]).unwrap();
let HookResult::RunNotSuccessful {
code,
stdout,
stderr,
hook: h,
} = result
else {
unreachable!("run_hook should've failed");
};
let stdout = stdout.as_str().trim_ascii_end();
assert_eq!(code, Some(42));
assert_eq!(h, hook.hook);
assert_eq!(stdout, TEXT, "{:?} != {TEXT:?}", stdout);
assert!(stderr.is_empty());
}
#[test]
fn test_no_hook_found() {
let (_td, repo) = repo_init();
let res = hooks_pre_commit(&repo, None).unwrap();
assert_eq!(res, HookResult::NoHookFound);
}
#[test]
fn test_other_path() {
let (td, repo) = repo_init();
let hook = b"#!/bin/sh
exit 0
";
let custom_hooks_path = td.path().join(".myhooks");
std::fs::create_dir(dbg!(&custom_hooks_path)).unwrap();
create_hook_in_path(
dbg!(custom_hooks_path.join(HOOK_PRE_COMMIT).as_path()),
hook,
);
let res =
hooks_pre_commit(&repo, Some(&["../.myhooks"])).unwrap();
assert!(res.is_ok());
}
#[test]
fn test_other_path_precedence() {
let (td, repo) = repo_init();
{
let hook = b"#!/bin/sh
exit 0
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
}
{
let reject_hook = b"#!/bin/sh
exit 1
";
let custom_hooks_path = td.path().join(".myhooks");
std::fs::create_dir(dbg!(&custom_hooks_path)).unwrap();
create_hook_in_path(
dbg!(custom_hooks_path
.join(HOOK_PRE_COMMIT)
.as_path()),
reject_hook,
);
}
let res =
hooks_pre_commit(&repo, Some(&["../.myhooks"])).unwrap();
assert!(res.is_ok());
}
#[test]
fn test_pre_commit_fail_sh() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo 'rejected'
exit 1
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
assert!(res.is_not_successful());
}
#[test]
fn test_env_containing_path() {
const PATH_EXPORT: &str = "export PATH";
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
export
exit 1
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
let HookResult::RunNotSuccessful { stdout, .. } = res else {
unreachable!()
};
assert!(
stdout
.lines()
.any(|line| line.starts_with(PATH_EXPORT)),
"Could not find line starting with {PATH_EXPORT:?} in: {stdout:?}"
);
}
#[test]
fn test_pre_commit_fail_hookspath() {
let (_td, repo) = repo_init();
let hooks = TempDir::new().unwrap();
let hook = b"#!/bin/sh
echo 'rejected'
exit 1
";
create_hook_in_path(&hooks.path().join("pre-commit"), hook);
repo.config()
.unwrap()
.set_str(
"core.hooksPath",
hooks.path().as_os_str().to_str().unwrap(),
)
.unwrap();
let res = hooks_pre_commit(&repo, None).unwrap();
let HookResult::RunNotSuccessful { code, stdout, .. } = res
else {
unreachable!()
};
assert_eq!(code.unwrap(), 1);
assert_eq!(&stdout, "rejected\n");
}
#[test]
fn test_pre_commit_fail_bare() {
let (_td, repo) = repo_init_bare();
let hook = b"#!/bin/sh
echo 'rejected'
exit 1
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
assert!(res.is_not_successful());
}
#[test]
fn test_pre_commit_py() {
let (_td, repo) = repo_init();
// mirror how python pre-commit sets itself up
#[cfg(not(windows))]
let hook = b"#!/usr/bin/env python
import sys
sys.exit(0)
";
#[cfg(windows)]
let hook = b"#!/bin/env python.exe
import sys
sys.exit(0)
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
assert!(res.is_ok(), "{res:?}");
}
#[test]
fn test_pre_commit_fail_py() {
let (_td, repo) = repo_init();
// mirror how python pre-commit sets itself up
#[cfg(not(windows))]
let hook = b"#!/usr/bin/env python
import sys
sys.exit(1)
";
#[cfg(windows)]
let hook = b"#!/bin/env python.exe
import sys
sys.exit(1)
";
create_hook(&repo, HOOK_PRE_COMMIT, hook);
let res = hooks_pre_commit(&repo, None).unwrap();
assert!(res.is_not_successful());
}
#[test]
fn test_hooks_commit_msg_reject() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo 'msg' > \"$1\"
echo 'rejected'
exit 1
";
create_hook(&repo, HOOK_COMMIT_MSG, hook);
let mut msg = String::from("test");
let res = hooks_commit_msg(&repo, None, &mut msg).unwrap();
let HookResult::RunNotSuccessful { code, stdout, .. } = res
else {
unreachable!()
};
assert_eq!(code.unwrap(), 1);
assert_eq!(&stdout, "rejected\n");
assert_eq!(msg, String::from("msg\n"));
}
#[test]
fn test_commit_msg_no_block_but_alter() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo 'msg' > \"$1\"
exit 0
";
create_hook(&repo, HOOK_COMMIT_MSG, hook);
let mut msg = String::from("test");
let res = hooks_commit_msg(&repo, None, &mut msg).unwrap();
assert!(res.is_ok());
assert_eq!(msg, String::from("msg\n"));
}
#[test]
fn test_hook_pwd_in_bare_without_workdir() {
let (_td, repo) = repo_init_bare();
let git_root = repo.path().to_path_buf();
let hook =
HookPaths::new(&repo, None, HOOK_POST_COMMIT).unwrap();
assert_eq!(hook.pwd, git_root);
}
#[test]
fn test_hook_pwd() {
let (_td, repo) = repo_init();
let git_root = repo.path().to_path_buf();
let hook =
HookPaths::new(&repo, None, HOOK_POST_COMMIT).unwrap();
assert_eq!(hook.pwd, git_root.parent().unwrap());
}
#[test]
fn test_hooks_prep_commit_msg_success() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo \"msg:$2\" > \"$1\"
exit 0
";
create_hook(&repo, HOOK_PREPARE_COMMIT_MSG, hook);
let mut msg = String::from("test");
let res = hooks_prepare_commit_msg(
&repo,
None,
PrepareCommitMsgSource::Message,
&mut msg,
)
.unwrap();
assert!(matches!(res, HookResult::Ok { .. }));
assert_eq!(msg, String::from("msg:message\n"));
}
#[test]
fn test_hooks_prep_commit_msg_reject() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo \"$2,$3\" > \"$1\"
echo 'rejected'
exit 2
";
create_hook(&repo, HOOK_PREPARE_COMMIT_MSG, hook);
let mut msg = String::from("test");
let res = hooks_prepare_commit_msg(
&repo,
None,
PrepareCommitMsgSource::Commit(git2::Oid::zero()),
&mut msg,
)
.unwrap();
let HookResult::RunNotSuccessful { code, stdout, .. } = res
else {
unreachable!()
};
assert_eq!(code.unwrap(), 2);
assert_eq!(&stdout, "rejected\n");
assert_eq!(
msg,
String::from(
"commit,0000000000000000000000000000000000000000\n"
)
);
}
#[test]
fn test_pre_push_sh() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
exit 0
";
create_hook(&repo, HOOK_PRE_PUSH, hook);
let res = hooks_pre_push(&repo, None).unwrap();
assert!(matches!(res, HookResult::Ok { .. }));
}
#[test]
fn test_pre_push_fail_sh() {
let (_td, repo) = repo_init();
let hook = b"#!/bin/sh
echo 'failed'
exit 3
";
create_hook(&repo, HOOK_PRE_PUSH, hook);
let res = hooks_pre_push(&repo, None).unwrap();
let HookResult::RunNotSuccessful { code, stdout, .. } = res
else {
unreachable!()
};
assert_eq!(code.unwrap(), 3);
assert_eq!(&stdout, "failed\n");
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/git2-hooks/src/error.rs | git2-hooks/src/error.rs | use thiserror::Error;
/// crate specific error type
#[derive(Error, Debug)]
pub enum HooksError {
#[error("git error:{0}")]
Git(#[from] git2::Error),
#[error("io error:{0}")]
Io(#[from] std::io::Error),
#[error("path string conversion error")]
PathToString,
#[error("shellexpand error:{0}")]
ShellExpand(#[from] shellexpand::LookupError<std::env::VarError>),
}
/// crate specific `Result` type
pub type Result<T> = std::result::Result<T, HooksError>;
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/git2-hooks/src/hookspath.rs | git2-hooks/src/hookspath.rs | use git2::Repository;
use crate::{error::Result, HookResult, HooksError};
use std::{
ffi::{OsStr, OsString},
path::{Path, PathBuf},
process::Command,
str::FromStr,
};
pub struct HookPaths {
pub git: PathBuf,
pub hook: PathBuf,
pub pwd: PathBuf,
}
const CONFIG_HOOKS_PATH: &str = "core.hooksPath";
const DEFAULT_HOOKS_PATH: &str = "hooks";
const ENOEXEC: i32 = 8;
impl HookPaths {
/// `core.hooksPath` always takes precedence.
/// If its defined and there is no hook `hook` this is not considered
/// an error or a reason to search in other paths.
/// If the config is not set we go into search mode and
/// first check standard `.git/hooks` folder and any sub path provided in `other_paths`.
///
/// Note: we try to model as closely as possible what git shell is doing.
pub fn new(
repo: &Repository,
other_paths: Option<&[&str]>,
hook: &str,
) -> Result<Self> {
let pwd = repo
.workdir()
.unwrap_or_else(|| repo.path())
.to_path_buf();
let git_dir = repo.path().to_path_buf();
if let Some(config_path) = Self::config_hook_path(repo)? {
let hooks_path = PathBuf::from(config_path);
let hook =
Self::expand_path(&hooks_path.join(hook), &pwd)?;
return Ok(Self {
git: git_dir,
hook,
pwd,
});
}
Ok(Self {
git: git_dir,
hook: Self::find_hook(repo, other_paths, hook),
pwd,
})
}
/// Expand path according to the rule of githooks and config
/// core.hooksPath
fn expand_path(path: &Path, pwd: &Path) -> Result<PathBuf> {
let hook_expanded = shellexpand::full(
path.as_os_str()
.to_str()
.ok_or(HooksError::PathToString)?,
)?;
let hook_expanded = PathBuf::from_str(hook_expanded.as_ref())
.map_err(|_| HooksError::PathToString)?;
// `man git-config`:
//
// > A relative path is taken as relative to the
// > directory where the hooks are run (see the
// > "DESCRIPTION" section of githooks[5]).
//
// `man githooks`:
//
// > Before Git invokes a hook, it changes its
// > working directory to either $GIT_DIR in a bare
// > repository or the root of the working tree in a
// > non-bare repository.
//
// I.e. relative paths in core.hooksPath in non-bare
// repositories are always relative to GIT_WORK_TREE.
Ok({
if hook_expanded.is_absolute() {
hook_expanded
} else {
pwd.join(hook_expanded)
}
})
}
fn config_hook_path(repo: &Repository) -> Result<Option<String>> {
Ok(repo.config()?.get_string(CONFIG_HOOKS_PATH).ok())
}
/// check default hook path first and then followed by `other_paths`.
/// if no hook is found we return the default hook path
fn find_hook(
repo: &Repository,
other_paths: Option<&[&str]>,
hook: &str,
) -> PathBuf {
let mut paths = vec![DEFAULT_HOOKS_PATH.to_string()];
if let Some(others) = other_paths {
paths.extend(
others
.iter()
.map(|p| p.trim_end_matches('/').to_string()),
);
}
for p in paths {
let p = repo.path().to_path_buf().join(p).join(hook);
if p.exists() {
return p;
}
}
repo.path()
.to_path_buf()
.join(DEFAULT_HOOKS_PATH)
.join(hook)
}
/// was a hook file found and is it executable
pub fn found(&self) -> bool {
self.hook.exists() && is_executable(&self.hook)
}
/// this function calls hook scripts based on conventions documented here
/// see <https://git-scm.com/docs/githooks>
pub fn run_hook(&self, args: &[&str]) -> Result<HookResult> {
self.run_hook_os_str(args)
}
/// this function calls hook scripts based on conventions documented here
/// see <https://git-scm.com/docs/githooks>
pub fn run_hook_os_str<I, S>(&self, args: I) -> Result<HookResult>
where
I: IntoIterator<Item = S> + Copy,
S: AsRef<OsStr>,
{
let hook = self.hook.clone();
log::trace!(
"run hook '{}' in '{}'",
hook.display(),
self.pwd.display()
);
let run_command = |command: &mut Command| {
command
.args(args)
.current_dir(&self.pwd)
.with_no_window()
.output()
};
let output = if cfg!(windows) {
// execute hook in shell
let command = {
// SEE: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02_02
// Enclosing characters in single-quotes ( '' ) shall preserve the literal value of each character within the single-quotes.
// A single-quote cannot occur within single-quotes.
const REPLACEMENT: &str = concat!(
"'", // closing single-quote
"\\'", // one escaped single-quote (outside of single-quotes)
"'", // new single-quote
);
let mut os_str = OsString::new();
os_str.push("'");
if let Some(hook) = hook.to_str() {
os_str.push(hook.replace('\'', REPLACEMENT));
} else {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
if hook
.as_os_str()
.encode_wide()
.any(|x| x == u16::from(b'\''))
{
// TODO: escape single quotes instead of failing
return Err(HooksError::PathToString);
}
}
os_str.push(hook.as_os_str());
}
os_str.push("'");
os_str.push(" \"$@\"");
os_str
};
run_command(
sh_command().arg("-c").arg(command).arg(&hook),
)
} else {
// execute hook directly
match run_command(&mut Command::new(&hook)) {
Err(err) if err.raw_os_error() == Some(ENOEXEC) => {
run_command(sh_command().arg(&hook))
}
result => result,
}
}?;
if output.status.success() {
Ok(HookResult::Ok { hook })
} else {
let stderr =
String::from_utf8_lossy(&output.stderr).to_string();
let stdout =
String::from_utf8_lossy(&output.stdout).to_string();
Ok(HookResult::RunNotSuccessful {
code: output.status.code(),
stdout,
stderr,
hook,
})
}
}
}
fn sh_command() -> Command {
let mut command = Command::new(gix_path::env::shell());
if cfg!(windows) {
// This call forces Command to handle the Path environment correctly on windows,
// the specific env set here does not matter
// see https://github.com/rust-lang/rust/issues/37519
command.env(
"DUMMY_ENV_TO_FIX_WINDOWS_CMD_RUNS",
"FixPathHandlingOnWindows",
);
// Use -l to avoid "command not found"
command.arg("-l");
}
command
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
let metadata = match path.metadata() {
Ok(metadata) => metadata,
Err(e) => {
log::error!("metadata error: {e}");
return false;
}
};
let permissions = metadata.permissions();
permissions.mode() & 0o111 != 0
}
#[cfg(windows)]
/// windows does not consider shell scripts to be executable so we consider everything
/// to be executable (which is not far from the truth for windows platform.)
const fn is_executable(_: &Path) -> bool {
true
}
trait CommandExt {
/// The process is a console application that is being run without a
/// console window. Therefore, the console handle for the application is
/// not set.
///
/// This flag is ignored if the application is not a console application,
/// or if it used with either `CREATE_NEW_CONSOLE` or `DETACHED_PROCESS`.
///
/// See: <https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags>
#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
fn with_no_window(&mut self) -> &mut Self;
}
impl CommandExt for Command {
/// On Windows, CLI applications that aren't the window's subsystem will
/// create and show a console window that pops up next to the main
/// application window when run. We disable this behavior by setting the
/// `CREATE_NO_WINDOW` flag.
#[inline]
fn with_no_window(&mut self) -> &mut Self {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
self.creation_flags(Self::CREATE_NO_WINDOW);
}
self
}
}
#[cfg(test)]
mod test {
use super::HookPaths;
use std::path::Path;
#[test]
fn test_hookspath_relative() {
assert_eq!(
HookPaths::expand_path(
Path::new("pre-commit"),
Path::new("example_git_root"),
)
.unwrap(),
Path::new("example_git_root").join("pre-commit")
);
}
#[test]
fn test_hookspath_absolute() {
let absolute_hook =
std::env::current_dir().unwrap().join("pre-commit");
assert_eq!(
HookPaths::expand_path(
&absolute_hook,
Path::new("example_git_root"),
)
.unwrap(),
absolute_hook
);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/app.rs | src/app.rs | use crate::{
accessors,
args::CliArgs,
cmdbar::CommandBar,
components::{
command_pump, event_pump, CommandInfo, Component,
DrawableComponent, FuzzyFinderTarget,
},
input::{Input, InputEvent, InputState},
keys::{key_match, KeyConfig, SharedKeyConfig},
options::{Options, SharedOptions},
popup_stack::PopupStack,
popups::{
AppOption, BlameFilePopup, BranchListPopup,
CheckoutOptionPopup, CommitPopup, CompareCommitsPopup,
ConfirmPopup, CreateBranchPopup, CreateRemotePopup,
ExternalEditorPopup, FetchPopup, FileRevlogPopup,
FuzzyFindPopup, GotoLinePopup, HelpPopup, InspectCommitPopup,
LogSearchPopupPopup, MsgPopup, OptionsPopup, PullPopup,
PushPopup, PushTagsPopup, RemoteListPopup, RenameBranchPopup,
RenameRemotePopup, ResetPopup, RevisionFilesPopup,
StashMsgPopup, SubmodulesListPopup, TagCommitPopup,
TagListPopup, UpdateRemoteUrlPopup,
},
queue::{
Action, AppTabs, InternalEvent, NeedsUpdate, Queue,
StackablePopupOpen,
},
setup_popups,
strings::{self, ellipsis_trim_start, order},
tabs::{FilesTab, Revlog, StashList, Stashing, Status},
try_or_popup,
ui::style::{SharedTheme, Theme},
AsyncAppNotification, AsyncNotification,
};
use anyhow::{bail, Result};
use asyncgit::{
sync::{
self,
utils::{repo_work_dir, undo_last_commit},
RepoPath, RepoPathRef,
},
AsyncGitNotification, PushType,
};
use crossbeam_channel::Sender;
use crossterm::event::{Event, KeyEvent};
use ratatui::{
layout::{
Alignment, Constraint, Direction, Layout, Margin, Rect,
},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Tabs},
Frame,
};
use std::{
cell::{Cell, RefCell},
path::{Path, PathBuf},
rc::Rc,
};
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum QuitState {
None,
Close,
OpenSubmodule(RepoPath),
}
/// the main app type
pub struct App {
repo: RepoPathRef,
do_quit: QuitState,
help_popup: HelpPopup,
msg_popup: MsgPopup,
confirm_popup: ConfirmPopup,
commit_popup: CommitPopup,
blame_file_popup: BlameFilePopup,
file_revlog_popup: FileRevlogPopup,
stashmsg_popup: StashMsgPopup,
inspect_commit_popup: InspectCommitPopup,
compare_commits_popup: CompareCommitsPopup,
external_editor_popup: ExternalEditorPopup,
revision_files_popup: RevisionFilesPopup,
fuzzy_find_popup: FuzzyFindPopup,
log_search_popup: LogSearchPopupPopup,
push_popup: PushPopup,
push_tags_popup: PushTagsPopup,
pull_popup: PullPopup,
fetch_popup: FetchPopup,
tag_commit_popup: TagCommitPopup,
create_branch_popup: CreateBranchPopup,
create_remote_popup: CreateRemotePopup,
rename_remote_popup: RenameRemotePopup,
update_remote_url_popup: UpdateRemoteUrlPopup,
remotes_popup: RemoteListPopup,
rename_branch_popup: RenameBranchPopup,
select_branch_popup: BranchListPopup,
options_popup: OptionsPopup,
submodule_popup: SubmodulesListPopup,
tags_popup: TagListPopup,
reset_popup: ResetPopup,
checkout_option_popup: CheckoutOptionPopup,
cmdbar: RefCell<CommandBar>,
tab: usize,
revlog: Revlog,
status_tab: Status,
stashing_tab: Stashing,
stashlist_tab: StashList,
files_tab: FilesTab,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
input: Input,
popup_stack: PopupStack,
options: SharedOptions,
repo_path_text: String,
goto_line_popup: GotoLinePopup,
// "Flags"
requires_redraw: Cell<bool>,
file_to_open: Option<String>,
}
pub struct Environment {
pub queue: Queue,
pub theme: SharedTheme,
pub key_config: SharedKeyConfig,
pub repo: RepoPathRef,
pub options: SharedOptions,
pub sender_git: Sender<AsyncGitNotification>,
pub sender_app: Sender<AsyncAppNotification>,
}
/// The need to construct a "whatever" environment only arises in testing right now
#[cfg(test)]
impl Environment {
pub fn test_env() -> Self {
use crossbeam_channel::unbounded;
Self {
queue: Queue::new(),
theme: Default::default(),
key_config: Default::default(),
repo: RefCell::new(RepoPath::Path(Default::default())),
options: Rc::new(RefCell::new(Options::test_env())),
sender_git: unbounded().0,
sender_app: unbounded().0,
}
}
}
// public interface
impl App {
///
#[allow(clippy::too_many_lines)]
pub fn new(
cliargs: CliArgs,
sender_git: Sender<AsyncGitNotification>,
sender_app: Sender<AsyncAppNotification>,
input: Input,
theme: Theme,
key_config: KeyConfig,
) -> Result<Self> {
let repo = RefCell::new(cliargs.repo_path.clone());
log::trace!("open repo at: {:?}", &repo);
let repo_path_text =
repo_work_dir(&repo.borrow()).unwrap_or_default();
let env = Environment {
queue: Queue::new(),
theme: Rc::new(theme),
key_config: Rc::new(key_config),
options: Options::new(repo.clone()),
repo,
sender_git,
sender_app,
};
let mut select_file: Option<PathBuf> = None;
let tab = if let Some(file) = cliargs.select_file {
// convert to relative git path
if let Ok(abs) = file.canonicalize() {
if let Ok(path) = abs.strip_prefix(
env.repo.borrow().gitpath().canonicalize()?,
) {
select_file = Some(Path::new(".").join(path));
}
}
2
} else {
env.options.borrow().current_tab()
};
let mut app = Self {
input,
confirm_popup: ConfirmPopup::new(&env),
commit_popup: CommitPopup::new(&env),
blame_file_popup: BlameFilePopup::new(
&env,
&strings::blame_title(&env.key_config),
),
file_revlog_popup: FileRevlogPopup::new(&env),
revision_files_popup: RevisionFilesPopup::new(&env),
stashmsg_popup: StashMsgPopup::new(&env),
inspect_commit_popup: InspectCommitPopup::new(&env),
compare_commits_popup: CompareCommitsPopup::new(&env),
external_editor_popup: ExternalEditorPopup::new(&env),
push_popup: PushPopup::new(&env),
push_tags_popup: PushTagsPopup::new(&env),
reset_popup: ResetPopup::new(&env),
pull_popup: PullPopup::new(&env),
fetch_popup: FetchPopup::new(&env),
tag_commit_popup: TagCommitPopup::new(&env),
create_branch_popup: CreateBranchPopup::new(&env),
create_remote_popup: CreateRemotePopup::new(&env),
rename_remote_popup: RenameRemotePopup::new(&env),
update_remote_url_popup: UpdateRemoteUrlPopup::new(&env),
remotes_popup: RemoteListPopup::new(&env),
rename_branch_popup: RenameBranchPopup::new(&env),
select_branch_popup: BranchListPopup::new(&env),
tags_popup: TagListPopup::new(&env),
options_popup: OptionsPopup::new(&env),
submodule_popup: SubmodulesListPopup::new(&env),
log_search_popup: LogSearchPopupPopup::new(&env),
fuzzy_find_popup: FuzzyFindPopup::new(&env),
do_quit: QuitState::None,
cmdbar: RefCell::new(CommandBar::new(
env.theme.clone(),
env.key_config.clone(),
)),
help_popup: HelpPopup::new(&env),
msg_popup: MsgPopup::new(&env),
revlog: Revlog::new(&env),
status_tab: Status::new(&env),
stashing_tab: Stashing::new(&env),
stashlist_tab: StashList::new(&env),
files_tab: FilesTab::new(&env, select_file),
checkout_option_popup: CheckoutOptionPopup::new(&env),
goto_line_popup: GotoLinePopup::new(&env),
tab: 0,
queue: env.queue,
theme: env.theme,
options: env.options,
key_config: env.key_config,
requires_redraw: Cell::new(false),
file_to_open: None,
repo: env.repo,
repo_path_text,
popup_stack: PopupStack::default(),
};
app.set_tab(tab)?;
Ok(app)
}
///
pub fn draw(&self, f: &mut Frame) -> Result<()> {
let fsize = f.area();
self.cmdbar.borrow_mut().refresh_width(fsize.width);
let chunks_main = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(2),
Constraint::Min(2),
Constraint::Length(self.cmdbar.borrow().height()),
]
.as_ref(),
)
.split(fsize);
self.cmdbar.borrow().draw(f, chunks_main[2]);
self.draw_top_bar(f, chunks_main[0]);
//TODO: component property + a macro `fullscreen_popup_open!`
// to make this scale better?
let fullscreen_popup_open =
self.revision_files_popup.is_visible()
|| self.inspect_commit_popup.is_visible()
|| self.compare_commits_popup.is_visible()
|| self.blame_file_popup.is_visible()
|| self.file_revlog_popup.is_visible();
if !fullscreen_popup_open {
//TODO: macro because of generic draw call
match self.tab {
0 => self.status_tab.draw(f, chunks_main[1])?,
1 => self.revlog.draw(f, chunks_main[1])?,
2 => self.files_tab.draw(f, chunks_main[1])?,
3 => self.stashing_tab.draw(f, chunks_main[1])?,
4 => self.stashlist_tab.draw(f, chunks_main[1])?,
_ => bail!("unknown tab"),
}
}
self.draw_popups(f)?;
Ok(())
}
///
pub fn event(&mut self, ev: InputEvent) -> Result<()> {
log::trace!("event: {ev:?}");
if let InputEvent::Input(ev) = ev {
if self.check_hard_exit(&ev) || self.check_quit(&ev) {
return Ok(());
}
let mut flags = NeedsUpdate::empty();
if event_pump(&ev, self.components_mut().as_mut_slice())?
.is_consumed()
{
flags.insert(NeedsUpdate::COMMANDS);
} else if let Event::Key(k) = &ev {
let new_flags = if key_match(
k,
self.key_config.keys.tab_toggle,
) {
self.toggle_tabs(false)?;
NeedsUpdate::COMMANDS
} else if key_match(
k,
self.key_config.keys.tab_toggle_reverse,
) {
self.toggle_tabs(true)?;
NeedsUpdate::COMMANDS
} else if key_match(
k,
self.key_config.keys.tab_status,
) || key_match(
k,
self.key_config.keys.tab_log,
) || key_match(
k,
self.key_config.keys.tab_files,
) || key_match(
k,
self.key_config.keys.tab_stashing,
) || key_match(
k,
self.key_config.keys.tab_stashes,
) {
self.switch_tab(k)?;
NeedsUpdate::COMMANDS
} else if key_match(
k,
self.key_config.keys.cmd_bar_toggle,
) {
self.cmdbar.borrow_mut().toggle_more();
NeedsUpdate::empty()
} else if key_match(
k,
self.key_config.keys.open_options,
) {
self.options_popup.show()?;
NeedsUpdate::ALL
} else {
NeedsUpdate::empty()
};
flags.insert(new_flags);
}
self.process_queue(flags)?;
} else if let InputEvent::State(polling_state) = ev {
self.external_editor_popup.hide();
if matches!(polling_state, InputState::Paused) {
let result =
if let Some(path) = self.file_to_open.take() {
ExternalEditorPopup::open_file_in_editor(
&self.repo.borrow(),
Path::new(&path),
)
} else {
let changes =
self.status_tab.get_files_changes()?;
self.commit_popup.show_editor(changes)
};
if let Err(e) = result {
let msg =
format!("failed to launch editor:\n{e}");
log::error!("{}", msg.as_str());
self.msg_popup.show_error(msg.as_str())?;
}
self.requires_redraw.set(true);
self.input.set_polling(true);
}
}
Ok(())
}
//TODO: do we need this?
/// forward ticking to components that require it
pub fn update(&mut self) -> Result<()> {
log::trace!("update");
self.commit_popup.update();
self.status_tab.update()?;
self.revlog.update()?;
self.files_tab.update()?;
self.stashing_tab.update()?;
self.stashlist_tab.update()?;
self.reset_popup.update()?;
self.update_commands();
Ok(())
}
///
pub fn update_async(
&mut self,
ev: AsyncNotification,
) -> Result<()> {
log::trace!("update_async: {ev:?}");
if let AsyncNotification::Git(ev) = ev {
self.status_tab.update_git(ev)?;
self.stashing_tab.update_git(ev)?;
self.revlog.update_git(ev)?;
self.file_revlog_popup.update_git(ev)?;
self.inspect_commit_popup.update_git(ev)?;
self.compare_commits_popup.update_git(ev)?;
self.push_popup.update_git(ev)?;
self.push_tags_popup.update_git(ev)?;
self.pull_popup.update_git(ev);
self.fetch_popup.update_git(ev);
self.select_branch_popup.update_git(ev)?;
}
self.files_tab.update_async(ev)?;
self.blame_file_popup.update_async(ev)?;
self.revision_files_popup.update(ev)?;
self.tags_popup.update(ev);
//TODO: better system for this
// can we simply process the queue here and everyone just uses the queue to schedule a cmd update?
self.process_queue(NeedsUpdate::COMMANDS)?;
Ok(())
}
///
pub fn is_quit(&self) -> bool {
!matches!(self.do_quit, QuitState::None)
|| self.input.is_aborted()
}
///
pub fn quit_state(&self) -> QuitState {
self.do_quit.clone()
}
///
pub fn any_work_pending(&self) -> bool {
self.status_tab.anything_pending()
|| self.revlog.any_work_pending()
|| self.stashing_tab.anything_pending()
|| self.files_tab.anything_pending()
|| self.blame_file_popup.any_work_pending()
|| self.file_revlog_popup.any_work_pending()
|| self.inspect_commit_popup.any_work_pending()
|| self.compare_commits_popup.any_work_pending()
|| self.input.is_state_changing()
|| self.push_popup.any_work_pending()
|| self.push_tags_popup.any_work_pending()
|| self.pull_popup.any_work_pending()
|| self.fetch_popup.any_work_pending()
|| self.revision_files_popup.any_work_pending()
|| self.tags_popup.any_work_pending()
}
///
pub fn requires_redraw(&self) -> bool {
if self.requires_redraw.get() {
self.requires_redraw.set(false);
true
} else {
false
}
}
}
// private impls
impl App {
accessors!(
self,
[
log_search_popup,
fuzzy_find_popup,
msg_popup,
confirm_popup,
commit_popup,
goto_line_popup,
blame_file_popup,
file_revlog_popup,
stashmsg_popup,
inspect_commit_popup,
compare_commits_popup,
external_editor_popup,
push_popup,
push_tags_popup,
pull_popup,
fetch_popup,
tag_commit_popup,
reset_popup,
checkout_option_popup,
create_branch_popup,
create_remote_popup,
rename_remote_popup,
update_remote_url_popup,
remotes_popup,
rename_branch_popup,
select_branch_popup,
revision_files_popup,
submodule_popup,
tags_popup,
options_popup,
help_popup,
revlog,
status_tab,
files_tab,
stashing_tab,
stashlist_tab
]
);
setup_popups!(
self,
[
commit_popup,
stashmsg_popup,
help_popup,
inspect_commit_popup,
compare_commits_popup,
blame_file_popup,
file_revlog_popup,
external_editor_popup,
tag_commit_popup,
select_branch_popup,
remotes_popup,
create_remote_popup,
rename_remote_popup,
update_remote_url_popup,
submodule_popup,
tags_popup,
reset_popup,
checkout_option_popup,
create_branch_popup,
rename_branch_popup,
revision_files_popup,
fuzzy_find_popup,
log_search_popup,
push_popup,
push_tags_popup,
pull_popup,
fetch_popup,
options_popup,
confirm_popup,
msg_popup,
goto_line_popup
]
);
fn check_quit(&mut self, ev: &Event) -> bool {
if self.any_popup_visible() {
return false;
}
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.quit) {
self.do_quit = QuitState::Close;
return true;
}
}
false
}
fn check_hard_exit(&mut self, ev: &Event) -> bool {
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.exit) {
self.do_quit = QuitState::Close;
return true;
}
}
false
}
fn get_tabs(&mut self) -> Vec<&mut dyn Component> {
vec![
&mut self.status_tab,
&mut self.revlog,
&mut self.files_tab,
&mut self.stashing_tab,
&mut self.stashlist_tab,
]
}
fn toggle_tabs(&mut self, reverse: bool) -> Result<()> {
let tabs_len = self.get_tabs().len();
let new_tab = if reverse {
self.tab.wrapping_sub(1).min(tabs_len.saturating_sub(1))
} else {
self.tab.saturating_add(1) % tabs_len
};
self.set_tab(new_tab)
}
fn switch_tab(&mut self, k: &KeyEvent) -> Result<()> {
if key_match(k, self.key_config.keys.tab_status) {
self.switch_to_tab(&AppTabs::Status)?;
} else if key_match(k, self.key_config.keys.tab_log) {
self.switch_to_tab(&AppTabs::Log)?;
} else if key_match(k, self.key_config.keys.tab_files) {
self.switch_to_tab(&AppTabs::Files)?;
} else if key_match(k, self.key_config.keys.tab_stashing) {
self.switch_to_tab(&AppTabs::Stashing)?;
} else if key_match(k, self.key_config.keys.tab_stashes) {
self.switch_to_tab(&AppTabs::Stashlist)?;
}
Ok(())
}
fn set_tab(&mut self, tab: usize) -> Result<()> {
let tabs = self.get_tabs();
for (i, t) in tabs.into_iter().enumerate() {
if tab == i {
t.show()?;
} else {
t.hide();
}
}
self.tab = tab;
self.options.borrow_mut().set_current_tab(tab);
Ok(())
}
fn switch_to_tab(&mut self, tab: &AppTabs) -> Result<()> {
match tab {
AppTabs::Status => self.set_tab(0)?,
AppTabs::Log => self.set_tab(1)?,
AppTabs::Files => self.set_tab(2)?,
AppTabs::Stashing => self.set_tab(3)?,
AppTabs::Stashlist => self.set_tab(4)?,
}
Ok(())
}
fn update_commands(&mut self) {
if self.help_popup.is_visible() {
self.help_popup.set_cmds(self.commands(true));
}
self.cmdbar.borrow_mut().set_cmds(self.commands(false));
}
fn process_queue(&mut self, flags: NeedsUpdate) -> Result<()> {
let mut flags = flags;
let new_flags = self.process_internal_events()?;
flags.insert(new_flags);
if flags.contains(NeedsUpdate::ALL) {
self.update()?;
}
//TODO: make this a queue event?
//NOTE: set when any tree component changed selection
if flags.contains(NeedsUpdate::DIFF) {
self.status_tab.update_diff()?;
self.inspect_commit_popup.update_diff()?;
self.compare_commits_popup.update_diff()?;
self.file_revlog_popup.update_diff()?;
}
if flags.contains(NeedsUpdate::COMMANDS) {
self.update_commands();
}
if flags.contains(NeedsUpdate::BRANCHES) {
self.select_branch_popup.update_branches()?;
}
if flags.contains(NeedsUpdate::REMOTES) {
self.remotes_popup.update_remotes()?;
}
Ok(())
}
fn open_popup(
&mut self,
popup: StackablePopupOpen,
) -> Result<()> {
match popup {
StackablePopupOpen::BlameFile(params) => {
self.blame_file_popup.open(params)?;
}
StackablePopupOpen::FileRevlog(param) => {
self.file_revlog_popup.open(param)?;
}
StackablePopupOpen::FileTree(param) => {
self.revision_files_popup.open(param)?;
}
StackablePopupOpen::InspectCommit(param) => {
self.inspect_commit_popup.open(param)?;
}
StackablePopupOpen::CompareCommits(param) => {
self.compare_commits_popup.open(param)?;
}
}
Ok(())
}
fn process_internal_events(&mut self) -> Result<NeedsUpdate> {
let mut flags = NeedsUpdate::empty();
loop {
let front = self.queue.pop();
if let Some(e) = front {
flags.insert(self.process_internal_event(e)?);
} else {
break;
}
}
self.queue.clear();
Ok(flags)
}
#[allow(clippy::too_many_lines)]
fn process_internal_event(
&mut self,
ev: InternalEvent,
) -> Result<NeedsUpdate> {
let mut flags = NeedsUpdate::empty();
match ev {
InternalEvent::ConfirmedAction(action) => {
self.process_confirmed_action(action, &mut flags)?;
}
InternalEvent::ConfirmAction(action) => {
self.confirm_popup.open(action)?;
flags.insert(NeedsUpdate::COMMANDS);
}
InternalEvent::ShowErrorMsg(msg) => {
self.msg_popup.show_error(msg.as_str())?;
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::ShowInfoMsg(msg) => {
self.msg_popup.show_info(msg.as_str())?;
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::Update(u) => flags.insert(u),
InternalEvent::OpenCommit => self.commit_popup.show()?,
InternalEvent::RewordCommit(id) => {
self.commit_popup.open(Some(id))?;
}
InternalEvent::PopupStashing(opts) => {
self.stashmsg_popup.options(opts);
self.stashmsg_popup.show()?;
}
InternalEvent::TagCommit(id) => {
self.tag_commit_popup.open(id)?;
}
InternalEvent::CreateRemote => {
self.create_remote_popup.open()?;
}
InternalEvent::RenameRemote(cur_name) => {
self.rename_remote_popup.open(cur_name)?;
}
InternalEvent::UpdateRemoteUrl(remote_name, cur_url) => {
self.update_remote_url_popup
.open(remote_name, cur_url)?;
}
InternalEvent::ViewRemotes => {
self.remotes_popup.open()?;
}
InternalEvent::CreateBranch => {
self.create_branch_popup.open()?;
}
InternalEvent::RenameBranch(branch_ref, cur_name) => {
self.rename_branch_popup
.open(branch_ref, cur_name)?;
}
InternalEvent::SelectBranch => {
self.select_branch_popup.open()?;
}
InternalEvent::ViewSubmodules => {
self.submodule_popup.open()?;
}
InternalEvent::Tags => {
self.tags_popup.open()?;
}
InternalEvent::TabSwitchStatus => self.set_tab(0)?,
InternalEvent::TabSwitch(tab) => {
self.switch_to_tab(&tab)?;
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::SelectCommitInRevlog(id) => {
if let Err(error) = self.revlog.select_commit(id) {
self.queue.push(InternalEvent::ShowErrorMsg(
error.to_string(),
));
} else {
self.tags_popup.hide();
flags.insert(NeedsUpdate::ALL);
}
}
InternalEvent::OpenExternalEditor(path) => {
self.input.set_polling(false);
self.external_editor_popup.show()?;
self.file_to_open = path;
flags.insert(NeedsUpdate::COMMANDS);
}
InternalEvent::Push(branch, push_type, force, delete) => {
self.push_popup
.push(branch, push_type, force, delete)?;
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::Pull(branch) => {
if let Err(error) = self.pull_popup.fetch(branch) {
self.queue.push(InternalEvent::ShowErrorMsg(
error.to_string(),
));
}
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::FetchRemotes => {
if let Err(error) = self.fetch_popup.fetch() {
self.queue.push(InternalEvent::ShowErrorMsg(
error.to_string(),
));
}
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::PushTags => {
self.push_tags_popup.push_tags()?;
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::StatusLastFileMoved => {
self.status_tab.last_file_moved()?;
}
InternalEvent::OpenFuzzyFinder(contents, target) => {
self.fuzzy_find_popup.open(contents, target)?;
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::OpenLogSearchPopup => {
self.log_search_popup.open()?;
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::OptionSwitched(o) => {
match o {
AppOption::StatusShowUntracked => {
self.status_tab.update()?;
}
AppOption::DiffContextLines
| AppOption::DiffIgnoreWhitespaces
| AppOption::DiffInterhunkLines => {
self.status_tab.update_diff()?;
}
}
flags.insert(NeedsUpdate::ALL);
}
InternalEvent::FuzzyFinderChanged(
idx,
content,
target,
) => {
match target {
FuzzyFinderTarget::Branches => self
.select_branch_popup
.branch_finder_update(idx)?,
FuzzyFinderTarget::Files => {
self.files_tab.file_finder_update(
&PathBuf::from(content.clone()),
);
self.revision_files_popup.file_finder_update(
&PathBuf::from(content),
);
}
}
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::OpenPopup(popup) => {
self.open_popup(popup)?;
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::PopupStackPop => {
if let Some(popup) = self.popup_stack.pop() {
self.open_popup(popup)?;
flags.insert(
NeedsUpdate::ALL | NeedsUpdate::COMMANDS,
);
}
}
InternalEvent::PopupStackPush(popup) => {
self.popup_stack.push(popup);
flags
.insert(NeedsUpdate::ALL | NeedsUpdate::COMMANDS);
}
InternalEvent::OpenRepo { path } => {
let submodule_repo_path = RepoPath::Path(
Path::new(&repo_work_dir(&self.repo.borrow())?)
.join(path),
);
//TODO: validate this is a valid repo first, so we can show proper error otherwise
self.do_quit =
QuitState::OpenSubmodule(submodule_repo_path);
}
InternalEvent::OpenResetPopup(id) => {
self.reset_popup.open(id)?;
}
InternalEvent::CommitSearch(options) => {
self.revlog.search(options);
}
InternalEvent::OpenGotoLinePopup(max_line) => {
self.goto_line_popup.open(max_line);
}
InternalEvent::GotoLine(line) => {
if self.blame_file_popup.is_visible() {
self.blame_file_popup.goto_line(line);
}
}
InternalEvent::CheckoutOption(branch) => {
self.checkout_option_popup.open(branch)?;
}
}
Ok(flags)
}
fn process_confirmed_action(
&mut self,
action: Action,
flags: &mut NeedsUpdate,
) -> Result<()> {
match action {
Action::Reset(r) => {
self.status_tab.reset(&r);
}
Action::StashDrop(_) | Action::StashPop(_) => {
if let Err(e) = self
.stashlist_tab
.action_confirmed(&self.repo.borrow(), &action)
{
self.queue.push(InternalEvent::ShowErrorMsg(
e.to_string(),
));
}
}
Action::ResetHunk(path, hash) => {
sync::reset_hunk(
&self.repo.borrow(),
&path,
hash,
Some(self.options.borrow().diff_options()),
)?;
}
Action::ResetLines(path, lines) => {
sync::discard_lines(
&self.repo.borrow(),
&path,
&lines,
)?;
}
Action::DeleteLocalBranch(branch_ref) => {
if let Err(e) = sync::delete_branch(
&self.repo.borrow(),
&branch_ref,
) {
self.queue.push(InternalEvent::ShowErrorMsg(
e.to_string(),
));
}
self.select_branch_popup.update_branches()?;
}
Action::DeleteRemoteBranch(branch_ref) => {
self.delete_remote_branch(&branch_ref)?;
}
Action::DeleteRemote(remote_name) => {
self.delete_remote(&remote_name);
}
Action::DeleteTag(tag_name) => {
self.delete_tag(tag_name)?;
}
Action::DeleteRemoteTag(tag_name, _remote) => {
self.queue.push(InternalEvent::Push(
tag_name,
PushType::Tag,
false,
true,
));
}
Action::ForcePush(branch, force) => {
self.queue.push(InternalEvent::Push(
branch,
PushType::Branch,
force,
false,
));
}
Action::PullMerge { rebase, .. } => {
self.pull_popup.try_conflict_free_merge(rebase);
}
Action::AbortRevert | Action::AbortMerge => {
self.status_tab.revert_pending_state();
}
Action::AbortRebase => {
self.status_tab.abort_rebase();
}
Action::UndoCommit => {
try_or_popup!(
self,
"undo commit failed:",
undo_last_commit(&self.repo.borrow())
);
}
}
flags.insert(NeedsUpdate::ALL);
Ok(())
}
fn delete_tag(&mut self, tag_name: String) -> Result<()> {
if let Err(error) =
sync::delete_tag(&self.repo.borrow(), &tag_name)
{
self.queue
.push(InternalEvent::ShowErrorMsg(error.to_string()));
} else {
let remote =
sync::get_default_remote(&self.repo.borrow())?;
self.queue.push(InternalEvent::ConfirmAction(
Action::DeleteRemoteTag(tag_name, remote),
));
self.tags_popup.update_tags()?;
}
Ok(())
}
fn delete_remote_branch(
&mut self,
branch_ref: &str,
) -> Result<()> {
self.queue.push(
//TODO: check if this is correct based on the fix in `c6abbaf`
branch_ref.rsplit('/').next().map_or_else(
|| {
InternalEvent::ShowErrorMsg(format!(
"Failed to find the branch name in {branch_ref}"
))
},
|name| {
InternalEvent::Push(
name.to_string(),
PushType::Branch,
false,
true,
)
},
),
);
self.select_branch_popup.update_branches()?;
Ok(())
}
fn delete_remote(&self, remote_name: &str) {
let res =
sync::delete_remote(&self.repo.borrow(), remote_name);
match res {
Ok(()) => {
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL | NeedsUpdate::REMOTES,
));
}
Err(e) => {
log::error!("delete remote: {e:?}");
self.queue.push(InternalEvent::ShowErrorMsg(
format!("delete remote error:\n{e}",),
));
}
}
}
fn commands(&self, force_all: bool) -> Vec<CommandInfo> {
let mut res = Vec::new();
command_pump(&mut res, force_all, &self.components());
res.push(CommandInfo::new(
strings::commands::find_file(&self.key_config),
!self.fuzzy_find_popup.is_visible(),
(!self.any_popup_visible()
&& self.files_tab.is_visible())
|| self.revision_files_popup.is_visible()
|| force_all,
));
res.push(
CommandInfo::new(
strings::commands::toggle_tabs(&self.key_config),
true,
!self.any_popup_visible(),
)
.order(order::NAV),
);
res.push(
CommandInfo::new(
strings::commands::toggle_tabs_direct(
&self.key_config,
),
true,
!self.any_popup_visible(),
)
.order(order::NAV),
);
res.push(
CommandInfo::new(
strings::commands::options_popup(&self.key_config),
true,
!self.any_popup_visible(),
)
.order(order::NAV),
);
res.push(
CommandInfo::new(
strings::commands::quit(&self.key_config),
true,
!self.any_popup_visible(),
)
.order(100),
);
res
}
//TODO: make this dynamic
fn draw_top_bar(&self, f: &mut Frame, r: Rect) {
const DIVIDER_PAD_SPACES: usize = 2;
const SIDE_PADS: usize = 2;
const MARGIN_LEFT_AND_RIGHT: usize = 2;
let r = r.inner(Margin {
vertical: 0,
horizontal: 1,
});
let tab_labels = [
Span::raw(strings::tab_status(&self.key_config)),
Span::raw(strings::tab_log(&self.key_config)),
Span::raw(strings::tab_files(&self.key_config)),
Span::raw(strings::tab_stashing(&self.key_config)),
Span::raw(strings::tab_stashes(&self.key_config)),
];
let divider = strings::tab_divider(&self.key_config);
// heuristic, since tui doesn't provide a way to know
// how much space is needed to draw a `Tabs`
let tabs_len: usize =
tab_labels.iter().map(Span::width).sum::<usize>()
+ tab_labels.len().saturating_sub(1)
* (divider.width() + DIVIDER_PAD_SPACES)
+ SIDE_PADS + MARGIN_LEFT_AND_RIGHT;
let left_right = Layout::default()
.direction(Direction::Horizontal)
.constraints(vec![
Constraint::Length(
u16::try_from(tabs_len).unwrap_or(r.width),
),
Constraint::Min(0),
])
.split(r);
let table_area = r; // use entire area to allow drawing the horizontal separator line
let text_area = left_right[1];
let tabs: Vec<Line> =
tab_labels.into_iter().map(Line::from).collect();
f.render_widget(
Tabs::new(tabs)
.block(
Block::default()
.borders(Borders::BOTTOM)
.border_style(self.theme.block(false)),
)
.style(self.theme.tab(false))
.highlight_style(self.theme.tab(true))
.divider(divider)
.select(self.tab),
table_area,
);
f.render_widget(
Paragraph::new(Line::from(vec![Span::styled(
ellipsis_trim_start(
&self.repo_path_text,
text_area.width as usize,
),
self.theme.title(false),
)]))
.alignment(Alignment::Right),
text_area,
);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/bug_report.rs | src/bug_report.rs | use bugreport::{
bugreport,
collector::{
CommandLine, CompileTimeInformation, EnvironmentVariables,
OperatingSystem, SoftwareVersion,
},
format::Markdown,
};
pub fn generate_bugreport() {
bugreport!()
.info(SoftwareVersion::default())
.info(OperatingSystem::default())
.info(CompileTimeInformation::default())
.info(EnvironmentVariables::list(&[
"SHELL",
"EDITOR",
"GIT_EDITOR",
"VISUAL",
]))
.info(CommandLine::default())
.print::<Markdown>();
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/clipboard.rs | src/clipboard.rs | use anyhow::{anyhow, Result};
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use which::which;
fn exec_copy_with_args(
command: &str,
args: &[&str],
text: &str,
pipe_stderr: bool,
) -> Result<()> {
let binary = which(command)
.ok()
.unwrap_or_else(|| PathBuf::from(command));
let mut process = Command::new(binary)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(if pipe_stderr {
Stdio::piped()
} else {
Stdio::null()
})
.spawn()
.map_err(|e| anyhow!("`{command:?}`: {e:?}"))?;
process
.stdin
.as_mut()
.ok_or_else(|| anyhow!("`{command:?}`"))?
.write_all(text.as_bytes())
.map_err(|e| anyhow!("`{command:?}`: {e:?}"))?;
let out = process
.wait_with_output()
.map_err(|e| anyhow!("`{command:?}`: {e:?}"))?;
if out.status.success() {
Ok(())
} else {
let msg = if out.stderr.is_empty() {
format!("{}", out.status).into()
} else {
String::from_utf8_lossy(&out.stderr)
};
Err(anyhow!("`{command:?}`: {msg}"))
}
}
// Implementation taken from https://crates.io/crates/wsl.
// Using /proc/sys/kernel/osrelease as an authoritative source
// based on this comment: https://github.com/microsoft/WSL/issues/423#issuecomment-221627364
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
fn is_wsl() -> bool {
if let Ok(b) = std::fs::read("/proc/sys/kernel/osrelease") {
if let Ok(s) = std::str::from_utf8(&b) {
let a = s.to_ascii_lowercase();
return a.contains("microsoft") || a.contains("wsl");
}
}
false
}
// Copy text using escape sequence Ps = 5 2.
// This enables copying even if there is no Wayland or X socket available,
// e.g. via SSH, as long as it supported by the terminal.
// See https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands
#[cfg(any(
all(target_family = "unix", not(target_os = "macos")),
test
))]
fn copy_string_osc52(text: &str, out: &mut impl Write) -> Result<()> {
use base64::prelude::{Engine, BASE64_STANDARD};
const OSC52_DESTINATION_CLIPBOARD: char = 'c';
write!(
out,
"\x1b]52;{destination};{encoded_text}\x07",
destination = OSC52_DESTINATION_CLIPBOARD,
encoded_text = BASE64_STANDARD.encode(text)
)?;
Ok(())
}
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
fn copy_string_wayland(text: &str) -> Result<()> {
if exec_copy_with_args("wl-copy", &[], text, false).is_ok() {
return Ok(());
}
copy_string_osc52(text, &mut std::io::stdout())
}
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
fn copy_string_x(text: &str) -> Result<()> {
if exec_copy_with_args(
"xclip",
&["-selection", "clipboard"],
text,
false,
)
.is_ok()
{
return Ok(());
}
if exec_copy_with_args("xsel", &["--clipboard"], text, true)
.is_ok()
{
return Ok(());
}
copy_string_osc52(text, &mut std::io::stdout())
}
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
pub fn copy_string(text: &str) -> Result<()> {
if std::env::var("WAYLAND_DISPLAY").is_ok() {
return copy_string_wayland(text);
}
if is_wsl() {
return exec_copy_with_args("clip.exe", &[], text, false);
}
copy_string_x(text)
}
#[cfg(any(target_os = "macos", windows))]
fn exec_copy(command: &str, text: &str) -> Result<()> {
exec_copy_with_args(command, &[], text, true)
}
#[cfg(target_os = "macos")]
pub fn copy_string(text: &str) -> Result<()> {
exec_copy("pbcopy", text)
}
#[cfg(windows)]
pub fn copy_string(text: &str) -> Result<()> {
exec_copy("clip", text)
}
#[cfg(test)]
mod tests {
#[test]
fn test_copy_string_osc52() {
let mut buffer = Vec::<u8>::new();
{
let mut cursor = std::io::Cursor::new(&mut buffer);
super::copy_string_osc52("foo", &mut cursor).unwrap();
}
let output = String::from_utf8(buffer).unwrap();
assert_eq!(output, "\x1b]52;c;Zm9v\x07");
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/args.rs | src/args.rs | use crate::bug_report;
use anyhow::{anyhow, Context, Result};
use asyncgit::sync::RepoPath;
use clap::{
builder::ArgPredicate, crate_authors, crate_description,
crate_name, Arg, Command as ClapApp,
};
use simplelog::{Config, LevelFilter, WriteLogger};
use std::{
env,
fs::{self, File},
path::PathBuf,
};
const BUG_REPORT_FLAG_ID: &str = "bugreport";
const LOG_FILE_FLAG_ID: &str = "logfile";
const LOGGING_FLAG_ID: &str = "logging";
const THEME_FLAG_ID: &str = "theme";
const WORKDIR_FLAG_ID: &str = "workdir";
const FILE_FLAG_ID: &str = "file";
const GIT_DIR_FLAG_ID: &str = "directory";
const WATCHER_FLAG_ID: &str = "watcher";
const KEY_BINDINGS_FLAG_ID: &str = "key_bindings";
const KEY_SYMBOLS_FLAG_ID: &str = "key_symbols";
const DEFAULT_THEME: &str = "theme.ron";
const DEFAULT_GIT_DIR: &str = ".";
#[derive(Clone)]
pub struct CliArgs {
pub theme: PathBuf,
pub select_file: Option<PathBuf>,
pub repo_path: RepoPath,
pub notify_watcher: bool,
pub key_bindings_path: Option<PathBuf>,
pub key_symbols_path: Option<PathBuf>,
}
pub fn process_cmdline() -> Result<CliArgs> {
let app = app();
let arg_matches = app.get_matches();
if arg_matches.get_flag(BUG_REPORT_FLAG_ID) {
bug_report::generate_bugreport();
std::process::exit(0);
}
if arg_matches.get_flag(LOGGING_FLAG_ID) {
let logfile = arg_matches.get_one::<String>(LOG_FILE_FLAG_ID);
setup_logging(logfile.map(PathBuf::from))?;
}
let workdir = arg_matches
.get_one::<String>(WORKDIR_FLAG_ID)
.map(PathBuf::from);
let gitdir =
arg_matches.get_one::<String>(GIT_DIR_FLAG_ID).map_or_else(
|| PathBuf::from(DEFAULT_GIT_DIR),
PathBuf::from,
);
let select_file = arg_matches
.get_one::<String>(FILE_FLAG_ID)
.map(PathBuf::from);
let repo_path = if let Some(w) = workdir {
RepoPath::Workdir { gitdir, workdir: w }
} else {
RepoPath::Path(gitdir)
};
let arg_theme = arg_matches
.get_one::<String>(THEME_FLAG_ID)
.map_or_else(|| PathBuf::from(DEFAULT_THEME), PathBuf::from);
let confpath = get_app_config_path()?;
fs::create_dir_all(&confpath).with_context(|| {
format!(
"failed to create config directory: {}",
confpath.display()
)
})?;
let theme = confpath.join(arg_theme);
let notify_watcher: bool =
*arg_matches.get_one(WATCHER_FLAG_ID).unwrap_or(&false);
let key_bindings_path = arg_matches
.get_one::<String>(KEY_BINDINGS_FLAG_ID)
.map(PathBuf::from);
let key_symbols_path = arg_matches
.get_one::<String>(KEY_SYMBOLS_FLAG_ID)
.map(PathBuf::from);
Ok(CliArgs {
theme,
select_file,
repo_path,
notify_watcher,
key_bindings_path,
key_symbols_path,
})
}
fn app() -> ClapApp {
ClapApp::new(crate_name!())
.author(crate_authors!())
.version(env!("GITUI_BUILD_NAME"))
.about(crate_description!())
.help_template(
"\
{before-help}gitui {version}
{author}
{about}
{usage-heading} {usage}
{all-args}{after-help}
",
)
.arg(
Arg::new(KEY_BINDINGS_FLAG_ID)
.help("Use a custom keybindings file")
.short('k')
.long("key-bindings")
.value_name("KEY_LIST_FILENAME")
.num_args(1),
)
.arg(
Arg::new(KEY_SYMBOLS_FLAG_ID)
.help("Use a custom symbols file")
.short('s')
.long("key-symbols")
.value_name("KEY_SYMBOLS_FILENAME")
.num_args(1),
)
.arg(
Arg::new(THEME_FLAG_ID)
.help("Set color theme filename loaded from config directory")
.short('t')
.long("theme")
.value_name("THEME_FILE")
.default_value(DEFAULT_THEME)
.num_args(1),
)
.arg(
Arg::new(LOGGING_FLAG_ID)
.help("Store logging output into a file (in the cache directory by default)")
.short('l')
.long("logging")
.default_value_if("logfile", ArgPredicate::IsPresent, "true")
.action(clap::ArgAction::SetTrue),
)
.arg(Arg::new(LOG_FILE_FLAG_ID)
.help("Store logging output into the specified file (implies --logging)")
.long("logfile")
.value_name("LOG_FILE"))
.arg(
Arg::new(WATCHER_FLAG_ID)
.help("Use notify-based file system watcher instead of tick-based update. This is more performant, but can cause issues on some platforms. See https://github.com/gitui-org/gitui/blob/master/FAQ.md#watcher for details.")
.long("watcher")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new(BUG_REPORT_FLAG_ID)
.help("Generate a bug report")
.long("bugreport")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new(FILE_FLAG_ID)
.help("Select the file in the file tab")
.short('f')
.long("file")
.num_args(1),
)
.arg(
Arg::new(GIT_DIR_FLAG_ID)
.help("Set the git directory")
.short('d')
.long("directory")
.env("GIT_DIR")
.num_args(1),
)
.arg(
Arg::new(WORKDIR_FLAG_ID)
.help("Set the working directory")
.short('w')
.long("workdir")
.env("GIT_WORK_TREE")
.num_args(1),
)
}
fn setup_logging(path_override: Option<PathBuf>) -> Result<()> {
let path = if let Some(path) = path_override {
path
} else {
let mut path = get_app_cache_path()?;
path.push("gitui.log");
path
};
println!("Logging enabled. Log written to: {}", path.display());
WriteLogger::init(
LevelFilter::Trace,
Config::default(),
File::create(path)?,
)?;
Ok(())
}
fn get_app_cache_path() -> Result<PathBuf> {
let mut path = dirs::cache_dir()
.ok_or_else(|| anyhow!("failed to find os cache dir."))?;
path.push("gitui");
fs::create_dir_all(&path).with_context(|| {
format!(
"failed to create cache directory: {}",
path.display()
)
})?;
Ok(path)
}
pub fn get_app_config_path() -> Result<PathBuf> {
let mut path = if cfg!(target_os = "macos") {
dirs::home_dir().map(|h| h.join(".config"))
} else {
dirs::config_dir()
}
.ok_or_else(|| anyhow!("failed to find os config dir."))?;
path.push("gitui");
Ok(path)
}
#[test]
fn verify_app() {
app().debug_assert();
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/watcher.rs | src/watcher.rs | use anyhow::Result;
use crossbeam_channel::{unbounded, Sender};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use notify_debouncer_mini::{new_debouncer, DebounceEventResult};
use scopetime::scope_time;
use std::{path::Path, thread, time::Duration};
pub struct RepoWatcher {
receiver: crossbeam_channel::Receiver<()>,
}
impl RepoWatcher {
pub fn new(workdir: &str) -> Self {
log::trace!(
"recommended watcher: {:?}",
RecommendedWatcher::kind()
);
let (tx, rx) = std::sync::mpsc::channel();
let workdir = workdir.to_string();
thread::spawn(move || {
let timeout = Duration::from_secs(2);
create_watcher(timeout, tx, &workdir);
});
let (out_tx, out_rx) = unbounded();
thread::spawn(move || {
if let Err(e) = Self::forwarder(&rx, &out_tx) {
//maybe we need to restart the forwarder now?
log::error!("notify receive error: {e}");
}
});
Self { receiver: out_rx }
}
///
pub fn receiver(&self) -> crossbeam_channel::Receiver<()> {
self.receiver.clone()
}
fn forwarder(
receiver: &std::sync::mpsc::Receiver<DebounceEventResult>,
sender: &Sender<()>,
) -> Result<()> {
loop {
let ev = receiver.recv()?;
if let Ok(ev) = ev {
log::debug!("notify events: {}", ev.len());
for (idx, ev) in ev.iter().enumerate() {
log::debug!("notify [{idx}]: {ev:?}");
}
if !ev.is_empty() {
sender.send(())?;
}
}
}
}
}
fn create_watcher(
timeout: Duration,
tx: std::sync::mpsc::Sender<DebounceEventResult>,
workdir: &str,
) {
scope_time!("create_watcher");
let mut bouncer =
new_debouncer(timeout, tx).expect("Watch create error");
bouncer
.watcher()
.watch(Path::new(&workdir), RecursiveMode::Recursive)
.expect("Watch error");
std::mem::forget(bouncer);
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popup_stack.rs | src/popup_stack.rs | use crate::queue::StackablePopupOpen;
#[derive(Default)]
pub struct PopupStack {
stack: Vec<StackablePopupOpen>,
}
impl PopupStack {
pub fn push(&mut self, popup: StackablePopupOpen) {
self.stack.push(popup);
}
pub fn pop(&mut self) -> Option<StackablePopupOpen> {
self.stack.pop()
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/cmdbar.rs | src/cmdbar.rs | use crate::{
components::CommandInfo, keys::SharedKeyConfig, strings,
ui::style::SharedTheme,
};
use ratatui::{
layout::{Alignment, Rect},
text::{Line, Span},
widgets::Paragraph,
Frame,
};
use std::borrow::Cow;
use unicode_width::UnicodeWidthStr;
enum DrawListEntry {
LineBreak,
Splitter,
Command(Command),
}
struct Command {
txt: String,
enabled: bool,
}
/// helper to be used while drawing
pub struct CommandBar {
draw_list: Vec<DrawListEntry>,
cmd_infos: Vec<CommandInfo>,
theme: SharedTheme,
key_config: SharedKeyConfig,
lines: u16,
width: u16,
expandable: bool,
expanded: bool,
}
const MORE_WIDTH: u16 = 9;
impl CommandBar {
pub const fn new(
theme: SharedTheme,
key_config: SharedKeyConfig,
) -> Self {
Self {
draw_list: Vec::new(),
cmd_infos: Vec::new(),
theme,
key_config,
lines: 0,
width: 0,
expandable: false,
expanded: false,
}
}
pub fn refresh_width(&mut self, width: u16) {
if width != self.width {
self.refresh_list(width);
self.width = width;
}
}
fn is_multiline(&self, width: u16) -> bool {
let mut line_width = 0_usize;
for c in &self.cmd_infos {
let entry_w =
UnicodeWidthStr::width(c.text.name.as_str());
if line_width + entry_w > width as usize {
return true;
}
line_width += entry_w + 1;
}
false
}
fn refresh_list(&mut self, width: u16) {
self.draw_list.clear();
let width = if self.is_multiline(width) {
width.saturating_sub(MORE_WIDTH)
} else {
width
};
let mut line_width = 0_usize;
let mut lines = 1_u16;
for c in &self.cmd_infos {
let entry_w =
UnicodeWidthStr::width(c.text.name.as_str());
if line_width + entry_w > width as usize {
self.draw_list.push(DrawListEntry::LineBreak);
line_width = 0;
lines += 1;
} else if line_width > 0 {
self.draw_list.push(DrawListEntry::Splitter);
}
line_width += entry_w + 1;
self.draw_list.push(DrawListEntry::Command(Command {
txt: c.text.name.clone(),
enabled: c.enabled,
}));
}
self.expandable = lines > 1;
self.lines = lines;
}
pub fn set_cmds(&mut self, cmds: Vec<CommandInfo>) {
self.cmd_infos = cmds
.into_iter()
.filter(CommandInfo::show_in_quickbar)
.collect::<Vec<_>>();
self.cmd_infos.sort_by_key(|e| e.order);
self.refresh_list(self.width);
}
pub const fn height(&self) -> u16 {
if self.expandable && self.expanded {
self.lines
} else {
1_u16
}
}
pub fn toggle_more(&mut self) {
if self.expandable {
self.expanded = !self.expanded;
}
}
pub fn draw(&self, f: &mut Frame, r: Rect) {
if r.width < MORE_WIDTH {
return;
}
let splitter = Span::raw(Cow::from(strings::cmd_splitter(
&self.key_config,
)));
let texts = self
.draw_list
.split(|c| matches!(c, DrawListEntry::LineBreak))
.map(|c_arr| {
Line::from(
c_arr
.iter()
.map(|c| match c {
DrawListEntry::Command(c) => {
Span::styled(
Cow::from(c.txt.as_str()),
self.theme.commandbar(c.enabled),
)
}
DrawListEntry::LineBreak => {
// Doesn't exist in split array
Span::raw("")
}
DrawListEntry::Splitter => {
splitter.clone()
}
})
.collect::<Vec<Span>>(),
)
})
.collect::<Vec<Line>>();
f.render_widget(
Paragraph::new(texts).alignment(Alignment::Left),
r,
);
if self.expandable {
let r = Rect::new(
r.width.saturating_sub(MORE_WIDTH),
r.y + r.height.saturating_sub(1),
MORE_WIDTH.min(r.width),
1.min(r.height),
);
f.render_widget(
Paragraph::new(Line::from(vec![Span::raw(
Cow::from(if self.expanded {
"less [.]"
} else {
"more [.]"
}),
)]))
.alignment(Alignment::Right),
r,
);
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/options.rs | src/options.rs | use anyhow::Result;
use asyncgit::sync::{
diff::DiffOptions, repo_dir, RepoPathRef,
ShowUntrackedFilesConfig,
};
use ron::{
de::from_bytes,
ser::{to_string_pretty, PrettyConfig},
};
use serde::{Deserialize, Serialize};
use std::{
cell::RefCell,
fs::File,
io::{Read, Write},
path::PathBuf,
rc::Rc,
};
#[derive(Default, Clone, Serialize, Deserialize)]
struct OptionsData {
pub tab: usize,
pub diff: DiffOptions,
pub status_show_untracked: Option<ShowUntrackedFilesConfig>,
pub commit_msgs: Vec<String>,
}
const COMMIT_MSG_HISTORY_LENGTH: usize = 20;
#[derive(Clone)]
pub struct Options {
repo: RepoPathRef,
data: OptionsData,
}
#[cfg(test)]
impl Options {
pub fn test_env() -> Self {
use asyncgit::sync::RepoPath;
Self {
repo: RefCell::new(RepoPath::Path(Default::default())),
data: Default::default(),
}
}
}
pub type SharedOptions = Rc<RefCell<Options>>;
impl Options {
pub fn new(repo: RepoPathRef) -> SharedOptions {
Rc::new(RefCell::new(Self {
data: Self::read(&repo).unwrap_or_default(),
repo,
}))
}
pub fn set_current_tab(&mut self, tab: usize) {
self.data.tab = tab;
self.save();
}
pub const fn current_tab(&self) -> usize {
self.data.tab
}
pub const fn diff_options(&self) -> DiffOptions {
self.data.diff
}
pub const fn status_show_untracked(
&self,
) -> Option<ShowUntrackedFilesConfig> {
self.data.status_show_untracked
}
pub fn set_status_show_untracked(
&mut self,
value: Option<ShowUntrackedFilesConfig>,
) {
self.data.status_show_untracked = value;
self.save();
}
pub fn diff_context_change(&mut self, increase: bool) {
self.data.diff.context = if increase {
self.data.diff.context.saturating_add(1)
} else {
self.data.diff.context.saturating_sub(1)
};
self.save();
}
pub fn diff_hunk_lines_change(&mut self, increase: bool) {
self.data.diff.interhunk_lines = if increase {
self.data.diff.interhunk_lines.saturating_add(1)
} else {
self.data.diff.interhunk_lines.saturating_sub(1)
};
self.save();
}
pub fn diff_toggle_whitespace(&mut self) {
self.data.diff.ignore_whitespace =
!self.data.diff.ignore_whitespace;
self.save();
}
pub fn add_commit_msg(&mut self, msg: &str) {
self.data.commit_msgs.push(msg.to_owned());
while self.data.commit_msgs.len() > COMMIT_MSG_HISTORY_LENGTH
{
self.data.commit_msgs.remove(0);
}
self.save();
}
pub fn has_commit_msg_history(&self) -> bool {
!self.data.commit_msgs.is_empty()
}
pub fn commit_msg(&self, idx: usize) -> Option<String> {
if self.data.commit_msgs.is_empty() {
None
} else {
let entries = self.data.commit_msgs.len();
let mut index = idx;
while index >= entries {
index -= entries;
}
index = entries.saturating_sub(1) - index;
Some(self.data.commit_msgs[index].clone())
}
}
fn save(&self) {
if let Err(e) = self.save_failable() {
log::error!("options save error: {e}");
}
}
fn read(repo: &RepoPathRef) -> Result<OptionsData> {
let dir = Self::options_file(repo)?;
let mut f = File::open(dir)?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
Ok(from_bytes(&buffer)?)
}
fn save_failable(&self) -> Result<()> {
let dir = Self::options_file(&self.repo)?;
let mut file = File::create(dir)?;
let data =
to_string_pretty(&self.data, PrettyConfig::default())?;
file.write_all(data.as_bytes())?;
Ok(())
}
fn options_file(repo: &RepoPathRef) -> Result<PathBuf> {
let dir = repo_dir(&repo.borrow())?;
let dir = dir.join("gitui");
Ok(dir)
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/strings.rs | src/strings.rs | use std::borrow::Cow;
use asyncgit::sync::CommitId;
use unicode_truncate::UnicodeTruncateStr;
use unicode_width::UnicodeWidthStr;
use crate::keys::SharedKeyConfig;
pub mod order {
pub const RARE_ACTION: i8 = 30;
pub const NAV: i8 = 20;
pub const AVERAGE: i8 = 10;
pub const PRIORITY: i8 = 1;
}
pub static PUSH_POPUP_MSG: &str = "Push";
pub static FORCE_PUSH_POPUP_MSG: &str = "Force Push";
pub static PULL_POPUP_MSG: &str = "Pull";
pub static FETCH_POPUP_MSG: &str = "Fetch";
pub static PUSH_POPUP_PROGRESS_NONE: &str = "preparing...";
pub static PUSH_POPUP_STATES_ADDING: &str = "adding objects (1/3)";
pub static PUSH_POPUP_STATES_DELTAS: &str = "deltas (2/3)";
pub static PUSH_POPUP_STATES_PUSHING: &str = "pushing (3/3)";
pub static PUSH_POPUP_STATES_TRANSFER: &str = "transfer";
pub static PUSH_POPUP_STATES_DONE: &str = "done";
pub static PUSH_TAGS_POPUP_MSG: &str = "Push Tags";
pub static PUSH_TAGS_STATES_FETCHING: &str = "fetching";
pub static PUSH_TAGS_STATES_PUSHING: &str = "pushing";
pub static PUSH_TAGS_STATES_DONE: &str = "done";
pub static POPUP_TITLE_SUBMODULES: &str = "Submodules";
pub static POPUP_TITLE_REMOTES: &str = "Remotes";
pub static POPUP_SUBTITLE_REMOTES: &str = "Details";
pub static POPUP_TITLE_FUZZY_FIND: &str = "Fuzzy Finder";
pub static POPUP_TITLE_LOG_SEARCH: &str = "Search";
pub static POPUP_FAIL_COPY: &str = "Failed to copy text";
pub static POPUP_SUCCESS_COPY: &str = "Copied Text";
pub static POPUP_COMMIT_SHA_INVALID: &str = "Invalid commit sha";
pub mod symbol {
pub const CHECKMARK: &str = "\u{2713}"; //✓
pub const SPACE: &str = "\u{02FD}"; //˽
pub const EMPTY_SPACE: &str = " ";
pub const FOLDER_ICON_COLLAPSED: &str = "\u{25b8}"; //▸
pub const FOLDER_ICON_EXPANDED: &str = "\u{25be}"; //▾
pub const EMPTY_STR: &str = "";
pub const ELLIPSIS: char = '\u{2026}'; // …
}
pub fn title_branches() -> String {
"Branches".to_string()
}
pub fn title_tags() -> String {
"Tags".to_string()
}
pub fn title_status(_key_config: &SharedKeyConfig) -> String {
"Unstaged Changes".to_string()
}
pub fn title_diff(_key_config: &SharedKeyConfig) -> String {
"Diff: ".to_string()
}
pub fn title_index(_key_config: &SharedKeyConfig) -> String {
"Staged Changes".to_string()
}
pub fn tab_status(key_config: &SharedKeyConfig) -> String {
format!(
"Status [{}]",
key_config.get_hint(key_config.keys.tab_status)
)
}
pub fn tab_log(key_config: &SharedKeyConfig) -> String {
format!("Log [{}]", key_config.get_hint(key_config.keys.tab_log))
}
pub fn tab_files(key_config: &SharedKeyConfig) -> String {
format!(
"Files [{}]",
key_config.get_hint(key_config.keys.tab_files)
)
}
pub fn tab_stashing(key_config: &SharedKeyConfig) -> String {
format!(
"Stashing [{}]",
key_config.get_hint(key_config.keys.tab_stashing)
)
}
pub fn tab_stashes(key_config: &SharedKeyConfig) -> String {
format!(
"Stashes [{}]",
key_config.get_hint(key_config.keys.tab_stashes)
)
}
pub fn tab_divider(_key_config: &SharedKeyConfig) -> String {
" | ".to_string()
}
pub fn cmd_splitter(_key_config: &SharedKeyConfig) -> String {
" ".to_string()
}
pub fn msg_opening_editor(_key_config: &SharedKeyConfig) -> String {
"opening editor...".to_string()
}
pub fn msg_title_error(_key_config: &SharedKeyConfig) -> String {
"Error".to_string()
}
pub fn msg_title_info(_key_config: &SharedKeyConfig) -> String {
"Info".to_string()
}
pub fn commit_title() -> String {
"Commit".to_string()
}
pub fn commit_reword_title() -> String {
"Reword Commit".to_string()
}
pub fn commit_title_merge() -> String {
"Commit (Merge)".to_string()
}
pub fn commit_title_revert() -> String {
"Commit (Revert)".to_string()
}
pub fn commit_title_amend() -> String {
"Commit (Amend)".to_string()
}
pub fn commit_msg(_key_config: &SharedKeyConfig) -> String {
"type commit message..".to_string()
}
pub fn commit_first_line_warning(count: usize) -> String {
format!("[subject length: {count}]")
}
pub const fn branch_name_invalid() -> &'static str {
"[invalid name]"
}
pub fn commit_editor_msg(_key_config: &SharedKeyConfig) -> String {
r"
# Edit your commit message
# Lines starting with '#' will be ignored"
.to_string()
}
pub fn stash_popup_title(_key_config: &SharedKeyConfig) -> String {
"Stash".to_string()
}
pub fn stash_popup_msg(_key_config: &SharedKeyConfig) -> String {
"type name (optional)".to_string()
}
pub fn confirm_title_reset() -> String {
"Reset".to_string()
}
pub fn confirm_title_undo_commit() -> String {
"Undo commit".to_string()
}
pub fn confirm_title_stashdrop(
_key_config: &SharedKeyConfig,
multiple: bool,
) -> String {
format!("Drop Stash{}", if multiple { "es" } else { "" })
}
pub fn confirm_title_stashpop(
_key_config: &SharedKeyConfig,
) -> String {
"Pop".to_string()
}
pub fn confirm_title_merge(
_key_config: &SharedKeyConfig,
rebase: bool,
) -> String {
if rebase {
"Merge (via rebase)".to_string()
} else {
"Merge (via commit)".to_string()
}
}
pub fn confirm_msg_merge(
_key_config: &SharedKeyConfig,
incoming: usize,
rebase: bool,
) -> String {
if rebase {
format!("Rebase onto {incoming} incoming commits?")
} else {
format!("Merge of {incoming} incoming commits?")
}
}
pub fn confirm_title_abortmerge() -> String {
"Abort merge?".to_string()
}
pub fn confirm_title_abortrevert() -> String {
"Abort revert?".to_string()
}
pub fn confirm_msg_revertchanges() -> String {
"This will revert all uncommitted changes. Are you sure?"
.to_string()
}
pub fn confirm_title_abortrebase() -> String {
"Abort rebase?".to_string()
}
pub fn confirm_msg_abortrebase() -> String {
"This will revert all uncommitted changes. Are you sure?"
.to_string()
}
pub fn confirm_msg_reset() -> String {
"confirm file reset?".to_string()
}
pub fn confirm_msg_reset_lines(lines: usize) -> String {
format!(
"are you sure you want to discard {lines} selected lines?"
)
}
pub fn confirm_msg_undo_commit() -> String {
"confirm undo last commit?".to_string()
}
pub fn confirm_msg_stashdrop(
_key_config: &SharedKeyConfig,
ids: &[CommitId],
) -> String {
format!(
"Sure you want to drop following {}stash{}?\n\n{}",
if ids.len() > 1 {
format!("{} ", ids.len())
} else {
String::default()
},
if ids.len() > 1 { "es" } else { "" },
ids.iter()
.map(CommitId::get_short_string)
.collect::<Vec<_>>()
.join(", ")
)
}
pub fn confirm_msg_stashpop(_key_config: &SharedKeyConfig) -> String {
"The stash will be applied and removed from the stash list. Confirm stash pop?"
.to_string()
}
pub fn confirm_msg_resethunk(
_key_config: &SharedKeyConfig,
) -> String {
"confirm reset hunk?".to_string()
}
pub fn confirm_title_delete_branch(
_key_config: &SharedKeyConfig,
) -> String {
"Delete Branch".to_string()
}
pub fn confirm_msg_delete_branch(
_key_config: &SharedKeyConfig,
branch_ref: &str,
) -> String {
format!("Confirm deleting branch: '{branch_ref}' ?")
}
pub fn confirm_title_delete_remote_branch(
_key_config: &SharedKeyConfig,
) -> String {
"Delete Remote Branch".to_string()
}
pub fn confirm_title_delete_remote(
_key_config: &SharedKeyConfig,
) -> String {
"Delete Remote".to_string()
}
pub fn confirm_msg_delete_remote(
_key_config: &SharedKeyConfig,
remote_name: &str,
) -> String {
format!("Confirm deleting remote \"{remote_name}\"")
}
pub fn confirm_msg_delete_remote_branch(
_key_config: &SharedKeyConfig,
branch_ref: &str,
) -> String {
format!("Confirm deleting remote branch: '{branch_ref}' ?")
}
pub fn confirm_title_delete_tag(
_key_config: &SharedKeyConfig,
) -> String {
"Delete Tag".to_string()
}
pub fn confirm_msg_delete_tag(
_key_config: &SharedKeyConfig,
tag_name: &str,
) -> String {
format!("Confirm deleting Tag: '{tag_name}' ?")
}
pub fn confirm_title_delete_tag_remote() -> String {
"Delete Tag (remote)".to_string()
}
pub fn confirm_msg_delete_tag_remote(remote_name: &str) -> String {
format!("Confirm deleting tag on remote '{remote_name}'?")
}
pub fn confirm_title_force_push(
_key_config: &SharedKeyConfig,
) -> String {
"Force Push".to_string()
}
pub fn confirm_msg_force_push(
_key_config: &SharedKeyConfig,
branch_ref: &str,
) -> String {
format!(
"Confirm force push to branch '{branch_ref}' ? This may rewrite history."
)
}
pub fn log_title(_key_config: &SharedKeyConfig) -> String {
"Commit".to_string()
}
pub fn file_log_title(
file_path: &str,
selected: usize,
revisions: usize,
) -> String {
format!("Revisions of '{file_path}' ({selected}/{revisions})")
}
pub fn blame_title(_key_config: &SharedKeyConfig) -> String {
"Blame".to_string()
}
pub fn tag_popup_name_title() -> String {
"Tag".to_string()
}
pub fn tag_popup_name_msg() -> String {
"type tag name".to_string()
}
pub fn tag_popup_annotation_title(name: &str) -> String {
format!("Tag Annotation ({name})")
}
pub fn tag_popup_annotation_msg() -> String {
"type tag annotation".to_string()
}
pub fn stashlist_title(_key_config: &SharedKeyConfig) -> String {
"Stashes".to_string()
}
pub fn help_title(_key_config: &SharedKeyConfig) -> String {
"Help: all commands".to_string()
}
pub fn stashing_files_title(_key_config: &SharedKeyConfig) -> String {
"Files to Stash".to_string()
}
pub fn stashing_options_title(
_key_config: &SharedKeyConfig,
) -> String {
"Options".to_string()
}
pub fn loading_text(_key_config: &SharedKeyConfig) -> String {
"Loading ...".to_string()
}
pub fn create_branch_popup_title(
_key_config: &SharedKeyConfig,
) -> String {
"Branch".to_string()
}
pub fn create_branch_popup_msg(
_key_config: &SharedKeyConfig,
) -> String {
"type branch name".to_string()
}
pub fn rename_remote_popup_title(
_key_config: &SharedKeyConfig,
) -> String {
"Rename remote".to_string()
}
pub fn rename_remote_popup_msg(
_key_config: &SharedKeyConfig,
) -> String {
"new remote name".to_string()
}
pub fn update_remote_url_popup_title(
_key_config: &SharedKeyConfig,
) -> String {
"Update url".to_string()
}
pub fn update_remote_url_popup_msg(
_key_config: &SharedKeyConfig,
) -> String {
"new remote url".to_string()
}
pub fn create_remote_popup_title_name(
_key_config: &SharedKeyConfig,
) -> String {
"Remote name".to_string()
}
pub fn create_remote_popup_title_url(
_key_config: &SharedKeyConfig,
) -> String {
"Remote url".to_string()
}
pub fn create_remote_popup_msg_name(
_key_config: &SharedKeyConfig,
) -> String {
"type remote name".to_string()
}
pub fn create_remote_popup_msg_url(
_key_config: &SharedKeyConfig,
) -> String {
"type remote url".to_string()
}
pub const fn remote_name_invalid() -> &'static str {
"[invalid name]"
}
pub fn username_popup_title(_key_config: &SharedKeyConfig) -> String {
"Username".to_string()
}
pub fn username_popup_msg(_key_config: &SharedKeyConfig) -> String {
"type username".to_string()
}
pub fn password_popup_title(_key_config: &SharedKeyConfig) -> String {
"Password".to_string()
}
pub fn password_popup_msg(_key_config: &SharedKeyConfig) -> String {
"type password".to_string()
}
pub fn rename_branch_popup_title(
_key_config: &SharedKeyConfig,
) -> String {
"Rename Branch".to_string()
}
pub fn rename_branch_popup_msg(
_key_config: &SharedKeyConfig,
) -> String {
"new branch name".to_string()
}
pub fn copy_success(s: &str) -> String {
format!("{POPUP_SUCCESS_COPY} \"{s}\"")
}
pub fn ellipsis_trim_start(s: &str, width: usize) -> Cow<'_, str> {
if s.width() <= width {
Cow::Borrowed(s)
} else {
Cow::Owned(format!(
"[{}]{}",
symbol::ELLIPSIS,
s.unicode_truncate_start(
width.saturating_sub(3 /* front indicator */)
)
.0
))
}
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum CheckoutOptions {
KeepLocalChanges,
DiscardAllLocalChagnes,
}
impl CheckoutOptions {
pub const fn previous(self) -> Self {
match self {
Self::KeepLocalChanges => Self::DiscardAllLocalChagnes,
Self::DiscardAllLocalChagnes => Self::KeepLocalChanges,
}
}
pub const fn next(self) -> Self {
match self {
Self::KeepLocalChanges => Self::DiscardAllLocalChagnes,
Self::DiscardAllLocalChagnes => Self::KeepLocalChanges,
}
}
pub const fn to_string_pair(
self,
) -> (&'static str, &'static str) {
const CHECKOUT_OPTION_UNCHANGE: &str =
" 🟡 Keep local changes";
const CHECKOUT_OPTION_DISCARD: &str =
" 🔴 Discard all local changes";
match self {
Self::KeepLocalChanges => {
("Don't change", CHECKOUT_OPTION_UNCHANGE)
}
Self::DiscardAllLocalChagnes => {
("Discard", CHECKOUT_OPTION_DISCARD)
}
}
}
}
pub mod commit {
use crate::keys::SharedKeyConfig;
pub fn details_author() -> String {
"Author: ".to_string()
}
pub fn details_committer() -> String {
"Committer: ".to_string()
}
pub fn details_sha() -> String {
"Sha: ".to_string()
}
pub fn details_date() -> String {
"Date: ".to_string()
}
pub fn details_tags() -> String {
"Tags: ".to_string()
}
pub fn details_message() -> String {
"Subject: ".to_string()
}
pub fn details_info_title(
_key_config: &SharedKeyConfig,
) -> String {
"Info".to_string()
}
pub fn compare_details_info_title(
old: bool,
hash: &str,
) -> String {
format!("{}: {hash}", if old { "Old" } else { "New" })
}
pub fn details_message_title(
_key_config: &SharedKeyConfig,
) -> String {
"Message".to_string()
}
pub fn details_files_title(
_key_config: &SharedKeyConfig,
) -> String {
"Files:".to_string()
}
}
pub mod commands {
use crate::components::CommandText;
use crate::keys::SharedKeyConfig;
static CMD_GROUP_GENERAL: &str = "-- General --";
static CMD_GROUP_DIFF: &str = "-- Diff --";
static CMD_GROUP_CHANGES: &str = "-- Changes --";
static CMD_GROUP_COMMIT_POPUP: &str = "-- Commit Popup --";
static CMD_GROUP_STASHING: &str = "-- Stashing --";
static CMD_GROUP_STASHES: &str = "-- Stashes --";
static CMD_GROUP_LOG: &str = "-- Log --";
static CMD_GROUP_BRANCHES: &str = "-- Branches --";
pub fn toggle_tabs(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Next [{}]",
key_config.get_hint(key_config.keys.tab_toggle)
),
"switch to next tab",
CMD_GROUP_GENERAL,
)
}
pub fn find_file(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Find [{}]",
key_config.get_hint(key_config.keys.file_find)
),
"find file in tree",
CMD_GROUP_GENERAL,
)
}
pub fn find_branch(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Find [{}]",
key_config.get_hint(key_config.keys.branch_find)
),
"find branch in list",
CMD_GROUP_GENERAL,
)
}
pub fn toggle_tabs_direct(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Tab [{}{}{}{}{}]",
key_config.get_hint(key_config.keys.tab_status),
key_config.get_hint(key_config.keys.tab_log),
key_config.get_hint(key_config.keys.tab_files),
key_config.get_hint(key_config.keys.tab_stashing),
key_config.get_hint(key_config.keys.tab_stashes),
),
"switch top level tabs directly",
CMD_GROUP_GENERAL,
)
}
pub fn options_popup(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Options [{}]",
key_config.get_hint(key_config.keys.open_options),
),
"open options popup",
CMD_GROUP_GENERAL,
)
}
pub fn help_open(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Help [{}]",
key_config.get_hint(key_config.keys.open_help)
),
"open this help screen",
CMD_GROUP_GENERAL,
)
}
pub fn navigate_commit_message(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Nav [{}{}]",
key_config.get_hint(key_config.keys.move_up),
key_config.get_hint(key_config.keys.move_down)
),
"navigate commit message",
CMD_GROUP_GENERAL,
)
}
pub fn navigate_tree(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Nav [{}{}{}{}]",
key_config.get_hint(key_config.keys.move_up),
key_config.get_hint(key_config.keys.move_down),
key_config.get_hint(key_config.keys.move_right),
key_config.get_hint(key_config.keys.move_left)
),
"navigate tree view, collapse, expand",
CMD_GROUP_GENERAL,
)
}
pub fn scroll(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Scroll [{}{}]",
key_config.get_hint(key_config.keys.move_up),
key_config.get_hint(key_config.keys.move_down)
),
"scroll up or down in focused view",
CMD_GROUP_GENERAL,
)
}
pub fn commit_list_mark(
key_config: &SharedKeyConfig,
marked: bool,
) -> CommandText {
CommandText::new(
format!(
"{} [{}]",
if marked { "Unmark" } else { "Mark" },
key_config.get_hint(key_config.keys.log_mark_commit),
),
"mark multiple commits",
CMD_GROUP_GENERAL,
)
}
pub fn copy(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Copy [{}]",
key_config.get_hint(key_config.keys.copy),
),
"copy selected lines to clipboard",
CMD_GROUP_DIFF,
)
}
pub fn copy_hash(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Copy Hash [{}]",
key_config.get_hint(key_config.keys.copy),
),
"copy selected commit hash to clipboard",
CMD_GROUP_LOG,
)
}
pub fn copy_path(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Copy Path [{}]",
key_config.get_hint(key_config.keys.copy),
),
"copy selected file path to clipboard",
CMD_GROUP_LOG,
)
}
pub fn push_tags(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Push Tags [{}]",
key_config.get_hint(key_config.keys.push),
),
"push tags to remote",
CMD_GROUP_LOG,
)
}
pub fn toggle_option(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Toggle Option [{}]",
key_config.get_hint(key_config.keys.log_mark_commit),
),
"toggle search option selected",
CMD_GROUP_LOG,
)
}
pub fn show_tag_annotation(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Annotation [{}]",
key_config.get_hint(key_config.keys.move_right),
),
"show tag annotation",
CMD_GROUP_LOG,
)
}
pub fn diff_hunk_next(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Next hunk [{}]",
key_config.get_hint(key_config.keys.diff_hunk_next),
),
"move cursor to next hunk",
CMD_GROUP_DIFF,
)
}
pub fn diff_hunk_prev(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Prev hunk [{}]",
key_config.get_hint(key_config.keys.diff_hunk_prev),
),
"move cursor to prev hunk",
CMD_GROUP_DIFF,
)
}
pub fn diff_home_end(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Jump up/down [{},{},{},{}]",
key_config.get_hint(key_config.keys.home),
key_config.get_hint(key_config.keys.end),
key_config.get_hint(key_config.keys.move_up),
key_config.get_hint(key_config.keys.move_down)
),
"scroll to top or bottom of diff",
CMD_GROUP_DIFF,
)
}
pub fn diff_hunk_add(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Add hunk [{}]",
key_config
.get_hint(key_config.keys.stage_unstage_item),
),
"adds selected hunk to stage",
CMD_GROUP_DIFF,
)
}
pub fn diff_hunk_revert(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Reset hunk [{}]",
key_config
.get_hint(key_config.keys.status_reset_item),
),
"reverts selected hunk",
CMD_GROUP_DIFF,
)
}
pub fn diff_lines_revert(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Reset lines [{}]",
key_config.get_hint(key_config.keys.diff_reset_lines),
),
"resets selected lines",
CMD_GROUP_DIFF,
)
}
pub fn diff_lines_stage(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Stage lines [{}]",
key_config.get_hint(key_config.keys.diff_stage_lines),
),
"stage selected lines",
CMD_GROUP_DIFF,
)
}
pub fn diff_lines_unstage(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Unstage lines [{}]",
key_config.get_hint(key_config.keys.diff_stage_lines),
),
"unstage selected lines",
CMD_GROUP_DIFF,
)
}
pub fn diff_hunk_remove(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Remove hunk [{}]",
key_config
.get_hint(key_config.keys.stage_unstage_item),
),
"removes selected hunk from stage",
CMD_GROUP_DIFF,
)
}
pub fn close_fuzzy_finder(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Close [{}{}]",
key_config.get_hint(key_config.keys.exit_popup),
key_config.get_hint(key_config.keys.enter),
),
"close fuzzy finder",
CMD_GROUP_GENERAL,
)
}
pub fn close_popup(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Close [{}]",
key_config.get_hint(key_config.keys.exit_popup),
),
"close overlay (e.g commit, help)",
CMD_GROUP_GENERAL,
)
}
pub fn scroll_popup(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Scroll [{}{}]",
key_config.get_hint(key_config.keys.popup_down),
key_config.get_hint(key_config.keys.popup_up),
),
"scroll up or down in popup",
CMD_GROUP_GENERAL,
)
}
pub fn close_msg(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Close [{}]",
key_config.get_hint(key_config.keys.enter),
),
"close msg popup (e.g msg)",
CMD_GROUP_GENERAL,
)
.hide_help()
}
pub fn validate_msg(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Validate [{}]",
key_config.get_hint(key_config.keys.enter),
),
"validate msg",
CMD_GROUP_GENERAL,
)
.hide_help()
}
pub fn abort_merge(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Abort merge [{}]",
key_config.get_hint(key_config.keys.abort_merge),
),
"abort ongoing merge",
CMD_GROUP_GENERAL,
)
}
pub fn abort_revert(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Abort revert [{}]",
key_config.get_hint(key_config.keys.abort_merge),
),
"abort ongoing revert",
CMD_GROUP_GENERAL,
)
}
pub fn view_submodules(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Submodules [{}]",
key_config.get_hint(key_config.keys.view_submodules),
),
"open submodule view",
CMD_GROUP_GENERAL,
)
}
pub fn view_remotes(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Remotes [{}]",
key_config.get_hint(key_config.keys.view_remotes)
),
"open remotes view",
CMD_GROUP_GENERAL,
)
}
pub fn update_remote_name(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Edit name [{}]",
key_config
.get_hint(key_config.keys.update_remote_name)
),
"updates a remote name",
CMD_GROUP_GENERAL,
)
}
pub fn update_remote_url(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Edit url [{}]",
key_config
.get_hint(key_config.keys.update_remote_url)
),
"updates a remote url",
CMD_GROUP_GENERAL,
)
}
pub fn create_remote(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Add [{}]",
key_config.get_hint(key_config.keys.add_remote)
),
"creates a new remote",
CMD_GROUP_GENERAL,
)
}
pub fn delete_remote_popup(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Remove [{}]",
key_config.get_hint(key_config.keys.delete_remote),
),
"remove a remote",
CMD_GROUP_BRANCHES,
)
}
pub fn remote_confirm_name_msg(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Confirm name [{}]",
key_config.get_hint(key_config.keys.enter),
),
"confirm remote name",
CMD_GROUP_BRANCHES,
)
.hide_help()
}
pub fn remote_confirm_url_msg(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Confirm url [{}]",
key_config.get_hint(key_config.keys.enter),
),
"confirm remote url",
CMD_GROUP_BRANCHES,
)
.hide_help()
}
pub fn open_submodule(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Open [{}]",
key_config.get_hint(key_config.keys.enter),
),
"open submodule",
CMD_GROUP_GENERAL,
)
}
pub fn open_submodule_parent(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Open Parent [{}]",
key_config
.get_hint(key_config.keys.view_submodule_parent),
),
"open submodule parent repo",
CMD_GROUP_GENERAL,
)
}
pub fn update_submodule(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Update [{}]",
key_config.get_hint(key_config.keys.update_submodule),
),
"update submodule",
CMD_GROUP_GENERAL,
)
}
pub fn continue_rebase(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Continue rebase [{}]",
key_config.get_hint(key_config.keys.rebase_branch),
),
"continue ongoing rebase",
CMD_GROUP_GENERAL,
)
}
pub fn abort_rebase(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Abort rebase [{}]",
key_config.get_hint(key_config.keys.abort_merge),
),
"abort ongoing rebase",
CMD_GROUP_GENERAL,
)
}
pub fn select_staging(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"To stage [{}]",
key_config.get_hint(key_config.keys.toggle_workarea),
),
"focus/select staging area",
CMD_GROUP_GENERAL,
)
}
pub fn select_unstaged(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"To unstaged [{}]",
key_config.get_hint(key_config.keys.toggle_workarea),
),
"focus/select unstaged area",
CMD_GROUP_GENERAL,
)
}
pub fn undo_commit(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Undo Commit [{}]",
key_config.get_hint(key_config.keys.undo_commit),
),
"undo last commit",
CMD_GROUP_GENERAL,
)
}
pub fn commit_open(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Commit [{}]",
key_config.get_hint(key_config.keys.open_commit),
),
"open commit popup (available in non-empty stage)",
CMD_GROUP_GENERAL,
)
}
pub fn commit_open_editor(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Open editor [{}]",
key_config
.get_hint(key_config.keys.open_commit_editor),
),
"open commit editor (available in commit popup)",
CMD_GROUP_COMMIT_POPUP,
)
}
pub fn commit_next_msg_from_history(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Previous Msg [{}]",
key_config
.get_hint(key_config.keys.commit_history_next),
),
"use previous commit message from history",
CMD_GROUP_COMMIT_POPUP,
)
}
pub fn commit_submit(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Do Commit [{}]",
key_config.get_hint(key_config.keys.commit),
),
"commit (available when commit message is non-empty)",
CMD_GROUP_COMMIT_POPUP,
)
.hide_help()
}
pub fn newline(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"New line [{}]",
key_config.get_hint(key_config.keys.newline),
),
"create line break",
CMD_GROUP_COMMIT_POPUP,
)
.hide_help()
}
pub fn toggle_verify(
key_config: &SharedKeyConfig,
current_verify: bool,
) -> CommandText {
let verb = if current_verify { "disable" } else { "enable" };
CommandText::new(
format!(
"{} hooks [{}]",
verb,
key_config.get_hint(key_config.keys.toggle_verify),
),
"toggle running on commit hooks (available in commit popup)",
CMD_GROUP_COMMIT_POPUP,
)
}
pub fn commit_amend(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Amend [{}]",
key_config.get_hint(key_config.keys.commit_amend),
),
"amend last commit (available in commit popup)",
CMD_GROUP_COMMIT_POPUP,
)
}
pub fn commit_signoff(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Sign-off [{}]",
key_config.get_hint(key_config.keys.toggle_signoff),
),
"sign-off commit (-s option)",
CMD_GROUP_COMMIT_POPUP,
)
}
pub fn edit_item(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Edit [{}]",
key_config.get_hint(key_config.keys.edit_file),
),
"edit the currently selected file in an external editor",
CMD_GROUP_CHANGES,
)
}
pub fn stage_item(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Stage [{}]",
key_config
.get_hint(key_config.keys.stage_unstage_item),
),
"stage currently selected file or entire path",
CMD_GROUP_CHANGES,
)
}
pub fn stage_all(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Stage All [{}]",
key_config.get_hint(key_config.keys.status_stage_all),
),
"stage all changes (in unstaged files)",
CMD_GROUP_CHANGES,
)
}
pub fn unstage_item(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Unstage [{}]",
key_config
.get_hint(key_config.keys.stage_unstage_item),
),
"unstage currently selected file or entire path",
CMD_GROUP_CHANGES,
)
}
pub fn unstage_all(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Unstage all [{}]",
key_config.get_hint(key_config.keys.status_stage_all),
),
"unstage all files (in staged files)",
CMD_GROUP_CHANGES,
)
}
pub fn reset_item(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Reset [{}]",
key_config
.get_hint(key_config.keys.status_reset_item),
),
"revert changes in selected file or entire path",
CMD_GROUP_CHANGES,
)
}
pub fn ignore_item(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Ignore [{}]",
key_config
.get_hint(key_config.keys.status_ignore_file),
),
"Add file or path to .gitignore",
CMD_GROUP_CHANGES,
)
}
pub fn diff_focus_left(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Back [{}]",
key_config.get_hint(key_config.keys.move_left),
),
"view and select changed files",
CMD_GROUP_GENERAL,
)
}
pub fn diff_focus_right(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Diff [{}]",
key_config.get_hint(key_config.keys.move_right),
),
"inspect file diff",
CMD_GROUP_GENERAL,
)
}
pub fn quit(key_config: &SharedKeyConfig) -> CommandText {
CommandText::new(
format!(
"Quit [{}]",
key_config.get_hint(key_config.keys.exit),
),
"quit gitui application",
CMD_GROUP_GENERAL,
)
}
pub fn confirm_action(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Confirm [{}]",
key_config.get_hint(key_config.keys.enter),
),
"confirm action",
CMD_GROUP_GENERAL,
)
}
pub fn stashing_save(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Save [{}]",
key_config.get_hint(key_config.keys.stashing_save),
),
"opens stash name input popup",
CMD_GROUP_STASHING,
)
}
pub fn stashing_toggle_indexed(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Toggle Staged [{}]",
key_config
.get_hint(key_config.keys.stashing_toggle_index),
),
"toggle including staged files into stash",
CMD_GROUP_STASHING,
)
}
pub fn stashing_toggle_untracked(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Toggle Untracked [{}]",
key_config.get_hint(
key_config.keys.stashing_toggle_untracked
),
),
"toggle including untracked files into stash",
CMD_GROUP_STASHING,
)
}
pub fn stashing_confirm_msg(
key_config: &SharedKeyConfig,
) -> CommandText {
CommandText::new(
format!(
"Stash [{}]",
key_config.get_hint(key_config.keys.enter),
),
"save files to stash",
CMD_GROUP_STASHING,
)
}
pub fn stashlist_apply(
key_config: &SharedKeyConfig,
) -> CommandText {
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | true |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/main.rs | src/main.rs | //!
//! The gitui program is a text-based UI for working with a Git repository.
//! The main navigation occurs between a number of tabs.
//! When you execute commands, the program may use popups to communicate
//! with the user. It is possible to customize the keybindings.
//!
//!
//! ## Internal Modules
//! The top-level modules of gitui can be grouped as follows:
//!
//! - User Interface
//! - [tabs] for main navigation
//! - [components] for visual elements used on tabs
//! - [popups] for temporary dialogs
//! - [ui] for tooling like scrollbars
//! - Git Interface
//! - [asyncgit] (crate) for async operations on repository
//! - Distribution and Documentation
//! - Project files
//! - Github CI
//! - Installation files
//! - Usage guides
//!
//! ## Included Crates
//! Some crates are part of the gitui repository:
//! - [asyncgit] for Git operations in the background.
//! - git2-hooks (used by asyncgit).
//! - git2-testing (used by git2-hooks).
//! - invalidstring used by asyncgit for testing with invalid strings.
//! - [filetreelist] for a tree view of files.
//! - [scopetime] for measuring execution time.
//!
#![forbid(unsafe_code)]
#![deny(
mismatched_lifetime_syntaxes,
unused_imports,
unused_must_use,
dead_code,
unstable_name_collisions,
unused_assignments
)]
#![deny(clippy::all, clippy::perf, clippy::nursery, clippy::pedantic)]
#![deny(
clippy::unwrap_used,
clippy::filetype_is_file,
clippy::cargo,
clippy::panic,
clippy::match_like_matches_macro
)]
#![allow(
clippy::multiple_crate_versions,
clippy::bool_to_int_with_if,
clippy::module_name_repetitions,
clippy::empty_docs,
clippy::unnecessary_debug_formatting
)]
//TODO:
// #![deny(clippy::expect_used)]
mod app;
mod args;
mod bug_report;
mod clipboard;
mod cmdbar;
mod components;
mod input;
mod keys;
mod notify_mutex;
mod options;
mod popup_stack;
mod popups;
mod queue;
mod spinner;
mod string_utils;
mod strings;
mod tabs;
mod ui;
mod watcher;
use crate::{
app::App,
args::{process_cmdline, CliArgs},
};
use anyhow::{anyhow, bail, Result};
use app::QuitState;
use asyncgit::{
sync::{utils::repo_work_dir, RepoPath},
AsyncGitNotification,
};
use backtrace::Backtrace;
use crossbeam_channel::{never, tick, unbounded, Receiver, Select};
use crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen,
LeaveAlternateScreen,
},
ExecutableCommand,
};
use input::{Input, InputEvent, InputState};
use keys::KeyConfig;
use ratatui::backend::CrosstermBackend;
use scopeguard::defer;
use scopetime::scope_time;
use spinner::Spinner;
use std::{
io::{self, Stdout},
panic,
path::Path,
time::{Duration, Instant},
};
use ui::style::Theme;
use watcher::RepoWatcher;
type Terminal = ratatui::Terminal<CrosstermBackend<io::Stdout>>;
static TICK_INTERVAL: Duration = Duration::from_secs(5);
static SPINNER_INTERVAL: Duration = Duration::from_millis(80);
///
#[derive(Clone)]
pub enum QueueEvent {
Tick,
Notify,
SpinnerUpdate,
AsyncEvent(AsyncNotification),
InputEvent(InputEvent),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SyntaxHighlightProgress {
Progress,
Done,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsyncAppNotification {
///
SyntaxHighlighting(SyntaxHighlightProgress),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsyncNotification {
///
App(AsyncAppNotification),
///
Git(AsyncGitNotification),
}
#[derive(Clone, Copy, PartialEq)]
enum Updater {
Ticker,
NotifyWatcher,
}
/// Do `log::error!` and `eprintln!` in one line.
macro_rules! log_eprintln {
( $($arg:tt)* ) => {{
log::error!($($arg)*);
eprintln!($($arg)*);
}};
}
fn main() -> Result<()> {
let app_start = Instant::now();
let cliargs = process_cmdline()?;
asyncgit::register_tracing_logging();
ensure_valid_path(&cliargs.repo_path)?;
let key_config = KeyConfig::init(
cliargs.key_bindings_path.as_ref(),
cliargs.key_symbols_path.as_ref(),
)
.map_err(|e| log_eprintln!("KeyConfig loading error: {e}"))
.unwrap_or_default();
let theme = Theme::init(&cliargs.theme);
setup_terminal()?;
defer! {
shutdown_terminal();
}
set_panic_handler()?;
let mut terminal =
start_terminal(io::stdout(), &cliargs.repo_path)?;
let input = Input::new();
let updater = if cliargs.notify_watcher {
Updater::NotifyWatcher
} else {
Updater::Ticker
};
let mut args = cliargs;
loop {
let quit_state = run_app(
app_start,
args.clone(),
theme.clone(),
key_config.clone(),
&input,
updater,
&mut terminal,
)?;
match quit_state {
QuitState::OpenSubmodule(p) => {
args = CliArgs {
repo_path: p,
select_file: None,
theme: args.theme,
notify_watcher: args.notify_watcher,
key_bindings_path: args.key_bindings_path,
key_symbols_path: args.key_symbols_path,
}
}
_ => break,
}
}
Ok(())
}
fn run_app(
app_start: Instant,
cliargs: CliArgs,
theme: Theme,
key_config: KeyConfig,
input: &Input,
updater: Updater,
terminal: &mut Terminal,
) -> Result<QuitState, anyhow::Error> {
let (tx_git, rx_git) = unbounded();
let (tx_app, rx_app) = unbounded();
let rx_input = input.receiver();
let (rx_ticker, rx_watcher) = match updater {
Updater::NotifyWatcher => {
let repo_watcher = RepoWatcher::new(
repo_work_dir(&cliargs.repo_path)?.as_str(),
);
(never(), repo_watcher.receiver())
}
Updater::Ticker => (tick(TICK_INTERVAL), never()),
};
let spinner_ticker = tick(SPINNER_INTERVAL);
let mut app = App::new(
cliargs,
tx_git,
tx_app,
input.clone(),
theme,
key_config,
)?;
let mut spinner = Spinner::default();
let mut first_update = true;
log::trace!("app start: {} ms", app_start.elapsed().as_millis());
loop {
let event = if first_update {
first_update = false;
QueueEvent::Notify
} else {
select_event(
&rx_input,
&rx_git,
&rx_app,
&rx_ticker,
&rx_watcher,
&spinner_ticker,
)?
};
{
if matches!(event, QueueEvent::SpinnerUpdate) {
spinner.update();
spinner.draw(terminal)?;
continue;
}
scope_time!("loop");
match event {
QueueEvent::InputEvent(ev) => {
if matches!(
ev,
InputEvent::State(InputState::Polling)
) {
//Note: external ed closed, we need to re-hide cursor
terminal.hide_cursor()?;
}
app.event(ev)?;
}
QueueEvent::Tick | QueueEvent::Notify => {
app.update()?;
}
QueueEvent::AsyncEvent(ev) => {
if !matches!(
ev,
AsyncNotification::Git(
AsyncGitNotification::FinishUnchanged
)
) {
app.update_async(ev)?;
}
}
QueueEvent::SpinnerUpdate => unreachable!(),
}
draw(terminal, &app)?;
spinner.set_state(app.any_work_pending());
spinner.draw(terminal)?;
if app.is_quit() {
break;
}
}
}
Ok(app.quit_state())
}
fn setup_terminal() -> Result<()> {
enable_raw_mode()?;
io::stdout().execute(EnterAlternateScreen)?;
Ok(())
}
fn shutdown_terminal() {
let leave_screen =
io::stdout().execute(LeaveAlternateScreen).map(|_f| ());
if let Err(e) = leave_screen {
log::error!("leave_screen failed:\n{e}");
}
let leave_raw_mode = disable_raw_mode();
if let Err(e) = leave_raw_mode {
log::error!("leave_raw_mode failed:\n{e}");
}
}
fn draw(terminal: &mut Terminal, app: &App) -> io::Result<()> {
if app.requires_redraw() {
terminal.clear()?;
}
terminal.draw(|f| {
if let Err(e) = app.draw(f) {
log::error!("failed to draw: {e:?}");
}
})?;
Ok(())
}
fn ensure_valid_path(repo_path: &RepoPath) -> Result<()> {
match asyncgit::sync::repo_open_error(repo_path) {
Some(e) => {
log::error!("invalid repo path: {e}");
bail!("invalid repo path: {e}")
}
None => Ok(()),
}
}
fn select_event(
rx_input: &Receiver<InputEvent>,
rx_git: &Receiver<AsyncGitNotification>,
rx_app: &Receiver<AsyncAppNotification>,
rx_ticker: &Receiver<Instant>,
rx_notify: &Receiver<()>,
rx_spinner: &Receiver<Instant>,
) -> Result<QueueEvent> {
let mut sel = Select::new();
sel.recv(rx_input);
sel.recv(rx_git);
sel.recv(rx_app);
sel.recv(rx_ticker);
sel.recv(rx_notify);
sel.recv(rx_spinner);
let oper = sel.select();
let index = oper.index();
let ev = match index {
0 => oper.recv(rx_input).map(QueueEvent::InputEvent),
1 => oper.recv(rx_git).map(|e| {
QueueEvent::AsyncEvent(AsyncNotification::Git(e))
}),
2 => oper.recv(rx_app).map(|e| {
QueueEvent::AsyncEvent(AsyncNotification::App(e))
}),
3 => oper.recv(rx_ticker).map(|_| QueueEvent::Notify),
4 => oper.recv(rx_notify).map(|()| QueueEvent::Notify),
5 => oper.recv(rx_spinner).map(|_| QueueEvent::SpinnerUpdate),
_ => bail!("unknown select source"),
}?;
Ok(ev)
}
fn start_terminal(
buf: Stdout,
repo_path: &RepoPath,
) -> Result<Terminal> {
let mut path = repo_path.gitpath().canonicalize()?;
let home = dirs::home_dir().ok_or_else(|| {
anyhow!("failed to find the home directory")
})?;
if path.starts_with(&home) {
let relative_part = path
.strip_prefix(&home)
.expect("can't fail because of the if statement");
path = Path::new("~").join(relative_part);
}
let mut backend = CrosstermBackend::new(buf);
backend.execute(crossterm::terminal::SetTitle(format!(
"gitui ({})",
path.display()
)))?;
let mut terminal = Terminal::new(backend)?;
terminal.hide_cursor()?;
terminal.clear()?;
Ok(terminal)
}
fn set_panic_handler() -> Result<()> {
panic::set_hook(Box::new(|e| {
let backtrace = Backtrace::new();
shutdown_terminal();
log_eprintln!("\nGitUI was closed due to an unexpected panic.\nPlease file an issue on https://github.com/gitui-org/gitui/issues with the following info:\n\n{e}\n\ntrace:\n{backtrace:?}");
}));
// global threadpool
rayon_core::ThreadPoolBuilder::new()
.num_threads(4)
.build_global()?;
Ok(())
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/notify_mutex.rs | src/notify_mutex.rs | use std::sync::{Arc, Condvar, Mutex};
/// combines a `Mutex` and `Condvar` to allow waiting for a change in the variable protected by the `Mutex`
#[derive(Clone, Debug)]
pub struct NotifiableMutex<T>
where
T: Send + Sync,
{
data: Arc<(Mutex<T>, Condvar)>,
}
impl<T> NotifiableMutex<T>
where
T: Send + Sync,
{
///
pub fn new(start_value: T) -> Self {
Self {
data: Arc::new((Mutex::new(start_value), Condvar::new())),
}
}
///
pub fn wait(&self, condition: T)
where
T: PartialEq + Copy,
{
let mut data = self.data.0.lock().expect("lock err");
while *data != condition {
data = self.data.1.wait(data).expect("wait err");
}
drop(data);
}
///
pub fn set_and_notify(&self, value: T) {
*self.data.0.lock().expect("set err") = value;
self.data.1.notify_one();
}
///
pub fn get(&self) -> T
where
T: Copy,
{
*self.data.0.lock().expect("get err")
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/spinner.rs | src/spinner.rs | use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use std::{cell::Cell, char, io};
// static SPINNER_CHARS: &[char] = &['◢', '◣', '◤', '◥'];
// static SPINNER_CHARS: &[char] = &['⢹', '⢺', '⢼', '⣸', '⣇', '⡧', '⡗', '⡏'];
static SPINNER_CHARS: &[char] =
&['⣷', '⣯', '⣟', '⡿', '⢿', '⣻', '⣽', '⣾'];
///
pub struct Spinner {
idx: usize,
active: bool,
last_char: Cell<char>,
}
impl Default for Spinner {
fn default() -> Self {
Self {
idx: 0,
active: false,
last_char: Cell::new(' '),
}
}
}
impl Spinner {
/// increment spinner graphic by one
pub fn update(&mut self) {
self.idx += 1;
self.idx %= SPINNER_CHARS.len();
}
///
pub fn set_state(&mut self, active: bool) {
self.active = active;
}
/// draws or removes spinner char depending on `pending` state
pub fn draw(
&self,
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
) -> io::Result<()> {
let idx = self.idx;
let char_to_draw =
if self.active { SPINNER_CHARS[idx] } else { ' ' };
if self.last_char.get() != char_to_draw {
self.last_char.set(char_to_draw);
let c = ratatui::buffer::Cell::default()
.set_char(char_to_draw)
.clone();
terminal
.backend_mut()
.draw(vec![(0_u16, 0_u16, &c)].into_iter())?;
Backend::flush(terminal.backend_mut())?;
}
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/queue.rs | src/queue.rs | use crate::{
components::FuzzyFinderTarget,
popups::{
AppOption, BlameFileOpen, FileRevOpen, FileTreeOpen,
InspectCommitOpen,
},
tabs::StashingOptions,
};
use asyncgit::{
sync::{
diff::DiffLinePosition, BranchInfo, CommitId,
LogFilterSearchOptions,
},
PushType,
};
use bitflags::bitflags;
use std::{
cell::RefCell, collections::VecDeque, path::PathBuf, rc::Rc,
};
bitflags! {
/// flags defining what part of the app need to update
pub struct NeedsUpdate: u32 {
/// app::update
const ALL = 0b001;
/// diff may have changed (app::update_diff)
const DIFF = 0b010;
/// commands might need updating (app::update_commands)
const COMMANDS = 0b100;
/// branches have changed
const BRANCHES = 0b1000;
/// Remotes have changed
const REMOTES = 0b1001;
}
}
/// data of item that is supposed to be reset
pub struct ResetItem {
/// path to the item (folder/file)
pub path: String,
}
///
pub enum Action {
Reset(ResetItem),
ResetHunk(String, u64),
ResetLines(String, Vec<DiffLinePosition>),
StashDrop(Vec<CommitId>),
StashPop(CommitId),
DeleteLocalBranch(String),
DeleteRemoteBranch(String),
DeleteTag(String),
DeleteRemoteTag(String, String),
DeleteRemote(String),
ForcePush(String, bool),
PullMerge { incoming: usize, rebase: bool },
AbortMerge,
AbortRebase,
AbortRevert,
UndoCommit,
}
#[derive(Debug)]
pub enum StackablePopupOpen {
///
BlameFile(BlameFileOpen),
///
FileRevlog(FileRevOpen),
///
FileTree(FileTreeOpen),
///
InspectCommit(InspectCommitOpen),
///
CompareCommits(InspectCommitOpen),
}
pub enum AppTabs {
Status,
Log,
Files,
Stashing,
Stashlist,
}
///
pub enum InternalEvent {
///
ConfirmAction(Action),
///
ConfirmedAction(Action),
///
ShowErrorMsg(String),
///
ShowInfoMsg(String),
///
Update(NeedsUpdate),
///
StatusLastFileMoved,
/// open commit msg input
OpenCommit,
///
PopupStashing(StashingOptions),
///
TabSwitchStatus,
///
TabSwitch(AppTabs),
///
SelectCommitInRevlog(CommitId),
///
TagCommit(CommitId),
///
Tags,
///
CreateBranch,
///
RenameRemote(String),
///
UpdateRemoteUrl(String, String),
///
RenameBranch(String, String),
///
SelectBranch,
///
OpenExternalEditor(Option<String>),
///
Push(String, PushType, bool, bool),
///
Pull(String),
///
PushTags,
///
OptionSwitched(AppOption),
///
OpenFuzzyFinder(Vec<String>, FuzzyFinderTarget),
///
OpenLogSearchPopup,
///
FuzzyFinderChanged(usize, String, FuzzyFinderTarget),
///
FetchRemotes,
///
OpenPopup(StackablePopupOpen),
///
PopupStackPop,
///
PopupStackPush(StackablePopupOpen),
///
ViewSubmodules,
///
ViewRemotes,
///
CreateRemote,
///
OpenRepo { path: PathBuf },
///
OpenResetPopup(CommitId),
///
RewordCommit(CommitId),
///
CommitSearch(LogFilterSearchOptions),
///
OpenGotoLinePopup(usize),
///
GotoLine(usize),
///
CheckoutOption(BranchInfo),
}
/// single threaded simple queue for components to communicate with each other
#[derive(Clone, Default)]
pub struct Queue {
data: Rc<RefCell<VecDeque<InternalEvent>>>,
}
impl Queue {
pub fn new() -> Self {
Self {
data: Rc::new(RefCell::new(VecDeque::new())),
}
}
pub fn push(&self, ev: InternalEvent) {
self.data.borrow_mut().push_back(ev);
}
pub fn pop(&self) -> Option<InternalEvent> {
self.data.borrow_mut().pop_front()
}
pub fn clear(&self) {
self.data.borrow_mut().clear();
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/string_utils.rs | src/string_utils.rs | use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
///
pub fn trim_length_left(s: &str, width: usize) -> &str {
let len = s.len();
if len > width {
for i in len - width..len {
if s.is_char_boundary(i) {
return &s[i..];
}
}
}
s
}
//TODO: allow customize tabsize
pub fn tabs_to_spaces(input: String) -> String {
if input.contains('\t') {
input.replace('\t', " ")
} else {
input
}
}
/// This function will return a str slice which start at specified offset.
/// As src is a unicode str, start offset has to be calculated with each character.
pub fn trim_offset(src: &str, mut offset: usize) -> &str {
let mut start = 0;
for c in UnicodeSegmentation::graphemes(src, true) {
let w = c.width();
if w <= offset {
offset -= w;
start += c.len();
} else {
break;
}
}
&src[start..]
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use crate::string_utils::trim_length_left;
#[test]
fn test_trim() {
assert_eq!(trim_length_left("👍foo", 3), "foo");
assert_eq!(trim_length_left("👍foo", 4), "foo");
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/input.rs | src/input.rs | use crate::notify_mutex::NotifiableMutex;
use anyhow::Result;
use crossbeam_channel::{unbounded, Receiver, Sender};
use crossterm::event::{self, Event, Event::Key, KeyEventKind};
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
time::Duration,
};
static FAST_POLL_DURATION: Duration = Duration::from_millis(100);
static SLOW_POLL_DURATION: Duration = Duration::from_millis(10000);
///
#[derive(Clone, Copy, Debug)]
pub enum InputState {
Paused,
Polling,
}
///
#[derive(Clone, Debug)]
pub enum InputEvent {
Input(Event),
State(InputState),
}
///
#[derive(Clone)]
pub struct Input {
desired_state: Arc<NotifiableMutex<bool>>,
current_state: Arc<AtomicBool>,
receiver: Receiver<InputEvent>,
aborted: Arc<AtomicBool>,
}
impl Input {
///
pub fn new() -> Self {
let (tx, rx) = unbounded();
let desired_state = Arc::new(NotifiableMutex::new(true));
let current_state = Arc::new(AtomicBool::new(true));
let aborted = Arc::new(AtomicBool::new(false));
let arc_desired = Arc::clone(&desired_state);
let arc_current = Arc::clone(¤t_state);
let arc_aborted = Arc::clone(&aborted);
thread::spawn(move || {
if let Err(e) =
Self::input_loop(&arc_desired, &arc_current, &tx)
{
log::error!("input thread error: {e}");
arc_aborted.store(true, Ordering::SeqCst);
}
});
Self {
receiver: rx,
desired_state,
current_state,
aborted,
}
}
///
pub fn receiver(&self) -> Receiver<InputEvent> {
self.receiver.clone()
}
///
pub fn set_polling(&self, enabled: bool) {
self.desired_state.set_and_notify(enabled);
}
fn shall_poll(&self) -> bool {
self.desired_state.get()
}
///
pub fn is_state_changing(&self) -> bool {
self.shall_poll()
!= self.current_state.load(Ordering::Relaxed)
}
pub fn is_aborted(&self) -> bool {
self.aborted.load(Ordering::SeqCst)
}
fn poll(dur: Duration) -> anyhow::Result<Option<Event>> {
if event::poll(dur)? {
Ok(Some(event::read()?))
} else {
Ok(None)
}
}
fn input_loop(
arc_desired: &Arc<NotifiableMutex<bool>>,
arc_current: &Arc<AtomicBool>,
tx: &Sender<InputEvent>,
) -> Result<()> {
let mut poll_duration = SLOW_POLL_DURATION;
loop {
if arc_desired.get() {
if !arc_current.load(Ordering::Relaxed) {
log::info!("input polling resumed");
tx.send(InputEvent::State(InputState::Polling))?;
}
arc_current.store(true, Ordering::Relaxed);
if let Some(e) = Self::poll(poll_duration)? {
// windows send key release too, only process key press
if let Key(key) = e {
if key.kind != KeyEventKind::Press {
continue;
}
}
tx.send(InputEvent::Input(e))?;
//Note: right after an input event we might have a reason to stop
// polling (external editor opening) so lets do a quick poll until the next input
// this fixes https://github.com/gitui-org/gitui/issues/1506
poll_duration = FAST_POLL_DURATION;
} else {
poll_duration = SLOW_POLL_DURATION;
}
} else {
if arc_current.load(Ordering::Relaxed) {
log::info!("input polling suspended");
tx.send(InputEvent::State(InputState::Paused))?;
}
arc_current.store(false, Ordering::Relaxed);
arc_desired.wait(true);
}
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/commitlist.rs | src/components/commitlist.rs | use super::utils::logitems::{ItemBatch, LogEntry};
use crate::{
app::Environment,
components::{
utils::string_width_align, CommandBlocking, CommandInfo,
Component, DrawableComponent, EventState, ScrollType,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, Queue},
strings::{self, symbol},
try_or_popup,
ui::style::{SharedTheme, Theme},
ui::{calc_scroll_top, draw_scrollbar, Orientation},
};
use anyhow::Result;
use asyncgit::sync::{
self, checkout_commit, BranchDetails, BranchInfo, CommitId,
RepoPathRef, Tags,
};
use chrono::{DateTime, Local};
use crossterm::event::Event;
use indexmap::IndexSet;
use itertools::Itertools;
use ratatui::{
layout::{Alignment, Rect},
style::Style,
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
Frame,
};
use std::{
borrow::Cow, cell::Cell, cmp, collections::BTreeMap, rc::Rc,
time::Instant,
};
const ELEMENTS_PER_LINE: usize = 9;
const SLICE_SIZE: usize = 1200;
///
pub struct CommitList {
repo: RepoPathRef,
title: Box<str>,
selection: usize,
highlighted_selection: Option<usize>,
items: ItemBatch,
highlights: Option<Rc<IndexSet<CommitId>>>,
commits: IndexSet<CommitId>,
/// The marked commits.
/// `self.marked[].0` holds the commit index into `self.items.items` - used for ordering the list.
/// `self.marked[].1` is the commit id of the marked commit.
marked: Vec<(usize, CommitId)>,
scroll_state: (Instant, f32),
tags: Option<Tags>,
local_branches: BTreeMap<CommitId, Vec<BranchInfo>>,
remote_branches: BTreeMap<CommitId, Vec<BranchInfo>>,
current_size: Cell<Option<(u16, u16)>>,
scroll_top: Cell<usize>,
theme: SharedTheme,
queue: Queue,
key_config: SharedKeyConfig,
}
impl CommitList {
///
pub fn new(env: &Environment, title: &str) -> Self {
Self {
repo: env.repo.clone(),
items: ItemBatch::default(),
marked: Vec::with_capacity(2),
selection: 0,
highlighted_selection: None,
commits: IndexSet::new(),
highlights: None,
scroll_state: (Instant::now(), 0_f32),
tags: None,
local_branches: BTreeMap::default(),
remote_branches: BTreeMap::default(),
current_size: Cell::new(None),
scroll_top: Cell::new(0),
theme: env.theme.clone(),
queue: env.queue.clone(),
key_config: env.key_config.clone(),
title: title.into(),
}
}
///
pub const fn tags(&self) -> Option<&Tags> {
self.tags.as_ref()
}
///
pub fn clear(&mut self) {
self.items.clear();
self.commits.clear();
}
///
pub fn copy_items(&self) -> Vec<CommitId> {
self.commits.iter().copied().collect_vec()
}
///
pub fn set_tags(&mut self, tags: Tags) {
self.tags = Some(tags);
}
///
pub fn selected_entry(&self) -> Option<&LogEntry> {
self.items.iter().nth(
self.selection.saturating_sub(self.items.index_offset()),
)
}
///
pub fn marked_count(&self) -> usize {
self.marked.len()
}
///
pub fn clear_marked(&mut self) {
self.marked.clear();
}
///
pub fn marked_commits(&self) -> Vec<CommitId> {
let (_, commits): (Vec<_>, Vec<CommitId>) =
self.marked.iter().copied().unzip();
commits
}
/// Build string of marked or selected (if none are marked) commit ids
fn concat_selected_commit_ids(&self) -> Option<String> {
match self.marked.as_slice() {
[] => self
.items
.iter()
.nth(
self.selection
.saturating_sub(self.items.index_offset()),
)
.map(|e| e.id.to_string()),
marked => Some(
marked
.iter()
.map(|(_idx, commit)| commit.to_string())
.join(" "),
),
}
}
/// Copy currently marked or selected (if none are marked) commit ids
/// to clipboard
pub fn copy_commit_hash(&self) -> Result<()> {
if let Some(yank) = self.concat_selected_commit_ids() {
crate::clipboard::copy_string(&yank)?;
self.queue.push(InternalEvent::ShowInfoMsg(
strings::copy_success(&yank),
));
}
Ok(())
}
///
pub fn checkout(&self) {
if let Some(commit_hash) =
self.selected_entry().map(|entry| entry.id)
{
try_or_popup!(
self,
"failed to checkout commit:",
checkout_commit(&self.repo.borrow(), commit_hash)
);
}
}
///
pub fn set_local_branches(
&mut self,
local_branches: Vec<BranchInfo>,
) {
self.local_branches.clear();
for local_branch in local_branches {
self.local_branches
.entry(local_branch.top_commit)
.or_default()
.push(local_branch);
}
}
///
pub fn set_remote_branches(
&mut self,
remote_branches: Vec<BranchInfo>,
) {
self.remote_branches.clear();
for remote_branch in remote_branches {
self.remote_branches
.entry(remote_branch.top_commit)
.or_default()
.push(remote_branch);
}
}
///
pub fn set_commits(&mut self, commits: IndexSet<CommitId>) {
if commits != self.commits {
self.items.clear();
self.commits = commits;
self.fetch_commits(false);
}
}
///
pub fn refresh_extend_data(&mut self, commits: Vec<CommitId>) {
let new_commits = !commits.is_empty();
self.commits.extend(commits);
let selection = self.selection();
let selection_max = self.selection_max();
if self.needs_data(selection, selection_max) || new_commits {
self.fetch_commits(false);
}
}
///
pub fn set_highlighting(
&mut self,
highlighting: Option<Rc<IndexSet<CommitId>>>,
) {
//note: set highlights to none if there is no highlight
self.highlights = if highlighting
.as_ref()
.is_some_and(|set| set.is_empty())
{
None
} else {
highlighting
};
self.select_next_highlight();
self.set_highlighted_selection_index();
self.fetch_commits(true);
}
///
pub fn select_commit(&mut self, id: CommitId) -> Result<()> {
let index = self.commits.get_index_of(&id);
if let Some(index) = index {
self.selection = index;
self.set_highlighted_selection_index();
Ok(())
} else {
anyhow::bail!("Could not select commit. It might not be loaded yet or it might be on a different branch.");
}
}
///
pub fn highlighted_selection_info(&self) -> (usize, usize) {
let amount = self
.highlights
.as_ref()
.map(|highlights| highlights.len())
.unwrap_or_default();
(self.highlighted_selection.unwrap_or_default(), amount)
}
fn set_highlighted_selection_index(&mut self) {
self.highlighted_selection =
self.highlights.as_ref().and_then(|highlights| {
highlights.iter().position(|entry| {
entry == &self.commits[self.selection]
})
});
}
const fn selection(&self) -> usize {
self.selection
}
/// will return view size or None before the first render
fn current_size(&self) -> Option<(u16, u16)> {
self.current_size.get()
}
fn selection_max(&self) -> usize {
self.commits.len().saturating_sub(1)
}
fn selected_entry_marked(&self) -> bool {
self.selected_entry()
.and_then(|e| self.is_marked(&e.id))
.unwrap_or_default()
}
fn move_selection(&mut self, scroll: ScrollType) -> Result<bool> {
let needs_update = if self.items.highlighting() {
self.move_selection_highlighting(scroll)?
} else {
self.move_selection_normal(scroll)?
};
Ok(needs_update)
}
fn move_selection_highlighting(
&mut self,
scroll: ScrollType,
) -> Result<bool> {
let (current_index, selection_max) =
self.highlighted_selection_info();
let new_index = match scroll {
ScrollType::Up => current_index.saturating_sub(1),
ScrollType::Down => current_index.saturating_add(1),
//TODO: support this?
// ScrollType::Home => 0,
// ScrollType::End => self.selection_max(),
_ => return Ok(false),
};
let new_index =
cmp::min(new_index, selection_max.saturating_sub(1));
let index_changed = new_index != current_index;
if !index_changed {
return Ok(false);
}
let new_selected_commit =
self.highlights.as_ref().and_then(|highlights| {
highlights.iter().nth(new_index).copied()
});
if let Some(c) = new_selected_commit {
self.select_commit(c)?;
return Ok(true);
}
Ok(false)
}
fn move_selection_normal(
&mut self,
scroll: ScrollType,
) -> Result<bool> {
self.update_scroll_speed();
#[allow(clippy::cast_possible_truncation)]
let speed_int = usize::try_from(self.scroll_state.1 as i64)?.max(1);
let page_offset = usize::from(
self.current_size.get().unwrap_or_default().1,
)
.saturating_sub(1);
let new_selection = match scroll {
ScrollType::Up => {
self.selection.saturating_sub(speed_int)
}
ScrollType::Down => {
self.selection.saturating_add(speed_int)
}
ScrollType::PageUp => {
self.selection.saturating_sub(page_offset)
}
ScrollType::PageDown => {
self.selection.saturating_add(page_offset)
}
ScrollType::Home => 0,
ScrollType::End => self.selection_max(),
};
let new_selection =
cmp::min(new_selection, self.selection_max());
let needs_update = new_selection != self.selection;
self.selection = new_selection;
Ok(needs_update)
}
fn mark(&mut self) {
if let Some(e) = self.selected_entry() {
let id = e.id;
let selected = self
.selection
.saturating_sub(self.items.index_offset());
if self.is_marked(&id).unwrap_or_default() {
self.marked.retain(|marked| marked.1 != id);
} else {
self.marked.push((selected, id));
self.marked.sort_unstable_by(|first, second| {
first.0.cmp(&second.0)
});
}
}
}
fn update_scroll_speed(&mut self) {
const REPEATED_SCROLL_THRESHOLD_MILLIS: u128 = 300;
const SCROLL_SPEED_START: f32 = 0.1_f32;
const SCROLL_SPEED_MAX: f32 = 10_f32;
const SCROLL_SPEED_MULTIPLIER: f32 = 1.05_f32;
let now = Instant::now();
let since_last_scroll =
now.duration_since(self.scroll_state.0);
self.scroll_state.0 = now;
let speed = if since_last_scroll.as_millis()
< REPEATED_SCROLL_THRESHOLD_MILLIS
{
self.scroll_state.1 * SCROLL_SPEED_MULTIPLIER
} else {
SCROLL_SPEED_START
};
self.scroll_state.1 = speed.min(SCROLL_SPEED_MAX);
}
fn is_marked(&self, id: &CommitId) -> Option<bool> {
if self.marked.is_empty() {
None
} else {
let found =
self.marked.iter().any(|entry| entry.1 == *id);
Some(found)
}
}
#[allow(clippy::too_many_arguments)]
fn get_entry_to_add<'a>(
&self,
e: &'a LogEntry,
selected: bool,
tags: Option<String>,
local_branches: Option<String>,
remote_branches: Option<String>,
theme: &Theme,
width: usize,
now: DateTime<Local>,
marked: Option<bool>,
) -> Line<'a> {
let mut txt: Vec<Span> = Vec::with_capacity(
ELEMENTS_PER_LINE + if marked.is_some() { 2 } else { 0 },
);
let normal = !self.items.highlighting()
|| (self.items.highlighting() && e.highlighted);
let splitter_txt = Cow::from(symbol::EMPTY_SPACE);
let splitter = Span::styled(
splitter_txt,
if normal {
theme.text(true, selected)
} else {
Style::default()
},
);
// marker
if let Some(marked) = marked {
txt.push(Span::styled(
Cow::from(if marked {
symbol::CHECKMARK
} else {
symbol::EMPTY_SPACE
}),
theme.log_marker(selected),
));
txt.push(splitter.clone());
}
let style_hash = if normal {
theme.commit_hash(selected)
} else {
theme.commit_unhighlighted()
};
let style_time = if normal {
theme.commit_time(selected)
} else {
theme.commit_unhighlighted()
};
let style_author = if normal {
theme.commit_author(selected)
} else {
theme.commit_unhighlighted()
};
let style_tags = if normal {
theme.tags(selected)
} else {
theme.commit_unhighlighted()
};
let style_branches = if normal {
theme.branch(selected, true)
} else {
theme.commit_unhighlighted()
};
let style_msg = if normal {
theme.text(true, selected)
} else {
theme.commit_unhighlighted()
};
// commit hash
txt.push(Span::styled(Cow::from(&*e.hash_short), style_hash));
txt.push(splitter.clone());
// commit timestamp
txt.push(Span::styled(
Cow::from(e.time_to_string(now)),
style_time,
));
txt.push(splitter.clone());
let author_width =
(width.saturating_sub(19) / 3).clamp(3, 20);
let author = string_width_align(&e.author, author_width);
// commit author
txt.push(Span::styled(author, style_author));
txt.push(splitter.clone());
// commit tags
if let Some(tags) = tags {
txt.push(splitter.clone());
txt.push(Span::styled(tags, style_tags));
}
if let Some(local_branches) = local_branches {
txt.push(splitter.clone());
txt.push(Span::styled(local_branches, style_branches));
}
if let Some(remote_branches) = remote_branches {
txt.push(splitter.clone());
txt.push(Span::styled(remote_branches, style_branches));
}
txt.push(splitter);
let message_width = width.saturating_sub(
txt.iter().map(|span| span.content.len()).sum(),
);
// commit msg
txt.push(Span::styled(
format!("{:message_width$}", &e.msg),
style_msg,
));
Line::from(txt)
}
fn get_text(&self, height: usize, width: usize) -> Vec<Line<'_>> {
let selection = self.relative_selection();
let mut txt: Vec<Line> = Vec::with_capacity(height);
let now = Local::now();
let any_marked = !self.marked.is_empty();
for (idx, e) in self
.items
.iter()
.skip(self.scroll_top.get())
.take(height)
.enumerate()
{
let tags =
self.tags.as_ref().and_then(|t| t.get(&e.id)).map(
|tags| {
tags.iter()
.map(|t| format!("<{}>", t.name))
.join(" ")
},
);
let local_branches =
self.local_branches.get(&e.id).map(|local_branch| {
local_branch
.iter()
.map(|local_branch| {
format!("{{{0}}}", local_branch.name)
})
.join(" ")
});
let marked = if any_marked {
self.is_marked(&e.id)
} else {
None
};
txt.push(self.get_entry_to_add(
e,
idx + self.scroll_top.get() == selection,
tags,
local_branches,
self.remote_branches_string(e),
&self.theme,
width,
now,
marked,
));
}
txt
}
fn remote_branches_string(&self, e: &LogEntry) -> Option<String> {
self.remote_branches.get(&e.id).and_then(|remote_branches| {
let filtered_branches: Vec<_> = remote_branches
.iter()
.filter(|remote_branch| {
self.local_branches.get(&e.id).is_none_or(
|local_branch| {
local_branch.iter().any(|local_branch| {
let has_corresponding_local_branch =
match &local_branch.details {
BranchDetails::Local(
details,
) => details
.upstream
.as_ref()
.is_some_and(
|upstream| {
upstream.reference == remote_branch.reference
},
),
BranchDetails::Remote(_) => {
false
}
};
!has_corresponding_local_branch
})
},
)
})
.map(|remote_branch| {
format!("[{0}]", remote_branch.name)
})
.collect();
if filtered_branches.is_empty() {
None
} else {
Some(filtered_branches.join(" "))
}
})
}
fn relative_selection(&self) -> usize {
self.selection.saturating_sub(self.items.index_offset())
}
fn select_next_highlight(&mut self) {
if self.highlights.is_none() {
return;
}
let old_selection = self.selection;
let mut offset = 0;
loop {
let hit_upper_bound =
old_selection + offset > self.selection_max();
let hit_lower_bound = offset > old_selection;
if !hit_upper_bound {
self.selection = old_selection + offset;
if self.selection_highlighted() {
break;
}
}
if !hit_lower_bound {
self.selection = old_selection - offset;
if self.selection_highlighted() {
break;
}
}
if hit_lower_bound && hit_upper_bound {
self.selection = old_selection;
break;
}
offset += 1;
}
}
fn selection_highlighted(&self) -> bool {
let commit = self.commits[self.selection];
self.highlights
.as_ref()
.is_some_and(|highlights| highlights.contains(&commit))
}
fn needs_data(&self, idx: usize, idx_max: usize) -> bool {
self.items.needs_data(idx, idx_max)
}
// checks if first entry in items is the same commit as we expect
fn is_list_in_sync(&self) -> bool {
self.items
.index_offset_raw()
.and_then(|index| {
self.items
.iter()
.next()
.map(|item| item.id == self.commits[index])
})
.unwrap_or_default()
}
fn fetch_commits(&mut self, force: bool) {
let want_min =
self.selection().saturating_sub(SLICE_SIZE / 2);
let commits = self.commits.len();
let want_min = want_min.min(commits);
let index_in_sync = self
.items
.index_offset_raw()
.is_some_and(|index| want_min == index);
if !index_in_sync || !self.is_list_in_sync() || force {
let commits = sync::get_commits_info(
&self.repo.borrow(),
self.commits
.iter()
.skip(want_min)
.take(SLICE_SIZE)
.copied()
.collect_vec()
.as_slice(),
self.current_size()
.map_or(100u16, |size| size.0)
.into(),
);
if let Ok(commits) = commits {
self.items.set_items(
want_min,
commits,
self.highlights.as_ref(),
);
}
}
}
}
impl DrawableComponent for CommitList {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
let current_size = (
area.width.saturating_sub(2),
area.height.saturating_sub(2),
);
self.current_size.set(Some(current_size));
let height_in_lines = current_size.1 as usize;
let selection = self.relative_selection();
self.scroll_top.set(calc_scroll_top(
self.scroll_top.get(),
height_in_lines,
selection,
));
let title = format!(
"{} {}/{}",
self.title,
self.commits.len().saturating_sub(self.selection),
self.commits.len(),
);
f.render_widget(
Paragraph::new(
self.get_text(
height_in_lines,
current_size.0 as usize,
),
)
.block(
Block::default()
.borders(Borders::ALL)
.title(Span::styled(
title.as_str(),
self.theme.title(true),
))
.border_style(self.theme.block(true)),
)
.alignment(Alignment::Left),
area,
);
draw_scrollbar(
f,
area,
&self.theme,
self.commits.len(),
self.selection,
Orientation::Vertical,
);
Ok(())
}
}
impl Component for CommitList {
fn event(&mut self, ev: &Event) -> Result<EventState> {
if let Event::Key(k) = ev {
let selection_changed =
if key_match(k, self.key_config.keys.move_up) {
self.move_selection(ScrollType::Up)?
} else if key_match(k, self.key_config.keys.move_down)
{
self.move_selection(ScrollType::Down)?
} else if key_match(k, self.key_config.keys.shift_up)
|| key_match(k, self.key_config.keys.home)
{
self.move_selection(ScrollType::Home)?
} else if key_match(
k,
self.key_config.keys.shift_down,
) || key_match(k, self.key_config.keys.end)
{
self.move_selection(ScrollType::End)?
} else if key_match(k, self.key_config.keys.page_up) {
self.move_selection(ScrollType::PageUp)?
} else if key_match(k, self.key_config.keys.page_down)
{
self.move_selection(ScrollType::PageDown)?
} else if key_match(
k,
self.key_config.keys.log_mark_commit,
) {
self.mark();
true
} else if key_match(
k,
self.key_config.keys.log_checkout_commit,
) {
self.checkout();
true
} else {
false
};
return Ok(selection_changed.into());
}
Ok(EventState::NotConsumed)
}
fn commands(
&self,
out: &mut Vec<CommandInfo>,
_force_all: bool,
) -> CommandBlocking {
out.push(CommandInfo::new(
strings::commands::scroll(&self.key_config),
self.selected_entry().is_some(),
true,
));
out.push(CommandInfo::new(
strings::commands::commit_list_mark(
&self.key_config,
self.selected_entry_marked(),
),
true,
true,
));
CommandBlocking::PassingOn
}
}
#[cfg(test)]
mod tests {
use asyncgit::sync::CommitInfo;
use super::*;
impl Default for CommitList {
fn default() -> Self {
Self {
title: String::new().into_boxed_str(),
selection: 0,
highlighted_selection: Option::None,
highlights: Option::None,
tags: Option::None,
items: ItemBatch::default(),
commits: IndexSet::default(),
marked: Vec::default(),
scroll_top: Cell::default(),
local_branches: BTreeMap::default(),
remote_branches: BTreeMap::default(),
theme: SharedTheme::default(),
key_config: SharedKeyConfig::default(),
scroll_state: (Instant::now(), 0.0),
current_size: Cell::default(),
repo: RepoPathRef::new(sync::RepoPath::Path(
std::path::PathBuf::default(),
)),
queue: Queue::default(),
}
}
}
#[test]
fn test_string_width_align() {
assert_eq!(string_width_align("123", 3), "123");
assert_eq!(string_width_align("123", 2), "..");
assert_eq!(string_width_align("123", 3), "123");
assert_eq!(string_width_align("12345", 6), "12345 ");
assert_eq!(string_width_align("1234556", 4), "12..");
}
#[test]
fn test_string_width_align_unicode() {
assert_eq!(string_width_align("äste", 3), "ä..");
assert_eq!(
string_width_align("wüsten äste", 10),
"wüsten ä.."
);
assert_eq!(
string_width_align("Jon Grythe Stødle", 19),
"Jon Grythe Stødle "
);
}
/// Build a commit list with a few commits loaded
fn build_commit_list_with_some_commits() -> CommitList {
let mut items = ItemBatch::default();
let basic_commit_info = CommitInfo {
message: String::default(),
time: 0,
author: String::default(),
id: CommitId::default(),
};
// This just creates a sequence of fake ordered ids
// 0000000000000000000000000000000000000000
// 0000000000000000000000000000000000000001
// 0000000000000000000000000000000000000002
// ...
items.set_items(
2, /* randomly choose an offset */
(0..20)
.map(|idx| CommitInfo {
id: CommitId::from_str_unchecked(&format!(
"{idx:040}",
))
.unwrap(),
..basic_commit_info.clone()
})
.collect(),
None,
);
CommitList {
items,
selection: 4, // Randomly select one commit
..Default::default()
}
}
/// Build a value for cl.marked based on indices into cl.items
fn build_marked_from_indices(
cl: &CommitList,
marked_indices: &[usize],
) -> Vec<(usize, CommitId)> {
let offset = cl.items.index_offset();
marked_indices
.iter()
.map(|idx| {
(*idx, cl.items.iter().nth(*idx - offset).unwrap().id)
})
.collect()
}
#[test]
fn test_copy_commit_list_empty() {
assert_eq!(
CommitList::default().concat_selected_commit_ids(),
None
);
}
#[test]
fn test_copy_commit_none_marked() {
let cl = CommitList {
selection: 4,
..build_commit_list_with_some_commits()
};
// ids from build_commit_list_with_some_commits() are
// offset by two, so we expect commit id 2 for
// selection = 4
assert_eq!(
cl.concat_selected_commit_ids(),
Some(String::from(
"0000000000000000000000000000000000000002"
))
);
}
#[test]
fn test_copy_commit_one_marked() {
let cl = build_commit_list_with_some_commits();
let cl = CommitList {
marked: build_marked_from_indices(&cl, &[3]),
..cl
};
assert_eq!(
cl.concat_selected_commit_ids(),
Some(String::from(
"0000000000000000000000000000000000000001",
))
);
}
#[test]
fn test_copy_commit_range_marked() {
let cl = build_commit_list_with_some_commits();
let cl = CommitList {
marked: build_marked_from_indices(&cl, &[4, 5, 6, 7]),
..cl
};
assert_eq!(
cl.concat_selected_commit_ids(),
Some(String::from(concat!(
"0000000000000000000000000000000000000002 ",
"0000000000000000000000000000000000000003 ",
"0000000000000000000000000000000000000004 ",
"0000000000000000000000000000000000000005"
)))
);
}
#[test]
fn test_copy_commit_random_marked() {
let cl = build_commit_list_with_some_commits();
let cl = CommitList {
marked: build_marked_from_indices(&cl, &[4, 7]),
..cl
};
assert_eq!(
cl.concat_selected_commit_ids(),
Some(String::from(concat!(
"0000000000000000000000000000000000000002 ",
"0000000000000000000000000000000000000005"
)))
);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/syntax_text.rs | src/components/syntax_text.rs | use super::{
CommandBlocking, CommandInfo, Component, DrawableComponent,
EventState,
};
use crate::{
app::Environment,
keys::SharedKeyConfig,
string_utils::tabs_to_spaces,
strings,
ui::{
self, common_nav, style::SharedTheme, AsyncSyntaxJob,
ParagraphState, ScrollPos, StatefulParagraph,
},
AsyncAppNotification, AsyncNotification, SyntaxHighlightProgress,
};
use anyhow::Result;
use asyncgit::{
asyncjob::AsyncSingleJob,
sync::{self, RepoPathRef, TreeFile},
ProgressPercent,
};
use crossterm::event::Event;
use filetreelist::MoveSelection;
use itertools::Either;
use ratatui::{
layout::Rect,
text::Text,
widgets::{Block, Borders, Wrap},
Frame,
};
use std::{cell::Cell, path::Path};
pub struct SyntaxTextComponent {
repo: RepoPathRef,
current_file: Option<(String, Either<ui::SyntaxText, String>)>,
async_highlighting: AsyncSingleJob<AsyncSyntaxJob>,
syntax_progress: Option<ProgressPercent>,
key_config: SharedKeyConfig,
paragraph_state: Cell<ParagraphState>,
focused: bool,
theme: SharedTheme,
}
impl SyntaxTextComponent {
///
pub fn new(env: &Environment) -> Self {
Self {
async_highlighting: AsyncSingleJob::new(
env.sender_app.clone(),
),
syntax_progress: None,
current_file: None,
paragraph_state: Cell::new(ParagraphState::default()),
focused: false,
key_config: env.key_config.clone(),
theme: env.theme.clone(),
repo: env.repo.clone(),
}
}
///
pub fn update(&mut self, ev: AsyncNotification) {
if let AsyncNotification::App(
AsyncAppNotification::SyntaxHighlighting(progress),
) = ev
{
match progress {
SyntaxHighlightProgress::Progress => {
self.syntax_progress =
self.async_highlighting.progress();
}
SyntaxHighlightProgress::Done => {
self.syntax_progress = None;
if let Some(job) =
self.async_highlighting.take_last()
{
if let Some((path, content)) =
self.current_file.as_mut()
{
if let Some(syntax) = job.result() {
if syntax.path() == Path::new(path) {
*content = Either::Left(syntax);
}
}
}
}
}
}
}
}
///
pub fn any_work_pending(&self) -> bool {
self.async_highlighting.is_pending()
}
///
pub fn clear(&mut self) {
self.current_file = None;
}
///
pub fn load_file(&mut self, path: String, item: &TreeFile) {
let already_loaded = self
.current_file
.as_ref()
.is_some_and(|(current_file, _)| current_file == &path);
if !already_loaded {
//TODO: fetch file content async as well
match sync::tree_file_content(&self.repo.borrow(), item) {
Ok(content) => {
let content = tabs_to_spaces(content);
self.syntax_progress =
Some(ProgressPercent::empty());
self.async_highlighting.spawn(
AsyncSyntaxJob::new(
content.clone(),
path.clone(),
self.theme.get_syntax(),
),
);
self.current_file =
Some((path, Either::Right(content)));
}
Err(e) => {
self.current_file = Some((
path,
Either::Right(format!(
"error loading file: {e}"
)),
));
}
}
}
}
fn scroll(&self, nav: MoveSelection) -> bool {
let state = self.paragraph_state.get();
let new_scroll_pos = match nav {
MoveSelection::Down => state.scroll().y.saturating_add(1),
MoveSelection::Up => state.scroll().y.saturating_sub(1),
MoveSelection::Top => 0,
MoveSelection::End => state
.lines()
.saturating_sub(state.height().saturating_sub(2)),
MoveSelection::PageUp => state
.scroll()
.y
.saturating_sub(state.height().saturating_sub(2)),
MoveSelection::PageDown => state
.scroll()
.y
.saturating_add(state.height().saturating_sub(2)),
_ => state.scroll().y,
};
self.set_scroll(new_scroll_pos)
}
fn set_scroll(&self, pos: u16) -> bool {
let mut state = self.paragraph_state.get();
let new_scroll_pos = pos.min(
state
.lines()
.saturating_sub(state.height().saturating_sub(2)),
);
if new_scroll_pos == state.scroll().y {
return false;
}
state.set_scroll(ScrollPos {
x: 0,
y: new_scroll_pos,
});
self.paragraph_state.set(state);
true
}
}
impl DrawableComponent for SyntaxTextComponent {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
let text = self.current_file.as_ref().map_or_else(
|| Text::from(""),
|(_, content)| match content {
Either::Left(syn) => syn.into(),
Either::Right(s) => Text::from(s.as_str()),
},
);
let title = format!(
"{}{}",
self.current_file
.as_ref()
.map(|(name, _)| name.clone())
.unwrap_or_default(),
self.syntax_progress
.map(|p| format!(" ({}%)", p.progress))
.unwrap_or_default()
);
let content = StatefulParagraph::new(text)
.wrap(Wrap { trim: false })
.block(
Block::default()
.title(title)
.borders(Borders::ALL)
.border_style(self.theme.title(self.focused())),
);
let mut state = self.paragraph_state.get();
f.render_stateful_widget(content, area, &mut state);
self.paragraph_state.set(state);
self.set_scroll(state.scroll().y);
if self.focused() {
ui::draw_scrollbar(
f,
area,
&self.theme,
usize::from(state.lines().saturating_sub(
state.height().saturating_sub(2),
)),
usize::from(state.scroll().y),
ui::Orientation::Vertical,
);
}
Ok(())
}
}
impl Component for SyntaxTextComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.focused() || force_all {
out.push(
CommandInfo::new(
strings::commands::scroll(&self.key_config),
true,
true,
)
.order(strings::order::NAV),
);
}
CommandBlocking::PassingOn
}
fn event(
&mut self,
event: &crossterm::event::Event,
) -> Result<EventState> {
if let Event::Key(key) = event {
if let Some(nav) = common_nav(key, &self.key_config) {
return Ok(if self.scroll(nav) {
EventState::Consumed
} else {
EventState::NotConsumed
});
}
}
Ok(EventState::NotConsumed)
}
///
fn focused(&self) -> bool {
self.focused
}
/// focus/unfocus this component depending on param
fn focus(&mut self, focus: bool) {
self.focused = focus;
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/command.rs | src/components/command.rs | use crate::strings::order;
///
#[derive(Clone, PartialEq, PartialOrd, Ord, Eq)]
pub struct CommandText {
///
pub name: String,
///
pub desc: &'static str,
///
pub group: &'static str,
///
pub hide_help: bool,
}
impl CommandText {
///
pub const fn new(
name: String,
desc: &'static str,
group: &'static str,
) -> Self {
Self {
name,
desc,
group,
hide_help: false,
}
}
///
pub const fn hide_help(self) -> Self {
let mut tmp = self;
tmp.hide_help = true;
tmp
}
}
///
pub struct CommandInfo {
///
pub text: CommandText,
/// available but not active in the context
pub enabled: bool,
/// will show up in the quick bar
pub quick_bar: bool,
/// available in current app state
pub available: bool,
/// used to order commands in quickbar
pub order: i8,
}
impl CommandInfo {
///
pub const fn new(
text: CommandText,
enabled: bool,
available: bool,
) -> Self {
Self {
text,
enabled,
quick_bar: true,
available,
order: order::AVERAGE,
}
}
///
pub const fn order(self, order: i8) -> Self {
let mut res = self;
res.order = order;
res
}
///
pub const fn hidden(self) -> Self {
let mut res = self;
res.quick_bar = false;
res
}
///
pub const fn show_in_quickbar(&self) -> bool {
self.quick_bar && self.available
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/textinput.rs | src/components/textinput.rs | use crate::app::Environment;
use crate::keys::key_match;
use crate::ui::Size;
use crate::{
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState,
},
keys::SharedKeyConfig,
strings,
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use crossterm::event::Event;
use ratatui::widgets::{Block, Borders};
use ratatui::{
layout::{Alignment, Rect},
widgets::{Clear, Paragraph},
Frame,
};
use std::cell::Cell;
use std::cell::OnceCell;
use tui_textarea::{CursorMove, Input, Key, Scrolling, TextArea};
///
#[derive(PartialEq, Eq)]
pub enum InputType {
Singleline,
Multiline,
Password,
}
#[derive(PartialEq, Eq)]
enum SelectionState {
Selecting,
NotSelecting,
SelectionEndPending,
}
type TextAreaComponent = TextArea<'static>;
///
pub struct TextInputComponent {
title: String,
default_msg: String,
selected: Option<bool>,
msg: OnceCell<String>,
show_char_count: bool,
theme: SharedTheme,
key_config: SharedKeyConfig,
input_type: InputType,
current_area: Cell<Rect>,
embed: bool,
textarea: Option<TextAreaComponent>,
select_state: SelectionState,
}
impl TextInputComponent {
///
pub fn new(
env: &Environment,
title: &str,
default_msg: &str,
show_char_count: bool,
) -> Self {
Self {
msg: OnceCell::default(),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
show_char_count,
title: title.to_string(),
default_msg: default_msg.to_string(),
selected: None,
input_type: InputType::Multiline,
current_area: Cell::new(Rect::default()),
embed: false,
textarea: None,
select_state: SelectionState::NotSelecting,
}
}
///
pub const fn with_input_type(
mut self,
input_type: InputType,
) -> Self {
self.input_type = input_type;
self
}
///
pub fn set_input_type(&mut self, input_type: InputType) {
self.clear();
self.input_type = input_type;
}
/// Clear the `msg`.
pub fn clear(&mut self) {
self.msg.take();
if self.is_visible() {
self.show_inner_textarea();
}
}
/// Get the `msg`.
pub fn get_text(&self) -> &str {
// the fancy footwork with the OnceCell is to allow
// the reading of msg as a &str.
// tui_textarea returns its lines to the caller as &[String]
// gitui wants &str of \n delimited text
// it would be simple if this was a mut method. You could
// just load up msg from the lines area and return an &str pointing at it
// but its not a mut method. So we need to store the text in a OnceCell
// The methods that change msg call take() on the cell. That makes
// get_or_init run again
self.msg.get_or_init(|| {
self.textarea
.as_ref()
.map_or_else(String::new, |ta| ta.lines().join("\n"))
})
}
/// screen area (last time we got drawn)
pub fn get_area(&self) -> Rect {
self.current_area.get()
}
/// embed into parent draw area
pub fn embed(&mut self) {
self.embed = true;
}
///
pub fn enabled(&mut self, enable: bool) {
self.selected = Some(enable);
}
fn show_inner_textarea(&mut self) {
// create the textarea and then load it with the text
// from self.msg
let lines: Vec<String> = self
.msg
.get()
.unwrap_or(&String::new())
.split('\n')
.map(ToString::to_string)
.collect();
self.textarea = Some({
let mut text_area = TextArea::new(lines);
if self.input_type == InputType::Password {
text_area.set_mask_char('*');
}
text_area
.set_cursor_line_style(self.theme.text(true, false));
text_area.set_placeholder_text(self.default_msg.clone());
text_area.set_placeholder_style(
self.theme
.text(self.selected.unwrap_or_default(), false),
);
text_area.set_style(
self.theme.text(self.selected.unwrap_or(true), false),
);
if !self.embed {
text_area.set_block(
Block::default()
.borders(Borders::ALL)
.border_style(
ratatui::style::Style::default()
.add_modifier(
ratatui::style::Modifier::BOLD,
),
)
.title(self.title.clone()),
);
}
text_area
});
}
/// Set the `msg`.
pub fn set_text(&mut self, msg: String) {
self.msg = msg.into();
if self.is_visible() {
self.show_inner_textarea();
}
}
/// Set the `title`.
pub fn set_title(&mut self, t: String) {
self.title = t;
}
///
pub fn set_default_msg(&mut self, v: String) {
self.default_msg = v;
if self.is_visible() {
self.show_inner_textarea();
}
}
fn draw_char_count(&self, f: &mut Frame, r: Rect) {
let count = self.get_text().len();
if count > 0 {
let w = Paragraph::new(format!("[{count} chars]"))
.alignment(Alignment::Right);
let mut rect = {
let mut rect = r;
rect.y += rect.height.saturating_sub(1);
rect
};
rect.x += 1;
rect.width = rect.width.saturating_sub(2);
rect.height = rect
.height
.saturating_sub(rect.height.saturating_sub(1));
f.render_widget(w, rect);
}
}
fn should_select(&mut self, input: &Input) {
if input.key == Key::Null {
return;
}
// Should we start selecting text, stop the current selection, or do nothing?
// the end is handled after the ending keystroke
match (&self.select_state, input.shift) {
(SelectionState::Selecting, true)
| (SelectionState::NotSelecting, false) => {
// continue selecting or not selecting
}
(SelectionState::Selecting, false) => {
// end select
self.select_state =
SelectionState::SelectionEndPending;
}
(SelectionState::NotSelecting, true) => {
// start select
// this should always work since we are only called
// if we have a textarea to get input
if let Some(ta) = &mut self.textarea {
ta.start_selection();
self.select_state = SelectionState::Selecting;
}
}
(SelectionState::SelectionEndPending, _) => {
// this really should not happen because the end pending state
// should have been picked up in the same pass as it was set
// so lets clear it
self.select_state = SelectionState::NotSelecting;
}
}
}
#[allow(clippy::too_many_lines, clippy::unnested_or_patterns)]
fn process_inputs(ta: &mut TextArea<'_>, input: &Input) -> bool {
match input {
Input {
key: Key::Char(c),
ctrl: false,
alt: false,
..
} => {
ta.insert_char(*c);
true
}
Input {
key: Key::Tab,
ctrl: false,
alt: false,
..
} => {
ta.insert_tab();
true
}
Input {
key: Key::Char('h'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Backspace,
ctrl: false,
alt: false,
..
} => {
ta.delete_char();
true
}
Input {
key: Key::Char('d'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Delete,
ctrl: false,
alt: false,
..
} => {
ta.delete_next_char();
true
}
Input {
key: Key::Char('k'),
ctrl: true,
alt: false,
..
} => {
ta.delete_line_by_end();
true
}
Input {
key: Key::Char('j'),
ctrl: true,
alt: false,
..
} => {
ta.delete_line_by_head();
true
}
Input {
key: Key::Char('w'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Char('h'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Backspace,
ctrl: false,
alt: true,
..
} => {
ta.delete_word();
true
}
Input {
key: Key::Delete,
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Char('d'),
ctrl: false,
alt: true,
..
} => {
ta.delete_next_word();
true
}
Input {
key: Key::Char('n'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Down,
ctrl: false,
alt: false,
..
} => {
ta.move_cursor(CursorMove::Down);
true
}
Input {
key: Key::Char('p'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Up,
ctrl: false,
alt: false,
..
} => {
ta.move_cursor(CursorMove::Up);
true
}
Input {
key: Key::Char('f'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Right,
ctrl: false,
alt: false,
..
} => {
ta.move_cursor(CursorMove::Forward);
true
}
Input {
key: Key::Char('b'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::Left,
ctrl: false,
alt: false,
..
} => {
ta.move_cursor(CursorMove::Back);
true
}
Input {
key: Key::Char('a'),
ctrl: true,
alt: false,
..
}
| Input { key: Key::Home, .. }
| Input {
key: Key::Left | Key::Char('b'),
ctrl: true,
alt: true,
..
} => {
ta.move_cursor(CursorMove::Head);
true
}
Input {
key: Key::Char('e'),
ctrl: true,
alt: false,
..
}
| Input { key: Key::End, .. }
| Input {
key: Key::Right | Key::Char('f'),
ctrl: true,
alt: true,
..
} => {
ta.move_cursor(CursorMove::End);
true
}
Input {
key: Key::Char('<'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Up | Key::Char('p'),
ctrl: true,
alt: true,
..
} => {
ta.move_cursor(CursorMove::Top);
true
}
Input {
key: Key::Char('>'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Down | Key::Char('n'),
ctrl: true,
alt: true,
..
} => {
ta.move_cursor(CursorMove::Bottom);
true
}
Input {
key: Key::Char('f'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Right,
ctrl: true,
alt: false,
..
} => {
ta.move_cursor(CursorMove::WordForward);
true
}
Input {
key: Key::Char('b'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Left,
ctrl: true,
alt: false,
..
} => {
ta.move_cursor(CursorMove::WordBack);
true
}
Input {
key: Key::Char(']'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Char('n'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Down,
ctrl: true,
alt: false,
..
} => {
ta.move_cursor(CursorMove::ParagraphForward);
true
}
Input {
key: Key::Char('['),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Char('p'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::Up,
ctrl: true,
alt: false,
..
} => {
ta.move_cursor(CursorMove::ParagraphBack);
true
}
Input {
key: Key::Char('u'),
ctrl: true,
alt: false,
..
} => {
ta.undo();
true
}
Input {
key: Key::Char('r'),
ctrl: true,
alt: false,
..
} => {
ta.redo();
true
}
Input {
key: Key::Char('y'),
ctrl: true,
alt: false,
..
} => {
ta.paste();
true
}
Input {
key: Key::Char('v'),
ctrl: true,
alt: false,
..
}
| Input {
key: Key::PageDown, ..
} => {
ta.scroll(Scrolling::PageDown);
true
}
Input {
key: Key::Char('v'),
ctrl: false,
alt: true,
..
}
| Input {
key: Key::PageUp, ..
} => {
ta.scroll(Scrolling::PageUp);
true
}
_ => false,
}
}
}
impl DrawableComponent for TextInputComponent {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
// this should always be true since draw should only be being called
// is control is visible
if let Some(ta) = &self.textarea {
let area = if self.embed {
rect
} else if self.input_type == InputType::Multiline {
let area = ui::centered_rect(60, 20, f.area());
ui::rect_inside(
Size::new(10, 3),
f.area().into(),
area,
)
} else {
let area = ui::centered_rect(60, 1, f.area());
ui::rect_inside(
Size::new(10, 3),
f.area().into(),
area,
)
};
f.render_widget(Clear, area);
f.render_widget(ta, area);
if self.show_char_count {
self.draw_char_count(f, area);
}
self.current_area.set(area);
}
Ok(())
}
}
impl Component for TextInputComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
_force_all: bool,
) -> CommandBlocking {
out.push(
CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
self.is_visible(),
)
.order(1),
);
//TODO: we might want to show the textarea specific commands here
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
let input = Input::from(ev.clone());
self.should_select(&input);
if let Some(ta) = &mut self.textarea {
let modified = if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.exit_popup) {
self.hide();
return Ok(EventState::Consumed);
}
if key_match(e, self.key_config.keys.newline)
&& self.input_type == InputType::Multiline
{
ta.insert_newline();
true
} else {
Self::process_inputs(ta, &input)
}
} else {
false
};
if self.select_state
== SelectionState::SelectionEndPending
{
ta.cancel_selection();
self.select_state = SelectionState::NotSelecting;
}
if modified {
self.msg.take();
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
/*
visible maps to textarea Option
None = > not visible
Some => visible
*/
fn is_visible(&self) -> bool {
self.textarea.is_some()
}
fn hide(&mut self) {
self.textarea = None;
}
fn show(&mut self) -> Result<()> {
self.show_inner_textarea();
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_smoke() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
comp.show_inner_textarea();
comp.set_text(String::from("a\nb"));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
assert_eq!(ta.cursor(), (0, 0));
ta.move_cursor(CursorMove::Forward);
assert_eq!(ta.cursor(), (0, 1));
ta.move_cursor(CursorMove::Back);
assert_eq!(ta.cursor(), (0, 0));
}
}
#[test]
fn text_cursor_initial_position() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
comp.show_inner_textarea();
comp.set_text(String::from("a"));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
let txt = ta.lines();
assert_eq!(txt[0].len(), 1);
assert_eq!(txt[0].as_bytes()[0], b'a');
}
}
#[test]
fn test_multiline() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
comp.show_inner_textarea();
comp.set_text(String::from("a\nb\nc"));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
let txt = ta.lines();
assert_eq!(txt[0], "a");
assert_eq!(txt[1], "b");
assert_eq!(txt[2], "c");
}
}
#[test]
fn test_next_word_position() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
comp.show_inner_textarea();
comp.set_text(String::from("aa b;c"));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
// from word start
ta.move_cursor(CursorMove::Head);
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 3));
// from inside start
ta.move_cursor(CursorMove::Forward);
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 5));
// to string end
ta.move_cursor(CursorMove::Forward);
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 6));
// from string end
ta.move_cursor(CursorMove::Forward);
let save_cursor = ta.cursor();
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), save_cursor);
}
}
#[test]
fn test_previous_word_position() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
comp.show_inner_textarea();
comp.set_text(String::from(" a bb;c"));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
// from string end
ta.move_cursor(CursorMove::End);
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 6));
// from inside word
ta.move_cursor(CursorMove::Back);
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 3));
// from word start
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 1));
// to string start
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 0));
// from string start
let save_cursor = ta.cursor();
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), save_cursor);
}
}
#[test]
fn test_next_word_multibyte() {
let env = Environment::test_env();
let mut comp = TextInputComponent::new(&env, "", "", false);
// should emojis be word boundaries or not?
// various editors (vs code, vim) do not agree with the
// behavhior of the original textinput here.
//
// tui-textarea agrees with them.
// So these tests are changed to match that behavior
// FYI: this line is "a à ❤ab🤯 a"
// "01245 89A EFG"
let text = dbg!("a à \u{2764}ab\u{1F92F} a");
comp.show_inner_textarea();
comp.set_text(String::from(text));
assert!(comp.is_visible());
if let Some(ta) = &mut comp.textarea {
ta.move_cursor(CursorMove::Head);
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 2));
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 4));
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 9));
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), (0, 10));
let save_cursor = ta.cursor();
ta.move_cursor(CursorMove::WordForward);
assert_eq!(ta.cursor(), save_cursor);
ta.move_cursor(CursorMove::End);
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 9));
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 4));
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 2));
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), (0, 0));
let save_cursor = ta.cursor();
ta.move_cursor(CursorMove::WordBack);
assert_eq!(ta.cursor(), save_cursor);
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/diff.rs | src/components/diff.rs | use super::{
utils::scroll_horizontal::HorizontalScroll,
utils::scroll_vertical::VerticalScroll, CommandBlocking,
Direction, DrawableComponent, HorizontalScrollType, ScrollType,
};
use crate::{
app::Environment,
components::{CommandInfo, Component, EventState},
keys::{key_match, SharedKeyConfig},
options::SharedOptions,
queue::{Action, InternalEvent, NeedsUpdate, Queue, ResetItem},
string_utils::tabs_to_spaces,
string_utils::trim_offset,
strings, try_or_popup,
ui::style::SharedTheme,
};
use anyhow::Result;
use asyncgit::{
hash,
sync::{self, diff::DiffLinePosition, RepoPathRef},
DiffLine, DiffLineType, FileDiff,
};
use bytesize::ByteSize;
use crossterm::event::Event;
use ratatui::{
layout::Rect,
symbols,
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
Frame,
};
use std::{borrow::Cow, cell::Cell, cmp, path::Path};
#[derive(Default)]
struct Current {
path: String,
is_stage: bool,
hash: u64,
}
///
#[derive(Clone, Copy)]
enum Selection {
Single(usize),
Multiple(usize, usize),
}
impl Selection {
const fn get_start(&self) -> usize {
match self {
Self::Single(start) | Self::Multiple(start, _) => *start,
}
}
const fn get_end(&self) -> usize {
match self {
Self::Single(end) | Self::Multiple(_, end) => *end,
}
}
fn get_top(&self) -> usize {
match self {
Self::Single(start) => *start,
Self::Multiple(start, end) => cmp::min(*start, *end),
}
}
fn get_bottom(&self) -> usize {
match self {
Self::Single(start) => *start,
Self::Multiple(start, end) => cmp::max(*start, *end),
}
}
fn modify(&mut self, direction: Direction, max: usize) {
let start = self.get_start();
let old_end = self.get_end();
*self = match direction {
Direction::Up => {
Self::Multiple(start, old_end.saturating_sub(1))
}
Direction::Down => {
Self::Multiple(start, cmp::min(old_end + 1, max))
}
};
}
fn contains(&self, index: usize) -> bool {
match self {
Self::Single(start) => index == *start,
Self::Multiple(start, end) => {
if start <= end {
*start <= index && index <= *end
} else {
*end <= index && index <= *start
}
}
}
}
}
///
pub struct DiffComponent {
repo: RepoPathRef,
diff: Option<FileDiff>,
longest_line: usize,
pending: bool,
selection: Selection,
selected_hunk: Option<usize>,
current_size: Cell<(u16, u16)>,
focused: bool,
current: Current,
vertical_scroll: VerticalScroll,
horizontal_scroll: HorizontalScroll,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
is_immutable: bool,
options: SharedOptions,
}
impl DiffComponent {
///
pub fn new(env: &Environment, is_immutable: bool) -> Self {
Self {
focused: false,
queue: env.queue.clone(),
current: Current::default(),
pending: false,
selected_hunk: None,
diff: None,
longest_line: 0,
current_size: Cell::new((0, 0)),
selection: Selection::Single(0),
vertical_scroll: VerticalScroll::new(),
horizontal_scroll: HorizontalScroll::new(),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
is_immutable,
repo: env.repo.clone(),
options: env.options.clone(),
}
}
///
fn can_scroll(&self) -> bool {
self.diff.as_ref().is_some_and(|diff| diff.lines > 1)
}
///
pub fn current(&self) -> (String, bool) {
(self.current.path.clone(), self.current.is_stage)
}
///
pub fn clear(&mut self, pending: bool) {
self.current = Current::default();
self.diff = None;
self.longest_line = 0;
self.vertical_scroll.reset();
self.horizontal_scroll.reset();
self.selection = Selection::Single(0);
self.selected_hunk = None;
self.pending = pending;
}
///
pub fn update(
&mut self,
path: String,
is_stage: bool,
diff: FileDiff,
) {
self.pending = false;
let hash = hash(&diff);
if self.current.hash != hash {
let reset_selection = self.current.path != path;
self.current = Current {
path,
is_stage,
hash,
};
self.diff = Some(diff);
self.longest_line = self
.diff
.iter()
.flat_map(|diff| diff.hunks.iter())
.flat_map(|hunk| hunk.lines.iter())
.map(|line| {
let converted_content = tabs_to_spaces(
line.content.as_ref().to_string(),
);
converted_content.len()
})
.max()
.map_or(0, |len| {
// Each hunk uses a 1-character wide vertical bar to its left to indicate
// selection.
len + 1
});
if reset_selection {
self.vertical_scroll.reset();
self.selection = Selection::Single(0);
self.update_selection(0);
} else {
let old_selection = match self.selection {
Selection::Single(line) => line,
Selection::Multiple(start, _) => start,
};
self.update_selection(old_selection);
}
}
}
fn move_selection(&mut self, move_type: ScrollType) {
if let Some(diff) = &self.diff {
let max = diff.lines.saturating_sub(1);
let new_start = match move_type {
ScrollType::Down => {
self.selection.get_bottom().saturating_add(1)
}
ScrollType::Up => {
self.selection.get_top().saturating_sub(1)
}
ScrollType::Home => 0,
ScrollType::End => max,
ScrollType::PageDown => {
self.selection.get_bottom().saturating_add(
self.current_size.get().1.saturating_sub(1)
as usize,
)
}
ScrollType::PageUp => {
self.selection.get_top().saturating_sub(
self.current_size.get().1.saturating_sub(1)
as usize,
)
}
};
self.update_selection(new_start);
}
}
fn update_selection(&mut self, new_start: usize) {
if let Some(diff) = &self.diff {
let max = diff.lines.saturating_sub(1);
let new_start = cmp::min(max, new_start);
self.selection = Selection::Single(new_start);
self.selected_hunk =
Self::find_selected_hunk(diff, new_start);
}
}
fn lines_count(&self) -> usize {
self.diff.as_ref().map_or(0, |diff| diff.lines)
}
fn max_scroll_right(&self) -> usize {
self.longest_line
.saturating_sub(self.current_size.get().0.into())
}
fn modify_selection(&mut self, direction: Direction) {
if self.diff.is_some() {
self.selection.modify(direction, self.lines_count());
}
}
fn copy_selection(&self) {
if let Some(diff) = &self.diff {
let lines_to_copy: Vec<&str> =
diff.hunks
.iter()
.flat_map(|hunk| hunk.lines.iter())
.enumerate()
.filter_map(|(i, line)| {
if self.selection.contains(i) {
Some(line.content.trim_matches(|c| {
c == '\n' || c == '\r'
}))
} else {
None
}
})
.collect();
try_or_popup!(
self,
"copy to clipboard error:",
crate::clipboard::copy_string(
&lines_to_copy.join("\n")
)
);
}
}
fn find_selected_hunk(
diff: &FileDiff,
line_selected: usize,
) -> Option<usize> {
let mut line_cursor = 0_usize;
for (i, hunk) in diff.hunks.iter().enumerate() {
let hunk_len = hunk.lines.len();
let hunk_min = line_cursor;
let hunk_max = line_cursor + hunk_len;
let hunk_selected =
hunk_min <= line_selected && hunk_max > line_selected;
if hunk_selected {
return Some(i);
}
line_cursor += hunk_len;
}
None
}
fn get_text(&self, width: u16, height: u16) -> Vec<Line<'_>> {
if let Some(diff) = &self.diff {
return if diff.hunks.is_empty() {
self.get_text_binary(diff)
} else {
let mut res: Vec<Line> = Vec::new();
let min = self.vertical_scroll.get_top();
let max = min + height as usize;
let mut line_cursor = 0_usize;
let mut lines_added = 0_usize;
for (i, hunk) in diff.hunks.iter().enumerate() {
let hunk_selected = self.focused()
&& self.selected_hunk.is_some_and(|s| s == i);
if lines_added >= height as usize {
break;
}
let hunk_len = hunk.lines.len();
let hunk_min = line_cursor;
let hunk_max = line_cursor + hunk_len;
if Self::hunk_visible(
hunk_min, hunk_max, min, max,
) {
for (i, line) in hunk.lines.iter().enumerate()
{
if line_cursor >= min
&& line_cursor <= max
{
res.push(Self::get_line_to_add(
width,
line,
self.focused()
&& self
.selection
.contains(line_cursor),
hunk_selected,
i == hunk_len - 1,
&self.theme,
self.horizontal_scroll
.get_right(),
));
lines_added += 1;
}
line_cursor += 1;
}
} else {
line_cursor += hunk_len;
}
}
res
};
}
vec![]
}
fn get_text_binary(&self, diff: &FileDiff) -> Vec<Line<'_>> {
let is_positive = diff.size_delta >= 0;
let delta_byte_size =
ByteSize::b(diff.size_delta.unsigned_abs());
let sign = if is_positive { "+" } else { "-" };
vec![Line::from(vec![
Span::raw(Cow::from("size: ")),
Span::styled(
Cow::from(format!("{}", ByteSize::b(diff.sizes.0))),
self.theme.text(false, false),
),
Span::raw(Cow::from(" -> ")),
Span::styled(
Cow::from(format!("{}", ByteSize::b(diff.sizes.1))),
self.theme.text(false, false),
),
Span::raw(Cow::from(" (")),
Span::styled(
Cow::from(format!("{sign}{delta_byte_size:}")),
self.theme.diff_line(
if is_positive {
DiffLineType::Add
} else {
DiffLineType::Delete
},
false,
),
),
Span::raw(Cow::from(")")),
])]
}
fn get_line_to_add<'a>(
width: u16,
line: &'a DiffLine,
selected: bool,
selected_hunk: bool,
end_of_hunk: bool,
theme: &SharedTheme,
scrolled_right: usize,
) -> Line<'a> {
let style = theme.diff_hunk_marker(selected_hunk);
let is_content_line =
matches!(line.line_type, DiffLineType::None);
let left_side_of_line = if end_of_hunk {
Span::styled(Cow::from(symbols::line::BOTTOM_LEFT), style)
} else {
match line.line_type {
DiffLineType::Header => Span::styled(
Cow::from(symbols::line::TOP_LEFT),
style,
),
_ => Span::styled(
Cow::from(symbols::line::VERTICAL),
style,
),
}
};
let content =
if !is_content_line && line.content.as_ref().is_empty() {
theme.line_break()
} else {
tabs_to_spaces(line.content.as_ref().to_string())
};
let content = trim_offset(&content, scrolled_right);
let filled = if selected {
// selected line
format!("{content:w$}\n", w = width as usize)
} else {
// weird eof missing eol line
format!("{content}\n")
};
Line::from(vec![
left_side_of_line,
Span::styled(
Cow::from(filled),
theme.diff_line(line.line_type, selected),
),
])
}
const fn hunk_visible(
hunk_min: usize,
hunk_max: usize,
min: usize,
max: usize,
) -> bool {
// full overlap
if hunk_min <= min && hunk_max >= max {
return true;
}
// partly overlap
if (hunk_min >= min && hunk_min <= max)
|| (hunk_max >= min && hunk_max <= max)
{
return true;
}
false
}
fn unstage_hunk(&self) -> Result<()> {
if let Some(diff) = &self.diff {
if let Some(hunk) = self.selected_hunk {
let hash = diff.hunks[hunk].header_hash;
sync::unstage_hunk(
&self.repo.borrow(),
&self.current.path,
hash,
Some(self.options.borrow().diff_options()),
)?;
self.queue_update();
}
}
Ok(())
}
fn stage_hunk(&self) -> Result<()> {
if let Some(diff) = &self.diff {
if let Some(hunk) = self.selected_hunk {
if diff.untracked {
sync::stage_add_file(
&self.repo.borrow(),
Path::new(&self.current.path),
)?;
} else {
let hash = diff.hunks[hunk].header_hash;
sync::stage_hunk(
&self.repo.borrow(),
&self.current.path,
hash,
Some(self.options.borrow().diff_options()),
)?;
}
self.queue_update();
}
}
Ok(())
}
fn queue_update(&self) {
self.queue.push(InternalEvent::Update(NeedsUpdate::ALL));
}
fn reset_hunk(&self) {
if let Some(diff) = &self.diff {
if let Some(hunk) = self.selected_hunk {
let hash = diff.hunks[hunk].header_hash;
self.queue.push(InternalEvent::ConfirmAction(
Action::ResetHunk(
self.current.path.clone(),
hash,
),
));
}
}
}
fn reset_lines(&self) {
self.queue.push(InternalEvent::ConfirmAction(
Action::ResetLines(
self.current.path.clone(),
self.selected_lines(),
),
));
}
fn stage_lines(&self) {
if let Some(diff) = &self.diff {
//TODO: support untracked files as well
if !diff.untracked {
let selected_lines = self.selected_lines();
try_or_popup!(
self,
"(un)stage lines:",
sync::stage_lines(
&self.repo.borrow(),
&self.current.path,
self.is_stage(),
&selected_lines,
)
);
self.queue_update();
}
}
}
fn selected_lines(&self) -> Vec<DiffLinePosition> {
self.diff
.as_ref()
.map(|diff| {
diff.hunks
.iter()
.flat_map(|hunk| hunk.lines.iter())
.enumerate()
.filter_map(|(i, line)| {
let is_add_or_delete = line.line_type
== DiffLineType::Add
|| line.line_type == DiffLineType::Delete;
if self.selection.contains(i)
&& is_add_or_delete
{
Some(line.position)
} else {
None
}
})
.collect()
})
.unwrap_or_default()
}
fn reset_untracked(&self) {
self.queue.push(InternalEvent::ConfirmAction(Action::Reset(
ResetItem {
path: self.current.path.clone(),
},
)));
}
fn stage_unstage_hunk(&self) -> Result<()> {
if self.current.is_stage {
self.unstage_hunk()?;
} else {
self.stage_hunk()?;
}
Ok(())
}
fn calc_hunk_move_target(
&self,
direction: isize,
) -> Option<usize> {
let diff = self.diff.as_ref()?;
if diff.hunks.is_empty() {
return None;
}
let max = diff.hunks.len() - 1;
let target_index = self.selected_hunk.map_or(0, |i| {
let target = if direction >= 0 {
i.saturating_add(direction.unsigned_abs())
} else {
i.saturating_sub(direction.unsigned_abs())
};
std::cmp::min(max, target)
});
Some(target_index)
}
fn diff_hunk_move_up_down(&mut self, direction: isize) {
let Some(diff) = &self.diff else { return };
let hunk_index = self.calc_hunk_move_target(direction);
// return if selected_hunk not change
if self.selected_hunk == hunk_index {
return;
}
if let Some(hunk_index) = hunk_index {
let line_index = diff
.hunks
.iter()
.take(hunk_index)
.fold(0, |sum, hunk| sum + hunk.lines.len());
let hunk = &diff.hunks[hunk_index];
self.selection = Selection::Single(line_index);
self.selected_hunk = Some(hunk_index);
self.vertical_scroll.move_area_to_visible(
self.current_size.get().1 as usize,
line_index,
line_index.saturating_add(hunk.lines.len()),
);
}
}
const fn is_stage(&self) -> bool {
self.current.is_stage
}
}
impl DrawableComponent for DiffComponent {
fn draw(&self, f: &mut Frame, r: Rect) -> Result<()> {
self.current_size.set((
r.width.saturating_sub(2),
r.height.saturating_sub(2),
));
let current_width = self.current_size.get().0;
let current_height = self.current_size.get().1;
self.vertical_scroll.update(
self.selection.get_end(),
self.lines_count(),
usize::from(current_height),
);
self.horizontal_scroll.update_no_selection(
self.longest_line,
current_width.into(),
);
let title = format!(
"{}{}",
strings::title_diff(&self.key_config),
self.current.path
);
let txt = if self.pending {
vec![Line::from(vec![Span::styled(
Cow::from(strings::loading_text(&self.key_config)),
self.theme.text(false, false),
)])]
} else {
self.get_text(r.width, current_height)
};
f.render_widget(
Paragraph::new(txt).block(
Block::default()
.title(Span::styled(
title.as_str(),
self.theme.title(self.focused()),
))
.borders(Borders::ALL)
.border_style(self.theme.block(self.focused())),
),
r,
);
if self.focused() {
self.vertical_scroll.draw(f, r, &self.theme);
if self.max_scroll_right() > 0 {
self.horizontal_scroll.draw(f, r, &self.theme);
}
}
Ok(())
}
}
impl Component for DiffComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
_force_all: bool,
) -> CommandBlocking {
out.push(CommandInfo::new(
strings::commands::scroll(&self.key_config),
self.can_scroll(),
self.focused(),
));
out.push(CommandInfo::new(
strings::commands::diff_hunk_next(&self.key_config),
self.calc_hunk_move_target(1) != self.selected_hunk,
self.focused(),
));
out.push(CommandInfo::new(
strings::commands::diff_hunk_prev(&self.key_config),
self.calc_hunk_move_target(-1) != self.selected_hunk,
self.focused(),
));
out.push(
CommandInfo::new(
strings::commands::diff_home_end(&self.key_config),
self.can_scroll(),
self.focused(),
)
.hidden(),
);
if !self.is_immutable {
out.push(CommandInfo::new(
strings::commands::diff_hunk_remove(&self.key_config),
self.selected_hunk.is_some(),
self.focused() && self.is_stage(),
));
out.push(CommandInfo::new(
strings::commands::diff_hunk_add(&self.key_config),
self.selected_hunk.is_some(),
self.focused() && !self.is_stage(),
));
out.push(CommandInfo::new(
strings::commands::diff_hunk_revert(&self.key_config),
self.selected_hunk.is_some(),
self.focused() && !self.is_stage(),
));
out.push(CommandInfo::new(
strings::commands::diff_lines_revert(
&self.key_config,
),
//TODO: only if any modifications are selected
true,
self.focused() && !self.is_stage(),
));
out.push(CommandInfo::new(
strings::commands::diff_lines_stage(&self.key_config),
//TODO: only if any modifications are selected
true,
self.focused() && !self.is_stage(),
));
out.push(CommandInfo::new(
strings::commands::diff_lines_unstage(
&self.key_config,
),
//TODO: only if any modifications are selected
true,
self.focused() && self.is_stage(),
));
}
out.push(CommandInfo::new(
strings::commands::copy(&self.key_config),
true,
self.focused(),
));
CommandBlocking::PassingOn
}
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.focused() {
if let Event::Key(e) = ev {
return if key_match(e, self.key_config.keys.move_down)
{
self.move_selection(ScrollType::Down);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.shift_down,
) {
self.modify_selection(Direction::Down);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.shift_up)
{
self.modify_selection(Direction::Up);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.end) {
self.move_selection(ScrollType::End);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.home) {
self.move_selection(ScrollType::Home);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.move_up) {
self.move_selection(ScrollType::Up);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.page_up) {
self.move_selection(ScrollType::PageUp);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.page_down)
{
self.move_selection(ScrollType::PageDown);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.move_right,
) {
self.horizontal_scroll
.move_right(HorizontalScrollType::Right);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.move_left)
{
self.horizontal_scroll
.move_right(HorizontalScrollType::Left);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.diff_hunk_next,
) {
self.diff_hunk_move_up_down(1);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.diff_hunk_prev,
) {
self.diff_hunk_move_up_down(-1);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.stage_unstage_item,
) && !self.is_immutable
{
try_or_popup!(
self,
"hunk error:",
self.stage_unstage_hunk()
);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.status_reset_item,
) && !self.is_immutable
&& !self.is_stage()
{
if let Some(diff) = &self.diff {
if diff.untracked {
self.reset_untracked();
} else {
self.reset_hunk();
}
}
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.diff_stage_lines,
) && !self.is_immutable
{
self.stage_lines();
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.diff_reset_lines,
) && !self.is_immutable
&& !self.is_stage()
{
if let Some(diff) = &self.diff {
//TODO: reset untracked lines
if !diff.untracked {
self.reset_lines();
}
}
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.copy) {
self.copy_selection();
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn focused(&self) -> bool {
self.focused
}
fn focus(&mut self, focus: bool) {
self.focused = focus;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ui::style::Theme;
use std::io::Write;
use std::rc::Rc;
use tempfile::NamedTempFile;
#[test]
fn test_line_break() {
let diff_line = DiffLine {
content: "".into(),
line_type: DiffLineType::Add,
position: Default::default(),
};
{
let default_theme = Rc::new(Theme::default());
assert_eq!(
DiffComponent::get_line_to_add(
4,
&diff_line,
false,
false,
false,
&default_theme,
0
)
.spans
.last()
.unwrap(),
&Span::styled(
Cow::from("¶\n"),
default_theme
.diff_line(diff_line.line_type, false)
)
);
}
{
let mut file = NamedTempFile::new().unwrap();
writeln!(
file,
r#"
(
line_break: Some("+")
)
"#
)
.unwrap();
let theme =
Rc::new(Theme::init(&file.path().to_path_buf()));
assert_eq!(
DiffComponent::get_line_to_add(
4, &diff_line, false, false, false, &theme, 0
)
.spans
.last()
.unwrap(),
&Span::styled(
Cow::from("+\n"),
theme.diff_line(diff_line.line_type, false)
)
);
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/revision_files.rs | src/components/revision_files.rs | use super::{
utils::scroll_vertical::VerticalScroll, CommandBlocking,
CommandInfo, Component, DrawableComponent, EventState,
FuzzyFinderTarget, SyntaxTextComponent,
};
use crate::{
app::Environment,
keys::{key_match, SharedKeyConfig},
popups::{BlameFileOpen, FileRevOpen},
queue::{InternalEvent, Queue, StackablePopupOpen},
strings::{self, order, symbol},
try_or_popup,
ui::{self, common_nav, style::SharedTheme},
AsyncNotification,
};
use anyhow::Result;
use asyncgit::{
asyncjob::AsyncSingleJob,
sync::{
get_commit_info, CommitId, CommitInfo, RepoPathRef, TreeFile,
},
AsyncGitNotification, AsyncTreeFilesJob,
};
use crossterm::event::Event;
use filetreelist::{FileTree, FileTreeItem};
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
text::Span,
widgets::{Block, Borders},
Frame,
};
use std::{borrow::Cow, fmt::Write};
use std::{
collections::BTreeSet,
path::{Path, PathBuf},
};
use unicode_truncate::UnicodeTruncateStr;
use unicode_width::UnicodeWidthStr;
enum Focus {
Tree,
File,
}
pub struct RevisionFilesComponent {
repo: RepoPathRef,
queue: Queue,
theme: SharedTheme,
//TODO: store TreeFiles in `tree`
files: Option<Vec<TreeFile>>,
async_treefiles: AsyncSingleJob<AsyncTreeFilesJob>,
current_file: SyntaxTextComponent,
tree: FileTree,
scroll: VerticalScroll,
visible: bool,
revision: Option<CommitInfo>,
focus: Focus,
key_config: SharedKeyConfig,
select_file: Option<PathBuf>,
}
impl RevisionFilesComponent {
///
pub fn new(
env: &Environment,
select_file: Option<PathBuf>,
) -> Self {
Self {
queue: env.queue.clone(),
tree: FileTree::default(),
scroll: VerticalScroll::new(),
current_file: SyntaxTextComponent::new(env),
theme: env.theme.clone(),
files: None,
async_treefiles: AsyncSingleJob::new(
env.sender_git.clone(),
),
revision: None,
focus: Focus::Tree,
key_config: env.key_config.clone(),
repo: env.repo.clone(),
select_file,
visible: false,
}
}
///
pub fn set_commit(&mut self, commit: CommitId) -> Result<()> {
self.show()?;
let same_id =
self.revision.as_ref().is_some_and(|c| c.id == commit);
if !same_id {
self.files = None;
self.request_files(commit);
self.revision =
Some(get_commit_info(&self.repo.borrow(), &commit)?);
}
Ok(())
}
///
pub const fn revision(&self) -> Option<&CommitInfo> {
self.revision.as_ref()
}
///
pub fn update(&mut self, ev: AsyncNotification) -> Result<()> {
self.current_file.update(ev);
if matches!(
ev,
AsyncNotification::Git(AsyncGitNotification::TreeFiles)
) {
self.refresh_files()?;
}
Ok(())
}
fn refresh_files(&mut self) -> Result<(), anyhow::Error> {
if let Some(last) = self.async_treefiles.take_last() {
if let Some(result) = last.result() {
if self
.revision
.as_ref()
.is_some_and(|commit| commit.id == result.commit)
{
if let Ok(last) = result.result {
let filenames: Vec<&Path> = last
.iter()
.map(|f| f.path.as_path())
.collect();
self.tree = FileTree::new(
&filenames,
&BTreeSet::new(),
)?;
self.tree.collapse_but_root();
self.files = Some(last);
let select_file = self.select_file.clone();
self.select_file = None;
if let Some(file) = select_file {
self.find_file(file.as_path());
}
}
} else if let Some(rev) = &self.revision {
self.request_files(rev.id);
}
}
}
Ok(())
}
///
pub fn any_work_pending(&self) -> bool {
self.current_file.any_work_pending()
|| self.async_treefiles.is_pending()
}
fn tree_item_to_span<'a>(
item: &'a FileTreeItem,
theme: &SharedTheme,
width: usize,
selected: bool,
) -> Span<'a> {
let path = item.info().path_str();
let indent = item.info().indent();
let indent_str = if indent == 0 {
String::new()
} else {
format!("{:w$}", " ", w = (indent as usize) * 2)
};
let is_path = item.kind().is_path();
let path_arrow = if is_path {
if item.kind().is_path_collapsed() {
symbol::FOLDER_ICON_COLLAPSED
} else {
symbol::FOLDER_ICON_EXPANDED
}
} else {
symbol::EMPTY_STR
};
let available_width =
width.saturating_sub(indent_str.len() + path_arrow.len());
let path = format!(
"{indent_str}{path_arrow}{path:available_width$}"
);
Span::styled(path, theme.file_tree_item(is_path, selected))
}
fn blame(&self) -> bool {
self.selected_file_path().is_some_and(|path| {
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::BlameFile(BlameFileOpen {
file_path: path,
commit_id: self.revision.as_ref().map(|c| c.id),
selection: None,
}),
));
true
})
}
fn file_history(&self) -> bool {
self.selected_file_path().is_some_and(|path| {
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::FileRevlog(FileRevOpen::new(
path,
)),
));
true
})
}
fn open_finder(&self) {
if let Some(files) = self.files.clone() {
self.queue.push(InternalEvent::OpenFuzzyFinder(
files
.iter()
.map(|a| {
a.path
.to_str()
.unwrap_or_default()
.to_string()
})
.collect(),
FuzzyFinderTarget::Files,
));
}
}
pub fn find_file(&mut self, file: &Path) {
self.tree.collapse_but_root();
if self.tree.select_file(file) {
self.selection_changed();
}
}
fn selected_file_path_with_prefix(&self) -> Option<String> {
self.tree
.selected_file()
.map(|file| file.full_path_str().to_string())
}
fn selected_file_path(&self) -> Option<String> {
self.tree.selected_file().map(|file| {
file.full_path_str()
.strip_prefix("./")
.unwrap_or_default()
.to_string()
})
}
fn selection_changed(&mut self) {
//TODO: retrieve TreeFile from tree datastructure
if let Some(file) = self.selected_file_path_with_prefix() {
if let Some(files) = &self.files {
let path = Path::new(&file);
if let Some(item) =
files.iter().find(|f| f.path == path)
{
if let Ok(path) = path.strip_prefix("./") {
return self.current_file.load_file(
path.to_string_lossy().to_string(),
item,
);
}
}
self.current_file.clear();
}
}
}
fn draw_tree(&self, f: &mut Frame, area: Rect) -> Result<()> {
let tree_height = usize::from(area.height.saturating_sub(2));
let tree_width = usize::from(area.width);
self.tree.window_height.set(Some(tree_height));
self.tree.visual_selection().map_or_else(
|| {
self.scroll.reset();
},
|selection| {
self.scroll.update(
selection.index,
selection.count,
tree_height,
);
},
);
let items = self
.tree
.iterate(self.scroll.get_top(), tree_height)
.map(|(item, selected)| {
Self::tree_item_to_span(
item,
&self.theme,
tree_width,
selected,
)
});
let is_tree_focused = matches!(self.focus, Focus::Tree);
let title = self.title_within(tree_width)?;
let block = Block::default()
.title(Span::styled(
title,
self.theme.title(is_tree_focused),
))
.borders(Borders::ALL)
.border_style(self.theme.block(is_tree_focused));
if self.files.is_some() {
ui::draw_list_block(f, area, block, items);
} else {
ui::draw_list_block(
f,
area,
block,
vec![Span::styled(
Cow::from(strings::loading_text(
&self.key_config,
)),
self.theme.text(false, false),
)]
.into_iter(),
);
}
if is_tree_focused {
self.scroll.draw(f, area, &self.theme);
}
Ok(())
}
fn title_within(&self, tree_width: usize) -> Result<String> {
let mut title = String::from("Files at");
let message = self.revision.as_ref().and_then(|c| {
let _ignore =
write!(title, " {{{}}}", c.id.get_short_string());
c.message.lines().next()
});
if let Some(message) = message {
const ELLIPSIS: char = '\u{2026}'; // …
let available = tree_width
.saturating_sub(title.width())
.saturating_sub(
2 /* frame end corners */ + 1 /* space */ + 2, /* square brackets */
);
if message.width() <= available {
write!(title, " [{message}]")?;
} else if available > 1 {
write!(
title,
" [{}{}]",
message.unicode_truncate(available - 1).0,
ELLIPSIS
)?;
} else {
title.push(ELLIPSIS);
}
}
Ok(title)
}
fn request_files(&self, commit: CommitId) {
self.async_treefiles.spawn(AsyncTreeFilesJob::new(
self.repo.borrow().clone(),
commit,
));
}
}
impl DrawableComponent for RevisionFilesComponent {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
if self.is_visible() {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
Constraint::Percentage(40),
Constraint::Percentage(60),
]
.as_ref(),
)
.split(area);
self.draw_tree(f, chunks[0])?;
self.current_file.draw(f, chunks[1])?;
}
Ok(())
}
}
impl Component for RevisionFilesComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if !self.is_visible() && !force_all {
return CommandBlocking::PassingOn;
}
let is_tree_focused = matches!(self.focus, Focus::Tree);
if is_tree_focused || force_all {
out.push(
CommandInfo::new(
strings::commands::blame_file(&self.key_config),
self.tree.selected_file().is_some(),
true,
)
.order(order::NAV),
);
out.push(CommandInfo::new(
strings::commands::edit_item(&self.key_config),
self.tree.selected_file().is_some(),
true,
));
out.push(
CommandInfo::new(
strings::commands::open_file_history(
&self.key_config,
),
self.tree.selected_file().is_some(),
true,
)
.order(order::RARE_ACTION),
);
out.push(
CommandInfo::new(
strings::commands::copy_path(&self.key_config),
self.tree.selected_file().is_some(),
true,
)
.order(order::RARE_ACTION),
);
tree_nav_cmds(&self.tree, &self.key_config, out);
} else {
self.current_file.commands(out, force_all);
}
CommandBlocking::PassingOn
}
fn event(
&mut self,
event: &crossterm::event::Event,
) -> Result<EventState> {
if !self.is_visible() {
return Ok(EventState::NotConsumed);
}
if let Event::Key(key) = event {
let is_tree_focused = matches!(self.focus, Focus::Tree);
if is_tree_focused
&& tree_nav(&mut self.tree, &self.key_config, key)
{
self.selection_changed();
return Ok(EventState::Consumed);
} else if key_match(key, self.key_config.keys.blame) {
if self.blame() {
self.hide();
return Ok(EventState::Consumed);
}
} else if key_match(
key,
self.key_config.keys.file_history,
) {
if self.file_history() {
self.hide();
return Ok(EventState::Consumed);
}
} else if key_match(key, self.key_config.keys.move_right)
{
if is_tree_focused {
self.focus = Focus::File;
self.current_file.focus(true);
self.focus(true);
return Ok(EventState::Consumed);
}
} else if key_match(key, self.key_config.keys.move_left) {
if !is_tree_focused {
self.focus = Focus::Tree;
self.current_file.focus(false);
self.focus(false);
return Ok(EventState::Consumed);
}
} else if key_match(key, self.key_config.keys.file_find) {
if is_tree_focused {
self.open_finder();
return Ok(EventState::Consumed);
}
} else if key_match(key, self.key_config.keys.edit_file) {
if let Some(file) =
self.selected_file_path_with_prefix()
{
//Note: switch to status tab so its clear we are
// not altering a file inside a revision here
self.queue.push(InternalEvent::TabSwitchStatus);
self.queue.push(
InternalEvent::OpenExternalEditor(Some(file)),
);
return Ok(EventState::Consumed);
}
} else if key_match(key, self.key_config.keys.copy) {
if let Some(file) = self.selected_file_path() {
try_or_popup!(
self,
strings::POPUP_FAIL_COPY,
crate::clipboard::copy_string(&file)
);
}
return Ok(EventState::Consumed);
} else if !is_tree_focused {
return self.current_file.event(event);
}
}
Ok(EventState::NotConsumed)
}
fn hide(&mut self) {
self.visible = false;
}
fn is_visible(&self) -> bool {
self.visible
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.refresh_files()?;
Ok(())
}
}
//TODO: reuse for other tree usages
fn tree_nav_cmds(
tree: &FileTree,
key_config: &SharedKeyConfig,
out: &mut Vec<CommandInfo>,
) {
out.push(
CommandInfo::new(
strings::commands::navigate_tree(key_config),
!tree.is_empty(),
true,
)
.order(order::NAV),
);
}
//TODO: reuse for other tree usages
fn tree_nav(
tree: &mut FileTree,
key_config: &SharedKeyConfig,
key: &crossterm::event::KeyEvent,
) -> bool {
if let Some(common_nav) = common_nav(key, key_config) {
tree.move_selection(common_nav)
} else if key_match(key, key_config.keys.tree_collapse_recursive)
{
tree.collapse_recursive();
true
} else if key_match(key, key_config.keys.tree_expand_recursive) {
tree.expand_recursive();
true
} else {
false
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/status_tree.rs | src/components/status_tree.rs | use super::{
utils::{
filetree::{FileTreeItem, FileTreeItemKind},
statustree::{MoveSelection, StatusTree},
},
CommandBlocking, DrawableComponent,
};
use crate::{
app::Environment,
components::{CommandInfo, Component, EventState},
keys::{key_match, SharedKeyConfig},
popups::{BlameFileOpen, FileRevOpen},
queue::{InternalEvent, NeedsUpdate, Queue, StackablePopupOpen},
strings::{self, order},
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use asyncgit::{hash, sync::CommitId, StatusItem, StatusItemType};
use crossterm::event::Event;
use ratatui::{layout::Rect, text::Span, Frame};
use std::{borrow::Cow, cell::Cell, path::Path};
//TODO: use new `filetreelist` crate
///
#[allow(clippy::struct_excessive_bools)]
pub struct StatusTreeComponent {
title: String,
tree: StatusTree,
pending: bool,
current_hash: u64,
focused: bool,
show_selection: bool,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
scroll_top: Cell<usize>,
visible: bool,
revision: Option<CommitId>,
}
impl StatusTreeComponent {
///
pub fn new(env: &Environment, title: &str, focus: bool) -> Self {
Self {
title: title.to_string(),
tree: StatusTree::default(),
current_hash: 0,
focused: focus,
show_selection: focus,
queue: env.queue.clone(),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
scroll_top: Cell::new(0),
pending: true,
visible: false,
revision: None,
}
}
pub fn set_commit(&mut self, revision: Option<CommitId>) {
self.revision = revision;
}
///
pub fn update(&mut self, list: &[StatusItem]) -> Result<()> {
self.pending = false;
let new_hash = hash(list);
if self.current_hash != new_hash {
self.tree.update(list)?;
self.current_hash = new_hash;
}
Ok(())
}
///
pub fn selection(&self) -> Option<FileTreeItem> {
self.tree.selected_item()
}
///
pub fn selection_file(&self) -> Option<StatusItem> {
self.tree.selected_item().and_then(|f| {
if let FileTreeItemKind::File(f) = f.kind {
Some(f)
} else {
None
}
})
}
///
pub fn show_selection(&mut self, show: bool) {
self.show_selection = show;
}
/// returns true if list is empty
pub fn is_empty(&self) -> bool {
self.tree.is_empty()
}
///
pub const fn file_count(&self) -> usize {
self.tree.tree.file_count()
}
///
pub fn set_title(&mut self, title: String) {
self.title = title;
}
///
pub fn clear(&mut self) -> Result<()> {
self.current_hash = 0;
self.pending = true;
self.tree.update(&[])
}
///
pub fn is_file_selected(&self) -> bool {
self.tree.selected_item().is_some_and(|item| {
match item.kind {
FileTreeItemKind::File(_) => true,
FileTreeItemKind::Path(..) => false,
}
})
}
fn move_selection(&mut self, dir: MoveSelection) -> bool {
let changed = self.tree.move_selection(dir);
if changed {
self.queue.push(InternalEvent::Update(NeedsUpdate::DIFF));
}
changed
}
const fn item_status_char(item_type: StatusItemType) -> char {
match item_type {
StatusItemType::Modified => 'M',
StatusItemType::New => '+',
StatusItemType::Deleted => '-',
StatusItemType::Renamed => 'R',
StatusItemType::Typechange => ' ',
StatusItemType::Conflicted => '!',
}
}
fn item_to_text<'b>(
string: &str,
indent: usize,
visible: bool,
file_item_kind: &FileTreeItemKind,
width: u16,
selected: bool,
theme: &'b SharedTheme,
) -> Option<Span<'b>> {
let indent_str = if indent == 0 {
String::new()
} else {
format!("{:w$}", " ", w = indent * 2)
};
if !visible {
return None;
}
match file_item_kind {
FileTreeItemKind::File(status_item) => {
let status_char =
Self::item_status_char(status_item.status);
let file = Path::new(&status_item.path)
.file_name()
.and_then(std::ffi::OsStr::to_str)
.expect("invalid path.");
let txt = if selected {
format!(
"{} {}{:w$}",
status_char,
indent_str,
file,
w = width as usize
)
} else {
format!("{status_char} {indent_str}{file}")
};
Some(Span::styled(
Cow::from(txt),
theme.item(status_item.status, selected),
))
}
FileTreeItemKind::Path(path_collapsed) => {
let collapse_char =
if path_collapsed.0 { '▸' } else { '▾' };
let txt = if selected {
format!(
" {}{}{:w$}",
indent_str,
collapse_char,
string,
w = width as usize
)
} else {
format!(" {indent_str}{collapse_char}{string}",)
};
Some(Span::styled(
Cow::from(txt),
theme.text(true, selected),
))
}
}
}
/// Returns a `Vec<TextDrawInfo>` which is used to draw the `FileTreeComponent` correctly,
/// allowing folders to be folded up if they are alone in their directory
fn build_vec_text_draw_info_for_drawing(
&self,
) -> (Vec<TextDrawInfo<'_>>, usize, usize) {
let mut should_skip_over: usize = 0;
let mut selection_offset: usize = 0;
let mut selection_offset_visible: usize = 0;
let mut vec_draw_text_info: Vec<TextDrawInfo> = vec![];
let tree_items = self.tree.tree.items();
for (index, item) in tree_items.iter().enumerate() {
if should_skip_over > 0 {
should_skip_over -= 1;
continue;
}
let index_above_select =
index < self.tree.selection.unwrap_or(0);
if !item.info.visible && index_above_select {
selection_offset_visible += 1;
}
vec_draw_text_info.push(TextDrawInfo {
name: item.info.path.clone(),
indent: item.info.indent,
visible: item.info.visible,
item_kind: &item.kind,
});
let mut idx_temp = index;
while idx_temp < tree_items.len().saturating_sub(2)
&& tree_items[idx_temp].info.indent
< tree_items[idx_temp + 1].info.indent
{
// fold up the folder/file
idx_temp += 1;
should_skip_over += 1;
// don't fold files up
if let FileTreeItemKind::File(_) =
&tree_items[idx_temp].kind
{
should_skip_over -= 1;
break;
}
// don't fold up if more than one folder in folder
else if self
.tree
.tree
.multiple_items_at_path(idx_temp)
{
should_skip_over -= 1;
break;
}
// There is only one item at this level (i.e only one folder in the folder),
// so do fold up
let vec_draw_text_info_len = vec_draw_text_info.len();
vec_draw_text_info[vec_draw_text_info_len - 1]
.name += &(String::from("/")
+ &tree_items[idx_temp].info.path);
if index_above_select {
selection_offset += 1;
}
}
}
(
vec_draw_text_info,
selection_offset,
selection_offset_visible,
)
}
// Copy the real path of selected file to clickboard
fn copy_file_path(&self) {
if let Some(item) = self.selection() {
if crate::clipboard::copy_string(&item.info.full_path)
.is_err()
{
self.queue.push(InternalEvent::ShowErrorMsg(
strings::POPUP_FAIL_COPY.to_string(),
));
}
}
}
fn open_history(&mut self) {
match self.selection_file() {
Some(status_item)
if !matches!(
status_item.status,
StatusItemType::New
) =>
{
self.hide();
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::FileRevlog(FileRevOpen::new(
status_item.path,
)),
));
}
_ => {}
}
}
}
/// Used for drawing the `FileTreeComponent`
struct TextDrawInfo<'a> {
name: String,
indent: u8,
visible: bool,
item_kind: &'a FileTreeItemKind,
}
impl DrawableComponent for StatusTreeComponent {
fn draw(&self, f: &mut Frame, r: Rect) -> Result<()> {
if !self.is_visible() {
return Ok(());
}
if self.pending {
let items = vec![Span::styled(
Cow::from(strings::loading_text(&self.key_config)),
self.theme.text(false, false),
)];
ui::draw_list(
f,
r,
self.title.as_str(),
items.into_iter(),
self.focused,
&self.theme,
);
} else {
let (
vec_draw_text_info,
selection_offset,
selection_offset_visible,
) = self.build_vec_text_draw_info_for_drawing();
let select = self
.tree
.selection
.map(|idx| idx.saturating_sub(selection_offset))
.unwrap_or_default();
let tree_height = r.height.saturating_sub(2) as usize;
self.tree.window_height.set(Some(tree_height));
self.scroll_top.set(ui::calc_scroll_top(
self.scroll_top.get(),
tree_height,
select.saturating_sub(selection_offset_visible),
));
let items = vec_draw_text_info
.iter()
.enumerate()
.filter_map(|(index, draw_text_info)| {
Self::item_to_text(
&draw_text_info.name,
draw_text_info.indent as usize,
draw_text_info.visible,
draw_text_info.item_kind,
r.width,
self.show_selection && select == index,
&self.theme,
)
})
.skip(self.scroll_top.get());
ui::draw_list(
f,
r,
self.title.as_str(),
items,
self.focused,
&self.theme,
);
}
Ok(())
}
}
impl Component for StatusTreeComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
let available = self.focused || force_all;
let selection = self.selection_file();
let selected_is_file = selection.is_some();
let tracked = selection.is_some_and(|s| {
!matches!(s.status, StatusItemType::New)
});
out.push(
CommandInfo::new(
strings::commands::navigate_tree(&self.key_config),
!self.is_empty(),
available,
)
.order(order::NAV),
);
out.push(
CommandInfo::new(
strings::commands::blame_file(&self.key_config),
selected_is_file && tracked,
available,
)
.order(order::RARE_ACTION),
);
out.push(
CommandInfo::new(
strings::commands::open_file_history(
&self.key_config,
),
selected_is_file && tracked,
available,
)
.order(order::RARE_ACTION),
);
out.push(
CommandInfo::new(
strings::commands::edit_item(&self.key_config),
selected_is_file,
available,
)
.order(order::RARE_ACTION),
);
out.push(
CommandInfo::new(
strings::commands::copy_path(&self.key_config),
selected_is_file,
available,
)
.order(order::RARE_ACTION),
);
CommandBlocking::PassingOn
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.focused {
if let Event::Key(e) = ev {
return if key_match(e, self.key_config.keys.blame) {
match self.selection_file() {
Some(status_item)
if !matches!(
status_item.status,
StatusItemType::New
) =>
{
self.hide();
self.queue.push(
InternalEvent::OpenPopup(
StackablePopupOpen::BlameFile(
BlameFileOpen {
file_path: status_item
.path,
commit_id: self.revision,
selection: None,
},
),
),
);
}
_ => {}
}
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.file_history,
) {
self.open_history();
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.edit_file)
{
if let Some(status_item) = self.selection_file() {
self.queue.push(
InternalEvent::OpenExternalEditor(Some(
status_item.path,
)),
);
}
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.copy) {
self.copy_file_path();
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.move_down)
{
Ok(self
.move_selection(MoveSelection::Down)
.into())
} else if key_match(e, self.key_config.keys.move_up) {
Ok(self.move_selection(MoveSelection::Up).into())
} else if key_match(e, self.key_config.keys.home)
|| key_match(e, self.key_config.keys.shift_up)
{
Ok(self
.move_selection(MoveSelection::Home)
.into())
} else if key_match(e, self.key_config.keys.end)
|| key_match(e, self.key_config.keys.shift_down)
{
Ok(self.move_selection(MoveSelection::End).into())
} else if key_match(e, self.key_config.keys.page_up) {
Ok(self
.move_selection(MoveSelection::PageUp)
.into())
} else if key_match(e, self.key_config.keys.page_down)
{
Ok(self
.move_selection(MoveSelection::PageDown)
.into())
} else if key_match(e, self.key_config.keys.move_left)
{
Ok(self
.move_selection(MoveSelection::Left)
.into())
} else if key_match(
e,
self.key_config.keys.move_right,
) {
Ok(self
.move_selection(MoveSelection::Right)
.into())
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn focused(&self) -> bool {
self.focused
}
fn focus(&mut self, focus: bool) {
self.focused = focus;
self.show_selection(focus);
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn string_vec_to_status(items: &[&str]) -> Vec<StatusItem> {
items
.iter()
.map(|a| StatusItem {
path: String::from(*a),
status: StatusItemType::Modified,
})
.collect::<Vec<_>>()
}
#[test]
fn test_correct_scroll_position() {
let items = string_vec_to_status(&[
"a/b/b1", //
"a/b/b2", //
"a/c/c1", //
]);
//0 a/
//1 b/
//2 b1
//3 b2
//4 c/
//5 c1
// Set up test terminal
let test_backend =
ratatui::backend::TestBackend::new(100, 100);
let mut terminal = ratatui::Terminal::new(test_backend)
.expect("Unable to set up terminal");
let mut frame = terminal.get_frame();
// set up file tree
let mut ftc = StatusTreeComponent::new(
&Environment::test_env(),
"title",
true,
);
ftc.update(&items)
.expect("Updating FileTreeComponent failed");
ftc.move_selection(MoveSelection::Down); // Move to b/
ftc.move_selection(MoveSelection::Left); // Fold b/
ftc.move_selection(MoveSelection::Down); // Move to c/
ftc.draw(&mut frame, Rect::new(0, 0, 10, 5))
.expect("Draw failed");
assert_eq!(ftc.scroll_top.get(), 0); // should still be at top
}
#[test]
fn test_correct_foldup_and_not_visible_scroll_position() {
let items = string_vec_to_status(&[
"a/b/b1", //
"c/d1", //
"c/d2", //
]);
//0 a/b/
//2 b1
//3 c/
//4 d1
//5 d2
// Set up test terminal
let test_backend =
ratatui::backend::TestBackend::new(100, 100);
let mut terminal = ratatui::Terminal::new(test_backend)
.expect("Unable to set up terminal");
let mut frame = terminal.get_frame();
// set up file tree
let mut ftc = StatusTreeComponent::new(
&Environment::test_env(),
"title",
true,
);
ftc.update(&items)
.expect("Updating FileTreeComponent failed");
ftc.move_selection(MoveSelection::Left); // Fold a/b/
ftc.move_selection(MoveSelection::Down); // Move to c/
ftc.draw(&mut frame, Rect::new(0, 0, 10, 5))
.expect("Draw failed");
assert_eq!(ftc.scroll_top.get(), 0); // should still be at top
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/cred.rs | src/components/cred.rs | use anyhow::Result;
use crossterm::event::Event;
use ratatui::{layout::Rect, Frame};
use asyncgit::sync::cred::BasicAuthCredential;
use crate::app::Environment;
use crate::components::{EventState, InputType, TextInputComponent};
use crate::keys::key_match;
use crate::{
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent,
},
keys::SharedKeyConfig,
strings,
};
///
pub struct CredComponent {
visible: bool,
key_config: SharedKeyConfig,
input_username: TextInputComponent,
input_password: TextInputComponent,
cred: BasicAuthCredential,
}
impl CredComponent {
///
pub fn new(env: &Environment) -> Self {
let key_config = env.key_config.clone();
Self {
visible: false,
input_username: TextInputComponent::new(
env,
&strings::username_popup_title(&key_config),
&strings::username_popup_msg(&key_config),
false,
)
.with_input_type(InputType::Singleline),
input_password: TextInputComponent::new(
env,
&strings::password_popup_title(&key_config),
&strings::password_popup_msg(&key_config),
false,
)
.with_input_type(InputType::Password),
key_config,
cred: BasicAuthCredential::new(None, None),
}
}
pub fn set_cred(&mut self, cred: BasicAuthCredential) {
self.cred = cred;
}
pub const fn get_cred(&self) -> &BasicAuthCredential {
&self.cred
}
}
impl DrawableComponent for CredComponent {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.visible {
self.input_username.draw(f, rect)?;
self.input_password.draw(f, rect)?;
}
Ok(())
}
}
impl Component for CredComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
if !force_all {
out.clear();
}
out.push(CommandInfo::new(
strings::commands::validate_msg(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
true,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.visible {
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.exit_popup) {
self.hide();
return Ok(EventState::Consumed);
}
if self.input_username.event(ev)?.is_consumed()
|| self.input_password.event(ev)?.is_consumed()
{
return Ok(EventState::Consumed);
} else if key_match(e, self.key_config.keys.enter) {
if self.input_username.is_visible() {
self.cred = BasicAuthCredential::new(
Some(
self.input_username
.get_text()
.to_string(),
),
None,
);
self.input_username.hide();
self.input_password.show()?;
} else if self.input_password.is_visible() {
self.cred = BasicAuthCredential::new(
self.cred.username.clone(),
Some(
self.input_password
.get_text()
.to_string(),
),
);
self.input_password.hide();
self.input_password.clear();
return Ok(EventState::NotConsumed);
} else {
self.hide();
}
}
}
return Ok(EventState::Consumed);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.cred = BasicAuthCredential::new(None, None);
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
if self.cred.username.is_none() {
self.input_username.show()
} else if self.cred.password.is_none() {
self.input_password.show()
} else {
Ok(())
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/mod.rs | src/components/mod.rs | /*!
Components are the visible building blocks in gitui.
They have a state, handle events, and render to the terminal:
* Some are full screen. That would be all the [`tabs`](super::tabs).
* Some look like panels, eg [`CommitDetailsComponent`]
* Some overlap others. They are collected in module [`popups`](super::popups)
* Some are decorations, eg [`HorizontalScroll`](utils::scroll_horizontal::HorizontalScroll).
Components can be reused.
For example, [`CommitList`] is used in both tab "revlog" and tab "stashlist".
## Composition
In gitui, composition is driven by code. This means each component must
have code that explicitly forwards component function calls like draw,
commands and event to the components it is composed of.
Other systems use composition by data: They provide a generic data structure
that reflects the visual hierarchy, and uses it at runtime to
determine which code should be executed. This is not how gitui works.
## Traits
There are two traits defined here:
* [`Component`] handles events from the user,
* [`DrawableComponent`] renders to the terminal.
In the current codebase these are always implemented together, and it probably
makes more sense to merge them some time in the future.
It is a little strange that you implement `draw()` on a `DrawableComponent`,
but have function `hide()` from trait Component which does not know how
to `draw()`.
*/
mod changes;
mod command;
mod commit_details;
mod commitlist;
mod cred;
mod diff;
mod revision_files;
mod status_tree;
mod syntax_text;
mod textinput;
mod utils;
pub use self::status_tree::StatusTreeComponent;
pub use changes::ChangesComponent;
pub use command::{CommandInfo, CommandText};
pub use commit_details::CommitDetailsComponent;
pub use commitlist::CommitList;
pub use cred::CredComponent;
pub use diff::DiffComponent;
pub use revision_files::RevisionFilesComponent;
pub use syntax_text::SyntaxTextComponent;
pub use textinput::{InputType, TextInputComponent};
pub use utils::{
filetree::FileTreeItemKind, logitems::ItemBatch,
scroll_vertical::VerticalScroll, string_width_align,
time_to_string,
};
use crate::ui::style::Theme;
use anyhow::Result;
use crossterm::event::Event;
use ratatui::{
layout::{Alignment, Rect},
text::{Span, Text},
widgets::{Block, Borders, Paragraph},
Frame,
};
/// creates accessors for a list of components
///
/// allows generating code to make sure
/// we always enumerate all components in both getter functions
#[macro_export]
macro_rules! accessors {
($self:ident, [$($element:ident),+]) => {
fn components(& $self) -> Vec<&dyn Component> {
vec![
$(&$self.$element,)+
]
}
fn components_mut(&mut $self) -> Vec<&mut dyn Component> {
vec![
$(&mut $self.$element,)+
]
}
};
}
/// creates a function to determine if any popup is visible
#[macro_export]
macro_rules! any_popup_visible {
($self:ident, [$($element:ident),+]) => {
fn any_popup_visible(& $self) -> bool{
($($self.$element.is_visible()) || +)
}
};
}
/// creates the draw popup function
#[macro_export]
macro_rules! draw_popups {
($self:ident, [$($element:ident),+]) => {
fn draw_popups(& $self, mut f: &mut Frame) -> Result<()>{
//TODO: move the layout part out and feed it into `draw_popups`
let size = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Min(1),
Constraint::Length($self.cmdbar.borrow().height()),
]
.as_ref(),
)
.split(f.area())[0];
($($self.$element.draw(&mut f, size)?) , +);
return Ok(());
}
};
}
/// simply calls
/// `any_popup_visible`!() and `draw_popups`!() macros
#[macro_export]
macro_rules! setup_popups {
($self:ident, [$($element:ident),+]) => {
$crate::any_popup_visible!($self, [$($element),+]);
$crate::draw_popups!($self, [ $($element),+ ]);
};
}
/// returns `true` if event was consumed
pub fn event_pump(
ev: &Event,
components: &mut [&mut dyn Component],
) -> Result<EventState> {
for c in components {
if c.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
/// helper fn to simplify delegating command
/// gathering down into child components
/// see `event_pump`,`accessors`
pub fn command_pump(
out: &mut Vec<CommandInfo>,
force_all: bool,
components: &[&dyn Component],
) {
for c in components {
if c.commands(out, force_all) != CommandBlocking::PassingOn
&& !force_all
{
break;
}
}
}
#[derive(Copy, Clone)]
pub enum ScrollType {
Up,
Down,
Home,
End,
PageUp,
PageDown,
}
#[derive(Copy, Clone)]
pub enum HorizontalScrollType {
Left,
Right,
}
#[derive(Copy, Clone)]
pub enum Direction {
Up,
Down,
}
///
#[derive(PartialEq, Eq)]
pub enum CommandBlocking {
Blocking,
PassingOn,
}
///
pub fn visibility_blocking<T: Component>(
comp: &T,
) -> CommandBlocking {
if comp.is_visible() {
CommandBlocking::Blocking
} else {
CommandBlocking::PassingOn
}
}
///
pub trait DrawableComponent {
///
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()>;
}
///
#[derive(PartialEq, Eq)]
pub enum EventState {
Consumed,
NotConsumed,
}
#[derive(Copy, Clone)]
pub enum FuzzyFinderTarget {
Branches,
Files,
}
impl EventState {
pub fn is_consumed(&self) -> bool {
*self == Self::Consumed
}
}
impl From<bool> for EventState {
fn from(consumed: bool) -> Self {
if consumed {
Self::Consumed
} else {
Self::NotConsumed
}
}
}
/// base component trait
pub trait Component {
///
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking;
///
fn event(&mut self, ev: &Event) -> Result<EventState>;
///
fn focused(&self) -> bool {
false
}
/// focus/unfocus this component depending on param
fn focus(&mut self, _focus: bool) {}
///
fn is_visible(&self) -> bool {
true
}
///
fn hide(&mut self) {}
///
fn show(&mut self) -> Result<()> {
Ok(())
}
///
fn toggle_visible(&mut self) -> Result<()> {
if self.is_visible() {
self.hide();
Ok(())
} else {
self.show()
}
}
}
fn dialog_paragraph<'a>(
title: &'a str,
content: Text<'a>,
theme: &Theme,
focused: bool,
) -> Paragraph<'a> {
Paragraph::new(content)
.block(
Block::default()
.title(Span::styled(title, theme.title(focused)))
.borders(Borders::ALL)
.border_style(theme.block(focused)),
)
.alignment(Alignment::Left)
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/changes.rs | src/components/changes.rs | use super::{
status_tree::StatusTreeComponent,
utils::filetree::{FileTreeItem, FileTreeItemKind},
CommandBlocking, DrawableComponent,
};
use crate::{
app::Environment,
components::{CommandInfo, Component, EventState},
keys::{key_match, SharedKeyConfig},
options::SharedOptions,
queue::{Action, InternalEvent, NeedsUpdate, Queue, ResetItem},
strings, try_or_popup,
};
use anyhow::Result;
use asyncgit::{
sync::{self, RepoPathRef},
StatusItem, StatusItemType,
};
use crossterm::event::Event;
use ratatui::{layout::Rect, Frame};
use std::path::Path;
///
pub struct ChangesComponent {
repo: RepoPathRef,
files: StatusTreeComponent,
is_working_dir: bool,
queue: Queue,
key_config: SharedKeyConfig,
options: SharedOptions,
}
impl ChangesComponent {
///
pub fn new(
env: &Environment,
title: &str,
focus: bool,
is_working_dir: bool,
) -> Self {
Self {
files: StatusTreeComponent::new(env, title, focus),
is_working_dir,
queue: env.queue.clone(),
key_config: env.key_config.clone(),
options: env.options.clone(),
repo: env.repo.clone(),
}
}
///
pub fn set_items(&mut self, list: &[StatusItem]) -> Result<()> {
self.files.show()?;
self.files.update(list)?;
Ok(())
}
///
pub fn selection(&self) -> Option<FileTreeItem> {
self.files.selection()
}
///
pub fn focus_select(&mut self, focus: bool) {
self.files.focus(focus);
self.files.show_selection(focus);
}
/// returns true if list is empty
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
///
pub fn is_file_selected(&self) -> bool {
self.files.is_file_selected()
}
fn index_add_remove(&self) -> Result<bool> {
if let Some(tree_item) = self.selection() {
if self.is_working_dir {
if let FileTreeItemKind::File(i) = tree_item.kind {
let path = Path::new(i.path.as_str());
match i.status {
StatusItemType::Deleted => {
sync::stage_addremoved(
&self.repo.borrow(),
path,
)?;
}
_ => sync::stage_add_file(
&self.repo.borrow(),
path,
)?,
}
} else {
let config =
self.options.borrow().status_show_untracked();
//TODO: check if we can handle the one file case with it as well
sync::stage_add_all(
&self.repo.borrow(),
tree_item.info.full_path.as_str(),
config,
)?;
}
//TODO: this might be slow in big repos,
// in theory we should be able to ask the tree structure
// if we are currently on a leaf or a lonely branch that
// would mean that after staging the workdir becomes empty
if sync::is_workdir_clean(
&self.repo.borrow(),
self.options.borrow().status_show_untracked(),
)? {
self.queue
.push(InternalEvent::StatusLastFileMoved);
}
} else {
// this is a staged entry, so lets unstage it
let path = tree_item.info.full_path.as_str();
sync::reset_stage(&self.repo.borrow(), path)?;
}
return Ok(true);
}
Ok(false)
}
fn index_add_all(&self) -> Result<()> {
let config = self.options.borrow().status_show_untracked();
sync::stage_add_all(&self.repo.borrow(), "*", config)?;
self.queue.push(InternalEvent::Update(NeedsUpdate::ALL));
Ok(())
}
fn stage_remove_all(&self) -> Result<()> {
sync::reset_stage(&self.repo.borrow(), "*")?;
self.queue.push(InternalEvent::Update(NeedsUpdate::ALL));
Ok(())
}
fn dispatch_reset_workdir(&self) -> bool {
if let Some(tree_item) = self.selection() {
self.queue.push(InternalEvent::ConfirmAction(
Action::Reset(ResetItem {
path: tree_item.info.full_path,
}),
));
return true;
}
false
}
fn add_to_ignore(&self) -> bool {
if let Some(tree_item) = self.selection() {
if let Err(e) = sync::add_to_ignore(
&self.repo.borrow(),
&tree_item.info.full_path,
) {
self.queue.push(InternalEvent::ShowErrorMsg(
format!(
"ignore error:\n{}\nfile:\n{:?}",
e, tree_item.info.full_path
),
));
} else {
self.queue
.push(InternalEvent::Update(NeedsUpdate::ALL));
return true;
}
}
false
}
}
impl DrawableComponent for ChangesComponent {
fn draw(&self, f: &mut Frame, r: Rect) -> Result<()> {
self.files.draw(f, r)?;
Ok(())
}
}
impl Component for ChangesComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
self.files.commands(out, force_all);
let some_selection = self.selection().is_some();
if self.is_working_dir {
out.push(CommandInfo::new(
strings::commands::stage_all(&self.key_config),
true,
some_selection && self.focused(),
));
out.push(CommandInfo::new(
strings::commands::stage_item(&self.key_config),
true,
some_selection && self.focused(),
));
out.push(CommandInfo::new(
strings::commands::reset_item(&self.key_config),
true,
some_selection && self.focused(),
));
out.push(CommandInfo::new(
strings::commands::ignore_item(&self.key_config),
true,
some_selection && self.focused(),
));
} else {
out.push(CommandInfo::new(
strings::commands::unstage_item(&self.key_config),
true,
some_selection && self.focused(),
));
out.push(CommandInfo::new(
strings::commands::unstage_all(&self.key_config),
true,
some_selection && self.focused(),
));
}
CommandBlocking::PassingOn
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.files.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if self.focused() {
if let Event::Key(e) = ev {
return if key_match(
e,
self.key_config.keys.stage_unstage_item,
) {
try_or_popup!(
self,
"staging error:",
self.index_add_remove()
);
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL,
));
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.status_stage_all,
) && !self.is_empty()
{
if self.is_working_dir {
try_or_popup!(
self,
"staging all error:",
self.index_add_all()
);
} else {
self.stage_remove_all()?;
}
self.queue
.push(InternalEvent::StatusLastFileMoved);
Ok(EventState::Consumed)
} else if key_match(
e,
self.key_config.keys.status_reset_item,
) && self.is_working_dir
{
Ok(self.dispatch_reset_workdir().into())
} else if key_match(
e,
self.key_config.keys.status_ignore_file,
) && self.is_working_dir
&& !self.is_empty()
{
Ok(self.add_to_ignore().into())
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn focused(&self) -> bool {
self.files.focused()
}
fn focus(&mut self, focus: bool) {
self.files.focus(focus);
}
fn is_visible(&self) -> bool {
self.files.is_visible()
}
fn hide(&mut self) {
self.files.hide();
}
fn show(&mut self) -> Result<()> {
self.files.show()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/commit_details/compare_details.rs | src/components/commit_details/compare_details.rs | use std::borrow::Cow;
use crate::{
app::Environment,
components::{
commit_details::style::{style_detail, Detail},
dialog_paragraph,
utils::time_to_string,
CommandBlocking, CommandInfo, Component, DrawableComponent,
EventState,
},
strings::{self},
ui::style::SharedTheme,
};
use anyhow::Result;
use asyncgit::sync::{
self, commit_files::OldNew, CommitDetails, CommitId, RepoPathRef,
};
use crossterm::event::Event;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
text::{Line, Span, Text},
Frame,
};
pub struct CompareDetailsComponent {
repo: RepoPathRef,
data: Option<OldNew<CommitDetails>>,
theme: SharedTheme,
focused: bool,
}
impl CompareDetailsComponent {
///
pub fn new(env: &Environment, focused: bool) -> Self {
Self {
data: None,
theme: env.theme.clone(),
focused,
repo: env.repo.clone(),
}
}
pub fn set_commits(&mut self, ids: Option<OldNew<CommitId>>) {
self.data = ids.and_then(|ids| {
let old = sync::get_commit_details(
&self.repo.borrow(),
ids.old,
)
.ok()?;
let new = sync::get_commit_details(
&self.repo.borrow(),
ids.new,
)
.ok()?;
Some(OldNew { old, new })
});
}
fn get_commit_text(&self, data: &CommitDetails) -> Vec<Line<'_>> {
let mut res = vec![
Line::from(vec![
style_detail(&self.theme, &Detail::Author),
Span::styled(
Cow::from(format!(
"{} <{}>",
data.author.name, data.author.email
)),
self.theme.text(true, false),
),
]),
Line::from(vec![
style_detail(&self.theme, &Detail::Date),
Span::styled(
Cow::from(time_to_string(
data.author.time,
false,
)),
self.theme.text(true, false),
),
]),
];
res.push(Line::from(vec![
style_detail(&self.theme, &Detail::Message),
Span::styled(
Cow::from(
data.message
.as_ref()
.map(|msg| msg.subject.clone())
.unwrap_or_default(),
),
self.theme.text(true, false),
),
]));
res
}
}
impl DrawableComponent for CompareDetailsComponent {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Length(5), Constraint::Length(5)]
.as_ref(),
)
.split(rect);
if let Some(data) = &self.data {
f.render_widget(
dialog_paragraph(
&strings::commit::compare_details_info_title(
true,
data.old.short_hash(),
),
Text::from(self.get_commit_text(&data.old)),
&self.theme,
false,
),
chunks[0],
);
f.render_widget(
dialog_paragraph(
&strings::commit::compare_details_info_title(
false,
data.new.short_hash(),
),
Text::from(self.get_commit_text(&data.new)),
&self.theme,
false,
),
chunks[1],
);
}
Ok(())
}
}
impl Component for CompareDetailsComponent {
fn commands(
&self,
_out: &mut Vec<CommandInfo>,
_force_all: bool,
) -> CommandBlocking {
CommandBlocking::PassingOn
}
fn event(&mut self, _event: &Event) -> Result<EventState> {
Ok(EventState::NotConsumed)
}
fn focused(&self) -> bool {
self.focused
}
fn focus(&mut self, focus: bool) {
self.focused = focus;
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/commit_details/mod.rs | src/components/commit_details/mod.rs | mod compare_details;
mod details;
mod style;
use super::{
command_pump, event_pump, CommandBlocking, CommandInfo,
Component, DrawableComponent, EventState, StatusTreeComponent,
};
use crate::{
accessors,
app::Environment,
keys::{key_match, SharedKeyConfig},
strings,
};
use anyhow::Result;
use asyncgit::{
sync::{commit_files::OldNew, CommitTags},
AsyncCommitFiles, CommitFilesParams,
};
use compare_details::CompareDetailsComponent;
use crossterm::event::Event;
use details::DetailsComponent;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
Frame,
};
pub struct CommitDetailsComponent {
commit: Option<CommitFilesParams>,
single_details: DetailsComponent,
compare_details: CompareDetailsComponent,
file_tree: StatusTreeComponent,
git_commit_files: AsyncCommitFiles,
visible: bool,
key_config: SharedKeyConfig,
}
impl CommitDetailsComponent {
accessors!(self, [single_details, compare_details, file_tree]);
///
pub fn new(env: &Environment) -> Self {
Self {
single_details: DetailsComponent::new(env, false),
compare_details: CompareDetailsComponent::new(env, false),
git_commit_files: AsyncCommitFiles::new(
env.repo.borrow().clone(),
&env.sender_git,
),
file_tree: StatusTreeComponent::new(env, "", false),
visible: false,
commit: None,
key_config: env.key_config.clone(),
}
}
fn get_files_title(&self) -> String {
let files_count = self.file_tree.file_count();
format!(
"{} {}",
strings::commit::details_files_title(&self.key_config),
files_count
)
}
///
pub fn set_commits(
&mut self,
params: Option<CommitFilesParams>,
tags: Option<&CommitTags>,
) -> Result<()> {
if params.is_none() {
self.single_details.set_commit(None, None);
self.compare_details.set_commits(None);
}
self.commit = params;
if let Some(id) = params {
self.file_tree.set_commit(Some(id.id));
if let Some(other) = id.other {
self.compare_details.set_commits(Some(OldNew {
new: id.id,
old: other,
}));
} else {
self.single_details
.set_commit(Some(id.id), tags.cloned());
}
if let Some((fetched_id, res)) =
self.git_commit_files.current()?
{
if fetched_id == id {
self.file_tree.update(res.as_slice())?;
self.file_tree.set_title(self.get_files_title());
return Ok(());
}
}
self.file_tree.clear()?;
self.git_commit_files.fetch(id)?;
}
self.file_tree.set_title(self.get_files_title());
Ok(())
}
///
pub fn any_work_pending(&self) -> bool {
self.git_commit_files.is_pending()
}
///
pub const fn files(&self) -> &StatusTreeComponent {
&self.file_tree
}
fn details_focused(&self) -> bool {
self.single_details.focused()
|| self.compare_details.focused()
}
fn set_details_focus(&mut self, focus: bool) {
if self.is_compare() {
self.compare_details.focus(focus);
} else {
self.single_details.focus(focus);
}
}
fn is_compare(&self) -> bool {
self.commit.is_some_and(|p| p.other.is_some())
}
}
impl DrawableComponent for CommitDetailsComponent {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if !self.visible {
return Ok(());
}
let constraints = if self.is_compare() {
[Constraint::Length(10), Constraint::Min(0)]
} else {
let details_focused = self.details_focused();
let percentages = if self.file_tree.focused() {
(40, 60)
} else if details_focused {
(60, 40)
} else {
(40, 60)
};
[
Constraint::Percentage(percentages.0),
Constraint::Percentage(percentages.1),
]
};
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints.as_ref())
.split(rect);
if self.is_compare() {
self.compare_details.draw(f, chunks[0])?;
} else {
self.single_details.draw(f, chunks[0])?;
}
self.file_tree.draw(f, chunks[1])?;
Ok(())
}
}
impl Component for CommitDetailsComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
command_pump(
out,
force_all,
self.components().as_slice(),
);
}
CommandBlocking::PassingOn
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if event_pump(ev, self.components_mut().as_mut_slice())?
.is_consumed()
{
if !self.file_tree.is_visible() {
self.hide();
}
return Ok(EventState::Consumed);
}
if self.focused() {
if let Event::Key(e) = ev {
return if key_match(e, self.key_config.keys.move_down)
&& self.details_focused()
{
self.set_details_focus(false);
self.file_tree.focus(true);
Ok(EventState::Consumed)
} else if key_match(e, self.key_config.keys.move_up)
&& self.file_tree.focused()
&& !self.is_compare()
{
self.file_tree.focus(false);
self.set_details_focus(true);
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.file_tree.show()?;
Ok(())
}
fn focused(&self) -> bool {
self.details_focused() || self.file_tree.focused()
}
fn focus(&mut self, focus: bool) {
self.single_details.focus(false);
self.compare_details.focus(false);
self.file_tree.focus(focus);
self.file_tree.show_selection(true);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/commit_details/style.rs | src/components/commit_details/style.rs | use crate::{strings, ui::style::SharedTheme};
use ratatui::text::Span;
use std::borrow::Cow;
pub enum Detail {
Author,
Date,
Committer,
Sha,
Message,
}
pub fn style_detail<'a>(
theme: &'a SharedTheme,
field: &Detail,
) -> Span<'a> {
match field {
Detail::Author => Span::styled(
Cow::from(strings::commit::details_author()),
theme.text(false, false),
),
Detail::Date => Span::styled(
Cow::from(strings::commit::details_date()),
theme.text(false, false),
),
Detail::Committer => Span::styled(
Cow::from(strings::commit::details_committer()),
theme.text(false, false),
),
Detail::Sha => Span::styled(
Cow::from(strings::commit::details_tags()),
theme.text(false, false),
),
Detail::Message => Span::styled(
Cow::from(strings::commit::details_message()),
theme.text(false, false),
),
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/commit_details/details.rs | src/components/commit_details/details.rs | use crate::{
app::Environment,
components::{
commit_details::style::style_detail,
dialog_paragraph,
utils::{scroll_vertical::VerticalScroll, time_to_string},
CommandBlocking, CommandInfo, Component, DrawableComponent,
EventState, ScrollType,
},
keys::{key_match, SharedKeyConfig},
strings::{self, order},
ui::style::SharedTheme,
};
use anyhow::Result;
use asyncgit::sync::{
self, CommitDetails, CommitId, CommitMessage, RepoPathRef, Tag,
};
use crossterm::event::Event;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span, Text},
Frame,
};
use std::{borrow::Cow, cell::Cell};
use sync::CommitTags;
use super::style::Detail;
pub struct DetailsComponent {
repo: RepoPathRef,
data: Option<CommitDetails>,
tags: Vec<Tag>,
theme: SharedTheme,
focused: bool,
current_width: Cell<u16>,
scroll: VerticalScroll,
scroll_to_bottom_next_draw: Cell<bool>,
key_config: SharedKeyConfig,
}
type WrappedCommitMessage<'a> =
(Vec<Cow<'a, str>>, Vec<Cow<'a, str>>);
impl DetailsComponent {
///
pub fn new(env: &Environment, focused: bool) -> Self {
Self {
repo: env.repo.clone(),
data: None,
tags: Vec::new(),
theme: env.theme.clone(),
focused,
scroll_to_bottom_next_draw: Cell::new(false),
current_width: Cell::new(0),
scroll: VerticalScroll::new(),
key_config: env.key_config.clone(),
}
}
pub fn set_commit(
&mut self,
id: Option<CommitId>,
tags: Option<CommitTags>,
) {
self.tags.clear();
self.data = id.and_then(|id| {
sync::get_commit_details(&self.repo.borrow(), id).ok()
});
self.scroll.reset();
if let Some(tags) = tags {
self.tags.extend(tags);
}
}
fn wrap_commit_details(
message: &CommitMessage,
width: usize,
) -> WrappedCommitMessage<'_> {
let width = width.max(1);
let wrapped_title = bwrap::wrap!(&message.subject, width)
.lines()
.map(String::from)
.map(Cow::from)
.collect();
if let Some(ref body) = message.body {
let wrapped_message: Vec<Cow<'_, str>> =
bwrap::wrap!(body, width)
.lines()
.map(String::from)
.map(Cow::from)
.collect();
(wrapped_title, wrapped_message)
} else {
(wrapped_title, vec![])
}
}
fn get_wrapped_lines(
data: Option<&CommitDetails>,
width: usize,
) -> WrappedCommitMessage<'_> {
if let Some(data) = data {
if let Some(message) = &data.message {
return Self::wrap_commit_details(message, width);
}
}
(vec![], vec![])
}
fn get_number_of_lines(
details: Option<&CommitDetails>,
width: usize,
) -> usize {
let (wrapped_title, wrapped_message) =
Self::get_wrapped_lines(details, width);
wrapped_title.len() + wrapped_message.len()
}
fn get_theme_for_line(&self, bold: bool) -> Style {
if bold {
self.theme.text(true, false).add_modifier(Modifier::BOLD)
} else {
self.theme.text(true, false)
}
}
fn get_wrapped_text_message(
&self,
width: usize,
height: usize,
) -> Vec<Line<'_>> {
let (wrapped_title, wrapped_message) =
Self::get_wrapped_lines(self.data.as_ref(), width);
[&wrapped_title[..], &wrapped_message[..]]
.concat()
.iter()
.enumerate()
.skip(self.scroll.get_top())
.take(height)
.map(|(i, line)| {
Line::from(vec![Span::styled(
line.clone(),
self.get_theme_for_line(i < wrapped_title.len()),
)])
})
.collect()
}
#[allow(clippy::too_many_lines)]
fn get_text_info(&self) -> Vec<Line<'_>> {
self.data.as_ref().map_or_else(Vec::new, |data| {
let mut res = vec![
Line::from(vec![
style_detail(&self.theme, &Detail::Author),
Span::styled(
Cow::from(format!(
"{} <{}>",
data.author.name, data.author.email
)),
self.theme.text(true, false),
),
]),
Line::from(vec![
style_detail(&self.theme, &Detail::Date),
Span::styled(
Cow::from(time_to_string(
data.author.time,
false,
)),
self.theme.text(true, false),
),
]),
];
if let Some(ref committer) = data.committer {
res.extend(vec![
Line::from(vec![
style_detail(&self.theme, &Detail::Committer),
Span::styled(
Cow::from(format!(
"{} <{}>",
committer.name, committer.email
)),
self.theme.text(true, false),
),
]),
Line::from(vec![
style_detail(&self.theme, &Detail::Date),
Span::styled(
Cow::from(time_to_string(
committer.time,
false,
)),
self.theme.text(true, false),
),
]),
]);
}
res.push(Line::from(vec![
Span::styled(
Cow::from(strings::commit::details_sha()),
self.theme.text(false, false),
),
Span::styled(
Cow::from(data.hash.clone()),
self.theme.text(true, false),
),
]));
if !self.tags.is_empty() {
res.push(Line::from(style_detail(
&self.theme,
&Detail::Sha,
)));
res.push(Line::from(
itertools::Itertools::intersperse(
self.tags.iter().map(|tag| {
Span::styled(
Cow::from(&tag.name),
self.theme.text(true, false),
)
}),
Span::styled(
Cow::from(","),
self.theme.text(true, false),
),
)
.collect::<Vec<Span>>(),
));
}
res
})
}
fn move_scroll_top(&self, move_type: ScrollType) -> bool {
if self.data.is_some() {
self.scroll.move_top(move_type)
} else {
false
}
}
}
impl DrawableComponent for DetailsComponent {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
const CANSCROLL_STRING: &str = "[\u{2026}]";
const EMPTY_STRING: &str = "";
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Length(8), Constraint::Min(10)].as_ref(),
)
.split(rect);
f.render_widget(
dialog_paragraph(
&strings::commit::details_info_title(
&self.key_config,
),
Text::from(self.get_text_info()),
&self.theme,
false,
),
chunks[0],
);
// We have to take the border into account which is one character on
// each side.
let border_width: u16 = 2;
let width = chunks[1].width.saturating_sub(border_width);
let height = chunks[1].height.saturating_sub(border_width);
self.current_width.set(width);
let number_of_lines = Self::get_number_of_lines(
self.data.as_ref(),
usize::from(width),
);
self.scroll.update_no_selection(
number_of_lines,
usize::from(height),
);
if self.scroll_to_bottom_next_draw.get() {
self.scroll.move_top(ScrollType::End);
self.scroll_to_bottom_next_draw.set(false);
}
let can_scroll = usize::from(height) < number_of_lines;
f.render_widget(
dialog_paragraph(
&format!(
"{} {}",
strings::commit::details_message_title(
&self.key_config,
),
if !self.focused && can_scroll {
CANSCROLL_STRING
} else {
EMPTY_STRING
}
),
Text::from(self.get_wrapped_text_message(
width as usize,
height as usize,
)),
&self.theme,
self.focused,
),
chunks[1],
);
if self.focused {
self.scroll.draw(f, chunks[1], &self.theme);
}
Ok(())
}
}
impl Component for DetailsComponent {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
let width = usize::from(self.current_width.get());
let number_of_lines =
Self::get_number_of_lines(self.data.as_ref(), width);
out.push(
CommandInfo::new(
strings::commands::navigate_commit_message(
&self.key_config,
),
number_of_lines > 0,
self.focused || force_all,
)
.order(order::NAV),
);
CommandBlocking::PassingOn
}
fn event(&mut self, event: &Event) -> Result<EventState> {
if self.focused {
if let Event::Key(e) = event {
return Ok(
if key_match(e, self.key_config.keys.move_up) {
self.move_scroll_top(ScrollType::Up).into()
} else if key_match(
e,
self.key_config.keys.move_down,
) {
self.move_scroll_top(ScrollType::Down).into()
} else if key_match(
e,
self.key_config.keys.page_up,
) {
self.move_scroll_top(ScrollType::PageUp)
.into()
} else if key_match(
e,
self.key_config.keys.page_down,
) {
self.move_scroll_top(ScrollType::PageDown)
.into()
} else if key_match(e, self.key_config.keys.home)
|| key_match(e, self.key_config.keys.shift_up)
{
self.move_scroll_top(ScrollType::Home).into()
} else if key_match(e, self.key_config.keys.end)
|| key_match(
e,
self.key_config.keys.shift_down,
) {
self.move_scroll_top(ScrollType::End).into()
} else {
EventState::NotConsumed
},
);
}
}
Ok(EventState::NotConsumed)
}
fn focused(&self) -> bool {
self.focused
}
fn focus(&mut self, focus: bool) {
if focus {
self.scroll_to_bottom_next_draw.set(true);
} else {
self.scroll.reset();
}
self.focused = focus;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn get_wrapped_lines(
message: &CommitMessage,
width: usize,
) -> Vec<Cow<'_, str>> {
let (wrapped_title, wrapped_message) =
DetailsComponent::wrap_commit_details(message, width);
[&wrapped_title[..], &wrapped_message[..]].concat()
}
#[test]
fn test_textwrap() {
let message = CommitMessage::from("Commit message");
assert_eq!(
get_wrapped_lines(&message, 7),
vec!["Commit", "message"]
);
assert_eq!(
get_wrapped_lines(&message, 14),
vec!["Commit message"]
);
assert_eq!(
get_wrapped_lines(&message, 0),
vec!["Commit", "message"]
);
let message_with_newline =
CommitMessage::from("Commit message\n");
assert_eq!(
get_wrapped_lines(&message_with_newline, 7),
vec!["Commit", "message"]
);
assert_eq!(
get_wrapped_lines(&message_with_newline, 14),
vec!["Commit message"]
);
assert_eq!(
get_wrapped_lines(&message, 0),
vec!["Commit", "message"]
);
let message_with_body = CommitMessage::from(
"Commit message\nFirst line\nSecond line",
);
assert_eq!(
get_wrapped_lines(&message_with_body, 7),
vec![
"Commit", "message", "First", "line", "Second",
"line"
]
);
assert_eq!(
get_wrapped_lines(&message_with_body, 14),
vec!["Commit message", "First line", "Second line"]
);
assert_eq!(
get_wrapped_lines(&message_with_body, 7),
vec![
"Commit", "message", "First", "line", "Second",
"line"
]
);
}
}
#[cfg(test)]
mod test_line_count {
use super::*;
#[test]
fn test_smoke() {
let commit = CommitDetails {
message: Some(CommitMessage {
subject: String::from("subject line"),
body: Some(String::from("body lone")),
}),
..CommitDetails::default()
};
let lines = DetailsComponent::get_number_of_lines(
Some(commit.clone()).as_ref(),
50,
);
assert_eq!(lines, 2);
let lines = DetailsComponent::get_number_of_lines(
Some(commit).as_ref(),
8,
);
assert_eq!(lines, 4);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/statustree.rs | src/components/utils/statustree.rs | use super::filetree::{
FileTreeItem, FileTreeItemKind, FileTreeItems, PathCollapsed,
};
use anyhow::Result;
use asyncgit::StatusItem;
use std::{cell::Cell, cmp, collections::BTreeSet};
//TODO: use new `filetreelist` crate
///
#[derive(Default)]
pub struct StatusTree {
pub tree: FileTreeItems,
pub selection: Option<usize>,
// some folders may be folded up, this allows jumping
// over folders which are folded into their parent
pub available_selections: Vec<usize>,
pub window_height: Cell<Option<usize>>,
}
///
#[derive(Copy, Clone, Debug)]
pub enum MoveSelection {
Up,
Down,
Left,
Right,
Home,
End,
PageDown,
PageUp,
}
#[derive(Copy, Clone, Debug)]
struct SelectionChange {
new_index: usize,
changes: bool,
}
impl SelectionChange {
const fn new(new_index: usize, changes: bool) -> Self {
Self { new_index, changes }
}
}
impl StatusTree {
/// update tree with a new list, try to retain selection and collapse states
pub fn update(&mut self, list: &[StatusItem]) -> Result<()> {
let last_collapsed = self.all_collapsed();
let last_selection =
self.selected_item().map(|e| e.info.full_path);
let last_selection_index = self.selection.unwrap_or(0);
self.tree = FileTreeItems::new(list, &last_collapsed)?;
self.selection = last_selection.as_ref().map_or_else(
|| self.tree.items().first().map(|_| 0),
|last_selection| {
self.find_last_selection(
last_selection,
last_selection_index,
)
.or_else(|| self.tree.items().first().map(|_| 0))
},
);
self.update_visibility(None, 0, true);
self.available_selections = self.setup_available_selections();
//NOTE: now that visibility is set we can make sure selection is visible
if let Some(idx) = self.selection {
self.selection = Some(self.find_visible_idx(idx));
}
Ok(())
}
/// Return which indices can be selected, taking into account that
/// some folders may be folded up into their parent
///
/// It should be impossible to select a folder which has been folded into its parent
fn setup_available_selections(&self) -> Vec<usize> {
// use the same algorithm as in filetree build_vec_text_for_drawing function
let mut should_skip_over: usize = 0;
let mut vec_available_selections: Vec<usize> = vec![];
let tree_items = self.tree.items();
for index in 0..tree_items.len() {
if should_skip_over > 0 {
should_skip_over -= 1;
continue;
}
let mut idx_temp = index;
vec_available_selections.push(index);
while idx_temp < tree_items.len().saturating_sub(2)
&& tree_items[idx_temp].info.indent
< tree_items[idx_temp + 1].info.indent
{
// fold up the folder/file
idx_temp += 1;
should_skip_over += 1;
// don't fold files up
if let FileTreeItemKind::File(_) =
&tree_items[idx_temp].kind
{
should_skip_over -= 1;
break;
}
// don't fold up if more than one folder in folder
if self.tree.multiple_items_at_path(idx_temp) {
should_skip_over -= 1;
break;
}
}
}
vec_available_selections
}
fn find_visible_idx(&self, mut idx: usize) -> usize {
while idx > 0 {
if self.is_visible_index(idx) {
break;
}
idx -= 1;
}
idx
}
///
pub fn move_selection(&mut self, dir: MoveSelection) -> bool {
self.selection.is_some_and(|selection| {
let selection_change = match dir {
MoveSelection::Up => {
self.selection_updown(selection, true)
}
MoveSelection::Down => {
self.selection_updown(selection, false)
}
MoveSelection::Left => self.selection_left(selection),
MoveSelection::Right => {
self.selection_right(selection)
}
MoveSelection::Home => SelectionChange::new(0, false),
MoveSelection::End => self.selection_end(),
MoveSelection::PageUp => self.selection_page_updown(
selection,
(0..=selection).rev(),
),
MoveSelection::PageDown => self
.selection_page_updown(
selection,
selection..(self.tree.len()),
),
};
let changed_index =
selection_change.new_index != selection;
self.selection = Some(selection_change.new_index);
changed_index || selection_change.changes
})
}
///
pub fn selected_item(&self) -> Option<FileTreeItem> {
self.selection.map(|i| self.tree[i].clone())
}
///
pub fn is_empty(&self) -> bool {
self.tree.items().is_empty()
}
fn all_collapsed(&self) -> BTreeSet<&String> {
let mut res = BTreeSet::new();
for i in self.tree.items() {
if let FileTreeItemKind::Path(PathCollapsed(collapsed)) =
i.kind
{
if collapsed {
res.insert(&i.info.full_path);
}
}
}
res
}
fn find_last_selection(
&self,
last_selection: &str,
last_index: usize,
) -> Option<usize> {
if self.is_empty() {
return None;
}
if let Ok(i) = self.tree.items().binary_search_by(|e| {
e.info.full_path.as_str().cmp(last_selection)
}) {
return Some(i);
}
Some(cmp::min(last_index, self.tree.len() - 1))
}
fn selection_updown(
&self,
current_index: usize,
up: bool,
) -> SelectionChange {
let mut current_index_in_available_selections;
let mut cur_index_find = current_index;
if self.available_selections.is_empty() {
// Go to top
current_index_in_available_selections = 0;
} else {
loop {
if let Some(pos) = self
.available_selections
.iter()
.position(|i| *i == cur_index_find)
{
current_index_in_available_selections = pos;
break;
}
// Find the closest to the index, usually this shouldn't happen
if current_index == 0 {
// This should never happen
current_index_in_available_selections = 0;
break;
}
cur_index_find -= 1;
}
}
let mut new_index;
loop {
// Use available_selections to go to the correct selection as
// some of the folders may be folded up
new_index = if up {
current_index_in_available_selections =
current_index_in_available_selections
.saturating_sub(1);
self.available_selections
[current_index_in_available_selections]
} else if current_index_in_available_selections
.saturating_add(1)
<= self.available_selections.len().saturating_sub(1)
{
current_index_in_available_selections =
current_index_in_available_selections
.saturating_add(1);
self.available_selections
[current_index_in_available_selections]
} else {
// can't move down anymore
new_index = current_index;
break;
};
if self.is_visible_index(new_index) {
break;
}
}
SelectionChange::new(new_index, false)
}
fn selection_end(&self) -> SelectionChange {
let items_max = self.tree.len().saturating_sub(1);
let mut new_index = items_max;
loop {
if self.is_visible_index(new_index) {
break;
}
if new_index == 0 {
break;
}
new_index = new_index.saturating_sub(1);
new_index = cmp::min(new_index, items_max);
}
SelectionChange::new(new_index, false)
}
fn selection_page_updown(
&self,
current_index: usize,
range: impl Iterator<Item = usize>,
) -> SelectionChange {
let page_size = self.window_height.get().unwrap_or(0);
let new_index = range
.filter(|index| {
self.available_selections.contains(index)
&& self.is_visible_index(*index)
})
.take(page_size)
.last()
.unwrap_or(current_index);
SelectionChange::new(new_index, false)
}
fn is_visible_index(&self, idx: usize) -> bool {
self.tree[idx].info.visible
}
fn selection_right(
&mut self,
current_selection: usize,
) -> SelectionChange {
let item_kind = self.tree[current_selection].kind.clone();
let item_path =
self.tree[current_selection].info.full_path.clone();
match item_kind {
FileTreeItemKind::Path(PathCollapsed(collapsed))
if collapsed =>
{
self.expand(&item_path, current_selection);
return SelectionChange::new(current_selection, true);
}
FileTreeItemKind::Path(PathCollapsed(collapsed))
if !collapsed =>
{
return self
.selection_updown(current_selection, false);
}
_ => (),
}
SelectionChange::new(current_selection, false)
}
fn selection_left(
&mut self,
current_selection: usize,
) -> SelectionChange {
let item_kind = self.tree[current_selection].kind.clone();
let item_path =
self.tree[current_selection].info.full_path.clone();
if matches!(item_kind, FileTreeItemKind::File(_))
|| matches!(item_kind,FileTreeItemKind::Path(PathCollapsed(collapsed))
if collapsed)
{
let mut cur_parent =
self.tree.find_parent_index(current_selection);
while !self.available_selections.contains(&cur_parent)
&& cur_parent != 0
{
cur_parent = self.tree.find_parent_index(cur_parent);
}
SelectionChange::new(cur_parent, false)
} else if matches!(item_kind, FileTreeItemKind::Path(PathCollapsed(collapsed))
if !collapsed)
{
self.collapse(&item_path, current_selection);
SelectionChange::new(current_selection, true)
} else {
SelectionChange::new(current_selection, false)
}
}
fn collapse(&mut self, path: &str, index: usize) {
if let FileTreeItemKind::Path(PathCollapsed(
ref mut collapsed,
)) = self.tree[index].kind
{
*collapsed = true;
}
let path = format!("{path}/");
for i in index + 1..self.tree.len() {
let item = &mut self.tree[i];
let item_path = &item.info.full_path;
if item_path.starts_with(&path) {
item.info.visible = false;
} else {
return;
}
}
}
fn expand(&mut self, path: &str, current_index: usize) {
if let FileTreeItemKind::Path(PathCollapsed(
ref mut collapsed,
)) = self.tree[current_index].kind
{
*collapsed = false;
}
let path = format!("{path}/");
self.update_visibility(
Some(path.as_str()),
current_index + 1,
false,
);
}
fn update_visibility(
&mut self,
prefix: Option<&str>,
start_idx: usize,
set_defaults: bool,
) {
// if we are in any subpath that is collapsed we keep skipping over it
let mut inner_collapsed: Option<String> = None;
for i in start_idx..self.tree.len() {
if let Some(ref collapsed_path) = inner_collapsed {
let p: &String = &self.tree[i].info.full_path;
if p.starts_with(collapsed_path) {
if set_defaults {
self.tree[i].info.visible = false;
}
// we are still in a collapsed inner path
continue;
}
inner_collapsed = None;
}
let item_kind = self.tree[i].kind.clone();
let item_path = &self.tree[i].info.full_path;
if matches!(item_kind, FileTreeItemKind::Path(PathCollapsed(collapsed)) if collapsed)
{
// we encountered an inner path that is still collapsed
inner_collapsed = Some(format!("{}/", &item_path));
}
if prefix
.is_none_or(|prefix| item_path.starts_with(prefix))
{
self.tree[i].info.visible = true;
} else {
// if we do not set defaults we can early out
if set_defaults {
self.tree[i].info.visible = false;
} else {
return;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use asyncgit::StatusItemType;
fn string_vec_to_status(items: &[&str]) -> Vec<StatusItem> {
items
.iter()
.map(|a| StatusItem {
path: String::from(*a),
status: StatusItemType::Modified,
})
.collect::<Vec<_>>()
}
fn get_visible(tree: &StatusTree) -> Vec<bool> {
tree.tree
.items()
.iter()
.map(|e| e.info.visible)
.collect::<Vec<_>>()
}
#[test]
fn test_selection() {
let items = string_vec_to_status(&[
"a/b", //
]);
let mut res = StatusTree::default();
res.update(&items).unwrap();
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(1));
assert!(res.move_selection(MoveSelection::Left));
assert_eq!(res.selection, Some(0));
}
#[test]
fn test_keep_selected_item() {
let mut res = StatusTree::default();
res.update(&string_vec_to_status(&["b"])).unwrap();
assert_eq!(res.selection, Some(0));
res.update(&string_vec_to_status(&["a", "b"])).unwrap();
assert_eq!(res.selection, Some(1));
}
#[test]
fn test_keep_selected_index() {
let mut res = StatusTree::default();
res.update(&string_vec_to_status(&["a", "b"])).unwrap();
res.selection = Some(1);
res.update(&string_vec_to_status(&["d", "c", "a"])).unwrap();
assert_eq!(res.selection, Some(1));
}
#[test]
fn test_keep_selected_index_if_not_collapsed() {
let mut res = StatusTree::default();
res.update(&string_vec_to_status(&["a/b", "c"])).unwrap();
res.collapse("a/b", 0);
res.selection = Some(2);
res.update(&string_vec_to_status(&["a/b"])).unwrap();
assert_eq!(
get_visible(&res),
vec![
true, //
false, //
]
);
assert!(res.is_visible_index(res.selection.unwrap()));
assert_eq!(res.selection, Some(0));
}
#[test]
fn test_keep_collapsed_states() {
let mut res = StatusTree::default();
res.update(&string_vec_to_status(&[
"a/b", //
"c",
]))
.unwrap();
res.collapse("a", 0);
assert_eq!(
res.all_collapsed().iter().collect::<Vec<_>>(),
vec![&&String::from("a")]
);
assert_eq!(
get_visible(&res),
vec![
true, //
false, //
true, //
]
);
res.update(&string_vec_to_status(&[
"a/b", //
"c", //
"d",
]))
.unwrap();
assert_eq!(
res.all_collapsed().iter().collect::<Vec<_>>(),
vec![&&String::from("a")]
);
assert_eq!(
get_visible(&res),
vec![
true, //
false, //
true, //
true
]
);
}
#[test]
fn test_expand() {
let items = string_vec_to_status(&[
"a/b/c", //
"a/d", //
]);
//0 a/
//1 b/
//2 c
//3 d
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.collapse(&String::from("a/b"), 1);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
true, //
false, //
true,
]
);
res.expand(&String::from("a/b"), 1);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
true, //
true, //
true,
]
);
}
#[test]
fn test_expand_bug() {
let items = string_vec_to_status(&[
"a/b/c", //
"a/b2/d", //
]);
//0 a/
//1 b/
//2 c
//3 b2/
//4 d
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.collapse(&String::from("b"), 1);
res.collapse(&String::from("a"), 0);
assert_eq!(
get_visible(&res),
vec![
true, //
false, //
false, //
false, //
false,
]
);
res.expand(&String::from("a"), 0);
assert_eq!(
get_visible(&res),
vec![
true, //
true, //
false, //
true, //
true,
]
);
}
#[test]
fn test_collapse_too_much() {
let items = string_vec_to_status(&[
"a/b", //
"a2/c", //
]);
//0 a/
//1 b
//2 a2/
//3 c
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.collapse(&String::from("a"), 0);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
false, //
true, //
true,
]
);
}
#[test]
fn test_expand_with_collapsed_sub_parts() {
let items = string_vec_to_status(&[
"a/b/c", //
"a/d", //
]);
//0 a/
//1 b/
//2 c
//3 d
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.collapse(&String::from("a/b"), 1);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
true, //
false, //
true,
]
);
res.collapse(&String::from("a"), 0);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
false, //
false, //
false,
]
);
res.expand(&String::from("a"), 0);
let visible = get_visible(&res);
assert_eq!(
visible,
vec![
true, //
true, //
false, //
true,
]
);
}
#[test]
fn test_selection_skips_collapsed() {
let items = string_vec_to_status(&[
"a/b/c", //
"a/d", //
]);
//0 a/
//1 b/
//2 c
//3 d
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.collapse(&String::from("a/b"), 1);
res.selection = Some(1);
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(3));
}
#[test]
fn test_folders_fold_up_if_alone_in_directory() {
let items = string_vec_to_status(&[
"a/b/c/d", //
"a/e/f/g", //
"a/h/i/j", //
]);
//0 a/
//1 b/
//2 c/
//3 d
//4 e/
//5 f/
//6 g
//7 h/
//8 i/
//9 j
//0 a/
//1 b/c/
//3 d
//4 e/f/
//6 g
//7 h/i/
//9 j
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.selection = Some(0);
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(1));
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(3));
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(4));
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(6));
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(7));
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(9));
}
#[test]
fn test_folders_fold_up_if_alone_in_directory_2() {
let items = string_vec_to_status(&["a/b/c/d/e/f/g/h"]);
//0 a/
//1 b/
//2 c/
//3 d/
//4 e/
//5 f/
//6 g/
//7 h
//0 a/b/c/d/e/f/g/
//7 h
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.selection = Some(0);
assert!(res.move_selection(MoveSelection::Down));
assert_eq!(res.selection, Some(7));
}
#[test]
fn test_folders_fold_up_down_with_selection_left_right() {
let items = string_vec_to_status(&[
"a/b/c/d", //
"a/e/f/g", //
"a/h/i/j", //
]);
//0 a/
//1 b/
//2 c/
//3 d
//4 e/
//5 f/
//6 g
//7 h/
//8 i/
//9 j
//0 a/
//1 b/c/
//3 d
//4 e/f/
//6 g
//7 h/i/
//9 j
let mut res = StatusTree::default();
res.update(&items).unwrap();
res.selection = Some(0);
assert!(res.move_selection(MoveSelection::Left));
assert_eq!(res.selection, Some(0));
// These should do nothing
res.move_selection(MoveSelection::Left);
res.move_selection(MoveSelection::Left);
assert_eq!(res.selection, Some(0));
//
assert!(res.move_selection(MoveSelection::Right)); // unfold 0
assert_eq!(res.selection, Some(0));
assert!(res.move_selection(MoveSelection::Right)); // move to 1
assert_eq!(res.selection, Some(1));
assert!(res.move_selection(MoveSelection::Left)); // fold 1
assert!(res.move_selection(MoveSelection::Down)); // move to 4
assert_eq!(res.selection, Some(4));
assert!(res.move_selection(MoveSelection::Left)); // fold 4
assert!(res.move_selection(MoveSelection::Down)); // move to 7
assert_eq!(res.selection, Some(7));
assert!(res.move_selection(MoveSelection::Right)); // move to 9
assert_eq!(res.selection, Some(9));
assert!(res.move_selection(MoveSelection::Left)); // move to 7
assert_eq!(res.selection, Some(7));
assert!(res.move_selection(MoveSelection::Left)); // folds 7
assert_eq!(res.selection, Some(7));
assert!(res.move_selection(MoveSelection::Left)); // jump to 0
assert_eq!(res.selection, Some(0));
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/filetree.rs | src/components/utils/filetree.rs | //TODO: remove in favour of new `filetreelist` crate
use anyhow::{bail, Result};
use asyncgit::StatusItem;
use std::{
collections::BTreeSet,
ffi::OsStr,
ops::{Index, IndexMut},
path::Path,
};
/// holds the information shared among all `FileTreeItem` in a `FileTree`
#[derive(Debug, Clone)]
pub struct TreeItemInfo {
/// indent level
pub indent: u8,
/// currently visible depending on the folder collapse states
pub visible: bool,
/// just the last path element
pub path: String,
/// the full path
pub full_path: String,
}
impl TreeItemInfo {
const fn new(
indent: u8,
path: String,
full_path: String,
) -> Self {
Self {
indent,
visible: true,
path,
full_path,
}
}
}
/// attribute used to indicate the collapse/expand state of a path item
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub struct PathCollapsed(pub bool);
/// `FileTreeItem` can be of two kinds
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum FileTreeItemKind {
Path(PathCollapsed),
File(StatusItem),
}
/// `FileTreeItem` can be of two kinds: see `FileTreeItem` but shares an info
#[derive(Debug, Clone)]
pub struct FileTreeItem {
pub info: TreeItemInfo,
pub kind: FileTreeItemKind,
}
impl FileTreeItem {
fn new_file(item: &StatusItem) -> Result<Self> {
let item_path = Path::new(&item.path);
let indent = u8::try_from(
item_path.ancestors().count().saturating_sub(2),
)?;
let name = item_path
.file_name()
.map(OsStr::to_string_lossy)
.map(|x| x.to_string());
match name {
Some(path) => Ok(Self {
info: TreeItemInfo::new(
indent,
path,
item.path.clone(),
),
kind: FileTreeItemKind::File(item.clone()),
}),
None => bail!("invalid file name {item:?}"),
}
}
fn new_path(
path: &Path,
path_string: String,
collapsed: bool,
) -> Result<Self> {
let indent =
u8::try_from(path.ancestors().count().saturating_sub(2))?;
match path
.components()
.next_back()
.map(std::path::Component::as_os_str)
.map(OsStr::to_string_lossy)
.map(String::from)
{
Some(path) => Ok(Self {
info: TreeItemInfo::new(indent, path, path_string),
kind: FileTreeItemKind::Path(PathCollapsed(
collapsed,
)),
}),
None => bail!("failed to create item from path"),
}
}
}
impl Eq for FileTreeItem {}
impl PartialEq for FileTreeItem {
fn eq(&self, other: &Self) -> bool {
self.info.full_path.eq(&other.info.full_path)
}
}
impl PartialOrd for FileTreeItem {
fn partial_cmp(
&self,
other: &Self,
) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for FileTreeItem {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.info.path.cmp(&other.info.path)
}
}
///
#[derive(Default)]
pub struct FileTreeItems {
items: Vec<FileTreeItem>,
file_count: usize,
}
impl FileTreeItems {
///
pub(crate) fn new(
list: &[StatusItem],
collapsed: &BTreeSet<&String>,
) -> Result<Self> {
let mut items = Vec::with_capacity(list.len());
let mut paths_added = BTreeSet::new();
for e in list {
{
let item_path = Path::new(&e.path);
Self::push_dirs(
item_path,
&mut items,
&mut paths_added,
collapsed,
)?;
}
items.push(FileTreeItem::new_file(e)?);
}
Ok(Self {
items,
file_count: list.len(),
})
}
///
pub(crate) const fn items(&self) -> &Vec<FileTreeItem> {
&self.items
}
///
pub(crate) fn len(&self) -> usize {
self.items.len()
}
///
pub const fn file_count(&self) -> usize {
self.file_count
}
///
pub(crate) fn find_parent_index(&self, index: usize) -> usize {
let item_indent = &self.items[index].info.indent;
let mut parent_index = index;
while item_indent <= &self.items[parent_index].info.indent {
if parent_index == 0 {
return 0;
}
parent_index -= 1;
}
parent_index
}
fn push_dirs<'a>(
item_path: &'a Path,
nodes: &mut Vec<FileTreeItem>,
paths_added: &mut BTreeSet<&'a Path>,
collapsed: &BTreeSet<&String>,
) -> Result<()> {
let mut ancestors =
{ item_path.ancestors().skip(1).collect::<Vec<_>>() };
ancestors.reverse();
for c in &ancestors {
if c.parent().is_some() && !paths_added.contains(c) {
paths_added.insert(c);
//TODO: get rid of expect
let path_string =
String::from(c.to_str().expect("invalid path"));
let is_collapsed = collapsed.contains(&path_string);
nodes.push(FileTreeItem::new_path(
c,
path_string,
is_collapsed,
)?);
}
}
Ok(())
}
pub fn multiple_items_at_path(&self, index: usize) -> bool {
let tree_items = self.items();
let mut idx_temp_inner;
if index + 2 < tree_items.len() {
idx_temp_inner = index + 1;
while idx_temp_inner < tree_items.len().saturating_sub(1)
&& tree_items[index].info.indent
< tree_items[idx_temp_inner].info.indent
{
idx_temp_inner += 1;
}
} else {
return false;
}
tree_items[idx_temp_inner].info.indent
== tree_items[index].info.indent
}
}
impl IndexMut<usize> for FileTreeItems {
fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
&mut self.items[idx]
}
}
impl Index<usize> for FileTreeItems {
type Output = FileTreeItem;
fn index(&self, idx: usize) -> &Self::Output {
&self.items[idx]
}
}
#[cfg(test)]
mod tests {
use super::*;
use asyncgit::StatusItemType;
fn string_vec_to_status(items: &[&str]) -> Vec<StatusItem> {
items
.iter()
.map(|a| StatusItem {
path: String::from(*a),
status: StatusItemType::Modified,
})
.collect::<Vec<_>>()
}
#[test]
fn test_simple() {
let items = string_vec_to_status(&[
"file.txt", //
]);
let res =
FileTreeItems::new(&items, &BTreeSet::new()).unwrap();
assert_eq!(
res.items,
vec![FileTreeItem {
info: TreeItemInfo {
path: items[0].path.clone(),
full_path: items[0].path.clone(),
indent: 0,
visible: true,
},
kind: FileTreeItemKind::File(items[0].clone())
}]
);
let items = string_vec_to_status(&[
"file.txt", //
"file2.txt", //
]);
let res =
FileTreeItems::new(&items, &BTreeSet::new()).unwrap();
assert_eq!(res.items.len(), 2);
assert_eq!(res.items[1].info.path, items[1].path);
}
#[test]
fn test_folder() {
let items = string_vec_to_status(&[
"a/file.txt", //
]);
let res = FileTreeItems::new(&items, &BTreeSet::new())
.unwrap()
.items
.iter()
.map(|i| i.info.full_path.clone())
.collect::<Vec<_>>();
assert_eq!(
res,
vec![String::from("a"), items[0].path.clone(),]
);
}
#[test]
fn test_indent() {
let items = string_vec_to_status(&[
"a/b/file.txt", //
]);
let list =
FileTreeItems::new(&items, &BTreeSet::new()).unwrap();
let mut res = list
.items
.iter()
.map(|i| (i.info.indent, i.info.path.as_str()));
assert_eq!(res.next(), Some((0, "a")));
assert_eq!(res.next(), Some((1, "b")));
assert_eq!(res.next(), Some((2, "file.txt")));
}
#[test]
fn test_indent_folder_file_name() {
let items = string_vec_to_status(&[
"a/b", //
"a.txt", //
]);
let list =
FileTreeItems::new(&items, &BTreeSet::new()).unwrap();
let mut res = list
.items
.iter()
.map(|i| (i.info.indent, i.info.path.as_str()));
assert_eq!(res.next(), Some((0, "a")));
assert_eq!(res.next(), Some((1, "b")));
assert_eq!(res.next(), Some((0, "a.txt")));
}
#[test]
fn test_folder_dup() {
let items = string_vec_to_status(&[
"a/file.txt", //
"a/file2.txt", //
]);
let res = FileTreeItems::new(&items, &BTreeSet::new())
.unwrap()
.items
.iter()
.map(|i| i.info.full_path.clone())
.collect::<Vec<_>>();
assert_eq!(
res,
vec![
String::from("a"),
items[0].path.clone(),
items[1].path.clone()
]
);
}
#[test]
fn test_multiple_items_at_path() {
//0 a/
//1 b/
//2 c/
//3 d
//4 e/
//5 f
let res = FileTreeItems::new(
&string_vec_to_status(&[
"a/b/c/d", //
"a/b/e/f", //
]),
&BTreeSet::new(),
)
.unwrap();
assert!(!res.multiple_items_at_path(0));
assert!(!res.multiple_items_at_path(1));
assert!(res.multiple_items_at_path(2));
}
#[test]
fn test_find_parent() {
//0 a/
//1 b/
//2 c
//3 d
let res = FileTreeItems::new(
&string_vec_to_status(&[
"a/b/c", //
"a/b/d", //
]),
&BTreeSet::new(),
)
.unwrap();
assert_eq!(res.find_parent_index(3), 1);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/logitems.rs | src/components/utils/logitems.rs | use asyncgit::sync::{CommitId, CommitInfo};
use chrono::{DateTime, Duration, Local, Utc};
use indexmap::IndexSet;
use std::{rc::Rc, slice::Iter};
#[cfg(feature = "ghemoji")]
use super::emoji::emojifi_string;
static SLICE_OFFSET_RELOAD_THRESHOLD: usize = 100;
type BoxStr = Box<str>;
pub struct LogEntry {
//TODO: cache string representation
pub time: DateTime<Local>,
//TODO: use tinyvec here
pub author: BoxStr,
pub msg: BoxStr,
//TODO: use tinyvec here
pub hash_short: BoxStr,
pub id: CommitId,
pub highlighted: bool,
}
impl From<CommitInfo> for LogEntry {
fn from(c: CommitInfo) -> Self {
let hash_short = c.id.get_short_string().into();
let time = {
let date = DateTime::from_timestamp(c.time, 0)
.map(|d| d.naive_utc());
if date.is_none() {
log::error!("error reading commit date: {hash_short} - timestamp: {}",c.time);
}
DateTime::<Local>::from(
DateTime::<Utc>::from_naive_utc_and_offset(
date.unwrap_or_default(),
Utc,
),
)
};
let author = c.author;
let msg = c.message;
// Replace markdown emojis with Unicode equivalent
#[cfg(feature = "ghemoji")]
let msg = emojifi_string(msg);
Self {
author: author.into(),
msg: msg.into(),
time,
hash_short,
id: c.id,
highlighted: false,
}
}
}
impl LogEntry {
pub fn time_to_string(&self, now: DateTime<Local>) -> String {
let delta = now - self.time;
if delta < Duration::try_minutes(30).unwrap_or_default() {
let delta_str = if delta
< Duration::try_minutes(1).unwrap_or_default()
{
"<1m ago".to_string()
} else {
format!("{:0>2}m ago", delta.num_minutes())
};
format!("{delta_str: <10}")
} else if self.time.date_naive() == now.date_naive() {
self.time.format("%T ").to_string()
} else {
self.time.format("%Y-%m-%d").to_string()
}
}
}
///
#[derive(Default)]
pub struct ItemBatch {
index_offset: Option<usize>,
items: Vec<LogEntry>,
highlighting: bool,
}
impl ItemBatch {
fn last_idx(&self) -> usize {
self.index_offset() + self.items.len()
}
///
pub fn index_offset(&self) -> usize {
self.index_offset.unwrap_or_default()
}
///
pub const fn index_offset_raw(&self) -> Option<usize> {
self.index_offset
}
///
pub const fn highlighting(&self) -> bool {
self.highlighting
}
/// shortcut to get an `Iter` of our internal items
pub fn iter(&self) -> Iter<'_, LogEntry> {
self.items.iter()
}
/// clear current list of items
pub fn clear(&mut self) {
self.items.clear();
self.index_offset = None;
}
/// insert new batch of items
pub fn set_items(
&mut self,
start_index: usize,
commits: Vec<CommitInfo>,
highlighted: Option<&Rc<IndexSet<CommitId>>>,
) {
self.clear();
if !commits.is_empty() {
self.items.extend(commits.into_iter().map(|c| {
let id = c.id;
let mut entry = LogEntry::from(c);
if highlighted.as_ref().is_some_and(|highlighted| {
highlighted.contains(&id)
}) {
entry.highlighted = true;
}
entry
}));
self.index_offset = Some(start_index);
self.highlighting = highlighted.is_some();
}
}
/// returns `true` if we should fetch updated list of items
pub fn needs_data(&self, idx: usize, idx_max: usize) -> bool {
let want_min =
idx.saturating_sub(SLICE_OFFSET_RELOAD_THRESHOLD);
let want_max = idx
.saturating_add(SLICE_OFFSET_RELOAD_THRESHOLD)
.min(idx_max);
let needs_data_top = want_min < self.index_offset();
let needs_data_bottom = want_max >= self.last_idx();
needs_data_bottom || needs_data_top
}
}
impl<'a> IntoIterator for &'a ItemBatch {
type IntoIter = std::slice::Iter<
'a,
crate::components::utils::logitems::LogEntry,
>;
type Item = &'a crate::components::utils::logitems::LogEntry;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[cfg(test)]
#[cfg(feature = "ghemoji")]
mod tests {
use super::*;
fn test_conversion(s: &str) -> String {
emojifi_string(s.into())
}
#[test]
fn test_emojifi_string_conversion_cases() {
assert_eq!(
&test_conversion("It's :hammer: time!"),
"It's 🔨 time!"
);
assert_eq!(
&test_conversion(":red_circle::orange_circle::yellow_circle::green_circle::large_blue_circle::purple_circle:"),
"🔴🟠🟡🟢🔵🟣"
);
assert_eq!(
&test_conversion("It's raining :cat:s and :dog:s"),
"It's raining 🐱s and 🐶s"
);
assert_eq!(&test_conversion(":crab: rules!"), "🦀 rules!");
}
#[test]
fn test_emojifi_string_no_conversion_cases() {
assert_eq!(&test_conversion("123"), "123");
assert_eq!(
&test_conversion("This :should_not_convert:"),
"This :should_not_convert:"
);
assert_eq!(&test_conversion(":gopher:"), ":gopher:");
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/emoji.rs | src/components/utils/emoji.rs | use once_cell::sync::Lazy;
use std::borrow::Cow;
static EMOJI_REPLACER: Lazy<gh_emoji::Replacer> =
Lazy::new(gh_emoji::Replacer::new);
// Replace markdown emojis with Unicode equivalent
// :hammer: --> 🔨
#[inline]
pub fn emojifi_string(s: String) -> String {
if let Cow::Owned(altered_s) = EMOJI_REPLACER.replace_all(&s) {
altered_s
} else {
s
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/mod.rs | src/components/utils/mod.rs | use chrono::{DateTime, Local, Utc};
use unicode_width::UnicodeWidthStr;
#[cfg(feature = "ghemoji")]
pub mod emoji;
pub mod filetree;
pub mod logitems;
pub mod scroll_horizontal;
pub mod scroll_vertical;
pub mod statustree;
/// macro to simplify running code that might return Err.
/// It will show a popup in that case
#[macro_export]
macro_rules! try_or_popup {
($self:ident, $msg:expr, $e:expr) => {
if let Err(err) = $e {
::log::error!("{} {}", $msg, err);
$self.queue.push(
$crate::queue::InternalEvent::ShowErrorMsg(format!(
"{}\n{}",
$msg, err
)),
);
}
};
}
/// helper func to convert unix time since epoch to formatted time string in local timezone
pub fn time_to_string(secs: i64, short: bool) -> String {
let time = DateTime::<Local>::from(
DateTime::<Utc>::from_naive_utc_and_offset(
DateTime::from_timestamp(secs, 0)
.unwrap_or_default()
.naive_utc(),
Utc,
),
);
time.format(if short {
"%Y-%m-%d"
} else {
"%Y-%m-%d %H:%M:%S"
})
.to_string()
}
#[inline]
pub fn string_width_align(s: &str, width: usize) -> String {
static POSTFIX: &str = "..";
let len = UnicodeWidthStr::width(s);
let width_wo_postfix = width.saturating_sub(POSTFIX.len());
if (len >= width_wo_postfix && len <= width)
|| (len <= width_wo_postfix)
{
format!("{s:width$}")
} else {
let mut s = s.to_string();
s.truncate(find_truncate_point(&s, width_wo_postfix));
format!("{s}{POSTFIX}")
}
}
#[inline]
fn find_truncate_point(s: &str, chars: usize) -> usize {
s.chars().take(chars).map(char::len_utf8).sum()
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/scroll_vertical.rs | src/components/utils/scroll_vertical.rs | use crate::{
components::ScrollType,
ui::{draw_scrollbar, style::SharedTheme, Orientation},
};
use ratatui::{layout::Rect, Frame};
use std::cell::Cell;
pub struct VerticalScroll {
top: Cell<usize>,
max_top: Cell<usize>,
visual_height: Cell<usize>,
}
impl VerticalScroll {
pub const fn new() -> Self {
Self {
top: Cell::new(0),
max_top: Cell::new(0),
visual_height: Cell::new(0),
}
}
pub fn get_top(&self) -> usize {
self.top.get()
}
pub fn reset(&self) {
self.top.set(0);
}
pub fn move_top(&self, move_type: ScrollType) -> bool {
let old = self.top.get();
let max = self.max_top.get();
let new_scroll_top = match move_type {
ScrollType::Down => old.saturating_add(1),
ScrollType::Up => old.saturating_sub(1),
ScrollType::PageDown => old
.saturating_sub(1)
.saturating_add(self.visual_height.get()),
ScrollType::PageUp => old
.saturating_add(1)
.saturating_sub(self.visual_height.get()),
ScrollType::Home => 0,
ScrollType::End => max,
};
let new_scroll_top = new_scroll_top.clamp(0, max);
if new_scroll_top == old {
return false;
}
self.top.set(new_scroll_top);
true
}
pub fn move_area_to_visible(
&self,
height: usize,
start: usize,
end: usize,
) {
let top = self.top.get();
let bottom = top + height;
let max_top = self.max_top.get();
// the top of some content is hidden
if start < top {
self.top.set(start);
return;
}
// the bottom of some content is hidden and there is visible space available
if end > bottom && start > top {
let avail_space = start.saturating_sub(top);
let diff = std::cmp::min(
avail_space,
end.saturating_sub(bottom),
);
let top = top.saturating_add(diff);
self.top.set(std::cmp::min(max_top, top));
}
}
pub fn update(
&self,
selection: usize,
selection_max: usize,
visual_height: usize,
) -> usize {
self.visual_height.set(visual_height);
let new_top = calc_scroll_top(
self.get_top(),
visual_height,
selection,
selection_max,
);
self.top.set(new_top);
if visual_height == 0 {
self.max_top.set(0);
} else {
let new_max = selection_max.saturating_sub(visual_height);
self.max_top.set(new_max);
}
new_top
}
pub fn update_no_selection(
&self,
line_count: usize,
visual_height: usize,
) -> usize {
self.update(self.get_top(), line_count, visual_height)
}
pub fn draw(&self, f: &mut Frame, r: Rect, theme: &SharedTheme) {
draw_scrollbar(
f,
r,
theme,
self.max_top.get(),
self.top.get(),
Orientation::Vertical,
);
}
}
const fn calc_scroll_top(
current_top: usize,
height_in_lines: usize,
selection: usize,
selection_max: usize,
) -> usize {
if height_in_lines == 0 {
return 0;
}
if selection_max <= height_in_lines {
return 0;
}
if current_top + height_in_lines <= selection {
selection.saturating_sub(height_in_lines) + 1
} else if current_top > selection {
selection
} else {
current_top
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_scroll_no_scroll_to_top() {
assert_eq!(calc_scroll_top(1, 10, 4, 4), 0);
}
#[test]
fn test_scroll_zero_height() {
assert_eq!(calc_scroll_top(4, 0, 4, 3), 0);
}
#[test]
fn test_scroll_bottom_into_view() {
let visual_height = 10;
let line_count = 20;
let scroll = VerticalScroll::new();
scroll.max_top.set(line_count - visual_height);
// intersecting with the bottom of the visible area
scroll.move_area_to_visible(visual_height, 9, 11);
assert_eq!(scroll.get_top(), 1);
// completely below the visible area
scroll.move_area_to_visible(visual_height, 15, 17);
assert_eq!(scroll.get_top(), 7);
// scrolling to the bottom overflow
scroll.move_area_to_visible(visual_height, 30, 40);
assert_eq!(scroll.get_top(), 10);
}
#[test]
fn test_scroll_top_into_view() {
let visual_height = 10;
let line_count = 20;
let scroll = VerticalScroll::new();
scroll.max_top.set(line_count - visual_height);
scroll.top.set(4);
// intersecting with the top of the visible area
scroll.move_area_to_visible(visual_height, 2, 8);
assert_eq!(scroll.get_top(), 2);
// completely above the visible area
scroll.move_area_to_visible(visual_height, 0, 2);
assert_eq!(scroll.get_top(), 0);
}
#[test]
fn test_scroll_with_pageup_pagedown() {
let scroll = VerticalScroll::new();
scroll.max_top.set(10);
scroll.visual_height.set(8);
assert!(scroll.move_top(ScrollType::End));
assert_eq!(scroll.get_top(), 10);
assert!(!scroll.move_top(ScrollType::PageDown));
assert_eq!(scroll.get_top(), 10);
assert!(scroll.move_top(ScrollType::PageUp));
assert_eq!(scroll.get_top(), 3);
assert!(scroll.move_top(ScrollType::PageUp));
assert_eq!(scroll.get_top(), 0);
assert!(!scroll.move_top(ScrollType::PageUp));
assert_eq!(scroll.get_top(), 0);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/components/utils/scroll_horizontal.rs | src/components/utils/scroll_horizontal.rs | use crate::{
components::HorizontalScrollType,
ui::{draw_scrollbar, style::SharedTheme, Orientation},
};
use ratatui::{layout::Rect, Frame};
use std::cell::Cell;
pub struct HorizontalScroll {
right: Cell<usize>,
max_right: Cell<usize>,
}
impl HorizontalScroll {
pub const fn new() -> Self {
Self {
right: Cell::new(0),
max_right: Cell::new(0),
}
}
pub fn get_right(&self) -> usize {
self.right.get()
}
pub fn reset(&self) {
self.right.set(0);
}
pub fn move_right(
&self,
move_type: HorizontalScrollType,
) -> bool {
let old = self.right.get();
let max = self.max_right.get();
let new_scroll_right = match move_type {
HorizontalScrollType::Left => old.saturating_sub(1),
HorizontalScrollType::Right => old.saturating_add(1),
};
let new_scroll_right = new_scroll_right.clamp(0, max);
if new_scroll_right == old {
return false;
}
self.right.set(new_scroll_right);
true
}
pub fn update(
&self,
selection: usize,
max_selection: usize,
visual_width: usize,
) -> usize {
let new_right = calc_scroll_right(
self.get_right(),
visual_width,
selection,
max_selection,
);
self.right.set(new_right);
if visual_width == 0 {
self.max_right.set(0);
} else {
let new_max_right =
max_selection.saturating_sub(visual_width);
self.max_right.set(new_max_right);
}
new_right
}
pub fn update_no_selection(
&self,
column_count: usize,
visual_width: usize,
) -> usize {
self.update(self.get_right(), column_count, visual_width)
}
pub fn draw(&self, f: &mut Frame, r: Rect, theme: &SharedTheme) {
draw_scrollbar(
f,
r,
theme,
self.max_right.get(),
self.right.get(),
Orientation::Horizontal,
);
}
}
const fn calc_scroll_right(
current_right: usize,
width_in_lines: usize,
selection: usize,
selection_max: usize,
) -> usize {
if width_in_lines == 0 {
return 0;
}
if selection_max <= width_in_lines {
return 0;
}
if current_right + width_in_lines <= selection {
selection.saturating_sub(width_in_lines) + 1
} else if current_right > selection {
selection
} else {
current_right
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_scroll_no_scroll_to_right() {
assert_eq!(calc_scroll_right(1, 10, 4, 4), 0);
}
#[test]
fn test_scroll_zero_width() {
assert_eq!(calc_scroll_right(4, 0, 4, 3), 0);
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/status.rs | src/tabs/status.rs | use crate::{
accessors,
app::Environment,
components::{
command_pump, event_pump, visibility_blocking,
ChangesComponent, CommandBlocking, CommandInfo, Component,
DiffComponent, DrawableComponent, EventState,
FileTreeItemKind,
},
keys::{key_match, SharedKeyConfig},
options::SharedOptions,
queue::{Action, InternalEvent, NeedsUpdate, Queue, ResetItem},
strings, try_or_popup,
ui::style::Theme,
};
use anyhow::Result;
use asyncgit::{
cached,
sync::{
self, status::StatusType, RepoPath, RepoPathRef, RepoState,
},
sync::{BranchCompare, CommitId},
AsyncDiff, AsyncGitNotification, AsyncStatus, DiffParams,
DiffType, PushType, StatusItem, StatusParams,
};
use crossterm::event::Event;
use itertools::Itertools;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout},
style::{Color, Style},
widgets::{Block, BorderType, Borders, Paragraph},
};
/// what part of the screen is focused
#[derive(PartialEq)]
enum Focus {
WorkDir,
Diff,
Stage,
}
/// focus can toggle between workdir and stage
impl Focus {
const fn toggled_focus(&self) -> Self {
match self {
Self::WorkDir => Self::Stage,
Self::Stage => Self::WorkDir,
Self::Diff => Self::Diff,
}
}
}
/// which target are we showing a diff against
#[derive(PartialEq, Copy, Clone)]
enum DiffTarget {
Stage,
WorkingDir,
}
struct RemoteStatus {
has_remote_for_fetch: bool,
has_remote_for_push: bool,
}
pub struct Status {
repo: RepoPathRef,
visible: bool,
focus: Focus,
diff_target: DiffTarget,
index: ChangesComponent,
index_wd: ChangesComponent,
diff: DiffComponent,
remotes: RemoteStatus,
git_diff: AsyncDiff,
git_state: RepoState,
git_status_workdir: AsyncStatus,
git_status_stage: AsyncStatus,
git_branch_state: Option<BranchCompare>,
git_branch_name: cached::BranchName,
queue: Queue,
git_action_executed: bool,
options: SharedOptions,
key_config: SharedKeyConfig,
}
impl DrawableComponent for Status {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::layout::Rect,
) -> Result<()> {
let repo_unclean = self.repo_state_unclean();
let rects = if repo_unclean {
Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Min(1), Constraint::Length(3)]
.as_ref(),
)
.split(rect)
} else {
std::rc::Rc::new([rect])
};
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
if self.focus == Focus::Diff {
[
Constraint::Percentage(0),
Constraint::Percentage(100),
]
} else {
[
Constraint::Percentage(50),
Constraint::Percentage(50),
]
}
.as_ref(),
)
.split(rects[0]);
let left_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
if self.diff_target == DiffTarget::WorkingDir {
[
Constraint::Percentage(60),
Constraint::Percentage(40),
]
} else {
[
Constraint::Percentage(40),
Constraint::Percentage(60),
]
}
.as_ref(),
)
.split(chunks[0]);
self.index_wd.draw(f, left_chunks[0])?;
self.index.draw(f, left_chunks[1])?;
self.diff.draw(f, chunks[1])?;
self.draw_branch_state(f, &left_chunks);
if repo_unclean {
self.draw_repo_state(f, rects[1]);
}
Ok(())
}
}
impl Status {
accessors!(self, [index, index_wd, diff]);
///
pub fn new(env: &Environment) -> Self {
let repo_clone = env.repo.borrow().clone();
Self {
queue: env.queue.clone(),
visible: true,
remotes: RemoteStatus {
has_remote_for_fetch: false,
has_remote_for_push: false,
},
git_state: RepoState::Clean,
focus: Focus::WorkDir,
diff_target: DiffTarget::WorkingDir,
index_wd: ChangesComponent::new(
env,
&strings::title_status(&env.key_config),
true,
true,
),
index: ChangesComponent::new(
env,
&strings::title_index(&env.key_config),
false,
false,
),
diff: DiffComponent::new(env, false),
git_diff: AsyncDiff::new(
repo_clone.clone(),
&env.sender_git,
),
git_status_workdir: AsyncStatus::new(
repo_clone.clone(),
env.sender_git.clone(),
),
git_status_stage: AsyncStatus::new(
repo_clone,
env.sender_git.clone(),
),
git_action_executed: false,
git_branch_state: None,
git_branch_name: cached::BranchName::new(
env.repo.clone(),
),
key_config: env.key_config.clone(),
options: env.options.clone(),
repo: env.repo.clone(),
}
}
fn draw_branch_state(
&self,
f: &mut ratatui::Frame,
chunks: &[ratatui::layout::Rect],
) {
if let Some(branch_name) = self.git_branch_name.last() {
let ahead_behind = self
.git_branch_state
.as_ref()
.map_or_else(String::new, |state| {
format!(
"\u{2191}{} \u{2193}{} ",
state.ahead, state.behind,
)
});
let w = Paragraph::new(format!(
"{ahead_behind}{{{branch_name}}}"
))
.alignment(Alignment::Right);
let mut rect = if self.index_wd.focused() {
let mut rect = chunks[0];
rect.y += rect.height.saturating_sub(1);
rect
} else {
chunks[1]
};
rect.x += 1;
rect.width = rect.width.saturating_sub(2);
rect.height = rect
.height
.saturating_sub(rect.height.saturating_sub(1));
f.render_widget(w, rect);
}
}
fn repo_state_text(repo: &RepoPath, state: &RepoState) -> String {
match state {
RepoState::Merge => {
let ids =
sync::mergehead_ids(repo).unwrap_or_default();
format!(
"Commits: {}",
ids.iter()
.map(sync::CommitId::get_short_string)
.join(",")
)
}
RepoState::Rebase => sync::rebase_progress(repo)
.map_or_else(
|_| String::new(),
|p| {
format!(
"Step: {}/{} Current Commit: {}",
p.current + 1,
p.steps,
p.current_commit
.as_ref()
.map(CommitId::get_short_string)
.unwrap_or_default(),
)
},
),
RepoState::Revert => {
format!(
"Revert {}",
sync::revert_head(repo)
.ok()
.as_ref()
.map(CommitId::get_short_string)
.unwrap_or_default(),
)
}
_ => format!("{state:?}"),
}
}
fn draw_repo_state(
&self,
f: &mut ratatui::Frame,
r: ratatui::layout::Rect,
) {
if self.git_state != RepoState::Clean {
let txt = Self::repo_state_text(
&self.repo.borrow(),
&self.git_state,
);
let w = Paragraph::new(txt)
.block(
Block::default()
.border_type(BorderType::Plain)
.borders(Borders::all())
.border_style(Theme::attention_block())
.title(format!(
"Pending {:?}",
self.git_state
)),
)
.style(Style::default().fg(Color::Red))
.alignment(Alignment::Left);
f.render_widget(w, r);
}
}
fn repo_state_unclean(&self) -> bool {
self.git_state != RepoState::Clean
}
fn can_focus_diff(&self) -> bool {
match self.focus {
Focus::WorkDir => self.index_wd.is_file_selected(),
Focus::Stage => self.index.is_file_selected(),
Focus::Diff => false,
}
}
fn is_focus_on_diff(&self) -> bool {
self.focus == Focus::Diff
}
fn switch_focus(&mut self, f: Focus) -> Result<bool> {
if self.focus != f {
self.focus = f;
match self.focus {
Focus::WorkDir => {
self.set_diff_target(DiffTarget::WorkingDir);
self.diff.focus(false);
}
Focus::Stage => {
self.set_diff_target(DiffTarget::Stage);
self.diff.focus(false);
}
Focus::Diff => {
self.index.focus(false);
self.index_wd.focus(false);
self.diff.focus(true);
}
}
self.update_diff()?;
return Ok(true);
}
Ok(false)
}
fn set_diff_target(&mut self, target: DiffTarget) {
self.diff_target = target;
let is_stage = self.diff_target == DiffTarget::Stage;
self.index_wd.focus_select(!is_stage);
self.index.focus_select(is_stage);
}
pub fn selected_path(&self) -> Option<(String, bool)> {
let (idx, is_stage) = match self.diff_target {
DiffTarget::Stage => (&self.index, true),
DiffTarget::WorkingDir => (&self.index_wd, false),
};
if let Some(item) = idx.selection() {
if let FileTreeItemKind::File(i) = item.kind {
return Some((i.path, is_stage));
}
}
None
}
///
pub fn update(&mut self) -> Result<()> {
self.git_branch_name.lookup().map(Some).unwrap_or(None);
if self.is_visible() {
let config =
self.options.borrow().status_show_untracked();
self.git_diff.refresh()?;
self.git_status_workdir.fetch(&StatusParams::new(
StatusType::WorkingDir,
config,
))?;
self.git_status_stage.fetch(&StatusParams::new(
StatusType::Stage,
config,
))?;
self.git_state = sync::repo_state(&self.repo.borrow())
.unwrap_or(RepoState::Clean);
self.branch_compare();
}
Ok(())
}
///
pub fn anything_pending(&self) -> bool {
self.git_diff.is_pending()
|| self.git_status_stage.is_pending()
|| self.git_status_workdir.is_pending()
}
fn check_remotes(&mut self) {
self.remotes.has_remote_for_fetch =
sync::get_default_remote_for_fetch(
&self.repo.borrow().clone(),
)
.is_ok();
self.remotes.has_remote_for_push =
sync::get_default_remote_for_push(
&self.repo.borrow().clone(),
)
.is_ok();
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if !self.is_visible() {
return Ok(());
}
match ev {
AsyncGitNotification::Diff => self.update_diff()?,
AsyncGitNotification::Status => self.update_status()?,
AsyncGitNotification::Branches => self.check_remotes(),
AsyncGitNotification::Push
| AsyncGitNotification::Pull
| AsyncGitNotification::CommitFiles => {
self.branch_compare();
}
_ => (),
}
Ok(())
}
pub fn get_files_changes(&self) -> Result<Vec<StatusItem>> {
Ok(self.git_status_stage.last()?.items)
}
fn update_status(&mut self) -> Result<()> {
let stage_status = self.git_status_stage.last()?;
self.index.set_items(&stage_status.items)?;
let workdir_status = self.git_status_workdir.last()?;
self.index_wd.set_items(&workdir_status.items)?;
self.update_diff()?;
if self.git_action_executed {
self.git_action_executed = false;
if self.focus == Focus::WorkDir
&& workdir_status.items.is_empty()
&& !stage_status.items.is_empty()
{
self.switch_focus(Focus::Stage)?;
} else if self.focus == Focus::Stage
&& stage_status.items.is_empty()
{
self.switch_focus(Focus::WorkDir)?;
}
}
Ok(())
}
///
pub fn update_diff(&mut self) -> Result<()> {
if let Some((path, is_stage)) = self.selected_path() {
let diff_type = if is_stage {
DiffType::Stage
} else {
DiffType::WorkDir
};
let diff_params = DiffParams {
path: path.clone(),
diff_type,
options: self.options.borrow().diff_options(),
};
if self.diff.current() == (path.clone(), is_stage) {
// we are already showing a diff of the right file
// maybe the diff changed (outside file change)
if let Some((params, last)) = self.git_diff.last()? {
if params == diff_params {
// all params match, so we might need to update
self.diff.update(path, is_stage, last);
} else {
// params changed, we need to request the right diff
self.request_diff(
diff_params,
path,
is_stage,
)?;
}
}
} else {
// we dont show the right diff right now, so we need to request
self.request_diff(diff_params, path, is_stage)?;
}
} else {
self.diff.clear(false);
}
Ok(())
}
fn request_diff(
&mut self,
diff_params: DiffParams,
path: String,
is_stage: bool,
) -> Result<(), anyhow::Error> {
if let Some(diff) = self.git_diff.request(diff_params)? {
self.diff.update(path, is_stage, diff);
} else {
self.diff.clear(true);
}
Ok(())
}
/// called after confirmation
pub fn reset(&self, item: &ResetItem) -> bool {
if let Err(e) = sync::reset_workdir(
&self.repo.borrow(),
item.path.as_str(),
) {
self.queue.push(InternalEvent::ShowErrorMsg(format!(
"reset failed:\n{e}"
)));
false
} else {
true
}
}
pub fn last_file_moved(&mut self) -> Result<()> {
if !self.is_focus_on_diff() && self.is_visible() {
self.switch_focus(self.focus.toggled_focus())?;
}
Ok(())
}
fn push(&self, force: bool) {
if self.can_push() {
if let Some(branch) = self.git_branch_name.last() {
if force {
self.queue.push(InternalEvent::ConfirmAction(
Action::ForcePush(branch, force),
));
} else {
self.queue.push(InternalEvent::Push(
branch,
PushType::Branch,
force,
false,
));
}
}
}
}
fn fetch(&self) {
if self.can_fetch() {
self.queue.push(InternalEvent::FetchRemotes);
}
}
fn pull(&self) {
if let Some(branch) = self.git_branch_name.last() {
self.queue.push(InternalEvent::Pull(branch));
}
}
fn undo_last_commit(&self) {
self.queue
.push(InternalEvent::ConfirmAction(Action::UndoCommit));
}
fn branch_compare(&mut self) {
self.git_branch_state =
self.git_branch_name.last().and_then(|branch| {
sync::branch_compare_upstream(
&self.repo.borrow(),
branch.as_str(),
)
.ok()
});
}
fn can_push(&self) -> bool {
let is_ahead = self
.git_branch_state
.as_ref()
.is_none_or(|state| state.ahead > 0);
is_ahead && self.remotes.has_remote_for_push
}
const fn can_fetch(&self) -> bool {
self.remotes.has_remote_for_fetch
&& self.git_branch_state.is_some()
}
fn can_abort_merge(&self) -> bool {
self.git_state == RepoState::Merge
}
fn pending_rebase(&self) -> bool {
self.git_state == RepoState::Rebase
}
fn pending_revert(&self) -> bool {
self.git_state == RepoState::Revert
}
pub fn revert_pending_state(&self) {
try_or_popup!(
self,
"revert pending state",
sync::abort_pending_state(&self.repo.borrow())
);
}
pub fn abort_rebase(&self) {
try_or_popup!(
self,
"abort rebase",
sync::abort_pending_rebase(&self.repo.borrow())
);
}
fn continue_rebase(&self) {
try_or_popup!(
self,
"continue rebase",
sync::continue_pending_rebase(&self.repo.borrow())
);
}
fn commands_nav(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) {
let focus_on_diff = self.is_focus_on_diff();
out.push(
CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
(self.visible && focus_on_diff) || force_all,
)
.order(strings::order::NAV),
);
out.push(
CommandInfo::new(
strings::commands::diff_focus_right(&self.key_config),
self.can_focus_diff(),
(self.visible && !focus_on_diff) || force_all,
)
.order(strings::order::NAV),
);
out.push(
CommandInfo::new(
strings::commands::select_staging(&self.key_config),
!focus_on_diff,
(self.visible
&& !focus_on_diff
&& self.focus == Focus::WorkDir)
|| force_all,
)
.order(strings::order::NAV),
);
out.push(
CommandInfo::new(
strings::commands::select_unstaged(&self.key_config),
!focus_on_diff,
(self.visible
&& !focus_on_diff
&& self.focus == Focus::Stage)
|| force_all,
)
.order(strings::order::NAV),
);
}
fn can_commit(&self) -> bool {
self.index.focused()
&& !self.index.is_empty()
&& !self.pending_rebase()
}
}
impl Component for Status {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
let focus_on_diff = self.is_focus_on_diff();
if self.visible || force_all {
command_pump(
out,
force_all,
self.components().as_slice(),
);
out.push(
CommandInfo::new(
strings::commands::commit_open(&self.key_config),
true,
self.can_commit() || force_all,
)
.order(-1),
);
out.push(CommandInfo::new(
strings::commands::open_branch_select_popup(
&self.key_config,
),
true,
!focus_on_diff,
));
out.push(CommandInfo::new(
strings::commands::status_push(&self.key_config),
self.can_push(),
!focus_on_diff,
));
out.push(CommandInfo::new(
strings::commands::status_force_push(
&self.key_config,
),
true,
self.can_push() && !focus_on_diff,
));
out.push(CommandInfo::new(
strings::commands::status_fetch(&self.key_config),
self.can_fetch(),
!focus_on_diff,
));
out.push(CommandInfo::new(
strings::commands::status_pull(&self.key_config),
self.can_fetch(),
!focus_on_diff,
));
out.push(CommandInfo::new(
strings::commands::undo_commit(&self.key_config),
true,
(!self.pending_rebase() && !focus_on_diff)
|| force_all,
));
out.push(CommandInfo::new(
strings::commands::abort_merge(&self.key_config),
true,
self.can_abort_merge() || force_all,
));
out.push(CommandInfo::new(
strings::commands::continue_rebase(&self.key_config),
true,
self.pending_rebase() || force_all,
));
out.push(CommandInfo::new(
strings::commands::abort_rebase(&self.key_config),
true,
self.pending_rebase() || force_all,
));
out.push(CommandInfo::new(
strings::commands::abort_revert(&self.key_config),
true,
self.pending_revert() || force_all,
));
out.push(CommandInfo::new(
strings::commands::view_submodules(&self.key_config),
true,
true,
));
}
self.commands_nav(out, force_all);
visibility_blocking(self)
}
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
fn event(
&mut self,
ev: &crossterm::event::Event,
) -> Result<EventState> {
if self.visible {
if event_pump(ev, self.components_mut().as_mut_slice())?
.is_consumed()
{
self.git_action_executed = true;
return Ok(EventState::Consumed);
}
if let Event::Key(k) = ev {
return if key_match(
k,
self.key_config.keys.open_commit,
) && self.can_commit()
{
self.queue.push(InternalEvent::OpenCommit);
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.toggle_workarea,
) && !self.is_focus_on_diff()
{
self.switch_focus(self.focus.toggled_focus())
.map(Into::into)
} else if key_match(
k,
self.key_config.keys.move_right,
) && self.can_focus_diff()
{
self.switch_focus(Focus::Diff).map(Into::into)
} else if key_match(
k,
self.key_config.keys.exit_popup,
) {
self.switch_focus(match self.diff_target {
DiffTarget::Stage => Focus::Stage,
DiffTarget::WorkingDir => Focus::WorkDir,
})
.map(Into::into)
} else if key_match(k, self.key_config.keys.move_down)
&& self.focus == Focus::WorkDir
&& !self.index.is_empty()
{
self.switch_focus(Focus::Stage).map(Into::into)
} else if key_match(k, self.key_config.keys.move_up)
&& self.focus == Focus::Stage
&& !self.index_wd.is_empty()
{
self.switch_focus(Focus::WorkDir).map(Into::into)
} else if key_match(
k,
self.key_config.keys.select_branch,
) && !self.is_focus_on_diff()
{
self.queue.push(InternalEvent::SelectBranch);
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.force_push,
) && !self.is_focus_on_diff()
&& self.can_push()
{
self.push(true);
Ok(EventState::Consumed)
} else if key_match(k, self.key_config.keys.push)
&& !self.is_focus_on_diff()
{
self.push(false);
Ok(EventState::Consumed)
} else if key_match(k, self.key_config.keys.fetch)
&& !self.is_focus_on_diff()
&& self.can_fetch()
{
self.fetch();
Ok(EventState::Consumed)
} else if key_match(k, self.key_config.keys.pull)
&& !self.is_focus_on_diff()
&& self.can_fetch()
{
self.pull();
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.undo_commit,
) && !self.is_focus_on_diff()
{
self.undo_last_commit();
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL,
));
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.abort_merge,
) {
if self.can_abort_merge() {
self.queue.push(
InternalEvent::ConfirmAction(
Action::AbortMerge,
),
);
} else if self.pending_rebase() {
self.queue.push(
InternalEvent::ConfirmAction(
Action::AbortRebase,
),
);
} else if self.pending_revert() {
self.queue.push(
InternalEvent::ConfirmAction(
Action::AbortRevert,
),
);
}
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.rebase_branch,
) && self.pending_rebase()
{
self.continue_rebase();
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL,
));
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.view_submodules,
) {
self.queue.push(InternalEvent::ViewSubmodules);
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
self.index.hide();
self.index_wd.hide();
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.index.show()?;
self.index_wd.show()?;
self.check_remotes();
self.update()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/stashlist.rs | src/tabs/stashlist.rs | use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo,
CommitList, Component, DrawableComponent, EventState,
},
keys::{key_match, SharedKeyConfig},
popups::InspectCommitOpen,
queue::{Action, InternalEvent, Queue, StackablePopupOpen},
strings,
};
use anyhow::Result;
use asyncgit::sync::{self, CommitId, RepoPath, RepoPathRef};
use crossterm::event::Event;
pub struct StashList {
repo: RepoPathRef,
list: CommitList,
visible: bool,
queue: Queue,
key_config: SharedKeyConfig,
}
impl StashList {
///
pub fn new(env: &Environment) -> Self {
Self {
visible: false,
list: CommitList::new(
env,
&strings::stashlist_title(&env.key_config),
),
queue: env.queue.clone(),
key_config: env.key_config.clone(),
repo: env.repo.clone(),
}
}
///
pub fn update(&mut self) -> Result<()> {
if self.is_visible() {
let stashes = sync::get_stashes(&self.repo.borrow())?;
self.list.set_commits(stashes.into_iter().collect());
}
Ok(())
}
fn apply_stash(&self) {
if let Some(e) = self.list.selected_entry() {
match sync::stash_apply(&self.repo.borrow(), e.id, false)
{
Ok(()) => {
self.queue.push(InternalEvent::TabSwitchStatus);
}
Err(e) => {
self.queue.push(InternalEvent::ShowErrorMsg(
format!("stash apply error:\n{e}",),
));
}
}
}
}
fn drop_stash(&self) {
if self.list.marked_count() > 0 {
self.queue.push(InternalEvent::ConfirmAction(
Action::StashDrop(self.list.marked_commits()),
));
} else if let Some(e) = self.list.selected_entry() {
self.queue.push(InternalEvent::ConfirmAction(
Action::StashDrop(vec![e.id]),
));
}
}
fn pop_stash(&self) {
if let Some(e) = self.list.selected_entry() {
self.queue.push(InternalEvent::ConfirmAction(
Action::StashPop(e.id),
));
}
}
fn inspect(&self) {
if let Some(e) = self.list.selected_entry() {
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::InspectCommit(
InspectCommitOpen::new(e.id),
),
));
}
}
/// Called when a pending stash action has been confirmed
pub fn action_confirmed(
&mut self,
repo: &RepoPath,
action: &Action,
) -> Result<()> {
match action {
Action::StashDrop(ids) => self.drop(repo, ids)?,
Action::StashPop(id) => self.pop(repo, *id)?,
_ => (),
}
Ok(())
}
fn drop(
&mut self,
repo: &RepoPath,
ids: &[CommitId],
) -> Result<()> {
for id in ids {
sync::stash_drop(repo, *id)?;
}
self.list.clear_marked();
self.update()?;
Ok(())
}
fn pop(&mut self, repo: &RepoPath, id: CommitId) -> Result<()> {
sync::stash_pop(repo, id)?;
self.list.clear_marked();
self.update()?;
self.queue.push(InternalEvent::TabSwitchStatus);
Ok(())
}
}
impl DrawableComponent for StashList {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::layout::Rect,
) -> Result<()> {
self.list.draw(f, rect)?;
Ok(())
}
}
impl Component for StashList {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
self.list.commands(out, force_all);
let selection_valid =
self.list.selected_entry().is_some();
out.push(CommandInfo::new(
strings::commands::stashlist_pop(&self.key_config),
selection_valid,
true,
));
out.push(CommandInfo::new(
strings::commands::stashlist_apply(&self.key_config),
selection_valid,
true,
));
out.push(CommandInfo::new(
strings::commands::stashlist_drop(
&self.key_config,
self.list.marked_count(),
),
selection_valid,
true,
));
out.push(CommandInfo::new(
strings::commands::stashlist_inspect(
&self.key_config,
),
selection_valid,
true,
));
}
visibility_blocking(self)
}
fn event(
&mut self,
ev: &crossterm::event::Event,
) -> Result<EventState> {
if self.is_visible() {
if self.list.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if let Event::Key(k) = ev {
if key_match(k, self.key_config.keys.enter) {
self.pop_stash();
} else if key_match(
k,
self.key_config.keys.stash_apply,
) {
self.apply_stash();
} else if key_match(
k,
self.key_config.keys.stash_drop,
) {
self.drop_stash();
} else if key_match(
k,
self.key_config.keys.stash_open,
) {
self.inspect();
}
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.update()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/mod.rs | src/tabs/mod.rs | /*!
The tabs module contains a struct for each of the tabs visible in the
ui:
- [`Status`]: Stage changes, push, pull
- [`Revlog`]: Revision log (think git log)
- [`FilesTab`]: See content of any file at HEAD. Blame
- [`Stashing`]: Managing one stash
- [`StashList`]: Managing all stashes
Many of the tabs can expand to show more details. This is done via
Enter or right-arrow. To close again, press ESC.
*/
mod files;
mod revlog;
mod stashing;
mod stashlist;
mod status;
pub use files::FilesTab;
pub use revlog::Revlog;
pub use stashing::{Stashing, StashingOptions};
pub use stashlist::StashList;
pub use status::Status;
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/files.rs | src/tabs/files.rs | use std::path::{Path, PathBuf};
use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, RevisionFilesComponent,
},
AsyncNotification,
};
use anyhow::Result;
use asyncgit::sync::{self, RepoPathRef};
pub struct FilesTab {
repo: RepoPathRef,
visible: bool,
files: RevisionFilesComponent,
}
impl FilesTab {
///
pub fn new(
env: &Environment,
select_file: Option<PathBuf>,
) -> Self {
Self {
visible: false,
files: RevisionFilesComponent::new(env, select_file),
repo: env.repo.clone(),
}
}
///
pub fn update(&mut self) -> Result<()> {
if self.is_visible() {
if let Ok(head) = sync::get_head(&self.repo.borrow()) {
self.files.set_commit(head)?;
}
}
Ok(())
}
///
pub fn anything_pending(&self) -> bool {
self.files.any_work_pending()
}
///
pub fn update_async(
&mut self,
ev: AsyncNotification,
) -> Result<()> {
if self.is_visible() {
self.files.update(ev)?;
}
Ok(())
}
pub fn file_finder_update(&mut self, file: &Path) {
self.files.find_file(file);
}
}
impl DrawableComponent for FilesTab {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::layout::Rect,
) -> Result<()> {
if self.is_visible() {
self.files.draw(f, rect)?;
}
Ok(())
}
}
impl Component for FilesTab {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
return self.files.commands(out, force_all);
}
visibility_blocking(self)
}
fn event(
&mut self,
ev: &crossterm::event::Event,
) -> Result<EventState> {
if self.visible {
return self.files.event(ev);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.update()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/revlog.rs | src/tabs/revlog.rs | use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo,
CommitDetailsComponent, CommitList, Component,
DrawableComponent, EventState,
},
keys::{key_match, SharedKeyConfig},
popups::{FileTreeOpen, InspectCommitOpen},
queue::{InternalEvent, Queue, StackablePopupOpen},
strings::{self, order},
try_or_popup,
ui::style::{SharedTheme, Theme},
};
use anyhow::Result;
use asyncgit::{
asyncjob::AsyncSingleJob,
sync::{
self, filter_commit_by_search, CommitId, LogFilterSearch,
LogFilterSearchOptions, RepoPathRef,
},
AsyncBranchesJob, AsyncCommitFilterJob, AsyncGitNotification,
AsyncLog, AsyncTags, CommitFilesParams, FetchStatus,
ProgressPercent,
};
use crossbeam_channel::Sender;
use crossterm::event::Event;
use indexmap::IndexSet;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
text::Span,
widgets::{Block, Borders, Paragraph},
Frame,
};
use std::{
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use sync::CommitTags;
struct LogSearchResult {
options: LogFilterSearchOptions,
duration: Duration,
}
//TODO: deserves its own component
enum LogSearch {
Off,
Searching(
AsyncSingleJob<AsyncCommitFilterJob>,
LogFilterSearchOptions,
Option<ProgressPercent>,
Arc<AtomicBool>,
),
Results(LogSearchResult),
}
///
pub struct Revlog {
repo: RepoPathRef,
commit_details: CommitDetailsComponent,
list: CommitList,
git_log: AsyncLog,
search: LogSearch,
git_tags: AsyncTags,
git_local_branches: AsyncSingleJob<AsyncBranchesJob>,
git_remote_branches: AsyncSingleJob<AsyncBranchesJob>,
queue: Queue,
visible: bool,
key_config: SharedKeyConfig,
sender: Sender<AsyncGitNotification>,
theme: SharedTheme,
}
impl Revlog {
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
queue: env.queue.clone(),
commit_details: CommitDetailsComponent::new(env),
list: CommitList::new(
env,
&strings::log_title(&env.key_config),
),
git_log: AsyncLog::new(
env.repo.borrow().clone(),
&env.sender_git,
None,
),
search: LogSearch::Off,
git_tags: AsyncTags::new(
env.repo.borrow().clone(),
&env.sender_git,
),
git_local_branches: AsyncSingleJob::new(
env.sender_git.clone(),
),
git_remote_branches: AsyncSingleJob::new(
env.sender_git.clone(),
),
visible: false,
key_config: env.key_config.clone(),
sender: env.sender_git.clone(),
theme: env.theme.clone(),
}
}
///
pub fn any_work_pending(&self) -> bool {
self.git_log.is_pending()
|| self.is_search_pending()
|| self.git_tags.is_pending()
|| self.git_local_branches.is_pending()
|| self.git_remote_branches.is_pending()
|| self.commit_details.any_work_pending()
}
const fn is_search_pending(&self) -> bool {
matches!(self.search, LogSearch::Searching(_, _, _, _))
}
///
pub fn update(&mut self) -> Result<()> {
if self.is_visible() {
if self.git_log.fetch()? == FetchStatus::Started {
self.list.clear();
}
self.list
.refresh_extend_data(self.git_log.extract_items()?);
self.git_tags.request(Duration::from_secs(3), false)?;
if self.commit_details.is_visible() {
let commit = self.selected_commit();
let tags = self.selected_commit_tags(commit.as_ref());
self.commit_details.set_commits(
commit.map(CommitFilesParams::from),
tags.as_ref(),
)?;
}
}
Ok(())
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if self.visible {
match ev {
AsyncGitNotification::CommitFiles
| AsyncGitNotification::Log => self.update()?,
AsyncGitNotification::CommitFilter => {
self.update_search_state();
}
AsyncGitNotification::Tags => {
if let Some(tags) = self.git_tags.last()? {
self.list.set_tags(tags);
self.update()?;
}
}
AsyncGitNotification::Branches => {
if let Some(local_branches) =
self.git_local_branches.take_last()
{
if let Some(Ok(local_branches)) =
local_branches.result()
{
self.list
.set_local_branches(local_branches);
self.update()?;
}
}
if let Some(remote_branches) =
self.git_remote_branches.take_last()
{
if let Some(Ok(remote_branches)) =
remote_branches.result()
{
self.list
.set_remote_branches(remote_branches);
self.update()?;
}
}
}
_ => (),
}
}
Ok(())
}
fn selected_commit(&self) -> Option<CommitId> {
self.list.selected_entry().map(|e| e.id)
}
fn selected_commit_tags(
&self,
commit: Option<&CommitId>,
) -> Option<CommitTags> {
let tags = self.list.tags();
commit.and_then(|commit| {
tags.and_then(|tags| tags.get(commit).cloned())
})
}
///
pub fn select_commit(&mut self, id: CommitId) -> Result<()> {
self.list.select_commit(id)
}
fn revert_commit(&self) -> Result<()> {
if let Some(c) = self.selected_commit() {
sync::revert_commit(&self.repo.borrow(), c)?;
self.queue.push(InternalEvent::TabSwitchStatus);
}
Ok(())
}
fn inspect_commit(&self) {
if let Some(commit_id) = self.selected_commit() {
let tags =
self.selected_commit_tags(Some(commit_id).as_ref());
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::InspectCommit(
InspectCommitOpen::new_with_tags(commit_id, tags),
),
));
}
}
pub fn search(&mut self, options: LogFilterSearchOptions) {
if !self.can_start_search() {
return;
}
if matches!(
self.search,
LogSearch::Off | LogSearch::Results(_)
) {
log::info!("start search: {options:?}");
let filter = filter_commit_by_search(
LogFilterSearch::new(options.clone()),
);
let cancellation_flag = Arc::new(AtomicBool::new(false));
let job = AsyncSingleJob::new(self.sender.clone());
job.spawn(AsyncCommitFilterJob::new(
self.repo.borrow().clone(),
self.list.copy_items(),
filter,
Arc::clone(&cancellation_flag),
));
self.search = LogSearch::Searching(
job,
options,
None,
Arc::clone(&cancellation_flag),
);
self.list.set_highlighting(None);
}
}
fn cancel_search(&mut self) -> bool {
if let LogSearch::Searching(_, _, _, cancellation_flag) =
&self.search
{
cancellation_flag.store(true, Ordering::Relaxed);
self.list.set_highlighting(None);
return true;
}
false
}
fn update_search_state(&mut self) {
match &mut self.search {
LogSearch::Off | LogSearch::Results(_) => (),
LogSearch::Searching(
search,
options,
progress,
cancel,
) => {
if search.is_pending() {
//update progress
*progress = search.progress();
} else if let Some(search) = search
.take_last()
.and_then(|search| search.result())
{
match search {
Ok(search) => {
let was_aborted =
cancel.load(Ordering::Relaxed);
self.search = if was_aborted {
LogSearch::Off
} else {
self.list.set_highlighting(Some(
Rc::new(
search
.result
.into_iter()
.collect::<IndexSet<_>>(),
),
));
LogSearch::Results(LogSearchResult {
options: options.clone(),
duration: search.duration,
})
};
}
Err(err) => {
self.queue.push(
InternalEvent::ShowErrorMsg(format!(
"search error: {err}",
)),
);
self.search = LogSearch::Off;
}
}
}
}
}
}
const fn is_in_search_mode(&self) -> bool {
!matches!(self.search, LogSearch::Off)
}
fn draw_search(&self, f: &mut Frame, area: Rect) {
let (text, title) = match &self.search {
LogSearch::Searching(_, options, progress, _) => (
format!("'{}'", options.search_pattern.clone()),
format!(
"({}%)",
progress
.map(|progress| progress.progress)
.unwrap_or_default()
),
),
LogSearch::Results(results) => {
let info = self.list.highlighted_selection_info();
(
format!(
"'{}' (duration: {:?})",
results.options.search_pattern.clone(),
results.duration,
),
format!(
"({}/{})",
(info.0 + 1).min(info.1),
info.1
),
)
}
LogSearch::Off => (String::new(), String::new()),
};
f.render_widget(
Paragraph::new(text)
.block(
Block::default()
.title(Span::styled(
format!(
"{} {}",
strings::POPUP_TITLE_LOG_SEARCH,
title
),
self.theme.title(true),
))
.borders(Borders::ALL)
.border_style(Theme::attention_block()),
)
.alignment(Alignment::Left),
area,
);
}
const fn can_close_search(&self) -> bool {
self.is_in_search_mode() && !self.is_search_pending()
}
fn can_start_search(&self) -> bool {
!self.git_log.is_pending() && !self.is_search_pending()
}
}
impl DrawableComponent for Revlog {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
let area = if self.is_in_search_mode() {
Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Min(1), Constraint::Length(3)]
.as_ref(),
)
.split(area)
} else {
Rc::new([area])
};
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[
Constraint::Percentage(60),
Constraint::Percentage(40),
]
.as_ref(),
)
.split(area[0]);
if self.commit_details.is_visible() {
self.list.draw(f, chunks[0])?;
self.commit_details.draw(f, chunks[1])?;
} else {
self.list.draw(f, area[0])?;
}
if self.is_in_search_mode() {
self.draw_search(f, area[1]);
}
Ok(())
}
}
impl Component for Revlog {
//TODO: cleanup
#[allow(clippy::too_many_lines)]
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.visible {
let event_used = self.list.event(ev)?;
if event_used.is_consumed() {
self.update()?;
return Ok(EventState::Consumed);
} else if let Event::Key(k) = ev {
if key_match(k, self.key_config.keys.enter) {
self.commit_details.toggle_visible()?;
self.update()?;
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.exit_popup,
) {
if self.is_search_pending() {
self.cancel_search();
} else if self.can_close_search() {
self.list.set_highlighting(None);
self.search = LogSearch::Off;
}
return Ok(EventState::Consumed);
} else if key_match(k, self.key_config.keys.copy) {
try_or_popup!(
self,
strings::POPUP_FAIL_COPY,
self.list.copy_commit_hash()
);
return Ok(EventState::Consumed);
} else if key_match(k, self.key_config.keys.push) {
self.queue.push(InternalEvent::PushTags);
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.log_tag_commit,
) {
return self.selected_commit().map_or(
Ok(EventState::NotConsumed),
|id| {
self.queue
.push(InternalEvent::TagCommit(id));
Ok(EventState::Consumed)
},
);
} else if key_match(
k,
self.key_config.keys.move_right,
) && self.commit_details.is_visible()
{
self.inspect_commit();
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.select_branch,
) && !self.is_search_pending()
{
self.queue.push(InternalEvent::SelectBranch);
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.status_reset_item,
) && !self.is_search_pending()
{
try_or_popup!(
self,
"revert error:",
self.revert_commit()
);
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.open_file_tree,
) && !self.is_search_pending()
{
return self.selected_commit().map_or(
Ok(EventState::NotConsumed),
|id| {
self.queue.push(
InternalEvent::OpenPopup(
StackablePopupOpen::FileTree(
FileTreeOpen::new(id),
),
),
);
Ok(EventState::Consumed)
},
);
} else if key_match(k, self.key_config.keys.tags) {
self.queue.push(InternalEvent::Tags);
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.log_reset_commit,
) && !self.is_search_pending()
{
return self.selected_commit().map_or(
Ok(EventState::NotConsumed),
|id| {
self.queue.push(
InternalEvent::OpenResetPopup(id),
);
Ok(EventState::Consumed)
},
);
} else if key_match(
k,
self.key_config.keys.log_reword_commit,
) && !self.is_search_pending()
{
return self.selected_commit().map_or(
Ok(EventState::NotConsumed),
|id| {
self.queue.push(
InternalEvent::RewordCommit(id),
);
Ok(EventState::Consumed)
},
);
} else if key_match(k, self.key_config.keys.log_find)
&& self.can_start_search()
{
self.queue
.push(InternalEvent::OpenLogSearchPopup);
return Ok(EventState::Consumed);
} else if key_match(
k,
self.key_config.keys.compare_commits,
) && self.list.marked_count() > 0
&& !self.is_search_pending()
{
if self.list.marked_count() == 1 {
// compare against head
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::CompareCommits(
InspectCommitOpen::new(
self.list.marked_commits()[0],
),
),
));
return Ok(EventState::Consumed);
} else if self.list.marked_count() == 2 {
//compare two marked commits
let marked = self.list.marked_commits();
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::CompareCommits(
InspectCommitOpen {
commit_id: marked[0],
compare_id: Some(marked[1]),
tags: None,
},
),
));
return Ok(EventState::Consumed);
}
}
}
}
Ok(EventState::NotConsumed)
}
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
self.list.commands(out, force_all);
}
out.push(
CommandInfo::new(
strings::commands::log_close_search(&self.key_config),
true,
(self.visible
&& (self.can_close_search()
|| self.is_search_pending()))
|| force_all,
)
.order(order::PRIORITY),
);
out.push(CommandInfo::new(
strings::commands::log_details_toggle(&self.key_config),
true,
self.visible,
));
out.push(CommandInfo::new(
strings::commands::commit_details_open(&self.key_config),
true,
(self.visible && self.commit_details.is_visible())
|| force_all,
));
out.push(CommandInfo::new(
strings::commands::open_branch_select_popup(
&self.key_config,
),
true,
(self.visible && !self.is_search_pending()) || force_all,
));
out.push(CommandInfo::new(
strings::commands::compare_with_head(&self.key_config),
self.list.marked_count() == 1,
(self.visible
&& !self.is_search_pending()
&& self.list.marked_count() <= 1)
|| force_all,
));
out.push(CommandInfo::new(
strings::commands::compare_commits(&self.key_config),
true,
(self.visible
&& !self.is_search_pending()
&& self.list.marked_count() == 2)
|| force_all,
));
out.push(CommandInfo::new(
strings::commands::copy_hash(&self.key_config),
self.selected_commit().is_some(),
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::log_tag_commit(&self.key_config),
self.selected_commit().is_some(),
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::log_checkout_commit(&self.key_config),
self.selected_commit().is_some(),
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::open_tags_popup(&self.key_config),
true,
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::push_tags(&self.key_config),
true,
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::inspect_file_tree(&self.key_config),
self.selected_commit().is_some(),
(self.visible && !self.is_search_pending()) || force_all,
));
out.push(CommandInfo::new(
strings::commands::revert_commit(&self.key_config),
self.selected_commit().is_some(),
(self.visible && !self.is_search_pending()) || force_all,
));
out.push(CommandInfo::new(
strings::commands::log_reset_commit(&self.key_config),
self.selected_commit().is_some(),
(self.visible && !self.is_search_pending()) || force_all,
));
out.push(CommandInfo::new(
strings::commands::log_reword_commit(&self.key_config),
self.selected_commit().is_some(),
(self.visible && !self.is_search_pending()) || force_all,
));
out.push(CommandInfo::new(
strings::commands::log_find_commit(&self.key_config),
self.can_start_search(),
self.visible || force_all,
));
visibility_blocking(self)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
self.git_log.set_background();
}
fn show(&mut self) -> Result<()> {
self.visible = true;
self.git_local_branches.spawn(AsyncBranchesJob::new(
self.repo.borrow().clone(),
true,
));
self.git_remote_branches.spawn(AsyncBranchesJob::new(
self.repo.borrow().clone(),
false,
));
self.update()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/tabs/stashing.rs | src/tabs/stashing.rs | use crate::{
accessors,
app::Environment,
components::{
command_pump, event_pump, visibility_blocking,
CommandBlocking, CommandInfo, Component, DrawableComponent,
EventState, StatusTreeComponent,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, Queue},
strings,
ui::style::SharedTheme,
};
use anyhow::Result;
use asyncgit::{
sync::{self, status::StatusType, RepoPathRef},
AsyncGitNotification, AsyncStatus, StatusParams,
};
use crossterm::event::Event;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout},
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
};
use std::borrow::Cow;
#[derive(Default, Clone, Copy, Debug)]
pub struct StashingOptions {
pub stash_untracked: bool,
pub keep_index: bool,
}
pub struct Stashing {
repo: RepoPathRef,
index: StatusTreeComponent,
visible: bool,
options: StashingOptions,
theme: SharedTheme,
git_status: AsyncStatus,
queue: Queue,
key_config: SharedKeyConfig,
}
impl Stashing {
accessors!(self, [index]);
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
index: StatusTreeComponent::new(
env,
&strings::stashing_files_title(&env.key_config),
true,
),
visible: false,
options: StashingOptions {
keep_index: false,
stash_untracked: true,
},
theme: env.theme.clone(),
git_status: AsyncStatus::new(
env.repo.borrow().clone(),
env.sender_git.clone(),
),
queue: env.queue.clone(),
key_config: env.key_config.clone(),
}
}
///
pub fn update(&self) -> Result<()> {
if self.is_visible() {
self.git_status
//TODO: support options
.fetch(&StatusParams::new(StatusType::Both, None))?;
}
Ok(())
}
///
pub fn anything_pending(&self) -> bool {
self.git_status.is_pending()
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if self.is_visible() && ev == AsyncGitNotification::Status {
let status = self.git_status.last()?;
self.index.show()?;
self.index.update(&status.items)?;
}
Ok(())
}
fn get_option_text(&self) -> Vec<Line<'_>> {
let bracket_open = Span::raw(Cow::from("["));
let bracket_close = Span::raw(Cow::from("]"));
let option_on =
Span::styled(Cow::from("x"), self.theme.option(true));
let option_off =
Span::styled(Cow::from("_"), self.theme.option(false));
vec![
Line::from(vec![
bracket_open.clone(),
if self.options.stash_untracked {
option_on.clone()
} else {
option_off.clone()
},
bracket_close.clone(),
Span::raw(Cow::from(" stash untracked")),
]),
Line::from(vec![
bracket_open,
if self.options.keep_index {
option_on
} else {
option_off
},
bracket_close,
Span::raw(Cow::from(" keep index")),
]),
]
}
}
impl DrawableComponent for Stashing {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::layout::Rect,
) -> Result<()> {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(
[Constraint::Min(1), Constraint::Length(22)].as_ref(),
)
.split(rect);
let right_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Length(4), Constraint::Min(1)].as_ref(),
)
.split(chunks[1]);
f.render_widget(
Paragraph::new(self.get_option_text())
.block(Block::default().borders(Borders::ALL).title(
strings::stashing_options_title(&self.key_config),
))
.alignment(Alignment::Left),
right_chunks[0],
);
self.index.draw(f, chunks[0])?;
Ok(())
}
}
impl Component for Stashing {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
command_pump(
out,
force_all,
self.components().as_slice(),
);
out.push(CommandInfo::new(
strings::commands::stashing_save(&self.key_config),
self.visible && !self.index.is_empty(),
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::stashing_toggle_indexed(
&self.key_config,
),
self.visible,
self.visible || force_all,
));
out.push(CommandInfo::new(
strings::commands::stashing_toggle_untracked(
&self.key_config,
),
self.visible,
self.visible || force_all,
));
}
visibility_blocking(self)
}
fn event(
&mut self,
ev: &crossterm::event::Event,
) -> Result<EventState> {
if self.visible {
if event_pump(ev, self.components_mut().as_mut_slice())?
.is_consumed()
{
return Ok(EventState::Consumed);
}
if let Event::Key(k) = ev {
return if key_match(
k,
self.key_config.keys.stashing_save,
) && !self.index.is_empty()
{
self.queue.push(InternalEvent::PopupStashing(
self.options,
));
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.stashing_toggle_index,
) {
self.options.keep_index =
!self.options.keep_index;
self.update()?;
Ok(EventState::Consumed)
} else if key_match(
k,
self.key_config.keys.stashing_toggle_untracked,
) {
self.options.stash_untracked =
!self.options.stash_untracked;
self.update()?;
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
};
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
let config_untracked_files =
sync::untracked_files_config(&self.repo.borrow())?;
self.options.stash_untracked =
!config_untracked_files.include_none();
self.index.show()?;
self.visible = true;
self.update()?;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/branchlist.rs | src/popups/branchlist.rs | use crate::components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, FuzzyFinderTarget, VerticalScroll,
};
use crate::{
app::Environment,
components::ScrollType,
keys::{key_match, SharedKeyConfig},
queue::{
Action, InternalEvent, NeedsUpdate, Queue, StackablePopupOpen,
},
strings, try_or_popup,
ui::{self, Size},
};
use anyhow::Result;
use asyncgit::{
sync::{
self,
branch::{
checkout_remote_branch, BranchDetails, LocalBranch,
RemoteBranch,
},
checkout_branch, get_branches_info,
status::StatusType,
BranchInfo, BranchType, CommitId, RepoPathRef, RepoState,
},
AsyncGitNotification,
};
use crossterm::event::{Event, KeyEvent};
use ratatui::{
layout::{
Alignment, Constraint, Direction, Layout, Margin, Rect,
},
text::{Line, Span, Text},
widgets::{Block, BorderType, Borders, Clear, Paragraph, Tabs},
Frame,
};
use std::cell::Cell;
use ui::style::SharedTheme;
use unicode_truncate::UnicodeTruncateStr;
use super::InspectCommitOpen;
///
pub struct BranchListPopup {
repo: RepoPathRef,
branches: Vec<BranchInfo>,
local: bool,
has_remotes: bool,
visible: bool,
selection: u16,
scroll: VerticalScroll,
current_height: Cell<u16>,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
}
impl DrawableComponent for BranchListPopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.is_visible() {
const PERCENT_SIZE: Size = Size::new(80, 50);
const MIN_SIZE: Size = Size::new(60, 20);
let area = ui::centered_rect(
PERCENT_SIZE.width,
PERCENT_SIZE.height,
f.area(),
);
let area =
ui::rect_inside(MIN_SIZE, f.area().into(), area);
let area = area.intersection(rect);
f.render_widget(Clear, area);
f.render_widget(
Block::default()
.title(strings::title_branches())
.border_type(BorderType::Thick)
.borders(Borders::ALL),
area,
);
let area = area.inner(Margin {
vertical: 1,
horizontal: 1,
});
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[Constraint::Length(2), Constraint::Min(1)]
.as_ref(),
)
.split(area);
self.draw_tabs(f, chunks[0]);
self.draw_list(f, chunks[1])?;
}
Ok(())
}
}
impl Component for BranchListPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
if !force_all {
out.clear();
}
self.add_commands_internal(out);
}
visibility_blocking(self)
}
//TODO: cleanup
#[allow(clippy::cognitive_complexity)]
fn event(&mut self, ev: &Event) -> Result<EventState> {
if !self.visible {
return Ok(EventState::NotConsumed);
}
if let Event::Key(e) = ev {
if self.move_event(e)?.is_consumed() {
return Ok(EventState::Consumed);
}
let selection_is_cur_branch =
self.selection_is_cur_branch();
if key_match(e, self.key_config.keys.enter) {
try_or_popup!(
self,
"switch branch error:",
self.switch_to_selected_branch()
);
} else if key_match(e, self.key_config.keys.create_branch)
&& self.local
{
self.queue.push(InternalEvent::CreateBranch);
} else if key_match(e, self.key_config.keys.rename_branch)
&& self.valid_selection()
{
self.rename_branch();
} else if key_match(e, self.key_config.keys.delete_branch)
&& !selection_is_cur_branch
&& self.valid_selection()
{
self.delete_branch();
} else if key_match(e, self.key_config.keys.merge_branch)
&& !selection_is_cur_branch
&& self.valid_selection()
{
try_or_popup!(
self,
"merge branch error:",
self.merge_branch()
);
} else if key_match(e, self.key_config.keys.rebase_branch)
&& !selection_is_cur_branch
&& self.valid_selection()
{
try_or_popup!(
self,
"rebase error:",
self.rebase_branch()
);
} else if key_match(e, self.key_config.keys.move_right)
&& self.valid_selection()
{
self.inspect_head_of_branch();
} else if key_match(
e,
self.key_config.keys.compare_commits,
) && self.valid_selection()
{
self.hide();
if let Some(commit_id) = self.get_selected_commit() {
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::CompareCommits(
InspectCommitOpen::new(commit_id),
),
));
}
} else if key_match(e, self.key_config.keys.fetch)
&& self.has_remotes
{
self.queue.push(InternalEvent::FetchRemotes);
} else if key_match(e, self.key_config.keys.view_remotes)
{
self.queue.push(InternalEvent::ViewRemotes);
} else if key_match(e, self.key_config.keys.reset_branch)
{
if let Some(commit_id) = self.get_selected_commit() {
self.queue.push(InternalEvent::OpenResetPopup(
commit_id,
));
}
} else if key_match(
e,
self.key_config.keys.cmd_bar_toggle,
) {
//do not consume if its the more key
return Ok(EventState::NotConsumed);
} else if key_match(e, self.key_config.keys.branch_find) {
let branches = self
.branches
.iter()
.map(|b| b.name.clone())
.collect();
self.queue.push(InternalEvent::OpenFuzzyFinder(
branches,
FuzzyFinderTarget::Branches,
));
}
}
Ok(EventState::Consumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
impl BranchListPopup {
pub fn new(env: &Environment) -> Self {
Self {
branches: Vec::new(),
local: true,
has_remotes: false,
visible: false,
selection: 0,
scroll: VerticalScroll::new(),
queue: env.queue.clone(),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
current_height: Cell::new(0),
repo: env.repo.clone(),
}
}
fn move_event(&mut self, e: &KeyEvent) -> Result<EventState> {
if key_match(e, self.key_config.keys.exit_popup) {
self.hide();
} else if key_match(e, self.key_config.keys.move_down) {
return self
.move_selection(ScrollType::Up)
.map(Into::into);
} else if key_match(e, self.key_config.keys.move_up) {
return self
.move_selection(ScrollType::Down)
.map(Into::into);
} else if key_match(e, self.key_config.keys.page_down) {
return self
.move_selection(ScrollType::PageDown)
.map(Into::into);
} else if key_match(e, self.key_config.keys.page_up) {
return self
.move_selection(ScrollType::PageUp)
.map(Into::into);
} else if key_match(e, self.key_config.keys.home) {
return self
.move_selection(ScrollType::Home)
.map(Into::into);
} else if key_match(e, self.key_config.keys.end) {
return self
.move_selection(ScrollType::End)
.map(Into::into);
} else if key_match(e, self.key_config.keys.tab_toggle) {
self.local = !self.local;
self.check_remotes();
self.update_branches()?;
}
Ok(EventState::NotConsumed)
}
///
pub fn open(&mut self) -> Result<()> {
self.show()?;
self.update_branches()?;
Ok(())
}
pub fn branch_finder_update(&mut self, idx: usize) -> Result<()> {
self.set_selection(idx.try_into()?)?;
Ok(())
}
fn check_remotes(&mut self) {
if self.visible {
self.has_remotes =
get_branches_info(&self.repo.borrow(), false)
.map(|branches| !branches.is_empty())
.unwrap_or(false);
}
}
/// fetch list of branches
pub fn update_branches(&mut self) -> Result<()> {
if self.is_visible() {
self.check_remotes();
self.branches =
get_branches_info(&self.repo.borrow(), self.local)?;
//remove remote branch called `HEAD`
if !self.local {
self.branches
.iter()
.position(|b| b.name.ends_with("/HEAD"))
.map(|idx| self.branches.remove(idx));
}
self.set_selection(self.selection)?;
}
Ok(())
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if self.is_visible() && ev == AsyncGitNotification::Push {
self.update_branches()?;
}
Ok(())
}
fn valid_selection(&self) -> bool {
!self.branches.is_empty()
}
fn merge_branch(&mut self) -> Result<()> {
if let Some(branch) =
self.branches.get(usize::from(self.selection))
{
sync::merge_branch(
&self.repo.borrow(),
&branch.name,
self.get_branch_type(),
)?;
self.hide_and_switch_tab()?;
}
Ok(())
}
fn rebase_branch(&mut self) -> Result<()> {
if let Some(branch) =
self.branches.get(usize::from(self.selection))
{
sync::rebase_branch(
&self.repo.borrow(),
&branch.name,
self.get_branch_type(),
)?;
self.hide_and_switch_tab()?;
}
Ok(())
}
fn inspect_head_of_branch(&mut self) {
if let Some(commit_id) = self.get_selected_commit() {
self.hide();
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::InspectCommit(
InspectCommitOpen::new(commit_id),
),
));
}
}
const fn get_branch_type(&self) -> BranchType {
if self.local {
BranchType::Local
} else {
BranchType::Remote
}
}
fn hide_and_switch_tab(&mut self) -> Result<()> {
self.hide();
self.queue.push(InternalEvent::Update(NeedsUpdate::ALL));
if sync::repo_state(&self.repo.borrow())? != RepoState::Clean
{
self.queue.push(InternalEvent::TabSwitchStatus);
}
Ok(())
}
fn selection_is_cur_branch(&self) -> bool {
self.branches
.iter()
.enumerate()
.filter(|(index, b)| {
b.local_details().is_some_and(|details| {
details.is_head
&& *index == self.selection as usize
})
})
.count() > 0
}
// top commit of selected branch
fn get_selected_commit(&self) -> Option<CommitId> {
self.branches
.get(usize::from(self.selection))
.map(|b| b.top_commit)
}
///
fn move_selection(&mut self, scroll: ScrollType) -> Result<bool> {
let new_selection = match scroll {
ScrollType::Up => self.selection.saturating_add(1),
ScrollType::Down => self.selection.saturating_sub(1),
ScrollType::PageDown => self
.selection
.saturating_add(self.current_height.get()),
ScrollType::PageUp => self
.selection
.saturating_sub(self.current_height.get()),
ScrollType::Home => 0,
ScrollType::End => {
let num_branches: u16 =
self.branches.len().try_into()?;
num_branches.saturating_sub(1)
}
};
self.set_selection(new_selection)?;
Ok(true)
}
fn set_selection(&mut self, selection: u16) -> Result<()> {
let num_branches: u16 = self.branches.len().try_into()?;
let num_branches = num_branches.saturating_sub(1);
let selection = if selection > num_branches {
num_branches
} else {
selection
};
self.selection = selection;
Ok(())
}
/// Get branches to display
fn get_text(
&self,
theme: &SharedTheme,
width_available: u16,
height: usize,
) -> Text<'_> {
const UPSTREAM_SYMBOL: char = '\u{2191}';
const TRACKING_SYMBOL: char = '\u{2193}';
const HEAD_SYMBOL: char = '*';
const EMPTY_SYMBOL: char = ' ';
const THREE_DOTS: &str = "...";
const THREE_DOTS_LENGTH: usize = THREE_DOTS.len(); // "..."
const COMMIT_HASH_LENGTH: usize = 8;
const IS_HEAD_STAR_LENGTH: usize = 3; // "* "
let branch_name_length: usize =
width_available as usize * 40 / 100;
// commit message takes up the remaining width
let commit_message_length: usize = (width_available as usize)
.saturating_sub(COMMIT_HASH_LENGTH)
.saturating_sub(branch_name_length)
.saturating_sub(IS_HEAD_STAR_LENGTH)
.saturating_sub(THREE_DOTS_LENGTH);
let mut txt = Vec::new();
for (i, displaybranch) in self
.branches
.iter()
.skip(self.scroll.get_top())
.take(height)
.enumerate()
{
let mut commit_message =
displaybranch.top_commit_message.clone();
if commit_message.len() > commit_message_length {
commit_message.unicode_truncate(
commit_message_length
.saturating_sub(THREE_DOTS_LENGTH),
);
commit_message += THREE_DOTS;
}
let mut branch_name = displaybranch.name.clone();
if branch_name.len()
> branch_name_length.saturating_sub(THREE_DOTS_LENGTH)
{
branch_name = branch_name
.unicode_truncate(
branch_name_length
.saturating_sub(THREE_DOTS_LENGTH),
)
.0
.to_string();
branch_name += THREE_DOTS;
}
let selected = (self.selection as usize
- self.scroll.get_top())
== i;
let is_head = displaybranch
.local_details()
.is_some_and(|details| details.is_head);
let is_head_str =
if is_head { HEAD_SYMBOL } else { EMPTY_SYMBOL };
let upstream_tracking_str = match displaybranch.details {
BranchDetails::Local(LocalBranch {
has_upstream,
..
}) if has_upstream => UPSTREAM_SYMBOL,
BranchDetails::Remote(RemoteBranch {
has_tracking,
..
}) if has_tracking => TRACKING_SYMBOL,
_ => EMPTY_SYMBOL,
};
let span_prefix = Span::styled(
format!("{is_head_str}{upstream_tracking_str} "),
theme.commit_author(selected),
);
let span_hash = Span::styled(
format!(
"{} ",
displaybranch.top_commit.get_short_string()
),
theme.commit_hash(selected),
);
let span_msg = Span::styled(
commit_message.clone(),
theme.text(true, selected),
);
let span_name = Span::styled(
format!("{branch_name:branch_name_length$} "),
theme.branch(selected, is_head),
);
txt.push(Line::from(vec![
span_prefix,
span_name,
span_hash,
span_msg,
]));
}
Text::from(txt)
}
///
fn switch_to_selected_branch(&mut self) -> Result<()> {
if !self.valid_selection() {
anyhow::bail!("no valid branch selected");
}
let status = sync::status::get_status(
&self.repo.borrow(),
StatusType::WorkingDir,
None,
)
.expect("Could not get status");
let selected_branch = &self.branches[self.selection as usize];
if status.is_empty() {
if self.local {
checkout_branch(
&self.repo.borrow(),
&selected_branch.name,
)?;
self.hide();
} else {
checkout_remote_branch(
&self.repo.borrow(),
selected_branch,
)?;
self.local = true;
self.update_branches()?;
}
self.queue.push(InternalEvent::Update(NeedsUpdate::ALL));
} else {
self.queue.push(InternalEvent::CheckoutOption(
selected_branch.clone(),
));
}
Ok(())
}
fn draw_tabs(&self, f: &mut Frame, r: Rect) {
let tabs: Vec<Line> =
[Span::raw("Local"), Span::raw("Remote")]
.iter()
.cloned()
.map(Line::from)
.collect();
f.render_widget(
Tabs::new(tabs)
.block(
Block::default()
.borders(Borders::BOTTOM)
.border_style(self.theme.block(false)),
)
.style(self.theme.tab(false))
.highlight_style(self.theme.tab(true))
.divider(strings::tab_divider(&self.key_config))
.select(if self.local { 0 } else { 1 }),
r,
);
}
fn draw_list(&self, f: &mut Frame, r: Rect) -> Result<()> {
let height_in_lines = r.height as usize;
self.current_height.set(height_in_lines.try_into()?);
self.scroll.update(
self.selection as usize,
self.branches.len(),
height_in_lines,
);
f.render_widget(
Paragraph::new(self.get_text(
&self.theme,
r.width,
height_in_lines,
))
.alignment(Alignment::Left),
r,
);
let mut r = r;
r.width += 1;
r.height += 2;
r.y = r.y.saturating_sub(1);
self.scroll.draw(f, r, &self.theme);
Ok(())
}
fn rename_branch(&self) {
let cur_branch = &self.branches[self.selection as usize];
self.queue.push(InternalEvent::RenameBranch(
cur_branch.reference.clone(),
cur_branch.name.clone(),
));
}
fn delete_branch(&self) {
let reference =
self.branches[self.selection as usize].reference.clone();
self.queue.push(InternalEvent::ConfirmAction(
if self.local {
Action::DeleteLocalBranch(reference)
} else {
Action::DeleteRemoteBranch(reference)
},
));
}
fn add_commands_internal(&self, out: &mut Vec<CommandInfo>) {
let selection_is_cur_branch = self.selection_is_cur_branch();
out.push(CommandInfo::new(
strings::commands::scroll(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::commit_details_open(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::compare_with_head(&self.key_config),
!selection_is_cur_branch,
true,
));
out.push(CommandInfo::new(
strings::commands::toggle_branch_popup(
&self.key_config,
self.local,
),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::select_branch_popup(&self.key_config),
!selection_is_cur_branch && self.valid_selection(),
true,
));
out.push(CommandInfo::new(
strings::commands::open_branch_create_popup(
&self.key_config,
),
true,
self.local,
));
out.push(CommandInfo::new(
strings::commands::delete_branch_popup(&self.key_config),
!selection_is_cur_branch,
true,
));
out.push(CommandInfo::new(
strings::commands::merge_branch_popup(&self.key_config),
!selection_is_cur_branch,
true,
));
out.push(CommandInfo::new(
strings::commands::branch_popup_rebase(&self.key_config),
!selection_is_cur_branch,
true,
));
out.push(CommandInfo::new(
strings::commands::rename_branch_popup(&self.key_config),
true,
self.local,
));
out.push(CommandInfo::new(
strings::commands::fetch_remotes(&self.key_config),
self.has_remotes,
true,
));
out.push(CommandInfo::new(
strings::commands::find_branch(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::reset_branch(&self.key_config),
self.valid_selection(),
true,
));
out.push(CommandInfo::new(
strings::commands::view_remotes(&self.key_config),
true,
self.has_remotes,
));
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/rename_branch.rs | src/popups/rename_branch.rs | use crate::components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, InputType, TextInputComponent,
};
use crate::ui::style::SharedTheme;
use crate::{
app::Environment,
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, NeedsUpdate, Queue},
strings,
};
use anyhow::Result;
use asyncgit::sync::{self, RepoPathRef};
use crossterm::event::Event;
use easy_cast::Cast;
use ratatui::{layout::Rect, widgets::Paragraph, Frame};
pub struct RenameBranchPopup {
repo: RepoPathRef,
input: TextInputComponent,
branch_ref: Option<String>,
queue: Queue,
key_config: SharedKeyConfig,
theme: SharedTheme,
}
impl DrawableComponent for RenameBranchPopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.is_visible() {
self.input.draw(f, rect)?;
self.draw_warnings(f);
}
Ok(())
}
}
impl Component for RenameBranchPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
self.input.commands(out, force_all);
out.push(CommandInfo::new(
strings::commands::rename_branch_confirm_msg(
&self.key_config,
),
true,
true,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.is_visible() {
if self.input.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.enter) {
self.rename_branch();
}
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.input.is_visible()
}
fn hide(&mut self) {
self.input.hide();
}
fn show(&mut self) -> Result<()> {
self.input.show()?;
Ok(())
}
}
impl RenameBranchPopup {
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
queue: env.queue.clone(),
input: TextInputComponent::new(
env,
&strings::rename_branch_popup_title(&env.key_config),
&strings::rename_branch_popup_msg(&env.key_config),
true,
)
.with_input_type(InputType::Singleline),
branch_ref: None,
key_config: env.key_config.clone(),
theme: env.theme.clone(),
}
}
///
pub fn open(
&mut self,
branch_ref: String,
cur_name: String,
) -> Result<()> {
self.branch_ref = None;
self.branch_ref = Some(branch_ref);
self.input.set_text(cur_name);
self.show()?;
Ok(())
}
///
pub fn rename_branch(&mut self) {
if let Some(br) = &self.branch_ref {
let res = sync::rename_branch(
&self.repo.borrow(),
br,
self.input.get_text(),
);
match res {
Ok(()) => {
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL,
));
self.hide();
self.queue.push(InternalEvent::SelectBranch);
}
Err(e) => {
log::error!("create branch: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(
format!("rename branch error:\n{e}",),
));
}
}
} else {
log::error!("create branch: No branch selected");
self.queue.push(InternalEvent::ShowErrorMsg(
"rename branch error: No branch selected to rename"
.to_string(),
));
}
self.input.clear();
}
fn draw_warnings(&self, f: &mut Frame) {
let current_text = self.input.get_text();
if !current_text.is_empty() {
let valid = sync::validate_branch_name(current_text)
.unwrap_or_default();
if !valid {
let msg = strings::branch_name_invalid();
let msg_length: u16 = msg.len().cast();
let w = Paragraph::new(msg)
.style(self.theme.text_danger());
let rect = {
let mut rect = self.input.get_area();
rect.y += rect.height.saturating_sub(1);
rect.height = 1;
let offset =
rect.width.saturating_sub(msg_length + 1);
rect.width =
rect.width.saturating_sub(offset + 1);
rect.x += offset;
rect
};
f.render_widget(w, rect);
}
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/taglist.rs | src/popups/taglist.rs | use crate::components::{
time_to_string, visibility_blocking, CommandBlocking,
CommandInfo, Component, DrawableComponent, EventState,
};
use crate::{
app::Environment,
components::ScrollType,
keys::{key_match, SharedKeyConfig},
queue::{Action, InternalEvent, Queue},
strings,
ui::{self, Size},
AsyncNotification,
};
use anyhow::Result;
use asyncgit::{
asyncjob::AsyncSingleJob,
remote_tags::AsyncRemoteTagsJob,
sync::cred::{
extract_username_password, need_username_password,
BasicAuthCredential,
},
sync::{
self, get_tags_with_metadata, RepoPathRef, TagWithMetadata,
},
AsyncGitNotification,
};
use crossterm::event::Event;
use ratatui::{
layout::{Constraint, Margin, Rect},
text::Span,
widgets::{
Block, BorderType, Borders, Cell, Clear, Row, Table,
TableState,
},
Frame,
};
use ui::style::SharedTheme;
///
pub struct TagListPopup {
repo: RepoPathRef,
theme: SharedTheme,
queue: Queue,
tags: Option<Vec<TagWithMetadata>>,
visible: bool,
table_state: std::cell::Cell<TableState>,
current_height: std::cell::Cell<usize>,
missing_remote_tags: Option<Vec<String>>,
has_remotes: bool,
basic_credential: Option<BasicAuthCredential>,
async_remote_tags: AsyncSingleJob<AsyncRemoteTagsJob>,
key_config: SharedKeyConfig,
}
impl DrawableComponent for TagListPopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.visible {
const PERCENT_SIZE: Size = Size::new(80, 50);
const MIN_SIZE: Size = Size::new(60, 20);
let area = ui::centered_rect(
PERCENT_SIZE.width,
PERCENT_SIZE.height,
f.area(),
);
let area =
ui::rect_inside(MIN_SIZE, f.area().into(), area);
let area = area.intersection(rect);
let tag_name_width =
self.tags.as_ref().map_or(0, |tags| {
tags.iter()
.fold(0, |acc, tag| acc.max(tag.name.len()))
});
let constraints = [
// symbol if tag is not yet on remote and can be pushed
Constraint::Length(1),
// tag name
Constraint::Length(tag_name_width.try_into()?),
// commit date
Constraint::Length(10),
// author width
Constraint::Length(19),
// attachment
Constraint::Length(1),
// commit id
Constraint::Percentage(100),
];
let rows = self.get_rows();
let number_of_rows = rows.len();
let table = Table::new(rows, constraints)
.column_spacing(1)
.row_highlight_style(self.theme.text(true, true))
.block(
Block::default()
.borders(Borders::ALL)
.title(Span::styled(
strings::title_tags(),
self.theme.title(true),
))
.border_style(self.theme.block(true))
.border_type(BorderType::Thick),
);
let mut table_state = self.table_state.take();
f.render_widget(Clear, area);
f.render_stateful_widget(table, area, &mut table_state);
let area = area.inner(Margin {
vertical: 1,
horizontal: 0,
});
ui::draw_scrollbar(
f,
area,
&self.theme,
number_of_rows,
table_state.selected().unwrap_or(0),
ui::Orientation::Vertical,
);
self.table_state.set(table_state);
self.current_height.set(area.height.into());
}
Ok(())
}
}
impl Component for TagListPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible || force_all {
if !force_all {
out.clear();
}
out.push(CommandInfo::new(
strings::commands::scroll(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::delete_tag_popup(&self.key_config),
self.valid_selection(),
true,
));
out.push(CommandInfo::new(
strings::commands::select_tag(&self.key_config),
self.valid_selection(),
true,
));
out.push(CommandInfo::new(
strings::commands::push_tags(&self.key_config),
self.has_remotes,
true,
));
out.push(CommandInfo::new(
strings::commands::show_tag_annotation(
&self.key_config,
),
self.can_show_annotation(),
true,
));
}
visibility_blocking(self)
}
fn event(&mut self, event: &Event) -> Result<EventState> {
if self.visible {
if let Event::Key(key) = event {
if key_match(key, self.key_config.keys.exit_popup) {
self.hide();
} else if key_match(key, self.key_config.keys.move_up)
{
self.move_selection(ScrollType::Up);
} else if key_match(
key,
self.key_config.keys.move_down,
) {
self.move_selection(ScrollType::Down);
} else if key_match(
key,
self.key_config.keys.shift_up,
) || key_match(
key,
self.key_config.keys.home,
) {
self.move_selection(ScrollType::Home);
} else if key_match(
key,
self.key_config.keys.shift_down,
) || key_match(
key,
self.key_config.keys.end,
) {
self.move_selection(ScrollType::End);
} else if key_match(
key,
self.key_config.keys.page_down,
) {
self.move_selection(ScrollType::PageDown);
} else if key_match(key, self.key_config.keys.page_up)
{
self.move_selection(ScrollType::PageUp);
} else if key_match(
key,
self.key_config.keys.move_right,
) && self.can_show_annotation()
{
self.show_annotation();
} else if key_match(
key,
self.key_config.keys.delete_tag,
) {
return self.selected_tag().map_or(
Ok(EventState::NotConsumed),
|tag| {
self.queue.push(
InternalEvent::ConfirmAction(
Action::DeleteTag(
tag.name.clone(),
),
),
);
Ok(EventState::Consumed)
},
);
} else if key_match(
key,
self.key_config.keys.select_tag,
) {
return self.selected_tag().map_or(
Ok(EventState::NotConsumed),
|tag| {
self.queue.push(
InternalEvent::SelectCommitInRevlog(
tag.commit_id,
),
);
Ok(EventState::Consumed)
},
);
} else if key_match(key, self.key_config.keys.push)
&& self.has_remotes
{
self.queue.push(InternalEvent::PushTags);
}
}
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
}
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
impl TagListPopup {
pub fn new(env: &Environment) -> Self {
Self {
theme: env.theme.clone(),
queue: env.queue.clone(),
tags: None,
visible: false,
has_remotes: false,
table_state: std::cell::Cell::new(TableState::default()),
current_height: std::cell::Cell::new(0),
basic_credential: None,
missing_remote_tags: None,
async_remote_tags: AsyncSingleJob::new(
env.sender_git.clone(),
),
key_config: env.key_config.clone(),
repo: env.repo.clone(),
}
}
///
pub fn open(&mut self) -> Result<()> {
self.table_state.get_mut().select(Some(0));
self.show()?;
self.has_remotes =
sync::get_branches_info(&self.repo.borrow(), false)
.map(|branches| !branches.is_empty())
.unwrap_or(false);
let basic_credential = if self.has_remotes {
if need_username_password(&self.repo.borrow())? {
let credential =
extract_username_password(&self.repo.borrow())?;
if credential.is_complete() {
Some(credential)
} else {
None
}
} else {
None
}
} else {
None
};
self.basic_credential = basic_credential;
self.update_tags()?;
self.update_missing_remote_tags();
Ok(())
}
///
pub fn update(&mut self, ev: AsyncNotification) {
if matches!(
ev,
AsyncNotification::Git(AsyncGitNotification::RemoteTags)
) {
if let Some(job) = self.async_remote_tags.take_last() {
if let Some(Ok(missing_remote_tags)) = job.result() {
self.missing_remote_tags =
Some(missing_remote_tags);
}
}
} else if matches!(
ev,
AsyncNotification::Git(AsyncGitNotification::PushTags)
) {
self.update_missing_remote_tags();
}
}
///
pub fn any_work_pending(&self) -> bool {
self.async_remote_tags.is_pending()
}
/// fetch list of tags
pub fn update_tags(&mut self) -> Result<()> {
let tags = get_tags_with_metadata(&self.repo.borrow())?;
self.tags = Some(tags);
Ok(())
}
pub fn update_missing_remote_tags(&self) {
if self.has_remotes {
self.async_remote_tags.spawn(AsyncRemoteTagsJob::new(
self.repo.borrow().clone(),
self.basic_credential.clone(),
));
}
}
///
fn move_selection(&self, scroll_type: ScrollType) -> bool {
let mut table_state = self.table_state.take();
let old_selection = table_state.selected().unwrap_or(0);
let max_selection =
self.tags.as_ref().map_or(0, |tags| tags.len() - 1);
let new_selection = match scroll_type {
ScrollType::Up => old_selection.saturating_sub(1),
ScrollType::Down => {
old_selection.saturating_add(1).min(max_selection)
}
ScrollType::Home => 0,
ScrollType::End => max_selection,
ScrollType::PageUp => old_selection.saturating_sub(
self.current_height.get().saturating_sub(1),
),
ScrollType::PageDown => old_selection
.saturating_add(
self.current_height.get().saturating_sub(1),
)
.min(max_selection),
};
let needs_update = new_selection != old_selection;
table_state.select(Some(new_selection));
self.table_state.set(table_state);
needs_update
}
fn show_annotation(&self) {
if let Some(tag) = self.selected_tag() {
if let Some(annotation) = &tag.annotation {
self.queue.push(InternalEvent::ShowInfoMsg(
annotation.clone(),
));
}
}
}
fn can_show_annotation(&self) -> bool {
self.selected_tag()
.and_then(|t| t.annotation.as_ref())
.is_some()
}
///
fn get_rows(&self) -> Vec<Row<'_>> {
self.tags.as_ref().map_or_else(Vec::new, |tags| {
tags.iter().map(|tag| self.get_row(tag)).collect()
})
}
///
fn get_row(&self, tag: &TagWithMetadata) -> Row<'_> {
const UPSTREAM_SYMBOL: &str = "\u{2191}";
const ATTACHMENT_SYMBOL: &str = "@";
const EMPTY_SYMBOL: &str = " ";
let is_tag_missing_on_remote = self
.missing_remote_tags
.as_ref()
.is_some_and(|missing_remote_tags| {
let remote_tag = format!("refs/tags/{}", tag.name);
missing_remote_tags.contains(&remote_tag)
});
let has_remote_str = if is_tag_missing_on_remote {
UPSTREAM_SYMBOL
} else {
EMPTY_SYMBOL
};
let has_attachment_str = if tag.annotation.is_some() {
ATTACHMENT_SYMBOL
} else {
EMPTY_SYMBOL
};
let cells: Vec<Cell> = vec![
Cell::from(has_remote_str)
.style(self.theme.commit_author(false)),
Cell::from(tag.name.clone())
.style(self.theme.text(true, false)),
Cell::from(time_to_string(tag.time, true))
.style(self.theme.commit_time(false)),
Cell::from(tag.author.clone())
.style(self.theme.commit_author(false)),
Cell::from(has_attachment_str)
.style(self.theme.text_danger()),
Cell::from(tag.message.clone())
.style(self.theme.text(true, false)),
];
Row::new(cells)
}
fn valid_selection(&self) -> bool {
self.selected_tag().is_some()
}
fn selected_tag(&self) -> Option<&TagWithMetadata> {
self.tags.as_ref().and_then(|tags| {
let table_state = self.table_state.take();
let tag = table_state
.selected()
.and_then(|selected| tags.get(selected));
self.table_state.set(table_state);
tag
})
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/create_remote.rs | src/popups/create_remote.rs | use anyhow::Result;
use asyncgit::sync::{self, validate_remote_name, RepoPathRef};
use crossterm::event::Event;
use easy_cast::Cast;
use ratatui::{widgets::Paragraph, Frame};
use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, InputType, TextInputComponent,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, NeedsUpdate, Queue},
strings,
ui::style::SharedTheme,
};
#[derive(Default)]
enum State {
// first we ask for a name for a new remote
#[default]
Name,
// second we ask for a url and carry with us the name previously entered
Url {
name: String,
},
}
pub struct CreateRemotePopup {
repo: RepoPathRef,
input: TextInputComponent,
queue: Queue,
key_config: SharedKeyConfig,
state: State,
theme: SharedTheme,
}
impl DrawableComponent for CreateRemotePopup {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::prelude::Rect,
) -> anyhow::Result<()> {
if self.is_visible() {
self.input.draw(f, rect)?;
self.draw_warnings(f);
}
Ok(())
}
}
impl Component for CreateRemotePopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
self.input.commands(out, force_all);
out.push(CommandInfo::new(
strings::commands::remote_confirm_name_msg(
&self.key_config,
),
true,
true,
));
}
visibility_blocking(self)
}
fn event(
&mut self,
ev: &crossterm::event::Event,
) -> Result<EventState> {
if self.is_visible() {
if self.input.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.enter) {
self.handle_submit();
}
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.input.is_visible()
}
fn hide(&mut self) {
self.input.hide();
}
fn show(&mut self) -> Result<()> {
self.input.clear();
self.input.set_title(
strings::create_remote_popup_title_name(&self.key_config),
);
self.input.set_default_msg(
strings::create_remote_popup_msg_name(&self.key_config),
);
self.input.show()?;
Ok(())
}
}
impl CreateRemotePopup {
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
queue: env.queue.clone(),
input: TextInputComponent::new(env, "", "", true)
.with_input_type(InputType::Singleline),
key_config: env.key_config.clone(),
state: State::Name,
theme: env.theme.clone(),
}
}
pub fn open(&mut self) -> Result<()> {
self.state = State::Name;
self.input.clear();
self.show()?;
Ok(())
}
fn draw_warnings(&self, f: &mut Frame) {
let remote_name = match self.state {
State::Name => self.input.get_text(),
State::Url { .. } => return,
};
if !remote_name.is_empty() {
let valid = validate_remote_name(remote_name);
if !valid {
let msg = strings::remote_name_invalid();
let msg_length: u16 = msg.len().cast();
let w = Paragraph::new(msg)
.style(self.theme.text_danger());
let rect = {
let mut rect = self.input.get_area();
rect.y += rect.height.saturating_sub(1);
rect.height = 1;
let offset =
rect.width.saturating_sub(msg_length + 1);
rect.width =
rect.width.saturating_sub(offset + 1);
rect.x += offset;
rect
};
f.render_widget(w, rect);
}
}
}
fn handle_submit(&mut self) {
match &self.state {
State::Name => {
self.state = State::Url {
name: self.input.get_text().to_string(),
};
self.input.clear();
self.input.set_title(
strings::create_remote_popup_title_url(
&self.key_config,
),
);
self.input.set_default_msg(
strings::create_remote_popup_msg_url(
&self.key_config,
),
);
}
State::Url { name } => {
let res = sync::add_remote(
&self.repo.borrow(),
name,
self.input.get_text(),
);
match res {
Ok(()) => {
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL | NeedsUpdate::REMOTES,
));
}
Err(e) => {
log::error!("create remote: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(
format!("create remote error:\n{e}",),
));
}
}
self.hide();
}
}
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/fuzzy_find.rs | src/popups/fuzzy_find.rs | use crate::components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, FuzzyFinderTarget, InputType,
ScrollType, TextInputComponent,
};
use crate::{
app::Environment,
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, Queue},
string_utils::trim_length_left,
strings,
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use crossterm::event::Event;
use fuzzy_matcher::FuzzyMatcher;
use ratatui::{
layout::{Constraint, Direction, Layout, Margin, Rect},
text::{Line, Span},
widgets::{Block, Borders, Clear},
Frame,
};
use std::borrow::Cow;
use unicode_segmentation::UnicodeSegmentation;
pub struct FuzzyFindPopup {
queue: Queue,
visible: bool,
find_text: TextInputComponent,
query: Option<String>,
theme: SharedTheme,
contents: Vec<String>,
selection: usize,
selected_index: Option<usize>,
filtered: Vec<(usize, Vec<usize>)>,
key_config: SharedKeyConfig,
target: Option<FuzzyFinderTarget>,
}
impl FuzzyFindPopup {
///
pub fn new(env: &Environment) -> Self {
let mut find_text =
TextInputComponent::new(env, "", "start typing..", false)
.with_input_type(InputType::Singleline);
find_text.embed();
Self {
queue: env.queue.clone(),
visible: false,
query: None,
find_text,
theme: env.theme.clone(),
contents: Vec::new(),
filtered: Vec::new(),
selected_index: None,
key_config: env.key_config.clone(),
selection: 0,
target: None,
}
}
fn update_query(&mut self) {
if self.find_text.get_text().is_empty() {
self.set_query(None);
} else if self
.query
.as_ref()
.is_none_or(|q| q != self.find_text.get_text())
{
self.set_query(Some(
self.find_text.get_text().to_string(),
));
}
}
fn set_query(&mut self, query: Option<String>) {
self.query = query;
self.filtered.clear();
if let Some(q) = &self.query {
let matcher =
fuzzy_matcher::skim::SkimMatcherV2::default();
let mut contents = self
.contents
.iter()
.enumerate()
.filter_map(|a| {
matcher
.fuzzy_indices(a.1, q)
.map(|(score, indices)| (score, a.0, indices))
})
.collect::<Vec<(_, _, _)>>();
contents.sort_by(|(score1, _, _), (score2, _, _)| {
score2.cmp(score1)
});
self.filtered.extend(
contents.into_iter().map(|entry| (entry.1, entry.2)),
);
}
self.selection = 0;
self.refresh_selection();
}
fn refresh_selection(&mut self) {
let selection =
self.filtered.get(self.selection).map(|a| a.0);
if self.selected_index != selection {
self.selected_index = selection;
if let Some(idx) = self.selected_index {
if let Some(target) = self.target {
self.queue.push(
InternalEvent::FuzzyFinderChanged(
idx,
self.contents[idx].clone(),
target,
),
);
}
}
}
}
pub fn open(
&mut self,
contents: Vec<String>,
target: FuzzyFinderTarget,
) -> Result<()> {
self.show()?;
self.find_text.show()?;
self.find_text.set_text(String::new());
self.query = None;
self.target = Some(target);
if self.contents != contents {
self.contents = contents;
}
self.update_query();
Ok(())
}
fn move_selection(&mut self, move_type: ScrollType) -> bool {
let new_selection = match move_type {
ScrollType::Up => self.selection.saturating_sub(1),
ScrollType::Down => self.selection.saturating_add(1),
_ => self.selection,
};
let new_selection = new_selection
.clamp(0, self.filtered.len().saturating_sub(1));
if new_selection != self.selection {
self.selection = new_selection;
self.refresh_selection();
return true;
}
false
}
#[inline]
fn draw_matches_list(&self, f: &mut Frame, mut area: Rect) {
{
// Block has two lines up and down which need to be considered
const HEIGHT_BLOCK_MARGIN: usize = 2;
let title = format!("Hits: {}", self.filtered.len());
let height = usize::from(area.height);
let width = usize::from(area.width);
let list_height =
height.saturating_sub(HEIGHT_BLOCK_MARGIN);
let scroll_skip =
self.selection.saturating_sub(list_height);
let items = self
.filtered
.iter()
.skip(scroll_skip)
.take(height)
.map(|(idx, indices)| {
let selected = self
.selected_index
.is_some_and(|index| index == *idx);
let full_text =
trim_length_left(&self.contents[*idx], width);
let trim_length =
self.contents[*idx].graphemes(true).count()
- full_text.graphemes(true).count();
Line::from(
full_text
.graphemes(true)
.enumerate()
.map(|(c_idx, c)| {
Span::styled(
Cow::from(c.to_string()),
self.theme.text(
selected,
indices.contains(
&(c_idx + trim_length),
),
),
)
})
.collect::<Vec<_>>(),
)
});
ui::draw_list_block(
f,
area,
Block::default()
.title(Span::styled(
title,
self.theme.title(true),
))
.borders(Borders::TOP),
items,
);
// Draw scrollbar when needed
if self.filtered.len() > list_height {
// Reset list area margin
area.width += 1;
area.height += 1;
ui::draw_scrollbar(
f,
area,
&self.theme,
self.filtered.len().saturating_sub(1),
self.selection,
ui::Orientation::Vertical,
);
}
}
}
}
impl DrawableComponent for FuzzyFindPopup {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
if self.is_visible() {
const MAX_SIZE: (u16, u16) = (50, 20);
let any_hits = !self.filtered.is_empty();
let area = ui::centered_rect_absolute(
MAX_SIZE.0, MAX_SIZE.1, area,
);
let area = if any_hits {
area
} else {
Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(3),
Constraint::Percentage(100),
]
.as_ref(),
)
.split(area)[0]
};
f.render_widget(Clear, area);
f.render_widget(
Block::default()
.borders(Borders::all())
.style(self.theme.title(true))
.title(Span::styled(
strings::POPUP_TITLE_FUZZY_FIND,
self.theme.title(true),
)),
area,
);
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(1),
Constraint::Percentage(100),
]
.as_ref(),
)
.split(area.inner(Margin {
horizontal: 1,
vertical: 1,
}));
self.find_text.draw(f, chunks[0])?;
if any_hits {
self.draw_matches_list(f, chunks[1]);
}
}
Ok(())
}
}
impl Component for FuzzyFindPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
out.push(CommandInfo::new(
strings::commands::scroll_popup(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::close_fuzzy_finder(
&self.key_config,
),
true,
true,
));
}
visibility_blocking(self)
}
fn event(
&mut self,
event: &crossterm::event::Event,
) -> Result<EventState> {
if self.is_visible() {
if let Event::Key(key) = event {
if key_match(key, self.key_config.keys.exit_popup)
|| key_match(key, self.key_config.keys.enter)
{
self.hide();
} else if key_match(
key,
self.key_config.keys.popup_down,
) {
self.move_selection(ScrollType::Down);
} else if key_match(
key,
self.key_config.keys.popup_up,
) {
self.move_selection(ScrollType::Up);
}
}
if self.find_text.event(event)?.is_consumed() {
self.update_query();
}
return Ok(EventState::Consumed);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/push.rs | src/popups/push.rs | use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
CredComponent, DrawableComponent, EventState,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, Queue},
strings,
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use asyncgit::{
sync::{
cred::{
extract_username_password_for_push,
need_username_password_for_push, BasicAuthCredential,
},
get_branch_remote, hooks_pre_push,
remotes::get_default_remote_for_push,
HookResult, RepoPathRef,
},
AsyncGitNotification, AsyncPush, PushRequest, PushType,
RemoteProgress, RemoteProgressState,
};
use crossterm::event::Event;
use ratatui::{
layout::Rect,
text::Span,
widgets::{Block, BorderType, Borders, Clear, Gauge},
Frame,
};
///
#[derive(PartialEq, Eq)]
enum PushComponentModifier {
None,
Force,
Delete,
ForceDelete,
}
impl PushComponentModifier {
pub(crate) fn force(&self) -> bool {
self == &Self::Force || self == &Self::ForceDelete
}
pub(crate) fn delete(&self) -> bool {
self == &Self::Delete || self == &Self::ForceDelete
}
}
///
pub struct PushPopup {
repo: RepoPathRef,
modifier: PushComponentModifier,
visible: bool,
git_push: AsyncPush,
progress: Option<RemoteProgress>,
pending: bool,
branch: String,
push_type: PushType,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
input_cred: CredComponent,
}
impl PushPopup {
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
queue: env.queue.clone(),
modifier: PushComponentModifier::None,
pending: false,
visible: false,
branch: String::new(),
push_type: PushType::Branch,
git_push: AsyncPush::new(
env.repo.borrow().clone(),
&env.sender_git,
),
progress: None,
input_cred: CredComponent::new(env),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
}
}
///
pub fn push(
&mut self,
branch: String,
push_type: PushType,
force: bool,
delete: bool,
) -> Result<()> {
self.branch = branch;
self.push_type = push_type;
self.modifier = match (force, delete) {
(true, true) => PushComponentModifier::ForceDelete,
(false, true) => PushComponentModifier::Delete,
(true, false) => PushComponentModifier::Force,
(false, false) => PushComponentModifier::None,
};
self.show()?;
if need_username_password_for_push(&self.repo.borrow())? {
let cred = extract_username_password_for_push(
&self.repo.borrow(),
)
.unwrap_or_else(|_| BasicAuthCredential::new(None, None));
if cred.is_complete() {
self.push_to_remote(Some(cred), force)
} else {
self.input_cred.set_cred(cred);
self.input_cred.show()
}
} else {
self.push_to_remote(None, force)
}
}
fn push_to_remote(
&mut self,
cred: Option<BasicAuthCredential>,
force: bool,
) -> Result<()> {
let remote = if let Ok(Some(remote)) =
get_branch_remote(&self.repo.borrow(), &self.branch)
{
log::info!("push: branch '{}' has upstream for remote '{}' - using that",self.branch,remote);
remote
} else {
log::info!("push: branch '{}' has no upstream - looking up default remote",self.branch);
let remote =
get_default_remote_for_push(&self.repo.borrow())?;
log::info!(
"push: branch '{}' to remote '{}'",
self.branch,
remote
);
remote
};
// run pre push hook - can reject push
if let HookResult::NotOk(e) =
hooks_pre_push(&self.repo.borrow())?
{
log::error!("pre-push hook failed: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(format!(
"pre-push hook failed:\n{e}"
)));
self.pending = false;
self.visible = false;
return Ok(());
}
self.pending = true;
self.progress = None;
self.git_push.request(PushRequest {
remote,
branch: self.branch.clone(),
push_type: self.push_type,
force,
delete: self.modifier.delete(),
basic_credential: cred,
})?;
Ok(())
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if self.is_visible() && ev == AsyncGitNotification::Push {
self.update()?;
}
Ok(())
}
///
fn update(&mut self) -> Result<()> {
self.pending = self.git_push.is_pending()?;
self.progress = self.git_push.progress()?;
if !self.pending {
if let Some(err) = self.git_push.last_result()? {
self.queue.push(InternalEvent::ShowErrorMsg(
format!("push failed:\n{err}"),
));
}
self.hide();
}
Ok(())
}
///
pub const fn any_work_pending(&self) -> bool {
self.pending
}
///
pub fn get_progress(
progress: Option<&RemoteProgress>,
) -> (String, u8) {
progress.as_ref().map_or_else(
|| (strings::PUSH_POPUP_PROGRESS_NONE.into(), 0),
|progress| {
(
Self::progress_state_name(&progress.state),
progress.get_progress_percent(),
)
},
)
}
fn progress_state_name(state: &RemoteProgressState) -> String {
match state {
RemoteProgressState::PackingAddingObject => {
strings::PUSH_POPUP_STATES_ADDING
}
RemoteProgressState::PackingDeltafiction => {
strings::PUSH_POPUP_STATES_DELTAS
}
RemoteProgressState::Pushing => {
strings::PUSH_POPUP_STATES_PUSHING
}
RemoteProgressState::Transfer => {
strings::PUSH_POPUP_STATES_TRANSFER
}
RemoteProgressState::Done => {
strings::PUSH_POPUP_STATES_DONE
}
}
.into()
}
}
impl DrawableComponent for PushPopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.visible {
let (state, progress) =
Self::get_progress(self.progress.as_ref());
let area = ui::centered_rect_absolute(30, 3, f.area());
f.render_widget(Clear, area);
f.render_widget(
Gauge::default()
.label(state.as_str())
.block(
Block::default()
.title(Span::styled(
if self.modifier.force() {
strings::FORCE_PUSH_POPUP_MSG
} else {
strings::PUSH_POPUP_MSG
},
self.theme.title(true),
))
.borders(Borders::ALL)
.border_type(BorderType::Thick)
.border_style(self.theme.block(true)),
)
.gauge_style(self.theme.push_gauge())
.percent(u16::from(progress)),
area,
);
self.input_cred.draw(f, rect)?;
}
Ok(())
}
}
impl Component for PushPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
if !force_all {
out.clear();
}
if self.input_cred.is_visible() {
return self.input_cred.commands(out, force_all);
}
out.push(CommandInfo::new(
strings::commands::close_msg(&self.key_config),
!self.pending,
self.visible,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.visible {
if let Event::Key(e) = ev {
if self.input_cred.is_visible() {
self.input_cred.event(ev)?;
if self.input_cred.get_cred().is_complete()
|| !self.input_cred.is_visible()
{
self.push_to_remote(
Some(self.input_cred.get_cred().clone()),
self.modifier.force(),
)?;
self.input_cred.hide();
}
} else if key_match(
e,
self.key_config.keys.exit_popup,
) && !self.pending
{
self.hide();
}
}
return Ok(EventState::Consumed);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/update_remote_url.rs | src/popups/update_remote_url.rs | use anyhow::Result;
use asyncgit::sync::{self, RepoPathRef};
use crossterm::event::Event;
use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, InputType, TextInputComponent,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, NeedsUpdate, Queue},
strings,
};
pub struct UpdateRemoteUrlPopup {
repo: RepoPathRef,
input: TextInputComponent,
key_config: SharedKeyConfig,
queue: Queue,
remote_name: Option<String>,
initial_url: Option<String>,
}
impl DrawableComponent for UpdateRemoteUrlPopup {
fn draw(
&self,
f: &mut ratatui::Frame,
rect: ratatui::prelude::Rect,
) -> anyhow::Result<()> {
if self.is_visible() {
self.input.draw(f, rect)?;
}
Ok(())
}
}
impl Component for UpdateRemoteUrlPopup {
fn commands(
&self,
out: &mut Vec<crate::components::CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
self.input.commands(out, force_all);
out.push(CommandInfo::new(
strings::commands::remote_confirm_url_msg(
&self.key_config,
),
true,
true,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.is_visible() {
if self.input.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.enter) {
self.update_remote_url();
}
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.input.is_visible()
}
fn hide(&mut self) {
self.input.hide();
}
fn show(&mut self) -> Result<()> {
self.input.show()?;
Ok(())
}
}
impl UpdateRemoteUrlPopup {
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
input: TextInputComponent::new(
env,
&strings::update_remote_url_popup_title(
&env.key_config,
),
&strings::update_remote_url_popup_msg(
&env.key_config,
),
true,
)
.with_input_type(InputType::Singleline),
key_config: env.key_config.clone(),
queue: env.queue.clone(),
initial_url: None,
remote_name: None,
}
}
///
pub fn open(
&mut self,
remote_name: String,
cur_url: String,
) -> Result<()> {
self.input.set_text(cur_url.clone());
self.remote_name = Some(remote_name);
self.initial_url = Some(cur_url);
self.show()?;
Ok(())
}
///
pub fn update_remote_url(&mut self) {
if let Some(remote_name) = &self.remote_name {
let res = sync::update_remote_url(
&self.repo.borrow(),
remote_name,
self.input.get_text(),
);
match res {
Ok(()) => {
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL | NeedsUpdate::REMOTES,
));
}
Err(e) => {
log::error!("update remote url: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(
format!("update remote url error:\n{e}",),
));
}
}
}
self.input.clear();
self.initial_url = None;
self.hide();
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/rename_remote.rs | src/popups/rename_remote.rs | use anyhow::Result;
use asyncgit::sync::{self, RepoPathRef};
use crossterm::event::Event;
use easy_cast::Cast;
use ratatui::{layout::Rect, widgets::Paragraph, Frame};
use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState, InputType, TextInputComponent,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, NeedsUpdate, Queue},
strings,
ui::style::SharedTheme,
};
pub struct RenameRemotePopup {
repo: RepoPathRef,
input: TextInputComponent,
theme: SharedTheme,
key_config: SharedKeyConfig,
queue: Queue,
initial_name: Option<String>,
}
impl DrawableComponent for RenameRemotePopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.is_visible() {
self.input.draw(f, rect)?;
self.draw_warnings(f);
}
Ok(())
}
}
impl Component for RenameRemotePopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
self.input.commands(out, force_all);
out.push(CommandInfo::new(
strings::commands::remote_confirm_name_msg(
&self.key_config,
),
true,
true,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.is_visible() {
if self.input.event(ev)?.is_consumed() {
return Ok(EventState::Consumed);
}
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.enter) {
self.rename_remote();
}
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.input.is_visible()
}
fn hide(&mut self) {
self.input.hide();
}
fn show(&mut self) -> Result<()> {
self.input.show()?;
Ok(())
}
}
impl RenameRemotePopup {
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
input: TextInputComponent::new(
env,
&strings::rename_remote_popup_title(&env.key_config),
&strings::rename_remote_popup_msg(&env.key_config),
true,
)
.with_input_type(InputType::Singleline),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
queue: env.queue.clone(),
initial_name: None,
}
}
///
pub fn open(&mut self, cur_name: String) -> Result<()> {
self.input.set_text(cur_name.clone());
self.initial_name = Some(cur_name);
self.show()?;
Ok(())
}
fn draw_warnings(&self, f: &mut Frame) {
let current_text = self.input.get_text();
if !current_text.is_empty() {
let valid = sync::validate_remote_name(current_text);
if !valid {
let msg = strings::branch_name_invalid();
let msg_length: u16 = msg.len().cast();
let w = Paragraph::new(msg)
.style(self.theme.text_danger());
let rect = {
let mut rect = self.input.get_area();
rect.y += rect.height.saturating_sub(1);
rect.height = 1;
let offset =
rect.width.saturating_sub(msg_length + 1);
rect.width =
rect.width.saturating_sub(offset + 1);
rect.x += offset;
rect
};
f.render_widget(w, rect);
}
}
}
///
pub fn rename_remote(&mut self) {
if let Some(init_name) = &self.initial_name {
if init_name != self.input.get_text() {
let res = sync::rename_remote(
&self.repo.borrow(),
init_name,
self.input.get_text(),
);
match res {
Ok(()) => {
self.queue.push(InternalEvent::Update(
NeedsUpdate::ALL | NeedsUpdate::REMOTES,
));
}
Err(e) => {
log::error!("rename remote: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(
format!("rename remote error:\n{e}",),
));
}
}
}
}
self.input.clear();
self.initial_name = None;
self.hide();
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/externaleditor.rs | src/popups/externaleditor.rs | use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState,
},
keys::SharedKeyConfig,
strings,
ui::{self, style::SharedTheme},
};
use anyhow::{anyhow, bail, Result};
use asyncgit::sync::{
get_config_string, utils::repo_work_dir, RepoPath,
};
use crossterm::{
event::Event,
terminal::{EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use ratatui::{
layout::Rect,
text::{Line, Span},
widgets::{Block, BorderType, Borders, Clear, Paragraph},
Frame,
};
use scopeguard::defer;
use std::ffi::OsStr;
use std::{env, io, path::Path, process::Command};
///
pub struct ExternalEditorPopup {
visible: bool,
theme: SharedTheme,
key_config: SharedKeyConfig,
}
impl ExternalEditorPopup {
///
pub fn new(env: &Environment) -> Self {
Self {
visible: false,
theme: env.theme.clone(),
key_config: env.key_config.clone(),
}
}
/// opens file at given `path` in an available editor
pub fn open_file_in_editor(
repo: &RepoPath,
path: &Path,
) -> Result<()> {
let work_dir = repo_work_dir(repo)?;
let path = if path.is_relative() {
Path::new(&work_dir).join(path)
} else {
path.into()
};
if !path.exists() {
bail!("file not found: {path:?}");
}
io::stdout().execute(LeaveAlternateScreen)?;
defer! {
io::stdout().execute(EnterAlternateScreen).expect("reset terminal");
}
let environment_options = ["GIT_EDITOR", "VISUAL", "EDITOR"];
let editor = env::var(environment_options[0])
.ok()
.or_else(|| {
get_config_string(repo, "core.editor").ok()?
})
.or_else(|| env::var(environment_options[1]).ok())
.or_else(|| env::var(environment_options[2]).ok())
.unwrap_or_else(|| String::from("vi"));
// TODO: proper handling arguments containing whitespaces
// This does not do the right thing if the input is `editor --something "with spaces"`
// deal with "editor name with spaces" p1 p2 p3
// and with "editor_no_spaces" p1 p2 p3
// does not address spaces in pn
let mut echars = editor.chars().peekable();
let first_char = *echars.peek().ok_or_else(|| {
anyhow!(
"editor env variable found empty: {}",
environment_options.join(" or ")
)
})?;
let command: String = if first_char == '\"' {
echars
.by_ref()
.skip(1)
.take_while(|c| *c != '\"')
.collect()
} else {
echars.by_ref().take_while(|c| *c != ' ').collect()
};
let remainder_str = echars.collect::<String>();
let remainder = remainder_str.split_whitespace();
let mut args: Vec<&OsStr> =
remainder.map(OsStr::new).collect();
args.push(path.as_os_str());
Command::new(command.clone())
.current_dir(work_dir)
.args(args)
.status()
.map_err(|e| anyhow!("\"{command}\": {e}"))?;
Ok(())
}
}
impl DrawableComponent for ExternalEditorPopup {
fn draw(&self, f: &mut Frame, _rect: Rect) -> Result<()> {
if self.visible {
let txt = Line::from(
strings::msg_opening_editor(&self.key_config)
.split('\n')
.map(|string| {
Span::raw::<String>(string.to_string())
})
.collect::<Vec<Span>>(),
);
let area = ui::centered_rect_absolute(25, 3, f.area());
f.render_widget(Clear, area);
f.render_widget(
Paragraph::new(txt)
.block(
Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Thick)
.border_style(self.theme.block(true)),
)
.style(self.theme.block(true)),
area,
);
}
Ok(())
}
}
impl Component for ExternalEditorPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.visible && !force_all {
out.clear();
}
visibility_blocking(self)
}
fn event(&mut self, _ev: &Event) -> Result<EventState> {
if self.visible {
return Ok(EventState::Consumed);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/help.rs | src/popups/help.rs | use crate::components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
DrawableComponent, EventState,
};
use crate::{
app::Environment,
keys::{key_match, SharedKeyConfig},
strings, ui,
};
use anyhow::Result;
use asyncgit::hash;
use crossterm::event::Event;
use itertools::Itertools;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, BorderType, Borders, Clear, Paragraph},
Frame,
};
use std::{borrow::Cow, cmp};
use ui::style::SharedTheme;
///
pub struct HelpPopup {
cmds: Vec<CommandInfo>,
visible: bool,
selection: u16,
theme: SharedTheme,
key_config: SharedKeyConfig,
}
impl DrawableComponent for HelpPopup {
fn draw(&self, f: &mut Frame, _rect: Rect) -> Result<()> {
if self.visible {
const SIZE: (u16, u16) = (65, 24);
let scroll_threshold = SIZE.1 / 3;
let scroll =
self.selection.saturating_sub(scroll_threshold);
let area =
ui::centered_rect_absolute(SIZE.0, SIZE.1, f.area());
f.render_widget(Clear, area);
f.render_widget(
Block::default()
.title(strings::help_title(&self.key_config))
.borders(Borders::ALL)
.border_type(BorderType::Thick),
area,
);
let chunks = Layout::default()
.vertical_margin(1)
.horizontal_margin(1)
.direction(Direction::Vertical)
.constraints(
[Constraint::Min(1), Constraint::Length(1)]
.as_ref(),
)
.split(area);
f.render_widget(
Paragraph::new(self.get_text())
.scroll((scroll, 0))
.alignment(Alignment::Left),
chunks[0],
);
ui::draw_scrollbar(
f,
area,
&self.theme,
self.cmds.len(),
self.selection as usize,
ui::Orientation::Vertical,
);
f.render_widget(
Paragraph::new(Line::from(vec![Span::styled(
Cow::from(format!(
"gitui {}",
env!("GITUI_BUILD_NAME"),
)),
Style::default(),
)]))
.alignment(Alignment::Right),
chunks[1],
);
}
Ok(())
}
}
impl Component for HelpPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
// only if help is open we have no other commands available
if self.visible && !force_all {
out.clear();
}
if self.visible {
out.push(CommandInfo::new(
strings::commands::scroll(&self.key_config),
true,
true,
));
out.push(CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
true,
));
}
if !self.visible || force_all {
out.push(
CommandInfo::new(
strings::commands::help_open(&self.key_config),
true,
true,
)
.order(99),
);
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.visible {
if let Event::Key(e) = ev {
if key_match(e, self.key_config.keys.exit_popup) {
self.hide();
} else if key_match(e, self.key_config.keys.move_down)
{
self.move_selection(true);
} else if key_match(e, self.key_config.keys.move_up) {
self.move_selection(false);
}
}
Ok(EventState::Consumed)
} else if let Event::Key(k) = ev {
if key_match(k, self.key_config.keys.open_help) {
self.show()?;
Ok(EventState::Consumed)
} else {
Ok(EventState::NotConsumed)
}
} else {
Ok(EventState::NotConsumed)
}
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
impl HelpPopup {
pub fn new(env: &Environment) -> Self {
Self {
cmds: vec![],
visible: false,
selection: 0,
theme: env.theme.clone(),
key_config: env.key_config.clone(),
}
}
///
pub fn set_cmds(&mut self, cmds: Vec<CommandInfo>) {
self.cmds = cmds
.into_iter()
.filter(|e| !e.text.hide_help)
.collect::<Vec<_>>();
self.cmds.sort_by_key(|e| e.text.clone());
self.cmds.dedup_by_key(|e| e.text.clone());
self.cmds.sort_by_key(|e| hash(&e.text.group));
}
fn move_selection(&mut self, inc: bool) {
let mut new_selection = self.selection;
new_selection = if inc {
new_selection.saturating_add(1)
} else {
new_selection.saturating_sub(1)
};
new_selection = cmp::max(new_selection, 0);
if let Ok(max) =
u16::try_from(self.cmds.len().saturating_sub(1))
{
self.selection = cmp::min(new_selection, max);
}
}
fn get_text(&self) -> Vec<Line<'_>> {
let mut txt: Vec<Line> = Vec::new();
let mut processed = 0_u16;
for (key, group) in
&self.cmds.iter().chunk_by(|e| e.text.group)
{
txt.push(Line::from(Span::styled(
Cow::from(key.to_string()),
Style::default().add_modifier(Modifier::REVERSED),
)));
for command_info in group {
let is_selected = self.selection == processed;
processed += 1;
txt.push(Line::from(Span::styled(
Cow::from(if is_selected {
format!(">{}", command_info.text.name)
} else {
format!(" {}", command_info.text.name)
}),
self.theme.text(true, is_selected),
)));
if is_selected {
txt.push(Line::from(Span::styled(
Cow::from(format!(
" {}\n",
command_info.text.desc
)),
self.theme.text(true, is_selected),
)));
}
}
}
txt
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/blame_file.rs | src/popups/blame_file.rs | use crate::{
app::Environment,
components::{
string_width_align, time_to_string, visibility_blocking,
CommandBlocking, CommandInfo, Component, DrawableComponent,
EventState, ScrollType,
},
keys::{key_match, SharedKeyConfig},
popups::{FileRevOpen, InspectCommitOpen},
queue::{InternalEvent, Queue, StackablePopupOpen},
string_utils::tabs_to_spaces,
strings,
ui::{self, style::SharedTheme, AsyncSyntaxJob, SyntaxText},
AsyncAppNotification, AsyncNotification, SyntaxHighlightProgress,
};
use anyhow::Result;
use asyncgit::{
asyncjob::AsyncSingleJob,
sync::{BlameHunk, CommitId, FileBlame, RepoPathRef},
AsyncBlame, AsyncGitNotification, BlameParams,
};
use crossbeam_channel::Sender;
use crossterm::event::Event;
use ratatui::{
layout::{Constraint, Rect},
symbols::line::VERTICAL,
text::{Span, Text},
widgets::{Block, Borders, Cell, Clear, Row, Table, TableState},
Frame,
};
use std::path::Path;
static NO_COMMIT_ID: &str = "0000000";
static NO_AUTHOR: &str = "<no author>";
static MIN_AUTHOR_WIDTH: usize = 3;
static MAX_AUTHOR_WIDTH: usize = 20;
struct SyntaxFileBlame {
pub file_blame: FileBlame,
pub styled_text: Option<SyntaxText>,
}
impl SyntaxFileBlame {
fn path(&self) -> &str {
&self.file_blame.path
}
const fn commit_id(&self) -> &CommitId {
&self.file_blame.commit_id
}
const fn lines(&self) -> &Vec<(Option<BlameHunk>, String)> {
&self.file_blame.lines
}
}
enum BlameProcess {
GettingBlame(AsyncBlame),
SyntaxHighlighting {
unstyled_file_blame: SyntaxFileBlame,
job: AsyncSingleJob<AsyncSyntaxJob>,
},
Result(SyntaxFileBlame),
}
impl BlameProcess {
const fn result(&self) -> Option<&SyntaxFileBlame> {
match self {
Self::GettingBlame(_) => None,
Self::SyntaxHighlighting {
unstyled_file_blame,
..
} => Some(unstyled_file_blame),
Self::Result(ref file_blame) => Some(file_blame),
}
}
}
#[derive(Clone, Debug)]
pub struct BlameFileOpen {
pub file_path: String,
pub commit_id: Option<CommitId>,
pub selection: Option<usize>,
}
pub struct BlameFilePopup {
title: String,
theme: SharedTheme,
queue: Queue,
visible: bool,
open_request: Option<BlameFileOpen>,
params: Option<BlameParams>,
table_state: std::cell::Cell<TableState>,
key_config: SharedKeyConfig,
current_height: std::cell::Cell<usize>,
blame: Option<BlameProcess>,
app_sender: Sender<AsyncAppNotification>,
git_sender: Sender<AsyncGitNotification>,
repo: RepoPathRef,
}
impl DrawableComponent for BlameFilePopup {
fn draw(&self, f: &mut Frame, area: Rect) -> Result<()> {
if self.is_visible() {
let title = self.get_title();
let rows = self.get_rows(area.width.into());
let author_width = get_author_width(area.width.into());
let constraints = [
// commit id
Constraint::Length(7),
// commit date
Constraint::Length(10),
// commit author
Constraint::Length(author_width.try_into()?),
// line number and vertical bar
Constraint::Length(
(self.get_line_number_width().saturating_add(1))
.try_into()?,
),
// the source code line
Constraint::Percentage(100),
];
let number_of_rows: usize = rows.len();
let syntax_highlight_progress = match self.blame {
Some(BlameProcess::SyntaxHighlighting {
ref job,
..
}) => job
.progress()
.map(|p| format!(" ({}%)", p.progress))
.unwrap_or_default(),
_ => String::new(),
};
let title_with_highlight_progress =
format!("{title}{syntax_highlight_progress}");
let table = Table::new(rows, constraints)
.column_spacing(1)
.row_highlight_style(self.theme.text(true, true))
.block(
Block::default()
.borders(Borders::ALL)
.title(Span::styled(
title_with_highlight_progress,
self.theme.title(true),
))
.border_style(self.theme.block(true)),
);
let mut table_state = self.table_state.take();
f.render_widget(Clear, area);
f.render_stateful_widget(table, area, &mut table_state);
ui::draw_scrollbar(
f,
area,
&self.theme,
// April 2021: `draw_scrollbar` assumes that the last parameter
// is `scroll_top`. Therefore, it subtracts the area’s height
// before calculating the position of the scrollbar. To account
// for that, we add the current height.
number_of_rows + (area.height as usize),
// April 2021: we don’t have access to `table_state.offset`
// (it’s private), so we use `table_state.selected()` as a
// replacement.
//
// Other widgets, for example `BranchListComponent`, manage
// scroll state themselves and use `self.scroll_top` in this
// situation.
//
// There are plans to change `render_stateful_widgets`, so this
// might be acceptable as an interim solution.
//
// https://github.com/fdehau/tui-rs/issues/448
table_state.selected().unwrap_or(0),
ui::Orientation::Vertical,
);
self.table_state.set(table_state);
self.current_height.set(area.height.into());
}
Ok(())
}
}
impl Component for BlameFilePopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
let has_result = self
.blame
.as_ref()
.is_some_and(|blame| blame.result().is_some());
if self.is_visible() || force_all {
out.push(
CommandInfo::new(
strings::commands::close_popup(&self.key_config),
true,
true,
)
.order(1),
);
out.push(
CommandInfo::new(
strings::commands::scroll(&self.key_config),
true,
has_result,
)
.order(1),
);
out.push(
CommandInfo::new(
strings::commands::commit_details_open(
&self.key_config,
),
true,
has_result,
)
.order(1),
);
out.push(
CommandInfo::new(
strings::commands::open_file_history(
&self.key_config,
),
true,
has_result,
)
.order(1),
);
out.push(
CommandInfo::new(
strings::commands::open_line_number_popup(
&self.key_config,
),
true,
has_result,
)
.order(1),
);
}
visibility_blocking(self)
}
fn event(
&mut self,
event: &crossterm::event::Event,
) -> Result<EventState> {
if self.is_visible() {
if let Event::Key(key) = event {
if key_match(key, self.key_config.keys.exit_popup) {
self.hide_stacked(false);
} else if key_match(key, self.key_config.keys.move_up)
{
self.move_selection(ScrollType::Up);
} else if key_match(
key,
self.key_config.keys.move_down,
) {
self.move_selection(ScrollType::Down);
} else if key_match(
key,
self.key_config.keys.shift_up,
) || key_match(
key,
self.key_config.keys.home,
) {
self.move_selection(ScrollType::Home);
} else if key_match(
key,
self.key_config.keys.shift_down,
) || key_match(
key,
self.key_config.keys.end,
) {
self.move_selection(ScrollType::End);
} else if key_match(
key,
self.key_config.keys.page_down,
) {
self.move_selection(ScrollType::PageDown);
} else if key_match(key, self.key_config.keys.page_up)
{
self.move_selection(ScrollType::PageUp);
} else if key_match(
key,
self.key_config.keys.move_right,
) {
if let Some(commit_id) = self.selected_commit() {
self.hide_stacked(true);
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::InspectCommit(
InspectCommitOpen::new(commit_id),
),
));
}
} else if key_match(
key,
self.key_config.keys.file_history,
) {
if let Some(filepath) = self
.params
.as_ref()
.map(|p| p.file_path.clone())
{
self.hide_stacked(true);
self.queue.push(InternalEvent::OpenPopup(
StackablePopupOpen::FileRevlog(
FileRevOpen::new(filepath),
),
));
}
} else if key_match(
key,
self.key_config.keys.goto_line,
) {
let maybe_blame_result = &self
.blame
.as_ref()
.and_then(|blame| blame.result());
if let Some(blame_result) = maybe_blame_result {
let max_line = blame_result.lines().len() - 1;
self.queue.push(
InternalEvent::OpenGotoLinePopup(
max_line,
),
);
}
}
return Ok(EventState::Consumed);
}
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
impl BlameFilePopup {
///
pub fn new(env: &Environment, title: &str) -> Self {
Self {
title: String::from(title),
theme: env.theme.clone(),
queue: env.queue.clone(),
visible: false,
params: None,
open_request: None,
table_state: std::cell::Cell::new(TableState::default()),
key_config: env.key_config.clone(),
current_height: std::cell::Cell::new(0),
app_sender: env.sender_app.clone(),
git_sender: env.sender_git.clone(),
blame: None,
repo: env.repo.clone(),
}
}
fn hide_stacked(&mut self, stack: bool) {
self.visible = false;
if stack {
if let Some(request) = self.open_request.clone() {
self.queue.push(InternalEvent::PopupStackPush(
StackablePopupOpen::BlameFile(BlameFileOpen {
file_path: request.file_path,
commit_id: request.commit_id,
selection: self.get_selection(),
}),
));
}
} else {
self.queue.push(InternalEvent::PopupStackPop);
}
}
///
pub fn open(&mut self, open: BlameFileOpen) -> Result<()> {
self.open_request = Some(open.clone());
self.params = Some(BlameParams {
file_path: open.file_path,
commit_id: open.commit_id,
});
self.blame =
Some(BlameProcess::GettingBlame(AsyncBlame::new(
self.repo.borrow().clone(),
&self.git_sender,
)));
self.table_state.get_mut().select(Some(0));
self.visible = true;
self.update()?;
Ok(())
}
///
pub const fn any_work_pending(&self) -> bool {
self.blame.is_some()
&& !matches!(self.blame, Some(BlameProcess::Result(_)))
}
pub fn update_async(
&mut self,
ev: AsyncNotification,
) -> Result<()> {
if let AsyncNotification::Git(ev) = ev {
return self.update_git(ev);
}
self.update_syntax(ev);
Ok(())
}
fn update_git(
&mut self,
event: AsyncGitNotification,
) -> Result<()> {
if self.is_visible() && event == AsyncGitNotification::Blame {
self.update()?;
}
Ok(())
}
fn update(&mut self) -> Result<()> {
if self.is_visible() {
if let Some(BlameProcess::GettingBlame(
ref mut async_blame,
)) = self.blame
{
if let Some(params) = &self.params {
if let Some((
previous_blame_params,
last_file_blame,
)) = async_blame.last()?
{
if previous_blame_params == *params {
self.blame = Some(
BlameProcess::SyntaxHighlighting {
unstyled_file_blame:
SyntaxFileBlame {
file_blame:
last_file_blame,
styled_text: None,
},
job: AsyncSingleJob::new(
self.app_sender.clone(),
),
},
);
self.set_open_selection();
self.highlight_blame_lines();
return Ok(());
}
}
async_blame.request(params.clone())?;
}
}
}
Ok(())
}
fn update_syntax(&mut self, ev: AsyncNotification) {
let Some(BlameProcess::SyntaxHighlighting {
ref unstyled_file_blame,
ref job,
}) = self.blame
else {
return;
};
if let AsyncNotification::App(
AsyncAppNotification::SyntaxHighlighting(progress),
) = ev
{
match progress {
SyntaxHighlightProgress::Done => {
if let Some(job) = job.take_last() {
if let Some(syntax) = job.result() {
if syntax.path()
== Path::new(
unstyled_file_blame.path(),
) {
self.blame =
Some(BlameProcess::Result(
SyntaxFileBlame {
file_blame:
unstyled_file_blame
.file_blame
.clone(),
styled_text: Some(syntax),
},
));
}
}
}
}
SyntaxHighlightProgress::Progress => {}
}
}
}
///
fn get_title(&self) -> String {
match (
self.any_work_pending(),
self.params.as_ref(),
self.blame.as_ref().and_then(|blame| blame.result()),
) {
(true, Some(params), _) => {
format!(
"{} -- {} -- <calculating.. (who is to blame?)>",
self.title, params.file_path
)
}
(false, Some(params), Some(file_blame)) => {
format!(
"{} -- {} -- {}",
self.title,
params.file_path,
file_blame.commit_id().get_short_string()
)
}
(false, Some(params), None) => {
format!(
"{} -- {} -- <no blame available>",
self.title, params.file_path
)
}
_ => format!("{} -- <no blame available>", self.title),
}
}
///
fn get_rows(&self, width: usize) -> Vec<Row<'_>> {
self.blame
.as_ref()
.and_then(|blame| blame.result())
.map(|file_blame| {
let styled_text: Option<Text<'_>> = file_blame
.styled_text
.as_ref()
.map(std::convert::Into::into);
file_blame
.lines()
.iter()
.enumerate()
.map(|(i, (blame_hunk, line))| {
self.get_line_blame(
width,
i,
(blame_hunk.as_ref(), line.as_ref()),
file_blame,
styled_text.as_ref(),
)
})
.collect()
})
.unwrap_or_default()
}
fn highlight_blame_lines(&mut self) {
let Some(BlameProcess::SyntaxHighlighting {
ref unstyled_file_blame,
ref mut job,
}) = self.blame
else {
return;
};
let Some(params) = &self.params else {
return;
};
let raw_lines = unstyled_file_blame
.lines()
.iter()
.map(|l| l.1.clone())
.collect::<Vec<_>>();
let mut text = tabs_to_spaces(raw_lines.join("\n"));
text.push('\n');
job.spawn(AsyncSyntaxJob::new(
text,
params.file_path.clone(),
self.theme.get_syntax(),
));
}
fn get_line_blame<'a>(
&'a self,
width: usize,
line_number: usize,
hunk_and_line: (Option<&BlameHunk>, &str),
file_blame: &'a SyntaxFileBlame,
styled_text: Option<&Text<'a>>,
) -> Row<'a> {
let (hunk_for_line, line) = hunk_and_line;
let show_metadata = if line_number == 0 {
true
} else {
let hunk_for_previous_line =
&file_blame.lines()[line_number - 1];
match (hunk_for_previous_line, hunk_for_line) {
((Some(previous), _), Some(current)) => {
previous.commit_id != current.commit_id
}
_ => true,
}
};
let mut cells = if show_metadata {
self.get_metadata_for_line_blame(width, hunk_for_line)
} else {
vec![Cell::from(""), Cell::from(""), Cell::from("")]
};
let line_number_width = self.get_line_number_width();
let text_cell = styled_text.as_ref().map_or_else(
|| {
Cell::from(tabs_to_spaces(String::from(line)))
.style(self.theme.text(true, false))
},
|styled_text| {
let styled_text =
styled_text.lines[line_number].clone();
Cell::from(styled_text)
},
);
cells.push(
Cell::from(format!(
"{line_number:>line_number_width$}{VERTICAL}",
))
.style(self.theme.text(true, false)),
);
cells.push(text_cell);
Row::new(cells)
}
fn get_metadata_for_line_blame(
&self,
width: usize,
blame_hunk: Option<&BlameHunk>,
) -> Vec<Cell<'_>> {
let commit_hash = blame_hunk.map_or_else(
|| NO_COMMIT_ID.into(),
|hunk| hunk.commit_id.get_short_string(),
);
let author_width = get_author_width(width);
let truncated_author: String = blame_hunk.map_or_else(
|| NO_AUTHOR.into(),
|hunk| string_width_align(&hunk.author, author_width),
);
let author = format!("{truncated_author:MAX_AUTHOR_WIDTH$}");
let time = blame_hunk.map_or_else(String::new, |hunk| {
time_to_string(hunk.time, true)
});
let file_blame =
self.blame.as_ref().and_then(|blame| blame.result());
let is_blamed_commit = file_blame
.and_then(|file_blame| {
blame_hunk.map(|hunk| {
file_blame.commit_id() == &hunk.commit_id
})
})
.unwrap_or(false);
vec![
Cell::from(commit_hash).style(
self.theme.commit_hash_in_blame(is_blamed_commit),
),
Cell::from(time).style(self.theme.commit_time(false)),
Cell::from(author).style(self.theme.commit_author(false)),
]
}
fn get_max_line_number(&self) -> usize {
self.blame
.as_ref()
.and_then(|blame| blame.result())
.map_or(0, |file_blame| file_blame.lines().len() - 1)
}
fn get_line_number_width(&self) -> usize {
let max_line_number = self.get_max_line_number();
number_of_digits(max_line_number)
}
fn move_selection(&self, scroll_type: ScrollType) -> bool {
let mut table_state = self.table_state.take();
let old_selection = table_state.selected().unwrap_or(0);
let max_selection = self.get_max_line_number();
let new_selection = match scroll_type {
ScrollType::Up => old_selection.saturating_sub(1),
ScrollType::Down => {
old_selection.saturating_add(1).min(max_selection)
}
ScrollType::Home => 0,
ScrollType::End => max_selection,
ScrollType::PageUp => old_selection.saturating_sub(
self.current_height.get().saturating_sub(2),
),
ScrollType::PageDown => old_selection
.saturating_add(
self.current_height.get().saturating_sub(2),
)
.min(max_selection),
};
let needs_update = new_selection != old_selection;
table_state.select(Some(new_selection));
self.table_state.set(table_state);
needs_update
}
fn set_open_selection(&self) {
if let Some(selection) =
self.open_request.as_ref().and_then(|req| req.selection)
{
let mut table_state = self.table_state.take();
table_state.select(Some(selection));
self.table_state.set(table_state);
}
}
fn get_selection(&self) -> Option<usize> {
self.blame
.as_ref()
.and_then(|blame| blame.result())
.and_then(|_| {
let table_state = self.table_state.take();
let selection = table_state.selected();
self.table_state.set(table_state);
selection
})
}
pub fn goto_line(&mut self, line: usize) {
self.visible = true;
let mut table_state = self.table_state.take();
table_state
.select(Some(line.clamp(0, self.get_max_line_number())));
self.table_state.set(table_state);
}
fn selected_commit(&self) -> Option<CommitId> {
self.blame
.as_ref()
.and_then(|blame| blame.result())
.and_then(|file_blame| {
let table_state = self.table_state.take();
let commit_id =
table_state.selected().and_then(|selected| {
file_blame.lines()[selected]
.0
.as_ref()
.map(|hunk| hunk.commit_id)
});
self.table_state.set(table_state);
commit_id
})
}
}
fn get_author_width(width: usize) -> usize {
(width.saturating_sub(19) / 3)
.clamp(MIN_AUTHOR_WIDTH, MAX_AUTHOR_WIDTH)
}
const fn number_of_digits(number: usize) -> usize {
let mut rest = number;
let mut result = 0;
while rest > 0 {
rest /= 10;
result += 1;
}
result
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
gitui-org/gitui | https://github.com/gitui-org/gitui/blob/d68f366b1b7106223a0b5ad2481a782a7bd68883/src/popups/push_tags.rs | src/popups/push_tags.rs | use crate::{
app::Environment,
components::{
visibility_blocking, CommandBlocking, CommandInfo, Component,
CredComponent, DrawableComponent, EventState,
},
keys::{key_match, SharedKeyConfig},
queue::{InternalEvent, Queue},
strings,
ui::{self, style::SharedTheme},
};
use anyhow::Result;
use asyncgit::{
sync::{
cred::{
extract_username_password, need_username_password,
BasicAuthCredential,
},
get_default_remote, hooks_pre_push, AsyncProgress,
HookResult, PushTagsProgress, RepoPathRef,
},
AsyncGitNotification, AsyncPushTags, PushTagsRequest,
};
use crossterm::event::Event;
use ratatui::{
layout::Rect,
text::Span,
widgets::{Block, BorderType, Borders, Clear, Gauge},
Frame,
};
///
pub struct PushTagsPopup {
repo: RepoPathRef,
visible: bool,
git_push: AsyncPushTags,
progress: Option<PushTagsProgress>,
pending: bool,
queue: Queue,
theme: SharedTheme,
key_config: SharedKeyConfig,
input_cred: CredComponent,
}
impl PushTagsPopup {
///
pub fn new(env: &Environment) -> Self {
Self {
repo: env.repo.clone(),
queue: env.queue.clone(),
pending: false,
visible: false,
git_push: AsyncPushTags::new(
env.repo.borrow().clone(),
&env.sender_git,
),
progress: None,
input_cred: CredComponent::new(env),
theme: env.theme.clone(),
key_config: env.key_config.clone(),
}
}
///
pub fn push_tags(&mut self) -> Result<()> {
self.show()?;
if need_username_password(&self.repo.borrow())? {
let cred = extract_username_password(&self.repo.borrow())
.unwrap_or_else(|_| {
BasicAuthCredential::new(None, None)
});
if cred.is_complete() {
self.push_to_remote(Some(cred))
} else {
self.input_cred.set_cred(cred);
self.input_cred.show()
}
} else {
self.push_to_remote(None)
}
}
fn push_to_remote(
&mut self,
cred: Option<BasicAuthCredential>,
) -> Result<()> {
// run pre push hook - can reject push
if let HookResult::NotOk(e) =
hooks_pre_push(&self.repo.borrow())?
{
log::error!("pre-push hook failed: {e}");
self.queue.push(InternalEvent::ShowErrorMsg(format!(
"pre-push hook failed:\n{e}"
)));
self.pending = false;
self.visible = false;
return Ok(());
}
self.pending = true;
self.progress = None;
self.git_push.request(PushTagsRequest {
remote: get_default_remote(&self.repo.borrow())?,
basic_credential: cred,
})?;
Ok(())
}
///
pub fn update_git(
&mut self,
ev: AsyncGitNotification,
) -> Result<()> {
if self.is_visible() && ev == AsyncGitNotification::PushTags {
self.update()?;
}
Ok(())
}
///
fn update(&mut self) -> Result<()> {
self.pending = self.git_push.is_pending()?;
self.progress = self.git_push.progress()?;
if !self.pending {
if let Some(err) = self.git_push.last_result()? {
self.queue.push(InternalEvent::ShowErrorMsg(
format!("push tags failed:\n{err}"),
));
}
self.hide();
}
Ok(())
}
///
pub const fn any_work_pending(&self) -> bool {
self.pending
}
///
pub fn get_progress(
progress: Option<&PushTagsProgress>,
) -> (String, u8) {
progress.as_ref().map_or_else(
|| (strings::PUSH_POPUP_PROGRESS_NONE.into(), 0),
|progress| {
(
Self::progress_state_name(progress),
progress.progress().progress,
)
},
)
}
fn progress_state_name(progress: &PushTagsProgress) -> String {
match progress {
PushTagsProgress::CheckRemote => {
strings::PUSH_TAGS_STATES_FETCHING
}
PushTagsProgress::Push { .. } => {
strings::PUSH_TAGS_STATES_PUSHING
}
PushTagsProgress::Done => strings::PUSH_TAGS_STATES_DONE,
}
.to_string()
}
}
impl DrawableComponent for PushTagsPopup {
fn draw(&self, f: &mut Frame, rect: Rect) -> Result<()> {
if self.visible {
let (state, progress) =
Self::get_progress(self.progress.as_ref());
let area = ui::centered_rect_absolute(30, 3, f.area());
f.render_widget(Clear, area);
f.render_widget(
Gauge::default()
.label(state.as_str())
.block(
Block::default()
.title(Span::styled(
strings::PUSH_TAGS_POPUP_MSG,
self.theme.title(true),
))
.borders(Borders::ALL)
.border_type(BorderType::Thick)
.border_style(self.theme.block(true)),
)
.gauge_style(self.theme.push_gauge())
.percent(u16::from(progress)),
area,
);
self.input_cred.draw(f, rect)?;
}
Ok(())
}
}
impl Component for PushTagsPopup {
fn commands(
&self,
out: &mut Vec<CommandInfo>,
force_all: bool,
) -> CommandBlocking {
if self.is_visible() || force_all {
if !force_all {
out.clear();
}
if self.input_cred.is_visible() {
return self.input_cred.commands(out, force_all);
}
out.push(CommandInfo::new(
strings::commands::close_msg(&self.key_config),
!self.pending,
self.visible,
));
}
visibility_blocking(self)
}
fn event(&mut self, ev: &Event) -> Result<EventState> {
if self.visible {
if let Event::Key(e) = ev {
if self.input_cred.is_visible() {
self.input_cred.event(ev)?;
if self.input_cred.get_cred().is_complete()
|| !self.input_cred.is_visible()
{
self.push_to_remote(Some(
self.input_cred.get_cred().clone(),
))?;
self.input_cred.hide();
}
} else if key_match(
e,
self.key_config.keys.exit_popup,
) && !self.pending
{
self.hide();
}
}
return Ok(EventState::Consumed);
}
Ok(EventState::NotConsumed)
}
fn is_visible(&self) -> bool {
self.visible
}
fn hide(&mut self) {
self.visible = false;
}
fn show(&mut self) -> Result<()> {
self.visible = true;
Ok(())
}
}
| rust | MIT | d68f366b1b7106223a0b5ad2481a782a7bd68883 | 2026-01-04T15:40:16.730844Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.