Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29758eb9bb | ||
|
|
332de9e00c | ||
|
|
6f503c8540 | ||
|
|
9950ff2063 | ||
|
|
4c777a93e1 | ||
|
|
a96578bbf0 | ||
|
|
8fa95705e1 | ||
|
|
9dcca2ce54 | ||
|
|
4152c3d67f | ||
|
|
d84fb58a5c | ||
|
|
128d417014 | ||
|
|
176fa5c8b9 | ||
|
|
ccaf764f52 | ||
|
|
ccda231fb2 | ||
|
|
0f82829172 | ||
|
|
0ccde33c85 | ||
|
|
3f9fb5d1e9 | ||
|
|
62e6498b11 | ||
|
|
40dd26519d | ||
|
|
28da46ad05 | ||
|
|
49cdf67c5c | ||
|
|
2b6e1d73dc | ||
|
|
40debeea06 | ||
|
|
60a824d55a | ||
|
|
2897a4eaa4 | ||
|
|
c36a971125 | ||
|
|
f08f737b6f | ||
|
|
1161dbb129 | ||
|
|
5d4fc5334c | ||
|
|
f93494469d | ||
|
|
a94fcff758 | ||
|
|
1870724875 | ||
|
|
bd3a2f98e8 | ||
|
|
516de13894 | ||
|
|
d7188a8784 | ||
|
|
c03ea6a14b | ||
|
|
d418af45f1 | ||
|
|
ac05381038 | ||
|
|
4d29e32651 | ||
|
|
91795976ff | ||
|
|
484000bc6e | ||
|
|
e373053f03 | ||
|
|
31ef8edaf0 | ||
|
|
ff568ebf56 | ||
|
|
ee6f00d56b | ||
|
|
fff5c91b5c | ||
|
|
cd27aee7b8 |
@@ -0,0 +1,52 @@
|
|||||||
|
# Search Improvements
|
||||||
|
|
||||||
|
Branch: `feature/search-improvements`
|
||||||
|
|
||||||
|
## Completed
|
||||||
|
|
||||||
|
- [x] Add playlists and audiobooks to search results
|
||||||
|
- Parse from MA API response
|
||||||
|
- Filter chips for each type
|
||||||
|
- Tile builders with navigation to detail screens
|
||||||
|
|
||||||
|
- [x] Unified Relevance-Based "All" Results
|
||||||
|
- Scoring algorithm implemented:
|
||||||
|
- Exact match: 100 points
|
||||||
|
- Starts with query: 80 points
|
||||||
|
- Contains query (word boundary): 60 points
|
||||||
|
- Contains query (anywhere): 40 points
|
||||||
|
- Fuzzy match: 20 points
|
||||||
|
- Bonus for library items (albums): +10 points
|
||||||
|
- Bonus for favorites: +5 points
|
||||||
|
- Secondary field matching (artist name in albums/tracks)
|
||||||
|
- Merged all results into single sorted list
|
||||||
|
- Type indicators in subtitle (e.g., "Artist • Album")
|
||||||
|
|
||||||
|
- [x] Smart Cross-Referencing
|
||||||
|
- Extracts unique artists from matched tracks/albums
|
||||||
|
- Filters to artists whose name contains query words (min 3 chars)
|
||||||
|
- Adds cross-referenced artists with lower relevance score (25)
|
||||||
|
- Avoids duplicates with direct search results
|
||||||
|
|
||||||
|
- [x] Past Searches Row
|
||||||
|
- Added SearchHistory table to database (schema v4)
|
||||||
|
- Saves successful searches (deduplicated, max 10)
|
||||||
|
- Displays as ActionChips in empty state
|
||||||
|
- Clicking chip performs that search
|
||||||
|
|
||||||
|
## Remaining Ideas (Lower Priority)
|
||||||
|
|
||||||
|
- **Library-only toggle:** Add switch to filter search to library items only (MA API supports this)
|
||||||
|
- **Voice search:** Add microphone button if platform supports speech recognition
|
||||||
|
- **Search suggestions:** Typeahead from library as user types
|
||||||
|
- **Quick actions:** Long-press result for play/queue options without navigating
|
||||||
|
- **Clear history in settings:** Add option to clear search history
|
||||||
|
|
||||||
|
## Files Modified
|
||||||
|
|
||||||
|
| File | Changes |
|
||||||
|
|------|---------|
|
||||||
|
| `lib/database/database.dart` | Added SearchHistory table, schema v4 |
|
||||||
|
| `lib/services/database_service.dart` | Added search history methods |
|
||||||
|
| `lib/screens/search_screen.dart` | Relevance scoring, cross-refs, history UI |
|
||||||
|
| `lib/l10n/app_en.arb` | Added localization strings |
|
||||||
@@ -168,12 +168,24 @@ class HomeRowCache extends Table {
|
|||||||
Set<Column> get primaryKey => {rowType};
|
Set<Column> get primaryKey => {rowType};
|
||||||
}
|
}
|
||||||
|
|
||||||
@DriftDatabase(tables: [Profiles, RecentlyPlayed, LibraryCache, SyncMetadata, PlaybackState, CachedPlayers, CachedQueue, HomeRowCache])
|
/// Search history for quick access to recent searches
|
||||||
|
class SearchHistory extends Table {
|
||||||
|
/// Auto-incrementing ID
|
||||||
|
IntColumn get id => integer().autoIncrement()();
|
||||||
|
|
||||||
|
/// The search query
|
||||||
|
TextColumn get query => text()();
|
||||||
|
|
||||||
|
/// When the search was performed
|
||||||
|
DateTimeColumn get searchedAt => dateTime()();
|
||||||
|
}
|
||||||
|
|
||||||
|
@DriftDatabase(tables: [Profiles, RecentlyPlayed, LibraryCache, SyncMetadata, PlaybackState, CachedPlayers, CachedQueue, HomeRowCache, SearchHistory])
|
||||||
class AppDatabase extends _$AppDatabase {
|
class AppDatabase extends _$AppDatabase {
|
||||||
AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());
|
AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());
|
||||||
|
|
||||||
@override
|
@override
|
||||||
int get schemaVersion => 3;
|
int get schemaVersion => 4;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
MigrationStrategy get migration {
|
MigrationStrategy get migration {
|
||||||
@@ -192,6 +204,10 @@ class AppDatabase extends _$AppDatabase {
|
|||||||
if (from < 3) {
|
if (from < 3) {
|
||||||
await m.createTable(homeRowCache);
|
await m.createTable(homeRowCache);
|
||||||
}
|
}
|
||||||
|
// Migration from v3 to v4: Add search history table
|
||||||
|
if (from < 4) {
|
||||||
|
await m.createTable(searchHistory);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -569,4 +585,51 @@ class AppDatabase extends _$AppDatabase {
|
|||||||
Future<void> clearHomeRowCache() async {
|
Future<void> clearHomeRowCache() async {
|
||||||
await delete(homeRowCache).go();
|
await delete(homeRowCache).go();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Search History Operations
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/// Save a search query to history (deduplicates and limits to 10)
|
||||||
|
Future<void> saveSearchQuery(String query) async {
|
||||||
|
final trimmedQuery = query.trim();
|
||||||
|
if (trimmedQuery.isEmpty) return;
|
||||||
|
|
||||||
|
await transaction(() async {
|
||||||
|
// Delete existing entry with same query (case-insensitive)
|
||||||
|
await (delete(searchHistory)
|
||||||
|
..where((s) => s.query.lower().equals(trimmedQuery.toLowerCase())))
|
||||||
|
.go();
|
||||||
|
|
||||||
|
// Insert the new search
|
||||||
|
await into(searchHistory).insert(SearchHistoryCompanion.insert(
|
||||||
|
query: trimmedQuery,
|
||||||
|
searchedAt: DateTime.now(),
|
||||||
|
));
|
||||||
|
|
||||||
|
// Keep only the 10 most recent searches
|
||||||
|
final allSearches = await (select(searchHistory)
|
||||||
|
..orderBy([(s) => OrderingTerm.desc(s.searchedAt)]))
|
||||||
|
.get();
|
||||||
|
|
||||||
|
if (allSearches.length > 10) {
|
||||||
|
final toDelete = allSearches.skip(10).map((s) => s.id).toList();
|
||||||
|
await (delete(searchHistory)..where((s) => s.id.isIn(toDelete))).go();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get recent search queries (up to 10, most recent first)
|
||||||
|
Future<List<String>> getRecentSearches() async {
|
||||||
|
final searches = await (select(searchHistory)
|
||||||
|
..orderBy([(s) => OrderingTerm.desc(s.searchedAt)])
|
||||||
|
..limit(10))
|
||||||
|
.get();
|
||||||
|
return searches.map((s) => s.query).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clear all search history
|
||||||
|
Future<void> clearSearchHistory() async {
|
||||||
|
await delete(searchHistory).go();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -279,6 +279,7 @@
|
|||||||
"playerStateUnavailable": "Nicht verfügbar",
|
"playerStateUnavailable": "Nicht verfügbar",
|
||||||
"playerStateOff": "Aus",
|
"playerStateOff": "Aus",
|
||||||
"playerStateIdle": "Inaktiv",
|
"playerStateIdle": "Inaktiv",
|
||||||
|
"playerStateExternalSource": "Externe Quelle",
|
||||||
"playerSelected": "Ausgewählt",
|
"playerSelected": "Ausgewählt",
|
||||||
"actionQueuedForSync": "Wird synchronisiert wenn online",
|
"actionQueuedForSync": "Wird synchronisiert wenn online",
|
||||||
"pendingOfflineActions": "{count} ausstehende Synchronisierung",
|
"pendingOfflineActions": "{count} ausstehende Synchronisierung",
|
||||||
|
|||||||
@@ -261,6 +261,26 @@
|
|||||||
"description": "Search hint text"
|
"description": "Search hint text"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"recentSearches": "Recent Searches",
|
||||||
|
"@recentSearches": {
|
||||||
|
"description": "Label for recent search history section"
|
||||||
|
},
|
||||||
|
|
||||||
|
"clearSearchHistory": "Clear Search History",
|
||||||
|
"@clearSearchHistory": {
|
||||||
|
"description": "Button to clear search history"
|
||||||
|
},
|
||||||
|
|
||||||
|
"searchHistoryCleared": "Search history cleared",
|
||||||
|
"@searchHistoryCleared": {
|
||||||
|
"description": "Confirmation message after clearing search history"
|
||||||
|
},
|
||||||
|
|
||||||
|
"libraryOnly": "Library only",
|
||||||
|
"@libraryOnly": {
|
||||||
|
"description": "Toggle to search only in library"
|
||||||
|
},
|
||||||
|
|
||||||
"retry": "Retry",
|
"retry": "Retry",
|
||||||
"@retry": {
|
"@retry": {
|
||||||
"description": "Retry button label"
|
"description": "Retry button label"
|
||||||
@@ -610,6 +630,11 @@
|
|||||||
"description": "Radio button label"
|
"description": "Radio button label"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"addedToQueue": "Added to queue",
|
||||||
|
"@addedToQueue": {
|
||||||
|
"description": "Confirmation when item added to queue"
|
||||||
|
},
|
||||||
|
|
||||||
"inLibrary": "In Library",
|
"inLibrary": "In Library",
|
||||||
"@inLibrary": {
|
"@inLibrary": {
|
||||||
"description": "In library section title"
|
"description": "In library section title"
|
||||||
@@ -1133,6 +1158,16 @@
|
|||||||
"description": "Singular form of audiobook"
|
"description": "Singular form of audiobook"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"albumSingular": "Album",
|
||||||
|
"@albumSingular": {
|
||||||
|
"description": "Singular form of album for search type indicator"
|
||||||
|
},
|
||||||
|
|
||||||
|
"trackSingular": "Track",
|
||||||
|
"@trackSingular": {
|
||||||
|
"description": "Singular form of track for search type indicator"
|
||||||
|
},
|
||||||
|
|
||||||
"trackCount": "{count} {count, plural, =1{track} other{tracks}}",
|
"trackCount": "{count} {count, plural, =1{track} other{tracks}}",
|
||||||
"@trackCount": {
|
"@trackCount": {
|
||||||
"description": "Track count with plural",
|
"description": "Track count with plural",
|
||||||
@@ -1193,6 +1228,11 @@
|
|||||||
"description": "Player state when idle"
|
"description": "Player state when idle"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
"playerStateExternalSource": "External Source",
|
||||||
|
"@playerStateExternalSource": {
|
||||||
|
"description": "Player state when playing from external source (optical, Spotify, etc.)"
|
||||||
|
},
|
||||||
|
|
||||||
"playerSelected": "Selected",
|
"playerSelected": "Selected",
|
||||||
"@playerSelected": {
|
"@playerSelected": {
|
||||||
"description": "Label for selected player"
|
"description": "Label for selected player"
|
||||||
|
|||||||
@@ -475,6 +475,7 @@
|
|||||||
"playerStateUnavailable": "No disponible",
|
"playerStateUnavailable": "No disponible",
|
||||||
"playerStateOff": "Apagado",
|
"playerStateOff": "Apagado",
|
||||||
"playerStateIdle": "Inactivo",
|
"playerStateIdle": "Inactivo",
|
||||||
|
"playerStateExternalSource": "Fuente Externa",
|
||||||
"playerSelected": "Seleccionado",
|
"playerSelected": "Seleccionado",
|
||||||
"actionQueuedForSync": "Se sincronizará cuando esté en línea",
|
"actionQueuedForSync": "Se sincronizará cuando esté en línea",
|
||||||
"pendingOfflineActions": "{count} sincronización pendiente",
|
"pendingOfflineActions": "{count} sincronización pendiente",
|
||||||
|
|||||||
+54
-5
@@ -348,7 +348,16 @@ class _SystemUIWrapperState extends State<SystemUIWrapper> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Startup widget that checks if user is logged in and auto-connects
|
/// Startup widget that checks if user is logged in and auto-connects.
|
||||||
|
///
|
||||||
|
/// CRITICAL: This widget is the single source of truth for the startup transition.
|
||||||
|
/// It loads settings FIRST (before connection), then waits for the appropriate
|
||||||
|
/// conditions before showing HomeScreen. This eliminates the race condition between
|
||||||
|
/// AppStartup and GlobalPlayerOverlay that caused the home screen flash.
|
||||||
|
///
|
||||||
|
/// For first-time users: Holds dark screen until connected + player selected,
|
||||||
|
/// so the welcome overlay can appear seamlessly.
|
||||||
|
/// For returning users: Transitions as soon as connection is established.
|
||||||
class AppStartup extends StatefulWidget {
|
class AppStartup extends StatefulWidget {
|
||||||
const AppStartup({super.key});
|
const AppStartup({super.key});
|
||||||
|
|
||||||
@@ -361,9 +370,32 @@ class _AppStartupState extends State<AppStartup> {
|
|||||||
String? _savedServerUrl;
|
String? _savedServerUrl;
|
||||||
bool _connectionAttempted = false;
|
bool _connectionAttempted = false;
|
||||||
|
|
||||||
|
// Welcome system state - loaded FIRST before connection check
|
||||||
|
bool _settingsLoaded = false;
|
||||||
|
bool _hasCompletedOnboarding = true; // Default to true (no welcome needed)
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_loadSettingsFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load settings BEFORE checking connection.
|
||||||
|
/// This ensures we know if this is a first-time user before transitioning.
|
||||||
|
Future<void> _loadSettingsFirst() async {
|
||||||
|
// Load onboarding state first - this is critical for determining
|
||||||
|
// when to transition to HomeScreen
|
||||||
|
_hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
setState(() {
|
||||||
|
_settingsLoaded = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
_logger.log('🚀 AppStartup: Settings loaded, hasCompletedOnboarding=$_hasCompletedOnboarding');
|
||||||
|
|
||||||
|
// Now check connection
|
||||||
_checkAndConnect();
|
_checkAndConnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -388,14 +420,30 @@ class _AppStartupState extends State<AppStartup> {
|
|||||||
// Just wait for it to complete or timeout
|
// Just wait for it to complete or timeout
|
||||||
_logger.log('🚀 AppStartup: Waiting for provider auto-connection to $serverUrl');
|
_logger.log('🚀 AppStartup: Waiting for provider auto-connection to $serverUrl');
|
||||||
|
|
||||||
|
// For first-time users, we need to wait for both connection AND player selection
|
||||||
|
// so the welcome overlay can appear immediately without home screen flash.
|
||||||
|
// For returning users, just wait for connection.
|
||||||
|
final needsWelcome = !_hasCompletedOnboarding;
|
||||||
|
|
||||||
// Give the provider time to connect (it restores credentials and connects in _initialize)
|
// Give the provider time to connect (it restores credentials and connects in _initialize)
|
||||||
// Check connection state periodically
|
// Check connection state periodically
|
||||||
for (var i = 0; i < 20; i++) {
|
for (var i = 0; i < 20; i++) {
|
||||||
await Future.delayed(const Duration(milliseconds: 250));
|
await Future.delayed(const Duration(milliseconds: 250));
|
||||||
if (provider.isConnected) {
|
|
||||||
_logger.log('🚀 AppStartup: Connection established');
|
if (needsWelcome) {
|
||||||
break;
|
// First-time user: wait for connection + player selection
|
||||||
|
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||||
|
_logger.log('🚀 AppStartup: First-time user ready (connected + player selected)');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Returning user: just wait for connection
|
||||||
|
if (provider.isConnected) {
|
||||||
|
_logger.log('🚀 AppStartup: Connection established');
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (provider.connectionState == MAConnectionState.error) {
|
if (provider.connectionState == MAConnectionState.error) {
|
||||||
_logger.log('🚀 AppStartup: Connection failed with error');
|
_logger.log('🚀 AppStartup: Connection failed with error');
|
||||||
break;
|
break;
|
||||||
@@ -422,7 +470,8 @@ class _AppStartupState extends State<AppStartup> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// Show loading while checking settings or connecting
|
// Show loading while checking settings or connecting
|
||||||
if (!_connectionAttempted || _isConnecting) {
|
// CRITICAL: Don't transition until settings are loaded - this prevents the race
|
||||||
|
if (!_settingsLoaded || !_connectionAttempted || _isConnecting) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
backgroundColor: const Color(0xFF1a1a1a),
|
backgroundColor: const Color(0xFF1a1a1a),
|
||||||
body: Center(
|
body: Center(
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ class Player {
|
|||||||
final double? elapsedTimeLastUpdated; // Unix timestamp when elapsed_time was last updated
|
final double? elapsedTimeLastUpdated; // Unix timestamp when elapsed_time was last updated
|
||||||
final List<String>? groupMembers; // List of player IDs in sync group (includes self)
|
final List<String>? groupMembers; // List of player IDs in sync group (includes self)
|
||||||
final String? syncedTo; // Player ID this player is synced to (null if leader or not synced)
|
final String? syncedTo; // Player ID this player is synced to (null if leader or not synced)
|
||||||
|
final String? activeSource; // The currently active source for this player
|
||||||
|
final bool isExternalSource; // True when an external source (optical, Spotify, etc.) is active
|
||||||
|
|
||||||
Player({
|
Player({
|
||||||
required this.playerId,
|
required this.playerId,
|
||||||
@@ -29,6 +31,8 @@ class Player {
|
|||||||
this.elapsedTimeLastUpdated,
|
this.elapsedTimeLastUpdated,
|
||||||
this.groupMembers,
|
this.groupMembers,
|
||||||
this.syncedTo,
|
this.syncedTo,
|
||||||
|
this.activeSource,
|
||||||
|
this.isExternalSource = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Create a copy of this Player with some fields replaced
|
/// Create a copy of this Player with some fields replaced
|
||||||
@@ -46,6 +50,8 @@ class Player {
|
|||||||
double? elapsedTimeLastUpdated,
|
double? elapsedTimeLastUpdated,
|
||||||
List<String>? groupMembers,
|
List<String>? groupMembers,
|
||||||
String? syncedTo,
|
String? syncedTo,
|
||||||
|
String? activeSource,
|
||||||
|
bool? isExternalSource,
|
||||||
}) {
|
}) {
|
||||||
return Player(
|
return Player(
|
||||||
playerId: playerId ?? this.playerId,
|
playerId: playerId ?? this.playerId,
|
||||||
@@ -61,6 +67,8 @@ class Player {
|
|||||||
elapsedTimeLastUpdated: elapsedTimeLastUpdated ?? this.elapsedTimeLastUpdated,
|
elapsedTimeLastUpdated: elapsedTimeLastUpdated ?? this.elapsedTimeLastUpdated,
|
||||||
groupMembers: groupMembers ?? this.groupMembers,
|
groupMembers: groupMembers ?? this.groupMembers,
|
||||||
syncedTo: syncedTo ?? this.syncedTo,
|
syncedTo: syncedTo ?? this.syncedTo,
|
||||||
|
activeSource: activeSource ?? this.activeSource,
|
||||||
|
isExternalSource: isExternalSource ?? this.isExternalSource,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +193,61 @@ class Player {
|
|||||||
// Parse synced_to - the player ID this player is synced to
|
// Parse synced_to - the player ID this player is synced to
|
||||||
final syncedTo = json['synced_to'] as String?;
|
final syncedTo = json['synced_to'] as String?;
|
||||||
|
|
||||||
|
// Parse active_source - the currently active source for this player
|
||||||
|
final activeSource = json['active_source'] as String?;
|
||||||
|
|
||||||
|
// Detect external source (optical, Spotify, AirPlay, etc.)
|
||||||
|
// Primary indicator: app_id - if not 'music_assistant', it's an external source
|
||||||
|
// Secondary indicators: URI patterns and media_type
|
||||||
|
bool isExternalSource = false;
|
||||||
|
|
||||||
|
// Check app_id first - this is the most reliable indicator for DLNA players
|
||||||
|
// When MA is playing: app_id = 'music_assistant'
|
||||||
|
// When external source: app_id = 'http', 'spotify', etc.
|
||||||
|
final appId = json['app_id'] as String?;
|
||||||
|
if (appId != null && appId.isNotEmpty && appId != 'music_assistant') {
|
||||||
|
// app_id is set but not 'music_assistant' - external source is active
|
||||||
|
isExternalSource = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also check current_media for additional external source indicators
|
||||||
|
if (!isExternalSource && json.containsKey('current_media')) {
|
||||||
|
final currentMedia = json['current_media'] as Map<String, dynamic>?;
|
||||||
|
if (currentMedia != null) {
|
||||||
|
final uri = currentMedia['uri'] as String?;
|
||||||
|
final mediaType = currentMedia['media_type'] as String?;
|
||||||
|
|
||||||
|
// External source indicators:
|
||||||
|
// 1. URI is a simple identifier like 'optical', 'line_in', 'bluetooth', 'hdmi'
|
||||||
|
// 2. URI starts with external protocols: 'spotify://', 'airplay://', etc.
|
||||||
|
// 3. Media type is 'unknown' (MA doesn't recognize the source)
|
||||||
|
if (uri != null) {
|
||||||
|
final uriLower = uri.toLowerCase();
|
||||||
|
// Simple external source identifiers (no :// or /)
|
||||||
|
final isSimpleExternalId = !uri.contains('://') && !uri.contains('/') &&
|
||||||
|
(uriLower == 'optical' || uriLower == 'line_in' || uriLower == 'bluetooth' ||
|
||||||
|
uriLower == 'hdmi' || uriLower == 'tv' || uriLower == 'aux' ||
|
||||||
|
uriLower == 'coaxial' || uriLower == 'toslink');
|
||||||
|
// External streaming protocols
|
||||||
|
final isExternalProtocol = uriLower.startsWith('spotify://') ||
|
||||||
|
uriLower.startsWith('airplay://') ||
|
||||||
|
uriLower.startsWith('cast://') ||
|
||||||
|
uriLower.startsWith('bluetooth://');
|
||||||
|
|
||||||
|
isExternalSource = isSimpleExternalId || isExternalProtocol;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also check media_type - 'unknown' often indicates external source
|
||||||
|
if (!isExternalSource && mediaType == 'unknown') {
|
||||||
|
// If media_type is unknown and URI doesn't look like MA content, it's external
|
||||||
|
final uri = currentMedia['uri'] as String?;
|
||||||
|
if (uri != null && !uri.startsWith('library://') && !uri.contains('://track/')) {
|
||||||
|
isExternalSource = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Player(
|
return Player(
|
||||||
playerId: json['player_id'] as String,
|
playerId: json['player_id'] as String,
|
||||||
name: json['name'] as String,
|
name: json['name'] as String,
|
||||||
@@ -199,6 +262,8 @@ class Player {
|
|||||||
elapsedTimeLastUpdated: elapsedTimeLastUpdated,
|
elapsedTimeLastUpdated: elapsedTimeLastUpdated,
|
||||||
groupMembers: groupMembers,
|
groupMembers: groupMembers,
|
||||||
syncedTo: syncedTo,
|
syncedTo: syncedTo,
|
||||||
|
activeSource: activeSource,
|
||||||
|
isExternalSource: isExternalSource,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,6 +282,8 @@ class Player {
|
|||||||
if (elapsedTimeLastUpdated != null) 'elapsed_time_last_updated': elapsedTimeLastUpdated,
|
if (elapsedTimeLastUpdated != null) 'elapsed_time_last_updated': elapsedTimeLastUpdated,
|
||||||
if (groupMembers != null) 'group_members': groupMembers,
|
if (groupMembers != null) 'group_members': groupMembers,
|
||||||
if (syncedTo != null) 'synced_to': syncedTo,
|
if (syncedTo != null) 'synced_to': syncedTo,
|
||||||
|
if (activeSource != null) 'active_source': activeSource,
|
||||||
|
'is_external_source': isExternalSource,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -597,7 +597,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
|
|
||||||
await _tryAdoptGhostPlayer();
|
await _tryAdoptGhostPlayer();
|
||||||
await _registerLocalPlayer();
|
await _registerLocalPlayer();
|
||||||
await _loadAndSelectPlayers();
|
await _loadAndSelectPlayers(coldStart: true);
|
||||||
|
|
||||||
loadLibrary();
|
loadLibrary();
|
||||||
|
|
||||||
@@ -785,6 +785,12 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
// This makes mini player and device button appear instantly on app resume
|
// This makes mini player and device button appear instantly on app resume
|
||||||
if (_availablePlayers.isEmpty && _cacheService.hasCachedPlayers) {
|
if (_availablePlayers.isEmpty && _cacheService.hasCachedPlayers) {
|
||||||
_availablePlayers = _cacheService.getCachedPlayers()!;
|
_availablePlayers = _cacheService.getCachedPlayers()!;
|
||||||
|
|
||||||
|
// Sort cached players immediately so list appears in correct order
|
||||||
|
final smartSort = await SettingsService.getSmartSortPlayers();
|
||||||
|
final builtinPlayerId = await SettingsService.getBuiltinPlayerId();
|
||||||
|
_sortPlayersSync(_availablePlayers, smartSort, builtinPlayerId);
|
||||||
|
|
||||||
_selectedPlayer = _cacheService.getCachedSelectedPlayer();
|
_selectedPlayer = _cacheService.getCachedSelectedPlayer();
|
||||||
// Also try to restore from settings if cache doesn't have selected player
|
// Also try to restore from settings if cache doesn't have selected player
|
||||||
if (_selectedPlayer == null && _availablePlayers.isNotEmpty) {
|
if (_selectedPlayer == null && _availablePlayers.isNotEmpty) {
|
||||||
@@ -801,7 +807,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
_selectedPlayer = _availablePlayers.first;
|
_selectedPlayer = _availablePlayers.first;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_logger.log('⚡ Loaded ${_availablePlayers.length} cached players instantly');
|
_logger.log('⚡ Loaded ${_availablePlayers.length} cached players instantly (sorted)');
|
||||||
notifyListeners(); // Update UI immediately with cached data
|
notifyListeners(); // Update UI immediately with cached data
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1590,6 +1596,37 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
|
|
||||||
if (currentMedia != null) {
|
if (currentMedia != null) {
|
||||||
final mediaType = currentMedia['media_type'] as String?;
|
final mediaType = currentMedia['media_type'] as String?;
|
||||||
|
final uri = currentMedia['uri'] as String?;
|
||||||
|
|
||||||
|
// Check for external source (optical, Spotify, etc.) - skip caching stale metadata
|
||||||
|
bool isExternalSource = false;
|
||||||
|
if (uri != null) {
|
||||||
|
final uriLower = uri.toLowerCase();
|
||||||
|
// Simple external source identifiers (no :// or /)
|
||||||
|
final isSimpleExternalId = !uri.contains('://') && !uri.contains('/') &&
|
||||||
|
(uriLower == 'optical' || uriLower == 'line_in' || uriLower == 'bluetooth' ||
|
||||||
|
uriLower == 'hdmi' || uriLower == 'tv' || uriLower == 'aux' ||
|
||||||
|
uriLower == 'coaxial' || uriLower == 'toslink');
|
||||||
|
// External streaming protocols
|
||||||
|
final isExternalProtocol = uriLower.startsWith('spotify://') ||
|
||||||
|
uriLower.startsWith('airplay://') ||
|
||||||
|
uriLower.startsWith('cast://') ||
|
||||||
|
uriLower.startsWith('bluetooth://');
|
||||||
|
isExternalSource = isSimpleExternalId || isExternalProtocol;
|
||||||
|
|
||||||
|
// Also treat unknown media type with non-MA URIs as external
|
||||||
|
if (!isExternalSource && mediaType == 'unknown' &&
|
||||||
|
!uri.startsWith('library://') && !uri.contains('://track/')) {
|
||||||
|
isExternalSource = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isExternalSource) {
|
||||||
|
_logger.log('📡 External source detected for $playerName (uri: $uri) - skipping metadata cache');
|
||||||
|
// Clear cached track for this player to avoid showing stale data
|
||||||
|
_cacheService.clearCachedTrackForPlayer(playerId);
|
||||||
|
return; // Skip further processing for external sources
|
||||||
|
}
|
||||||
|
|
||||||
// Clear audiobook context when switching to music (track) playback
|
// Clear audiobook context when switching to music (track) playback
|
||||||
if (mediaType == 'track' && _currentAudiobook != null) {
|
if (mediaType == 'track' && _currentAudiobook != null) {
|
||||||
@@ -2058,27 +2095,32 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
// SEARCH CACHING
|
// SEARCH CACHING
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
Future<Map<String, List<MediaItem>>> searchWithCache(String query, {bool forceRefresh = false}) async {
|
Future<Map<String, List<MediaItem>>> searchWithCache(String query, {bool forceRefresh = false, bool libraryOnly = false}) async {
|
||||||
final cacheKey = query.toLowerCase().trim();
|
final baseKey = query.toLowerCase().trim();
|
||||||
if (cacheKey.isEmpty) return {'artists': [], 'albums': [], 'tracks': []};
|
if (baseKey.isEmpty) return {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
|
|
||||||
|
// Include libraryOnly in cache key to separate results
|
||||||
|
final cacheKey = libraryOnly ? '$baseKey:library' : baseKey;
|
||||||
|
|
||||||
if (_cacheService.isSearchCacheValid(cacheKey, forceRefresh: forceRefresh)) {
|
if (_cacheService.isSearchCacheValid(cacheKey, forceRefresh: forceRefresh)) {
|
||||||
_logger.log('📦 Using cached search results for "$query"');
|
_logger.log('📦 Using cached search results for "$query" (libraryOnly: $libraryOnly)');
|
||||||
return _cacheService.getCachedSearchResults(cacheKey)!;
|
return _cacheService.getCachedSearchResults(cacheKey)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_api == null) {
|
if (_api == null) {
|
||||||
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': []};
|
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
_logger.log('🔄 Searching for "$query"...');
|
_logger.log('🔄 Searching for "$query" (libraryOnly: $libraryOnly)...');
|
||||||
final results = await _api!.search(query);
|
final results = await _api!.search(query, libraryOnly: libraryOnly);
|
||||||
|
|
||||||
final cachedResults = <String, List<MediaItem>>{
|
final cachedResults = <String, List<MediaItem>>{
|
||||||
'artists': results['artists'] ?? [],
|
'artists': results['artists'] ?? [],
|
||||||
'albums': results['albums'] ?? [],
|
'albums': results['albums'] ?? [],
|
||||||
'tracks': results['tracks'] ?? [],
|
'tracks': results['tracks'] ?? [],
|
||||||
|
'playlists': results['playlists'] ?? [],
|
||||||
|
'audiobooks': results['audiobooks'] ?? [],
|
||||||
};
|
};
|
||||||
|
|
||||||
_cacheService.setCachedSearchResults(cacheKey, cachedResults);
|
_cacheService.setCachedSearchResults(cacheKey, cachedResults);
|
||||||
@@ -2086,7 +2128,7 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
return cachedResults;
|
return cachedResults;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_logger.log('❌ Search failed: $e');
|
_logger.log('❌ Search failed: $e');
|
||||||
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': []};
|
return _cacheService.getCachedSearchResults(cacheKey) ?? {'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2121,7 +2163,38 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
return await SettingsService.getBuiltinPlayerId();
|
return await SettingsService.getBuiltinPlayerId();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadAndSelectPlayers({bool forceRefresh = false}) async {
|
/// Sort players list based on smart sort setting
|
||||||
|
/// Can be called synchronously with pre-fetched settings for cached players
|
||||||
|
void _sortPlayersSync(List<Player> players, bool smartSort, String? builtinPlayerId) {
|
||||||
|
if (smartSort) {
|
||||||
|
// Smart sort: local player first, then playing, then on, then off
|
||||||
|
players.sort((a, b) {
|
||||||
|
// Local player always first
|
||||||
|
final aIsLocal = builtinPlayerId != null && a.playerId == builtinPlayerId;
|
||||||
|
final bIsLocal = builtinPlayerId != null && b.playerId == builtinPlayerId;
|
||||||
|
if (aIsLocal && !bIsLocal) return -1;
|
||||||
|
if (bIsLocal && !aIsLocal) return 1;
|
||||||
|
|
||||||
|
// Then by status: playing > on > off
|
||||||
|
int statusPriority(Player p) {
|
||||||
|
if (p.state == 'playing') return 0;
|
||||||
|
if (p.powered && p.state != 'off') return 1;
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
final aPriority = statusPriority(a);
|
||||||
|
final bPriority = statusPriority(b);
|
||||||
|
if (aPriority != bPriority) return aPriority.compareTo(bPriority);
|
||||||
|
|
||||||
|
// Within same status, sort alphabetically
|
||||||
|
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Default alphabetical sort
|
||||||
|
players.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadAndSelectPlayers({bool forceRefresh = false, bool coldStart = false}) async {
|
||||||
try {
|
try {
|
||||||
if (!forceRefresh &&
|
if (!forceRefresh &&
|
||||||
_cacheService.isPlayersCacheValid() &&
|
_cacheService.isPlayersCacheValid() &&
|
||||||
@@ -2253,34 +2326,9 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
}).toList();
|
}).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort players - check if smart sort is enabled
|
// Sort players using helper method
|
||||||
final smartSort = await SettingsService.getSmartSortPlayers();
|
final smartSort = await SettingsService.getSmartSortPlayers();
|
||||||
if (smartSort) {
|
_sortPlayersSync(_availablePlayers, smartSort, builtinPlayerId);
|
||||||
// Smart sort: local player first, then playing, then on, then off
|
|
||||||
_availablePlayers.sort((a, b) {
|
|
||||||
// Local player always first
|
|
||||||
final aIsLocal = builtinPlayerId != null && a.playerId == builtinPlayerId;
|
|
||||||
final bIsLocal = builtinPlayerId != null && b.playerId == builtinPlayerId;
|
|
||||||
if (aIsLocal && !bIsLocal) return -1;
|
|
||||||
if (bIsLocal && !aIsLocal) return 1;
|
|
||||||
|
|
||||||
// Then by status: playing > on > off
|
|
||||||
int statusPriority(Player p) {
|
|
||||||
if (p.state == 'playing') return 0;
|
|
||||||
if (p.powered && p.state != 'off') return 1;
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
final aPriority = statusPriority(a);
|
|
||||||
final bPriority = statusPriority(b);
|
|
||||||
if (aPriority != bPriority) return aPriority.compareTo(bPriority);
|
|
||||||
|
|
||||||
// Within same status, sort alphabetically
|
|
||||||
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Default alphabetical sort
|
|
||||||
_availablePlayers.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache players for instant display on app resume
|
// Cache players for instant display on app resume
|
||||||
_cacheService.setCachedPlayers(_availablePlayers);
|
_cacheService.setCachedPlayers(_availablePlayers);
|
||||||
@@ -2310,7 +2358,8 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
|
|
||||||
// Keep currently selected player if still available (and not overridden by prefer local)
|
// Keep currently selected player if still available (and not overridden by prefer local)
|
||||||
// But allow switching to a playing player when preferLocalPlayer is OFF
|
// But allow switching to a playing player when preferLocalPlayer is OFF
|
||||||
if (playerToSelect == null && _selectedPlayer != null) {
|
// On coldStart, skip this block and apply full priority logic (playing > local > last selected)
|
||||||
|
if (playerToSelect == null && _selectedPlayer != null && !coldStart) {
|
||||||
final stillAvailable = _availablePlayers.any(
|
final stillAvailable = _availablePlayers.any(
|
||||||
(p) => p.playerId == _selectedPlayer!.playerId && p.available,
|
(p) => p.playerId == _selectedPlayer!.playerId && p.available,
|
||||||
);
|
);
|
||||||
@@ -2341,6 +2390,10 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (coldStart) {
|
||||||
|
_logger.log('🚀 Cold start: applying full priority logic (playing > local > last selected)');
|
||||||
|
}
|
||||||
|
|
||||||
if (playerToSelect == null) {
|
if (playerToSelect == null) {
|
||||||
// Smart auto-selection priority:
|
// Smart auto-selection priority:
|
||||||
// If "Prefer Local Player" is OFF: Single playing player -> Local player -> Last selected -> First available
|
// If "Prefer Local Player" is OFF: Single playing player -> Local player -> Last selected -> First available
|
||||||
@@ -2362,7 +2415,19 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
(p) => p.playerId == builtinPlayerId && p.available,
|
(p) => p.playerId == builtinPlayerId && p.available,
|
||||||
);
|
);
|
||||||
_logger.log('📱 Auto-selected local player: ${playerToSelect?.name}');
|
_logger.log('📱 Auto-selected local player: ${playerToSelect?.name}');
|
||||||
} catch (e) {}
|
} catch (e) {
|
||||||
|
// Local player not found or not available - check why
|
||||||
|
final localPlayer = _availablePlayers
|
||||||
|
.where((p) => p.playerId == builtinPlayerId)
|
||||||
|
.toList();
|
||||||
|
if (localPlayer.isEmpty) {
|
||||||
|
_logger.log('⚠️ Priority 2 skipped: local player ($builtinPlayerId) not in available players list');
|
||||||
|
} else {
|
||||||
|
_logger.log('⚠️ Priority 2 skipped: local player found but available=${localPlayer.first.available}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (playerToSelect == null && builtinPlayerId == null) {
|
||||||
|
_logger.log('⚠️ Priority 2 skipped: builtinPlayerId is null');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3367,6 +3432,18 @@ class MusicAssistantProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> addTrackToQueue(String playerId, Track track) async {
|
||||||
|
try {
|
||||||
|
await _api?.addTrackToQueue(playerId, track);
|
||||||
|
} catch (e) {
|
||||||
|
final errorInfo = ErrorHandler.handleError(e, context: 'Add to queue');
|
||||||
|
_error = errorInfo.userMessage;
|
||||||
|
ErrorHandler.logError('Add to queue', e);
|
||||||
|
notifyListeners();
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> playTracks(String playerId, List<Track> tracks, {int? startIndex, bool clearQueue = true}) async {
|
Future<void> playTracks(String playerId, List<Track> tracks, {int? startIndex, bool clearQueue = true}) async {
|
||||||
try {
|
try {
|
||||||
await _api?.playTracks(playerId, tracks, startIndex: startIndex, clearQueue: clearQueue);
|
await _api?.playTracks(playerId, tracks, startIndex: startIndex, clearQueue: clearQueue);
|
||||||
|
|||||||
@@ -558,7 +558,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1132,7 +1132,7 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared "Play on..." bottom sheet with fixed height and scrollable list
|
/// Shared "Play on..." bottom sheet that sizes to content
|
||||||
void _showPlayOnSheet(
|
void _showPlayOnSheet(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
List players, {
|
List players, {
|
||||||
@@ -1141,21 +1141,16 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
|||||||
// Slide mini player down out of the way
|
// Slide mini player down out of the way
|
||||||
GlobalPlayerOverlay.hidePlayer();
|
GlobalPlayerOverlay.hidePlayer();
|
||||||
|
|
||||||
final screenHeight = MediaQuery.of(context).size.height;
|
|
||||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
|
||||||
final sheetHeight = (screenHeight * 0.45) + bottomPadding; // Fixed 45% + safe area
|
|
||||||
|
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
backgroundColor: Colors.transparent,
|
backgroundColor: Colors.transparent,
|
||||||
isScrollControlled: true,
|
|
||||||
builder: (context) => Container(
|
builder: (context) => Container(
|
||||||
height: sheetHeight,
|
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surface,
|
color: Theme.of(context).colorScheme.surface,
|
||||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||||
),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
@@ -1163,30 +1158,33 @@ class _AlbumDetailsScreenState extends State<AlbumDetailsScreen> with SingleTick
|
|||||||
style: Theme.of(context).textTheme.titleLarge,
|
style: Theme.of(context).textTheme.titleLarge,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Expanded(
|
if (players.isEmpty)
|
||||||
child: players.isEmpty
|
Padding(
|
||||||
? Center(
|
padding: const EdgeInsets.all(32.0),
|
||||||
child: Text(S.of(context)!.noPlayersAvailable),
|
child: Text(S.of(context)!.noPlayersAvailable),
|
||||||
)
|
)
|
||||||
: ListView.builder(
|
else
|
||||||
padding: EdgeInsets.only(bottom: bottomPadding + 16),
|
Flexible(
|
||||||
itemCount: players.length,
|
child: ListView.builder(
|
||||||
itemBuilder: (context, index) {
|
shrinkWrap: true,
|
||||||
final player = players[index];
|
itemCount: players.length,
|
||||||
return ListTile(
|
itemBuilder: (context, index) {
|
||||||
leading: Icon(
|
final player = players[index];
|
||||||
Icons.speaker,
|
return ListTile(
|
||||||
color: Theme.of(context).colorScheme.onSurface,
|
leading: Icon(
|
||||||
),
|
Icons.speaker,
|
||||||
title: Text(player.name),
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
onTap: () {
|
),
|
||||||
Navigator.pop(context);
|
title: Text(player.name),
|
||||||
onPlayerSelected(player);
|
onTap: () {
|
||||||
},
|
Navigator.pop(context);
|
||||||
);
|
onPlayerSelected(player);
|
||||||
},
|
},
|
||||||
),
|
);
|
||||||
),
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -243,57 +243,25 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _startArtistRadio() async {
|
void _showRadioMenu(BuildContext context) {
|
||||||
final maProvider = context.read<MusicAssistantProvider>();
|
|
||||||
final selectedPlayer = maProvider.selectedPlayer;
|
|
||||||
|
|
||||||
if (selectedPlayer == null) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(content: Text(S.of(context)!.noPlayerSelected)),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await maProvider.playArtistRadio(selectedPlayer.playerId, widget.artist);
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(S.of(context)!.startingRadio(widget.artist.name)),
|
|
||||||
duration: const Duration(seconds: 1),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
_logger.log('Error starting artist radio: $e');
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(S.of(context)!.failedToStartRadio(e.toString())),
|
|
||||||
backgroundColor: Colors.red,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _showPlayOnMenu(BuildContext context) {
|
|
||||||
final maProvider = context.read<MusicAssistantProvider>();
|
final maProvider = context.read<MusicAssistantProvider>();
|
||||||
final players = maProvider.availablePlayers;
|
final players = maProvider.availablePlayers;
|
||||||
final colorScheme = Theme.of(context).colorScheme;
|
|
||||||
|
// Slide mini player down out of the way
|
||||||
|
GlobalPlayerOverlay.hidePlayer();
|
||||||
|
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
backgroundColor: colorScheme.surface,
|
backgroundColor: Colors.transparent,
|
||||||
shape: const RoundedRectangleBorder(
|
builder: (context) => Container(
|
||||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
decoration: BoxDecoration(
|
||||||
),
|
color: Theme.of(context).colorScheme.surface,
|
||||||
builder: (context) => Padding(
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||||
padding: const EdgeInsets.all(16.0),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
children: [
|
||||||
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
S.of(context)!.startRadioOn(widget.artist.name),
|
S.of(context)!.startRadioOn(widget.artist.name),
|
||||||
style: Theme.of(context).textTheme.titleLarge,
|
style: Theme.of(context).textTheme.titleLarge,
|
||||||
@@ -314,7 +282,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
return ListTile(
|
return ListTile(
|
||||||
leading: Icon(
|
leading: Icon(
|
||||||
Icons.speaker,
|
Icons.speaker,
|
||||||
color: colorScheme.onSurface,
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
),
|
),
|
||||||
title: Text(player.name),
|
title: Text(player.name),
|
||||||
onTap: () async {
|
onTap: () async {
|
||||||
@@ -345,46 +313,103 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
).whenComplete(() {
|
||||||
|
// Slide mini player back up when sheet is dismissed
|
||||||
|
GlobalPlayerOverlay.showPlayer();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _addArtistRadioToQueue() async {
|
void _showAddToQueueMenu(BuildContext context) {
|
||||||
final maProvider = context.read<MusicAssistantProvider>();
|
final maProvider = context.read<MusicAssistantProvider>();
|
||||||
final selectedPlayer = maProvider.selectedPlayer;
|
final players = maProvider.availablePlayers;
|
||||||
|
|
||||||
if (selectedPlayer == null) {
|
// Slide mini player down out of the way
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
GlobalPlayerOverlay.hidePlayer();
|
||||||
SnackBar(content: Text(S.of(context)!.noPlayerSelected)),
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
showModalBottomSheet(
|
||||||
// For adding to queue with radio mode, we use radio_mode but with 'add' option
|
context: context,
|
||||||
await maProvider.api?.playArtistRadioToQueue(selectedPlayer.playerId, widget.artist);
|
backgroundColor: Colors.transparent,
|
||||||
if (mounted) {
|
builder: (context) => Container(
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
decoration: BoxDecoration(
|
||||||
SnackBar(
|
color: Theme.of(context).colorScheme.surface,
|
||||||
content: Text(S.of(context)!.addedRadioToQueue(widget.artist.name)),
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||||
duration: const Duration(seconds: 1),
|
),
|
||||||
),
|
child: Column(
|
||||||
);
|
mainAxisSize: MainAxisSize.min,
|
||||||
}
|
children: [
|
||||||
} catch (e) {
|
const SizedBox(height: 16),
|
||||||
_logger.log('Error adding artist radio to queue: $e');
|
Text(
|
||||||
if (mounted) {
|
S.of(context)!.addToQueueOn,
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
style: Theme.of(context).textTheme.titleLarge,
|
||||||
SnackBar(
|
),
|
||||||
content: Text(S.of(context)!.failedToAddToQueue(e.toString())),
|
const SizedBox(height: 16),
|
||||||
backgroundColor: Colors.red,
|
if (players.isEmpty)
|
||||||
),
|
Padding(
|
||||||
);
|
padding: const EdgeInsets.all(32.0),
|
||||||
}
|
child: Text(S.of(context)!.noPlayersAvailable),
|
||||||
}
|
)
|
||||||
|
else
|
||||||
|
Flexible(
|
||||||
|
child: ListView.builder(
|
||||||
|
shrinkWrap: true,
|
||||||
|
itemCount: players.length,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final player = players[index];
|
||||||
|
return ListTile(
|
||||||
|
leading: Icon(
|
||||||
|
Icons.speaker,
|
||||||
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
|
),
|
||||||
|
title: Text(player.name),
|
||||||
|
onTap: () async {
|
||||||
|
Navigator.pop(context);
|
||||||
|
final api = maProvider.api;
|
||||||
|
if (api == null) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text(S.of(context)!.notConnected)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await api.playArtistRadioToQueue(player.playerId, widget.artist);
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(S.of(context)!.addedRadioToQueue(widget.artist.name)),
|
||||||
|
duration: const Duration(seconds: 1),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
_logger.log('Error adding artist radio to queue: $e');
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(S.of(context)!.failedToAddToQueue(e.toString())),
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
).whenComplete(() {
|
||||||
|
// Slide mini player back up when sheet is dismissed
|
||||||
|
GlobalPlayerOverlay.showPlayer();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadArtistImage() async {
|
Future<void> _loadArtistImage() async {
|
||||||
@@ -627,7 +652,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
height: 50,
|
height: 50,
|
||||||
child: ElevatedButton.icon(
|
child: ElevatedButton.icon(
|
||||||
onPressed: _startArtistRadio,
|
onPressed: () => _showRadioMenu(context),
|
||||||
icon: const Icon(Icons.radio),
|
icon: const Icon(Icons.radio),
|
||||||
label: Text(S.of(context)!.radio),
|
label: Text(S.of(context)!.radio),
|
||||||
style: ElevatedButton.styleFrom(
|
style: ElevatedButton.styleFrom(
|
||||||
@@ -640,23 +665,6 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 12),
|
|
||||||
|
|
||||||
// "Play on..." Button (Square)
|
|
||||||
SizedBox(
|
|
||||||
height: 50,
|
|
||||||
width: 50,
|
|
||||||
child: FilledButton.tonal(
|
|
||||||
onPressed: () => _showPlayOnMenu(context),
|
|
||||||
style: FilledButton.styleFrom(
|
|
||||||
padding: EdgeInsets.zero,
|
|
||||||
shape: RoundedRectangleBorder(
|
|
||||||
borderRadius: BorderRadius.circular(12),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
child: const Icon(Icons.speaker_group_outlined),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
|
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
|
|
||||||
@@ -665,7 +673,7 @@ class _ArtistDetailsScreenState extends State<ArtistDetailsScreen> {
|
|||||||
height: 50,
|
height: 50,
|
||||||
width: 50,
|
width: 50,
|
||||||
child: FilledButton.tonal(
|
child: FilledButton.tonal(
|
||||||
onPressed: _addArtistRadioToQueue,
|
onPressed: () => _showAddToQueueMenu(context),
|
||||||
style: FilledButton.styleFrom(
|
style: FilledButton.styleFrom(
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
shape: RoundedRectangleBorder(
|
shape: RoundedRectangleBorder(
|
||||||
|
|||||||
@@ -211,23 +211,19 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
|||||||
final maProvider = context.read<MusicAssistantProvider>();
|
final maProvider = context.read<MusicAssistantProvider>();
|
||||||
final players = maProvider.availablePlayers;
|
final players = maProvider.availablePlayers;
|
||||||
|
|
||||||
|
// Slide mini player down out of the way
|
||||||
GlobalPlayerOverlay.hidePlayer();
|
GlobalPlayerOverlay.hidePlayer();
|
||||||
|
|
||||||
final screenHeight = MediaQuery.of(context).size.height;
|
|
||||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
|
||||||
final sheetHeight = (screenHeight * 0.45) + bottomPadding;
|
|
||||||
|
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
backgroundColor: Colors.transparent,
|
backgroundColor: Colors.transparent,
|
||||||
isScrollControlled: true,
|
|
||||||
builder: (context) => Container(
|
builder: (context) => Container(
|
||||||
height: sheetHeight,
|
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: Theme.of(context).colorScheme.surface,
|
color: Theme.of(context).colorScheme.surface,
|
||||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||||
),
|
),
|
||||||
child: Column(
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
@@ -235,37 +231,43 @@ class _AudiobookDetailScreenState extends State<AudiobookDetailScreen> {
|
|||||||
style: Theme.of(context).textTheme.titleLarge,
|
style: Theme.of(context).textTheme.titleLarge,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Expanded(
|
if (players.isEmpty)
|
||||||
child: players.isEmpty
|
Padding(
|
||||||
? Center(child: Text(S.of(context)!.noPlayersAvailable))
|
padding: const EdgeInsets.all(32.0),
|
||||||
: ListView.builder(
|
child: Text(S.of(context)!.noPlayersAvailable),
|
||||||
padding: EdgeInsets.only(bottom: bottomPadding + 16),
|
)
|
||||||
itemCount: players.length,
|
else
|
||||||
itemBuilder: (context, index) {
|
Flexible(
|
||||||
final player = players[index];
|
child: ListView.builder(
|
||||||
return ListTile(
|
shrinkWrap: true,
|
||||||
leading: Icon(
|
itemCount: players.length,
|
||||||
Icons.speaker,
|
itemBuilder: (context, index) {
|
||||||
color: Theme.of(context).colorScheme.onSurface,
|
final player = players[index];
|
||||||
),
|
return ListTile(
|
||||||
title: Text(player.name),
|
leading: Icon(
|
||||||
onTap: () async {
|
Icons.speaker,
|
||||||
Navigator.pop(context);
|
color: Theme.of(context).colorScheme.onSurface,
|
||||||
maProvider.selectPlayer(player);
|
),
|
||||||
maProvider.setCurrentAudiobook(_audiobook);
|
title: Text(player.name),
|
||||||
await maProvider.api?.playAudiobook(
|
onTap: () async {
|
||||||
player.playerId,
|
Navigator.pop(context);
|
||||||
widget.audiobook,
|
maProvider.selectPlayer(player);
|
||||||
);
|
maProvider.setCurrentAudiobook(_audiobook);
|
||||||
},
|
await maProvider.api?.playAudiobook(
|
||||||
|
player.playerId,
|
||||||
|
widget.audiobook,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
);
|
||||||
),
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
).whenComplete(() {
|
).whenComplete(() {
|
||||||
|
// Slide mini player back up when sheet is dismissed
|
||||||
GlobalPlayerOverlay.showPlayer();
|
GlobalPlayerOverlay.showPlayer();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -443,6 +443,18 @@ class _LoginScreenState extends State<LoginScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (provider.isConnected) {
|
if (provider.isConnected) {
|
||||||
|
// For first-time users, wait for player selection so the welcome
|
||||||
|
// overlay can appear immediately without home screen flash.
|
||||||
|
// This matches the logic in AppStartup._checkAndConnect().
|
||||||
|
final hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||||
|
if (!hasCompletedOnboarding) {
|
||||||
|
// First-time user: wait for connection + player selection
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
await Future.delayed(const Duration(milliseconds: 250));
|
||||||
|
if (provider.selectedPlayer != null) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Navigate to home screen
|
// Navigate to home screen
|
||||||
if (mounted) {
|
if (mounted) {
|
||||||
// Ensure keyboard is closed before navigating
|
// Ensure keyboard is closed before navigating
|
||||||
|
|||||||
+1176
-217
File diff suppressed because it is too large
Load Diff
@@ -259,6 +259,11 @@ class CacheService {
|
|||||||
_playerTrackCache[playerId] = track;
|
_playerTrackCache[playerId] = track;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear cached track for a player (e.g., when external source is active)
|
||||||
|
void clearCachedTrackForPlayer(String playerId) {
|
||||||
|
_playerTrackCache.remove(playerId);
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// CLEAR ALL
|
// CLEAR ALL
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|||||||
@@ -239,4 +239,17 @@ class DatabaseService {
|
|||||||
|
|
||||||
/// Clear all home row cache
|
/// Clear all home row cache
|
||||||
Future<void> clearHomeRowCache() => db.clearHomeRowCache();
|
Future<void> clearHomeRowCache() => db.clearHomeRowCache();
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Search History Convenience Methods
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/// Save a search query to history
|
||||||
|
Future<void> saveSearchQuery(String query) => db.saveSearchQuery(query);
|
||||||
|
|
||||||
|
/// Get recent search queries (up to 10)
|
||||||
|
Future<List<String>> getRecentSearches() => db.getRecentSearches();
|
||||||
|
|
||||||
|
/// Clear all search history
|
||||||
|
Future<void> clearSearchHistory() => db.clearSearchHistory();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1399,7 +1399,7 @@ class MusicAssistantAPI {
|
|||||||
|
|
||||||
final result = searchResponse['result'] as Map<String, dynamic>?;
|
final result = searchResponse['result'] as Map<String, dynamic>?;
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse results from the search response
|
// Parse results from the search response
|
||||||
@@ -1418,6 +1418,16 @@ class MusicAssistantAPI {
|
|||||||
.toList() ??
|
.toList() ??
|
||||||
[];
|
[];
|
||||||
|
|
||||||
|
final playlists = (result['playlists'] as List<dynamic>?)
|
||||||
|
?.map((item) => Playlist.fromJson(item as Map<String, dynamic>))
|
||||||
|
.toList() ??
|
||||||
|
[];
|
||||||
|
|
||||||
|
final audiobooks = (result['audiobooks'] as List<dynamic>?)
|
||||||
|
?.map((item) => Audiobook.fromJson(item as Map<String, dynamic>))
|
||||||
|
.toList() ??
|
||||||
|
[];
|
||||||
|
|
||||||
// Deduplicate results by name
|
// Deduplicate results by name
|
||||||
// MA returns both library items and provider items for the same content
|
// MA returns both library items and provider items for the same content
|
||||||
// Prefer library items (provider='library') as they have all provider mappings
|
// Prefer library items (provider='library') as they have all provider mappings
|
||||||
@@ -1425,15 +1435,17 @@ class MusicAssistantAPI {
|
|||||||
'artists': _deduplicateResults(artists),
|
'artists': _deduplicateResults(artists),
|
||||||
'albums': _deduplicateResults(albums),
|
'albums': _deduplicateResults(albums),
|
||||||
'tracks': _deduplicateResults(tracks),
|
'tracks': _deduplicateResults(tracks),
|
||||||
|
'playlists': _deduplicateResults(playlists),
|
||||||
|
'audiobooks': _deduplicateResults(audiobooks),
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
_logger.log('Error searching: $e');
|
_logger.log('Error searching: $e');
|
||||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
).catchError((e) {
|
).catchError((e) {
|
||||||
_logger.log('Error searching after retries: $e');
|
_logger.log('Error searching after retries: $e');
|
||||||
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': []};
|
return <String, List<MediaItem>>{'artists': [], 'albums': [], 'tracks': [], 'playlists': [], 'audiobooks': []};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1602,6 +1614,25 @@ class MusicAssistantAPI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Add a single track to the queue without starting playback
|
||||||
|
Future<void> addTrackToQueue(String playerId, Track track) async {
|
||||||
|
try {
|
||||||
|
final uri = _buildTrackUri(track);
|
||||||
|
|
||||||
|
await _sendCommand(
|
||||||
|
'player_queues/play_media',
|
||||||
|
args: {
|
||||||
|
'queue_id': playerId,
|
||||||
|
'media': [uri],
|
||||||
|
'option': 'add', // Add to queue without starting
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
_logger.log('Error adding track to queue: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Play multiple tracks via queue
|
/// Play multiple tracks via queue
|
||||||
/// If clearQueue is true, replaces the queue (default behavior)
|
/// If clearQueue is true, replaces the queue (default behavior)
|
||||||
/// If startIndex is provided, only tracks from that index onwards will be queued
|
/// If startIndex is provided, only tracks from that index onwards will be queued
|
||||||
|
|||||||
@@ -167,9 +167,15 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
final _bounceOffsetNotifier = ValueNotifier<double>(0.0);
|
final _bounceOffsetNotifier = ValueNotifier<double>(0.0);
|
||||||
|
|
||||||
// Hint system state
|
// Hint system state
|
||||||
|
// NOTE: AppStartup now handles the settings loading gate. It waits for:
|
||||||
|
// - First-time users: connected + player selected before showing HomeScreen
|
||||||
|
// - Returning users: connected before showing HomeScreen
|
||||||
|
// This eliminates the race condition that caused home screen flash.
|
||||||
bool _showHints = true;
|
bool _showHints = true;
|
||||||
bool _hasCompletedOnboarding = false; // First-use welcome screen
|
bool _hasCompletedOnboarding = false; // First-use welcome screen
|
||||||
bool _hintTriggered = false; // Prevent multiple triggers per session
|
bool _hintTriggered = false; // Prevent multiple triggers per session
|
||||||
|
bool _settingsLoaded = false; // True once settings have been loaded from storage
|
||||||
|
bool _miniPlayerHintsReady = false; // True once connected with player (can show hints)
|
||||||
final _hintOpacityNotifier = ValueNotifier<double>(0.0);
|
final _hintOpacityNotifier = ValueNotifier<double>(0.0);
|
||||||
|
|
||||||
// Welcome content fade-in animation
|
// Welcome content fade-in animation
|
||||||
@@ -234,12 +240,66 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
Future<void> _loadHintSettings() async {
|
Future<void> _loadHintSettings() async {
|
||||||
_showHints = await SettingsService.getShowHints();
|
_showHints = await SettingsService.getShowHints();
|
||||||
_hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
_hasCompletedOnboarding = await SettingsService.getHasCompletedOnboarding();
|
||||||
// Show welcome screen only on first use (not completed onboarding yet)
|
if (!mounted) return;
|
||||||
if (!_hasCompletedOnboarding && mounted && !_hintTriggered) {
|
|
||||||
_startWelcomeScreen();
|
setState(() {
|
||||||
|
_settingsLoaded = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// If first-time user and already connected (AppStartup waited for us),
|
||||||
|
// start welcome screen immediately - no race condition possible
|
||||||
|
if (!_hasCompletedOnboarding && !_hintTriggered) {
|
||||||
|
final provider = context.read<MusicAssistantProvider>();
|
||||||
|
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||||
|
_miniPlayerHintsReady = true;
|
||||||
|
_startWelcomeScreen();
|
||||||
|
_startMiniPlayerBounce();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeDependencies() {
|
||||||
|
super.didChangeDependencies();
|
||||||
|
// Check if we should enable mini player hints now that we have connection
|
||||||
|
_checkConnectionForMiniPlayerHints();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check connection state and start welcome screen if appropriate.
|
||||||
|
/// This is called from multiple places:
|
||||||
|
/// 1. didChangeDependencies() - when widget first builds
|
||||||
|
/// 2. _loadHintSettings() - when settings finish loading
|
||||||
|
/// 3. build() - when provider state changes (via post-frame callback)
|
||||||
|
void _checkConnectionForMiniPlayerHints() {
|
||||||
|
if (_hintTriggered || !mounted || !_settingsLoaded) return;
|
||||||
|
if (_hasCompletedOnboarding) return; // Not first-time user
|
||||||
|
|
||||||
|
final provider = context.read<MusicAssistantProvider>();
|
||||||
|
if (provider.isConnected && provider.selectedPlayer != null) {
|
||||||
|
// Connected with a player - start welcome screen now
|
||||||
|
_miniPlayerHintsReady = true;
|
||||||
|
_startWelcomeScreen();
|
||||||
|
// Start the bounce animation now that mini player is visible
|
||||||
|
_startMiniPlayerBounce();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the bounce animation for mini player hints
|
||||||
|
void _startMiniPlayerBounce() {
|
||||||
|
if (!_isHintModeActive || !mounted) return;
|
||||||
|
_doubleBounceController.reset();
|
||||||
|
_doubleBounceController.forward();
|
||||||
|
|
||||||
|
// Repeat bounce every 2 seconds
|
||||||
|
_hintBounceTimer?.cancel();
|
||||||
|
_hintBounceTimer = Timer.periodic(const Duration(seconds: 2), (_) {
|
||||||
|
if (_isHintModeActive && mounted) {
|
||||||
|
_doubleBounceController.reset();
|
||||||
|
_doubleBounceController.forward();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// Start the welcome screen with fade-in animation
|
/// Start the welcome screen with fade-in animation
|
||||||
void _startWelcomeScreen() {
|
void _startWelcomeScreen() {
|
||||||
if (_hintTriggered) return;
|
if (_hintTriggered) return;
|
||||||
@@ -250,24 +310,10 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
_isHintModeActive = true;
|
_isHintModeActive = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fade in welcome content
|
// Fade in welcome content (logo + title)
|
||||||
_welcomeFadeController.forward();
|
_welcomeFadeController.forward();
|
||||||
|
|
||||||
// Start bounce animation after fade completes
|
// Mini player bounce is started separately once connected via _startMiniPlayerBounce()
|
||||||
_welcomeFadeController.addStatusListener((status) {
|
|
||||||
if (status == AnimationStatus.completed && mounted) {
|
|
||||||
_doubleBounceController.reset();
|
|
||||||
_doubleBounceController.forward();
|
|
||||||
|
|
||||||
// Repeat bounce every 2 seconds
|
|
||||||
_hintBounceTimer = Timer.periodic(const Duration(seconds: 2), (_) {
|
|
||||||
if (_isHintModeActive && mounted) {
|
|
||||||
_doubleBounceController.reset();
|
|
||||||
_doubleBounceController.forward();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -362,6 +408,36 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final colorScheme = theme.colorScheme;
|
final colorScheme = theme.colorScheme;
|
||||||
|
|
||||||
|
// Watch provider to trigger rebuilds when connection state changes
|
||||||
|
final provider = context.watch<MusicAssistantProvider>();
|
||||||
|
|
||||||
|
// Compute whether this is a first-time user ready for welcome screen.
|
||||||
|
// This is SYNCHRONOUS - no setState needed - so it works in the same frame.
|
||||||
|
final isFirstTimeUserReady = _settingsLoaded &&
|
||||||
|
!_hasCompletedOnboarding &&
|
||||||
|
provider.isConnected &&
|
||||||
|
provider.selectedPlayer != null;
|
||||||
|
|
||||||
|
// Show welcome backdrop if:
|
||||||
|
// 1. Already in hint mode (_isHintModeActive), OR
|
||||||
|
// 2. First-time user ready but hint mode not started yet (!_hintTriggered)
|
||||||
|
// This ensures backdrop appears IMMEDIATELY when HomeScreen renders,
|
||||||
|
// preventing the flash. Welcome content fades in after via animation.
|
||||||
|
final shouldShowWelcomeBackdrop = _isHintModeActive ||
|
||||||
|
(isFirstTimeUserReady && !_hintTriggered);
|
||||||
|
|
||||||
|
// Trigger hint mode if conditions are met (for animations, bounce, etc)
|
||||||
|
if (isFirstTimeUserReady && !_hintTriggered) {
|
||||||
|
// Schedule for post-frame to avoid setState during build
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (mounted && !_hintTriggered) {
|
||||||
|
_miniPlayerHintsReady = true;
|
||||||
|
_startWelcomeScreen();
|
||||||
|
_startMiniPlayerBounce();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Handle back gesture at top level - dismiss hint mode or device list if visible
|
// Handle back gesture at top level - dismiss hint mode or device list if visible
|
||||||
return PopScope(
|
return PopScope(
|
||||||
canPop: !_isRevealVisible && !_isHintModeActive,
|
canPop: !_isRevealVisible && !_isHintModeActive,
|
||||||
@@ -383,14 +459,18 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
child: widget.child,
|
child: widget.child,
|
||||||
),
|
),
|
||||||
// Global persistent bottom navigation bar - positioned at bottom
|
// Global persistent bottom navigation bar - positioned at bottom
|
||||||
Positioned(
|
// Hide when: not connected, no player selected, OR showing welcome screen
|
||||||
left: 0,
|
// For first-time users, selectedPlayer becomes non-null at the same time
|
||||||
right: 0,
|
// as shouldShowWelcomeBackdrop becomes true, preventing any gap.
|
||||||
bottom: 0,
|
if (provider.isConnected && provider.selectedPlayer != null && !shouldShowWelcomeBackdrop)
|
||||||
child: ListenableBuilder(
|
Positioned(
|
||||||
listenable: navigationProvider,
|
left: 0,
|
||||||
builder: (context, _) {
|
right: 0,
|
||||||
return Consumer<ThemeProvider>(
|
bottom: 0,
|
||||||
|
child: ListenableBuilder(
|
||||||
|
listenable: navigationProvider,
|
||||||
|
builder: (context, _) {
|
||||||
|
return Consumer<ThemeProvider>(
|
||||||
builder: (context, themeProvider, _) {
|
builder: (context, themeProvider, _) {
|
||||||
// Use adaptive primary color for bottom nav when adaptive theme is enabled
|
// Use adaptive primary color for bottom nav when adaptive theme is enabled
|
||||||
final sourceColor = themeProvider.adaptiveTheme
|
final sourceColor = themeProvider.adaptiveTheme
|
||||||
@@ -479,9 +559,9 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
|
||||||
// Blur backdrop for device selector (reveal mode) - static, no animation
|
// Blur backdrop for device selector (reveal mode) - static, no animation
|
||||||
if (_isRevealVisible && !_isHintModeActive)
|
if (_isRevealVisible && !_isHintModeActive)
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
@@ -497,8 +577,10 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Blur backdrop for hint/welcome mode - animated fade from solid to semi-transparent
|
// Welcome/hint backdrop - shows IMMEDIATELY when first-time user is ready.
|
||||||
if (_isHintModeActive)
|
// Uses computed `shouldShowWelcomeBackdrop` which is true BEFORE _isHintModeActive,
|
||||||
|
// preventing the 1-frame gap where home screen would be visible.
|
||||||
|
if (shouldShowWelcomeBackdrop)
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: TweenAnimationBuilder<double>(
|
child: TweenAnimationBuilder<double>(
|
||||||
// Hold solid for 2s, then fade to 0.5 over 1s
|
// Hold solid for 2s, then fade to 0.5 over 1s
|
||||||
@@ -509,7 +591,8 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
return BackdropFilter(
|
return BackdropFilter(
|
||||||
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
|
filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
|
||||||
child: Container(
|
child: Container(
|
||||||
color: colorScheme.surface.withOpacity(opacity),
|
// Use same dark color as connection screen for seamless transition
|
||||||
|
color: const Color(0xFF1a1a1a).withOpacity(opacity),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
@@ -553,8 +636,8 @@ class _GlobalPlayerOverlayState extends State<GlobalPlayerOverlay>
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
// Bottom section: Hint text and Skip button (positioned relative to mini player)
|
// Bottom section: Hint text and Skip button (only show once mini player is visible)
|
||||||
if (_isHintModeActive)
|
if (_isHintModeActive && _miniPlayerHintsReady)
|
||||||
Positioned(
|
Positioned(
|
||||||
left: 24,
|
left: 24,
|
||||||
right: 24,
|
right: 24,
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
|||||||
double _dragOffset = 0;
|
double _dragOffset = 0;
|
||||||
bool _isDragging = false;
|
bool _isDragging = false;
|
||||||
|
|
||||||
|
// Scroll controller for when player list overflows
|
||||||
|
final ScrollController _scrollController = ScrollController();
|
||||||
|
bool _isScrollable = false;
|
||||||
|
|
||||||
// Cache extracted colors per player for per-device accent colors
|
// Cache extracted colors per player for per-device accent colors
|
||||||
final Map<String, ColorScheme?> _playerColors = {};
|
final Map<String, ColorScheme?> _playerColors = {};
|
||||||
|
|
||||||
@@ -128,6 +132,7 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
|||||||
void dispose() {
|
void dispose() {
|
||||||
_revealController.dispose();
|
_revealController.dispose();
|
||||||
_refreshTimer?.cancel();
|
_refreshTimer?.cancel();
|
||||||
|
_scrollController.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,19 +162,51 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if scroll is at top (or not scrollable)
|
||||||
|
bool get _isAtTop {
|
||||||
|
if (!_isScrollable) return true;
|
||||||
|
if (!_scrollController.hasClients) return true;
|
||||||
|
return _scrollController.offset <= 0;
|
||||||
|
}
|
||||||
|
|
||||||
void _handleVerticalDragUpdate(DragUpdateDetails details) {
|
void _handleVerticalDragUpdate(DragUpdateDetails details) {
|
||||||
|
final delta = details.primaryDelta ?? 0;
|
||||||
|
|
||||||
|
// If scrollable and not at top, let scroll handle it
|
||||||
|
if (_isScrollable && !_isAtTop) {
|
||||||
|
// Scroll the list
|
||||||
|
if (_scrollController.hasClients) {
|
||||||
|
final newOffset = _scrollController.offset - delta;
|
||||||
|
_scrollController.jumpTo(newOffset.clamp(0.0, _scrollController.position.maxScrollExtent));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// At top: check if trying to scroll down (view more) or dismiss
|
||||||
|
if (_isScrollable && delta < 0 && _scrollController.hasClients) {
|
||||||
|
// Swiping up (delta negative) = scroll down to see more players
|
||||||
|
final newOffset = _scrollController.offset - delta;
|
||||||
|
_scrollController.jumpTo(newOffset.clamp(0.0, _scrollController.position.maxScrollExtent));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only process dismiss gesture when swiping DOWN (positive delta = finger moving down)
|
||||||
|
// Ignore swipe up when not scrollable - cards should stay fixed
|
||||||
|
if (delta <= 0) return;
|
||||||
|
|
||||||
|
// Swiping down = dismiss gesture
|
||||||
setState(() {
|
setState(() {
|
||||||
_isDragging = true;
|
_isDragging = true;
|
||||||
// Negate delta so swipe down = cards move down (toward dismissal)
|
_dragOffset += delta;
|
||||||
_dragOffset -= details.primaryDelta ?? 0;
|
|
||||||
// Clamp: allow moving down (positive) freely, limit moving up to 20px
|
|
||||||
_dragOffset = _dragOffset.clamp(-20.0, double.infinity);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _handleVerticalDragEnd(DragEndDetails details) {
|
void _handleVerticalDragEnd(DragEndDetails details) {
|
||||||
final velocity = details.primaryVelocity ?? 0;
|
final velocity = details.primaryVelocity ?? 0;
|
||||||
|
|
||||||
|
// If not dragging (was scrolling), don't dismiss
|
||||||
|
if (!_isDragging) return;
|
||||||
|
|
||||||
// Dismiss if dragged down enough or with enough velocity
|
// Dismiss if dragged down enough or with enough velocity
|
||||||
if (_dragOffset > 100 || velocity > 500) {
|
if (_dragOffset > 100 || velocity > 500) {
|
||||||
HapticFeedback.lightImpact();
|
HapticFeedback.lightImpact();
|
||||||
@@ -215,6 +252,21 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
|||||||
const cardSpacing = 12.0;
|
const cardSpacing = 12.0;
|
||||||
final totalStackHeight = players.length * cardHeight + (players.length - 1) * cardSpacing;
|
final totalStackHeight = players.length * cardHeight + (players.length - 1) * cardSpacing;
|
||||||
|
|
||||||
|
// Calculate max available height (80% of screen minus mini player area)
|
||||||
|
final screenHeight = MediaQuery.of(context).size.height;
|
||||||
|
final statusBarHeight = MediaQuery.of(context).padding.top;
|
||||||
|
final bottomPadding = widget.miniPlayerBottom + widget.miniPlayerHeight + 20;
|
||||||
|
final maxListHeight = (screenHeight - statusBarHeight - bottomPadding) * 0.8;
|
||||||
|
|
||||||
|
// Determine if scrolling is needed
|
||||||
|
final needsScroll = totalStackHeight > maxListHeight;
|
||||||
|
// Update scrollable state (used by gesture handlers)
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
if (_isScrollable != needsScroll) {
|
||||||
|
_isScrollable = needsScroll;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
return AnimatedBuilder(
|
return AnimatedBuilder(
|
||||||
animation: _revealAnimation,
|
animation: _revealAnimation,
|
||||||
builder: (context, child) {
|
builder: (context, child) {
|
||||||
@@ -289,7 +341,76 @@ class PlayerRevealOverlayState extends State<PlayerRevealOverlay>
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
// Build player cards - all slide from behind mini player
|
// Build player cards - scrollable when overflow, otherwise static
|
||||||
|
// Using ListView.builder for many players: only builds visible items
|
||||||
|
// This significantly improves animation performance with 10+ players
|
||||||
|
if (needsScroll)
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: BoxConstraints(maxHeight: maxListHeight),
|
||||||
|
child: ListView.builder(
|
||||||
|
controller: _scrollController,
|
||||||
|
physics: const ClampingScrollPhysics(),
|
||||||
|
itemCount: players.length,
|
||||||
|
// Fixed height per item for optimal scroll performance
|
||||||
|
itemExtent: cardHeight + cardSpacing,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final player = players[index];
|
||||||
|
final isPlaying = player.state == 'playing';
|
||||||
|
final playerTrack = maProvider.getCachedTrackForPlayer(player.playerId);
|
||||||
|
String? albumArtUrl;
|
||||||
|
if (playerTrack != null && player.available && player.powered) {
|
||||||
|
albumArtUrl = maProvider.getImageUrl(playerTrack, size: 128);
|
||||||
|
}
|
||||||
|
final playerColorScheme = _playerColors[player.playerId];
|
||||||
|
final cardBgColor = playerColorScheme?.primaryContainer ?? defaultBgColor;
|
||||||
|
final cardTextColor = playerColorScheme?.onPrimaryContainer ?? defaultTextColor;
|
||||||
|
|
||||||
|
// Animation: slide from behind mini player
|
||||||
|
// Only calculate for items that will be built (visible ones)
|
||||||
|
const baseOffset = 80.0;
|
||||||
|
final reverseIndex = players.length - 1 - index;
|
||||||
|
final distanceToTravel = baseOffset + (reverseIndex * (cardHeight + cardSpacing));
|
||||||
|
final slideOffset = distanceToTravel * (1.0 - t);
|
||||||
|
|
||||||
|
return Transform.translate(
|
||||||
|
offset: Offset(0, slideOffset),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: cardSpacing),
|
||||||
|
child: PlayerCard(
|
||||||
|
player: player,
|
||||||
|
trackInfo: playerTrack,
|
||||||
|
albumArtUrl: albumArtUrl,
|
||||||
|
isSelected: false,
|
||||||
|
isPlaying: isPlaying,
|
||||||
|
isGrouped: player.isGrouped,
|
||||||
|
backgroundColor: cardBgColor,
|
||||||
|
textColor: cardTextColor,
|
||||||
|
onTap: () {
|
||||||
|
HapticFeedback.mediumImpact();
|
||||||
|
maProvider.selectPlayer(player);
|
||||||
|
dismiss();
|
||||||
|
},
|
||||||
|
onLongPress: () {
|
||||||
|
HapticFeedback.mediumImpact();
|
||||||
|
maProvider.togglePlayerSync(player.playerId);
|
||||||
|
},
|
||||||
|
onPlayPause: () {
|
||||||
|
if (isPlaying) {
|
||||||
|
maProvider.pausePlayer(player.playerId);
|
||||||
|
} else {
|
||||||
|
maProvider.resumePlayer(player.playerId);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSkipNext: () => maProvider.nextTrack(player.playerId),
|
||||||
|
onPower: () => maProvider.togglePower(player.playerId),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
// Non-scrollable list for when players fit
|
||||||
...List.generate(players.length, (index) {
|
...List.generate(players.length, (index) {
|
||||||
final player = players[index];
|
final player = players[index];
|
||||||
final isPlaying = player.state == 'playing';
|
final isPlaying = player.state == 'playing';
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import '../models/player.dart';
|
||||||
|
import '../l10n/app_localizations.dart';
|
||||||
|
|
||||||
|
/// A themed bottom sheet for selecting a player.
|
||||||
|
///
|
||||||
|
/// Supports adaptive theming - pass [adaptiveColorScheme] to use colors
|
||||||
|
/// extracted from album art, matching the detail screen backgrounds.
|
||||||
|
class PlayerPickerSheet extends StatelessWidget {
|
||||||
|
final String title;
|
||||||
|
final List<Player> players;
|
||||||
|
final Player? selectedPlayer;
|
||||||
|
final ColorScheme? adaptiveColorScheme;
|
||||||
|
final Future<void> Function(Player player) onPlayerSelected;
|
||||||
|
|
||||||
|
const PlayerPickerSheet({
|
||||||
|
super.key,
|
||||||
|
required this.title,
|
||||||
|
required this.players,
|
||||||
|
this.selectedPlayer,
|
||||||
|
this.adaptiveColorScheme,
|
||||||
|
required this.onPlayerSelected,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final themeColorScheme = Theme.of(context).colorScheme;
|
||||||
|
final colorScheme = adaptiveColorScheme ?? themeColorScheme;
|
||||||
|
|
||||||
|
// Use surface container for slightly elevated look, or adaptive surface
|
||||||
|
final backgroundColor = adaptiveColorScheme?.surface ?? themeColorScheme.surfaceContainerHigh;
|
||||||
|
final onBackgroundColor = adaptiveColorScheme?.onSurface ?? themeColorScheme.onSurface;
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: backgroundColor,
|
||||||
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
// Drag handle
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 12, bottom: 8),
|
||||||
|
child: Container(
|
||||||
|
width: 32,
|
||||||
|
height: 4,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: onBackgroundColor.withOpacity(0.3),
|
||||||
|
borderRadius: BorderRadius.circular(2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Title
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
|
||||||
|
child: Text(
|
||||||
|
title,
|
||||||
|
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||||
|
color: onBackgroundColor,
|
||||||
|
),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
|
||||||
|
// Player list
|
||||||
|
if (players.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(32.0),
|
||||||
|
child: Text(
|
||||||
|
S.of(context)!.noPlayersAvailable,
|
||||||
|
style: TextStyle(color: onBackgroundColor.withOpacity(0.6)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Flexible(
|
||||||
|
child: ListView.builder(
|
||||||
|
shrinkWrap: true,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
itemCount: players.length,
|
||||||
|
itemBuilder: (context, index) {
|
||||||
|
final player = players[index];
|
||||||
|
final isSelected = selectedPlayer?.playerId == player.playerId;
|
||||||
|
|
||||||
|
return _PlayerTile(
|
||||||
|
player: player,
|
||||||
|
isSelected: isSelected,
|
||||||
|
colorScheme: colorScheme,
|
||||||
|
onBackgroundColor: onBackgroundColor,
|
||||||
|
onTap: () => onPlayerSelected(player),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
SizedBox(height: MediaQuery.of(context).padding.bottom + 70),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _PlayerTile extends StatelessWidget {
|
||||||
|
final Player player;
|
||||||
|
final bool isSelected;
|
||||||
|
final ColorScheme colorScheme;
|
||||||
|
final Color onBackgroundColor;
|
||||||
|
final VoidCallback onTap;
|
||||||
|
|
||||||
|
const _PlayerTile({
|
||||||
|
required this.player,
|
||||||
|
required this.isSelected,
|
||||||
|
required this.colorScheme,
|
||||||
|
required this.onBackgroundColor,
|
||||||
|
required this.onTap,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
// Status color based on player state
|
||||||
|
Color statusColor;
|
||||||
|
if (!player.available) {
|
||||||
|
statusColor = Colors.grey.withOpacity(0.5);
|
||||||
|
} else if (!player.powered) {
|
||||||
|
statusColor = Colors.grey;
|
||||||
|
} else if (player.state == 'playing') {
|
||||||
|
statusColor = Colors.green;
|
||||||
|
} else {
|
||||||
|
statusColor = Colors.orange; // Idle/paused but powered
|
||||||
|
}
|
||||||
|
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||||
|
child: Material(
|
||||||
|
color: isSelected
|
||||||
|
? colorScheme.primaryContainer.withOpacity(0.3)
|
||||||
|
: Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: InkWell(
|
||||||
|
onTap: onTap,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
// Status indicator
|
||||||
|
Container(
|
||||||
|
width: 8,
|
||||||
|
height: 8,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
color: statusColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
|
||||||
|
// Speaker icon
|
||||||
|
Icon(
|
||||||
|
Icons.speaker_rounded,
|
||||||
|
color: isSelected
|
||||||
|
? colorScheme.primary
|
||||||
|
: onBackgroundColor.withOpacity(0.7),
|
||||||
|
size: 24,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
|
||||||
|
// Player name
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
player.name,
|
||||||
|
style: TextStyle(
|
||||||
|
color: isSelected
|
||||||
|
? colorScheme.primary
|
||||||
|
: onBackgroundColor,
|
||||||
|
fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Selected checkmark
|
||||||
|
if (isSelected)
|
||||||
|
Icon(
|
||||||
|
Icons.check_circle_rounded,
|
||||||
|
color: colorScheme.primary,
|
||||||
|
size: 20,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows the player picker bottom sheet with adaptive theming.
|
||||||
|
///
|
||||||
|
/// Returns the selected player, or null if dismissed.
|
||||||
|
Future<void> showPlayerPickerSheet({
|
||||||
|
required BuildContext context,
|
||||||
|
required String title,
|
||||||
|
required List<Player> players,
|
||||||
|
Player? selectedPlayer,
|
||||||
|
ColorScheme? adaptiveColorScheme,
|
||||||
|
required Future<void> Function(Player player) onPlayerSelected,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
isScrollControlled: true,
|
||||||
|
builder: (context) => PlayerPickerSheet(
|
||||||
|
title: title,
|
||||||
|
players: players,
|
||||||
|
selectedPlayer: selectedPlayer,
|
||||||
|
adaptiveColorScheme: adaptiveColorScheme,
|
||||||
|
onPlayerSelected: (player) async {
|
||||||
|
Navigator.pop(context);
|
||||||
|
await onPlayerSelected(player);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -202,17 +202,23 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
|||||||
// but still have track info - treat as "has content" for display
|
// but still have track info - treat as "has content" for display
|
||||||
final isIdle = player.state == 'idle';
|
final isIdle = player.state == 'idle';
|
||||||
|
|
||||||
|
// Check for external source (optical, Spotify, etc.)
|
||||||
|
final isExternalSource = player.isExternalSource;
|
||||||
|
|
||||||
// Get track info - use current track for selected player, cache for others
|
// Get track info - use current track for selected player, cache for others
|
||||||
final playerTrack = isSelected
|
// Skip track info for external sources
|
||||||
? currentTrack
|
final playerTrack = isExternalSource
|
||||||
: maProvider.getCachedTrackForPlayer(player.playerId);
|
? null
|
||||||
|
: (isSelected
|
||||||
|
? currentTrack
|
||||||
|
: maProvider.getCachedTrackForPlayer(player.playerId));
|
||||||
|
|
||||||
// Player has content if playing, paused, or idle with cached track
|
// Player has content if playing, paused, or idle with cached track (but not external source)
|
||||||
final hasContent = isPlaying || isPaused || (isIdle && playerTrack != null);
|
final hasContent = !isExternalSource && (isPlaying || isPaused || (isIdle && playerTrack != null));
|
||||||
|
|
||||||
// Get album art for any player with content
|
// Get album art for any player with content (skip for external source)
|
||||||
String? albumArtUrl;
|
String? albumArtUrl;
|
||||||
if (playerTrack != null && isOn && hasContent) {
|
if (!isExternalSource && playerTrack != null && isOn && hasContent) {
|
||||||
albumArtUrl = maProvider.getImageUrl(
|
albumArtUrl = maProvider.getImageUrl(
|
||||||
playerTrack.album ?? playerTrack,
|
playerTrack.album ?? playerTrack,
|
||||||
size: 128,
|
size: 128,
|
||||||
@@ -321,11 +327,13 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
|||||||
? colorScheme.onSurface.withOpacity(0.24)
|
? colorScheme.onSurface.withOpacity(0.24)
|
||||||
: !isOn
|
: !isOn
|
||||||
? colorScheme.onSurface.withOpacity(0.3)
|
? colorScheme.onSurface.withOpacity(0.3)
|
||||||
: isPlaying
|
: isExternalSource
|
||||||
? Colors.green
|
? Colors.cyan // external source (optical, Spotify, etc.)
|
||||||
: hasContent
|
: isPlaying
|
||||||
? Colors.orange // paused or idle with content
|
? Colors.green
|
||||||
: colorScheme.onSurfaceVariant.withOpacity(0.5),
|
: hasContent
|
||||||
|
? Colors.orange // paused or idle with content
|
||||||
|
: colorScheme.onSurfaceVariant.withOpacity(0.5),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
@@ -335,9 +343,11 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
|||||||
? S.of(context)!.playerStateUnavailable
|
? S.of(context)!.playerStateUnavailable
|
||||||
: !isOn
|
: !isOn
|
||||||
? S.of(context)!.playerStateOff
|
? S.of(context)!.playerStateOff
|
||||||
: hasContent && playerTrack != null
|
: isExternalSource
|
||||||
? playerTrack.name
|
? S.of(context)!.playerStateExternalSource
|
||||||
: S.of(context)!.playerStateIdle,
|
: hasContent && playerTrack != null
|
||||||
|
? playerTrack.name
|
||||||
|
: S.of(context)!.playerStateIdle,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
color: player.available
|
color: player.available
|
||||||
? colorScheme.onSurfaceVariant
|
? colorScheme.onSurfaceVariant
|
||||||
@@ -400,8 +410,8 @@ class _PlayerSelectorSheetState extends State<_PlayerSelectorSheet> {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
// Play/Pause button
|
// Play/Pause button (hidden for external sources - controls don't work)
|
||||||
if (player.available && isOn)
|
if (player.available && isOn && !isExternalSource)
|
||||||
IconButton(
|
IconButton(
|
||||||
icon: Icon(
|
icon: Icon(
|
||||||
isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
name: ensemble
|
name: ensemble
|
||||||
description: A minimalistic Music Assistant client built with Flutter
|
description: A minimalistic Music Assistant client built with Flutter
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
version: 2.6.0-beta+28
|
version: 2.7.2-beta+31
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: '>=3.0.0 <4.0.0'
|
sdk: '>=3.0.0 <4.0.0'
|
||||||
|
|||||||
Reference in New Issue
Block a user