Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix iOS share, lock screen controls, settings layout, and spurious completion guard

Nathan Poulson90547755c618
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 3cba8903..0c72f12f 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -771,7 +771,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
title: Row(children: [
- const Text('Merge libraries'),
+ const Flexible(child: Text('Merge libraries')),
_infoIcon('Merge Libraries', 'When enabled, the Absorbing screen shows all your in-progress books and podcasts from every library in a single view. When disabled, only items from the library you currently have selected are shown.'),
]),
subtitle: Text(
@@ -827,6 +827,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
@@ -848,6 +849,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text('Books', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
@@ -865,6 +867,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text('Podcasts', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
const SizedBox(height: 4),
SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 'off', icon: Icon(Icons.stop_rounded), label: Text('Off')),
ButtonSegment(value: 'manual', icon: Icon(Icons.queue_music_rounded), label: Text('Manual')),
@@ -1143,6 +1146,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
child: SizedBox(
width: double.infinity,
child: SegmentedButton<String>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 'off', label: Text('Off')),
ButtonSegment(value: 'addTime', label: Text('Add Time')),
@@ -1343,7 +1347,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
title: Row(children: [
- const Text('Auto download on Wi-Fi'),
+ const Flexible(child: Text('Auto download on Wi-Fi')),
_infoIcon('Auto Download on Wi-Fi', 'When you start streaming a book over Wi-Fi, it will automatically begin downloading the full book in the background. This way you\'ll have it available offline without having to manually start the download.'),
]),
subtitle: Text(
@@ -1367,6 +1371,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
Text('Concurrent downloads', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 1, label: Text('1')),
ButtonSegment(value: 2, label: Text('2')),
@@ -1403,6 +1408,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
]),
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 2, label: Text('2')),
ButtonSegment(value: 3, label: Text('3')),
@@ -1421,7 +1427,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
SwitchListTile(
title: Row(children: [
- const Text('Delete absorbed downloads'),
+ const Flexible(child: Text('Delete absorbed downloads')),
_infoIcon('Delete Absorbed Downloads', 'When enabled, downloaded books or episodes are automatically deleted from your device after you finish listening to them. This helps free up storage space as you work through your library.'),
]),
subtitle: Text(
@@ -1489,6 +1495,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
const SizedBox(height: 8),
SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 0, label: Text('Off')),
ButtonSegment(value: 128, label: Text('128 MB')),
@@ -1717,8 +1724,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right_rounded),
onTap: () async {
try {
+ final box = context.findRenderObject() as RenderBox?;
+ final origin = box != null
+ ? box.localToGlobal(Offset.zero) & box.size
+ : null;
await LogService().shareLogs(
serverVersion: auth.serverVersion,
+ sharePositionOrigin: origin,
);
} catch (e) {
if (mounted) {
@@ -1758,7 +1770,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
children: [
SwitchListTile(
title: Row(children: [
- const Text('Local server'),
+ const Flexible(child: Text('Local server')),
_infoIcon('Local Server', 'If you run your Audiobookshelf server at home, you can set a local/LAN URL here. Absorb will automatically switch to the faster local connection when it detects you\'re on your home network, and fall back to your remote URL when you\'re away.'),
]),
subtitle: Text(
@@ -1820,7 +1832,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
title: Row(children: [
- const Text('Disable audio focus'),
+ const Flexible(child: Text('Disable audio focus')),
_infoIcon('Audio Focus', 'By default, Android gives audio "focus" to one app at a time - when Absorb plays, other audio (music, videos) will pause. Disabling audio focus lets Absorb play alongside other apps. Phone calls will still pause playback regardless of this setting.'),
]),
subtitle: Text(
@@ -1855,7 +1867,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
title: Row(children: [
- const Text('Trust all certificates'),
+ const Flexible(child: Text('Trust all certificates')),
_infoIcon('Self-signed Certificates',
'Enable this if your Audiobookshelf server uses a self-signed certificate or a custom root CA. '
'When enabled, Absorb will skip TLS certificate verification for all connections. '
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 6c22af7a..c477fd55 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -563,18 +563,18 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> play() async {
- debugPrint('[Handler] play() called — routing to service (state=${_player.processingState.name})');
+ debugPrint('[Handler] play() called - routing to service (state=${_player.processingState.name})');
if (_service != null) {
await _service!.play();
} else {
- debugPrint('[Handler] play() — no service ref, using player directly');
+ debugPrint('[Handler] play() - no service ref, using player directly');
await _player.play();
}
}
@override
Future<void> pause() async {
- debugPrint('[Handler] pause() called — routing to service');
+ debugPrint('[Handler] pause() called - routing to service');
if (_service != null) {
await _service!.pause();
} else {
@@ -586,15 +586,10 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
Future<void> seek(Duration position) async {
debugPrint('[Handler] seek(${position.inSeconds}s)');
if (_service != null) {
- // The MediaSession reports speed-adjusted position/duration (divided
- // by speed), so incoming seek positions are also speed-adjusted.
- // Multiply by speed to get the real content position.
final speed = _player.speed;
final realPos = speed > 0 && speed != 1.0
? Duration(milliseconds: (position.inMilliseconds * speed).round())
: position;
- // In chapter mode, the notification sends chapter-relative position —
- // convert back to absolute book position.
final absPos = _service!.notifChapterMode
? realPos + Duration(seconds: _service!.currentChapterStart.round())
: realPos;
@@ -614,8 +609,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
/// Called when the user swipes the app away from recents.
@override
Future<void> onTaskRemoved() async {
- debugPrint('[Handler] onTaskRemoved — app swiped away');
- // Stop playback and sync via the service if available
+ debugPrint('[Handler] onTaskRemoved - app swiped away');
+ // Don't stop cast playback when app is swiped away
+ if (ChromecastService().isCasting) return;
if (_service != null) {
await _service!.pause();
await _service!.stop();
@@ -627,7 +623,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> fastForward() async {
- debugPrint('[Handler] fastForward() — seeking forward');
+ debugPrint('[Handler] fastForward() - seeking forward');
if (_service != null) {
final skipAmount = await PlayerSettings.getForwardSkip();
await _service!.skipForward(skipAmount);
@@ -639,7 +635,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
@override
Future<void> rewind() async {
- debugPrint('[Handler] rewind() — seeking back');
+ debugPrint('[Handler] rewind() - seeking back');
if (_service != null) {
final skipAmount = await PlayerSettings.getBackSkip();
await _service!.skipBackward(skipAmount);
@@ -985,6 +981,7 @@ class AudioPlayerService extends ChangeNotifier {
}
static AudioPlayerHandler? _handler;
+ static AudioPlayerHandler? get handler => _handler;
static Completer<void> _initCompleter = Completer<void>();
AudioPlayer? get _player => _handler?.player;
@@ -1770,9 +1767,23 @@ class AudioPlayerService extends ChangeNotifier {
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
debugPrint('[Player] Starting local playback at ${speed}x');
+ // Re-activate audio session before play so the first playback event
+ // reaches the audio_service iOS plugin with an active session.
+ // Without this, iOS ignores the MPNowPlayingInfoCenter update and
+ // lock screen / Control Center / AirPod controls never appear.
+ if (!_audioFocusDisabled) {
+ try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ }
_player!.play();
notifyListeners();
_setupSync();
+ // Ensure iOS lock screen / Control Center controls appear by pushing
+ // a fresh playback state after a short delay. The initial event from
+ // playbackEventStream can arrive before AVPlayer is fully "playing",
+ // causing the audio_service iOS plugin to skip command center activation.
+ Future.delayed(const Duration(milliseconds: 500), () {
+ _handler?.refreshPlaybackState();
+ });
// Fresh session — reset auto sleep dismiss and check
final sleepTimer = SleepTimerService();
sleepTimer.resetDismiss();
@@ -1907,9 +1918,17 @@ class AudioPlayerService extends ChangeNotifier {
final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
await _player!.setSpeed(speed);
debugPrint('[Player] Starting stream playback at ${speed}x');
+ // Re-activate audio session before play (see local playback comment above)
+ if (!_audioFocusDisabled) {
+ try { (await AudioSession.instance).setActive(true); } catch (_) {}
+ }
_player!.play();
notifyListeners();
_setupSync();
+ // Ensure iOS lock screen / Control Center controls appear (see local playback comment)
+ Future.delayed(const Duration(milliseconds: 500), () {
+ _handler?.refreshPlaybackState();
+ });
// Fresh session — reset auto sleep dismiss and check
final sleepTimer = SleepTimerService();
sleepTimer.resetDismiss();
@@ -2271,6 +2290,28 @@ class AudioPlayerService extends ChangeNotifier {
if (_isCompletingBook) return; // prevent re-entry
_isCompletingBook = true;
+ // Sanity check: if we're not near the end of the book, this is a spurious
+ // completion signal (iOS AVPlayer can fire completed on audio interruptions,
+ // buffer errors, etc.). Save current position and stop - don't mark finished
+ // or advance the queue.
+ if (_totalDuration > 0 && _lastKnownPositionSec > 0 &&
+ _lastKnownPositionSec < _totalDuration * 0.9 &&
+ _lastKnownPositionSec < _totalDuration - 30) {
+ debugPrint('[Player] Spurious completion at ${_lastKnownPositionSec.toStringAsFixed(1)}s / ${_totalDuration.toStringAsFixed(1)}s — saving position instead of marking finished');
+ _logEvent(PlaybackEventType.pause, detail: 'Spurious completion blocked');
+ _syncSub?.cancel();
+ _syncSub = null;
+ _completionSub?.cancel();
+ _completionSub = null;
+ _bgSaveTimer?.cancel();
+ _bgSaveTimer = null;
+ await _player?.stop();
+ await _saveProgressLocal(Duration(milliseconds: (_lastKnownPositionSec * 1000).round()));
+ _isCompletingBook = false;
+ notifyListeners();
+ return;
+ }
+
debugPrint('[Player] Book complete: $_currentTitle');
_logEvent(PlaybackEventType.pause, detail: 'Book finished');
@@ -2629,8 +2670,9 @@ class AudioPlayerService extends ChangeNotifier {
if (SleepTimerService().isActive) {
SleepTimerService().cancel();
}
- // Release audio focus so other apps can use it
- if (!_audioFocusDisabled) {
+ // Release audio focus so other apps can use it - but not during casting,
+ // because deactivating the session can interfere with cast playback.
+ if (!_audioFocusDisabled && !ChromecastService().isCasting) {
try { (await AudioSession.instance).setActive(false); } catch (_) {}
}
}
diff --git a/lib/services/log_service.dart b/lib/services/log_service.dart
index 0a767b4b..7e0a588e 100644
--- a/lib/services/log_service.dart
+++ b/lib/services/log_service.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
@@ -126,7 +127,9 @@ class LogService {
}
/// Share log file as attachment via share sheet with device info.
- Future<void> shareLogs({String? serverVersion}) async {
+ ///
+ /// [sharePositionOrigin] is required on iPad for the share popover anchor.
+ Future<void> shareLogs({String? serverVersion, Rect? sharePositionOrigin}) async {
final info = _deviceInfo(serverVersion: serverVersion);
final hasFile =
@@ -137,11 +140,13 @@ class LogService {
[XFile(_logFile!.path)],
subject: 'Absorb Log Report',
text: 'Send to: $supportEmail\n\n$info',
+ sharePositionOrigin: sharePositionOrigin,
);
} else {
await Share.share(
'Send to: $supportEmail\n\n$info\n(No log file found — is logging enabled?)',
subject: 'Absorb Log Report',
+ sharePositionOrigin: sharePositionOrigin,
);
}
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 9b3539ca..28b101d5 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -1240,7 +1240,11 @@ class _FullCoverViewerState extends State<_FullCoverViewer> {
final file = File('${dir.path}/$safeTitle$ext');
await file.writeAsBytes(response.bodyBytes);
if (!mounted) return;
- await Share.shareXFiles([XFile(file.path)]);
+ final box = context.findRenderObject() as RenderBox?;
+ final origin = box != null
+ ? box.localToGlobal(Offset.zero) & box.size
+ : null;
+ await Share.shareXFiles([XFile(file.path)], sharePositionOrigin: origin);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
diff --git a/lib/widgets/notes_sheet.dart b/lib/widgets/notes_sheet.dart
index 60206eb7..26b77da8 100644
--- a/lib/widgets/notes_sheet.dart
+++ b/lib/widgets/notes_sheet.dart
@@ -157,7 +157,11 @@ class _NotesSheetState extends State<NotesSheet> {
final safe = widget.itemTitle.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
final file = File('${dir.path}/${safe}_notes.$format');
await file.writeAsString(buffer.toString());
- await Share.shareXFiles([XFile(file.path)]);
+ final box = context.findRenderObject() as RenderBox?;
+ final origin = box != null
+ ? box.localToGlobal(Offset.zero) & box.size
+ : null;
+ await Share.shareXFiles([XFile(file.path)], sharePositionOrigin: origin);
}
Future<_NoteEditResult?> _showEditor(BuildContext context, {String title = '', String body = ''}) {
diff --git a/lib/widgets/sleep_timer_sheet.dart b/lib/widgets/sleep_timer_sheet.dart
index 9b92cca9..4247d85c 100644
--- a/lib/widgets/sleep_timer_sheet.dart
+++ b/lib/widgets/sleep_timer_sheet.dart
@@ -331,6 +331,7 @@ class _SleepTimerSheetState extends State<SleepTimerSheet> {
SizedBox(
width: double.infinity,
child: SegmentedButton<String>(
+ showSelectedIcon: false,
segments: const [
ButtonSegment(value: 'off', label: Text('Off')),
ButtonSegment(value: 'addTime', label: Text('Add Time')),