A cross platform Audiobookshelf client for Android and iOS
Dart
Give the widgets the squiggle progress bar and clocks that tick while playing
Barnabas6d4c34e7e1ae
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.ktindex 5b822409..403b9a07 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidget.kt@@ -39,6 +39,14 @@ class NowPlayingWidget : AppWidgetProvider() {}}+ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ WidgetClock.syncTicker(context)+ }++ override fun onDisabled(context: Context) {+ WidgetClock.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.@@ -144,8 +152,28 @@ class NowPlayingWidget : AppWidgetProvider() {} else {views.setViewVisibility(R.id.widget_chapter, View.GONE)}- views.setProgressBar(R.id.widget_progress, 1000, progress, false)- views.setViewVisibility(R.id.widget_progress, View.VISIBLE)++ // Squiggle bar + elapsed/remaining clocks; the WidgetClock+ // ticker keeps them live while playing.+ val times = WidgetClock.computeTimes(widgetData)+ val fraction = times?.fraction ?: (progress / 1000f)+ val density = context.resources.displayMetrics.density+ val widthDp = appWidgetManager.getAppWidgetOptions(appWidgetId)+ .getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 250)+ views.setImageViewBitmap(+ R.id.widget_progress,+ WidgetClock.drawProgressBar(WidgetClock.bigBarWidthPx(widthDp, density), (12 * density).toInt(), fraction, isPlaying, density)+ )+ if (times != null) {+ views.setTextViewText(R.id.widget_time_elapsed, WidgetClock.fmtTime(times.elapsedMs))+ views.setTextViewText(R.id.widget_time_remaining, "-" + WidgetClock.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)+ }+ views.setViewVisibility(R.id.widget_progress_row, View.VISIBLE)views.setViewVisibility(R.id.widget_controls, View.VISIBLE)if (isPlaying) {@@ -182,8 +210,7 @@ class NowPlayingWidget : AppWidgetProvider() {// Idle stateviews.setTextViewText(R.id.widget_title, "Absorb")views.setTextViewText(R.id.widget_author, "Not playing")- views.setProgressBar(R.id.widget_progress, 1000, 0, false)- views.setViewVisibility(R.id.widget_progress, View.INVISIBLE)+ views.setViewVisibility(R.id.widget_progress_row, View.INVISIBLE)views.setViewVisibility(R.id.widget_controls, View.GONE)views.setViewVisibility(R.id.widget_chapter, View.GONE)views.setImageViewResource(R.id.widget_cover, R.mipmap.ic_launcher)@@ -228,6 +255,7 @@ class NowPlayingWidget : AppWidgetProvider() {mediaButtonPendingIntent(context, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, 3))appWidgetManager.updateAppWidget(appWidgetId, views)+ WidgetClock.syncTicker(context)}}}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.ktindex 8e118cec..1c1392b0 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetCompact.kt@@ -39,6 +39,14 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {}}+ override fun onDeleted(context: Context, appWidgetIds: IntArray) {+ WidgetClock.syncTicker(context)+ }++ override fun onDisabled(context: Context) {+ WidgetClock.syncTicker(context)+ }+override fun onReceive(context: Context, intent: Intent) {if (intent.action == ACTION_TOGGLE_PLAYBACK) {val widgetData = HomeWidgetPlugin.getData(context)@@ -134,6 +142,28 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {views.setTextViewText(R.id.widget_author, author ?: "")views.setViewVisibility(R.id.widget_controls, View.VISIBLE)+ // Squiggle strip + elapsed/remaining clocks at the ends of the+ // controls row; the WidgetClock ticker keeps them live.+ val times = WidgetClock.computeTimes(widgetData)+ val fraction = times?.fraction ?: (widgetData.getInt("widget_progress", 0) / 1000f)+ val density = context.resources.displayMetrics.density+ val widthDp = appWidgetManager.getAppWidgetOptions(appWidgetId)+ .getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 250)+ views.setImageViewBitmap(+ R.id.widget_progress,+ WidgetClock.drawProgressBar(WidgetClock.compactBarWidthPx(widthDp, density), (8 * density).toInt(), fraction, isPlaying, density)+ )+ views.setViewVisibility(R.id.widget_progress, View.VISIBLE)+ if (times != null) {+ views.setTextViewText(R.id.widget_time_elapsed, WidgetClock.fmtTime(times.elapsedMs))+ views.setTextViewText(R.id.widget_time_remaining, "-" + WidgetClock.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)+ }+if (isPlaying) {views.setImageViewResource(R.id.widget_play_pause, R.drawable.ic_widget_pause_dark)} else {@@ -169,6 +199,9 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {views.setTextViewText(R.id.widget_title, "Absorb")views.setTextViewText(R.id.widget_author, "Not playing")views.setViewVisibility(R.id.widget_controls, View.GONE)+ views.setViewVisibility(R.id.widget_progress, View.GONE)+ views.setViewVisibility(R.id.widget_time_elapsed, View.GONE)+ views.setViewVisibility(R.id.widget_time_remaining, View.GONE)views.setImageViewResource(R.id.widget_cover, R.mipmap.ic_launcher)}@@ -209,6 +242,7 @@ class NowPlayingWidgetCompact : AppWidgetProvider() {mediaButtonPendingIntent(context, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD, 13))appWidgetManager.updateAppWidget(appWidgetId, views)+ WidgetClock.syncTicker(context)}}}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.ktindex 721351bd..5fc22864 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/NowPlayingWidgetTiny.kt@@ -6,26 +6,20 @@ 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.Canvasimport android.graphics.Paint-import android.graphics.Pathimport 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@@ -65,11 +59,11 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {}override fun onDeleted(context: Context, appWidgetIds: IntArray) {- syncTicker(context)+ WidgetClock.syncTicker(context)}override fun onDisabled(context: Context) {- syncTicker(context)+ WidgetClock.syncTicker(context)}override fun onReceive(context: Context, intent: Intent) {@@ -97,9 +91,6 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {companion object {const val ACTION_TOGGLE_PLAYBACK = "com.barnabas.absorb.ACTION_TOGGLE_PLAYBACK_TINY"- // 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.@@ -107,11 +98,6 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {private const val INFO_MIN_HEIGHT_DP = 175private 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,@@ -176,216 +162,6 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {return output}- // Progress bar drawn by hand so we can give it the Android-Auto squiggle:- // the played portion waves while playing and flattens when paused, the- // rest stays a dim straight track. The wave is static, not animated.- private fun drawProgressBar(- widthPx: Int,- heightPx: Int,- fraction: Float,- playing: Boolean,- density: Float- ): Bitmap {- val w = widthPx.coerceAtLeast(1)- val h = heightPx.coerceAtLeast(1)- val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)- val canvas = Canvas(bmp)- val centerY = h / 2f- val stroke = 2.5f * density- val inset = stroke- val progressX = (w * fraction.coerceIn(0f, 1f)).coerceIn(inset, w - inset)-- val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {- color = 0x66FFFFFF- style = Paint.Style.STROKE- strokeWidth = stroke- strokeCap = Paint.Cap.ROUND- }- val activePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {- color = 0xFFFFFFFF.toInt()- style = Paint.Style.STROKE- strokeWidth = stroke- strokeCap = Paint.Cap.ROUND- }-- // Remaining track: straight, dim.- canvas.drawLine(progressX, centerY, w - inset, centerY, trackPaint)-- // Played portion.- if (playing) {- val amplitude = 3f * density- val wavelength = 24f * density- val path = Path()- path.moveTo(inset, centerY)- var x = inset- while (x < progressX) {- val y = centerY + amplitude * Math.sin((x / wavelength) * 2.0 * Math.PI).toFloat()- path.lineTo(x, y)- x += 1.5f- }- path.lineTo(progressX, centerY + amplitude * Math.sin((progressX / wavelength) * 2.0 * Math.PI).toFloat())- canvas.drawPath(path, activePaint)- } else {- canvas.drawLine(inset, centerY, progressX, centerY, activePaint)- }-- 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,@@ -407,7 +183,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 && cellsFor(widthDp) >= 2+ val showPanel = hasBook && 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),@@ -449,20 +225,20 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {views.setTextViewText(R.id.widget_skip_forward_text, widgetData.getInt("widget_skip_forward", 30).toString())views.setImageViewResource(R.id.widget_pp, playPauseIcon)- val times = computeTimes(widgetData)+ val times = WidgetClock.computeTimes(widgetData)val fraction = times?.fraction ?: (widgetData.getInt("widget_progress", 0) / 1000f)- val showTimes = widthDp >= TIMES_MIN_WIDTH_DP && times != null+ val showTimes = widthDp >= WidgetClock.TINY_TIMES_MIN_WIDTH_DP && times != nullviews.setImageViewBitmap(R.id.widget_progress,- drawProgressBar(barWidthPx(widthDp, showTimes, density), (12 * density).toInt(), fraction, isPlaying, density)+ WidgetClock.drawProgressBar(WidgetClock.tinyBarWidthPx(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.setTextViewText(R.id.widget_time_elapsed, WidgetClock.fmtTime(times!!.elapsedMs))+ views.setTextViewText(R.id.widget_time_remaining, "-" + WidgetClock.fmtTime(times.remainingMs))views.setViewVisibility(R.id.widget_time_elapsed, View.VISIBLE)views.setViewVisibility(R.id.widget_time_remaining, View.VISIBLE)} else {@@ -528,7 +304,7 @@ class NowPlayingWidgetTiny : AppWidgetProvider() {}appWidgetManager.updateAppWidget(appWidgetId, views)- syncTicker(context)+ WidgetClock.syncTicker(context)}}}diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt b/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.ktnew file mode 100644index 00000000..e74ed16b--- /dev/null+++ b/android/app/src/main/kotlin/com/barnabas/absorb/WidgetClock.kt@@ -0,0 +1,280 @@+package com.barnabas.absorb++import android.appwidget.AppWidgetManager+import android.content.ComponentName+import android.content.Context+import android.content.SharedPreferences+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.Path+import android.os.Handler+import android.os.Looper+import android.os.PowerManager+import android.widget.RemoteViews+import es.antonborri.home_widget.HomeWidgetPlugin+import org.json.JSONArray++// Shared live-clock machinery for the now-playing widgets: the squiggle+// progress bar bitmap, elapsed/remaining formatting, position extrapolation+// between the app's throttled data pushes, and a per-second ticker that+// patches only the clock text (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.+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++ // 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.+ const val TINY_TIMES_MIN_WIDTH_DP = 230++ 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)+ }++ 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. Times are displayed as+ // 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.+ 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)+ return ScopeTimes(+ elapsed * 100 / speedX100,+ (scopeLen - elapsed) * 100 / speedX100,+ elapsed.toFloat() / scopeLen+ )+ }++ // Progress bar drawn by hand so we can give it the Android-Auto squiggle:+ // the played portion waves while playing and flattens when paused, the+ // rest stays a dim straight track. The wave is static, not animated.+ fun drawProgressBar(+ widthPx: Int,+ heightPx: Int,+ fraction: Float,+ playing: Boolean,+ density: Float+ ): Bitmap {+ val w = widthPx.coerceAtLeast(1)+ val h = heightPx.coerceAtLeast(1)+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bmp)+ val centerY = h / 2f+ val stroke = 2.5f * density+ val inset = stroke+ val progressX = (w * fraction.coerceIn(0f, 1f)).coerceIn(inset, w - inset)++ val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = 0x66FFFFFF+ style = Paint.Style.STROKE+ strokeWidth = stroke+ strokeCap = Paint.Cap.ROUND+ }+ val activePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = 0xFFFFFFFF.toInt()+ style = Paint.Style.STROKE+ strokeWidth = stroke+ strokeCap = Paint.Cap.ROUND+ }++ canvas.drawLine(progressX, centerY, w - inset, centerY, trackPaint)++ 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 path = Path()+ path.moveTo(inset, centerY)+ var x = inset+ while (x < progressX) {+ val y = centerY + amplitude * Math.sin((x / wavelength) * 2.0 * Math.PI).toFloat()+ path.lineTo(x, y)+ x += 1.5f+ }+ path.lineTo(progressX, centerY + amplitude * Math.sin((progressX / wavelength) * 2.0 * Math.PI).toFloat())+ canvas.drawPath(path, activePaint)+ } else {+ canvas.drawLine(inset, centerY, progressX, centerY, activePaint)+ }++ return bmp+ }++ // Bar bitmap width estimates per widget. The bars are stretched with+ // fitXY, so these only need to be close: the tiny widget's row padding+ // eats ~36dp and its two clocks ~110dp; the big widget loses its cover+ // and text padding; the compact its cover.+ fun tinyBarWidthPx(widthDp: Int, showTimes: Boolean, density: Float): Int =+ ((widthDp - 36 - if (showTimes) 110 else 0).coerceAtLeast(40) * density).toInt()++ fun bigBarWidthPx(widthDp: Int, density: Float): Int =+ ((widthDp - 160).coerceAtLeast(60) * density).toInt()++ fun compactBarWidthPx(widthDp: Int, density: Float): Int =+ ((widthDp - 110).coerceAtLeast(60) * density).toInt()++ // ── Per-second ticker ──++ 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("WidgetClock", "tick failed", e)+ }+ if (ticking) tickHandler.postDelayed(this, 1000L)+ }+ }++ private fun ids(context: Context, mgr: AppWidgetManager, cls: Class<*>): IntArray =+ mgr.getAppWidgetIds(ComponentName(context, cls))++ private fun minWidthDp(mgr: AppWidgetManager, id: Int): Int =+ mgr.getAppWidgetOptions(id).getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 0)++ 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)+ shouldTick = ids(app, mgr, NowPlayingWidget::class.java).isNotEmpty() ||+ ids(app, mgr, NowPlayingWidgetCompact::class.java).isNotEmpty() ||+ ids(app, mgr, NowPlayingWidgetTiny::class.java).any { cellsFor(minWidthDp(mgr, it)) >= 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)+ val refreshBar = tickCount % 10 == 0+ val elapsed = fmtTime(times.elapsedMs)+ val remaining = "-" + fmtTime(times.remainingMs)++ for (id in ids(context, mgr, NowPlayingWidgetTiny::class.java)) {+ val widthDp = minWidthDp(mgr, id)+ if (cellsFor(widthDp) < 2) continue+ val showTimes = widthDp >= TINY_TIMES_MIN_WIDTH_DP+ if (!showTimes && !refreshBar) continue+ val partial = RemoteViews(context.packageName, R.layout.now_playing_widget_tiny)+ if (showTimes) {+ partial.setTextViewText(R.id.widget_time_elapsed, elapsed)+ partial.setTextViewText(R.id.widget_time_remaining, remaining)+ }+ if (refreshBar) {+ partial.setImageViewBitmap(+ R.id.widget_progress,+ drawProgressBar(tinyBarWidthPx(widthDp, showTimes, density), (12 * density).toInt(), times.fraction, true, density)+ )+ }+ mgr.partiallyUpdateAppWidget(id, partial)+ }++ for (id in ids(context, mgr, NowPlayingWidget::class.java)) {+ val partial = RemoteViews(context.packageName, R.layout.now_playing_widget)+ partial.setTextViewText(R.id.widget_time_elapsed, elapsed)+ partial.setTextViewText(R.id.widget_time_remaining, remaining)+ if (refreshBar) {+ partial.setImageViewBitmap(+ R.id.widget_progress,+ drawProgressBar(bigBarWidthPx(minWidthDp(mgr, id), density), (12 * density).toInt(), times.fraction, true, density)+ )+ }+ mgr.partiallyUpdateAppWidget(id, partial)+ }++ for (id in ids(context, mgr, NowPlayingWidgetCompact::class.java)) {+ val partial = RemoteViews(context.packageName, R.layout.now_playing_widget_compact)+ partial.setTextViewText(R.id.widget_time_elapsed, elapsed)+ partial.setTextViewText(R.id.widget_time_remaining, remaining)+ if (refreshBar) {+ partial.setImageViewBitmap(+ R.id.widget_progress,+ drawProgressBar(compactBarWidthPx(minWidthDp(mgr, id), density), (8 * density).toInt(), times.fraction, true, density)+ )+ }+ mgr.partiallyUpdateAppWidget(id, partial)+ }+ }+}diff --git a/android/app/src/main/res/layout/now_playing_widget.xml b/android/app/src/main/res/layout/now_playing_widget.xmlindex c3cbf2a5..771f4837 100644--- a/android/app/src/main/res/layout/now_playing_widget.xml+++ b/android/app/src/main/res/layout/now_playing_widget.xml@@ -160,7 +160,9 @@</LinearLayout>- <!-- Wrapper fills the gap; ProgressBar is centered inside at 2dp thin -->+ <!-- Wrapper fills the gap; progress row (elapsed / squiggle bar /+ remaining) is centered inside. The bar is drawn as a bitmap by+ WidgetClock: a static wave while playing, flat when paused. --><FrameLayoutandroid:id="@+id/widget_progress_wrapper"android:layout_width="match_parent"@@ -169,18 +171,46 @@android:layout_below="@id/widget_chapter"android:layout_above="@id/widget_controls">- <ProgressBar- android:id="@+id/widget_progress"- style="@android:style/Widget.ProgressBar.Horizontal"+ <LinearLayout+ android:id="@+id/widget_progress_row"android:layout_width="match_parent"- android:layout_height="2dp"+ android:layout_height="wrap_content"android:layout_gravity="center"- android:layout_marginStart="12dp"- android:layout_marginEnd="12dp"- android:max="1000"- android:progress="0"- android:progressDrawable="@drawable/widget_progress_bar"- android:visibility="invisible" />+ android:paddingStart="12dp"+ android:paddingEnd="12dp"+ android:orientation="horizontal"+ android:gravity="center_vertical"+ android:visibility="invisible">++ <TextView+ android:id="@+id/widget_time_elapsed"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:layout_marginEnd="8dp"+ android:textColor="#99FFFFFF"+ android:textSize="9sp"+ 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="#99FFFFFF"+ android:textSize="9sp"+ android:fontFamily="sans-serif-medium"+ android:visibility="gone" />++ </LinearLayout></FrameLayout>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.xmlindex b5781d4a..6873f943 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@@ -65,6 +65,18 @@android:maxLines="1"android:ellipsize="end" />+ <!-- Thin squiggle progress strip (bitmap from WidgetClock) -->+ <ImageView+ android:id="@+id/widget_progress"+ android:layout_width="match_parent"+ android:layout_height="8dp"+ android:layout_marginStart="10dp"+ android:layout_marginEnd="10dp"+ android:layout_marginTop="2dp"+ android:scaleType="fitXY"+ android:contentDescription="Progress"+ android:visibility="gone" />+<!-- Equal spacers above and below controls to center them --><FrameLayoutandroid:layout_width="match_parent"@@ -82,6 +94,16 @@android:paddingEnd="4dp"android:visibility="gone">+ <TextView+ android:id="@+id/widget_time_elapsed"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingStart="8dp"+ android:textColor="#99FFFFFF"+ android:textSize="9sp"+ android:fontFamily="sans-serif-medium"+ android:visibility="gone" />+<FrameLayoutandroid:id="@+id/widget_skip_back"android:layout_width="0dp"@@ -144,6 +166,16 @@android:fontFamily="sans-serif-medium" /></FrameLayout>+ <TextView+ android:id="@+id/widget_time_remaining"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:paddingEnd="8dp"+ android:textColor="#99FFFFFF"+ android:textSize="9sp"+ android:fontFamily="sans-serif-medium"+ android:visibility="gone" />+</LinearLayout><FrameLayout