feat(library): page Artists from local catalog

Materialize source-scoped artist aggregates and FTS, then expose exact keyset pages and bounded A-Z metadata for the existing Artists rail.

Query the selected artist's albums through the indexed credit relationship with an independent bounded model, generation cancellation, artwork updates, and per-surface legacy fallback.

cx
This commit is contained in:
vicrodh committed 2026-08-23 12:17:08 -06:00
1 parent 299dcde5b4
commit 6fd83c42df
18 files changed
+3128 -36

No files matched your search

+479 -11
View File
@@ -10,8 +10,9 @@ use rusqlite::{
use crate::bootstrap::{BootstrapBatch, SourceCheckpoint, BOOTSTRAP_BATCH_ROWS};
use crate::model::{
AlbumCursor, AlbumPage, AlbumRecord, ProjectedTrack, QueryDescriptor, QuerySurface, SourceKey,
SourceKind, TrackCursor, TrackGroup, TrackPage, TrackRecord, TrackRef, TrackSort,
AlbumCursor, AlbumPage, AlbumRecord, ArtistCursor, ArtistPage, ArtistRecord, ProjectedTrack,
QueryDescriptor, QuerySurface, SourceKey, SourceKind, TrackCursor, TrackGroup, TrackPage,
TrackRecord, TrackRef, TrackSort,
};
use crate::projection::ReconciliationBatch;
use crate::schema;
@@ -540,7 +541,9 @@ impl Catalog {
pub(crate) fn rebuild_materialized_views(&mut self) -> Result<()> {
let tx = self.conn.transaction()?;
tx.execute_batch(
"DELETE FROM edition_artists;
"DELETE FROM artists_fts;
DELETE FROM artist_source_stats;
DELETE FROM edition_artists;
DELETE FROM albums_materialized;
DELETE FROM artists_materialized;
@@ -644,30 +647,95 @@ impl Catalog {
GROUP BY e.edition_id;
INSERT INTO artists_materialized(
artist_key,display_name,sort_name,album_count,track_count,available
artist_key,display_name,sort_name,album_count,track_count,available,
source_kind,artwork_source,artwork_token
)
SELECT ac.artist_key,MIN(ac.display_name),ac.artist_key,
COUNT(DISTINCT sc.edition_id),COUNT(DISTINCT ac.catalog_id),
COUNT(DISTINCT CASE WHEN t.available=1 THEN sc.edition_id END),
COUNT(DISTINCT CASE WHEN t.available=1 THEN ac.catalog_id END),
COALESCE(MAX(t.available),0),
CASE WHEN COUNT(DISTINCT t.source_kind)>1 THEN 'mixed'
ELSE MIN(t.source_kind) END,
COALESCE((
SELECT t2.source_kind
FROM artist_credits ac2
JOIN tracks t2 ON t2.catalog_id=ac2.catalog_id
WHERE ac2.artist_key=ac.artist_key
AND t2.available=1
AND COALESCE(t2.artwork_token,'') != ''
ORDER BY CASE ac2.role
WHEN 'track_artist' THEN 0
WHEN 'album_artist' THEN 1
WHEN 'featured' THEN 2
WHEN 'performer' THEN 3 ELSE 4 END,
t2.catalog_id LIMIT 1
),''),
COALESCE((
SELECT t2.artwork_token
FROM artist_credits ac2
JOIN tracks t2 ON t2.catalog_id=ac2.catalog_id
WHERE ac2.artist_key=ac.artist_key
AND t2.available=1
AND COALESCE(t2.artwork_token,'') != ''
ORDER BY CASE ac2.role
WHEN 'track_artist' THEN 0
WHEN 'album_artist' THEN 1
WHEN 'featured' THEN 2
WHEN 'performer' THEN 3 ELSE 4 END,
t2.catalog_id LIMIT 1
),'')
FROM artist_credits ac
JOIN tracks t ON t.catalog_id=ac.catalog_id
LEFT JOIN source_copies sc ON sc.source_copy_id=t.source_copy_id
GROUP BY ac.artist_key;
INSERT INTO artist_source_stats(
artist_key,source_kind,source_instance,album_count,track_count,available
)
SELECT ac.artist_key,t.source_kind,t.source_instance,
COUNT(DISTINCT CASE WHEN t.available=1 THEN sc.edition_id END),
COUNT(DISTINCT CASE WHEN t.available=1 THEN ac.catalog_id END),
COALESCE(MAX(t.available),0)
FROM artist_credits ac
JOIN tracks t ON t.catalog_id=ac.catalog_id
LEFT JOIN source_copies sc ON sc.source_copy_id=t.source_copy_id
GROUP BY ac.artist_key;",
GROUP BY ac.artist_key,t.source_kind,t.source_instance;
INSERT INTO artists_fts(artist_key,display_name)
SELECT artist_key,display_name FROM artists_materialized;",
)?;
tx.commit()?;
Ok(())
}
pub(crate) fn materialized_views_valid(&self) -> Result<bool> {
let (tracks, album_tracks, unresolved): (i64, i64, i64) = self.conn.query_row(
let (tracks, album_tracks, unresolved, credit_artists, materialized_artists, missing_stats):
(i64, i64, i64, i64, i64, i64) = self.conn.query_row(
"SELECT
(SELECT COUNT(*) FROM tracks),
(SELECT COALESCE(SUM(track_count),0) FROM albums_materialized),
(SELECT COUNT(*) FROM tracks WHERE source_copy_id IS NULL)",
(SELECT COUNT(*) FROM tracks WHERE source_copy_id IS NULL),
(SELECT COUNT(DISTINCT artist_key) FROM artist_credits),
(SELECT COUNT(*) FROM artists_materialized),
(SELECT COUNT(*) FROM artists_materialized am
WHERE NOT EXISTS (SELECT 1 FROM artist_source_stats ast
WHERE ast.artist_key=am.artist_key))",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
))
},
)?;
Ok(tracks == album_tracks && unresolved == 0)
Ok(tracks == album_tracks
&& unresolved == 0
&& credit_artists == materialized_artists
&& missing_stats == 0)
}
pub fn resolve(&self, track_ref: &TrackRef) -> Result<Option<TrackRecord>> {
@@ -861,6 +929,186 @@ impl Catalog {
))
}
pub fn count_artists(&self, descriptor: &QueryDescriptor) -> Result<u64> {
validate_artists_descriptor(descriptor)?;
let parts = artist_filter_parts(descriptor, None)?;
let sql = format!(
"SELECT COUNT(*) {} WHERE {}",
parts.from_sql, parts.where_sql
);
let count: i64 = self
.conn
.query_row(&sql, params_from_iter(parts.params), |row| row.get(0))?;
Ok(count.max(0) as u64)
}
/// Exact visual length of the Artists rail: one row per artist plus one
/// header for every non-empty A-Z/# bucket under the immutable query.
pub fn count_artist_entries(&self, descriptor: &QueryDescriptor) -> Result<u64> {
validate_artists_descriptor(descriptor)?;
let parts = artist_filter_parts(descriptor, None)?;
let sql = format!(
"SELECT COUNT(*) + COUNT(DISTINCT {}) {} WHERE {}",
artist_initial_expression("ar"),
parts.from_sql,
parts.where_sql
);
let count: i64 = self
.conn
.query_row(&sql, params_from_iter(parts.params), |row| row.get(0))?;
Ok(count.max(0) as u64)
}
pub fn query_artists(
&self,
descriptor: &QueryDescriptor,
cursor: Option<&ArtistCursor>,
page_size: usize,
) -> Result<ArtistPage> {
self.query_artists_timed(descriptor, cursor, page_size)
.map(|(page, _)| page)
}
pub fn query_artists_timed(
&self,
descriptor: &QueryDescriptor,
cursor: Option<&ArtistCursor>,
page_size: usize,
) -> Result<(ArtistPage, QueryMetrics)> {
validate_artists_descriptor(descriptor)?;
let limit = page_size.clamp(1, MAX_PAGE_SIZE);
let parts = artist_filter_parts(descriptor, cursor)?;
let descending = artist_descending(descriptor);
let order = if descending { "DESC" } else { "ASC" };
let sql = format!(
"SELECT ar.artist_key,ar.display_name,{},{},ar.artwork_source,
ar.artwork_token,{},ar.sort_name
{} WHERE {}
ORDER BY ar.sort_name {order},ar.artist_key {order} LIMIT {}",
parts.album_count_sql,
parts.track_count_sql,
parts.source_sql,
parts.from_sql,
parts.where_sql,
limit + 1
);
let key = descriptor_key(descriptor);
let started = Instant::now();
let mut stmt = self.conn.prepare_cached(&sql)?;
let mapped = stmt.query_map(params_from_iter(parts.params), |row| {
Ok((
ArtistRecord {
artist_key: row.get(0)?,
display_name: row.get(1)?,
album_count: row.get::<_, i64>(2)?.max(0) as u32,
track_count: row.get::<_, i64>(3)?.max(0) as u32,
artwork_source: row.get(4)?,
artwork_token: row.get(5)?,
source: row.get(6)?,
},
row.get::<_, String>(7)?,
))
})?;
let mut values = mapped.collect::<rusqlite::Result<Vec<_>>>()?;
let sql_time = started.elapsed();
let has_more = values.len() > limit;
values.truncate(limit);
let next_cursor = has_more.then(|| {
let (record, sort_name) = values.last().expect("non-empty page");
ArtistCursor {
descriptor_key: key,
sort_name: sort_name.clone(),
artist_key: record.artist_key.clone(),
}
});
let rows = values
.into_iter()
.map(|(record, _)| record)
.collect::<Vec<_>>();
let metrics = QueryMetrics {
sql_time,
rows: rows.len(),
};
Ok((
ArtistPage {
rows,
next_cursor,
has_more,
},
metrics,
))
}
/// Count the selected artist's albums through the normalized,
/// source-aware `edition_artists` relationship. No album collection is
/// materialized in the frontend to answer this question.
pub fn count_artist_albums(&self, artist_key: &str, sources: &[SourceKey]) -> Result<u64> {
validate_artist_key(artist_key)?;
let (where_sql, values) = artist_album_filter(artist_key, sources, None)?;
let sql = format!("SELECT COUNT(*) FROM albums_materialized am WHERE {where_sql}");
let count: i64 = self
.conn
.query_row(&sql, params_from_iter(values), |row| row.get(0))?;
Ok(count.max(0) as u64)
}
pub fn query_artist_albums(
&self,
artist_key: &str,
sources: &[SourceKey],
cursor: Option<&AlbumCursor>,
page_size: usize,
) -> Result<AlbumPage> {
self.query_artist_albums_timed(artist_key, sources, cursor, page_size)
.map(|(page, _)| page)
}
pub fn query_artist_albums_timed(
&self,
artist_key: &str,
sources: &[SourceKey],
cursor: Option<&AlbumCursor>,
page_size: usize,
) -> Result<(AlbumPage, QueryMetrics)> {
validate_artist_key(artist_key)?;
let limit = page_size.clamp(1, MAX_PAGE_SIZE);
let (where_sql, values) = artist_album_filter(artist_key, sources, cursor)?;
let sql = format!(
"SELECT {ALBUM_COLUMNS} FROM albums_materialized am
WHERE {where_sql}
ORDER BY am.sort_title,am.edition_id LIMIT {}",
limit + 1
);
let key = artist_relation_key(artist_key, sources);
let started = Instant::now();
let mut stmt = self.conn.prepare_cached(&sql)?;
let mapped = stmt.query_map(params_from_iter(values), map_album_row)?;
let mut values = mapped.collect::<rusqlite::Result<Vec<_>>>()?;
for value in &mut values {
value.cursor.descriptor_key = key.clone();
}
let sql_time = started.elapsed();
let has_more = values.len() > limit;
values.truncate(limit);
let next_cursor = has_more.then(|| values.last().expect("non-empty page").cursor.clone());
let rows = values
.into_iter()
.map(|value| value.record)
.collect::<Vec<_>>();
let metrics = QueryMetrics {
sql_time,
rows: rows.len(),
};
Ok((
AlbumPage {
rows,
next_cursor,
has_more,
},
metrics,
))
}
pub fn stats(&self) -> Result<CatalogStats> {
let track_count: i64 = self
.conn
@@ -921,10 +1169,17 @@ impl Catalog {
[],
)
.is_ok();
let artists_fts_ok = self
.conn
.execute(
"INSERT INTO artists_fts(artists_fts) VALUES ('integrity-check')",
[],
)
.is_ok();
Ok(IntegrityReport {
sqlite_ok: result == "ok",
foreign_key_violations: foreign_key_violations as u64,
fts_ok: tracks_fts_ok && albums_fts_ok,
fts_ok: tracks_fts_ok && albums_fts_ok && artists_fts_ok,
})
}
@@ -1872,6 +2127,219 @@ const ALBUM_COLUMNS: &str = "
am.sort_title,am.sort_artist,
CASE WHEN am.year IS NULL THEN 1 ELSE 0 END,COALESCE(am.year,0)";
struct ArtistQueryParts {
from_sql: String,
where_sql: String,
params: Vec<Value>,
album_count_sql: String,
track_count_sql: String,
source_sql: String,
}
fn validate_artists_descriptor(descriptor: &QueryDescriptor) -> Result<()> {
if descriptor.surface() != QuerySurface::Artists {
return Err(CatalogError::InvalidInput(
"a non-Artists descriptor was passed to an Artists query".to_string(),
));
}
if !descriptor.formats().is_empty()
|| descriptor.other_formats()
|| !descriptor.quality_tiers().is_empty()
|| !descriptor.source_buckets().is_empty()
|| descriptor.group() != TrackGroup::Off
{
return Err(CatalogError::InvalidInput(
"Artists supports source instances and name search only".to_string(),
));
}
match descriptor.sort() {
TrackSort::Default | TrackSort::ArtistAsc | TrackSort::ArtistDesc => Ok(()),
_ => Err(CatalogError::InvalidInput(
"Artists supports name ordering only".to_string(),
)),
}
}
fn artist_descending(descriptor: &QueryDescriptor) -> bool {
descriptor.sort() == TrackSort::ArtistDesc
}
fn artist_initial_expression(alias: &str) -> String {
format!(
"CASE WHEN UPPER(SUBSTR({alias}.sort_name,1,1)) BETWEEN 'A' AND 'Z' \
THEN UPPER(SUBSTR({alias}.sort_name,1,1)) ELSE '#' END"
)
}
fn artist_filter_parts(
descriptor: &QueryDescriptor,
cursor: Option<&ArtistCursor>,
) -> Result<ArtistQueryParts> {
if let Some(cursor) = cursor {
if cursor.descriptor_key != descriptor_key(descriptor) {
return Err(CatalogError::CursorDescriptorMismatch);
}
}
let mut params = Vec::new();
let (source_join, album_count_sql, track_count_sql, source_sql, source_filter) =
if descriptor.sources().is_empty() {
(
"".to_string(),
"ar.album_count".to_string(),
"ar.track_count".to_string(),
"ar.source_kind".to_string(),
None,
)
} else {
let mut source = Vec::new();
for key in descriptor.sources() {
if key.source_instance.trim().is_empty() {
return Err(CatalogError::InvalidInput(
"source filter instance must not be empty".to_string(),
));
}
let first = params.len() + 1;
source.push(format!(
"(ass.source_kind=?{first} AND ass.source_instance=?{})",
first + 1
));
params.push(Value::Text(key.source.as_str().to_string()));
params.push(Value::Text(key.source_instance.clone()));
}
let clause = source.join(" OR ");
(
"".to_string(),
format!(
"(SELECT COALESCE(SUM(ass.album_count),0) FROM artist_source_stats ass \
WHERE ass.artist_key=ar.artist_key AND ass.available=1 AND ({clause}))"
),
format!(
"(SELECT COALESCE(SUM(ass.track_count),0) FROM artist_source_stats ass \
WHERE ass.artist_key=ar.artist_key AND ass.available=1 AND ({clause}))"
),
format!(
"(SELECT CASE WHEN COUNT(DISTINCT ass.source_kind)>1 THEN 'mixed' \
ELSE MIN(ass.source_kind) END FROM artist_source_stats ass \
WHERE ass.artist_key=ar.artist_key AND ass.available=1 AND ({clause}))"
),
Some(clause),
)
};
let mut predicates = Vec::new();
let mut search_join = String::new();
if !descriptor.search().is_empty() {
let search_parameter = params.len() + 1;
if descriptor.search().chars().count() < 3 {
predicates.push(format!("INSTR(ar.sort_name,?{search_parameter})>0"));
params.push(Value::Text(normalize_artist_key(descriptor.search())));
} else {
search_join = "JOIN artists_fts ON artists_fts.artist_key=ar.artist_key".to_string();
predicates.push(format!("artists_fts MATCH ?{search_parameter}"));
params.push(fts_match_value(descriptor.search())?);
}
}
if descriptor.available_only() {
predicates.push("ar.available=1".to_string());
}
if let Some(source) = source_filter {
predicates.push(format!(
"EXISTS (SELECT 1 FROM artist_source_stats ass \
WHERE ass.artist_key=ar.artist_key AND ass.available=1 AND ({source}))"
));
}
if let Some(cursor) = cursor {
let comparison = if artist_descending(descriptor) {
"<"
} else {
">"
};
predicates.push(format!(
"(ar.sort_name{comparison}? OR (ar.sort_name=? AND ar.artist_key{comparison}?))"
));
params.push(Value::Text(cursor.sort_name.clone()));
params.push(Value::Text(cursor.sort_name.clone()));
params.push(Value::Text(cursor.artist_key.clone()));
}
if predicates.is_empty() {
predicates.push("1".to_string());
}
Ok(ArtistQueryParts {
from_sql: format!("FROM artists_materialized ar {source_join} {search_join}"),
where_sql: predicates.join(" AND "),
params,
album_count_sql,
track_count_sql,
source_sql,
})
}
fn validate_artist_key(artist_key: &str) -> Result<()> {
if artist_key.trim().is_empty() || normalize_artist_key(artist_key) != artist_key {
return Err(CatalogError::InvalidInput(
"artist relationship requires a normalized artist key".to_string(),
));
}
Ok(())
}
fn artist_relation_key(artist_key: &str, sources: &[SourceKey]) -> String {
let mut sources = sources.to_vec();
sources.sort();
sources.dedup();
let mut key = String::from("artist-albums|");
push_key_part(&mut key, artist_key);
for source in sources {
push_key_part(&mut key, source.source.as_str());
push_key_part(&mut key, &source.source_instance);
}
key
}
fn artist_album_filter(
artist_key: &str,
sources: &[SourceKey],
cursor: Option<&AlbumCursor>,
) -> Result<(String, Vec<Value>)> {
let relation_key = artist_relation_key(artist_key, sources);
if let Some(cursor) = cursor {
if cursor.descriptor_key != relation_key {
return Err(CatalogError::CursorDescriptorMismatch);
}
}
let mut predicates = vec![
"am.available=1".to_string(),
"EXISTS (SELECT 1 FROM edition_artists ea \
WHERE ea.edition_id=am.edition_id AND ea.artist_key=?)"
.to_string(),
];
let mut values = vec![Value::Text(artist_key.to_string())];
if !sources.is_empty() {
let mut source = Vec::new();
for key in sources {
if key.source_instance.trim().is_empty() {
return Err(CatalogError::InvalidInput(
"source filter instance must not be empty".to_string(),
));
}
source.push("(scf.source_kind=? AND scf.source_instance=?)");
values.push(Value::Text(key.source.as_str().to_string()));
values.push(Value::Text(key.source_instance.clone()));
}
predicates.push(format!(
"EXISTS (SELECT 1 FROM source_copies scf WHERE scf.edition_id=am.edition_id AND ({}))",
source.join(" OR ")
));
}
if let Some(cursor) = cursor {
predicates.push("(am.sort_title>? OR (am.sort_title=? AND am.edition_id>?))".to_string());
values.push(Value::Text(cursor.sort_title.clone()));
values.push(Value::Text(cursor.sort_title.clone()));
values.push(Value::Integer(cursor.edition_id));
}
Ok((predicates.join(" AND "), values))
}
/// Unicode-aware display sort key shared by ingest and query indices.
pub fn normalize_sort_key(value: &str) -> String {
value
+3 -3
View File
@@ -26,9 +26,9 @@ pub use legacy::{
reconcile_legacy_caches_with_progress, LegacyLocations, LegacySourceSpec,
};
pub use model::{
AlbumCursor, AlbumPage, AlbumRecord, ArtistCredit, CreditRole, ProjectedTrack, QueryDescriptor,
QuerySurface, SourceKey, SourceKind, TrackCursor, TrackGroup, TrackPage, TrackRecord, TrackRef,
TrackSort,
AlbumCursor, AlbumPage, AlbumRecord, ArtistCredit, ArtistCursor, ArtistPage, ArtistRecord,
CreditRole, ProjectedTrack, QueryDescriptor, QuerySurface, SourceKey, SourceKind, TrackCursor,
TrackGroup, TrackPage, TrackRecord, TrackRef, TrackSort,
};
pub use projection::{
ProjectionOutcome, ProjectionProgress, ProjectionSession, ReconciliationBatch,
+27
View File
@@ -412,3 +412,30 @@ pub struct AlbumPage {
pub next_cursor: Option<AlbumCursor>,
pub has_more: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistRecord {
pub artist_key: String,
pub display_name: String,
pub album_count: u32,
pub track_count: u32,
pub artwork_source: String,
pub artwork_token: String,
/// `local`, a remote source word, or `mixed` when several source kinds
/// contribute to the aggregate visible under the query descriptor.
pub source: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistCursor {
pub(crate) descriptor_key: String,
pub(crate) sort_name: String,
pub(crate) artist_key: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistPage {
pub rows: Vec<ArtistRecord>,
pub next_cursor: Option<ArtistCursor>,
pub has_more: bool,
}
+23 -1
View File
@@ -2,7 +2,7 @@ use rusqlite::{params, Connection};
use crate::{CatalogError, Result};
pub const SCHEMA_VERSION: u32 = 3;
pub const SCHEMA_VERSION: u32 = 4;
pub const APPLICATION_ID: i64 = 0x5142_5A43; // "QBZC"
pub(crate) fn configure(conn: &Connection) -> Result<()> {
@@ -314,6 +314,7 @@ CREATE TABLE IF NOT EXISTS artists_materialized (
album_count INTEGER NOT NULL DEFAULT 0,
track_count INTEGER NOT NULL DEFAULT 0,
available INTEGER NOT NULL DEFAULT 1 CHECK (available IN (0,1)),
source_kind TEXT NOT NULL DEFAULT 'local',
artwork_source TEXT NOT NULL DEFAULT '',
artwork_token TEXT NOT NULL DEFAULT ''
) STRICT;
@@ -321,6 +322,21 @@ CREATE TABLE IF NOT EXISTS artists_materialized (
CREATE INDEX IF NOT EXISTS idx_artists_materialized_name
ON artists_materialized(available, sort_name, artist_key);
CREATE TABLE IF NOT EXISTS artist_source_stats (
artist_key TEXT NOT NULL REFERENCES artists_materialized(artist_key) ON DELETE CASCADE,
source_kind TEXT NOT NULL CHECK (
source_kind IN ('local','offline','plex','jellyfin','subsonic')
),
source_instance TEXT NOT NULL,
album_count INTEGER NOT NULL DEFAULT 0,
track_count INTEGER NOT NULL DEFAULT 0,
available INTEGER NOT NULL DEFAULT 1 CHECK (available IN (0,1)),
PRIMARY KEY (artist_key, source_kind, source_instance)
) STRICT;
CREATE INDEX IF NOT EXISTS idx_artist_source_stats_source
ON artist_source_stats(source_kind, source_instance, available, artist_key);
CREATE TABLE IF NOT EXISTS edition_artists (
edition_id INTEGER NOT NULL REFERENCES editions(edition_id) ON DELETE CASCADE,
artist_key TEXT NOT NULL,
@@ -383,4 +399,10 @@ CREATE TRIGGER IF NOT EXISTS albums_fts_update AFTER UPDATE ON albums_materializ
INSERT INTO albums_fts(rowid, title, artist, all_artists)
VALUES (new.edition_id, new.title, new.artist, new.all_artists);
END;
CREATE VIRTUAL TABLE IF NOT EXISTS artists_fts USING fts5(
artist_key UNINDEXED,
display_name,
tokenize='trigram case_sensitive 0'
);
"#;
+317
View File
@@ -117,6 +117,26 @@ fn collect_all_albums(
rows
}
fn collect_all_artists(
catalog: &Catalog,
descriptor: &QueryDescriptor,
page_size: usize,
) -> Vec<ArtistRecord> {
let mut cursor = None;
let mut rows = Vec::new();
loop {
let page = catalog
.query_artists(descriptor, cursor.as_ref(), page_size)
.unwrap();
rows.extend(page.rows);
if !page.has_more {
break;
}
cursor = page.next_cursor;
}
rows
}
fn insert_album_fixture(catalog: &mut Catalog, count: usize) {
let mut by_source = std::collections::BTreeMap::<SourceKey, Vec<ProjectedTrack>>::new();
for index in 0..count {
@@ -185,14 +205,236 @@ fn schema_is_versioned_frontend_agnostic_and_fts5_enabled() {
"artist_credits",
"albums_materialized",
"artists_materialized",
"artist_source_stats",
"edition_artists",
"tracks_fts",
"albums_fts",
"artists_fts",
] {
assert!(tables.contains(required), "missing {required}");
}
}
#[test]
fn artist_keyset_search_and_source_scope_cover_every_remote_only_artist_once() {
let mut catalog = Catalog::open_in_memory(1).unwrap();
insert_album_fixture(&mut catalog, 1_231);
let all = QueryDescriptor::artists();
let rows = collect_all_artists(&catalog, &all, 17);
let keys = rows
.iter()
.map(|row| row.artist_key.clone())
.collect::<HashSet<_>>();
let expected_available = (0..1_231).filter(|index| index % 97 != 0).count();
assert_eq!(rows.len(), expected_available);
assert_eq!(keys.len(), rows.len());
assert_eq!(catalog.count_artists(&all).unwrap(), rows.len() as u64);
assert_eq!(
catalog.count_artist_entries(&all).unwrap(),
rows.len() as u64 + 1
);
let jellyfin_source = SourceKey {
source: SourceKind::Jellyfin,
source_instance: source_instance(SourceKind::Jellyfin).to_string(),
};
let jellyfin = QueryDescriptor::artists().with_sources(vec![jellyfin_source.clone()]);
let remote = collect_all_artists(&catalog, &jellyfin, 11);
assert!(!remote.is_empty());
assert!(remote.iter().all(|row| row.source == "jellyfin"));
assert_eq!(
catalog.count_artists(&jellyfin).unwrap(),
remote.len() as u64
);
assert!(remote
.iter()
.all(|row| row.album_count == 1 && row.track_count == 1));
let needle = remote[0]
.display_name
.chars()
.skip(7)
.take(3)
.collect::<String>();
let searched = collect_all_artists(
&catalog,
&QueryDescriptor::artists()
.with_sources(vec![jellyfin_source])
.with_search(needle),
7,
);
assert!(!searched.is_empty());
assert!(searched
.iter()
.all(|row| row.source == "jellyfin" && keys.contains(&row.artist_key)));
let searched_descriptor = QueryDescriptor::artists()
.with_sources(vec![SourceKey {
source: SourceKind::Jellyfin,
source_instance: source_instance(SourceKind::Jellyfin).to_string(),
}])
.with_search(
remote[0]
.display_name
.chars()
.skip(7)
.take(3)
.collect::<String>(),
);
assert_eq!(
catalog.count_artists(&searched_descriptor).unwrap(),
searched.len() as u64
);
assert_eq!(
catalog.count_artist_entries(&searched_descriptor).unwrap(),
searched.len() as u64 + 1
);
}
#[test]
fn artist_credit_counts_and_album_relationship_span_every_source() {
let mut catalog = Catalog::open_in_memory(1).unwrap();
let mut local = projected(10, SourceKind::Local);
local.native_album_id = Some("local-edition".to_string());
local.credits.push(ArtistCredit {
display_name: "Beyoncé".to_string(),
role: CreditRole::Featured,
ordinal: 1,
});
let mut remote = projected(80, SourceKind::Jellyfin);
remote.native_album_id = Some("remote-edition".to_string());
remote.credits.push(ArtistCredit {
display_name: "Beyonce".to_string(),
role: CreditRole::Performer,
ordinal: 1,
});
for track in [local, remote] {
let source = SourceKey {
source: track.track_ref.source,
source_instance: track.track_ref.source_instance.clone(),
};
catalog
.apply_bootstrap_batch(&BootstrapBatch {
source,
snapshot_version: "artist-credit-v1".to_string(),
expected_cursor: String::new(),
next_cursor: "1".to_string(),
tracks: vec![track],
complete: true,
})
.unwrap();
}
catalog.rebuild_materialized_views().unwrap();
let key = normalize_artist_key("Beyoncé");
let row = collect_all_artists(&catalog, &QueryDescriptor::artists(), 5)
.into_iter()
.find(|row| row.artist_key == key)
.expect("credit-only artist is materialized");
assert_eq!(row.album_count, 2);
assert_eq!(row.track_count, 2);
assert_eq!(row.source, "mixed");
let sources = vec![
SourceKey {
source: SourceKind::Local,
source_instance: source_instance(SourceKind::Local).to_string(),
},
SourceKey {
source: SourceKind::Jellyfin,
source_instance: source_instance(SourceKind::Jellyfin).to_string(),
},
];
assert_eq!(catalog.count_artist_albums(&key, &sources).unwrap(), 2);
let page = catalog
.query_artist_albums(&key, &sources, None, 1)
.unwrap();
assert_eq!(page.rows.len(), 1);
assert!(page.has_more);
let second = catalog
.query_artist_albums(&key, &sources, page.next_cursor.as_ref(), 1)
.unwrap();
assert_eq!(second.rows.len(), 1);
assert!(!second.has_more);
assert_ne!(page.rows[0].edition_id, second.rows[0].edition_id);
let jellyfin = &sources[1..];
assert_eq!(catalog.count_artist_albums(&key, jellyfin).unwrap(), 1);
let remote_row = collect_all_artists(
&catalog,
&QueryDescriptor::artists().with_sources(jellyfin.to_vec()),
5,
)
.into_iter()
.find(|row| row.artist_key == key)
.unwrap();
assert_eq!((remote_row.album_count, remote_row.track_count), (1, 1));
assert_eq!(remote_row.source, "jellyfin");
}
#[test]
fn artist_album_keysets_cross_pages_without_omissions_or_duplicates() {
const ALBUMS: usize = 731;
let mut catalog = Catalog::open_in_memory(1).unwrap();
let source = SourceKey {
source: SourceKind::Jellyfin,
source_instance: source_instance(SourceKind::Jellyfin).to_string(),
};
let mut rows = (0..ALBUMS)
.map(|index| {
let mut track = projected(80_000 + index, SourceKind::Jellyfin);
track.native_album_id = Some(format!("guest-album-{index:04}"));
track.album = format!("Guest Album {index:04}");
track.credits.push(ArtistCredit {
display_name: "Remote Guest".to_string(),
role: CreditRole::Featured,
ordinal: 1,
});
track
})
.collect::<Vec<_>>();
let expected_available = rows.iter().filter(|track| track.available).count();
let mut cursor = String::new();
for (batch_index, batch) in rows.chunks_mut(BOOTSTRAP_BATCH_ROWS).enumerate() {
let committed = (batch_index * BOOTSTRAP_BATCH_ROWS + batch.len()).min(ALBUMS);
let saved = catalog
.apply_bootstrap_batch(&BootstrapBatch {
source: source.clone(),
snapshot_version: "artist-albums-731".to_string(),
expected_cursor: cursor,
next_cursor: committed.to_string(),
tracks: batch.to_vec(),
complete: committed == ALBUMS,
})
.unwrap();
cursor = saved.checkpoint_cursor;
}
catalog.rebuild_materialized_views().unwrap();
let key = normalize_artist_key("Remote Guest");
assert_eq!(
catalog.count_artist_albums(&key, &[source.clone()]).unwrap(),
expected_available as u64
);
let mut cursor = None;
let mut ids = Vec::new();
loop {
let page = catalog
.query_artist_albums(&key, std::slice::from_ref(&source), cursor.as_ref(), 37)
.unwrap();
ids.extend(page.rows.into_iter().map(|row| row.edition_id));
if !page.has_more {
break;
}
cursor = page.next_cursor;
}
assert_eq!(ids.len(), expected_available);
assert_eq!(
ids.iter().copied().collect::<HashSet<_>>().len(),
expected_available
);
}
#[test]
fn album_keyset_pages_cover_every_id_once_for_all_orders_and_groups() {
let mut catalog = Catalog::open_in_memory(1).unwrap();
@@ -355,6 +597,81 @@ fn album_query_and_broad_search_metric_uses_a_mixed_deterministic_fixture() {
);
}
#[test]
fn artist_query_and_broad_search_metric_uses_a_mixed_deterministic_fixture() {
const ARTISTS: usize = 20_000;
let mut catalog = Catalog::open_in_memory(10).unwrap();
insert_album_fixture(&mut catalog, ARTISTS);
let descriptor = QueryDescriptor::artists();
let expected = (0..ARTISTS).filter(|index| index % 97 != 0).count() as u64;
let count_started = Instant::now();
let count = catalog.count_artists(&descriptor).unwrap();
let count_time = count_started.elapsed();
let (page, query) = catalog.query_artists_timed(&descriptor, None, 100).unwrap();
let broad = descriptor.clone().with_search("Artist");
let broad_count_started = Instant::now();
let broad_count = catalog.count_artists(&broad).unwrap();
let broad_count_time = broad_count_started.elapsed();
let (broad_page, broad_query) = catalog.query_artists_timed(&broad, None, 100).unwrap();
let source_counts = [
SourceKind::Local,
SourceKind::Offline,
SourceKind::Plex,
SourceKind::Jellyfin,
SourceKind::Subsonic,
]
.into_iter()
.map(|source| {
let scoped = QueryDescriptor::artists().with_sources(vec![SourceKey {
source,
source_instance: source_instance(source).to_string(),
}]);
format!(
"{}={}",
source.as_str(),
catalog.count_artists(&scoped).unwrap()
)
})
.collect::<Vec<_>>()
.join(",");
assert_eq!(count, expected);
assert_eq!(page.rows.len(), 100);
assert!(page.has_more);
assert_eq!(broad_count, expected);
assert_eq!(broad_page.rows.len(), 100);
assert_eq!(
catalog.count_artist_entries(&descriptor).unwrap(),
expected + 1
);
let plan = catalog
.connection()
.prepare(
"EXPLAIN QUERY PLAN SELECT artist_key FROM artists_materialized
WHERE available=1 ORDER BY sort_name,artist_key LIMIT 101",
)
.unwrap()
.query_map([], |row| row.get::<_, String>(3))
.unwrap()
.collect::<rusqlite::Result<Vec<_>>>()
.unwrap();
assert!(
plan.iter().all(|step| !step.contains("TEMP B-TREE")),
"{plan:?}"
);
println!(
"F2_ARTISTS_QUERY total={count} first_artists={} count_ms={:.3} query_ms={:.3} broad_count_ms={:.3} broad_query_ms={:.3} source_counts={source_counts}",
page.rows.len(),
count_time.as_secs_f64() * 1_000.0,
query.sql_time.as_secs_f64() * 1_000.0,
broad_count_time.as_secs_f64() * 1_000.0,
broad_query.sql_time.as_secs_f64() * 1_000.0,
);
}
#[test]
fn opening_an_unrelated_sqlite_file_is_refused_without_mutating_it() {
let temp = tempfile::tempdir().unwrap();
+1
View File
@@ -304,6 +304,7 @@ fn build_rhi_items() {
"tunnelflow_item",
"local_tracks_model",
"local_albums_model",
"local_artists_model",
] {
let header = format!("cxx/{item}.h");
let source = format!("cxx/{item}.cpp");
+19
View File
@@ -13,6 +13,7 @@
namespace {
QPointer<LocalAlbumsModel> g_model;
QPointer<LocalAlbumsModel> g_artist_model;
void registerLocalAlbumsModel()
{
@@ -21,6 +22,10 @@ void registerLocalAlbumsModel()
g_model = model;
qmlRegisterSingletonInstance<LocalAlbumsModel>(
"com.blitzfc.qbz", 1, 0, "QbzLocalAlbums", model);
auto *artistModel = new LocalAlbumsModel(application);
g_artist_model = artistModel;
qmlRegisterSingletonInstance<LocalAlbumsModel>(
"com.blitzfc.qbz", 1, 0, "QbzLocalArtistAlbums", artistModel);
}
Q_COREAPP_STARTUP_FUNCTION(registerLocalAlbumsModel)
@@ -303,3 +308,17 @@ extern "C" void qbz_local_albums_set_selection(
g_model->setSelection(
generation, QByteArray(json ? json : "{}"), selectedCount);
}
extern "C" void qbz_local_artist_albums_reset(
int generation, qint64 totalCount, qint64 albumTotal)
{
if (g_artist_model)
g_artist_model->resetQuery(generation, totalCount, albumTotal);
}
extern "C" bool qbz_local_artist_albums_apply_page(
int generation, int page, const char *json)
{
return g_artist_model && g_artist_model->applyPage(
generation, page, QByteArray(json ? json : "[]"));
}
+2
View File
@@ -83,6 +83,8 @@ void qbz_local_albums_register_qml_type();
void qbz_local_albums_reset(int generation, qint64 totalCount, qint64 albumTotal);
bool qbz_local_albums_apply_page(int generation, int page, const char *json);
void qbz_local_albums_set_selection(int generation, const char *json, qint64 selectedCount);
void qbz_local_artist_albums_reset(int generation, qint64 totalCount, qint64 albumTotal);
bool qbz_local_artist_albums_apply_page(int generation, int page, const char *json);
}
#endif // QBZ_LOCAL_ALBUMS_MODEL_H
+235
View File
@@ -0,0 +1,235 @@
#include "local_artists_model.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QMetaMethod>
#include <QtCore/QMetaObject>
#include <QtCore/QPointer>
#include <QtQml/qqml.h>
#include <limits>
namespace {
QPointer<LocalArtistsModel> g_model;
void registerLocalArtistsModel()
{
auto *model = new LocalArtistsModel(QCoreApplication::instance());
g_model = model;
qmlRegisterSingletonInstance<LocalArtistsModel>(
"com.blitzfc.qbz", 1, 0, "QbzLocalArtists", model);
}
Q_COREAPP_STARTUP_FUNCTION(registerLocalArtistsModel)
}
LocalArtistsModel::LocalArtistsModel(QObject *parent)
: QAbstractListModel(parent)
{
}
int LocalArtistsModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return int(qMin<qint64>(m_totalCount, std::numeric_limits<int>::max()));
}
QVariant LocalArtistsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || role != ModelDataRole)
return {};
return modelData(index.row());
}
QHash<int, QByteArray> LocalArtistsModel::roleNames() const
{
return {{ ModelDataRole, QByteArrayLiteral("modelData") }};
}
QVariantMap LocalArtistsModel::rowAt(qint64 row) const
{
if (row < 0 || row >= m_totalCount)
return {};
return modelData(row);
}
QVariantMap LocalArtistsModel::modelData(qint64 row) const
{
const int page = int(row / PageEntries);
const int offset = int(row % PageEntries);
const auto found = m_pages.constFind(page);
if (found == m_pages.cend() || offset >= found->size()) {
requestPage(page, false);
return {
{ QStringLiteral("t"), 1 },
{ QStringLiteral("loading"), true },
{ QStringLiteral("base"), 0 },
{ QStringLiteral("item"), QVariantMap() },
};
}
touch(page);
QVariantMap values = found->at(offset).values;
values.insert(QStringLiteral("loading"), false);
return values;
}
void LocalArtistsModel::requestPage(int page, bool prefetch) const
{
if (page < 0)
return;
const QMetaMethod missSignal = QMetaMethod::fromSignal(&LocalArtistsModel::pageMiss);
if (!isSignalConnected(missSignal))
return;
if (m_pending.contains(page)) {
if (!prefetch)
m_pending.insert(page, false);
return;
}
m_pending.insert(page, prefetch);
const int generation = m_generation;
auto *self = const_cast<LocalArtistsModel *>(this);
QMetaObject::invokeMethod(
self,
[self, page, generation]() {
if (generation != self->m_generation)
return;
if (self->isSignalConnected(
QMetaMethod::fromSignal(&LocalArtistsModel::pageMiss))) {
emit self->pageMiss(page, generation);
} else {
self->m_pending.remove(page);
}
},
Qt::QueuedConnection);
}
void LocalArtistsModel::touch(int page) const
{
m_lru.removeAll(page);
m_lru.append(page);
}
void LocalArtistsModel::resetQuery(int generation, qint64 totalCount, qint64 artistTotal)
{
beginResetModel();
m_generation = generation;
m_totalCount = qMax<qint64>(0, totalCount);
m_artistTotal = qMax<qint64>(0, artistTotal);
m_pages.clear();
m_lru.clear();
m_pending.clear();
m_residentArtists = 0;
m_evictions = 0;
endResetModel();
emit generationChanged();
emit totalCountChanged();
emit artistTotalChanged();
emit residentArtistsChanged();
emit evictionsChanged();
}
bool LocalArtistsModel::applyPage(int generation, int page, const QByteArray &json)
{
if (generation != m_generation || page < 0)
return false;
QJsonParseError error;
const QJsonDocument document = QJsonDocument::fromJson(json, &error);
if (error.error != QJsonParseError::NoError || !document.isArray())
return false;
Page entries;
const QJsonArray array = document.array();
entries.reserve(array.size());
for (const QJsonValue &value : array) {
if (!value.isObject())
return false;
Entry entry;
entry.values = value.toObject().toVariantMap();
entry.isArtist = entry.values.value(QStringLiteral("t")).toInt() == 1;
entry.artKey = entry.values.value(QStringLiteral("item"))
.toMap()
.value(QStringLiteral("artKey"))
.toString();
entries.append(std::move(entry));
}
const auto previous = m_pages.constFind(page);
if (previous != m_pages.cend()) {
for (const Entry &entry : *previous)
m_residentArtists -= int(entry.isArtist);
}
m_pages.insert(page, std::move(entries));
for (const Entry &entry : m_pages.value(page))
m_residentArtists += int(entry.isArtist);
const bool wasPrefetch = m_pending.take(page);
touch(page);
evictIfNeeded();
const int first = page * PageEntries;
const int last = qMin(rowCount() - 1, first + PageEntries - 1);
if (first <= last)
emit dataChanged(index(first, 0), index(last, 0), { ModelDataRole });
emit residentArtistsChanged();
const int next = page + 1;
if (!wasPrefetch && qint64(next) * PageEntries < m_totalCount && !m_pages.contains(next))
requestPage(next, true);
return true;
}
void LocalArtistsModel::evictIfNeeded()
{
while (m_residentArtists > MaxResidentArtists && m_pages.size() > 1 && !m_lru.isEmpty()) {
const int page = m_lru.takeFirst();
const auto found = m_pages.find(page);
if (found == m_pages.end())
continue;
for (const Entry &entry : *found)
m_residentArtists -= int(entry.isArtist);
m_pages.erase(found);
++m_evictions;
const int first = page * PageEntries;
const int last = qMin(rowCount() - 1, first + PageEntries - 1);
if (first <= last)
emit dataChanged(index(first, 0), index(last, 0), { ModelDataRole });
}
emit evictionsChanged();
}
void LocalArtistsModel::setArtwork(const QString &artKey, const QString &path)
{
if (artKey.isEmpty() || path.isEmpty())
return;
for (auto page = m_pages.begin(); page != m_pages.end(); ++page) {
for (int offset = 0; offset < page->size(); ++offset) {
Entry &entry = (*page)[offset];
if (entry.artKey != artKey)
continue;
QVariantMap item = entry.values.value(QStringLiteral("item")).toMap();
item.insert(QStringLiteral("artPath"), path);
entry.values.insert(QStringLiteral("item"), item);
const int row = page.key() * PageEntries + offset;
emit dataChanged(index(row, 0), index(row, 0), { ModelDataRole });
}
}
}
extern "C" void qbz_local_artists_register_qml_type()
{
// Link anchor. Registration is performed by Q_COREAPP_STARTUP_FUNCTION.
}
extern "C" void qbz_local_artists_reset(
int generation, qint64 totalCount, qint64 artistTotal)
{
if (g_model)
g_model->resetQuery(generation, totalCount, artistTotal);
}
extern "C" bool qbz_local_artists_apply_page(int generation, int page, const char *json)
{
return g_model && g_model->applyPage(
generation, page, QByteArray(json ? json : "[]"));
}
+79
View File
@@ -0,0 +1,79 @@
#ifndef QBZ_LOCAL_ARTISTS_MODEL_H
#define QBZ_LOCAL_ARTISTS_MODEL_H
#include <QtCore/QAbstractListModel>
#include <QtCore/QHash>
#include <QtCore/QList>
#include <QtCore/QVariantMap>
class LocalArtistsModel final : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int generation READ generation NOTIFY generationChanged)
Q_PROPERTY(qint64 totalCount READ totalCount NOTIFY totalCountChanged)
Q_PROPERTY(qint64 artistTotal READ artistTotal NOTIFY artistTotalChanged)
Q_PROPERTY(int residentArtists READ residentArtists NOTIFY residentArtistsChanged)
Q_PROPERTY(qint64 evictions READ evictions NOTIFY evictionsChanged)
public:
enum Role { ModelDataRole = Qt::UserRole + 1 };
explicit LocalArtistsModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
int generation() const { return m_generation; }
qint64 totalCount() const { return m_totalCount; }
qint64 artistTotal() const { return m_artistTotal; }
int residentArtists() const { return m_residentArtists; }
qint64 evictions() const { return m_evictions; }
Q_INVOKABLE QVariantMap rowAt(qint64 row) const;
Q_INVOKABLE void setArtwork(const QString &artKey, const QString &path);
void resetQuery(int generation, qint64 totalCount, qint64 artistTotal);
bool applyPage(int generation, int page, const QByteArray &json);
signals:
void generationChanged();
void totalCountChanged();
void artistTotalChanged();
void residentArtistsChanged();
void evictionsChanged();
void pageMiss(int page, int generation);
private:
struct Entry {
QVariantMap values;
QString artKey;
bool isArtist = false;
};
using Page = QList<Entry>;
static constexpr int PageEntries = 100;
static constexpr int MaxResidentArtists = 2000;
QVariantMap modelData(qint64 row) const;
void requestPage(int page, bool prefetch = false) const;
void touch(int page) const;
void evictIfNeeded();
int m_generation = 0;
qint64 m_totalCount = 0;
qint64 m_artistTotal = 0;
QHash<int, Page> m_pages;
mutable QList<int> m_lru;
mutable QHash<int, bool> m_pending;
int m_residentArtists = 0;
qint64 m_evictions = 0;
};
extern "C" {
void qbz_local_artists_register_qml_type();
void qbz_local_artists_reset(int generation, qint64 totalCount, qint64 artistTotal);
bool qbz_local_artists_apply_page(int generation, int page, const char *json);
}
#endif // QBZ_LOCAL_ARTISTS_MODEL_H
+19 -4
View File
@@ -63,6 +63,8 @@ Rectangle {
// the composition root also gives every Tracks delegate one stable model.
readonly property var nativeTracksModel: QbzLocalTracks
readonly property var nativeAlbumsModel: QbzLocalAlbums
readonly property var nativeArtistsModel: QbzLocalArtists
readonly property var nativeArtistAlbumsModel: QbzLocalArtistAlbums
// ============================ state ==================================
// Slint defaults, verbatim (state.slint LocalLibraryState).
@@ -335,6 +337,8 @@ Rectangle {
function onLocalArtworkReady(key, path) {
root.nativeTracksModel.setArtwork(key, path)
root.nativeAlbumsModel.setArtwork(key, path)
root.nativeArtistsModel.setArtwork(key, path)
root.nativeArtistAlbumsModel.setArtwork(key, path)
root._artInbox[key] = path
if (!artFlush.running) artFlush.start()
// An arrival is live evidence that the pass is still running, so
@@ -357,6 +361,18 @@ Rectangle {
QbzLocal.albumsNativePageMiss(page, generation)
}
}
Connections {
target: root.nativeArtistsModel
function onPageMiss(page, generation) {
QbzLocal.artistsNativePageMiss(page, generation)
}
}
Connections {
target: root.nativeArtistAlbumsModel
function onPageMiss(page, generation) {
QbzLocal.artistAlbumsNativePageMiss(page, generation)
}
}
// A name route from LocalAlbumView ("go to artist" on a local album:
// local/Plex artists have no catalog id) lands the view on the Artists
@@ -409,10 +425,6 @@ Rectangle {
}
onActiveTabChanged: {
QbzLocal.loadTab(activeTab)
// The Artists detail derives from the album set (the DB aggregates
// the contributor list per album), so make sure it is loaded.
if (activeTab === "artists" && albums.length === 0)
QbzLocal.loadTab("albums-legacy")
// The tab that just appeared has covers to ask for and the one that
// left has covers to let go of. Each surface answers for itself.
artworkRefresh()
@@ -615,6 +627,7 @@ Rectangle {
}
readonly property var artistsVisible: {
if (QbzLocal.localArtistsNativeActive && activeTab === "artists") return []
var q = artistsSearch.trim().toLowerCase()
if (q === "") return artists
var out = []
@@ -625,6 +638,7 @@ Rectangle {
}
readonly property int artistsVisibleCount: artistsVisible.length
readonly property var artistsGrouped: {
if (QbzLocal.localArtistsNativeActive && activeTab === "artists") return []
var rows = artistsVisible
var buckets = {}
var order = []
@@ -661,6 +675,7 @@ Rectangle {
// objects this view already parsed, in the published order.
readonly property var artistAlbums: {
if (selectedArtist === "") return []
if (QbzLocal.localArtistsNativeActive) return []
var rows = albums // binding dependency: re-derive on every republish
var ids = {}
try {
+126 -15
View File
@@ -20,6 +20,11 @@ Item {
readonly property int headerH: 22
readonly property int rowH: 62
readonly property bool nativeActive: QbzLocal.localArtistsNativeActive
readonly property var nativeModel: QbzLocalArtists
readonly property var nativeAlbumModel: QbzLocalArtistAlbums
readonly property int artistTotal: nativeActive
? QbzLocal.localArtistsNativeTotal : (view ? view.artists.length : 0)
// --------------------------- entry model ------------------------------
property var entries: []
@@ -32,7 +37,19 @@ Item {
property var flat: []
/// entry index -> index into `flat`, -1 for a letter header.
property var flatIndex: []
function parseNativeJumps() {
try { return JSON.parse(QbzLocal.localArtistsNativeJumpsJson || "[]") }
catch (e) { return [] }
}
function rebuild() {
if (nativeActive) {
entries = []
alphaJumps = parseNativeJumps()
flat = []
flatIndex = []
report()
return
}
var groups = view ? view.artistsGrouped : []
var out = []
var jumps = []
@@ -56,13 +73,51 @@ Item {
flatIndex = idx
report()
}
Component.onCompleted: { rebuild(); reportSoon() }
Component.onCompleted: {
rebuild()
reportSoon()
nativeQueryCoalescer.restart()
detailQueryCoalescer.restart()
}
Component.onDestruction: if (view) view.releaseWindow("artists-rail")
Connections {
target: root.view
function onArtistsGroupedChanged() { root.rebuild() }
function onArtistsSearchChanged() { root.nativeQueryCoalescer.restart() }
function onSelectedArtistChanged() { root.detailQueryCoalescer.restart() }
function onArtworkRefresh() { root.reportSoon() }
}
Connections {
target: QbzLocal
function onLocalArtistsNativeActiveChanged() {
root.rebuild()
if (root.nativeActive) root.detailQueryCoalescer.restart()
}
function onLocalArtistsNativeJumpsJsonChanged() {
if (root.nativeActive) root.alphaJumps = root.parseNativeJumps()
}
function onLocalArtistsLoadingChanged() {
if (!QbzLocal.localArtistsLoading) {
root.reportSoon()
root.detailQueryCoalescer.restart()
}
}
}
Timer {
id: nativeQueryCoalescer
interval: 0
onTriggered: if (root.view)
QbzLocal.artistsNativeReset(root.view.artistsSearch)
}
Timer {
id: detailQueryCoalescer
interval: 0
onTriggered: root.resetNativeDetail()
}
function resetNativeDetail() {
if (!nativeActive || !view || !artistCollection || artistCollection.cols <= 0) return
QbzLocal.artistsNativeSelect(view.selectedArtist, artistCollection.cols)
}
// Loading = the shape of the master/detail pair that is coming: 60px
// rail rows with a ROUND 48px avatar on the left, the album grid on the
@@ -97,7 +152,8 @@ Item {
}
// Empty library — icon + line (Slint :2222).
Column {
visible: !QbzLocal.localArtistsLoading && root.view.artists.length === 0
visible: !QbzLocal.localArtistsLoading && root.artistTotal === 0
&& (!root.view || root.view.artistsSearch === "")
anchors.centerIn: parent
spacing: 10
QbzIcon {
@@ -117,7 +173,8 @@ Item {
Row {
anchors.fill: parent
visible: !QbzLocal.localArtistsLoading && root.view.artists.length > 0
visible: !QbzLocal.localArtistsLoading
&& (root.artistTotal > 0 || (root.view && root.view.artistsSearch !== ""))
spacing: 0
// ---------------------- master rail ------------------------------
@@ -133,20 +190,23 @@ Item {
spacing: 8
Text {
text: root.view.artistsVisibleCount + " "
text: (root.nativeActive ? QbzLocal.localArtistsNativeTotal
: root.view.artistsVisibleCount) + " "
+ QbzSession.tr("artists", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
font.weight: theme.weightSemibold
}
Text {
visible: root.view.artistsVisibleCount === 0
visible: (root.nativeActive ? QbzLocal.localArtistsNativeTotal
: root.view.artistsVisibleCount) === 0
text: QbzSession.tr("No artists match your search.", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
}
Item {
visible: root.view.artistsVisibleCount > 0
visible: (root.nativeActive ? QbzLocal.localArtistsNativeTotal
: root.view.artistsVisibleCount) > 0
width: parent.width
height: parent.height - 30
@@ -159,7 +219,7 @@ Item {
clip: true
cacheBuffer: 62 * 8
boundsBehavior: Flickable.StopAtBounds
model: root.entries
model: root.nativeActive ? root.nativeModel : root.entries
onContentYChanged: root.report()
onModelChanged: root.report()
onHeightChanged: root.report()
@@ -172,7 +232,21 @@ Item {
required property var modelData
width: rail.width
height: modelData.t === 0 ? root.headerH : root.rowH
sourceComponent: modelData.t === 0 ? letterComp : artistComp
sourceComponent: modelData.loading ? loadingComp
: modelData.t === 0 ? letterComp : artistComp
onModelDataChanged: root.reportSoon()
Component {
id: loadingComp
QbzSkeleton {
variant: "rowList"
rowH: 60
rowGap: 2
rowArtSize: 48
rowArtRound: true
phase: root.view ? root.view.skelPhase : false
}
}
Component {
id: letterComp
@@ -192,7 +266,8 @@ Item {
width: rail.width
view: root.view
item: modelData.item
artSource: root.view.artMap[modelData.item.artKey] || ""
artSource: modelData.item.artPath
|| root.view.artMap[modelData.item.artKey] || ""
selected: root.view.selectedArtist === modelData.item.name
onPicked: function (name) { root.view.selectArtist(name) }
}
@@ -264,14 +339,19 @@ Item {
elide: Text.ElideRight
}
Text {
text: root.view.artistAlbums.length + " "
text: (root.nativeActive
? QbzLocal.localArtistAlbumsNativeTotal
: root.view.artistAlbums.length) + " "
+ QbzSession.tr("albums", QbzSession.trRev)
color: theme.textMuted
font.pixelSize: theme.fontLegal
}
}
Text {
visible: root.view.artistAlbums.length === 0
visible: !QbzLocal.localArtistAlbumsLoading
&& (root.nativeActive
? QbzLocal.localArtistAlbumsNativeTotal === 0
: root.view.artistAlbums.length === 0)
width: parent.width
topPadding: 24
text: QbzSession.tr("No albums found", QbzSession.trRev)
@@ -279,16 +359,33 @@ Item {
font.pixelSize: theme.fontBody
horizontalAlignment: Text.AlignHCenter
}
QbzSkeleton {
visible: root.nativeActive && QbzLocal.localArtistAlbumsLoading
width: parent.width
height: parent.height - 60
variant: "cardGrid"
cellW: 220
cellH: 266
phase: root.view.skelPhase
}
LocalAlbumCollection {
visible: root.view.artistAlbums.length > 0
id: artistCollection
visible: !QbzLocal.localArtistAlbumsLoading
&& (root.nativeActive
? QbzLocal.localArtistAlbumsNativeTotal > 0
: root.view.artistAlbums.length > 0)
width: parent.width
height: parent.height - 60
view: root.view
surface: "artist-albums"
rows: root.view.artistAlbums
rows: root.nativeActive ? [] : root.view.artistAlbums
grouped: false
viewMode: "grid"
showSource: true
nativeActive: root.nativeActive
nativeModel: root.nativeAlbumModel
nativeJumpsJson: "[]"
onColsChanged: root.detailQueryCoalescer.restart()
onOpenRequested: function (id) { root.view.openAlbum(id) }
onPlayRequested: function (id) { QbzLocal.playAlbum(id, false) }
onEnqueueRequested: function (id, m) { QbzLocal.enqueue("album", id, m) }
@@ -308,14 +405,28 @@ Item {
// when the viewport resizes.
function report() {
if (!view || !rail) return
if (!rail.visible || root.entries.length === 0) {
var count = root.nativeActive ? root.nativeModel.totalCount : root.entries.length
if (!rail.visible || count === 0) {
view.releaseWindow("artists-rail")
return
}
var first = rail.indexAt(4, rail.contentY + 1)
var last = rail.indexAt(4, rail.contentY + Math.max(1, rail.height) - 1)
if (first < 0) first = 0
if (last < 0) last = Math.min(root.entries.length - 1, first + 12)
if (last < 0) last = Math.min(count - 1, first + 12)
if (root.nativeActive) {
var resident = []
for (var entryIndex = first; entryIndex <= last; entryIndex++) {
var entry = root.nativeModel.rowAt(entryIndex)
if (!entry || entry.loading || entry.t !== 1 || !entry.item) continue
resident.push(entry.item)
}
if (resident.length > 0)
view.queueWindowReport(resident, 0, resident.length - 1, "artists-rail")
else
view.releaseWindow("artists-rail")
return
}
// Entry band -> rail-row band (letter headers do not carry a cover).
var lo = -1
var hi = -1
+15 -2
View File
@@ -355,9 +355,22 @@ Row {
// ============================ ARTISTS ================================
LocalSearchBox {
visible: root.view && root.view.activeTab === "artists"
&& root.view.artists.length > 0
&& ((QbzLocal.localArtistsNativeActive
? QbzLocal.localArtistsNativeTotal > 0
: root.view.artists.length > 0)
|| root.view.artistsSearch !== ""
|| QbzLocal.localArtistsLoading)
anchors.verticalCenter: parent.verticalCenter
placeholder: QbzSession.tr("Search artists", QbzSession.trRev)
onEdited: function (v) { root.view.artistsSearch = v }
property string pending: ""
onEdited: function (v) {
pending = v
artistsSearchDebounce.restart()
}
Timer {
id: artistsSearchDebounce
interval: 200
onTriggered: root.view.artistsSearch = parent.pending
}
}
}
File diff suppressed because it is too large. Load diff
+69
View File
@@ -68,6 +68,13 @@ pub mod qbz_local {
// --- Artists tab --------------------------------------------------
#[qproperty(bool, local_artists_loading)]
#[qproperty(QString, local_artists_json)]
/// Phase-F2 surface switch. False keeps the legacy JSON rail/pane.
#[qproperty(bool, local_artists_native_active)]
#[qproperty(i64, local_artists_native_total)]
#[qproperty(i64, local_artist_albums_native_total)]
#[qproperty(bool, local_artist_albums_loading)]
#[qproperty(QString, local_artists_native_jumps_json)]
#[qproperty(QString, local_artists_native_error)]
// --- Folders tab, FLAT mode ---------------------------------------
#[qproperty(bool, local_folders_loading)]
@@ -283,6 +290,28 @@ pub mod qbz_local {
#[qinvokable]
fn albums_native_bulk_action(self: Pin<&mut QbzLocal>, action: QString);
// --- Artists tab (native paged models) ---------------------------
#[qinvokable]
fn artists_native_reset(self: Pin<&mut QbzLocal>, search: QString);
#[qinvokable]
fn artists_native_page_miss(
self: Pin<&mut QbzLocal>,
page: i32,
generation: i32,
);
#[qinvokable]
fn artists_native_select(
self: Pin<&mut QbzLocal>,
artist: QString,
columns: i32,
);
#[qinvokable]
fn artist_albums_native_page_miss(
self: Pin<&mut QbzLocal>,
page: i32,
generation: i32,
);
// --- Tracks tab ----------------------------------------------------
/// Toolbar search (server-side; resets to page 1).
#[qinvokable]
@@ -609,6 +638,12 @@ pub struct QbzLocalRust {
local_albums_native_error: QString,
local_artists_loading: bool,
local_artists_json: QString,
local_artists_native_active: bool,
local_artists_native_total: i64,
local_artist_albums_native_total: i64,
local_artist_albums_loading: bool,
local_artists_native_jumps_json: QString,
local_artists_native_error: QString,
local_folders_loading: bool,
local_folders_json: QString,
local_tree_loading: bool,
@@ -676,6 +711,12 @@ impl Default for QbzLocalRust {
local_albums_native_error: QString::default(),
local_artists_loading: false,
local_artists_json: QString::from("[]"),
local_artists_native_active: false,
local_artists_native_total: 0,
local_artist_albums_native_total: 0,
local_artist_albums_loading: false,
local_artists_native_jumps_json: QString::from("[]"),
local_artists_native_error: QString::default(),
local_folders_loading: false,
local_folders_json: QString::from("[]"),
local_tree_loading: false,
@@ -850,6 +891,34 @@ impl qbz_local::QbzLocal {
crate::local_albums_model_qt::bulk_action(action.to_string());
}
pub fn artists_native_reset(self: Pin<&mut Self>, search: QString) {
crate::local_artists_model_qt::reset(search.to_string());
}
pub fn artists_native_page_miss(
self: Pin<&mut Self>,
page: i32,
generation: i32,
) {
crate::local_artists_model_qt::request_page(page, generation);
}
pub fn artists_native_select(
self: Pin<&mut Self>,
artist: QString,
columns: i32,
) {
crate::local_artists_model_qt::select_artist(artist.to_string(), columns);
}
pub fn artist_albums_native_page_miss(
self: Pin<&mut Self>,
page: i32,
generation: i32,
) {
crate::local_artists_model_qt::request_detail_page(page, generation);
}
pub fn tracks_search(self: Pin<&mut Self>, query: QString) {
lib::set_tracks_query(&query.to_string());
load_tracks(true);
+14
View File
@@ -301,6 +301,20 @@ pub(crate) fn invalidate_artists() {
}
pub(crate) fn load_artists() {
ui(|mut b| b.as_mut().set_local_artists_loading(true));
if crate::local_artists_model_qt::requested()
&& crate::local_library_qt::album_mode() == "folder"
{
crate::local_artists_model_qt::retry_last();
return;
}
load_artists_legacy();
if lib::state(|state| state.albums.is_empty()) {
load_albums_legacy();
}
}
pub(crate) fn load_artists_legacy() {
ui(|mut b| b.as_mut().set_local_artists_loading(true));
crate::spawn(async move {
let rows = tokio::task::spawn_blocking(lib::load_artists_blocking)
+6
View File
@@ -147,6 +147,9 @@ pub(crate) fn start() {
if ready && crate::local_albums_model_qt::requested() {
crate::local_albums_model_qt::retry_last();
}
if ready && crate::local_artists_model_qt::requested() {
crate::local_artists_model_qt::retry_last();
}
}
Ok(Err(CatalogError::InsufficientSpace {
required_bytes,
@@ -258,6 +261,9 @@ pub(crate) fn request_catch_up() {
if ready && crate::local_albums_model_qt::requested() {
crate::local_albums_model_qt::retry_last();
}
if ready && crate::local_artists_model_qt::requested() {
crate::local_artists_model_qt::retry_last();
}
}
Ok(Err(CatalogError::InsufficientSpace {
required_bytes,
+3
View File
@@ -186,6 +186,8 @@ mod local_catalog_qt;
mod local_tracks_model_qt;
// Native bounded Albums entry model (phase F1); grid/list geometry stays QML.
mod local_albums_model_qt;
// Native paged Artists rail + indexed artist-album pane (phase F2).
mod local_artists_model_qt;
mod local_plex;
// Plex PIN sign-in (the "Authorize" half of the Plex settings) + the
// Check-connection ping. Over `qbz_plex`'s existing pin/start, pin/check and
@@ -3040,6 +3042,7 @@ fn main() {
// registration itself runs at QCoreApplication startup.
local_tracks_model_qt::register_qml_model();
local_albums_model_qt::register_qml_model();
local_artists_model_qt::register_qml_model();
// BEFORE any restore reads a pref: read + increment the crash chain, so a
// boot that dies from a restored view or queue degrades the NEXT boot
// instead of trapping the user in a loop it cannot escape from inside the