feat(content): refine Modrinth discovery streaming

This commit is contained in:
objz committed 2026-07-22 22:22:00 +02:00
1 parent 774a6c6723
commit 19c47cdf7b
13 files changed
+840 -552

No files matched your search

Generated
+9 -358
View File
@@ -279,15 +279,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "bs58"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
"tinyvec",
]
[[package]]
name = "bumpalo"
version = "3.20.2"
@@ -560,26 +551,6 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -848,7 +819,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"powerfmt",
"serde_core",
]
[[package]]
@@ -990,12 +960,6 @@ dependencies = [
"litrs",
]
[[package]]
name = "dyn-clone"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "either"
version = "1.15.0"
@@ -1171,21 +1135,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -1402,19 +1351,13 @@ dependencies = [
"futures-core",
"futures-sink",
"http",
"indexmap 2.14.0",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.5"
@@ -1575,22 +1518,6 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "hyper-tls"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
dependencies = [
"bytes",
"http-body-util",
"hyper",
"hyper-util",
"native-tls",
"tokio",
"tokio-native-tls",
"tower-service",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
@@ -1609,11 +1536,9 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -1795,17 +1720,6 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5"
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown 0.12.3",
"serde",
]
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -2245,22 +2159,6 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c8dda44ff03a2f238717214da50f65d5a53b45cd213a7370424ffdb6fae815"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "minecraft-msa-auth"
version = "0.4.0"
@@ -2303,21 +2201,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "modrinth-api"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4164a0589b01583016844796046a54a868bbce0526e9c6cb5e1f898c32f5a1f3"
dependencies = [
"reqwest",
"serde",
"serde_json",
"serde_repr",
"serde_with",
"url",
"uuid",
]
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -2328,23 +2211,6 @@ dependencies = [
"pxfm",
]
[[package]]
name = "native-tls"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
dependencies = [
"libc",
"log",
"openssl",
"openssl-probe",
"openssl-sys",
"schannel",
"security-framework",
"security-framework-sys",
"tempfile",
]
[[package]]
name = "nix"
version = "0.29.0"
@@ -2531,49 +2397,6 @@ dependencies = [
"pathdiff",
]
[[package]]
name = "openssl"
version = "0.10.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
dependencies = [
"bitflags 2.11.1",
"cfg-if",
"foreign-types",
"libc",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-sys"
version = "0.9.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -3340,22 +3163,16 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64",
"bytes",
"encoding_rs",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-tls",
"hyper-util",
"js-sys",
"log",
"mime",
"mime_guess",
"native-tls",
"percent-encoding",
"pin-project-lite",
"quinn",
@@ -3366,7 +3183,6 @@ dependencies = [
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
@@ -3412,7 +3228,6 @@ dependencies = [
"libcasr",
"log",
"minecraft-msa-auth",
"modrinth-api",
"notify",
"oauth2",
"open",
@@ -3610,68 +3425,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
dependencies = [
"dyn-clone",
"ref-cast",
"serde",
"serde_json",
]
[[package]]
name = "schemars"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"
dependencies = [
"dyn-clone",
"ref-cast",
"serde",
"serde_json",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.11.1",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "semver"
version = "1.0.28"
@@ -3744,17 +3503,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_repr"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "serde_spanned"
version = "1.1.1"
@@ -3776,38 +3524,6 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_with"
version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
dependencies = [
"base64",
"bs58",
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.14.0",
"schemars 0.9.0",
"schemars 1.2.1",
"serde_core",
"serde_json",
"serde_with_macros",
"time",
]
[[package]]
name = "serde_with_macros"
version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
dependencies = [
"darling 0.23.0",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "sha1"
version = "0.11.0"
@@ -3989,17 +3705,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
@@ -4020,27 +3725,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.11.1",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "tachyonfx"
version = "0.25.0"
@@ -4304,16 +3988,6 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
dependencies = [
"native-tls",
"tokio",
]
[[package]]
name = "tokio-rustls"
version = "0.26.4"
@@ -4343,7 +4017,7 @@ version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"
dependencies = [
"indexmap 2.14.0",
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
@@ -4367,7 +4041,7 @@ version = "0.25.11+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
dependencies = [
"indexmap 2.14.0",
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
@@ -4612,12 +4286,6 @@ version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -4709,12 +4377,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -4870,7 +4532,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap 2.14.0",
"indexmap",
"wasm-encoder",
"wasmparser",
]
@@ -4896,7 +4558,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags 2.11.1",
"hashbrown 0.15.5",
"indexmap 2.14.0",
"indexmap",
"semver",
]
@@ -5139,17 +4801,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.2.0"
@@ -5418,7 +5069,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
"indexmap 2.14.0",
"indexmap",
"prettyplease",
"syn 2.0.117",
"wasm-metadata",
@@ -5449,7 +5100,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags 2.11.1",
"indexmap 2.14.0",
"indexmap",
"log",
"serde",
"serde_derive",
@@ -5468,7 +5119,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap 2.14.0",
"indexmap",
"log",
"semver",
"serde",
@@ -5621,7 +5272,7 @@ dependencies = [
"flate2",
"getrandom 0.4.2",
"hmac",
"indexmap 2.14.0",
"indexmap",
"lzma-rust2",
"memchr",
"pbkdf2",
-1
View File
@@ -53,7 +53,6 @@ ratatui-image = { version = "10.0.6", default-features = false, features = ["cro
image = { version = "0.25", default-features = false, features = ["png", "webp"] }
zip = "8.5.1"
minecraft-msa-auth = "0.4.0"
modrinth-api = "2.7.1"
oauth2 = "5.0.0"
open = "5"
which = "8.0.2"
+7 -1
View File
@@ -38,6 +38,12 @@ impl Default for HttpClient {
}
}
impl NetError {
pub(crate) fn is_retryable(&self) -> bool {
matches!(self, Self::StatusError { status: 429, .. }) || is_retryable(self)
}
}
impl HttpClient {
pub fn new() -> Self {
let user_agent = format!("rmcl/{} (Minecraft Launcher)", env!("CARGO_PKG_VERSION"));
@@ -146,7 +152,7 @@ const RETRY_BASE_DELAY_MS: u64 = 500;
async fn sleep_before_retry(kind: &str, url: &str, attempt: u32, err: &NetError) {
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt);
tracing::warn!(
tracing::debug!(
"{} failed, retrying after {}ms (attempt {}/{}): {}: {}",
kind,
delay,
+111 -47
View File
@@ -87,6 +87,39 @@ pub struct DiscoveryResults {
pub total_hits: usize,
}
#[derive(Debug, Deserialize)]
struct DiscoverySearchResponse {
hits: Vec<DiscoverySearchHit>,
#[serde(default)]
total_hits: i64,
}
#[derive(Debug, Deserialize)]
struct DiscoverySearchHit {
project_id: String,
slug: String,
title: String,
description: String,
#[serde(default)]
downloads: i64,
#[serde(default)]
icon_url: Option<String>,
}
impl From<DiscoverySearchHit> for DiscoveryProject {
fn from(project: DiscoverySearchHit) -> Self {
Self {
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.filter(|url| !url.trim().is_empty()),
icon_bytes: None,
}
}
}
pub async fn search_discovery(
client: &crate::net::HttpClient,
kind: DiscoveryKind,
@@ -97,43 +130,25 @@ pub async fn search_discovery(
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 {
let query = query.trim();
let index = if query.is_empty() {
"downloads"
} else {
"relevance"
};
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}")))?;
let url = format!(
"{API_BASE}/search?query={}&facets={}&index={index}&offset={offset}&limit={limit}",
url_encode(query),
url_encode(&facets),
);
let results: DiscoverySearchResponse = client.get_json(&url).await?;
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,
})
.map(DiscoveryProject::from)
.collect(),
})
}
@@ -338,6 +353,46 @@ mod tests {
);
}
#[test]
fn discovery_search_ignores_new_modrinth_enum_values() {
let response: DiscoverySearchResponse = serde_json::from_str(
r#"{
"hits": [{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"downloads": 42,
"icon_url": null,
"client_side": "unknown",
"server_side": "unknown"
}],
"total_hits": 1
}"#,
)
.unwrap();
assert_eq!(response.hits.len(), 1);
assert_eq!(response.hits[0].project_id, "project-id");
assert_eq!(response.total_hits, 1);
}
#[test]
fn discovery_search_treats_blank_icon_urls_as_missing() {
let hit: DiscoverySearchHit = serde_json::from_str(
r#"{
"project_id": "project-id",
"slug": "example",
"title": "Example",
"description": "Example project",
"icon_url": " "
}"#,
)
.unwrap();
assert!(DiscoveryProject::from(hit).icon_url.is_none());
}
#[tokio::test]
#[ignore = "hits live Modrinth API"]
async fn search_discovery_returns_compatible_mods() {
@@ -349,7 +404,7 @@ mod tests {
"1.21.1",
ModLoader::Fabric,
0,
20,
100,
)
.await
.unwrap();
@@ -368,23 +423,32 @@ mod tests {
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))
);
let mut seen = result
.projects
.iter()
.map(|project| project.id.clone())
.collect::<std::collections::HashSet<_>>();
let end = result.total_hits.min(300);
for offset in (100..end).step_by(100) {
let next = search_discovery(
&client,
DiscoveryKind::Mod,
"sodium",
"1.21.1",
ModLoader::Fabric,
offset,
100,
)
.await
.unwrap();
assert!(!next.projects.is_empty(), "empty page at offset {offset}");
assert!(
next.projects
.iter()
.all(|project| seen.insert(project.id.clone())),
"duplicate project at offset {offset}"
);
}
}
// covers each branch of url_encode: unreserved bytes pass through; the
+63 -26
View File
@@ -146,7 +146,7 @@ impl App {
if self.focused == FocusedArea::Content
&& self.content_mode == widgets::content::ContentMode::Discover
{
let (handled, submit_search) = {
let handled = {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_discovery_state),
widgets::content::ContentTab::ResourcePacks => {
@@ -160,13 +160,16 @@ impl App {
if let Some(state) = state {
widgets::content::discovery::handle_key(&key_event, state)
} else {
(false, false)
false
}
};
if submit_search {
self.spawn_active_discovery_search();
}
if handled {
if matches!(
key_event.code,
KeyCode::Char('j') | KeyCode::Char('k') | KeyCode::Down | KeyCode::Up
) {
self.spawn_active_discovery_page();
}
return Ok(());
}
} else if self.focused == FocusedArea::Content {
@@ -522,17 +525,22 @@ impl App {
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,
let (needs_search, search_due) = match self.content_tab {
widgets::content::ContentTab::Mods => (
self.mods_discovery_state.needs_search(&instance),
self.mods_discovery_state.search_due(),
),
widgets::content::ContentTab::ResourcePacks => (
self.resource_packs_discovery_state.needs_search(&instance),
self.resource_packs_discovery_state.search_due(),
),
widgets::content::ContentTab::Shaders => (
self.shaders_discovery_state.needs_search(&instance),
self.shaders_discovery_state.search_due(),
),
_ => (false, false),
};
if needs_search {
if needs_search || search_due {
self.spawn_active_discovery_search();
} else {
self.spawn_active_discovery_page();
@@ -584,6 +592,8 @@ impl App {
offset,
pending,
stream,
reconcile,
loaded_icon_stems,
} = request;
tokio::spawn(async move {
@@ -602,33 +612,60 @@ impl App {
Ok(results) => {
let total_hits = results.total_hits;
let received = results.projects.len();
let mut returned_stems = std::collections::HashSet::with_capacity(received);
let icon_slots = std::sync::Arc::new(tokio::sync::Semaphore::new(8));
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)) {
returned_stems.insert(project.id.clone());
let icon = (!loaded_icon_stems.contains(&project.id))
.then(|| project.icon_url.take())
.flatten()
.map(|url| {
(
url,
project.id.clone(),
std::path::PathBuf::from(&project.id),
)
});
if !stream.upsert(widgets::content::discovery::project_entry(project)) {
break;
}
if let Some((url, file_stem, path)) = icon {
let client = client.clone();
let stream = stream.clone();
let icon_slots = icon_slots.clone();
tokio::spawn(async move {
if let Ok(bytes) = client.get_bytes(&url).await {
stream.send_icon(file_stem, path, bytes);
let Ok(_permit) = icon_slots.acquire_owned().await else {
return;
};
match client.get_bytes(&url).await {
Ok(bytes) if !bytes.is_empty() => {
stream.send_icon(file_stem, path, bytes);
}
Ok(_) => tracing::debug!(
"Modrinth icon for '{}' was empty; using fallback",
file_stem
),
Err(error) => tracing::debug!(
"Failed to fetch Modrinth icon for '{}'; using fallback: {}",
file_stem,
error
),
}
});
}
}
if reconcile {
stream.retain(returned_stems);
}
Ok(widgets::content::discovery::DiscoveryPageResult {
received,
total_hits,
})
}
Err(error) => Err(error.to_string()),
Err(error) => Err(widgets::content::discovery::DiscoveryPageError {
retryable: error.is_retryable(),
message: error.to_string(),
}),
};
widgets::content::DiscoveryState::push_result(&pending, generation, offset, result);
});
+320 -24
View File
@@ -9,8 +9,12 @@ use crate::net::modrinth::{DiscoveryKind, DiscoveryProject};
use super::list::{ContentListState, ContentStream};
pub const PAGE_SIZE: usize = 20;
const PREFETCH_ITEMS: usize = 5;
pub const PAGE_SIZE: usize = 100;
const PREFETCH_VIEWPORTS: usize = 2;
const MIN_PREFETCH_ITEMS: usize = 10;
const SEARCH_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(300);
const PAGE_RETRY_BASE_DELAY: std::time::Duration = std::time::Duration::from_millis(500);
const PAGE_RETRY_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(8);
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentMode {
@@ -38,7 +42,12 @@ impl ContentMode {
pub struct PendingDiscoveryResult {
generation: u64,
offset: usize,
result: Result<DiscoveryPageResult, String>,
result: Result<DiscoveryPageResult, DiscoveryPageError>,
}
pub struct DiscoveryPageError {
pub message: String,
pub retryable: bool,
}
pub struct DiscoveryPageResult {
@@ -51,6 +60,8 @@ pub struct DiscoveryRequest {
pub offset: usize,
pub pending: PendingDiscovery,
pub stream: ContentStream,
pub reconcile: bool,
pub loaded_icon_stems: std::collections::HashSet<String>,
}
pub(crate) type PendingDiscovery = Arc<Mutex<Vec<PendingDiscoveryResult>>>;
@@ -69,6 +80,9 @@ pub struct DiscoveryState {
page_loading: bool,
exhausted: bool,
viewport_rows: u16,
search_changed_at: Option<std::time::Instant>,
retry_page_at: Option<std::time::Instant>,
page_retry_attempt: u32,
}
impl DiscoveryState {
@@ -87,6 +101,9 @@ impl DiscoveryState {
page_loading: false,
exhausted: false,
viewport_rows: 0,
search_changed_at: None,
retry_page_at: None,
page_retry_attempt: 0,
}
}
@@ -97,19 +114,42 @@ impl DiscoveryState {
pub fn begin_search(&mut self, instance: &InstanceConfig) -> DiscoveryRequest {
self.generation = self.generation.wrapping_add(1);
let context = discovery_context(instance);
let reconcile =
self.context.as_deref() == Some(context.as_str()) && !self.list.entries.is_empty();
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.search_changed_at = None;
self.retry_page_at = None;
self.page_retry_attempt = 0;
let loaded_icon_stems = if reconcile {
self.list
.entries
.iter()
.filter(|entry| entry.icon_bytes.is_some())
.map(|entry| entry.file_stem.clone())
.collect()
} else {
std::collections::HashSet::new()
};
let stream = if reconcile {
self.list.refresh_source_stream(context)
} else {
self.list.start_source_stream(context)
};
self.list.search.query.clone_from(&self.search.query);
self.list.set_search_filtering(false);
self.stream = Some(stream.clone());
DiscoveryRequest {
generation: self.generation,
offset: 0,
pending: self.pending.clone(),
stream,
reconcile,
loaded_icon_stems,
}
}
@@ -118,11 +158,21 @@ impl DiscoveryState {
return None;
}
self.page_loading = true;
self.retry_page_at = None;
let loaded_icon_stems = self
.list
.entries
.iter()
.filter(|entry| entry.icon_bytes.is_some())
.map(|entry| entry.file_stem.clone())
.collect();
Some(DiscoveryRequest {
generation: self.generation,
offset: self.next_offset,
pending: self.pending.clone(),
stream: self.stream.clone()?,
reconcile: false,
loaded_icon_stems,
})
}
@@ -130,11 +180,22 @@ impl DiscoveryState {
self.viewport_rows = rows;
}
pub fn search_due(&self) -> bool {
self.search_changed_at
.is_some_and(|changed| changed.elapsed() >= SEARCH_DEBOUNCE)
}
fn search_changed(&mut self) {
self.list.search.query.clone_from(&self.search.query);
self.list.set_search_filtering(false);
self.search_changed_at = Some(std::time::Instant::now());
}
pub fn push_result(
pending: &PendingDiscovery,
generation: u64,
offset: usize,
result: Result<DiscoveryPageResult, String>,
result: Result<DiscoveryPageResult, DiscoveryPageError>,
) {
if let Ok(mut pending) = pending.lock() {
pending.push(PendingDiscoveryResult {
@@ -163,11 +224,35 @@ impl DiscoveryState {
self.next_offset = pending.offset.saturating_add(result.received);
self.exhausted = result.received == 0 || self.next_offset >= self.total_hits;
self.error = None;
self.retry_page_at = None;
self.page_retry_attempt = 0;
}
Err(error) => {
self.total_hits = 0;
self.error = Some(error);
self.exhausted = true;
if error.retryable {
let multiplier = 1u32 << self.page_retry_attempt.min(4);
let delay = PAGE_RETRY_BASE_DELAY
.saturating_mul(multiplier)
.min(PAGE_RETRY_MAX_DELAY);
self.page_retry_attempt = self.page_retry_attempt.saturating_add(1);
self.retry_page_at = Some(std::time::Instant::now() + delay);
tracing::debug!(
"Modrinth discovery page at offset {} failed; retrying in {:?}: {}",
pending.offset,
delay,
error.message
);
} else if pending.offset == 0 {
self.total_hits = 0;
self.error = Some(error.message);
self.exhausted = true;
} else {
tracing::warn!(
"Modrinth discovery page at offset {} failed: {}",
pending.offset,
error.message
);
self.exhausted = true;
}
}
}
}
@@ -180,20 +265,30 @@ impl DiscoveryState {
}
fn should_load_more(&self) -> bool {
if self.page_loading || self.exhausted || self.error.is_some() || self.stream.is_none() {
if self.page_loading
|| self.exhausted
|| self.error.is_some()
|| self.stream.is_none()
|| self.search_changed_at.is_some()
|| self
.retry_page_at
.is_some_and(|retry_at| std::time::Instant::now() < retry_at)
{
return false;
}
let viewport_items = usize::from(self.viewport_rows).div_ceil(3);
let prefetch_items = viewport_items
.saturating_mul(PREFETCH_VIEWPORTS)
.max(MIN_PREFETCH_ITEMS);
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()
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) {
pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> bool {
if state.search.active {
let refresh = key_event.code == KeyCode::Enter
|| (key_event.code == KeyCode::Esc && !state.search.query.is_empty());
let previous_query = state.search.query.clone();
match key_event.code {
KeyCode::Enter => state.search.confirm(),
KeyCode::Esc => state.search.deactivate(),
@@ -201,16 +296,17 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> (bool, bo
KeyCode::Char(c) => state.search.push(c),
_ => {}
}
return (true, refresh);
let changed = state.search.query != previous_query;
if changed {
state.search_changed();
}
return true;
}
if key_event.code == KeyCode::Char('/') {
state.search.activate();
return (true, false);
return true;
}
(
super::list::handle_key_no_toggle(key_event, &mut state.list),
false,
)
super::list::handle_key_no_toggle(key_event, &mut state.list)
}
fn discovery_context(instance: &InstanceConfig) -> String {
@@ -261,6 +357,7 @@ fn format_downloads(downloads: u64) -> String {
mod tests {
use super::*;
use chrono::Utc;
use crossterm::event::KeyModifiers;
fn instance(name: &str, version: &str) -> InstanceConfig {
InstanceConfig {
@@ -321,6 +418,7 @@ mod tests {
#[test]
fn next_page_prefetches_before_selection_reaches_the_end() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.set_viewport_rows(30);
let instance = instance("one", "1.21.1");
let first = state.begin_search(&instance);
for index in 0..PAGE_SIZE {
@@ -341,19 +439,19 @@ mod tests {
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 100,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(80);
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() {
fn large_page_fills_a_tall_viewport_without_another_request() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.set_viewport_rows(90);
let first = state.begin_search(&instance("one", "1.21.1"));
@@ -375,11 +473,209 @@ mod tests {
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 100,
total_hits: 300,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
}
#[test]
fn typing_keeps_loaded_results_until_remote_search_is_due() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let request = state.begin_search(&instance("one", "1.21.1"));
for title in ["Sodium", "Lithium"] {
assert!(request.stream.send(project_entry(DiscoveryProject {
id: title.to_lowercase(),
slug: title.to_lowercase(),
title: title.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
})));
}
state.list.drain_pending();
handle_key(
&KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE),
&mut state,
);
for character in "sod".chars() {
handle_key(
&KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE),
&mut state,
);
}
assert_eq!(state.list.filtered_indices(), vec![0, 1]);
assert_eq!(state.list.search.query, "sod");
assert!(!state.search_due());
state.search_changed_at = Some(std::time::Instant::now() - SEARCH_DEBOUNCE);
assert!(state.search_due());
}
#[test]
fn search_refresh_keeps_rows_until_the_diff_arrives() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let instance = instance("one", "1.21.1");
let initial = state.begin_search(&instance);
for title in ["Sodium", "Lithium"] {
assert!(initial.stream.upsert(project_entry(DiscoveryProject {
id: title.to_lowercase(),
slug: title.to_lowercase(),
title: title.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: (title == "Sodium").then(|| vec![1, 2, 3]),
})));
}
state.list.drain_pending();
state.search.query = "sodium".to_owned();
state.search_changed();
let refresh = state.begin_search(&instance);
assert!(refresh.reconcile);
assert!(refresh.loaded_icon_stems.contains("sodium"));
assert!(!refresh.loaded_icon_stems.contains("lithium"));
assert_eq!(state.list.entries.len(), 2);
assert!(!state.list.loading);
}
#[test]
fn pagination_continues_across_multiple_pages() {
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.upsert(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: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE - MIN_PREFETCH_ITEMS);
let second = state.begin_next_page().unwrap();
for index in PAGE_SIZE..PAGE_SIZE * 2 {
assert!(second.stream.upsert(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(
&second.pending,
second.generation,
second.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE * 2 - MIN_PREFETCH_ITEMS);
let third = state.begin_next_page().unwrap();
assert_eq!(third.offset, PAGE_SIZE * 2);
}
#[test]
fn permanent_pagination_failure_stops_without_discarding_loaded_entries() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
for index in 0..PAGE_SIZE {
assert!(first.stream.upsert(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: 300,
}),
);
state.drain_pending();
state.list.list_state.selected = Some(PAGE_SIZE - MIN_PREFETCH_ITEMS);
let second = state.begin_next_page().unwrap();
DiscoveryState::push_result(
&second.pending,
second.generation,
second.offset,
Err(DiscoveryPageError {
message: "invalid response".to_owned(),
retryable: false,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
assert_eq!(state.list.entries.len(), PAGE_SIZE);
assert!(state.exhausted);
}
#[test]
fn transient_pagination_failure_retries_the_same_offset_after_a_delay() {
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
let first = state.begin_search(&instance("one", "1.21.1"));
DiscoveryState::push_result(
&first.pending,
first.generation,
first.offset,
Ok(DiscoveryPageResult {
received: PAGE_SIZE,
total_hits: 300,
}),
);
state.drain_pending();
let second = state.begin_next_page().unwrap();
DiscoveryState::push_result(
&second.pending,
second.generation,
second.offset,
Err(DiscoveryPageError {
message: "connection reset".to_owned(),
retryable: true,
}),
);
state.drain_pending();
assert!(state.begin_next_page().is_none());
state.retry_page_at = Some(std::time::Instant::now() - PAGE_RETRY_BASE_DELAY);
assert_eq!(state.begin_next_page().unwrap().offset, PAGE_SIZE);
}
}
+174 -23
View File
@@ -62,10 +62,34 @@ impl ContentStream {
false
}
}
pub fn upsert(&self, entry: ContentEntry) -> bool {
if self.sender.send(ContentStreamUpdate::Upsert(entry)).is_ok() {
crate::tui::request_redraw();
true
} else {
false
}
}
pub fn retain(&self, file_stems: HashSet<String>) -> bool {
if self
.sender
.send(ContentStreamUpdate::Retain(file_stems))
.is_ok()
{
crate::tui::request_redraw();
true
} else {
false
}
}
}
enum ContentStreamUpdate {
Entry(ContentEntry),
Upsert(ContentEntry),
Retain(HashSet<String>),
Icon {
file_stem: String,
path: std::path::PathBuf,
@@ -109,6 +133,7 @@ pub struct ContentListState {
images_dirty: bool,
display_metadata: HashMap<String, DisplayMetadata>,
pub search: crate::tui::widgets::search::SearchState,
filter_search: bool,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
stream_rx: Option<mpsc::Receiver<ContentStreamUpdate>>,
@@ -143,6 +168,7 @@ impl Default for ContentListState {
images_dirty: true,
display_metadata: HashMap::new(),
search: crate::tui::widgets::search::SearchState::default(),
filter_search: true,
cache: HashMap::new(),
stream_rx: None,
stream_order: ContentStreamOrder::default(),
@@ -164,6 +190,14 @@ impl ContentListState {
self.start_stream_with_order(source, ContentStreamOrder::Source)
}
pub fn refresh_source_stream(&mut self, source: impl Into<String>) -> ContentStream {
let (sender, receiver) = mpsc::channel();
self.stream_rx = Some(receiver);
self.stream_order = ContentStreamOrder::Source;
self.loaded_for = Some(source.into());
ContentStream { sender }
}
fn start_stream_with_order(
&mut self,
source: impl Into<String>,
@@ -293,6 +327,7 @@ impl ContentListState {
let mut received = false;
let mut received_count = 0usize;
let mut finished = false;
let mut restore_selected = None;
loop {
match rx.try_recv() {
Ok(ContentStreamUpdate::Entry(entry)) => {
@@ -314,6 +349,39 @@ impl ContentListState {
ContentStreamOrder::Source => self.entries.push(entry),
}
}
Ok(ContentStreamUpdate::Upsert(mut entry)) => {
received = true;
self.images_dirty = true;
received_count += 1;
self.display_metadata
.insert(entry.file_stem.clone(), display_metadata(&entry));
if let Some(existing) = self
.entries
.iter_mut()
.find(|existing| existing.file_stem == entry.file_stem)
{
if entry.icon_bytes.is_none() {
entry.icon_bytes = existing.icon_bytes.take();
entry.icon_lines = existing.icon_lines.take();
}
*existing = entry;
} else {
self.entries.push(entry);
}
}
Ok(ContentStreamUpdate::Retain(file_stems)) => {
let selected_stem = self.selected_file_stem();
self.entries
.retain(|entry| file_stems.contains(&entry.file_stem));
self.display_metadata
.retain(|stem, _| file_stems.contains(stem));
self.image_protocols
.retain(|stem, _| file_stems.contains(stem));
self.requested_images
.retain(|stem| file_stems.contains(stem));
restore_selected = Some(selected_stem);
self.images_dirty = true;
}
Ok(ContentStreamUpdate::Icon {
file_stem,
path,
@@ -338,6 +406,10 @@ impl ContentListState {
}
}
if let Some(selected_stem) = restore_selected {
self.restore_selected_file_stem(selected_stem.as_deref());
}
if received || finished {
self.loading = false;
if received_count > 0 {
@@ -556,11 +628,46 @@ impl ContentListState {
self.entries
.iter()
.enumerate()
.filter(|(_, e)| self.search.matches(&e.name))
.filter(|(_, entry)| {
!self.filter_search
|| self.search.matches(&entry.name)
|| self.search.matches(&entry.description)
})
.map(|(i, _)| i)
.collect()
}
pub fn set_search_filtering(&mut self, enabled: bool) {
let selected_stem = self.selected_file_stem();
self.filter_search = enabled;
self.restore_selected_file_stem(selected_stem.as_deref());
}
fn selected_file_stem(&self) -> Option<String> {
let filtered = self.filtered_indices();
let entry_index = self
.list_state
.selected
.and_then(|index| filtered.get(index))?;
self.entries
.get(*entry_index)
.map(|entry| entry.file_stem.clone())
}
fn restore_selected_file_stem(&mut self, file_stem: Option<&str>) {
let filtered = self.filtered_indices();
self.list_state.selected = file_stem
.and_then(|stem| {
filtered.iter().position(|index| {
self.entries
.get(*index)
.is_some_and(|entry| entry.file_stem == stem)
})
})
.or_else(|| (!filtered.is_empty()).then_some(0));
self.update_scrollbar();
}
pub fn pending_delete(&self) -> Option<PendingContentDelete> {
let filtered = self.filtered_indices();
let real_idx = self.list_state.selected.and_then(|i| filtered.get(i))?;
@@ -926,6 +1033,8 @@ pub fn render(
let entries = &state.entries;
let display_metadata = &state.display_metadata;
let filtered_rows = &filtered;
let search = &state.search;
let ready_image_stems: HashSet<String> = state.image_protocols.keys().cloned().collect();
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
@@ -934,7 +1043,10 @@ pub fn render(
let metadata = display_metadata.get(&entry.file_stem);
let enabled = entry.enabled;
let icon_pixels = &entry.icon_lines;
let has_image = entry.icon_bytes.is_some();
// Keep rendering the terminal fallback until the asynchronous image
// decoder has produced a protocol. Invalid and unsupported images
// therefore remain visible as a question mark instead of blank space.
let has_image = ready_image_stems.contains(&entry.file_stem);
let protocol_columns = protocol_icon_columns(entry, picker) as usize;
let show_selected = is_focused && context.is_selected;
let use_mc_colors = enabled;
@@ -990,11 +1102,7 @@ pub fn render(
if compact {
let mut line = Vec::new();
line.push(selector.clone());
if use_mc_colors {
line.extend(parse_mc_text(name, name_style));
} else {
line.push(Span::styled(strip_mc_codes(name), name_style));
}
line.extend(searchable_spans(search, name, name_style, use_mc_colors));
let item = Text::from(vec![Line::from(line)]).style(Style::default().bg(background));
(item, 1)
@@ -1017,11 +1125,7 @@ pub fn render(
protocol_columns,
));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
} else {
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
line_0.extend(searchable_spans(search, name, name_style, use_mc_colors));
let mut lines = vec![Line::from(line_0)];
@@ -1034,7 +1138,7 @@ pub fn render(
protocol_columns,
));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.to_string(), description_style));
row.extend(search.highlight_spans(stripped_desc, description_style));
lines.push(Line::from(row));
}
@@ -1055,11 +1159,7 @@ pub fn render(
} else {
let mut line_0 = Vec::new();
line_0.push(selector.clone());
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
} else {
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
line_0.extend(searchable_spans(search, name, name_style, use_mc_colors));
let mut lines = vec![Line::from(line_0)];
@@ -1069,10 +1169,9 @@ pub fn render(
} else {
Span::raw(" ")
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.to_string(), description_style),
]));
let mut description = vec![pad];
description.extend(search.highlight_spans(stripped_desc, description_style));
lines.push(Line::from(description));
}
let height = lines.len() as u16;
@@ -1205,6 +1304,21 @@ fn mc_color(code: char) -> Option<Color> {
}
}
fn searchable_spans(
search: &crate::tui::widgets::search::SearchState,
text: &str,
base_style: Style,
use_mc_colors: bool,
) -> Vec<Span<'static>> {
if !search.is_empty() {
search.highlight_spans(&strip_mc_codes(text), base_style)
} else if use_mc_colors {
parse_mc_text(text, base_style)
} else {
vec![Span::styled(strip_mc_codes(text), base_style)]
}
}
// parses minecraft's section-sign (U+00A7) formatting codes into styled spans.
// handles colors (0-f), bold (l), strikethrough (m), underline (n), italic (o), reset (r)
fn parse_mc_text(text: &str, base_style: Style) -> Vec<Span<'static>> {
@@ -1367,7 +1481,7 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use std::{collections::HashSet, path::PathBuf};
use crate::instance::content::mods::ContentEntry;
@@ -1443,4 +1557,41 @@ mod tests {
["Zulu", "Alpha"]
);
}
#[test]
fn source_refresh_reconciles_without_rebuilding_unchanged_entries() {
let mut state = ContentListState::default();
let initial = state.start_source_stream("remote");
let mut alpha = entry("Alpha");
alpha.icon_bytes = Some(vec![1, 2, 3]);
assert!(initial.upsert(alpha));
assert!(initial.upsert(entry("Beta")));
assert!(initial.upsert(entry("Gamma")));
state.drain_pending();
state.list_state.selected = Some(0);
let refresh = state.refresh_source_stream("remote");
let mut alpha_update = entry("Alpha");
alpha_update.description = "Updated".to_owned();
assert!(refresh.upsert(alpha_update));
assert!(refresh.upsert(entry("Delta")));
assert!(refresh.retain(HashSet::from(["alpha".to_owned(), "delta".to_owned(),])));
state.drain_pending();
assert_eq!(
state
.entries
.iter()
.map(|entry| entry.name.as_str())
.collect::<Vec<_>>(),
["Alpha", "Delta"]
);
assert_eq!(state.entries[0].description, "Updated");
assert_eq!(
state.entries[0].icon_bytes.as_deref(),
Some([1, 2, 3].as_slice())
);
assert_eq!(state.list_state.selected, Some(0));
assert!(!state.loading);
}
}
+3 -4
View File
@@ -291,10 +291,9 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
),
])
} else {
Line::from(vec![
selector.clone(),
Span::styled(instance.name.as_str(), name_style),
])
let mut spans = vec![selector.clone()];
spans.extend(state.search.highlight_spans(&instance.name, name_style));
Line::from(spans)
};
let (meta_text, meta_text_style) = match get_run_state(&instance.name) {
+62 -37
View File
@@ -182,21 +182,41 @@ impl LogsState {
}
fn display_count(&self) -> usize {
self.entries.len() + if self.has_live() { 1 } else { 0 }
self.display_indices().len()
}
fn live_display_name(&self) -> String {
self.entries
.first()
.map(|entry| entry.name.trim_end_matches(".log").to_owned())
.unwrap_or_else(|| "Live".to_owned())
}
fn display_indices(&self) -> Vec<Option<usize>> {
let mut indices = Vec::new();
if self.has_live() && self.search.matches(&self.live_display_name()) {
indices.push(None);
}
indices.extend(
self.entries
.iter()
.enumerate()
.filter(|(_, entry)| self.search.matches(entry.name.trim_end_matches(".log")))
.map(|(index, _)| Some(index)),
);
indices
}
fn is_live_selected(&self) -> bool {
self.has_live() && self.list_state.selected == Some(0)
self.list_state
.selected
.and_then(|selected| self.display_indices().get(selected).copied())
== Some(None)
}
fn file_index_for_selected(&self) -> Option<usize> {
let sel = self.list_state.selected?;
let offset = if self.has_live() { 1 } else { 0 };
if sel < offset {
None
} else {
Some(sel - offset)
}
let selected = self.list_state.selected?;
self.display_indices().get(selected).copied().flatten()
}
fn load_selected_content(&mut self) {
@@ -228,6 +248,15 @@ impl LogsState {
fn update_scrollbar(&mut self) {
let count = self.display_count();
let max = count.saturating_sub(1);
if count == 0 {
self.list_state.selected = None;
} else if self
.list_state
.selected
.is_none_or(|selected| selected >= count)
{
self.list_state.selected = Some(max);
}
let pos = self.list_state.selected.unwrap_or(0);
self.scrollbar_state = ScrollbarState::new(max).position(pos);
}
@@ -345,21 +374,25 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
KeyCode::Enter => {
state.search.confirm();
state.list_state.selected = Some(0);
state.load_selected_content();
state.update_scrollbar();
}
KeyCode::Esc => {
state.search.deactivate();
state.list_state.selected = Some(0);
state.load_selected_content();
state.update_scrollbar();
}
KeyCode::Backspace => {
state.search.pop();
state.list_state.selected = Some(0);
state.load_selected_content();
state.update_scrollbar();
}
KeyCode::Char(c) => {
state.search.push(c);
state.list_state.selected = Some(0);
state.load_selected_content();
state.update_scrollbar();
}
_ => {}
@@ -435,17 +468,11 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
let [list_area, viewer_area] =
Layout::horizontal([Constraint::Length(30), Constraint::Min(0)]).areas(area);
render_list(frame, list_area, state, is_focused, has_live);
render_list(frame, list_area, state, is_focused);
render_viewer(frame, viewer_area, state, is_focused, has_live);
}
fn render_list(
frame: &mut Frame,
area: Rect,
state: &mut LogsState,
is_focused: bool,
has_live: bool,
) {
fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) {
let theme = THEME.as_ref();
let list_focused = is_focused && !state.viewer_focused;
let border_color = if list_focused {
@@ -464,21 +491,21 @@ fn render_list(
let display_count = state.display_count();
let entries_snapshot: Vec<(String, bool)> = {
let mut v = Vec::new();
if has_live {
let live_name = state
.entries
.first()
.map(|e| e.name.trim_end_matches(".log"))
.unwrap_or("Live");
v.push((live_name.to_string(), true));
}
for e in &state.entries {
v.push((e.name.trim_end_matches(".log").to_string(), false));
}
v
};
let entries_snapshot: Vec<(String, bool)> = state
.display_indices()
.into_iter()
.map(|index| match index {
Some(index) => (
state.entries[index]
.name
.trim_end_matches(".log")
.to_owned(),
false,
),
None => (state.live_display_name(), true),
})
.collect();
let search = &state.search;
let builder = ListBuilder::new(move |context| {
let (name, is_live) = &entries_snapshot[context.index];
@@ -509,11 +536,9 @@ fn render_list(
} else {
Span::raw(" ")
};
let item = ratatui::text::Text::from(Line::from(vec![
selector,
Span::styled(name.clone(), style),
]))
.style(Style::default().bg(bg));
let mut spans = vec![selector];
spans.extend(search.highlight_spans(name, style));
let item = ratatui::text::Text::from(Line::from(spans)).style(Style::default().bg(bg));
(item, 1)
});
@@ -150,10 +150,10 @@ fn render_version_step(state: &ImportWizardState, area: Rect, buf: &mut ratatui:
.map(|version| {
let game_ver = version.game_versions.first().cloned().unwrap_or_default();
let loader = version.loaders.first().cloned().unwrap_or_default();
ListItem::new(Line::from(Span::styled(
format!("{} {} {}", version.version_number, game_ver, loader),
ListItem::new(state.version_search.highlight_line(
&format!("{} {} {}", version.version_number, game_ver, loader),
Style::default().fg(theme.text()),
)))
))
})
.collect();
@@ -186,10 +186,10 @@ fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe
} else {
" (snapshot)".to_string()
};
ListItem::new(Line::from(Span::styled(
format!("{}{}", version.id, suffix),
ListItem::new(state.version_search.highlight_line(
&format!("{}{}", version.id, suffix),
Style::default().fg(theme.text()),
)))
))
})
.collect();
+45 -14
View File
@@ -11,7 +11,6 @@ use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
style::{Modifier, Style},
text::Span,
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};
use ratatui_image::{Resize, StatefulImage, protocol::StatefulProtocol};
@@ -127,14 +126,15 @@ impl ScreenshotsState {
// only load images that are currently visible (or about to be).
// no point decoding a 4K screenshot the user can't even see yet
pub fn request_visible_loads(&mut self) {
if self.entries.is_empty() {
let filtered = self.filtered_indices();
if filtered.is_empty() {
return;
}
let first = self.scroll_row * self.cols;
let last = ((self.scroll_row + self.visible_rows + 1) * self.cols).min(self.entries.len());
let last = ((self.scroll_row + self.visible_rows + 1) * self.cols).min(filtered.len());
for idx in first..last {
for &idx in filtered.iter().take(last).skip(first) {
if !self.protocols.contains_key(&idx) && self.requested.insert(idx) {
let path = self.entries[idx].path.clone();
let pending = self.pending_images.clone();
@@ -173,13 +173,25 @@ impl ScreenshotsState {
if self.cols == 0 {
return 0;
}
self.entries.len().div_ceil(self.cols)
self.filtered_indices().len().div_ceil(self.cols)
}
fn filtered_indices(&self) -> Vec<usize> {
self.entries
.iter()
.enumerate()
.filter(|(_, entry)| self.search.matches(&entry.name))
.map(|(index, _)| index)
.collect()
}
pub fn pending_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let entry = self.entries.get(self.selected)?;
let entry = self
.filtered_indices()
.get(self.selected)
.and_then(|index| self.entries.get(*index))?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.path.clone(),
@@ -191,11 +203,12 @@ impl ScreenshotsState {
self.protocols.clear();
self.requested.clear();
if self.entries.is_empty() {
let visible_count = self.filtered_indices().len();
if visible_count == 0 {
self.selected = 0;
self.scroll_row = 0;
} else {
self.selected = self.selected.min(self.entries.len().saturating_sub(1));
self.selected = self.selected.min(visible_count.saturating_sub(1));
self.ensure_visible();
}
}
@@ -207,18 +220,22 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
KeyCode::Enter => {
state.search.confirm();
state.selected = 0;
state.scroll_row = 0;
}
KeyCode::Esc => {
state.search.deactivate();
state.selected = 0;
state.scroll_row = 0;
}
KeyCode::Backspace => {
state.search.pop();
state.selected = 0;
state.scroll_row = 0;
}
KeyCode::Char(c) => {
state.search.push(c);
state.selected = 0;
state.scroll_row = 0;
}
_ => {}
}
@@ -249,7 +266,9 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
true
}
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(entry) = state.entries.get(state.selected)
if let Some(entry) = filtered
.get(state.selected)
.and_then(|index| state.entries.get(*index))
&& let Some(dir) = entry.path.parent()
&& let Err(e) = open::that_detached(dir)
{
@@ -258,7 +277,9 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
true
}
KeyCode::Enter => {
if let Some(entry) = state.entries.get(state.selected)
if let Some(entry) = filtered
.get(state.selected)
.and_then(|index| state.entries.get(*index))
&& let Err(e) = open::that_detached(&entry.path)
{
tracing::error!("Failed to open file: {}", e);
@@ -314,6 +335,15 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
return;
}
let filtered = state.filtered_indices();
if filtered.is_empty() {
frame.render_widget(
Paragraph::new("No matching screenshots.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
}
let min_cols = (area.width / MAX_CELL_WIDTH).max(1) as usize;
let max_cols = (area.width / MIN_CELL_WIDTH).max(1) as usize;
let target_cols = (area.width / TARGET_CELL_WIDTH).max(1) as usize;
@@ -342,10 +372,11 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
for vr in 0..visible_rows {
for vc in 0..cols {
let idx = (state.scroll_row + vr) * cols + vc;
if idx >= state.entries.len() {
let display_index = (state.scroll_row + vr) * cols + vc;
if display_index >= filtered.len() {
break;
}
let idx = filtered[display_index];
let raw_x = area.x + vc as u16 * cell_width;
let raw_y = area.y + vr as u16 * cell_height;
@@ -363,7 +394,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
continue;
}
let is_selected = is_focused && idx == state.selected;
let is_selected = is_focused && display_index == state.selected;
let [img_area, name_area] =
Layout::vertical([Constraint::Min(0), Constraint::Length(NAME_ROW_HEIGHT)])
@@ -390,7 +421,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
name
};
frame.render_widget(
Paragraph::new(Span::styled(truncated, name_style)),
Paragraph::new(state.search.highlight_line(truncated, name_style)),
name_area,
);
}
+40 -11
View File
@@ -49,11 +49,11 @@ impl SearchState {
text.to_lowercase().contains(&self.query.to_lowercase())
}
// splits a line into spans, bolding+underlining the parts that match
// the query so they pop out visually
pub fn highlight_line<'a>(&self, text: &'a str, base_style: Style) -> Line<'a> {
// splits text into spans, bolding+underlining the parts that match
// the query so every searchable widget can use the same styling
pub fn highlight_spans(&self, text: &str, base_style: Style) -> Vec<Span<'static>> {
if self.query.is_empty() {
return Line::from(Span::styled(text, base_style));
return vec![Span::styled(text.to_owned(), base_style)];
}
let query_lower = self.query.to_lowercase();
@@ -62,25 +62,32 @@ impl SearchState {
let mut last = 0;
for (start, _) in text_lower.match_indices(&query_lower) {
let end = start + query_lower.len();
if !text.is_char_boundary(start) || !text.is_char_boundary(end) {
continue;
}
if start > last {
spans.push(Span::styled(&text[last..start], base_style));
spans.push(Span::styled(text[last..start].to_owned(), base_style));
}
spans.push(Span::styled(
&text[start..start + self.query.len()],
text[start..end].to_owned(),
base_style.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
));
last = start + self.query.len();
last = end;
}
if last < text.len() {
spans.push(Span::styled(&text[last..], base_style));
spans.push(Span::styled(text[last..].to_owned(), base_style));
}
if spans.is_empty() {
Line::from(Span::styled(text, base_style))
} else {
Line::from(spans)
spans.push(Span::styled(text.to_owned(), base_style));
}
spans
}
pub fn highlight_line(&self, text: &str, base_style: Style) -> Line<'static> {
Line::from(self.highlight_spans(text, base_style))
}
// renders the "/ query█" indicator in the block title bar
@@ -152,4 +159,26 @@ mod tests {
assert!(s.active);
assert_eq!(s.query, "te");
}
#[test]
fn highlight_spans_marks_each_case_insensitive_match() {
let search = SearchState {
query: "di".to_owned(),
..SearchState::default()
};
let spans = search.highlight_spans("Discovery DISK", Style::default());
assert_eq!(
spans
.iter()
.map(|span| span.content.as_ref())
.collect::<String>(),
"Discovery DISK"
);
assert!(spans[0].style.add_modifier.contains(Modifier::BOLD));
assert!(spans[0].style.add_modifier.contains(Modifier::UNDERLINED));
assert!(spans[2].style.add_modifier.contains(Modifier::BOLD));
assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED));
}
}