feat(content): add Modrinth discovery mode
This commit is contained in:
1 parent
ddfe0e26b2
commit
774a6c6723
12 files changed
+1552
-107
No files matched your search
@@ -513,7 +513,7 @@ fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
|
||||
}
|
||||
|
||||
// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
||||
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||
let b = IconCell {
|
||||
symbol: '\u{2584}',
|
||||
bg_r: 50,
|
||||
|
||||
@@ -53,6 +53,114 @@ pub struct MrpackFile {
|
||||
|
||||
use crate::instance::models::ModLoader;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiscoveryKind {
|
||||
Mod,
|
||||
ResourcePack,
|
||||
Shader,
|
||||
}
|
||||
|
||||
impl DiscoveryKind {
|
||||
fn project_type(self) -> &'static str {
|
||||
match self {
|
||||
Self::Mod => "mod",
|
||||
Self::ResourcePack => "resourcepack",
|
||||
Self::Shader => "shader",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DiscoveryProject {
|
||||
pub id: String,
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub downloads: u64,
|
||||
pub icon_url: Option<String>,
|
||||
pub icon_bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DiscoveryResults {
|
||||
pub projects: Vec<DiscoveryProject>,
|
||||
pub total_hits: usize,
|
||||
}
|
||||
|
||||
pub async fn search_discovery(
|
||||
client: &crate::net::HttpClient,
|
||||
kind: DiscoveryKind,
|
||||
query: &str,
|
||||
game_version: &str,
|
||||
loader: ModLoader,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||
let facets = discovery_facets(kind, game_version, loader);
|
||||
let mut configuration = modrinth_api::apis::configuration::Configuration::new();
|
||||
configuration.client = client.inner().clone();
|
||||
configuration.user_agent = Some(format!(
|
||||
"rmcl/{} (Minecraft Launcher)",
|
||||
env!("CARGO_PKG_VERSION")
|
||||
));
|
||||
let query = (!query.trim().is_empty()).then_some(query.trim());
|
||||
let index = if query.is_some() {
|
||||
"relevance"
|
||||
} else {
|
||||
"downloads"
|
||||
};
|
||||
let results = modrinth_api::apis::projects_api::search_projects(
|
||||
&configuration,
|
||||
query,
|
||||
Some(&facets),
|
||||
Some(index),
|
||||
Some(offset.min(i32::MAX as usize) as i32),
|
||||
Some(limit.min(i32::MAX as usize) as i32),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| crate::net::NetError::Parse(format!("Modrinth search failed: {e}")))?;
|
||||
|
||||
Ok(DiscoveryResults {
|
||||
total_hits: results.total_hits.max(0) as usize,
|
||||
projects: results
|
||||
.hits
|
||||
.into_iter()
|
||||
.map(|project| DiscoveryProject {
|
||||
id: project.project_id,
|
||||
slug: project.slug,
|
||||
title: project.title,
|
||||
description: project.description,
|
||||
downloads: project.downloads.max(0) as u64,
|
||||
icon_url: project.icon_url.flatten(),
|
||||
icon_bytes: None,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn discovery_facets(kind: DiscoveryKind, game_version: &str, loader: ModLoader) -> String {
|
||||
let mut facets = vec![vec![format!("project_type:{}", kind.project_type())]];
|
||||
if !game_version.is_empty() {
|
||||
facets.push(vec![format!("versions:{game_version}")]);
|
||||
}
|
||||
if kind == DiscoveryKind::Mod
|
||||
&& let Some(loader) = loader_facet(loader)
|
||||
{
|
||||
facets.push(vec![format!("categories:{loader}")]);
|
||||
}
|
||||
serde_json::to_string(&facets).unwrap_or_else(|_| "[]".to_string())
|
||||
}
|
||||
|
||||
fn loader_facet(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"),
|
||||
}
|
||||
}
|
||||
|
||||
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
|
||||
// checks in priority order and returns the first match.
|
||||
pub fn loader_from_dependencies(
|
||||
@@ -208,6 +316,77 @@ pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_mod_facets_include_instance_compatibility() {
|
||||
let facets = discovery_facets(DiscoveryKind::Mod, "1.21.1", ModLoader::Fabric);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
|
||||
vec![
|
||||
vec!["project_type:mod"],
|
||||
vec!["versions:1.21.1"],
|
||||
vec!["categories:fabric"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_resource_pack_facets_do_not_require_loader() {
|
||||
let facets = discovery_facets(DiscoveryKind::ResourcePack, "1.20.1", ModLoader::Forge);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Vec<Vec<String>>>(&facets).unwrap(),
|
||||
vec![vec!["project_type:resourcepack"], vec!["versions:1.20.1"]]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "hits live Modrinth API"]
|
||||
async fn search_discovery_returns_compatible_mods() {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let result = search_discovery(
|
||||
&client,
|
||||
DiscoveryKind::Mod,
|
||||
"sodium",
|
||||
"1.21.1",
|
||||
ModLoader::Fabric,
|
||||
0,
|
||||
20,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.projects.is_empty());
|
||||
assert!(result.total_hits >= result.projects.len());
|
||||
let icon_url = result
|
||||
.projects
|
||||
.iter()
|
||||
.find_map(|project| project.icon_url.as_deref())
|
||||
.expect("expected at least one project icon");
|
||||
let icon = client.get_bytes(icon_url).await.unwrap();
|
||||
assert!(
|
||||
image::load_from_memory(&icon).is_ok(),
|
||||
"failed to decode {icon_url}; first bytes: {:?}",
|
||||
icon.get(..icon.len().min(16))
|
||||
);
|
||||
|
||||
let next = search_discovery(
|
||||
&client,
|
||||
DiscoveryKind::Mod,
|
||||
"sodium",
|
||||
"1.21.1",
|
||||
ModLoader::Fabric,
|
||||
20,
|
||||
20,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!next.projects.is_empty());
|
||||
assert!(
|
||||
next.projects
|
||||
.iter()
|
||||
.all(|project| !result.projects.iter().any(|first| first.id == project.id))
|
||||
);
|
||||
}
|
||||
|
||||
// covers each branch of url_encode: unreserved bytes pass through; the
|
||||
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
|
||||
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
|
||||
|
||||
@@ -21,10 +21,14 @@ pub struct App {
|
||||
pub(super) focused: FocusedArea,
|
||||
pub(super) pre_overlay_focused: FocusedArea,
|
||||
pub(super) content_tab: widgets::content::ContentTab,
|
||||
pub(super) content_mode: widgets::content::ContentMode,
|
||||
pub(super) instances_state: instances::State,
|
||||
pub(super) mods_state: widgets::content::list::ContentListState,
|
||||
pub(super) mods_discovery_state: widgets::content::DiscoveryState,
|
||||
pub(super) resource_packs_state: widgets::content::list::ContentListState,
|
||||
pub(super) resource_packs_discovery_state: widgets::content::DiscoveryState,
|
||||
pub(super) shaders_state: widgets::content::list::ContentListState,
|
||||
pub(super) shaders_discovery_state: widgets::content::DiscoveryState,
|
||||
pub(super) worlds_state: widgets::content::list::ContentListState,
|
||||
pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState,
|
||||
pub(super) logs_state: widgets::logs_viewer::LogsState,
|
||||
@@ -81,10 +85,20 @@ impl App {
|
||||
focused: FocusedArea::default(),
|
||||
pre_overlay_focused: FocusedArea::default(),
|
||||
content_tab: widgets::content::ContentTab::default(),
|
||||
content_mode: widgets::content::ContentMode::default(),
|
||||
instances_state,
|
||||
mods_state: widgets::content::list::ContentListState::default(),
|
||||
mods_discovery_state: widgets::content::DiscoveryState::new(
|
||||
crate::net::modrinth::DiscoveryKind::Mod,
|
||||
),
|
||||
resource_packs_state: widgets::content::list::ContentListState::default(),
|
||||
resource_packs_discovery_state: widgets::content::DiscoveryState::new(
|
||||
crate::net::modrinth::DiscoveryKind::ResourcePack,
|
||||
),
|
||||
shaders_state: widgets::content::list::ContentListState::default(),
|
||||
shaders_discovery_state: widgets::content::DiscoveryState::new(
|
||||
crate::net::modrinth::DiscoveryKind::Shader,
|
||||
),
|
||||
worlds_state: widgets::content::list::ContentListState::default(),
|
||||
logs_state: widgets::logs_viewer::LogsState::default(),
|
||||
account_state: widgets::account::AccountState::default(),
|
||||
|
||||
@@ -38,14 +38,38 @@ impl App {
|
||||
self.mods_state.drain_watcher();
|
||||
self.mods_state.request_image_loads(&self.picker);
|
||||
self.mods_state.drain_image_loads(&self.picker);
|
||||
self.mods_discovery_state.drain_pending();
|
||||
self.mods_discovery_state.list.drain_pending();
|
||||
self.mods_discovery_state
|
||||
.list
|
||||
.request_image_loads(&self.picker);
|
||||
self.mods_discovery_state
|
||||
.list
|
||||
.drain_image_loads(&self.picker);
|
||||
self.resource_packs_state.drain_pending();
|
||||
self.resource_packs_state.drain_watcher();
|
||||
self.resource_packs_state.request_image_loads(&self.picker);
|
||||
self.resource_packs_state.drain_image_loads(&self.picker);
|
||||
self.resource_packs_discovery_state.drain_pending();
|
||||
self.resource_packs_discovery_state.list.drain_pending();
|
||||
self.resource_packs_discovery_state
|
||||
.list
|
||||
.request_image_loads(&self.picker);
|
||||
self.resource_packs_discovery_state
|
||||
.list
|
||||
.drain_image_loads(&self.picker);
|
||||
self.shaders_state.drain_pending();
|
||||
self.shaders_state.drain_watcher();
|
||||
self.shaders_state.request_image_loads(&self.picker);
|
||||
self.shaders_state.drain_image_loads(&self.picker);
|
||||
self.shaders_discovery_state.drain_pending();
|
||||
self.shaders_discovery_state.list.drain_pending();
|
||||
self.shaders_discovery_state
|
||||
.list
|
||||
.request_image_loads(&self.picker);
|
||||
self.shaders_discovery_state
|
||||
.list
|
||||
.drain_image_loads(&self.picker);
|
||||
self.worlds_state.drain_pending();
|
||||
self.worlds_state.drain_watcher();
|
||||
self.worlds_state.request_image_loads(&self.picker);
|
||||
@@ -57,6 +81,7 @@ impl App {
|
||||
self.screenshots_state.drain_pending_entries();
|
||||
self.screenshots_state.request_visible_loads();
|
||||
self.create_screenshot_protocols();
|
||||
self.ensure_active_discovery_loaded();
|
||||
let progress_active = progress::is_active();
|
||||
let spinner_active = progress_active || crate::running::has_active();
|
||||
if spinner_active {
|
||||
|
||||
+166
-9
@@ -143,7 +143,33 @@ impl App {
|
||||
|
||||
// content area delegates to whichever tab is active.
|
||||
// worlds use the same list navigation without the toggle
|
||||
if self.focused == FocusedArea::Content {
|
||||
if self.focused == FocusedArea::Content
|
||||
&& self.content_mode == widgets::content::ContentMode::Discover
|
||||
{
|
||||
let (handled, submit_search) = {
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => Some(&mut self.mods_discovery_state),
|
||||
widgets::content::ContentTab::ResourcePacks => {
|
||||
Some(&mut self.resource_packs_discovery_state)
|
||||
}
|
||||
widgets::content::ContentTab::Shaders => {
|
||||
Some(&mut self.shaders_discovery_state)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(state) = state {
|
||||
widgets::content::discovery::handle_key(&key_event, state)
|
||||
} else {
|
||||
(false, false)
|
||||
}
|
||||
};
|
||||
if submit_search {
|
||||
self.spawn_active_discovery_search();
|
||||
}
|
||||
if handled {
|
||||
return Ok(());
|
||||
}
|
||||
} else if self.focused == FocusedArea::Content {
|
||||
if self.content_tab == widgets::content::ContentTab::Logs {
|
||||
if key_event.code == KeyCode::Char('d')
|
||||
&& !self.logs_state.search.active
|
||||
@@ -374,15 +400,27 @@ impl App {
|
||||
self.pre_overlay_focused = self.focused;
|
||||
self.focused = FocusedArea::OverviewExpanded;
|
||||
}
|
||||
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right
|
||||
if self.focused == FocusedArea::Content =>
|
||||
{
|
||||
self.content_tab = self.content_tab.next();
|
||||
KeyCode::Tab if self.focused == FocusedArea::Content => {
|
||||
self.content_mode = self.content_mode.toggle();
|
||||
if self.content_mode == widgets::content::ContentMode::Discover
|
||||
&& !matches!(
|
||||
self.content_tab,
|
||||
widgets::content::ContentTab::Mods
|
||||
| widgets::content::ContentTab::ResourcePacks
|
||||
| widgets::content::ContentTab::Shaders
|
||||
)
|
||||
{
|
||||
self.content_tab = widgets::content::ContentTab::Mods;
|
||||
}
|
||||
self.ensure_active_discovery_loaded();
|
||||
}
|
||||
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left
|
||||
if self.focused == FocusedArea::Content =>
|
||||
{
|
||||
self.content_tab = self.content_tab.previous();
|
||||
KeyCode::Char('l') | KeyCode::Right if self.focused == FocusedArea::Content => {
|
||||
self.content_tab = self.content_tab.next_for_mode(self.content_mode);
|
||||
self.ensure_active_discovery_loaded();
|
||||
}
|
||||
KeyCode::Char('h') | KeyCode::Left if self.focused == FocusedArea::Content => {
|
||||
self.content_tab = self.content_tab.previous_for_mode(self.content_mode);
|
||||
self.ensure_active_discovery_loaded();
|
||||
}
|
||||
KeyCode::Char('d')
|
||||
if self.focused == FocusedArea::Instances
|
||||
@@ -477,6 +515,125 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn ensure_active_discovery_loaded(&mut self) {
|
||||
if self.content_mode != widgets::content::ContentMode::Discover {
|
||||
return;
|
||||
}
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let needs_search = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => self.mods_discovery_state.needs_search(&instance),
|
||||
widgets::content::ContentTab::ResourcePacks => {
|
||||
self.resource_packs_discovery_state.needs_search(&instance)
|
||||
}
|
||||
widgets::content::ContentTab::Shaders => {
|
||||
self.shaders_discovery_state.needs_search(&instance)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if needs_search {
|
||||
self.spawn_active_discovery_search();
|
||||
} else {
|
||||
self.spawn_active_discovery_page();
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_active_discovery_search(&mut self) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
|
||||
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
|
||||
widgets::content::ContentTab::Shaders => &mut self.shaders_discovery_state,
|
||||
_ => return,
|
||||
};
|
||||
let kind = state.kind;
|
||||
let query = state.search.query.clone();
|
||||
let request = state.begin_search(&instance);
|
||||
Self::spawn_discovery_request(instance, kind, query, request);
|
||||
}
|
||||
|
||||
fn spawn_active_discovery_page(&mut self) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let state = match self.content_tab {
|
||||
widgets::content::ContentTab::Mods => &mut self.mods_discovery_state,
|
||||
widgets::content::ContentTab::ResourcePacks => &mut self.resource_packs_discovery_state,
|
||||
widgets::content::ContentTab::Shaders => &mut self.shaders_discovery_state,
|
||||
_ => return,
|
||||
};
|
||||
let kind = state.kind;
|
||||
let query = state.search.query.clone();
|
||||
let Some(request) = state.begin_next_page() else {
|
||||
return;
|
||||
};
|
||||
Self::spawn_discovery_request(instance, kind, query, request);
|
||||
}
|
||||
|
||||
fn spawn_discovery_request(
|
||||
instance: crate::instance::InstanceConfig,
|
||||
kind: crate::net::modrinth::DiscoveryKind,
|
||||
query: String,
|
||||
request: widgets::content::discovery::DiscoveryRequest,
|
||||
) {
|
||||
let widgets::content::discovery::DiscoveryRequest {
|
||||
generation,
|
||||
offset,
|
||||
pending,
|
||||
stream,
|
||||
} = request;
|
||||
|
||||
tokio::spawn(async move {
|
||||
let client = crate::net::HttpClient::new();
|
||||
let result = crate::net::modrinth::search_discovery(
|
||||
&client,
|
||||
kind,
|
||||
&query,
|
||||
&instance.game_version,
|
||||
instance.loader,
|
||||
offset,
|
||||
widgets::content::discovery::PAGE_SIZE,
|
||||
)
|
||||
.await;
|
||||
let result = match result {
|
||||
Ok(results) => {
|
||||
let total_hits = results.total_hits;
|
||||
let received = results.projects.len();
|
||||
for mut project in results.projects {
|
||||
let icon = project.icon_url.take().map(|url| {
|
||||
(
|
||||
url,
|
||||
project.id.clone(),
|
||||
std::path::PathBuf::from(&project.id),
|
||||
)
|
||||
});
|
||||
if !stream.send(widgets::content::discovery::project_entry(project)) {
|
||||
break;
|
||||
}
|
||||
if let Some((url, file_stem, path)) = icon {
|
||||
let client = client.clone();
|
||||
let stream = stream.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Ok(bytes) = client.get_bytes(&url).await {
|
||||
stream.send_icon(file_stem, path, bytes);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(widgets::content::discovery::DiscoveryPageResult {
|
||||
received,
|
||||
total_hits,
|
||||
})
|
||||
}
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
widgets::content::DiscoveryState::push_result(&pending, generation, offset, result);
|
||||
});
|
||||
}
|
||||
|
||||
fn delete_config_profile(&mut self, profile: &str) -> color_eyre::Result<()> {
|
||||
let instances = self.instance_manager.load_all();
|
||||
for instance in instances
|
||||
|
||||
@@ -57,10 +57,14 @@ impl App {
|
||||
main_chunks[1],
|
||||
self.focused,
|
||||
self.content_tab,
|
||||
self.content_mode,
|
||||
self.instances_state.selected_instance(),
|
||||
&mut self.mods_state,
|
||||
&mut self.mods_discovery_state,
|
||||
&mut self.resource_packs_state,
|
||||
&mut self.resource_packs_discovery_state,
|
||||
&mut self.shaders_state,
|
||||
&mut self.shaders_discovery_state,
|
||||
&mut self.worlds_state,
|
||||
&mut self.screenshots_state,
|
||||
&mut self.logs_state,
|
||||
|
||||
@@ -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
@@ -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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user