Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Redesign the home screen widget's buttons to be pill-shaped and calmer, match sizing between the widget variants, and fix the play button sometimes doing nothing on a cold start

Barnabasf72fb1cc0165
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
index 403b9a07..4330c41a 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt
@@ -49,18 +49,29 @@ class NowPlayingWidget : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_TOGGLE_PLAYBACK) {
- // Optimistic UI: flip the icon immediately, then send the real media button.
+ // Optimistic UI for pause only. Never mark the widget playing
+ // before the audio service confirms there is actually audio.
val widgetData = HomeWidgetPlugin.getData(context)
- val wasPlaying = widgetData.getBoolean("widget_is_playing", false)
- widgetData.edit().putBoolean("widget_is_playing", !wasPlaying).apply()
+ widgetData.edit().putBoolean("widget_is_playing", false).apply()
- // Re-render both widget types so they stay in sync.
+ // Re-render every now-playing widget size so they stay in sync.
+ // A render failure here must not stop the broadcast below, or the
+ // tap silently does nothing instead of toggling playback.
val mgr = AppWidgetManager.getInstance(context)
for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidget::class.java))) {
- updateWidget(context, mgr, id)
+ try { updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidget", "toggle update failed", e)
+ }
}
for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetCompact::class.java))) {
- NowPlayingWidgetCompact.updateWidget(context, mgr, id)
+ try { NowPlayingWidgetCompact.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidget", "toggle update failed", e)
+ }
+ }
+ for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetTiny::class.java))) {
+ try { NowPlayingWidgetTiny.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidget", "toggle update failed", e)
+ }
}
// Forward to MediaButtonReceiver for the actual playback toggle.
@@ -130,8 +141,9 @@ class NowPlayingWidget : AppWidgetProvider() {
views.setViewPadding(R.id.widget_outer, 0, 0, 0, 0)
}
- val hasBook = widgetData.getBoolean("widget_has_book", false)
val title = widgetData.getString("widget_title", null)
+ val hasBook = widgetData.getBoolean("widget_has_book", false)
+ val canControl = (hasBook || !title.isNullOrEmpty()) && WidgetClock.isEngineAlive()
val author = widgetData.getString("widget_author", null)
val chapter = widgetData.getString("widget_chapter", null)
val isPlaying = widgetData.getBoolean("widget_is_playing", false)
@@ -232,9 +244,9 @@ class NowPlayingWidget : AppWidgetProvider() {
R.id.widget_skip_back,
mediaButtonPendingIntent(context, KeyEvent.KEYCODE_MEDIA_REWIND, 2)
)
- // Active session: custom broadcast flips the icon instantly then forwards
- // to MediaSession. No session: launch the app for cold resume.
- val playPauseIntent = if (hasBook) {
+ // Use MediaSession whenever the widget has a remembered item, but
+ // never mark it playing until Dart confirms audio actually started.
+ val playPauseIntent = if (canControl) {
val toggleIntent = Intent(context, NowPlayingWidget::class.java).apply {
action = ACTION_TOGGLE_PLAYBACK
}
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
index 1c1392b0..c51cef59 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt
@@ -50,15 +50,25 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_TOGGLE_PLAYBACK) {
val widgetData = HomeWidgetPlugin.getData(context)
- val wasPlaying = widgetData.getBoolean("widget_is_playing", false)
- widgetData.edit().putBoolean("widget_is_playing", !wasPlaying).apply()
+ widgetData.edit().putBoolean("widget_is_playing", false).apply()
+ // A render failure here must not stop the broadcast below, or the
+ // tap silently does nothing instead of toggling playback.
val mgr = AppWidgetManager.getInstance(context)
for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetCompact::class.java))) {
- updateWidget(context, mgr, id)
+ try { updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetCompact", "toggle update failed", e)
+ }
}
for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidget::class.java))) {
- NowPlayingWidget.updateWidget(context, mgr, id)
+ try { NowPlayingWidget.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetCompact", "toggle update failed", e)
+ }
+ }
+ for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetTiny::class.java))) {
+ try { NowPlayingWidgetTiny.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetCompact", "toggle update failed", e)
+ }
}
val mediaIntent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {
@@ -126,8 +136,9 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {
views.setViewPadding(R.id.widget_outer, 0, 0, 0, 0)
}
- val hasBook = widgetData.getBoolean("widget_has_book", false)
val title = widgetData.getString("widget_title", null)
+ val hasBook = widgetData.getBoolean("widget_has_book", false)
+ val canControl = (hasBook || !title.isNullOrEmpty()) && WidgetClock.isEngineAlive()
val author = widgetData.getString("widget_author", null)
val isPlaying = widgetData.getBoolean("widget_is_playing", false)
val coverPath = widgetData.getString("widget_cover_path", null)
@@ -221,7 +232,7 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {
R.id.widget_skip_back,
mediaButtonPendingIntent(context, KeyEvent.KEYCODE_MEDIA_REWIND, 12)
)
- val playPauseIntent = if (hasBook) {
+ val playPauseIntent = if (canControl) {
val toggleIntent = Intent(context, NowPlayingWidgetCompact::class.java).apply {
action = ACTION_TOGGLE_PLAYBACK
}
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt
index 5fc22864..efed4068 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt
@@ -13,7 +13,9 @@ import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
+import android.os.Build
import android.os.Bundle
+import android.util.TypedValue
import android.view.KeyEvent
import android.view.View
import android.net.Uri
@@ -68,14 +70,28 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_TOGGLE_PLAYBACK) {
- // Optimistic UI: flip the icon immediately, then send the real media button.
+ // Optimistic UI for pause only. Never mark the widget playing
+ // before the audio service confirms there is actually audio.
val widgetData = HomeWidgetPlugin.getData(context)
- val wasPlaying = widgetData.getBoolean("widget_is_playing", false)
- widgetData.edit().putBoolean("widget_is_playing", !wasPlaying).apply()
+ widgetData.edit().putBoolean("widget_is_playing", false).apply()
+ // A render failure here must not stop the broadcast below, or the
+ // tap silently does nothing instead of toggling playback.
val mgr = AppWidgetManager.getInstance(context)
for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetTiny::class.java))) {
- updateWidget(context, mgr, id)
+ try { updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetTiny", "toggle update failed", e)
+ }
+ }
+ for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidget::class.java))) {
+ try { NowPlayingWidget.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetTiny", "toggle update failed", e)
+ }
+ }
+ for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetCompact::class.java))) {
+ try { NowPlayingWidgetCompact.updateWidget(context, mgr, id) } catch (e: Exception) {
+ android.util.Log.e("NowPlayingWidgetTiny", "toggle update failed", e)
+ }
}
val mediaIntent = Intent(Intent.ACTION_MEDIA_BUTTON).apply {
@@ -170,8 +186,16 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
val widgetData = HomeWidgetPlugin.getData(context)
val views = RemoteViews(context.packageName, R.layout.now_playing_widget_tiny)
+ // OnePlus launchers add their own generous widget padding,
+ // so zero ours out to avoid double-padding.
+ if (Build.MANUFACTURER.equals("OnePlus", ignoreCase = true)) {
+ views.setViewPadding(R.id.widget_outer, 0, 0, 0, 0)
+ }
+
val hasBook = widgetData.getBoolean("widget_has_book", false)
val isPlaying = widgetData.getBoolean("widget_is_playing", false)
+ val title = widgetData.getString("widget_title", null)
+ val canControl = (hasBook || !title.isNullOrEmpty()) && WidgetClock.isEngineAlive()
val coverPath = widgetData.getString("widget_cover_path", null)
// Current widget size. Portrait reports width via MIN_WIDTH and
@@ -183,7 +207,7 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
val targetPx = (maxOf(widthDp, heightDp, 80) * density).toInt()
// Wide enough (2+ cells) for the transport row, and a session to control.
- val showPanel = hasBook && WidgetClock.cellsFor(widthDp) >= 2
+ val showPanel = canControl && WidgetClock.cellsFor(widthDp) >= 2
// Reveal the info rows by how many dp of height the launcher actually
// gives the widget, not by cell count: launcher row heights vary too
// much (a 1-row widget reports ~102dp on One UI but ~121dp on Pixel),
@@ -214,9 +238,21 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
// When it's only tall enough for the button row, keep the panel
// tight; give it breathing room once text/progress appear.
- val padTop = ((if (showInfo) 22 else 8) * density).toInt()
- val padBottom = ((if (showInfo) 12 else 8) * density).toInt()
- views.setViewPadding(R.id.widget_panel, 0, padTop, 0, padBottom)
+ val pad = ((if (showInfo) 22 else 4) * density).toInt()
+ views.setViewPadding(R.id.widget_panel, 0, pad, 0, pad)
+
+ // The short tier now also carries a title line (see below), so
+ // the transport row no longer fits at its full-height size
+ // without getting clipped by the panel's available height -
+ // shrink it to the same 40dp the compact widget uses, which is
+ // also exactly what the pill drawable's corner radius is tuned
+ // for.
+ if (!showInfo && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ views.setViewLayoutHeight(R.id.widget_pp, 40f, TypedValue.COMPLEX_UNIT_DIP)
+ views.setViewLayoutWidth(R.id.widget_pp, 56f, TypedValue.COMPLEX_UNIT_DIP)
+ views.setViewLayoutHeight(R.id.widget_skip_back, 40f, TypedValue.COMPLEX_UNIT_DIP)
+ views.setViewLayoutHeight(R.id.widget_skip_forward, 40f, TypedValue.COMPLEX_UNIT_DIP)
+ }
// Transport + progress are in every panel size, including the
// short buttons-only one (cover + squiggle + controls, like a
@@ -246,12 +282,14 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
views.setViewVisibility(R.id.widget_time_remaining, View.GONE)
}
- // Title / author only once there's vertical room for them.
+ // Title shows as soon as the panel does, even at a 1-row
+ // height (same as the compact widget) - just smaller and
+ // alone. Author needs the extra vertical room from showInfo.
+ views.setTextViewText(R.id.widget_title, if (title.isNullOrEmpty()) "Absorb" else title)
+ views.setViewVisibility(R.id.widget_title, View.VISIBLE)
if (showInfo) {
- val title = widgetData.getString("widget_title", null)
+ views.setTextViewTextSize(R.id.widget_title, TypedValue.COMPLEX_UNIT_SP, 15f)
val author = widgetData.getString("widget_author", null)
- views.setTextViewText(R.id.widget_title, if (title.isNullOrEmpty()) "Absorb" else title)
- views.setViewVisibility(R.id.widget_title, View.VISIBLE)
if (author.isNullOrEmpty()) {
views.setViewVisibility(R.id.widget_author, View.GONE)
} else {
@@ -259,7 +297,7 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
views.setViewVisibility(R.id.widget_author, View.VISIBLE)
}
} else {
- views.setViewVisibility(R.id.widget_title, View.GONE)
+ views.setTextViewTextSize(R.id.widget_title, TypedValue.COMPLEX_UNIT_SP, 12f)
views.setViewVisibility(R.id.widget_author, View.GONE)
}
@@ -286,14 +324,14 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {
} else {
// 1x1: centered indicator, whole tile toggles play/pause.
views.setViewVisibility(R.id.widget_panel, View.GONE)
- if (hasBook) {
+ if (canControl) {
views.setViewVisibility(R.id.widget_play_pause, View.VISIBLE)
views.setImageViewResource(R.id.widget_play_pause, playPauseIcon)
} else {
views.setViewVisibility(R.id.widget_play_pause, View.GONE)
}
- val tapIntent = if (hasBook) {
+ val tapIntent = if (canControl) {
togglePendingIntent(context)
} else {
HomeWidgetLaunchIntent.getActivity(
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt
index e74ed16b..f5439f84 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt
@@ -12,7 +12,9 @@ import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.widget.RemoteViews
+import com.ryanheise.audioservice.AudioServicePlugin
import es.antonborri.home_widget.HomeWidgetPlugin
+import io.flutter.embedding.engine.FlutterEngineCache
import org.json.JSONArray
// Shared live-clock machinery for the now-playing widgets: the squiggle
@@ -27,6 +29,16 @@ internal object WidgetClock {
// Android's own cell-size formula: 70dp per cell, 30dp inter-cell gap.
fun cellsFor(dp: Int): Int = if (dp <= 0) 1 else (dp + 30) / 70
+ // widget_has_book / widget_title are stashed prefs that outlive the app
+ // process, so they still read true after a swipe-close. Routing a tap
+ // through the MediaSession broadcast in that state is a dead end -
+ // AudioService.onCreate only adopts a cached engine, never creates one,
+ // so a truly dead process can't pick the button press up at all. Gate on
+ // whether an engine is actually cached to tell "session still alive" from
+ // "just stale prefs" and fall back to a normal cold-start app launch.
+ fun isEngineAlive(): Boolean =
+ FlutterEngineCache.getInstance().get(AudioServicePlugin.getFlutterEngineId()) != null
+
// Width gate for the tiny widget's clocks beside the progress bar.
// Measured: 2 real cells report 171dp (Pixel) / 201dp (One UI), 3 cells
// 266dp / 315dp - so 230 means "at least 3 cells wide" on both.
@@ -135,8 +147,8 @@ internal object WidgetClock {
if (playing) {
// Capped so the wave fits thinner bars (the compact strip).
- val amplitude = minOf(3f * density, (h - stroke * 2) / 2f).coerceAtLeast(1f)
- val wavelength = 24f * density
+ val amplitude = minOf(1.8f * density, (h - stroke * 2) / 2f).coerceAtLeast(0.75f)
+ val wavelength = 36f * density
val path = Path()
path.moveTo(inset, centerY)
var x = inset
@@ -196,7 +208,9 @@ internal object WidgetClock {
fun syncTicker(context: Context) {
val app = context.applicationContext
val widgetData = HomeWidgetPlugin.getData(app)
- var shouldTick = widgetData.getBoolean("widget_has_book", false) &&
+ val hasPlayableItem = widgetData.getBoolean("widget_has_book", false) ||
+ !widgetData.getString("widget_title", null).isNullOrEmpty()
+ var shouldTick = hasPlayableItem &&
widgetData.getBoolean("widget_is_playing", false)
if (shouldTick) {
val mgr = AppWidgetManager.getInstance(app)
diff --git a/android/app/src/main/res/drawable/widget_play_btn_bg.xml b/android/app/src/main/res/drawable/widget_play_btn_bg.xml
index 9f3c01df..a94ebf01 100644
--- a/android/app/src/main/res/drawable/widget_play_btn_bg.xml
+++ b/android/app/src/main/res/drawable/widget_play_btn_bg.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="oval">
+ android:shape="rectangle">
<solid android:color="#FFFFFF" />
+ <corners android:radius="20dp" />
</shape>
diff --git a/android/app/src/main/res/drawable/widget_play_button_bg.xml b/android/app/src/main/res/drawable/widget_play_button_bg.xml
index 9f3c01df..2076ca78 100644
--- a/android/app/src/main/res/drawable/widget_play_button_bg.xml
+++ b/android/app/src/main/res/drawable/widget_play_button_bg.xml
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="oval">
+ android:shape="rectangle">
<solid android:color="#FFFFFF" />
+ <corners android:radius="24dp" />
</shape>
diff --git a/android/app/src/main/res/layout/now_playing_widget.xml b/android/app/src/main/res/layout/now_playing_widget.xml
index 771f4837..2f2b8b8b 100644
--- a/android/app/src/main/res/layout/now_playing_widget.xml
+++ b/android/app/src/main/res/layout/now_playing_widget.xml
@@ -41,7 +41,7 @@
android:layout_alignTop="@id/widget_cover"
android:paddingStart="12dp"
android:paddingEnd="12dp"
- android:paddingTop="4dp"
+ android:paddingTop="12dp"
android:text="Absorb"
android:textColor="#FFFFFF"
android:textSize="15sp"
@@ -87,6 +87,7 @@
android:layout_height="wrap_content"
android:layout_toEndOf="@id/widget_cover"
android:layout_alignBottom="@id/widget_cover"
+ android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:paddingStart="4dp"
@@ -123,7 +124,7 @@
<!-- Play/pause: white circle with dark icon -->
<ImageButton
android:id="@+id/widget_play_pause"
- android:layout_width="40dp"
+ android:layout_width="56dp"
android:layout_height="40dp"
android:padding="8dp"
android:src="@drawable/ic_widget_play_dark"
diff --git a/android/app/src/main/res/layout/now_playing_widget_compact.xml b/android/app/src/main/res/layout/now_playing_widget_compact.xml
index 6873f943..8e17acae 100644
--- a/android/app/src/main/res/layout/now_playing_widget_compact.xml
+++ b/android/app/src/main/res/layout/now_playing_widget_compact.xml
@@ -132,7 +132,7 @@
<ImageButton
android:id="@+id/widget_play_pause"
- android:layout_width="40dp"
+ android:layout_width="56dp"
android:layout_height="40dp"
android:padding="8dp"
android:src="@drawable/ic_widget_play_dark"
diff --git a/android/app/src/main/res/layout/now_playing_widget_tiny.xml b/android/app/src/main/res/layout/now_playing_widget_tiny.xml
index 1c98d8c1..6fc3189d 100644
--- a/android/app/src/main/res/layout/now_playing_widget_tiny.xml
+++ b/android/app/src/main/res/layout/now_playing_widget_tiny.xml
@@ -4,6 +4,15 @@
player panel (title / author / chapter / progress / transport) fades in
over the bottom of the cover; rows appear as there's room for them. -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/widget_outer"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:paddingStart="5dp"
+ android:paddingEnd="5dp"
+ android:paddingTop="5dp"
+ android:paddingBottom="5dp">
+
+<FrameLayout
android:id="@+id/widget_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
@@ -21,7 +30,7 @@
<!-- Tiny-size indicator: reflects state; the whole tile is the tap target -->
<ImageView
android:id="@+id/widget_play_pause"
- android:layout_width="40dp"
+ android:layout_width="48dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:padding="9dp"
@@ -170,7 +179,7 @@
<!-- Play/pause: white circle with dark icon -->
<ImageButton
android:id="@+id/widget_pp"
- android:layout_width="52dp"
+ android:layout_width="72dp"
android:layout_height="52dp"
android:padding="12dp"
android:src="@drawable/ic_widget_play_dark"
@@ -209,3 +218,4 @@
</LinearLayout>
</FrameLayout>
+</FrameLayout>
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 5b36ce88..62559c3c 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -65,10 +65,12 @@ class HomeWidgetService {
await HomeWidget.setAppGroupId(_appGroupId);
debugPrint('[WidgetDebug] setAppGroupId=$_appGroupId');
try {
- _groupContainerPath =
- await _widgetChannel.invokeMethod<String>('getGroupContainerPath');
+ _groupContainerPath = await _widgetChannel.invokeMethod<String>(
+ 'getGroupContainerPath',
+ );
debugPrint(
- '[WidgetDebug] groupContainerPath=${_groupContainerPath ?? "<null>"}');
+ '[WidgetDebug] groupContainerPath=${_groupContainerPath ?? "<null>"}',
+ );
} catch (e) {
debugPrint('[WidgetDebug] Failed to get group container path: $e');
}
@@ -157,13 +159,16 @@ class HomeWidgetService {
///
/// iOS only - Android doesn't have the native core path.
Future<double?> getNativeNowPlayingPosition(
- String itemId, String? episodeId) async {
+ String itemId,
+ String? episodeId,
+ ) async {
if (!Platform.isIOS) return null;
try {
final stashedItem = await HomeWidget.getWidgetData<String>('np_item_id');
if (stashedItem != itemId) return null;
- final stashedEpisode =
- await HomeWidget.getWidgetData<String>('np_episode_id');
+ final stashedEpisode = await HomeWidget.getWidgetData<String>(
+ 'np_episode_id',
+ );
if (stashedEpisode != episodeId) return null;
final pos = await HomeWidget.getWidgetData<double>('np_position_s');
return pos;
@@ -202,7 +207,9 @@ class HomeWidgetService {
// any current session (the watch already knows what it picked).
final itemId = uri.queryParameters['itemId'];
final rawEpisode = uri.queryParameters['episodeId'];
- final episodeId = (rawEpisode == null || rawEpisode.isEmpty) ? null : rawEpisode;
+ final episodeId = (rawEpisode == null || rawEpisode.isEmpty)
+ ? null
+ : rawEpisode;
if (itemId != null && itemId.isNotEmpty) {
_handlePlayItem(itemId, episodeId);
}
@@ -238,7 +245,9 @@ class HomeWidgetService {
/// Always plays (no toggle path) — the watch already chose which book
/// it wants and the user expects an immediate switch.
Future<void> _handlePlayItem(String itemId, String? episodeId) async {
- debugPrint('[HomeWidget] _handlePlayItem itemId=$itemId episodeId=$episodeId');
+ debugPrint(
+ '[HomeWidget] _handlePlayItem itemId=$itemId episodeId=$episodeId',
+ );
final player = AudioPlayerService();
final prefs = await SharedPreferences.getInstance();
@@ -254,8 +263,9 @@ class HomeWidgetService {
final headersJson = prefs.getString('custom_headers');
if (headersJson != null) {
try {
- customHeaders =
- Map<String, String>.from(jsonDecode(headersJson) as Map);
+ customHeaders = Map<String, String>.from(
+ jsonDecode(headersJson) as Map,
+ );
} catch (_) {}
}
@@ -286,9 +296,9 @@ class HomeWidgetService {
if (episodeId != null) {
final episodes = (media['episodes'] as List<dynamic>?) ?? [];
final episode = episodes.cast<Map<String, dynamic>>().firstWhere(
- (e) => e['id'] == episodeId,
- orElse: () => <String, dynamic>{},
- );
+ (e) => e['id'] == episodeId,
+ orElse: () => <String, dynamic>{},
+ );
final epTitle = episode['title'] as String? ?? title;
final epDuration =
(episode['duration'] as num?)?.toDouble() ?? duration;
@@ -324,8 +334,9 @@ class HomeWidgetService {
Future<void> _handlePlayPause() async {
final player = AudioPlayerService();
debugPrint(
- '[WidgetDebug] _handlePlayPause hasBook=${player.hasBook} isPlaying=${player.isPlaying}\n'
- 'Caller:\n${StackTrace.current}');
+ '[WidgetDebug] _handlePlayPause hasBook=${player.hasBook} isPlaying=${player.isPlaying}\n'
+ 'Caller:\n${StackTrace.current}',
+ );
// When there's an active session the widget uses a MediaSession media button
// instead of launching the app, so this path is only hit for cold resume.
@@ -352,15 +363,18 @@ class HomeWidgetService {
final serverUrl = prefs.getString('server_url');
final token = prefs.getString('token');
final refreshToken = prefs.getString('refresh_token');
- debugPrint('[HomeWidget] play_pause: server=${serverUrl != null}, token=${token != null}');
+ debugPrint(
+ '[HomeWidget] play_pause: server=${serverUrl != null}, token=${token != null}',
+ );
if (serverUrl == null || token == null) return;
Map<String, String>? customHeaders;
final headersJson = prefs.getString('custom_headers');
if (headersJson != null) {
try {
- customHeaders =
- Map<String, String>.from(jsonDecode(headersJson) as Map);
+ customHeaders = Map<String, String>.from(
+ jsonDecode(headersJson) as Map,
+ );
} catch (_) {}
}
@@ -375,7 +389,9 @@ class HomeWidgetService {
final episodeId = prefs.getString('widget_episode_id');
try {
- debugPrint('[HomeWidget] play_pause: fetching item $itemId (episode=$episodeId)');
+ debugPrint(
+ '[HomeWidget] play_pause: fetching item $itemId (episode=$episodeId)',
+ );
final fullItem = await api.getLibraryItem(itemId);
if (fullItem == null) {
debugPrint('[HomeWidget] play_pause: getLibraryItem returned null');
@@ -395,9 +411,9 @@ class HomeWidgetService {
if (episodeId != null) {
final episodes = (media['episodes'] as List<dynamic>?) ?? [];
final episode = episodes.cast<Map<String, dynamic>>().firstWhere(
- (e) => e['id'] == episodeId,
- orElse: () => <String, dynamic>{},
- );
+ (e) => e['id'] == episodeId,
+ orElse: () => <String, dynamic>{},
+ );
final epTitle = episode['title'] as String? ?? title;
final epDuration =
(episode['duration'] as num?)?.toDouble() ?? duration;
@@ -466,13 +482,18 @@ class HomeWidgetService {
final hasBook = player.hasBook;
debugPrint(
- '[WidgetDebug] _updateWidgetData hasBook=$hasBook isPlaying=${player.isPlaying} title="${player.currentTitle ?? ""}" itemId=${player.currentItemId}');
+ '[WidgetDebug] _updateWidgetData hasBook=$hasBook isPlaying=${player.isPlaying} title="${player.currentTitle ?? ""}" itemId=${player.currentItemId}',
+ );
await HomeWidget.saveWidgetData<bool>('widget_has_book', hasBook);
// Push user's skip durations so the widget shows them on the buttons.
- final skipBack = await PlayerSettings.getEffectiveBackSkip(libraryId: player.currentLibraryId);
- final skipForward = await PlayerSettings.getEffectiveForwardSkip(libraryId: player.currentLibraryId);
+ final skipBack = await PlayerSettings.getEffectiveBackSkip(
+ libraryId: player.currentLibraryId,
+ );
+ final skipForward = await PlayerSettings.getEffectiveForwardSkip(
+ libraryId: player.currentLibraryId,
+ );
await HomeWidget.saveWidgetData<int>('widget_skip_back', skipBack);
await HomeWidget.saveWidgetData<int>('widget_skip_forward', skipForward);
@@ -481,12 +502,18 @@ class HomeWidgetService {
// the title and "Author · Book" beneath, same as the lock screen. The
// separate chapter line is cleared so the large widget doesn't repeat it.
await HomeWidget.saveWidgetData<String>(
- 'widget_title', player.nowPlayingTitle);
+ 'widget_title',
+ player.nowPlayingTitle,
+ );
await HomeWidget.saveWidgetData<String>(
- 'widget_author', player.nowPlayingSubtitle);
+ 'widget_author',
+ player.nowPlayingSubtitle,
+ );
await HomeWidget.saveWidgetData<String>('widget_chapter', '');
await HomeWidget.saveWidgetData<bool>(
- 'widget_is_playing', player.isPlaying);
+ 'widget_is_playing',
+ player.isPlaying,
+ );
final totalDur = player.totalDuration;
final posSec = player.position.inMilliseconds / 1000.0;
@@ -497,7 +524,10 @@ class HomeWidgetService {
final chStart = player.currentChapterStart;
final chLen = player.currentChapterEnd - chStart;
if (chLen > 0) {
- progress = (((posSec - chStart) / chLen) * 1000).round().clamp(0, 1000);
+ progress = (((posSec - chStart) / chLen) * 1000).round().clamp(
+ 0,
+ 1000,
+ );
}
} else if (totalDur > 0) {
progress = ((posSec / totalDur) * 1000).round().clamp(0, 1000);
@@ -509,15 +539,25 @@ class HomeWidgetService {
// timestamp + speed, so it can tick every second between these
// (throttled) pushes. Chapter bounds come from np_chapters_json.
await HomeWidget.saveWidgetData<int>(
- 'widget_pos_abs_ms', player.position.inMilliseconds);
+ 'widget_pos_abs_ms',
+ player.position.inMilliseconds,
+ );
+ await HomeWidget.saveWidgetData<int>(
+ 'widget_total_ms',
+ (totalDur * 1000).round(),
+ );
await HomeWidget.saveWidgetData<int>(
- 'widget_total_ms', (totalDur * 1000).round());
- await HomeWidget.saveWidgetData<int>('widget_pos_at_s',
- DateTime.now().millisecondsSinceEpoch ~/ 1000);
+ 'widget_pos_at_s',
+ DateTime.now().millisecondsSinceEpoch ~/ 1000,
+ );
await HomeWidget.saveWidgetData<int>(
- 'widget_speed_x100', (player.speed * 100).round());
+ 'widget_speed_x100',
+ (player.speed * 100).round(),
+ );
await HomeWidget.saveWidgetData<bool>(
- 'widget_chapter_mode', player.notifChapterMode);
+ 'widget_chapter_mode',
+ player.notifChapterMode,
+ );
// Persist item/episode ID so the widget can resume after app kill
final prefs = await SharedPreferences.getInstance();
@@ -586,11 +626,16 @@ class HomeWidgetService {
/// Streaming case (Phase 2) will need the server URL + auth token too;
/// for now we only stash the file paths so Phase 1.3 (downloaded books)
/// can play.
- Future<void> _stashPlaybackStateForNativeCore(AudioPlayerService player) async {
+ Future<void> _stashPlaybackStateForNativeCore(
+ AudioPlayerService player,
+ ) async {
final itemId = player.currentItemId;
if (itemId == null) return;
await HomeWidget.saveWidgetData<String>('np_item_id', itemId);
- await HomeWidget.saveWidgetData<String?>('np_episode_id', player.currentEpisodeId);
+ await HomeWidget.saveWidgetData<String?>(
+ 'np_episode_id',
+ player.currentEpisodeId,
+ );
final posSec = player.position.inMilliseconds / 1000.0;
await HomeWidget.saveWidgetData<double>('np_position_s', posSec);
@@ -599,19 +644,25 @@ class HomeWidgetService {
// session total above by minutes, and the widget must show the same
// numbers as the app.
await HomeWidget.saveWidgetData<double>(
- 'np_display_total_s', player.displayDuration);
+ 'np_display_total_s',
+ player.displayDuration,
+ );
await HomeWidget.saveWidgetData<double>('np_speed', player.speed);
// The iOS cover art widget divides its remaining time by the speed only
// when the in-app player does, so the two always show the same number.
await HomeWidget.saveWidgetData<bool>(
- 'np_speed_adjusted', await PlayerSettings.getSpeedAdjustedTime());
+ 'np_speed_adjusted',
+ await PlayerSettings.getSpeedAdjustedTime(),
+ );
// Chapters serialize as a JSON array of {start, end, title} maps. The
// native side decodes lazily; if decoding fails we fall back to no
// chapter info and play the file straight through.
try {
await HomeWidget.saveWidgetData<String>(
- 'np_chapters_json', jsonEncode(player.chapters));
+ 'np_chapters_json',
+ jsonEncode(player.chapters),
+ );
} catch (e) {
debugPrint('[WidgetDebug] chapter encode failed: $e');
await HomeWidget.saveWidgetData<String>('np_chapters_json', '[]');
@@ -621,22 +672,30 @@ class HomeWidgetService {
final download = DownloadService().getInfo(itemId);
final paths = download.localPaths;
await HomeWidget.saveWidgetData<String>(
- 'np_audio_paths_json', jsonEncode(paths));
+ 'np_audio_paths_json',
+ jsonEncode(paths),
+ );
await HomeWidget.saveWidgetData<bool>('np_is_downloaded', paths.isNotEmpty);
// Streaming endpoints (token already in URL, plus any reverse-proxy
// headers like Cloudflare Access). Native picks these up when
// np_is_downloaded is false.
await HomeWidget.saveWidgetData<String>(
- 'np_stream_urls_json', jsonEncode(player.activeStreamUrls));
+ 'np_stream_urls_json',
+ jsonEncode(player.activeStreamUrls),
+ );
await HomeWidget.saveWidgetData<String>(
- 'np_stream_headers_json', jsonEncode(player.activeStreamHeaders));
+ 'np_stream_headers_json',
+ jsonEncode(player.activeStreamHeaders),
+ );
// Multi-track support: cumulative track start offsets so the native
// core can figure out which track contains a given absolute position
// (e.g. saved-position 4500s in a 3-file book might fall in track 2).
await HomeWidget.saveWidgetData<String>(
- 'np_track_offsets_json', jsonEncode(player.trackStartOffsets));
+ 'np_track_offsets_json',
+ jsonEncode(player.trackStartOffsets),
+ );
// Server URL + API token so the native core can push progress updates
// directly to ABS while Flutter is dead. Lets users listen for hours
@@ -655,23 +714,28 @@ class HomeWidgetService {
// Cover path piggybacks on the existing widget_cover_path entry, but
// expose it under the np_ namespace too for clarity on the native side.
- final coverPath = await HomeWidget.getWidgetData<String>('widget_cover_path');
+ final coverPath = await HomeWidget.getWidgetData<String>(
+ 'widget_cover_path',
+ );
if (coverPath != null) {
await HomeWidget.saveWidgetData<String>('np_cover_path', coverPath);
}
// GH #298: iOS native now-playing (AbsorbPlayerCore) reads these — feed it
// the same chapter-as-title / "Author · Book" treatment as the lock screen.
+ await HomeWidget.saveWidgetData<String>('np_title', player.nowPlayingTitle);
await HomeWidget.saveWidgetData<String>(
- 'np_title', player.nowPlayingTitle);
- await HomeWidget.saveWidgetData<String>(
- 'np_author', player.nowPlayingSubtitle);
-
- debugPrint('[WidgetDebug] [NativeCore] Stashed: item=$itemId ep=${player.currentEpisodeId} '
- 'pos=${posSec.toStringAsFixed(1)}s tot=${player.totalDuration.toStringAsFixed(0)}s '
- 'speed=${player.speed} dl=${paths.isNotEmpty} '
- 'streams=${player.activeStreamUrls.length} '
- 'tracks=${player.trackStartOffsets.length} '
- 'server=${api?.baseUrl ?? "none"}');
+ 'np_author',
+ player.nowPlayingSubtitle,
+ );
+
+ debugPrint(
+ '[WidgetDebug] [NativeCore] Stashed: item=$itemId ep=${player.currentEpisodeId} '
+ 'pos=${posSec.toStringAsFixed(1)}s tot=${player.totalDuration.toStringAsFixed(0)}s '
+ 'speed=${player.speed} dl=${paths.isNotEmpty} '
+ 'streams=${player.activeStreamUrls.length} '
+ 'tracks=${player.trackStartOffsets.length} '
+ 'server=${api?.baseUrl ?? "none"}',
+ );
}
Future<void> _updateAllWidgets() async {
@@ -723,7 +787,9 @@ class HomeWidgetService {
if (!force && _lastStatsFetch != null) {
final since = DateTime.now().difference(_lastStatsFetch!);
if (since < _statsThrottle) {
- debugPrint('[StatsWidget] Skipping refresh: ${since.inSeconds}s since last (throttle=${_statsThrottle.inSeconds}s)');
+ debugPrint(
+ '[StatsWidget] Skipping refresh: ${since.inSeconds}s since last (throttle=${_statsThrottle.inSeconds}s)',
+ );
return;
}
}
@@ -739,7 +805,8 @@ class HomeWidgetService {
final stats = await api.getListeningStats();
final me = await api.getMe();
- if (stats == null) debugPrint('[StatsWidget] listening-stats returned null');
+ if (stats == null)
+ debugPrint('[StatsWidget] listening-stats returned null');
if (me == null) debugPrint('[StatsWidget] /me returned null');
// Both calls failed - the server is unreachable. Don't blow away the
@@ -754,10 +821,14 @@ class HomeWidgetService {
final today = _todaySeconds(dailyMap).round();
final week = _weekSeconds(dailyMap).round();
final streak = _currentStreak(dailyMap);
- final hidden = (await ScopedPrefs.getStringList('year_hidden_ids')).toSet();
+ final hidden = (await ScopedPrefs.getStringList(
+ 'year_hidden_ids',
+ )).toSet();
final booksYear = _countBooksFinishedThisYear(me, hidden);
- debugPrint('[StatsWidget] Computed: today=${today}s week=${week}s streak=${streak}d booksThisYear=$booksYear (dailyMapKeys=${dailyMap.length})');
+ debugPrint(
+ '[StatsWidget] Computed: today=${today}s week=${week}s streak=${streak}d booksThisYear=$booksYear (dailyMapKeys=${dailyMap.length})',
+ );
_todayBase = today;
_weekBase = week;
@@ -767,7 +838,10 @@ class HomeWidgetService {
await HomeWidget.saveWidgetData<int>('widget_stats_today', today);
await HomeWidget.saveWidgetData<int>('widget_stats_week', week);
await HomeWidget.saveWidgetData<int>('widget_stats_streak', streak);
- await HomeWidget.saveWidgetData<int>('widget_stats_books_year', booksYear);
+ await HomeWidget.saveWidgetData<int>(
+ 'widget_stats_books_year',
+ booksYear,
+ );
await _updateStatsWidget();
debugPrint('[StatsWidget] Pushed and updateWidget(StatsWidget) called');
} catch (e) {
@@ -787,9 +861,13 @@ class HomeWidgetService {
_localAddedWeek += seconds;
try {
await HomeWidget.saveWidgetData<int>(
- 'widget_stats_today', _todayBase + _localAddedToday);
+ 'widget_stats_today',
+ _todayBase + _localAddedToday,
+ );
await HomeWidget.saveWidgetData<int>(
- 'widget_stats_week', _weekBase + _localAddedWeek);
+ 'widget_stats_week',
+ _weekBase + _localAddedWeek,
+ );
await _updateStatsWidget();
} catch (e) {
debugPrint('[StatsWidget] Local add failed: $e');
@@ -807,8 +885,9 @@ class HomeWidgetService {
final headersJson = prefs.getString('custom_headers');
if (headersJson != null) {
try {
- customHeaders =
- Map<String, String>.from(jsonDecode(headersJson) as Map);
+ customHeaders = Map<String, String>.from(
+ jsonDecode(headersJson) as Map,
+ );
} catch (_) {}
}
final headers = customHeaders ?? const <String, String>{};
@@ -820,8 +899,10 @@ class HomeWidgetService {
final localEnabled = await PlayerSettings.getLocalServerEnabled();
final localUrl = await PlayerSettings.getLocalServerUrl();
if (localEnabled && localUrl.isNotEmpty) {
- final localReachable = await ApiService.pingServer(localUrl, customHeaders: headers)
- .timeout(const Duration(seconds: 3), onTimeout: () => false);
+ final localReachable = await ApiService.pingServer(
+ localUrl,
+ customHeaders: headers,
+ ).timeout(const Duration(seconds: 3), onTimeout: () => false);
if (localReachable) baseUrl = localUrl;
}
@@ -877,7 +958,8 @@ class HomeWidgetService {
final now = DateTime.now();
final startOffset = _daySeconds(dailyMap, _dateKey(now)) > 0 ? 0 : 1;
for (int i = startOffset; i < 365; i++) {
- if (_daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i)))) > 0) {
+ if (_daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i)))) >
+ 0) {
streak++;
} else {
break;
@@ -886,7 +968,10 @@ class HomeWidgetService {
return streak;
}
- int _countBooksFinishedThisYear(Map<String, dynamic>? me, Set<String> hidden) {
+ int _countBooksFinishedThisYear(
+ Map<String, dynamic>? me,
+ Set<String> hidden,
+ ) {
if (me == null) return 0;
final progress = me['mediaProgress'];
if (progress is! List) return 0;
@@ -962,10 +1047,13 @@ class HomeWidgetService {
}
final pathInGroup =
- coverPath != null && _groupContainerPath != null && coverPath.startsWith(_groupContainerPath!);
+ coverPath != null &&
+ _groupContainerPath != null &&
+ coverPath.startsWith(_groupContainerPath!);
final exists = coverPath != null && File(coverPath).existsSync();
debugPrint(
- '[WidgetDebug] cover source=$source path=$coverPath exists=$exists inAppGroup=$pathInGroup');
+ '[WidgetDebug] cover source=$source path=$coverPath exists=$exists inAppGroup=$pathInGroup',
+ );
try {
await HomeWidget.saveWidgetData<String?>('widget_cover_path', coverPath);