A cross platform Audiobookshelf client for Android and iOS
Dart
Add live elapsed and remaining times to the resizable widget
Barnabas82269731d117
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.ktindex 1a9c5071..721351bd 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt@@ -6,6 +6,7 @@ import android.app.PendingIntentimport android.content.ComponentNameimport android.content.Contextimport android.content.Intent+import android.content.SharedPreferencesimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.graphics.Canvas@@ -15,12 +16,16 @@ import android.graphics.PorterDuffimport android.graphics.PorterDuffXfermodeimport android.graphics.RectFimport android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.os.PowerManagerimport android.view.KeyEventimport android.view.Viewimport android.net.Uriimport android.widget.RemoteViewsimport es.antonborri.home_widget.HomeWidgetLaunchIntentimport es.antonborri.home_widget.HomeWidgetPlugin+import org.json.JSONArrayimport java.io.File// Adaptive now-playing widget. At 1x1 it's just the cover with a centered@@ -59,6 +64,14 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {}}+ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ syncTicker(context)+ }++ override fun onDisabled(context: Context) {+ syncTicker(context)+ }+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.@@ -87,6 +100,18 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {// Android's own cell-size formula: 70dp per cell, 30dp inter-cell gap.private fun cellsFor(dp: Int): Int = if (dp <= 0) 1 else (dp + 30) / 70+ // Portrait-height (dp) gates for the panel rows, measured across+ // launchers whose row heights differ a lot. A 1-row-tall widget reports+ // ~102dp (One UI) to ~121dp (Pixel); 2 rows ~233-257; 3 rows ~363-393.+ // These sit safely between those bands so tiers match on both.+ private const val INFO_MIN_HEIGHT_DP = 175+ private const val CHAPTER_MIN_HEIGHT_DP = 310++ // Width gate for the elapsed/remaining 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.+ private const val TIMES_MIN_WIDTH_DP = 230+private fun mediaButtonPendingIntent(context: Context,keyCode: Int,@@ -207,6 +232,160 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {return bmp}+ private fun fmtTime(ms: Long): String {+ val totalS = ms / 1000+ val h = totalS / 3600+ val m = (totalS % 3600) / 60+ val s = totalS % 60+ return if (h > 0) String.format("%d:%02d:%02d", h, m, s) else String.format("%d:%02d", m, s)+ }++ private data class ScopeTimes(val elapsedMs: Long, val remainingMs: Long, val fraction: Float)++ // Live position for the clocks and the bar. The app only pushes state+ // every couple of seconds (and much less often in the background), so+ // extrapolate from the last pushed position + timestamp + speed. In+ // chapter mode, resolve which chapter the extrapolated position falls+ // in from the stashed chapter list - that way the clock and bar roll+ // over to the next chapter on time even between pushes.+ private fun computeTimes(widgetData: SharedPreferences): ScopeTimes? {+ val baseMs = widgetData.getInt("widget_pos_abs_ms", -1)+ val totalMs = widgetData.getInt("widget_total_ms", 0)+ if (baseMs < 0 || totalMs <= 0) return null++ val speedX100 = widgetData.getInt("widget_speed_x100", 100).coerceAtLeast(1)+ var absMs = baseMs.toLong()+ if (widgetData.getBoolean("widget_is_playing", false)) {+ val atS = widgetData.getInt("widget_pos_at_s", 0)+ if (atS > 0) {+ val realMs = System.currentTimeMillis() - atS * 1000L+ if (realMs > 0) absMs += realMs * speedX100 / 100+ }+ }+ absMs = absMs.coerceIn(0L, totalMs.toLong())++ var scopeStart = 0L+ var scopeEnd = totalMs.toLong()+ if (widgetData.getBoolean("widget_chapter_mode", false)) {+ val json = widgetData.getString("np_chapters_json", null)+ if (!json.isNullOrEmpty()) {+ try {+ val arr = JSONArray(json)+ for (i in 0 until arr.length()) {+ val ch = arr.optJSONObject(i) ?: continue+ val startMs = (ch.optDouble("start", -1.0) * 1000).toLong()+ val endMs = (ch.optDouble("end", -1.0) * 1000).toLong()+ if (startMs < 0 || endMs <= startMs) continue+ if (absMs >= startMs && (absMs < endMs || i == arr.length() - 1)) {+ scopeStart = startMs+ scopeEnd = endMs+ break+ }+ }+ } catch (_: Exception) {+ }+ }+ }++ val scopeLen = (scopeEnd - scopeStart).coerceAtLeast(1L)+ val elapsed = (absMs - scopeStart).coerceIn(0L, scopeLen)+ // Display listening time (content time / speed), matching the app+ // and the notification at non-1x speeds. It also makes the clock+ // advance one second per real second instead of jumping.+ return ScopeTimes(+ elapsed * 100 / speedX100,+ (scopeLen - elapsed) * 100 / speedX100,+ elapsed.toFloat() / scopeLen+ )+ }++ // Per-second clock. While playing and at least one widget shows the+ // panel, a Handler ticks once a second and pushes ONLY the two time+ // strings (plus an occasional bar refresh) via+ // partiallyUpdateAppWidget - the cover bitmap is never re-sent, so a+ // tick is a few bytes of IPC. Skips all work while the screen is off+ // and stops itself when playback stops. The process is alive whenever+ // this matters because playback holds a foreground service.+ private val tickHandler = Handler(Looper.getMainLooper())+ private var ticking = false+ private var tickCount = 0+ private var tickContext: Context? = null++ private val tickRunnable = object : Runnable {+ override fun run() {+ if (!ticking) return+ val ctx = tickContext ?: return+ try {+ doTick(ctx)+ } catch (e: Exception) {+ android.util.Log.e("NowPlayingWidgetTiny", "tick failed", e)+ }+ if (ticking) tickHandler.postDelayed(this, 1000L)+ }+ }++ private fun syncTicker(context: Context) {+ val app = context.applicationContext+ val widgetData = HomeWidgetPlugin.getData(app)+ var shouldTick = widgetData.getBoolean("widget_has_book", false) &&+ widgetData.getBoolean("widget_is_playing", false)+ if (shouldTick) {+ val mgr = AppWidgetManager.getInstance(app)+ val ids = mgr.getAppWidgetIds(ComponentName(app, NowPlayingWidgetTiny::class.java))+ shouldTick = ids.any { id ->+ cellsFor(mgr.getAppWidgetOptions(id).getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 0)) >= 2+ }+ }+ if (shouldTick && !ticking) {+ ticking = true+ tickCount = 0+ tickContext = app+ tickHandler.postDelayed(tickRunnable, 1000L)+ } else if (!shouldTick && ticking) {+ ticking = false+ tickContext = null+ tickHandler.removeCallbacks(tickRunnable)+ }+ }++ private fun doTick(context: Context) {+ tickCount+++ val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager+ if (!pm.isInteractive) return+ val widgetData = HomeWidgetPlugin.getData(context)+ if (!widgetData.getBoolean("widget_is_playing", false)) {+ syncTicker(context)+ return+ }+ val times = computeTimes(widgetData) ?: return+ val density = context.resources.displayMetrics.density+ val mgr = AppWidgetManager.getInstance(context)+ for (id in mgr.getAppWidgetIds(ComponentName(context, NowPlayingWidgetTiny::class.java))) {+ val widthDp = mgr.getAppWidgetOptions(id).getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 0)+ if (cellsFor(widthDp) < 2) continue+ val showTimes = widthDp >= TIMES_MIN_WIDTH_DP+ val refreshBar = tickCount % 10 == 0+ if (!showTimes && !refreshBar) continue+ val partial = RemoteViews(context.packageName, R.layout.now_playing_widget_tiny)+ if (showTimes) {+ partial.setTextViewText(R.id.widget_time_elapsed, fmtTime(times.elapsedMs))+ partial.setTextViewText(R.id.widget_time_remaining, "-" + fmtTime(times.remainingMs))+ }+ if (refreshBar) {+ partial.setImageViewBitmap(+ R.id.widget_progress,+ drawProgressBar(barWidthPx(widthDp, showTimes, density), (12 * density).toInt(), times.fraction, true, density)+ )+ }+ mgr.partiallyUpdateAppWidget(id, partial)+ }+ }++ // The bar bitmap is stretched with fitXY, so this only needs to be+ // close: row padding eats ~36dp, the two clocks ~110dp when shown.+ private fun barWidthPx(widthDp: Int, showTimes: Boolean, density: Float): Int =+ ((widthDp - 36 - if (showTimes) 110 else 0).coerceAtLeast(40) * density).toInt()+fun updateWidget(context: Context,appWidgetManager: AppWidgetManager,@@ -227,13 +406,14 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {val density = context.resources.displayMetrics.densityval targetPx = (maxOf(widthDp, heightDp, 80) * density).toInt()- val cellsW = cellsFor(widthDp)- val cellsH = cellsFor(heightDp)// Wide enough (2+ cells) for the transport row, and a session to control.- val showPanel = hasBook && cellsW >= 2- // Tall enough to also carry the title/author, then chapter.- val showInfo = showPanel && cellsH >= 2- val showChapter = showPanel && cellsH >= 3+ val showPanel = hasBook && 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),+ // and the old 70dp-cell formula miscounted the taller one as 2 rows.+ val showInfo = showPanel && heightDp >= INFO_MIN_HEIGHT_DP+ val showChapter = showPanel && heightDp >= CHAPTER_MIN_HEIGHT_DP// Cover art (rounded corners)var cover: Bitmap? = null@@ -262,23 +442,36 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {val padBottom = ((if (showInfo) 12 else 8) * density).toInt()views.setViewPadding(R.id.widget_panel, 0, padTop, 0, padBottom)- // Transport is always in the panel.+ // Transport + progress are in every panel size, including the+ // short buttons-only one (cover + squiggle + controls, like a+ // compact notification).views.setTextViewText(R.id.widget_skip_back_text, widgetData.getInt("widget_skip_back", 10).toString())views.setTextViewText(R.id.widget_skip_forward_text, widgetData.getInt("widget_skip_forward", 30).toString())views.setImageViewResource(R.id.widget_pp, playPauseIcon)- // Progress + title/author appear once there's vertical room;- // at 1 cell tall it's just the buttons.- if (showInfo) {- val progress = widgetData.getInt("widget_progress", 0)- val barW = ((widthDp - 36).coerceAtLeast(40) * density).toInt()- val barH = (12 * density).toInt()- views.setImageViewBitmap(- R.id.widget_progress,- drawProgressBar(barW, barH, progress / 1000f, isPlaying, density)- )- views.setViewVisibility(R.id.widget_progress, View.VISIBLE)+ val times = computeTimes(widgetData)+ val fraction = times?.fraction ?: (widgetData.getInt("widget_progress", 0) / 1000f)+ val showTimes = widthDp >= TIMES_MIN_WIDTH_DP && times != null+ views.setImageViewBitmap(+ R.id.widget_progress,+ drawProgressBar(barWidthPx(widthDp, showTimes, density), (12 * density).toInt(), fraction, isPlaying, density)+ )+ views.setViewVisibility(R.id.widget_progress_row, View.VISIBLE)++ // Elapsed / remaining clocks flank the bar on wide widgets;+ // the per-second ticker keeps them live while playing.+ if (showTimes) {+ views.setTextViewText(R.id.widget_time_elapsed, fmtTime(times!!.elapsedMs))+ views.setTextViewText(R.id.widget_time_remaining, "-" + fmtTime(times.remainingMs))+ views.setViewVisibility(R.id.widget_time_elapsed, View.VISIBLE)+ views.setViewVisibility(R.id.widget_time_remaining, View.VISIBLE)+ } else {+ views.setViewVisibility(R.id.widget_time_elapsed, View.GONE)+ views.setViewVisibility(R.id.widget_time_remaining, View.GONE)+ }+ // Title / author only once there's vertical room for them.+ if (showInfo) {val title = widgetData.getString("widget_title", null)val author = widgetData.getString("widget_author", null)views.setTextViewText(R.id.widget_title, if (title.isNullOrEmpty()) "Absorb" else title)@@ -290,7 +483,6 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {views.setViewVisibility(R.id.widget_author, View.VISIBLE)}} else {- views.setViewVisibility(R.id.widget_progress, View.GONE)views.setViewVisibility(R.id.widget_title, View.GONE)views.setViewVisibility(R.id.widget_author, View.GONE)}@@ -336,6 +528,7 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {}appWidgetManager.updateAppWidget(appWidgetId, views)+ syncTicker(context)}}}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.xmlindex 2e0a4315..1c98d8c1 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@@ -82,21 +82,52 @@android:ellipsize="end"android:visibility="gone" />- <!-- Progress is drawn as a bitmap (see drawProgressBar): a static- Android-Auto-style squiggle while playing, flat when paused.- fitXY fills the panel width exactly, so the played fraction- lines up regardless of our width estimate. -->- <ImageView- android:id="@+id/widget_progress"+ <!-- Progress row: elapsed / remaining clocks flank the bar on wide+ widgets. The bar is drawn as a bitmap (see drawProgressBar): a+ static Android-Auto-style squiggle while playing, flat when+ paused. fitXY fills the row width exactly, so the played+ fraction lines up regardless of our width estimate. -->+ <LinearLayout+ android:id="@+id/widget_progress_row"android:layout_width="match_parent"- android:layout_height="12dp"- android:layout_marginStart="18dp"- android:layout_marginEnd="18dp"+ android:layout_height="wrap_content"android:layout_marginTop="6dp"android:layout_marginBottom="2dp"- android:scaleType="fitXY"- android:contentDescription="Progress"- android:visibility="gone" />+ android:paddingStart="18dp"+ android:paddingEnd="18dp"+ android:orientation="horizontal"+ android:gravity="center_vertical"+ android:visibility="gone">++ <TextView+ android:id="@+id/widget_time_elapsed"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginEnd="8dp"+ android:textColor="#CCFFFFFF"+ android:textSize="10sp"+ android:fontFamily="sans-serif-medium"+ android:visibility="gone" />++ <ImageView+ android:id="@+id/widget_progress"+ android:layout_width="0dp"+ android:layout_height="12dp"+ android:layout_weight="1"+ android:scaleType="fitXY"+ android:contentDescription="Progress" />++ <TextView+ android:id="@+id/widget_time_remaining"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginStart="8dp"+ android:textColor="#CCFFFFFF"+ android:textSize="10sp"+ android:fontFamily="sans-serif-medium"+ android:visibility="gone" />++ </LinearLayout><!-- Transport row: skip buttons pushed toward the edges, play/pausecentered. Weighted so the cluster spreads across the full width. -->diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 33b6569c..e5bedec4 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -503,6 +503,21 @@ class HomeWidgetService {}await HomeWidget.saveWidgetData<int>('widget_progress', progress);+ // Base state for the Android widget's live clock: the native side+ // extrapolates position from the last pushed position + wall-clock+ // 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);+ await HomeWidget.saveWidgetData<int>(+ 'widget_total_ms', (totalDur * 1000).round());+ await HomeWidget.saveWidgetData<int>('widget_pos_at_s',+ DateTime.now().millisecondsSinceEpoch ~/ 1000);+ await HomeWidget.saveWidgetData<int>(+ 'widget_speed_x100', (player.speed * 100).round());+ await HomeWidget.saveWidgetData<bool>(+ 'widget_chapter_mode', player.notifChapterMode);+// Persist item/episode ID so the widget can resume after app killfinal prefs = await SharedPreferences.getInstance();await prefs.setString('widget_item_id', player.currentItemId!);