feat(content): add Modrinth discovery mode

This commit is contained in:
objz committed 2026-07-22 20:44:16 +02:00
1 parent ddfe0e26b2
commit 774a6c6723
12 files changed
+1552 -107

No files matched your search

+385
View File
@@ -0,0 +1,385 @@
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
use crate::instance::content::mods::ContentEntry;
use crate::instance::{InstanceConfig, ModLoader};
use crate::net::modrinth::{DiscoveryKind, DiscoveryProject};
use super::list::{ContentListState, ContentStream};
pub const PAGE_SIZE: usize = 20;
const PREFETCH_ITEMS: usize = 5;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentMode {
#[default]
Installed,
Discover,
}
impl ContentMode {
pub fn toggle(self) -> Self {
match self {
Self::Installed => Self::Discover,
Self::Discover => Self::Installed,
}
}
pub fn label(self) -> &'static str {
match self {
Self::Installed => "Installed",
Self::Discover => "Discover",
}
}
}
pub struct PendingDiscoveryResult {
generation: u64,
offset: usize,
result: Result<DiscoveryPageResult, String>,
}
pub struct DiscoveryPageResult {
pub received: usize,
pub total_hits: usize,
}
pub struct DiscoveryRequest {
pub generation: u64,
pub offset: usize,
pub pending: PendingDiscovery,
pub stream: ContentStream,
}
pub(crate) type PendingDiscovery = Arc<Mutex<Vec<PendingDiscoveryResult>>>;
pub struct DiscoveryState {
pub kind: DiscoveryKind,
pub list: ContentListState,
pub search: crate::tui::widgets::search::SearchState,
pub total_hits: usize,
pub error: Option<String>,
context: Option<String>,
generation: u64,
pending: PendingDiscovery,
stream: Option<ContentStream>,
next_offset: usize,
page_loading: bool,
exhausted: bool,
viewport_rows: u16,
}
impl DiscoveryState {
pub fn new(kind: DiscoveryKind) -> Self {
Self {
kind,
list: ContentListState::default(),
search: crate::tui::widgets::search::SearchState::default(),
total_hits: 0,
error: None,
context: None,
generation: 0,
pending: Arc::new(Mutex::new(Vec::new())),
stream: None,
next_offset: 0,
page_loading: false,
exhausted: false,
viewport_rows: 0,
}
}
pub fn needs_search(&self, instance: &InstanceConfig) -> bool {
self.context.as_deref() != Some(discovery_context(instance).as_str())
}
pub fn begin_search(&mut self, instance: &InstanceConfig) -> DiscoveryRequest {
self.generation = self.generation.wrapping_add(1);
let context = discovery_context(instance);
self.context = Some(context.clone());
self.total_hits = 0;
self.error = None;
self.next_offset = 0;
self.page_loading = true;
self.exhausted = false;
let stream = self.list.start_source_stream(context);
self.stream = Some(stream.clone());
DiscoveryRequest {
generation: self.generation,
offset: 0,
pending: self.pending.clone(),
stream,
}
}
pub fn begin_next_page(&mut self) -> Option<DiscoveryRequest> {
if !self.should_load_more() {
return None;
}
self.page_loading = true;
Some(DiscoveryRequest {
generation: self.generation,
offset: self.next_offset,
pending: self.pending.clone(),
stream: self.stream.clone()?,
})
}
pub fn set_viewport_rows(&mut self, rows: u16) {
self.viewport_rows = rows;
}
pub fn push_result(
pending: &PendingDiscovery,
generation: u64,
offset: usize,
result: Result<DiscoveryPageResult, String>,
) {
if let Ok(mut pending) = pending.lock() {
pending.push(PendingDiscoveryResult {
generation,
offset,
result,
});
crate::tui::request_redraw();
}
}
pub fn drain_pending(&mut self) {
let results = match self.pending.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => return,
};
for pending in results {
if pending.generation != self.generation {
continue;
}
self.page_loading = false;
self.list.loading = false;
match pending.result {
Ok(result) => {
self.total_hits = result.total_hits;
self.next_offset = pending.offset.saturating_add(result.received);
self.exhausted = result.received == 0 || self.next_offset >= self.total_hits;
self.error = None;
}
Err(error) => {
self.total_hits = 0;
self.error = Some(error);
self.exhausted = true;
}
}
}
}
pub fn empty_text(&self) -> &str {
self.error
.as_deref()
.unwrap_or("No Modrinth projects found.")
}
fn should_load_more(&self) -> bool {
if self.page_loading || self.exhausted || self.error.is_some() || self.stream.is_none() {
return false;
}
let viewport_items = usize::from(self.viewport_rows).div_ceil(3);
let selected = self.list.list_state.selected.unwrap_or(0);
self.list.entries.len() < viewport_items.saturating_add(PREFETCH_ITEMS)
|| selected.saturating_add(PREFETCH_ITEMS) >= self.list.entries.len()
}
}
pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> (bool, bool) {
if state.search.active {
let refresh = key_event.code == KeyCode::Enter
|| (key_event.code == KeyCode::Esc && !state.search.query.is_empty());
match key_event.code {
KeyCode::Enter => state.search.confirm(),
KeyCode::Esc => state.search.deactivate(),
KeyCode::Backspace => state.search.pop(),
KeyCode::Char(c) => state.search.push(c),
_ => {}
}
return (true, refresh);
}
if key_event.code == KeyCode::Char('/') {
state.search.activate();
return (true, false);
}
(
super::list::handle_key_no_toggle(key_event, &mut state.list),
false,
)
}
fn discovery_context(instance: &InstanceConfig) -> String {
format!(
"{}:{}:{}",
instance.name,
instance.game_version,
loader_slug(instance.loader).unwrap_or("vanilla")
)
}
fn loader_slug(loader: ModLoader) -> Option<&'static str> {
match loader {
ModLoader::Vanilla => None,
ModLoader::Fabric => Some("fabric"),
ModLoader::Forge => Some("forge"),
ModLoader::NeoForge => Some("neoforge"),
ModLoader::Quilt => Some("quilt"),
}
}
pub(crate) fn project_entry(project: DiscoveryProject) -> ContentEntry {
let description = format!(
"{} • {} downloads",
project.description,
format_downloads(project.downloads)
);
ContentEntry {
file_stem: project.id.clone(),
name: project.title,
description,
enabled: true,
icon_bytes: project.icon_bytes,
path: PathBuf::from(project.id),
icon_lines: Some(crate::instance::content::mods::fallback_icon()),
}
}
fn format_downloads(downloads: u64) -> String {
match downloads {
1_000_000.. => format!("{:.1}M", downloads as f64 / 1_000_000.0),
1_000.. => format!("{:.1}K", downloads as f64 / 1_000.0),
_ => downloads.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
fn instance(name: &str, version: &str) -> InstanceConfig {
InstanceConfig {
name: name.to_string(),
game_version: version.to_string(),
loader: ModLoader::Fabric,
loader_version: None,
created: Utc::now(),
last_played: None,
java_path: None,
memory_max: None,
memory_min: None,
jvm_args: Vec::new(),
resolution: None,
config_sync_profile: None,
}
}
#[test]
fn content_mode_toggles_both_ways() {
assert_eq!(ContentMode::Installed.toggle(), ContentMode::Discover);
assert_eq!(ContentMode::Discover.toggle(), ContentMode::Installed);
}
#[test]
fn changing_instance_invalidates_results() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = instance("one", "1.21.1");
let second = instance("two", "1.21.1");
let _request = state.begin_search(&first);
assert!(!state.needs_search(&first));
assert!(state.needs_search(&second));
}
#[test]
fn stale_search_result_is_ignored() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let old = state.begin_search(&instance);
let _new = state.begin_search(&instance);
DiscoveryState::push_result(
&old.pending,
old.generation,
old.offset,
Ok(DiscoveryPageResult {
received: 20,
total_hits: 99,
}),
);
state.drain_pending();
assert_eq!(state.total_hits, 0);
assert!(state.list.loading);
}
#[test]
fn next_page_prefetches_before_selection_reaches_the_end() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
for index in 0..PAGE_SIZE {
assert!(first.stream.send(project_entry(DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
})));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 100,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE - PREFETCH_ITEMS);
let next = state.begin_next_page().expect("next page should prefetch");
assert_eq!(next.offset, PAGE_SIZE);
assert!(state.begin_next_page().is_none());
}
#[test]
fn tall_viewport_loads_enough_pages_to_fill_it() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.set_viewport_rows(90);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
assert!(first.stream.send(project_entry(DiscoveryProject {
id: index.to_string(),
slug: index.to_string(),
title: index.to_string(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
})));
}
state.list.drain_pending();
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 100,
}),
);
state.drain_pending();
assert_eq!(state.begin_next_page().unwrap().offset, PAGE_SIZE);
}
}
+173 -18
View File
@@ -24,6 +24,55 @@ use crate::instance::content::mods::{ContentEntry, IconCell};
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
#[derive(Clone, Copy, Default)]
enum ContentStreamOrder {
#[default]
Sorted,
Source,
}
#[derive(Clone)]
pub struct ContentStream {
sender: mpsc::Sender<ContentStreamUpdate>,
}
impl ContentStream {
pub fn send(&self, entry: ContentEntry) -> bool {
if self.sender.send(ContentStreamUpdate::Entry(entry)).is_ok() {
crate::tui::request_redraw();
true
} else {
false
}
}
pub fn send_icon(&self, file_stem: String, path: std::path::PathBuf, bytes: Vec<u8>) -> bool {
if self
.sender
.send(ContentStreamUpdate::Icon {
file_stem,
path,
bytes,
})
.is_ok()
{
crate::tui::request_redraw();
true
} else {
false
}
}
}
enum ContentStreamUpdate {
Entry(ContentEntry),
Icon {
file_stem: String,
path: std::path::PathBuf,
bytes: Vec<u8>,
},
}
struct CachedList {
entries: Vec<ContentEntry>,
selected: Option<usize>,
@@ -62,7 +111,8 @@ pub struct ContentListState {
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
stream_rx: Option<mpsc::Receiver<ContentEntry>>,
stream_rx: Option<mpsc::Receiver<ContentStreamUpdate>>,
stream_order: ContentStreamOrder,
// file watcher: notify callback spawns background work,
// precomputed diff lands here for the UI to pick up
watcher_diff: Arc<Mutex<Option<WatcherDiff>>>,
@@ -95,6 +145,7 @@ impl Default for ContentListState {
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
stream_rx: None,
stream_order: ContentStreamOrder::default(),
watcher_diff: Arc::new(Mutex::new(None)),
_watcher: None,
watched_dir: None,
@@ -105,6 +156,34 @@ impl Default for ContentListState {
}
impl ContentListState {
pub fn start_stream(&mut self, source: impl Into<String>) -> ContentStream {
self.start_stream_with_order(source, ContentStreamOrder::Sorted)
}
pub fn start_source_stream(&mut self, source: impl Into<String>) -> ContentStream {
self.start_stream_with_order(source, ContentStreamOrder::Source)
}
fn start_stream_with_order(
&mut self,
source: impl Into<String>,
order: ContentStreamOrder,
) -> ContentStream {
self.images_dirty = true;
self.image_protocols.clear();
self.requested_images.clear();
self.entries.clear();
self.display_metadata.clear();
self.list_state = TuiListState::default();
self.loading = true;
self.loaded_for = Some(source.into());
self.update_scrollbar();
let (sender, receiver) = mpsc::channel();
self.stream_rx = Some(receiver);
self.stream_order = order;
ContentStream { sender }
}
pub fn request_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
if !self.images_dirty {
return;
@@ -216,17 +295,39 @@ impl ContentListState {
let mut finished = false;
loop {
match rx.try_recv() {
Ok(entry) => {
Ok(ContentStreamUpdate::Entry(entry)) => {
received = true;
self.images_dirty = true;
received_count += 1;
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
let pos = self
match self.stream_order {
ContentStreamOrder::Sorted => {
let pos = self
.entries
.binary_search_by(|e| {
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
})
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
}
ContentStreamOrder::Source => self.entries.push(entry),
}
}
Ok(ContentStreamUpdate::Icon {
file_stem,
path,
bytes,
}) => {
if let Some(entry) = self
.entries
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
.unwrap_or_else(|i| i);
self.entries.insert(pos, entry);
.iter_mut()
.find(|entry| entry.file_stem == file_stem && entry.path == path)
{
entry.icon_bytes = Some(bytes);
self.requested_images.remove(&file_stem);
self.images_dirty = true;
}
}
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
@@ -524,15 +625,7 @@ impl ContentListState {
}
// no cache, stream entries one by one as each file is scanned
self.entries.clear();
self.display_metadata.clear();
self.list_state = TuiListState::default();
self.loading = true;
self.loaded_for = Some(instance_name.to_string());
self.update_scrollbar();
let (tx, rx) = mpsc::channel();
self.stream_rx = Some(rx);
let stream = self.start_stream(instance_name);
let dir = content_dir.to_path_buf();
tracing::debug!(
@@ -578,10 +671,9 @@ impl ContentListState {
};
let entry = scan_one_fn(&path, &file_stem, enabled);
if tx.send(entry).is_err() {
if !stream.send(entry) {
break; // receiver dropped (instance switched)
}
crate::tui::request_redraw();
}
})
.await;
@@ -1275,7 +1367,23 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
#[cfg(test)]
mod tests {
use super::square_icon_columns;
use std::path::PathBuf;
use crate::instance::content::mods::ContentEntry;
use super::{ContentListState, square_icon_columns};
fn entry(name: &str) -> ContentEntry {
ContentEntry {
file_stem: name.to_lowercase(),
name: name.to_owned(),
description: String::new(),
enabled: true,
icon_bytes: None,
path: PathBuf::from(name.to_lowercase()),
icon_lines: None,
}
}
#[test]
fn square_columns_follow_terminal_cell_ratio() {
@@ -1288,4 +1396,51 @@ mod tests {
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
#[test]
fn content_stream_inserts_entries_and_icons_incrementally() {
let mut state = ContentListState::default();
let stream = state.start_stream("remote");
assert!(stream.send(entry("Zulu")));
state.drain_pending();
assert_eq!(state.entries[0].name, "Zulu");
assert!(!state.loading);
assert!(stream.send(entry("Alpha")));
assert!(stream.send_icon("alpha".to_owned(), PathBuf::from("alpha"), vec![1, 2, 3],));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Alpha", "Zulu"]
);
assert_eq!(
state.entries[0].icon_bytes.as_deref(),
Some([1, 2, 3].as_slice())
);
}
#[test]
fn source_stream_preserves_remote_result_order() {
let mut state = ContentListState::default();
let stream = state.start_source_stream("remote");
assert!(stream.send(entry("Zulu")));
assert!(stream.send(entry("Alpha")));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Zulu", "Alpha"]
);
}
}
+2
View File
@@ -1,7 +1,9 @@
// the tabbed content area: mods, resource packs, shaders, screenshots, worlds, logs
pub mod discovery;
pub mod list;
pub mod tabs;
pub use discovery::{ContentMode, DiscoveryState};
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
pub use tabs::{ContentTab, render, title};
+225 -68
View File
@@ -13,6 +13,7 @@ use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::config::theme::{BORDER_STYLE, THEME};
use crate::tui::app::FocusedArea;
use crate::tui::widgets::content::{ContentMode, DiscoveryState};
use crate::tui::widgets::styled_title;
@@ -37,6 +38,12 @@ impl ContentTab {
ContentTab::Logs,
];
const DISCOVERY: &'static [ContentTab] = &[
ContentTab::Mods,
ContentTab::ResourcePacks,
ContentTab::Shaders,
];
pub fn label(self) -> &'static str {
match self {
ContentTab::Mods => "Mods",
@@ -64,6 +71,34 @@ impl ContentTab {
idx - 1
}]
}
pub fn next_for_mode(self, mode: ContentMode) -> Self {
cycle_tab(self, visible_tabs(mode), true)
}
pub fn previous_for_mode(self, mode: ContentMode) -> Self {
cycle_tab(self, visible_tabs(mode), false)
}
}
fn visible_tabs(mode: ContentMode) -> &'static [ContentTab] {
match mode {
ContentMode::Installed => ContentTab::ALL,
ContentMode::Discover => ContentTab::DISCOVERY,
}
}
fn cycle_tab(current: ContentTab, tabs: &[ContentTab], forward: bool) -> ContentTab {
let index = tabs.iter().position(|tab| *tab == current).unwrap_or(0);
if forward {
tabs[(index + 1) % tabs.len()]
} else {
tabs[if index == 0 {
tabs.len() - 1
} else {
index - 1
}]
}
}
#[allow(clippy::too_many_arguments)]
@@ -72,10 +107,14 @@ pub fn render(
area: Rect,
focused: FocusedArea,
tab: ContentTab,
mode: ContentMode,
instance: Option<&crate::instance::InstanceConfig>,
mods_state: &mut super::list::ContentListState,
mods_discovery_state: &mut DiscoveryState,
resource_packs_state: &mut super::list::ContentListState,
resource_packs_discovery_state: &mut DiscoveryState,
shaders_state: &mut super::list::ContentListState,
shaders_discovery_state: &mut DiscoveryState,
worlds_state: &mut super::list::ContentListState,
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
@@ -91,7 +130,8 @@ pub fn render(
theme.border()
};
let tab_titles: Vec<Span> = ContentTab::ALL
let tabs = visible_tabs(mode);
let tab_titles: Vec<Span> = tabs
.iter()
.enumerate()
.flat_map(|(i, t)| {
@@ -102,7 +142,7 @@ pub fn render(
Style::default().fg(theme.text_dim()),
));
}
if i == tab.index() {
if tabs.get(i) == Some(&tab) {
let style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
@@ -118,8 +158,17 @@ pub fn render(
.collect();
let search_line = match tab {
ContentTab::Mods if mode == ContentMode::Discover => {
mods_discovery_state.search.title_line()
}
ContentTab::Mods => mods_state.search.title_line(),
ContentTab::ResourcePacks if mode == ContentMode::Discover => {
resource_packs_discovery_state.search.title_line()
}
ContentTab::ResourcePacks => resource_packs_state.search.title_line(),
ContentTab::Shaders if mode == ContentMode::Discover => {
shaders_discovery_state.search.title_line()
}
ContentTab::Shaders => shaders_state.search.title_line(),
ContentTab::Worlds => worlds_state.search.title_line(),
ContentTab::Screenshots => screenshots_state.search.title_line(),
@@ -132,8 +181,24 @@ pub fn render(
}
};
let mode_color = match mode {
ContentMode::Installed => theme.success(),
ContentMode::Discover => theme.accent(),
};
let mut content_titles = vec![
Span::styled(
format!(" {} ", mode.label()),
Style::default()
.fg(theme.background())
.bg(mode_color)
.add_modifier(Modifier::BOLD),
),
Span::raw(" "),
];
content_titles.extend(tab_titles);
let mut block = Block::default()
.title_top(Line::from(tab_titles))
.title_top(Line::from(content_titles))
.borders(Borders::ALL)
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
@@ -145,31 +210,42 @@ pub fn render(
// keybinds change depending on which tab is active and whether
// the content panel or instances panel has focus
let kb: Option<&[(&str, &str)]> = if is_focused {
Some(match tab {
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
Some(match (mode, tab) {
(ContentMode::Discover, _) => &[
("j/k", " navigate"),
("h/l", " tabs"),
("/", " search"),
("Tab", " installed"),
],
(ContentMode::Installed, ContentTab::Mods)
| (ContentMode::Installed, ContentTab::ResourcePacks)
| (ContentMode::Installed, ContentTab::Shaders) => &[
("j/k", " navigate"),
("⏎", " toggle"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
("Tab", " discover"),
],
ContentTab::Worlds => &[
(ContentMode::Installed, ContentTab::Worlds) => &[
("j/k", " navigate"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
("Tab", " discover"),
],
ContentTab::Screenshots => &[
(ContentMode::Installed, ContentTab::Screenshots) => &[
("Shift+HJKL", " grid"),
("⏎", " open"),
("d", " delete"),
("Shift+⏎", " open dir"),
("h/l", " tabs"),
("/", " search"),
("Tab", " discover"),
],
ContentTab::Logs => {
(ContentMode::Installed, ContentTab::Logs) => {
if logs_state.viewer_focused {
&[
("j/k", " scroll"),
@@ -177,6 +253,7 @@ pub fn render(
("d", " delete"),
("Esc", " back"),
("/", " search"),
("Tab", " discover"),
]
} else {
&[
@@ -185,6 +262,7 @@ pub fn render(
("d", " delete"),
("h/l", " tabs"),
("/", " search"),
("Tab", " discover"),
]
}
}
@@ -220,28 +298,39 @@ pub fn render(
match tab {
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
mods_discovery_state,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("mods");
mods_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_mod,
".jar",
);
mods_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
mods_state,
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
mods_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
mods_state,
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
@@ -252,28 +341,39 @@ pub fn render(
}
ContentTab::ResourcePacks => {
if let Some(instance) = instance {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
resource_packs_discovery_state,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("resourcepacks");
resource_packs_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_resource_pack,
".zip",
);
resource_packs_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
resource_packs_state,
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
resource_packs_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
resource_packs_state,
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
@@ -284,28 +384,39 @@ pub fn render(
}
ContentTab::Shaders => {
if let Some(instance) = instance {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
if mode == ContentMode::Discover {
render_discovery(
frame,
content_area,
shaders_discovery_state,
is_focused,
"Searching Modrinth...",
picker,
);
} else {
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)
.join(".minecraft")
.join("shaderpacks");
shaders_state.start_load(
&content_dir,
&instance.name,
crate::instance::scan_one_shader,
".zip",
);
shaders_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
shaders_state,
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
shaders_state.watch_dir(content_dir);
}
super::list::render(
frame,
content_area,
shaders_state,
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
@@ -387,6 +498,27 @@ pub fn render(
}
}
fn render_discovery(
frame: &mut Frame,
area: Rect,
state: &mut DiscoveryState,
is_focused: bool,
loading_text: &str,
picker: &ratatui_image::picker::Picker,
) {
state.set_viewport_rows(area.height);
let empty_text = state.empty_text().to_string();
super::list::render(
frame,
area,
&mut state.list,
is_focused,
loading_text,
&empty_text,
picker,
);
}
// the header bar above the content tabs, showing instance name, loader info,
// and a spinner/error indicator when the instance is running or crashed
pub fn title(
@@ -491,3 +623,28 @@ pub fn title(
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn discovery_navigation_only_cycles_downloadable_tabs() {
assert_eq!(
ContentTab::Shaders.next_for_mode(ContentMode::Discover),
ContentTab::Mods
);
assert_eq!(
ContentTab::Mods.previous_for_mode(ContentMode::Discover),
ContentTab::Shaders
);
}
#[test]
fn discovery_navigation_recovers_from_hidden_local_tab() {
assert_eq!(
ContentTab::Logs.next_for_mode(ContentMode::Discover),
ContentTab::ResourcePacks
);
}
}