From d07568fef1fa03eb565249d7134ca6f5b5da022d Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:06:48 +0700 Subject: [PATCH] feat(home): show Library albums in On repeat's place without a listening record A tester turned "Record listening" off and still saw On repeat on Home. The shelf reads the last four weeks of the statistics and never looked at the switch, so songs recorded earlier stayed until they aged out. Tapping one then started a queue of the shelf, which read as an old queue coming back. With the switch off, the played shelves (On repeat, and Recently Played in the Mornye style) are now empty and do not read the statistics. The record itself is kept, so they return when the switch goes back on. So Home keeps its number of sections, On repeat's place is taken by "From your Library": ten albums of the Library, picked anew each day. Each album gets its place in the day's order from a stable hash of the day and its key, so a download landing mid-day swaps one cover at most instead of reshuffling the shelf. A Library of more than 300 albums is read through a window that moves with the day. Choosing a cover opens the album. The shelf is read only while the switch is off. --- lib/l10n/arb/app_en.arb | 4 + lib/l10n/arb/app_id.arb | 4 + lib/screens/home_tab.dart | 4 + lib/screens/home_tab_intro.dart | 182 ++++++++++++++++++++++++++ lib/services/library_mixes.dart | 4 +- test/home_library_albums_test.dart | 203 +++++++++++++++++++++++++++++ test/home_shelves_test.dart | 64 ++++++++- 7 files changed, 460 insertions(+), 5 deletions(-) create mode 100644 test/home_library_albums_test.dart diff --git a/lib/l10n/arb/app_en.arb b/lib/l10n/arb/app_en.arb index 2a068afab..3d5f0b8dd 100644 --- a/lib/l10n/arb/app_en.arb +++ b/lib/l10n/arb/app_en.arb @@ -9570,6 +9570,10 @@ "@homeOnRepeat": { "description": "Home section header for the most played tracks of the last four weeks" }, + "homeFromYourLibrary": "From your Library", + "@homeFromYourLibrary": { + "description": "Home section header for the day's albums from the Library, shown in On repeat's place while listening is not recorded" + }, "homeShortcuts": "Shortcuts", "@homeShortcuts": { "description": "Home section header for quick links to player tools" diff --git a/lib/l10n/arb/app_id.arb b/lib/l10n/arb/app_id.arb index 75e98dfc5..d9704e54d 100644 --- a/lib/l10n/arb/app_id.arb +++ b/lib/l10n/arb/app_id.arb @@ -8236,6 +8236,10 @@ "@homeOnRepeat": { "description": "Home section header for the most played tracks of the last four weeks" }, + "homeFromYourLibrary": "Dari Koleksimu", + "@homeFromYourLibrary": { + "description": "Home section header for the day's albums from the Library, shown in On repeat's place while listening is not recorded" + }, "homeShortcuts": "Pintasan", "@homeShortcuts": { "description": "Home section header for quick links to player tools" diff --git a/lib/screens/home_tab.dart b/lib/screens/home_tab.dart index 711b60216..27de5c1d0 100644 --- a/lib/screens/home_tab.dart +++ b/lib/screens/home_tab.dart @@ -54,6 +54,7 @@ import 'package:mornye/services/weekly_releases.dart'; import 'package:mornye/widgets/desktop/desktop_scroll_arrows.dart'; import 'package:mornye/widgets/desktop/hover_play_button.dart'; import 'package:mornye/widgets/explore_featured_section.dart'; +import 'package:mornye/providers/library_browse_provider.dart'; import 'package:mornye/providers/library_counts_provider.dart'; import 'package:mornye/providers/library_mixes_provider.dart'; import 'package:mornye/providers/local_library_provider.dart'; @@ -71,6 +72,7 @@ import 'package:mornye/screens/music_recognition_screen.dart'; import 'package:mornye/screens/network_storage_screen.dart'; import 'package:mornye/screens/now_playing_screen.dart'; import 'package:mornye/services/library_database.dart'; +import 'package:mornye/services/library_mixes.dart' show stableTextHash; import 'package:mornye/services/listening_statistics.dart'; import 'package:mornye/services/music_player_service.dart' show PlayableMedia; import 'package:mornye/screens/track_metadata_screen.dart'; @@ -93,6 +95,7 @@ import 'package:mornye/utils/file_access.dart'; import 'package:mornye/utils/home_greeting.dart'; import 'package:mornye/screens/playlist_screen.dart'; import 'package:mornye/screens/downloaded_album_screen.dart'; +import 'package:mornye/screens/local_album_screen.dart'; import 'package:mornye/widgets/download_service_picker.dart'; import 'package:mornye/widgets/track_collection_quick_actions.dart'; import 'package:mornye/widgets/desktop/context_menu.dart'; @@ -102,6 +105,7 @@ import 'package:mornye/widgets/audio_quality_badges.dart'; import 'package:mornye/widgets/cached_cover_image.dart'; import 'package:mornye/widgets/extension_icon_image.dart'; import 'package:mornye/widgets/library_mix_cover.dart'; +import 'package:mornye/widgets/local_library_artwork_builder.dart'; import 'package:mornye/widgets/player_artwork.dart'; import 'package:mornye/widgets/error_card.dart'; import 'package:mornye/widgets/in_library_badge.dart'; diff --git a/lib/screens/home_tab_intro.dart b/lib/screens/home_tab_intro.dart index 0b2f514f1..30cc4be59 100644 --- a/lib/screens/home_tab_intro.dart +++ b/lib/screens/home_tab_intro.dart @@ -139,6 +139,86 @@ final homeRecentlyPlayedProvider = return memo.recentlyPlayed = tracks; }); +/// Albums read for the day's picks; a larger Library moves the window daily. +const _homeAlbumPool = 300; + +/// Where the day's window starts among [albumCount] albums. +@visibleForTesting +int homeLibraryAlbumPoolOffset(int albumCount, String day) => + albumCount <= _homeAlbumPool + ? 0 + : stableTextHash(day) % (albumCount - _homeAlbumPool + 1); + +/// The day's albums from [pool]. Each album has its own place in the day's +/// order, so a Library change swaps a cover instead of the whole shelf. +@visibleForTesting +List homeLibraryAlbumPicks( + List pool, { + required String day, + int limit = _homeShelfLimit, +}) { + final order = { + for (final album in pool) + if (album.name.trim().isNotEmpty) + album: stableTextHash('$day|${album.source}|${album.key}'), + }; + final albums = order.keys.toList() + ..sort((a, b) { + final byOrder = order[a]!.compareTo(order[b]!); + return byOrder != 0 ? byOrder : a.key.compareTo(b.key); + }); + return albums.take(limit).toList(); +} + +/// Albums of the Library, picked anew each day. Home shows them in On +/// repeat's place while listening is not recorded. +final homeLibraryAlbumsProvider = + FutureProvider.autoDispose>((ref) async { + final includeLocal = ref.watch( + settingsProvider.select((s) => s.localLibraryEnabled), + ); + ref.watch(downloadHistoryProvider.select((s) => s.loadedIndexVersion)); + if (includeLocal) ref.watch(localLibraryIndexRevisionProvider); + final memo = ref.read(_homeShelfMemoProvider); + final counts = await ref.watch( + libraryCountsProvider( + LibraryCountsRequest.all(localLibraryEnabled: includeLocal), + ).future, + ); + final day = listeningDay(DateTime.now()); + final page = await LibraryDatabase.instance.getQueueAlbumPageResult( + QueueLibraryDbQuery( + includeLocal: includeLocal, + sortMode: 'a-z', + limit: _homeAlbumPool, + offset: homeLibraryAlbumPoolOffset(counts.albumCount, day), + ), + ); + final albums = homeLibraryAlbumPicks([ + for (final row in page.rows) + LibraryBrowseEntry.fromRow(row, isArtist: false), + ], day: day); + final last = memo.libraryAlbums; + if (last != null && _sameAlbums(last, albums)) return last; + return memo.libraryAlbums = albums; + }); + +bool _sameAlbums(List a, List b) { + if (a.length != b.length) return false; + for (var index = 0; index < a.length; index++) { + final one = a[index], other = b[index]; + if (one.source != other.source || + one.key != other.key || + one.name != other.name || + one.artist != other.artist || + one.cover != other.cover || + one.samplePath != other.samplePath) { + return false; + } + } + return true; +} + /// Up to [limit] played songs of the last four weeks that can be played /// again, matched to the Library. Reloads with what changes them. Future> _homeReplayableTracks( @@ -146,6 +226,12 @@ Future> _homeReplayableTracks( required int limit, bool latestFirst = false, }) async { + // Turning the record off hides what it already holds, without clearing it. + if (!ref.watch( + settingsProvider.select((s) => s.listeningStatisticsEnabled), + )) { + return const []; + } // A track that ends may have just earned a play. One that starts after // none, such as a restored session's, follows no play. ref.listen(currentMediaItemProvider.select((s) => s.value?.id), ( @@ -325,6 +411,7 @@ class _HomeShelfMemo { Map repeatMatches = {}; List? onRepeat; List? recentlyPlayed; + List? libraryAlbums; } final _homeShelfMemoProvider = Provider<_HomeShelfMemo>( @@ -370,6 +457,12 @@ class _HomeSections extends ConsumerWidget { ); final onRepeat = ref.watch(homeOnRepeatProvider.select((s) => s.value)) ?? const []; + // Read only without a listening record, when they take On repeat's place. + final libraryAlbums = + ref.watch(settingsProvider.select((s) => s.listeningStatisticsEnabled)) + ? const [] + : ref.watch(homeLibraryAlbumsProvider.select((s) => s.value)) ?? + const []; final mixes = ref.watch(libraryMixesProvider.select((s) => s.value)) ?? const []; final newReleases = @@ -468,6 +561,16 @@ class _HomeSections extends ConsumerWidget { tracks: onRepeat, inset: mornye ? inset + 8 : inset, ), + ) + else if (libraryAlbums.isNotEmpty) + _HomeSection( + title: l10n.homeFromYourLibrary, + inset: inset, + shelf: true, + child: _HomeLibraryAlbumsShelf( + albums: libraryAlbums, + inset: mornye ? inset + 8 : inset, + ), ), ]; @@ -1385,6 +1488,85 @@ class _HomeRecentlyPlayedShelf extends ConsumerWidget { } } +/// Library albums as covers named by album. Choosing one opens the album. +class _HomeLibraryAlbumsShelf extends StatelessWidget { + const _HomeLibraryAlbumsShelf({required this.albums, required this.inset}); + + final List albums; + final double inset; + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return _HomeShelfSize( + inset: inset, + builder: (context, coverSize) { + final cacheWidth = (coverSize * MediaQuery.devicePixelRatioOf(context)) + .round(); + return _HomeShelf( + inset: inset, + coverSize: coverSize, + itemCount: albums.length, + itemBuilder: (context, index) { + final album = albums[index]; + return _HomeShelfTile( + size: coverSize, + title: album.name, + subtitle: album.artist, + semanticLabel: context.l10n.a11yOpenAlbum(album.name), + cover: album.source == 'local' + ? LocalLibraryArtworkBuilder( + coverPath: album.cover, + filePath: album.samplePath, + builder: (context, cover) => PlayerArtwork( + artUri: cover, + colorScheme: colorScheme, + cacheWidth: cacheWidth, + iconSize: 32, + ), + ) + : _DownloadedOrRemoteCover( + downloadedFilePath: album.samplePath, + imageUrl: album.cover, + width: coverSize, + height: coverSize, + borderRadius: BorderRadius.zero, + fallbackIcon: Icons.album_outlined, + fallbackIconSize: 32, + colorScheme: colorScheme, + ), + onTap: () => _open(context, album), + ); + }, + ); + }, + ); + } + + void _open(BuildContext context, LibraryBrowseEntry album) { + pushPage( + context, + (_) => album.source == 'local' + ? LocalAlbumScreen( + albumName: album.name, + artistName: album.artist, + coverPath: album.cover, + loadTracks: () async => [ + for (final row + in await LibraryDatabase.instance + .getQueueLocalAlbumTracksByKey(album.key)) + LocalLibraryItem.fromJson(row), + ], + ) + : DownloadedAlbumScreen( + albumName: album.name, + artistName: album.artist, + coverUrl: album.cover, + ), + ); + } +} + void _homePlayRepeatTracks( WidgetRef ref, List tracks, diff --git a/lib/services/library_mixes.dart b/lib/services/library_mixes.dart index 685f3504b..3219d22b9 100644 --- a/lib/services/library_mixes.dart +++ b/lib/services/library_mixes.dart @@ -578,7 +578,7 @@ bool _remote(String source) => /// A stable 32-bit FNV-1a hash, since [String.hashCode] may change between /// runs. -int _stableHash(String value) { +int stableTextHash(String value) { var hash = 0x811c9dc5; for (final unit in value.codeUnits) { hash = ((hash ^ unit) * 0x01000193) & 0xffffffff; @@ -846,7 +846,7 @@ class _MixBuilder { } Random _random(LibraryMixKind kind, String key) => - Random(_stableHash('$day|${kind.name}|$key')); + Random(stableTextHash('$day|${kind.name}|$key')); LibraryMix? _favorites() { final played = songs.where((song) => plays(song) > 0).toList() diff --git a/test/home_library_albums_test.dart b/test/home_library_albums_test.dart new file mode 100644 index 000000000..58fdea6df --- /dev/null +++ b/test/home_library_albums_test.dart @@ -0,0 +1,203 @@ +import 'package:audio_service/audio_service.dart' show MediaItem; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:mornye/l10n/app_localizations.dart'; +import 'package:mornye/models/settings.dart'; +import 'package:mornye/models/unified_library_item.dart'; +import 'package:mornye/providers/download_history_provider.dart'; +import 'package:mornye/providers/explore_provider.dart'; +import 'package:mornye/providers/extension_provider.dart'; +import 'package:mornye/providers/home_top_picks_provider.dart'; +import 'package:mornye/providers/library_browse_provider.dart'; +import 'package:mornye/providers/library_mixes_provider.dart'; +import 'package:mornye/providers/music_player_provider.dart'; +import 'package:mornye/providers/recent_access_provider.dart'; +import 'package:mornye/providers/settings_provider.dart'; +import 'package:mornye/providers/weekly_releases_provider.dart'; +import 'package:mornye/screens/home_tab.dart'; +import 'package:mornye/services/weekly_releases.dart'; +import 'package:mornye/theme/app_theme.dart'; +import 'package:mornye/theme/mornye_theme.dart'; + +import 'support/fixed_settings.dart'; + +const _title = 'From your Library'; + +LibraryBrowseEntry _album(int index, {String? name}) => LibraryBrowseEntry( + source: 'downloaded', + key: 'album-$index', + name: name ?? 'Album $index', + artist: 'Artist', + samplePath: '', + trackCount: 2, +); + +List _keys(List albums) => [ + for (final album in albums) album.key, +]; + +/// Home without extensions, a feed or a played song, with [albums] as the +/// Library's albums of the day. +Widget _home({ + required bool mornye, + required bool recordListening, + required List albums, +}) => ProviderScope( + overrides: [ + homeNewReleasesProvider.overrideWith( + (ref) => Stream.value(const []), + ), + settingsProvider.overrideWith( + () => FixedSettingsNotifier( + AppSettings( + homeFeedProvider: AppSettings.homeFeedProviderOff, + listeningStatisticsEnabled: recordListening, + ), + ), + ), + extensionProvider.overrideWith(_Extensions.new), + exploreProvider.overrideWith(_Explore.new), + downloadHistoryProvider.overrideWith(_History.new), + recentAccessProvider.overrideWith(_Recent.new), + libraryMixesProvider.overrideWith((ref) async => const []), + homeTopPicksProvider.overrideWith((ref) async => const []), + homeRecentlyAddedProvider.overrideWith( + (ref) async => (items: const [], trackCount: 0), + ), + homeRecentlyPlayedProvider.overrideWith((ref) async => const []), + homeOnRepeatProvider.overrideWith((ref) async => const []), + homeLibraryAlbumsProvider.overrideWith((ref) async => albums), + playerUiEnabledProvider.overrideWithValue(true), + currentMediaItemProvider.overrideWithBuild( + (ref, notifier) => Stream.value(null), + ), + playbackResumeProvider.overrideWith((ref) async => null), + ], + child: MaterialApp( + theme: mornye ? MornyeTheme.build(Brightness.dark) : AppTheme.dark(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const HomeTab(mode: HomeTabMode.browse), + ), +); + +Future _open(WidgetTester tester, Widget home) async { + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(home); + for (var frame = 0; frame < 6; frame++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +void main() { + group('the day\'s albums', () { + final pool = [for (var index = 0; index < 40; index++) _album(index)]; + + test('are the same however the Library lists them', () { + final picks = homeLibraryAlbumPicks(pool, day: '2026-11-19'); + expect(picks, hasLength(10)); + expect( + _keys(homeLibraryAlbumPicks(pool.reversed.toList(), day: '2026-11-19')), + _keys(picks), + ); + }); + + test('change with the day', () { + expect( + _keys(homeLibraryAlbumPicks(pool, day: '2026-11-20')), + isNot(_keys(homeLibraryAlbumPicks(pool, day: '2026-11-19'))), + ); + }); + + test('keep their order when the Library gains an album', () { + final before = _keys(homeLibraryAlbumPicks(pool, day: '2026-11-19')); + for (var index = 40; index < 60; index++) { + final after = _keys( + homeLibraryAlbumPicks([...pool, _album(index)], day: '2026-11-19'), + )..remove('album-$index'); + expect(after, before.take(after.length)); + } + }); + + test('leave out an album without a name', () { + final picks = homeLibraryAlbumPicks([ + _album(0, name: ' '), + _album(1), + ], day: '2026-11-19'); + expect(_keys(picks), ['album-1']); + }); + + test('come from a window inside a large Library', () { + expect(homeLibraryAlbumPoolOffset(0, '2026-11-19'), 0); + expect(homeLibraryAlbumPoolOffset(300, '2026-11-19'), 0); + final offsets = { + for (var day = 10; day < 30; day++) + homeLibraryAlbumPoolOffset(1000, '2026-11-$day'), + }; + expect(offsets.every((offset) => offset >= 0 && offset <= 700), isTrue); + expect(offsets.length, greaterThan(1)); + }); + }); + + for (final mornye in [false, true]) { + final style = mornye ? 'Mornye' : 'Material'; + + testWidgets('the $style Home shows Library albums without a listening ' + 'record', (tester) async { + await _open( + tester, + _home( + mornye: mornye, + recordListening: false, + albums: [_album(0), _album(1)], + ), + ); + expect(tester.takeException(), isNull); + + expect(find.text(_title), findsOneWidget); + expect(find.text('Album 0'), findsOneWidget); + expect(find.text('On repeat'), findsNothing); + }); + + testWidgets('the $style Home leaves them out while listening is ' + 'recorded', (tester) async { + await _open( + tester, + _home( + mornye: mornye, + recordListening: true, + albums: [_album(0), _album(1)], + ), + ); + expect(tester.takeException(), isNull); + + expect(find.text(_title), findsNothing); + }); + } +} + +class _Extensions extends ExtensionNotifier { + @override + ExtensionState build() => const ExtensionState(); +} + +class _Explore extends ExploreNotifier { + @override + ExploreState build() => const ExploreState(); + + @override + Future fetchHomeFeed({bool forceRefresh = false}) async {} +} + +class _History extends DownloadHistoryNotifier { + @override + DownloadHistoryState build() => DownloadHistoryState(); +} + +class _Recent extends RecentAccessNotifier { + @override + RecentAccessState build() => const RecentAccessState(isLoaded: true); +} diff --git a/test/home_shelves_test.dart b/test/home_shelves_test.dart index 42650f7b9..ab5d17610 100644 --- a/test/home_shelves_test.dart +++ b/test/home_shelves_test.dart @@ -70,7 +70,12 @@ Map _download(String id, String path, {int number = 1}) => { 'isrc': 'ISRC-$id', }; -Future _addScanned(String id, String path, {String? source}) async { +Future _addScanned( + String id, + String path, { + String? source, + String? album, +}) async { final db = await LibraryDatabase.instance.database; await db.insert( 'library', @@ -80,7 +85,7 @@ Future _addScanned(String id, String path, {String? source}) async { sourceId: source ?? LibraryDatabase.legacySourceId, trackName: 'Scanned $id', artistName: 'Artist', - albumName: 'Album $id', + albumName: album ?? 'Album $id', filePath: path, scannedAt: DateTime.utc(2026, 10, 1), ).toJson(), @@ -138,6 +143,7 @@ final _media = StreamController.broadcast(); ProviderContainer _container({ required bool includeLocal, + bool recordListening = true, List inMemory = const [], List overrides = const [], }) { @@ -145,7 +151,10 @@ ProviderContainer _container({ overrides: [ settingsProvider.overrideWith( () => FixedSettingsNotifier( - AppSettings(localLibraryEnabled: includeLocal), + AppSettings( + localLibraryEnabled: includeLocal, + listeningStatisticsEnabled: recordListening, + ), ), ), downloadHistoryProvider.overrideWith( @@ -362,6 +371,55 @@ void main() { }); }); + group('Without a listening record', () { + test('the played shelves stay empty and read no statistics', () async { + await HistoryDatabase.instance.upsertBatch([ + _download('d0', _path('d0.flac')), + ]); + await _played(_path('d0.flac'), 600000); + + final recording = _container(includeLocal: true); + expect(await recording.read(homeOnRepeatProvider.future), hasLength(1)); + expect( + await recording.read(homeRecentlyPlayedProvider.future), + hasLength(1), + ); + + _statements.clear(); + final off = _container(includeLocal: true, recordListening: false); + expect(await off.read(homeOnRepeatProvider.future), isEmpty); + expect(await off.read(homeRecentlyPlayedProvider.future), isEmpty); + expect(_ran(_statisticsRead), 0); + }); + + for (final includeLocal in [true, false]) { + test('the day\'s albums are the Library\'s albums ' + '(Local Library ${includeLocal ? 'on' : 'off'})', () async { + await HistoryDatabase.instance.upsertBatch([ + for (final (index, album) in ['First', 'First', 'Second'].indexed) + { + ..._download('d$index', _path('d$index.flac'), number: index), + 'albumName': album, + }, + ]); + for (var index = 0; index < 2; index++) { + await _addScanned('s$index', _path('s$index.flac'), album: 'Scanned'); + } + + final container = _container( + includeLocal: includeLocal, + recordListening: false, + ); + final albums = await container.read(homeLibraryAlbumsProvider.future); + // An album of one song is a single, not an album. + expect( + {for (final album in albums) '${album.source}:${album.name}'}, + {'downloaded:First', if (includeLocal) 'local:Scanned'}, + ); + }); + } + }); + group('On Repeat', () { /// Downloads, scanned files (one on an offline source), files outside /// the Library that exist or are gone, streams, songs never counted as