fix(content): retain local files and resolve icons and categories safely

This commit is contained in:
objz committed 2026-09-24 20:22:34 +02:00
1 parent a7ace33ae1
commit af6d0b003b
6 files changed
+160 -138

No files matched your search

+64 -3
View File
@@ -71,6 +71,7 @@ struct Category {
struct SearchCategory {
id: u32,
slug: String,
name: String,
class_id: Option<u32>,
}
@@ -90,7 +91,15 @@ async fn search_category_id(
class_id: u32,
slug: &str,
) -> Result<Option<u32>, NetError> {
let categories = SEARCH_CATEGORIES
let categories = load_search_categories(client, api_key).await?;
Ok(category_id(categories, class_id, slug))
}
async fn load_search_categories(
client: &HttpClient,
api_key: &str,
) -> Result<&'static Vec<SearchCategory>, NetError> {
SEARCH_CATEGORIES
.get_or_try_init(|| async {
let response: ApiResponse<Vec<SearchCategory>> = get(
client,
@@ -98,10 +107,59 @@ async fn search_category_id(
&format!("{API_BASE}/categories?gameId={MINECRAFT_GAME_ID}"),
)
.await?;
crate::feedback::request_redraw();
Ok::<_, NetError>(response.data)
})
.await?;
Ok(category_id(categories, class_id, slug))
.await
}
pub(crate) async fn ensure_discovery_categories(client: &HttpClient) -> Result<(), NetError> {
if let Some(api_key) = api_key() {
load_search_categories(client, api_key).await?;
}
Ok(())
}
pub(crate) fn discovery_categories(class_id: u32) -> Vec<(&'static str, &'static str)> {
let mut categories = SEARCH_CATEGORIES
.get()
.into_iter()
.flatten()
.filter(|category| category.class_id == Some(class_id))
.map(|category| (category.slug.as_str(), category.name.as_str()))
.collect::<Vec<_>>();
categories.sort_by(|a, b| a.1.cmp(b.1));
categories
}
#[cfg(test)]
pub(crate) fn seed_discovery_categories_for_test() {
let categories = [
(MODS_CLASS_ID, "library-api", "API and Library"),
(MODS_CLASS_ID, "performance", "Performance"),
(MODS_CLASS_ID, "magic", "Magic"),
(MODS_CLASS_ID, "create", "Create"),
(MODPACKS_CLASS_ID, "tech", "Tech"),
(DATA_PACKS_CLASS_ID, "magic", "Magic"),
]
.into_iter()
.enumerate()
.map(|(id, (class_id, slug, name))| SearchCategory {
id: id as u32,
class_id: Some(class_id),
slug: slug.to_owned(),
name: name.to_owned(),
})
.collect();
let _ = SEARCH_CATEGORIES.set(categories);
}
pub(crate) fn discovery_class_id(kind: ContentKind, modpacks: bool) -> u32 {
if modpacks {
MODPACKS_CLASS_ID
} else {
class_id(kind)
}
}
#[derive(Debug, Deserialize)]
@@ -281,6 +339,9 @@ async fn search(
offset: usize,
limit: usize,
) -> Result<DiscoveryResults, NetError> {
if let Err(error) = load_search_categories(client, api_key).await {
tracing::warn!("CurseForge categories unavailable: {error}");
}
let loader = loader.and_then(loader_type);
// Multiple selected categories use OR; leave them local until categoryIds semantics are confirmed.
let category = if let [slug] = included_categories {
+1 -1
View File
@@ -5,7 +5,7 @@ use super::*;
#[test]
fn search_category_ids_match_the_selected_class() {
let response: ApiResponse<Vec<SearchCategory>> = serde_json::from_str(r#"{"data":[{"id":6,"slug":"mc-mods","classId":null},{"id":11,"slug":"magic","classId":6},{"id":22,"slug":"magic","classId":4471}]}"#).unwrap();
let response: ApiResponse<Vec<SearchCategory>> = serde_json::from_str(r#"{"data":[{"id":6,"slug":"mc-mods","name":"Mods","classId":null},{"id":11,"slug":"magic","name":"Magic","classId":6},{"id":22,"slug":"magic","name":"Magic","classId":4471}]}"#).unwrap();
assert_eq!(category_id(&response.data, 6, "magic"), Some(11));
assert_eq!(category_id(&response.data, 4471, "magic"), Some(22));
assert_eq!(category_id(&response.data, 12, "magic"), None);
@@ -231,6 +231,7 @@ fn filters_match_environment_and_include_exclude_categories() {
#[test]
fn preferred_provider_categories_only_map_shared_meanings() {
crate::net::curseforge::seed_discovery_categories_for_test();
let map =
|slug, from, to, kind, modpacks| category_for_provider(slug, from, to, kind, modpacks);
assert_eq!(
@@ -309,6 +310,7 @@ fn preferred_provider_categories_only_map_shared_meanings() {
#[test]
fn curseforge_discovery_uses_its_categories_and_supported_sorts() {
crate::net::curseforge::seed_discovery_categories_for_test();
let mut state = DiscoveryState::new(ContentKind::Mod);
state.category_provider = "curseforge".to_owned();
assert!(
+60
View File
@@ -613,6 +613,7 @@ fn discovery_stream_shows_each_row_after_its_icon_is_ready() {
state.show_source_rows_progressively();
let mut alpha = entry("Alpha");
alpha.provider_icon = true;
alpha.icon_bytes = Some(vec![1]);
stream.upsert(alpha);
stream.upsert(entry("Beta"));
state.drain_pending();
@@ -632,6 +633,8 @@ fn discovery_stream_shows_each_row_after_its_icon_is_ready() {
.push(PendingContentImage {
file_stem: "alpha".to_owned(),
path: state.entries[0].path.clone(),
source: None,
icon_bytes: vec![1],
icon_lines: crate::instance::content::fallback_icon(),
image: None,
});
@@ -639,6 +642,63 @@ fn discovery_stream_shows_each_row_after_its_icon_is_ready() {
assert_eq!(state.filtered_indices().len(), 2);
}
#[test]
fn stale_decoded_icon_does_not_replace_a_new_source_or_new_bytes() {
let mut state = ContentListState::default();
let mut project = entry("Alpha");
project.provider_project = Some(crate::instance::ProviderProject {
provider: "modrinth".to_owned(),
project_id: "123".to_owned(),
version_id: String::new(),
});
project.icon_bytes = Some(vec![1]);
state.entries.push(project.clone());
let stale = PendingContentImage {
file_stem: project.file_stem.clone(),
path: project.path.clone(),
source: project.provider_project.clone(),
icon_bytes: vec![1],
icon_lines: crate::instance::content::fallback_icon(),
image: None,
};
state.pending_entry_images.insert(project.file_stem.clone());
state.entries[0].provider_project.as_mut().unwrap().provider = "curseforge".to_owned();
state.pending_images.lock().unwrap().push(stale);
state.drain_image_loads(&ratatui_image::picker::Picker::halfblocks());
assert!(state.pending_entry_images.contains(&project.file_stem));
state.entries[0].provider_project = project.provider_project;
state.entries[0].icon_bytes = Some(vec![2]);
state
.pending_images
.lock()
.unwrap()
.push(PendingContentImage {
file_stem: project.file_stem.clone(),
path: project.path,
source: state.entries[0].provider_project.clone(),
icon_bytes: vec![1],
icon_lines: crate::instance::content::fallback_icon(),
image: None,
});
state.drain_image_loads(&ratatui_image::picker::Picker::halfblocks());
assert!(state.pending_entry_images.contains(&project.file_stem));
}
#[test]
fn current_version_keeps_unidentified_installed_files_visible() {
let mut state = ContentListState::default();
state.entries.push(entry("Local file"));
state.set_installed_options(
&crate::tui::widgets::content::discovery::DiscoveryFilters::default(),
5,
false,
"1.21.1",
false,
);
assert_eq!(state.filtered_indices(), [0]);
}
#[test]
fn stale_provider_icon_cannot_replace_a_new_provider_row() {
let mut state = ContentListState::default();
+18 -127
View File
@@ -283,6 +283,7 @@ pub(crate) enum DiscoveryTarget {
#[allow(clippy::too_many_arguments)]
async fn search_provider(
provider: Option<&dyn crate::instance::content::provider::ContentProvider>,
client: &crate::net::HttpClient,
enabled: bool,
target: &DiscoveryTarget,
query: &str,
@@ -292,6 +293,11 @@ async fn search_provider(
limit: usize,
) -> Option<Result<DiscoveryResults, crate::net::NetError>> {
let provider = provider.filter(|_| enabled)?;
if provider.id() == "curseforge"
&& let Err(error) = crate::net::curseforge::ensure_discovery_categories(client).await
{
tracing::warn!("CurseForge categories unavailable: {error}");
}
let (game_versions, excluded_versions) = match (&filters.game_version, target) {
(GameVersionFilter::Current, DiscoveryTarget::Content(content)) => {
(vec![content.instance.game_version.clone()], Vec::new())
@@ -416,6 +422,7 @@ pub(crate) fn spawn_provider_search(
crate::instance::content::provider::ProviderRegistry::configured(client.clone());
let modrinth_search = search_provider(
registry.get("modrinth"),
&client,
crate::config::SETTINGS
.read()
.content
@@ -429,6 +436,7 @@ pub(crate) fn spawn_provider_search(
);
let curseforge_search = search_provider(
registry.get("curseforge"),
&client,
crate::config::SETTINGS
.read()
.content
@@ -1020,128 +1028,10 @@ pub fn discovery_categories(
}
}
// Category slugs and names from CurseForge's Minecraft /v1/categories endpoint (gameId 432).
fn curseforge_categories(
kind: ContentKind,
modpacks: bool,
) -> &'static [(&'static str, &'static str)] {
if modpacks {
return &[
("adventure-and-rpg", "Adventure and RPG"),
("combat-pvp", "Combat / PvP"),
("expert", "Expert"),
("exploration", "Exploration"),
("extra-large", "Extra Large"),
("ftb-official-pack", "FTB Official Pack"),
("hardcore", "Hardcore"),
("horror", "Horror"),
("magic", "Magic"),
("map-based", "Map Based"),
("mini-game", "Mini Game"),
("multiplayer", "Multiplayer"),
("quests", "Quests"),
("rlcraft", "RLCraft"),
("sci-fi", "Sci-Fi"),
("skyblock", "Skyblock"),
("small-light", "Small / Light"),
("tech", "Tech"),
("vanilla", "Vanilla+"),
];
}
match kind {
ContentKind::Mod => &[
("addons-buildcraft", "Buildcraft"),
("addons-forestry", "Forestry"),
("addons-industrialcraft", "Industrial Craft"),
("addons-thermalexpansion", "Thermal Expansion"),
("addons-thaumcraft", "Thaumcraft"),
("addons-tinkers-construct", "Tinker's Construct"),
("adventure-rpg", "Adventure and RPG"),
("applied-energistics-2", "Applied Energistics 2"),
("armor-weapons-tools", "Armor, Tools, and Weapons"),
("blood-magic", "Blood Magic"),
("bug-fixes", "Bug Fixes"),
("cosmetic", "Cosmetic"),
("crafttweaker", "CraftTweaker"),
("create", "Create"),
("creativemode", "CreativeMode"),
("education", "Education"),
("farmers-delight", "Farmer's Delight"),
("galacticraft", "Galacticraft"),
("horror", "Horror"),
("integrated-dynamics", "Integrated Dynamics"),
("kubejs", "KubeJS"),
("library-api", "API and Library"),
("magic", "Magic"),
("map-information", "Map and Information"),
("mc-addons", "Addons"),
("mc-creator", "MCreator"),
("mc-food", "Food"),
("mc-miscellaneous", "Miscellaneous"),
("modjam-2025", "ModJam 2025"),
("performance", "Performance"),
("redstone", "Redstone"),
("refined-storage", "Refined Storage"),
("server-utility", "Server Utility"),
("skyblock", "Skyblock"),
("storage", "Storage"),
("technology", "Technology"),
("technology-automation", "Automation"),
("technology-energy", "Energy"),
("technology-farming", "Farming"),
("technology-genetics", "Genetics"),
(
"technology-item-fluid-energy-transport",
"Energy, Fluid, and Item Transport",
),
("technology-player-transport", "Player Transport"),
("technology-processing", "Processing"),
("twitch-integration", "Twitch Integration"),
("twilight-forest", "Twilight Forest"),
("utility-qol", "Utility & QoL"),
("world-biomes", "Biomes"),
("world-dimensions", "Dimensions"),
("world-gen", "World Gen"),
("world-mobs", "Mobs"),
("world-ores-resources", "Ores and Resources"),
("world-structures", "Structures"),
],
ContentKind::ResourcePack => &[
("animated", "Animated"),
("data-packs", "Data Packs"),
("five-twelve-x-and-beyond", "512x and Higher"),
("font-packs", "Font Packs"),
("medieval", "Medieval"),
("miscellaneous", "Miscellaneous"),
("mod-support", "Mod Support"),
("modern", "Modern"),
("modjam-2025", "ModJam 2025"),
("one-twenty-eight-x", "128x"),
("photo-realistic", "Photo Realistic"),
("sixteen-x", "16x"),
("sixty-four-x", "64x"),
("steampunk", "Steampunk"),
("thirty-two-x", "32x"),
("traditional", "Traditional"),
("two-fifty-six-x", "256x"),
],
ContentKind::Shader => &[
("fantasy", "Fantasy"),
("realistic", "Realistic"),
("vanilla", "Vanilla"),
],
ContentKind::DataPack => &[
("adventure", "Adventure"),
("fantasy", "Fantasy"),
("library", "Library"),
("magic", "Magic"),
("miscellaneous", "Miscellaneous"),
("mod-support", "Mod Support"),
("modjam-2025", "ModJam 2025"),
("tech", "Tech"),
("utility", "Utility"),
],
}
fn curseforge_categories(kind: ContentKind, modpacks: bool) -> Vec<(&'static str, &'static str)> {
crate::net::curseforge::discovery_categories(crate::net::curseforge::discovery_class_id(
kind, modpacks,
))
}
fn category_for_provider(
@@ -1154,12 +1044,12 @@ fn category_for_provider(
let from_categories = if from == "curseforge" {
curseforge_categories(kind, modpacks)
} else {
discovery_categories(kind, modpacks)
discovery_categories(kind, modpacks).to_vec()
};
let to_categories = if to == "curseforge" {
curseforge_categories(kind, modpacks)
} else {
discovery_categories(kind, modpacks)
discovery_categories(kind, modpacks).to_vec()
};
if from == to {
return to_categories
@@ -1317,11 +1207,11 @@ impl DiscoveryState {
+ self.filters.categories.len()
}
pub(crate) fn categories(&self) -> &'static [(&'static str, &'static str)] {
pub(crate) fn categories(&self) -> Vec<(&'static str, &'static str)> {
if !self.local_mode && self.category_provider == "curseforge" {
curseforge_categories(self.kind, self.modpacks)
} else {
discovery_categories(self.kind, self.modpacks)
discovery_categories(self.kind, self.modpacks).to_vec()
}
}
@@ -2168,7 +2058,8 @@ impl DiscoveryState {
self.filters.environment = self.filters.environment.next()
}
index => {
let Some((slug, _)) = self.categories().get(index - self.category_start()) else {
let categories = self.categories();
let Some((slug, _)) = categories.get(index - self.category_start()) else {
return;
};
match self.filters.categories.get(*slug) {
+15 -7
View File
@@ -217,6 +217,8 @@ impl FileSortMetadata {
struct PendingContentImage {
file_stem: String,
path: std::path::PathBuf,
source: Option<crate::instance::ProviderProject>,
icon_bytes: Vec<u8>,
icon_lines: Vec<Vec<IconCell>>,
image: Option<image::DynamicImage>,
}
@@ -740,6 +742,7 @@ impl ContentListState {
}
let file_stem = entry.file_stem.clone();
let path = entry.path.clone();
let source = entry.provider_project.clone();
let bytes = entry.icon_bytes.clone().unwrap_or_default();
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u32;
let columns = square_icon_columns(rows as u16, font_dimensions);
@@ -751,6 +754,8 @@ impl ContentListState {
return PendingContentImage {
file_stem,
path,
source,
icon_bytes: bytes,
icon_lines: crate::instance::content::fallback_icon(),
image: None,
};
@@ -775,6 +780,8 @@ impl ContentListState {
PendingContentImage {
file_stem,
path,
source,
icon_bytes: bytes,
icon_lines,
image,
}
@@ -799,11 +806,12 @@ impl ContentListState {
};
for result in images {
if let Some(entry) = self
.entries
.iter_mut()
.find(|entry| entry.file_stem == result.file_stem && entry.path == result.path)
{
if let Some(entry) = self.entries.iter_mut().find(|entry| {
entry.file_stem == result.file_stem
&& entry.path == result.path
&& entry.provider_project == result.source
&& entry.icon_bytes.as_ref() == Some(&result.icon_bytes)
}) {
self.pending_entry_images.remove(&result.file_stem);
self.filtered_cache.get_mut().take();
entry.icon_lines = Some(result.icon_lines);
@@ -1488,7 +1496,7 @@ impl ContentListState {
return true;
}
let Some(installed) = entry.provider_project.as_ref() else {
return false;
return filters.categories.is_empty() && filters.environment == EnvironmentFilter::Any;
};
let project = self
.project_metadata
@@ -1514,7 +1522,7 @@ impl ContentListState {
.version_metadata
.get(&(installed.provider.clone(), installed.version_id.clone()))
else {
return false;
return true; // No provider version to compare; keep locally installed content visible.
};
if let Some(specific) = specific {
let includes = specific