feat(tui): add screenshots grid with kitty protocol
This commit is contained in:
1 parent
794fb4d08c
commit
c3a26eaac2
8 files changed
+444
-21
No files matched your search
@@ -4,6 +4,7 @@ pub mod loader;
|
||||
pub mod models;
|
||||
pub mod mods;
|
||||
pub mod resource_packs;
|
||||
pub mod screenshots;
|
||||
pub mod shaders;
|
||||
|
||||
pub use launch::LaunchError;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ScreenshotEntry {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> {
|
||||
let dir = instances_dir
|
||||
.join(instance_name)
|
||||
.join(".minecraft")
|
||||
.join("screenshots");
|
||||
|
||||
let read_dir = match std::fs::read_dir(&dir) {
|
||||
Ok(rd) => rd,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut entries: Vec<ScreenshotEntry> = read_dir
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let path = entry.path();
|
||||
let name = path.file_name()?.to_str()?.to_string();
|
||||
if name.ends_with(".png") || name.ends_with(".jpg") || name.ends_with(".jpeg") {
|
||||
let (width, height) = image::image_dimensions(&path).unwrap_or((1920, 1080));
|
||||
Some(ScreenshotEntry {
|
||||
name,
|
||||
path,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
entries.sort_by(|a, b| b.name.cmp(&a.name));
|
||||
entries
|
||||
}
|
||||
+41
-12
@@ -34,6 +34,8 @@ pub struct App {
|
||||
mods_state: widgets::content_list::ContentListState,
|
||||
resource_packs_state: widgets::content_list::ContentListState,
|
||||
shaders_state: widgets::content_list::ContentListState,
|
||||
screenshots_state: widgets::screenshots_grid::ScreenshotsState,
|
||||
picker: ratatui_image::picker::Picker,
|
||||
instance_manager: InstanceManager,
|
||||
log_list_state: tui_logger::TuiWidgetState,
|
||||
throbber_state: throbber_widgets_tui::ThrobberState,
|
||||
@@ -61,8 +63,8 @@ pub enum FocusedArea {
|
||||
ConfirmDelete,
|
||||
}
|
||||
|
||||
impl Default for App {
|
||||
fn default() -> Self {
|
||||
impl App {
|
||||
pub fn new(picker: ratatui_image::picker::Picker) -> Self {
|
||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||
|
||||
@@ -93,6 +95,12 @@ impl Default for App {
|
||||
mods_state: widgets::content_list::ContentListState::default(),
|
||||
resource_packs_state: widgets::content_list::ContentListState::default(),
|
||||
shaders_state: widgets::content_list::ContentListState::default(),
|
||||
screenshots_state: {
|
||||
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
|
||||
s.font_size = picker.font_size();
|
||||
s
|
||||
},
|
||||
picker,
|
||||
instance_manager: manager,
|
||||
log_list_state: tui_logger::TuiWidgetState::new()
|
||||
.set_default_display_level(log::LevelFilter::Debug),
|
||||
@@ -117,6 +125,9 @@ impl App {
|
||||
self.mods_state.drain_pending();
|
||||
self.resource_packs_state.drain_pending();
|
||||
self.shaders_state.drain_pending();
|
||||
self.screenshots_state.drain_pending_entries();
|
||||
self.screenshots_state.request_visible_loads();
|
||||
self.create_screenshot_protocols();
|
||||
self.throbber_tick = self.throbber_tick.wrapping_add(1);
|
||||
if self.throbber_tick % 8 == 0 {
|
||||
self.throbber_state.calc_next();
|
||||
@@ -164,6 +175,7 @@ impl App {
|
||||
&mut self.mods_state,
|
||||
&mut self.resource_packs_state,
|
||||
&mut self.shaders_state,
|
||||
&mut self.screenshots_state,
|
||||
&self.instance_manager.instances_dir,
|
||||
);
|
||||
|
||||
@@ -289,18 +301,27 @@ impl App {
|
||||
}
|
||||
|
||||
if self.focused == FocusedArea::Content {
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
|
||||
widgets::content::ContentTab::ResourcePacks => {
|
||||
Some(&mut self.resource_packs_state)
|
||||
}
|
||||
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(state) = state {
|
||||
if widgets::content_list::handle_key(&key_event, state) {
|
||||
if self.content_tab == widgets::content::ContentTab::Screenshots {
|
||||
if widgets::screenshots_grid::handle_key(
|
||||
&key_event,
|
||||
&mut self.screenshots_state,
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
|
||||
widgets::content::ContentTab::ResourcePacks => {
|
||||
Some(&mut self.resource_packs_state)
|
||||
}
|
||||
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(state) = state {
|
||||
if widgets::content_list::handle_key(&key_event, state) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,6 +520,14 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_screenshot_protocols(&mut self) {
|
||||
let pending = self.screenshots_state.take_pending_images();
|
||||
for (idx, img) in pending {
|
||||
let proto = self.picker.new_resize_protocol(img);
|
||||
self.screenshots_state.set_protocol(idx, proto);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_log_overlay(frame: &mut Frame, log_state: &mut tui_logger::TuiWidgetState) {
|
||||
use crate::tui::theme::THEME;
|
||||
use ratatui::{
|
||||
|
||||
+4
-1
@@ -18,7 +18,10 @@ pub async fn show() -> color_eyre::Result<()> {
|
||||
)
|
||||
);
|
||||
|
||||
let result = layout::App::default().run(&mut terminal).await;
|
||||
let picker = ratatui_image::picker::Picker::from_query_stdio()
|
||||
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
|
||||
|
||||
let result = layout::App::new(picker).run(&mut terminal).await;
|
||||
|
||||
let _ = crossterm::execute!(
|
||||
std::io::stdout(),
|
||||
|
||||
@@ -71,6 +71,7 @@ pub fn render(
|
||||
mods_state: &mut super::content_list::ContentListState,
|
||||
resource_packs_state: &mut super::content_list::ContentListState,
|
||||
shaders_state: &mut super::content_list::ContentListState,
|
||||
screenshots_state: &mut super::screenshots_grid::ScreenshotsState,
|
||||
instances_dir: &std::path::Path,
|
||||
) {
|
||||
let is_focused = focused == FocusedArea::Content;
|
||||
@@ -202,15 +203,24 @@ pub fn render(
|
||||
);
|
||||
}
|
||||
}
|
||||
ContentTab::Screenshots => {
|
||||
if let Some(instance) = instance {
|
||||
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||
screenshots_state.start_load(instances_dir, &instance.name);
|
||||
}
|
||||
super::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
|
||||
} else {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No instance selected.")
|
||||
.style(Style::default().fg(THEME.colors.text_idle)),
|
||||
content_area,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let body = match tab {
|
||||
ContentTab::Screenshots => "No screenshots.",
|
||||
ContentTab::Worlds => "No worlds saved.",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
frame.render_widget(
|
||||
Paragraph::new(body).style(Style::default().fg(THEME.colors.text_idle)),
|
||||
Paragraph::new("No worlds saved.")
|
||||
.style(Style::default().fg(THEME.colors.text_idle)),
|
||||
content_area,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Color, Modifier, Style},
|
||||
@@ -191,6 +191,25 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
|
||||
state.update_scrollbar();
|
||||
true
|
||||
}
|
||||
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||
if let Some(entry) = state
|
||||
.list_state
|
||||
.selected
|
||||
.and_then(|i| state.entries.get(i))
|
||||
{
|
||||
if let Some(dir) = entry.path.parent() {
|
||||
if let Err(e) = std::process::Command::new("xdg-open")
|
||||
.arg(dir)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
tracing::error!("Failed to open directory: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
state.toggle_selected();
|
||||
true
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod account;
|
||||
pub mod content;
|
||||
pub mod content_list;
|
||||
pub mod details;
|
||||
pub mod screenshots_grid;
|
||||
pub mod popups;
|
||||
pub mod profiles;
|
||||
pub mod search;
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{
|
||||
layout::{Constraint, Layout, Rect},
|
||||
style::{Modifier, Style},
|
||||
text::Span,
|
||||
widgets::Paragraph,
|
||||
Frame,
|
||||
};
|
||||
use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
|
||||
|
||||
use crate::instance::screenshots::ScreenshotEntry;
|
||||
use crate::tui::theme::THEME;
|
||||
|
||||
const TARGET_CELL_WIDTH: u16 = 34;
|
||||
const MIN_CELL_WIDTH: u16 = 24;
|
||||
const MAX_CELL_WIDTH: u16 = 52;
|
||||
const NAME_ROW_HEIGHT: u16 = 1;
|
||||
const GAP: u16 = 1;
|
||||
|
||||
pub struct ScreenshotsState {
|
||||
pub entries: Vec<ScreenshotEntry>,
|
||||
protocols: HashMap<usize, StatefulProtocol>,
|
||||
requested: HashSet<usize>,
|
||||
pub selected: usize,
|
||||
pub scroll_row: usize,
|
||||
pub loaded_for: Option<String>,
|
||||
pub loading: bool,
|
||||
cols: usize,
|
||||
visible_rows: usize,
|
||||
pub font_size: (u16, u16),
|
||||
pending_entries: Arc<Mutex<Option<(String, Vec<ScreenshotEntry>)>>>,
|
||||
pending_images: Arc<Mutex<Vec<(usize, image::DynamicImage)>>>,
|
||||
}
|
||||
|
||||
impl Default for ScreenshotsState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
entries: Vec::new(),
|
||||
protocols: HashMap::new(),
|
||||
requested: HashSet::new(),
|
||||
selected: 0,
|
||||
scroll_row: 0,
|
||||
loaded_for: None,
|
||||
loading: false,
|
||||
cols: 3,
|
||||
visible_rows: 2,
|
||||
font_size: (8, 16),
|
||||
pending_entries: Arc::new(Mutex::new(None)),
|
||||
pending_images: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenshotsState {
|
||||
pub fn start_load(&mut self, instances_dir: &Path, instance_name: &str) {
|
||||
self.loading = true;
|
||||
self.loaded_for = Some(instance_name.to_string());
|
||||
self.entries.clear();
|
||||
self.protocols.clear();
|
||||
self.requested.clear();
|
||||
self.selected = 0;
|
||||
self.scroll_row = 0;
|
||||
|
||||
let dir = instances_dir.to_path_buf();
|
||||
let tag = instance_name.to_string();
|
||||
let pending = self.pending_entries.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let scan_dir = dir.clone();
|
||||
let scan_name = tag.clone();
|
||||
let entries = tokio::task::spawn_blocking(move || {
|
||||
crate::instance::screenshots::scan_screenshots(&scan_dir, &scan_name)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Ok(mut slot) = pending.lock() {
|
||||
*slot = Some((tag, entries));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn drain_pending_entries(&mut self) {
|
||||
let taken = if let Ok(mut slot) = self.pending_entries.lock() {
|
||||
slot.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some((instance_name, entries)) = taken {
|
||||
if self.loaded_for.as_deref() == Some(&instance_name) {
|
||||
self.entries = entries;
|
||||
self.loading = false;
|
||||
self.selected = 0;
|
||||
self.scroll_row = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_pending_images(&mut self) -> Vec<(usize, image::DynamicImage)> {
|
||||
if let Ok(mut slot) = self.pending_images.lock() {
|
||||
std::mem::take(&mut *slot)
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_protocol(&mut self, idx: usize, proto: StatefulProtocol) {
|
||||
self.protocols.insert(idx, proto);
|
||||
}
|
||||
|
||||
pub fn request_visible_loads(&mut self) {
|
||||
if self.entries.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let first = self.scroll_row * self.cols;
|
||||
let last = ((self.scroll_row + self.visible_rows + 1) * self.cols).min(self.entries.len());
|
||||
|
||||
for idx in first..last {
|
||||
if !self.protocols.contains_key(&idx) && self.requested.insert(idx) {
|
||||
let path = self.entries[idx].path.clone();
|
||||
let pending = self.pending_images.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let load_path = path.clone();
|
||||
let img = tokio::task::spawn_blocking(move || image::open(&load_path).ok())
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
|
||||
if let Some(img) = img {
|
||||
if let Ok(mut slot) = pending.lock() {
|
||||
slot.push((idx, img));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_visible(&mut self) {
|
||||
let row = if self.cols > 0 {
|
||||
self.selected / self.cols
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
if row < self.scroll_row {
|
||||
self.scroll_row = row;
|
||||
} else if row >= self.scroll_row + self.visible_rows {
|
||||
self.scroll_row = row.saturating_sub(self.visible_rows - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
|
||||
let count = state.entries.len();
|
||||
if count == 0 {
|
||||
return false;
|
||||
}
|
||||
let cols = state.cols.max(1);
|
||||
|
||||
match key_event.code {
|
||||
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||
if let Some(entry) = state.entries.get(state.selected) {
|
||||
if let Some(dir) = entry.path.parent() {
|
||||
xdg_open(dir);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some(entry) = state.entries.get(state.selected) {
|
||||
xdg_open(&entry.path);
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Char('l') | KeyCode::Right => {
|
||||
if state.selected + 1 < count {
|
||||
state.selected += 1;
|
||||
state.ensure_visible();
|
||||
}
|
||||
true
|
||||
}
|
||||
KeyCode::Char('h') | KeyCode::Left => {
|
||||
state.selected = state.selected.saturating_sub(1);
|
||||
state.ensure_visible();
|
||||
true
|
||||
}
|
||||
KeyCode::Char('j') | KeyCode::Down => {
|
||||
let next = state.selected + cols;
|
||||
if next < count {
|
||||
state.selected = next;
|
||||
}
|
||||
state.ensure_visible();
|
||||
true
|
||||
}
|
||||
KeyCode::Char('k') | KeyCode::Up => {
|
||||
state.selected = state.selected.saturating_sub(cols);
|
||||
state.ensure_visible();
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn xdg_open(path: &std::path::Path) {
|
||||
if let Err(e) = std::process::Command::new("xdg-open")
|
||||
.arg(path)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
tracing::error!("Failed to open: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_focused: bool) {
|
||||
if state.loading {
|
||||
frame.render_widget(
|
||||
Paragraph::new("Loading screenshots...")
|
||||
.style(Style::default().fg(THEME.colors.text_idle)),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if state.entries.is_empty() {
|
||||
frame.render_widget(
|
||||
Paragraph::new("No screenshots.").style(Style::default().fg(THEME.colors.text_idle)),
|
||||
area,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let min_cols = (area.width / MAX_CELL_WIDTH).max(1) as usize;
|
||||
let max_cols = (area.width / MIN_CELL_WIDTH).max(1) as usize;
|
||||
let target_cols = (area.width / TARGET_CELL_WIDTH).max(1) as usize;
|
||||
let cols = target_cols.clamp(min_cols, max_cols);
|
||||
let cell_width = area.width / cols as u16;
|
||||
|
||||
let (img_w, img_h) = state
|
||||
.entries
|
||||
.first()
|
||||
.map(|e| (e.width, e.height))
|
||||
.unwrap_or((1920, 1080));
|
||||
let (fw, fh) = (state.font_size.0.max(1) as u32, state.font_size.1.max(1) as u32);
|
||||
let img_rows = (cell_width as u32 * fw * img_h / (fh * img_w)).max(2) as u16;
|
||||
let cell_height = img_rows + NAME_ROW_HEIGHT + GAP;
|
||||
let visible_rows = (area.height / cell_height).max(1) as usize;
|
||||
|
||||
state.cols = cols;
|
||||
state.visible_rows = visible_rows;
|
||||
state.ensure_visible();
|
||||
|
||||
for vr in 0..visible_rows {
|
||||
for vc in 0..cols {
|
||||
let idx = (state.scroll_row + vr) * cols + vc;
|
||||
if idx >= state.entries.len() {
|
||||
break;
|
||||
}
|
||||
|
||||
let raw_x = area.x + vc as u16 * cell_width;
|
||||
let raw_y = area.y + vr as u16 * cell_height;
|
||||
let raw_w = cell_width.min(area.x + area.width - raw_x);
|
||||
let raw_h = cell_height.min(area.y + area.height - raw_y);
|
||||
|
||||
let cell = Rect {
|
||||
x: raw_x,
|
||||
y: raw_y,
|
||||
width: raw_w.saturating_sub(GAP),
|
||||
height: raw_h.saturating_sub(GAP),
|
||||
};
|
||||
|
||||
if cell.height < 2 || cell.width < 4 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_selected = is_focused && idx == state.selected;
|
||||
|
||||
let [img_area, name_area] = Layout::vertical([
|
||||
Constraint::Min(0),
|
||||
Constraint::Length(NAME_ROW_HEIGHT),
|
||||
])
|
||||
.areas(cell);
|
||||
|
||||
if let Some(proto) = state.protocols.get_mut(&idx) {
|
||||
let widget: StatefulImage<StatefulProtocol> =
|
||||
StatefulImage::default().resize(Resize::Fit(None));
|
||||
frame.render_stateful_widget(widget, img_area, proto);
|
||||
}
|
||||
|
||||
let name = &state.entries[idx].name;
|
||||
let name_style = if is_selected {
|
||||
Style::default()
|
||||
.fg(THEME.colors.accent)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default().fg(THEME.colors.text_idle)
|
||||
};
|
||||
|
||||
let truncated = if name.len() > cell_width as usize {
|
||||
&name[..cell_width as usize]
|
||||
} else {
|
||||
name
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(Span::styled(truncated, name_style)),
|
||||
name_area,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user