diff --git a/lib/data/db.dart b/lib/data/db.dart index 0b2bfea..7abb420 100644 --- a/lib/data/db.dart +++ b/lib/data/db.dart @@ -11,6 +11,7 @@ class Tracks extends Table { IntColumn get duration => integer().nullable()(); // Duration in milliseconds TextColumn get path => text().unique()(); TextColumn get artUri => text().nullable()(); // Path to local cover art + TextColumn get lyrics => text().nullable()(); // JSON formatted lyrics DateTimeColumn get addedAt => dateTime().withDefault(currentDateAndTime)(); } @@ -33,7 +34,7 @@ class AppDatabase extends _$AppDatabase { AppDatabase() : super(_openConnection()); @override - int get schemaVersion => 3; // Bump version + int get schemaVersion => 4; // Bump version for lyrics column @override MigrationStrategy get migration { @@ -49,6 +50,9 @@ class AppDatabase extends _$AppDatabase { await m.createTable(playlists); await m.createTable(playlistEntries); } + if (from < 4) { + await m.addColumn(tracks, tracks.lyrics); + } }, ); } diff --git a/lib/data/db.g.dart b/lib/data/db.g.dart index 8a4becb..857481b 100644 --- a/lib/data/db.g.dart +++ b/lib/data/db.g.dart @@ -78,6 +78,15 @@ class $TracksTable extends Tracks with TableInfo<$TracksTable, Track> { type: DriftSqlType.string, requiredDuringInsert: false, ); + static const VerificationMeta _lyricsMeta = const VerificationMeta('lyrics'); + @override + late final GeneratedColumn lyrics = GeneratedColumn( + 'lyrics', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); static const VerificationMeta _addedAtMeta = const VerificationMeta( 'addedAt', ); @@ -99,6 +108,7 @@ class $TracksTable extends Tracks with TableInfo<$TracksTable, Track> { duration, path, artUri, + lyrics, addedAt, ]; @override @@ -156,6 +166,12 @@ class $TracksTable extends Tracks with TableInfo<$TracksTable, Track> { artUri.isAcceptableOrUnknown(data['art_uri']!, _artUriMeta), ); } + if (data.containsKey('lyrics')) { + context.handle( + _lyricsMeta, + lyrics.isAcceptableOrUnknown(data['lyrics']!, _lyricsMeta), + ); + } if (data.containsKey('added_at')) { context.handle( _addedAtMeta, @@ -199,6 +215,10 @@ class $TracksTable extends Tracks with TableInfo<$TracksTable, Track> { DriftSqlType.string, data['${effectivePrefix}art_uri'], ), + lyrics: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}lyrics'], + ), addedAt: attachedDatabase.typeMapping.read( DriftSqlType.dateTime, data['${effectivePrefix}added_at'], @@ -220,6 +240,7 @@ class Track extends DataClass implements Insertable { final int? duration; final String path; final String? artUri; + final String? lyrics; final DateTime addedAt; const Track({ required this.id, @@ -229,6 +250,7 @@ class Track extends DataClass implements Insertable { this.duration, required this.path, this.artUri, + this.lyrics, required this.addedAt, }); @override @@ -249,6 +271,9 @@ class Track extends DataClass implements Insertable { if (!nullToAbsent || artUri != null) { map['art_uri'] = Variable(artUri); } + if (!nullToAbsent || lyrics != null) { + map['lyrics'] = Variable(lyrics); + } map['added_at'] = Variable(addedAt); return map; } @@ -270,6 +295,9 @@ class Track extends DataClass implements Insertable { artUri: artUri == null && nullToAbsent ? const Value.absent() : Value(artUri), + lyrics: lyrics == null && nullToAbsent + ? const Value.absent() + : Value(lyrics), addedAt: Value(addedAt), ); } @@ -287,6 +315,7 @@ class Track extends DataClass implements Insertable { duration: serializer.fromJson(json['duration']), path: serializer.fromJson(json['path']), artUri: serializer.fromJson(json['artUri']), + lyrics: serializer.fromJson(json['lyrics']), addedAt: serializer.fromJson(json['addedAt']), ); } @@ -301,6 +330,7 @@ class Track extends DataClass implements Insertable { 'duration': serializer.toJson(duration), 'path': serializer.toJson(path), 'artUri': serializer.toJson(artUri), + 'lyrics': serializer.toJson(lyrics), 'addedAt': serializer.toJson(addedAt), }; } @@ -313,6 +343,7 @@ class Track extends DataClass implements Insertable { Value duration = const Value.absent(), String? path, Value artUri = const Value.absent(), + Value lyrics = const Value.absent(), DateTime? addedAt, }) => Track( id: id ?? this.id, @@ -322,6 +353,7 @@ class Track extends DataClass implements Insertable { duration: duration.present ? duration.value : this.duration, path: path ?? this.path, artUri: artUri.present ? artUri.value : this.artUri, + lyrics: lyrics.present ? lyrics.value : this.lyrics, addedAt: addedAt ?? this.addedAt, ); Track copyWithCompanion(TracksCompanion data) { @@ -333,6 +365,7 @@ class Track extends DataClass implements Insertable { duration: data.duration.present ? data.duration.value : this.duration, path: data.path.present ? data.path.value : this.path, artUri: data.artUri.present ? data.artUri.value : this.artUri, + lyrics: data.lyrics.present ? data.lyrics.value : this.lyrics, addedAt: data.addedAt.present ? data.addedAt.value : this.addedAt, ); } @@ -347,14 +380,24 @@ class Track extends DataClass implements Insertable { ..write('duration: $duration, ') ..write('path: $path, ') ..write('artUri: $artUri, ') + ..write('lyrics: $lyrics, ') ..write('addedAt: $addedAt') ..write(')')) .toString(); } @override - int get hashCode => - Object.hash(id, title, artist, album, duration, path, artUri, addedAt); + int get hashCode => Object.hash( + id, + title, + artist, + album, + duration, + path, + artUri, + lyrics, + addedAt, + ); @override bool operator ==(Object other) => identical(this, other) || @@ -366,6 +409,7 @@ class Track extends DataClass implements Insertable { other.duration == this.duration && other.path == this.path && other.artUri == this.artUri && + other.lyrics == this.lyrics && other.addedAt == this.addedAt); } @@ -377,6 +421,7 @@ class TracksCompanion extends UpdateCompanion { final Value duration; final Value path; final Value artUri; + final Value lyrics; final Value addedAt; const TracksCompanion({ this.id = const Value.absent(), @@ -386,6 +431,7 @@ class TracksCompanion extends UpdateCompanion { this.duration = const Value.absent(), this.path = const Value.absent(), this.artUri = const Value.absent(), + this.lyrics = const Value.absent(), this.addedAt = const Value.absent(), }); TracksCompanion.insert({ @@ -396,6 +442,7 @@ class TracksCompanion extends UpdateCompanion { this.duration = const Value.absent(), required String path, this.artUri = const Value.absent(), + this.lyrics = const Value.absent(), this.addedAt = const Value.absent(), }) : title = Value(title), path = Value(path); @@ -407,6 +454,7 @@ class TracksCompanion extends UpdateCompanion { Expression? duration, Expression? path, Expression? artUri, + Expression? lyrics, Expression? addedAt, }) { return RawValuesInsertable({ @@ -417,6 +465,7 @@ class TracksCompanion extends UpdateCompanion { if (duration != null) 'duration': duration, if (path != null) 'path': path, if (artUri != null) 'art_uri': artUri, + if (lyrics != null) 'lyrics': lyrics, if (addedAt != null) 'added_at': addedAt, }); } @@ -429,6 +478,7 @@ class TracksCompanion extends UpdateCompanion { Value? duration, Value? path, Value? artUri, + Value? lyrics, Value? addedAt, }) { return TracksCompanion( @@ -439,6 +489,7 @@ class TracksCompanion extends UpdateCompanion { duration: duration ?? this.duration, path: path ?? this.path, artUri: artUri ?? this.artUri, + lyrics: lyrics ?? this.lyrics, addedAt: addedAt ?? this.addedAt, ); } @@ -467,6 +518,9 @@ class TracksCompanion extends UpdateCompanion { if (artUri.present) { map['art_uri'] = Variable(artUri.value); } + if (lyrics.present) { + map['lyrics'] = Variable(lyrics.value); + } if (addedAt.present) { map['added_at'] = Variable(addedAt.value); } @@ -483,6 +537,7 @@ class TracksCompanion extends UpdateCompanion { ..write('duration: $duration, ') ..write('path: $path, ') ..write('artUri: $artUri, ') + ..write('lyrics: $lyrics, ') ..write('addedAt: $addedAt') ..write(')')) .toString(); @@ -1079,6 +1134,7 @@ typedef $$TracksTableCreateCompanionBuilder = Value duration, required String path, Value artUri, + Value lyrics, Value addedAt, }); typedef $$TracksTableUpdateCompanionBuilder = @@ -1090,6 +1146,7 @@ typedef $$TracksTableUpdateCompanionBuilder = Value duration, Value path, Value artUri, + Value lyrics, Value addedAt, }); @@ -1162,6 +1219,11 @@ class $$TracksTableFilterComposer builder: (column) => ColumnFilters(column), ); + ColumnFilters get lyrics => $composableBuilder( + column: $table.lyrics, + builder: (column) => ColumnFilters(column), + ); + ColumnFilters get addedAt => $composableBuilder( column: $table.addedAt, builder: (column) => ColumnFilters(column), @@ -1237,6 +1299,11 @@ class $$TracksTableOrderingComposer builder: (column) => ColumnOrderings(column), ); + ColumnOrderings get lyrics => $composableBuilder( + column: $table.lyrics, + builder: (column) => ColumnOrderings(column), + ); + ColumnOrderings get addedAt => $composableBuilder( column: $table.addedAt, builder: (column) => ColumnOrderings(column), @@ -1273,6 +1340,9 @@ class $$TracksTableAnnotationComposer GeneratedColumn get artUri => $composableBuilder(column: $table.artUri, builder: (column) => column); + GeneratedColumn get lyrics => + $composableBuilder(column: $table.lyrics, builder: (column) => column); + GeneratedColumn get addedAt => $composableBuilder(column: $table.addedAt, builder: (column) => column); @@ -1337,6 +1407,7 @@ class $$TracksTableTableManager Value duration = const Value.absent(), Value path = const Value.absent(), Value artUri = const Value.absent(), + Value lyrics = const Value.absent(), Value addedAt = const Value.absent(), }) => TracksCompanion( id: id, @@ -1346,6 +1417,7 @@ class $$TracksTableTableManager duration: duration, path: path, artUri: artUri, + lyrics: lyrics, addedAt: addedAt, ), createCompanionCallback: @@ -1357,6 +1429,7 @@ class $$TracksTableTableManager Value duration = const Value.absent(), required String path, Value artUri = const Value.absent(), + Value lyrics = const Value.absent(), Value addedAt = const Value.absent(), }) => TracksCompanion.insert( id: id, @@ -1366,6 +1439,7 @@ class $$TracksTableTableManager duration: duration, path: path, artUri: artUri, + lyrics: lyrics, addedAt: addedAt, ), withReferenceMapper: (p0) => p0 diff --git a/lib/data/playlist_repository.g.dart b/lib/data/playlist_repository.g.dart index ca7f52c..8dd2db2 100644 --- a/lib/data/playlist_repository.g.dart +++ b/lib/data/playlist_repository.g.dart @@ -34,7 +34,7 @@ final class PlaylistRepositoryProvider } String _$playlistRepositoryHash() => - r'9a76fa2443bfb810b75b26adaf6225de48049a3a'; + r'614d837f9438d2454778edb4ff60b046418490b8'; abstract class _$PlaylistRepository extends $AsyncNotifier { FutureOr build(); diff --git a/lib/data/track_repository.dart b/lib/data/track_repository.dart index b2f457d..4acb8a2 100644 --- a/lib/data/track_repository.dart +++ b/lib/data/track_repository.dart @@ -128,4 +128,26 @@ class TrackRepository extends _$TrackRepository { } } } + + /// Update lyrics for a track. + Future updateLyrics(int trackId, String? lyricsJson) async { + final db = ref.read(databaseProvider); + await (db.update(db.tracks)..where((t) => t.id.equals(trackId))).write( + TracksCompanion(lyrics: Value(lyricsJson)), + ); + } + + /// Get a single track by ID. + Future getTrack(int trackId) async { + final db = ref.read(databaseProvider); + return (db.select( + db.tracks, + )..where((t) => t.id.equals(trackId))).getSingleOrNull(); + } + + /// Get all tracks for batch matching. + Future> getAllTracks() async { + final db = ref.read(databaseProvider); + return db.select(db.tracks).get(); + } } diff --git a/lib/data/track_repository.g.dart b/lib/data/track_repository.g.dart index 5be2a7b..162a651 100644 --- a/lib/data/track_repository.g.dart +++ b/lib/data/track_repository.g.dart @@ -33,7 +33,7 @@ final class TrackRepositoryProvider TrackRepository create() => TrackRepository(); } -String _$trackRepositoryHash() => r'57600f36bc6b3963105e2b6f4b2554dfbc03aa69'; +String _$trackRepositoryHash() => r'ad77006c472739d9d5067d394d6c5a3437535a11'; abstract class _$TrackRepository extends $AsyncNotifier { FutureOr build(); diff --git a/lib/logic/lyrics_parser.dart b/lib/logic/lyrics_parser.dart new file mode 100644 index 0000000..2e51fb2 --- /dev/null +++ b/lib/logic/lyrics_parser.dart @@ -0,0 +1,155 @@ +import 'dart:convert'; + +/// Represents a single line of lyrics with optional timing. +class LyricsLine { + final int? timeMs; // Time in milliseconds, null for plaintext + final String text; + + LyricsLine({this.timeMs, required this.text}); + + Map toJson() => {'time': timeMs, 'text': text}; + + factory LyricsLine.fromJson(Map json) => + LyricsLine(timeMs: json['time'] as int?, text: json['text'] as String); +} + +/// Represents parsed lyrics data. +class LyricsData { + final String type; // 'timed' or 'plain' + final List lines; + + LyricsData({required this.type, required this.lines}); + + Map toJson() => { + 'type': type, + 'lines': lines.map((l) => l.toJson()).toList(), + }; + + factory LyricsData.fromJson(Map json) => LyricsData( + type: json['type'] as String, + lines: (json['lines'] as List) + .map((l) => LyricsLine.fromJson(l as Map)) + .toList(), + ); + + String toJsonString() => jsonEncode(toJson()); + + static LyricsData fromJsonString(String json) => + LyricsData.fromJson(jsonDecode(json) as Map); +} + +/// Parser for various lyrics file formats. +class LyricsParser { + /// Parse LRC format lyrics. + /// Format: [mm:ss.xx] Lyrics text + static LyricsData parseLrc(String content) { + final lines = []; + final regex = RegExp(r'\[(\d+):(\d+)\.?(\d+)?\](.*)'); + + for (final line in content.split('\n')) { + final match = regex.firstMatch(line.trim()); + if (match != null) { + final minutes = int.parse(match.group(1)!); + final seconds = int.parse(match.group(2)!); + final centiseconds = int.tryParse(match.group(3) ?? '0') ?? 0; + final text = match.group(4)?.trim() ?? ''; + + // Convert to milliseconds + final timeMs = + (minutes * 60 * 1000) + + (seconds * 1000) + + (centiseconds * 10); // centiseconds to ms + + if (text.isNotEmpty) { + lines.add(LyricsLine(timeMs: timeMs, text: text)); + } + } + } + + // Sort by time + lines.sort((a, b) => (a.timeMs ?? 0).compareTo(b.timeMs ?? 0)); + + return LyricsData(type: 'timed', lines: lines); + } + + /// Parse SRT (SubRip) format. + /// Format: + /// 1 + /// 00:00:12,500 --> 00:00:15,000 + /// Lyrics text + static LyricsData parseSrt(String content) { + final lines = []; + final blocks = content.split(RegExp(r'\n\s*\n')); + final timeRegex = RegExp( + r'(\d+):(\d+):(\d+)[,.](\d+)\s*-->\s*\d+:\d+:\d+[,.]?\d*', + ); + + for (final block in blocks) { + final blockLines = block.trim().split('\n'); + if (blockLines.length >= 2) { + // Find timestamp line + for (int i = 0; i < blockLines.length; i++) { + final match = timeRegex.firstMatch(blockLines[i]); + if (match != null) { + final hours = int.parse(match.group(1)!); + final minutes = int.parse(match.group(2)!); + final seconds = int.parse(match.group(3)!); + final millis = int.parse(match.group(4)!.padRight(3, '0')); + + final timeMs = + (hours * 3600 * 1000) + + (minutes * 60 * 1000) + + (seconds * 1000) + + millis; + + // Text is everything after the timestamp line + final text = blockLines.sublist(i + 1).join(' ').trim(); + if (text.isNotEmpty) { + lines.add(LyricsLine(timeMs: timeMs, text: text)); + } + break; + } + } + } + } + + // Sort by time + lines.sort((a, b) => (a.timeMs ?? 0).compareTo(b.timeMs ?? 0)); + + return LyricsData(type: 'timed', lines: lines); + } + + /// Parse plaintext lyrics (no timing). + static LyricsData parsePlaintext(String content) { + final lines = content + .split('\n') + .map((l) => l.trim()) + .where((l) => l.isNotEmpty) + .map((l) => LyricsLine(text: l)) + .toList(); + + return LyricsData(type: 'plain', lines: lines); + } + + /// Auto-detect format and parse. + static LyricsData parse(String content, String filename) { + final lowerFilename = filename.toLowerCase(); + + if (lowerFilename.endsWith('.lrc')) { + return parseLrc(content); + } else if (lowerFilename.endsWith('.srt')) { + return parseSrt(content); + } else { + // Check if content looks like LRC + if (RegExp(r'\[\d+:\d+').hasMatch(content)) { + return parseLrc(content); + } + // Check if content looks like SRT + if (RegExp(r'\d+:\d+:\d+[,.]').hasMatch(content)) { + return parseSrt(content); + } + // Default to plaintext + return parsePlaintext(content); + } + } +} diff --git a/lib/ui/screens/library_screen.dart b/lib/ui/screens/library_screen.dart index 530fda1..b79a9b4 100644 --- a/lib/ui/screens/library_screen.dart +++ b/lib/ui/screens/library_screen.dart @@ -9,6 +9,7 @@ import '../../data/track_repository.dart'; import '../../providers/audio_provider.dart'; import '../../data/playlist_repository.dart'; import '../../data/db.dart'; +import '../../logic/lyrics_parser.dart'; import '../tabs/albums_tab.dart'; import '../tabs/playlists_tab.dart'; @@ -109,6 +110,11 @@ class LibraryScreen extends HookConsumerWidget { } }, ), + IconButton( + icon: const Icon(Icons.lyrics_outlined), + tooltip: 'Batch Import Lyrics', + onPressed: () => _batchImportLyrics(context, ref), + ), const Gap(8), ], ), @@ -130,6 +136,9 @@ class LibraryScreen extends HookConsumerWidget { } return ListView.builder( + padding: EdgeInsets.only( + bottom: 72 + MediaQuery.paddingOf(context).bottom, + ), itemCount: tracks.length, itemBuilder: (context, index) { final track = tracks[index]; @@ -295,6 +304,14 @@ class LibraryScreen extends HookConsumerWidget { _showEditDialog(context, ref, track); }, ), + ListTile( + leading: const Icon(Icons.lyrics_outlined), + title: const Text('Import Lyrics'), + onTap: () { + Navigator.pop(context); + _importLyricsForTrack(context, ref, track); + }, + ), ListTile( leading: const Icon(Icons.delete, color: Colors.red), title: const Text( @@ -557,4 +574,92 @@ class LibraryScreen extends HookConsumerWidget { ); } } + + Future _importLyricsForTrack( + BuildContext context, + WidgetRef ref, + Track track, + ) async { + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['lrc', 'srt', 'txt'], + allowMultiple: false, + ); + + if (result != null && result.files.isNotEmpty) { + final file = File(result.files.first.path!); + final content = await file.readAsString(); + final filename = result.files.first.name; + + final lyricsData = LyricsParser.parse(content, filename); + final lyricsJson = lyricsData.toJsonString(); + + await ref + .read(trackRepositoryProvider.notifier) + .updateLyrics(track.id, lyricsJson); + + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Imported ${lyricsData.lines.length} lyrics lines for "${track.title}"', + ), + ), + ); + } + } + + Future _batchImportLyrics(BuildContext context, WidgetRef ref) async { + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['lrc', 'srt', 'txt'], + allowMultiple: true, + ); + + if (result == null || result.files.isEmpty) return; + + final repo = ref.read(trackRepositoryProvider.notifier); + final tracks = await repo.getAllTracks(); + + int matched = 0; + int notMatched = 0; + + for (final pickedFile in result.files) { + if (pickedFile.path == null) continue; + + final file = File(pickedFile.path!); + final content = await file.readAsString(); + final filename = pickedFile.name; + + // Get basename without extension for matching + final baseName = filename + .replaceAll(RegExp(r'\.(lrc|srt|txt)$', caseSensitive: false), '') + .toLowerCase(); + + // Try to find a matching track by title + final matchingTrack = tracks.where((t) { + final trackTitle = t.title.toLowerCase(); + return trackTitle == baseName || + trackTitle.contains(baseName) || + baseName.contains(trackTitle); + }).firstOrNull; + + if (matchingTrack != null) { + final lyricsData = LyricsParser.parse(content, filename); + await repo.updateLyrics(matchingTrack.id, lyricsData.toJsonString()); + matched++; + } else { + notMatched++; + } + } + + if (!context.mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Batch import complete: $matched matched, $notMatched not matched', + ), + ), + ); + } } diff --git a/lib/ui/screens/player_screen.dart b/lib/ui/screens/player_screen.dart index 4e75612..319d89b 100644 --- a/lib/ui/screens/player_screen.dart +++ b/lib/ui/screens/player_screen.dart @@ -2,9 +2,13 @@ import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:media_kit/media_kit.dart'; +import 'package:super_sliver_list/super_sliver_list.dart'; import '../../providers/audio_provider.dart'; +import '../../providers/db_provider.dart'; import '../../logic/metadata_service.dart'; +import '../../logic/lyrics_parser.dart'; +import '../../data/db.dart' as db; import '../widgets/mini_player.dart'; class PlayerScreen extends HookConsumerWidget { @@ -15,47 +19,84 @@ class PlayerScreen extends HookConsumerWidget { final audioHandler = ref.watch(audioHandlerProvider); final player = audioHandler.player; + final tabController = useTabController(initialLength: 2); + final isMobile = MediaQuery.sizeOf(context).width <= 640; + return Scaffold( - appBar: AppBar( - title: const Text('Now Playing'), - centerTitle: true, - leading: IconButton( - icon: const Icon(Icons.keyboard_arrow_down), - onPressed: () => Navigator.of(context).pop(), - ), - ), - body: StreamBuilder( - stream: player.stream.playlist, - initialData: player.state.playlist, - builder: (context, snapshot) { - final index = snapshot.data?.index ?? 0; - final medias = snapshot.data?.medias ?? []; - if (medias.isEmpty || index < 0 || index >= medias.length) { - return const Center(child: Text('No media selected')); - } - final media = medias[index]; - final path = Uri.decodeFull(Uri.parse(media.uri).path); - - final metadataAsync = ref.watch(trackMetadataProvider(path)); - - return LayoutBuilder( - builder: (context, constraints) { - if (constraints.maxWidth < 600) { - return _MobileLayout( - player: player, - metadataAsync: metadataAsync, - media: media, - ); - } else { - return _DesktopLayout( - player: player, - metadataAsync: metadataAsync, - media: media, - ); + body: Stack( + children: [ + // Main content (StreamBuilder) + StreamBuilder( + stream: player.stream.playlist, + initialData: player.state.playlist, + builder: (context, snapshot) { + final index = snapshot.data?.index ?? 0; + final medias = snapshot.data?.medias ?? []; + if (medias.isEmpty || index < 0 || index >= medias.length) { + return const Center(child: Text('No media selected')); } + final media = medias[index]; + final path = Uri.decodeFull(Uri.parse(media.uri).path); + + final metadataAsync = ref.watch(trackMetadataProvider(path)); + + return Builder( + builder: (context) { + if (isMobile) { + return Padding( + padding: EdgeInsets.only( + top: MediaQuery.of(context).padding.top + 48, + ), + child: _MobileLayout( + player: player, + tabController: tabController, + metadataAsync: metadataAsync, + media: media, + trackPath: path, + ), + ); + } else { + return _DesktopLayout( + player: player, + metadataAsync: metadataAsync, + media: media, + trackPath: path, + ); + } + }, + ); }, - ); - }, + ), + // IconButton + Positioned( + top: MediaQuery.of(context).padding.top + 8, + left: 8, + child: IconButton( + icon: const Icon(Icons.keyboard_arrow_down), + onPressed: () => Navigator.of(context).pop(), + padding: EdgeInsets.zero, + ), + ), + // TabBar (if mobile) + if (isMobile) + Positioned( + top: MediaQuery.of(context).padding.top + 8, + left: 50, + right: 50, + child: TabBar( + controller: tabController, + tabAlignment: TabAlignment.fill, + tabs: const [ + Tab(text: 'Cover'), + Tab(text: 'Lyrics'), + ], + dividerHeight: 0, + indicatorColor: Colors.transparent, + overlayColor: WidgetStatePropertyAll(Colors.transparent), + splashFactory: NoSplash.splashFactory, + ), + ), + ], ), ); } @@ -63,73 +104,58 @@ class PlayerScreen extends HookConsumerWidget { class _MobileLayout extends StatelessWidget { final Player player; + final TabController tabController; final AsyncValue metadataAsync; final Media media; + final String trackPath; const _MobileLayout({ required this.player, + required this.tabController, required this.metadataAsync, required this.media, + required this.trackPath, }); @override Widget build(BuildContext context) { - return DefaultTabController( - length: 2, - child: Column( - children: [ - const TabBar( - tabs: [ - Tab(text: 'Cover'), - Tab(text: 'Lyrics'), + return TabBarView( + controller: tabController, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Column( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Center( + child: _PlayerCoverArt(metadataAsync: metadataAsync), + ), + ), + ), + _PlayerControls( + player: player, + metadataAsync: metadataAsync, + media: media, + ), + const SizedBox(height: 24), ], - dividerColor: Colors.transparent, - splashFactory: NoSplash.splashFactory, - overlayColor: WidgetStatePropertyAll(Colors.transparent), ), - Expanded( - child: TabBarView( - children: [ - // Cover Art Tab with Full Controls - Column( - children: [ - Expanded( - child: Padding( - padding: const EdgeInsets.all(32.0), - child: Center( - child: _PlayerCoverArt(metadataAsync: metadataAsync), - ), - ), - ), - _PlayerControls( - player: player, - metadataAsync: metadataAsync, - media: media, - ), - const SizedBox(height: 24), - ], - ), - // Lyrics Tab with Mini Player - Column( - children: [ - const Expanded( - child: Padding( - padding: EdgeInsets.all(16.0), - child: _PlayerLyrics(), - ), - ), - MiniPlayer(enableTapToOpen: false), - ], - ), - ], + ), + // Lyrics Tab with Mini Player + Column( + children: [ + Expanded( + child: Padding( + padding: EdgeInsets.all(16.0), + child: _PlayerLyrics(trackPath: trackPath, player: player), + ), ), - ), - // Tab Indicators (Overlay style or bottom? Standard is usually separate or top. Keeping bottom for consistency with previous, but maybe cleaner at top? User didn't specify position, just content. Let's keep indicators at bottom of screen but actually, if controls are in tabs, indicators might overlap? Moving indicators to top standard position or just removing them if swiping is enough? Let's keep them at the top of the content area for clarity, or overlay. Actually, previous layout had indicators below TabBarView but above controls. Now controls are IN TabBarView. Let's put TabBar at the TOP or BOTTOM of the screen. Top is standard Android/iOS for sub-views. Let's try TOP.) - // Actually, let's put TabBar at the very bottom, or top. Let's stick to top as standard.) - // Wait, the previous code had them between tabs and controls. - // Let's place TabBar at the top of the screen (below AppBar) for this layout. - ], - ), + MiniPlayer(enableTapToOpen: false), + ], + ), + ], ); } } @@ -138,11 +164,13 @@ class _DesktopLayout extends StatelessWidget { final Player player; final AsyncValue metadataAsync; final Media media; + final String trackPath; const _DesktopLayout({ required this.player, required this.metadataAsync, required this.media, + required this.trackPath, }); @override @@ -152,36 +180,46 @@ class _DesktopLayout extends StatelessWidget { // Left Side: Cover + Controls Expanded( flex: 1, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Expanded( - child: Padding( - padding: const EdgeInsets.all(32.0), - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 400), - child: AspectRatio( - aspectRatio: 1, - child: _PlayerCoverArt(metadataAsync: metadataAsync), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 480), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: AspectRatio( + aspectRatio: 1, + child: _PlayerCoverArt( + metadataAsync: metadataAsync, + ), + ), + ), ), ), ), - ), + _PlayerControls( + player: player, + metadataAsync: metadataAsync, + media: media, + ), + const SizedBox(height: 32), + ], ), - _PlayerControls( - player: player, - metadataAsync: metadataAsync, - media: media, - ), - const SizedBox(height: 32), - ], + ), ), ), // Right Side: Lyrics - const Expanded( + Expanded( flex: 1, - child: Padding(padding: EdgeInsets.all(32.0), child: _PlayerLyrics()), + child: Padding( + padding: EdgeInsets.all(32.0), + child: _PlayerLyrics(trackPath: trackPath, player: player), + ), ), ], ); @@ -221,7 +259,7 @@ class _PlayerCoverArt extends StatelessWidget { : null, ), loading: () => const Center(child: CircularProgressIndicator()), - error: (_, __) => Container( + error: (_, _) => Container( decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(24), @@ -234,24 +272,158 @@ class _PlayerCoverArt extends StatelessWidget { } } -class _PlayerLyrics extends StatelessWidget { - const _PlayerLyrics(); +class _PlayerLyrics extends HookConsumerWidget { + final String? trackPath; + final Player player; + + const _PlayerLyrics({this.trackPath, required this.player}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + // Watch for track data (including lyrics) by path + final trackAsync = trackPath != null + ? ref.watch(_trackByPathProvider(trackPath!)) + : const AsyncValue.data(null); + + return trackAsync.when( + loading: () => const Center(child: CircularProgressIndicator()), + error: (e, _) => Center(child: Text('Error: $e')), + data: (track) { + if (track == null || track.lyrics == null) { + return const Center( + child: Text( + 'No Lyrics Available', + style: TextStyle(fontStyle: FontStyle.italic), + ), + ); + } + + try { + final lyricsData = LyricsData.fromJsonString(track.lyrics!); + + if (lyricsData.type == 'timed') { + return _TimedLyricsView(lyrics: lyricsData, player: player); + } else { + // Plain text lyrics + return ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: lyricsData.lines.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Text( + lyricsData.lines[index].text, + style: Theme.of(context).textTheme.bodyLarge, + textAlign: TextAlign.center, + ), + ); + }, + ); + } + } catch (e) { + return Center(child: Text('Error parsing lyrics: $e')); + } + }, + ); + } +} + +// Provider to fetch a single track by path +final _trackByPathProvider = FutureProvider.family(( + ref, + trackPath, +) async { + final database = ref.watch(databaseProvider); + return (database.select( + database.tracks, + )..where((t) => t.path.equals(trackPath))).getSingleOrNull(); +}); + +class _TimedLyricsView extends HookWidget { + final LyricsData lyrics; + final Player player; + + const _TimedLyricsView({required this.lyrics, required this.player}); @override Widget build(BuildContext context) { - return Container( - decoration: BoxDecoration( - color: Theme.of( - context, - ).colorScheme.surfaceContainerHighest.withValues(alpha: 0.3), - borderRadius: BorderRadius.circular(16), - ), - child: const Center( - child: Text( - 'No Lyrics Available', - style: TextStyle(fontStyle: FontStyle.italic), - ), - ), + final listController = useMemoized(() => ListController(), []); + final scrollController = useScrollController(); + final previousIndex = useState(-1); + + return StreamBuilder( + stream: player.stream.position, + initialData: player.state.position, + builder: (context, snapshot) { + final position = snapshot.data ?? Duration.zero; + final positionMs = position.inMilliseconds; + + // Find current line index + int currentIndex = 0; + for (int i = 0; i < lyrics.lines.length; i++) { + if ((lyrics.lines[i].timeMs ?? 0) <= positionMs) { + currentIndex = i; + } else { + break; + } + } + + // Auto-scroll when current line changes + if (currentIndex != previousIndex.value) { + WidgetsBinding.instance.addPostFrameCallback((_) { + previousIndex.value = currentIndex; + listController.animateToItem( + index: currentIndex, + scrollController: scrollController, + alignment: 0.5, + duration: (_) => const Duration(milliseconds: 300), + curve: (_) => Curves.easeOutCubic, + ); + }); + } + + return SuperListView.builder( + padding: EdgeInsets.only( + top: 0.25 * MediaQuery.sizeOf(context).height, + bottom: 0.25 * MediaQuery.sizeOf(context).height, + ), + listController: listController, + controller: scrollController, + itemCount: lyrics.lines.length, + itemBuilder: (context, index) { + final line = lyrics.lines[index]; + final isActive = index == currentIndex; + + return InkWell( + onTap: () { + if (line.timeMs != null) { + player.seek(Duration(milliseconds: line.timeMs!)); + } + }, + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 8, + horizontal: 16, + ), + child: AnimatedDefaultTextStyle( + duration: const Duration(milliseconds: 200), + style: Theme.of(context).textTheme.bodyLarge!.copyWith( + fontSize: isActive ? 20 : 16, + fontWeight: isActive ? FontWeight.bold : FontWeight.normal, + color: isActive + ? Theme.of(context).colorScheme.primary + : Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.7), + ), + textAlign: TextAlign.center, + child: Text(line.text, textAlign: TextAlign.center), + ), + ), + ); + }, + ); + }, ); } } diff --git a/lib/ui/widgets/mini_player.dart b/lib/ui/widgets/mini_player.dart index a39a93c..1dbe07a 100644 --- a/lib/ui/widgets/mini_player.dart +++ b/lib/ui/widgets/mini_player.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:gap/gap.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:media_kit/media_kit.dart'; @@ -36,7 +37,7 @@ class MiniPlayer extends HookConsumerWidget { final metadataAsync = ref.watch(trackMetadataProvider(filePath)); Widget content = Container( - height: 80, // Increased height for slider + height: 72, width: double.infinity, decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceContainerHighest, @@ -82,8 +83,10 @@ class MiniPlayer extends HookConsumerWidget { thumbShape: const RoundSliderThumbShape( enabledThumbRadius: 6, ), + trackShape: const RectangularSliderTrackShape(), ), child: Slider( + padding: EdgeInsets.zero, value: currentValue, min: 0, max: max > 0 ? max : 1.0, @@ -106,25 +109,23 @@ class MiniPlayer extends HookConsumerWidget { child: Row( children: [ // Cover Art (Small) - Padding( - padding: const EdgeInsets.all(8.0), - child: AspectRatio( - aspectRatio: 1, - child: metadataAsync.when( - data: (meta) => meta.artBytes != null - ? Image.memory(meta.artBytes!, fit: BoxFit.cover) - : Container( - color: Colors.grey[800], - child: const Icon( - Icons.music_note, - color: Colors.white54, - ), + AspectRatio( + aspectRatio: 1, + child: metadataAsync.when( + data: (meta) => meta.artBytes != null + ? Image.memory(meta.artBytes!, fit: BoxFit.cover) + : Container( + color: Colors.grey[800], + child: const Icon( + Icons.music_note, + color: Colors.white54, ), - loading: () => Container(color: Colors.grey[800]), - error: (_, __) => Container(color: Colors.grey[800]), - ), + ), + loading: () => Container(color: Colors.grey[800]), + error: (_, _) => Container(color: Colors.grey[800]), ), ), + const Gap(8), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), @@ -142,7 +143,7 @@ class MiniPlayer extends HookConsumerWidget { overflow: TextOverflow.ellipsis, ), loading: () => const Text('Loading...'), - error: (_, __) => + error: (_, _) => Text(Uri.parse(media.uri).pathSegments.last), ), metadataAsync.when( @@ -153,7 +154,7 @@ class MiniPlayer extends HookConsumerWidget { overflow: TextOverflow.ellipsis, ), loading: () => const SizedBox.shrink(), - error: (_, __) => const SizedBox.shrink(), + error: (_, _) => const SizedBox.shrink(), ), ], ), @@ -163,13 +164,31 @@ class MiniPlayer extends HookConsumerWidget { stream: player.stream.playing, builder: (context, snapshot) { final playing = snapshot.data ?? false; - return IconButton( - icon: Icon(playing ? Icons.pause : Icons.play_arrow), - onPressed: playing ? player.pause : player.play, + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: IconButton.filled( + color: Theme.of( + context, + ).colorScheme.primaryContainer, + icon: AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: + (Widget child, Animation animation) { + return ScaleTransition( + scale: animation, + child: child, + ); + }, + child: Icon( + playing ? Icons.pause : Icons.play_arrow, + key: ValueKey(playing), + ), + ), + onPressed: playing ? player.pause : player.play, + ), ); }, ), - const SizedBox(width: 8), ], ), ), diff --git a/pubspec.lock b/pubspec.lock index 00698e5..1dc46cc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -504,6 +504,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.2" + lint: + dependency: transitive + description: + name: lint + sha256: "4a539aa34ec5721a2c7574ae2ca0336738ea4adc2a34887d54b7596310b33c85" + url: "https://pub.dev" + source: hosted + version: "1.10.0" lints: dependency: transitive description: @@ -925,6 +933,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + styled_widget: + dependency: "direct main" + description: + name: styled_widget + sha256: "4d439802919b6ccf10d1488798656da8804633b03012682dd1c8ca70a084aa84" + url: "https://pub.dev" + source: hosted + version: "0.4.1" + super_sliver_list: + dependency: "direct main" + description: + name: super_sliver_list + sha256: b1e1e64d08ce40e459b9bb5d9f8e361617c26b8c9f3bb967760b0f436b6e3f56 + url: "https://pub.dev" + source: hosted + version: "0.4.1" synchronized: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 061aa42..1fccec5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -48,6 +48,8 @@ dependencies: flutter_media_metadata: ^1.0.0+1 animations: ^2.1.1 gap: ^3.0.1 + styled_widget: ^0.4.1 + super_sliver_list: ^0.4.1 dev_dependencies: flutter_test: