widgets: fix blank photos widget, stale screentime, double weather refresh
- Commit
ae33599cad378cea96c6a4619cecd1e2359b7373- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-20 22:44 UTC (15 days ago)
- Parents
a94bc29
Photos widget rendered blank when the library was empty or a photo undecodable - it now shows the placeholder drawable. Screentime kept showing a stale top-app after the top app disappeared; the keys are cleared and absent values render an em-dash instead of '0m'. Calendar/todo widgets did provider/ Room reads on the composition thread - now on Dispatchers.IO like email's widget. The shared hourly widget worker forced NetworkType.CONNECTED on every widget, so offline-data widgets (calendar, todo, email, photos) went stale offline; requiresNetwork is now per-widget and false for local-data widgets. Weather had two hourly schedulers; the generic re-render is dropped and WeatherRefreshWorker (fresh fetch + updateAll for both widgets) is the single hourly path. Todo's complete action refreshes its widget directly instead of hoping TodoBackground is alive. The widget lint now requires exactly one MaWidget + its receiver per widget file; all 12 existing widget files pass. Verified: compile for photos/screentime/email/calendar/todo, :library:widgets tests.
Diff
calendar/src/main/java/com/vayunmathur/calendar/platform/BootReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/platform/BootReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/platform/BootReceiver.ktindex 2d466c3c55..e67eebcb23 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/platform/BootReceiver.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/platform/BootReceiver.kt@@ -70,8 +70,8 @@ class BootReceiver : BroadcastReceiver() { Log.error(TAG, "$action: could not reschedule reminders from the calendar provider", expected) } try {- context.scheduleHourlyUpdate(CalendarGlanceWidget::class)- context.scheduleHourlyUpdate(CalendarMonthGlanceWidget::class)+ context.scheduleHourlyUpdate(CalendarGlanceWidget::class, requiresNetwork = false)+ context.scheduleHourlyUpdate(CalendarMonthGlanceWidget::class, requiresNetwork = false) CalendarGlanceWidget().updateAll(context) CalendarMonthGlanceWidget().updateAll(context) } catch (expected: Exception) {
calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarGlanceWidget.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarGlanceWidget.kt b/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarGlanceWidget.ktindex f04578871d..6af5971a6c 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarGlanceWidget.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarGlanceWidget.kt@@ -50,6 +50,8 @@ import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.plus import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.json.Json+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import androidx.glance.LocalContext import kotlin.time.Clock @@ -60,7 +62,8 @@ data class CalendarWidgetData( /** Agenda Glance widget showing the next month of visible events grouped by day. */ class CalendarGlanceWidget : MaWidget<CalendarWidgetData>() {- override suspend fun loadData(context: Context, id: GlanceId): CalendarWidgetData {+ override suspend fun loadData(context: Context, id: GlanceId): CalendarWidgetData =+ withContext(Dispatchers.IO) { val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()) val today = now.date @@ -82,8 +85,8 @@ class CalendarGlanceWidget : MaWidget<CalendarWidgetData>() { (notAllDay.filter { day in it.spanDays }.sortedBy { it.startDateTime } + allDay.filter { day in it.spanDays }) }- return CalendarWidgetData(positionedEvents)- }+ CalendarWidgetData(positionedEvents)+ } override fun previewData(context: Context): CalendarWidgetData = CalendarWidgetData(emptyMap()) @@ -250,5 +253,6 @@ class CalendarGlanceWidgetReceiver : MaWidgetReceiver<CalendarGlanceWidget>( widgetClass = CalendarGlanceWidget::class, receiverClass = CalendarGlanceWidgetReceiver::class, dateTriggers = true,+ requiresNetwork = false, widgetFactory = ::CalendarGlanceWidget, )
calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarMonthGlanceWidget.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarMonthGlanceWidget.kt b/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarMonthGlanceWidget.ktindex f8adaab52f..3983d2dc4a 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarMonthGlanceWidget.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/widget/CalendarMonthGlanceWidget.kt@@ -58,6 +58,8 @@ import kotlinx.datetime.plus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext /** Month-grid data for the month widget, real or sample. */ data class MonthWidgetData(@@ -77,7 +79,8 @@ class CalendarMonthGlanceWidget : MaWidget<MonthWidgetData>() { */ override val sizeMode: SizeMode = SizeMode.Exact - override suspend fun loadData(context: Context, id: GlanceId): MonthWidgetData {+ override suspend fun loadData(context: Context, id: GlanceId): MonthWidgetData =+ withContext(Dispatchers.IO) { val zone = TimeZone.currentSystemDefault() val today = Clock.System.now().toLocalDateTime(zone).date @@ -101,8 +104,8 @@ class CalendarMonthGlanceWidget : MaWidget<MonthWidgetData>() { val dayNames = localizedDayOfWeekNames(DateNameStyle.SHORT, locale) val weekdayNames = weeks.first().map { day -> dayNames[day.dayOfWeek.isoDayNumber - 1] } - return MonthWidgetData(monthLabel, weeks, eventsByDay, today, today.month, weekdayNames)- }+ MonthWidgetData(monthLabel, weeks, eventsByDay, today, today.month, weekdayNames)+ } override fun previewData(context: Context): MonthWidgetData { val zone = TimeZone.currentSystemDefault()@@ -412,5 +415,6 @@ class CalendarMonthGlanceWidgetReceiver : MaWidgetReceiver<CalendarMonthGlanceWi widgetClass = CalendarMonthGlanceWidget::class, receiverClass = CalendarMonthGlanceWidgetReceiver::class, dateTriggers = true,+ requiresNetwork = false, widgetFactory = ::CalendarMonthGlanceWidget, )
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex f25569d20c..91627d796e 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -420,10 +420,20 @@ class ImapIdleService : Service() { private fun buildOngoingNotification(): Notification { ensureChannel(applicationContext)+ // Tap opens the app: the ongoing foreground notification was a dead tap before.+ val contentIntent = android.app.PendingIntent.getActivity(+ applicationContext,+ NOTIFICATION_ID,+ Intent(applicationContext, com.vayunmathur.email.MainActivity::class.java).apply {+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+ },+ android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE,+ ) return androidx.core.app.NotificationCompat.Builder(applicationContext, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification_mail) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.listening_for_new_mail))+ .setContentIntent(contentIntent) .setPriority(androidx.core.app.NotificationCompat.PRIORITY_LOW) .setOngoing(true) .setShowWhen(false)
email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.ktindex ec9408f40e..4accfbab29 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailNotifications.kt@@ -60,6 +60,28 @@ object EmailNotifications { } } + /**+ * Cancel the notifications for [messages] (one per message, posted under+ * [notificationId]). Called when their thread is opened: the tapped+ * notification auto-cancels itself, but the rest of the thread's stay in+ * the shade until they are cancelled here.+ */+ fun cancelForMessages(context: Context, messages: List<EmailMessage>) {+ if (messages.isEmpty()) return+ val nm = NotificationManagerCompat.from(context)+ for (msg in messages) {+ try {+ nm.cancel(notificationId(msg))+ } catch (_: SecurityException) {+ // Notifications revoked — nothing to cancel.+ }+ }+ }++ /** Cancel the notification for a single message (see [cancelForMessages]). */+ fun cancelForMessage(context: Context, msg: EmailMessage) =+ cancelForMessages(context, listOf(msg))+ private fun postOne( nm: NotificationManagerCompat, context: Context,
email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.ktindex f309ab723f..8324f50435 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageThreadPage.kt@@ -1,8 +1,11 @@ package com.vayunmathur.email.ui import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue+import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.email.platform.EmailNotifications import com.vayunmathur.email.platform.EmailViewModel @Composable@@ -16,5 +19,10 @@ fun MessageThreadPage( onCompose: (String, String) -> Unit ) { val messages by viewModel.getThread(accountEmail, threadId).collectAsStateWithLifecycle(emptyList())+ val context = LocalContext.current+ // Cancel-on-read: opening the thread clears its notifications from the shade.+ LaunchedEffect(messages) {+ if (messages.isNotEmpty()) EmailNotifications.cancelForMessages(context, messages)+ } MessageThreadScreen(messages = messages, actions = viewModel, threadId = threadId, onBack = onBack, onReply = onReply, onForward = onForward, onCompose = onCompose) }
email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt
diff --git a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.ktindex ebc1f66ee0..84be688129 100644--- a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt+++ b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt@@ -229,5 +229,6 @@ class EmailWidget : MaWidget<List<EmailPreview>>() { class EmailWidgetReceiver : MaWidgetReceiver<EmailWidget>( widgetClass = EmailWidget::class, receiverClass = EmailWidgetReceiver::class,+ requiresNetwork = false, widgetFactory = ::EmailWidget, )
email/src/main/res/xml/email_widget_info.xml
diff --git a/email/src/main/res/xml/email_widget_info.xml b/email/src/main/res/xml/email_widget_info.xmlindex a4fbc028f0..7a80e57297 100644--- a/email/src/main/res/xml/email_widget_info.xml+++ b/email/src/main/res/xml/email_widget_info.xml@@ -4,5 +4,6 @@ android:minWidth="200dp" android:minHeight="150dp" android:description="@string/email_widget_description"+ android:updatePeriodMillis="0" android:resizeMode="horizontal|vertical" android:widgetCategory="home_screen" />
library/widgets/src/main/java/com/vayunmathur/library/widgets/MaWidgetReceiver.kt
diff --git a/library/widgets/src/main/java/com/vayunmathur/library/widgets/MaWidgetReceiver.kt b/library/widgets/src/main/java/com/vayunmathur/library/widgets/MaWidgetReceiver.ktindex f54e93c819..cddce47182 100644--- a/library/widgets/src/main/java/com/vayunmathur/library/widgets/MaWidgetReceiver.kt+++ b/library/widgets/src/main/java/com/vayunmathur/library/widgets/MaWidgetReceiver.kt@@ -25,7 +25,8 @@ import kotlin.reflect.KClass * A receiver keeps one line per widget: * `class FooReceiver : MaWidgetReceiver<FooWidget>(FooWidget::class, * FooReceiver::class)`, plus `dateTriggers = true` for date-driven widgets,- * `hourly = false` for push-updated widgets, `previews = false` when the+ * `hourly = false` for push-updated widgets, `requiresNetwork = false` for+ * hourly widgets whose data is purely on-device, `previews = false` when the * picker preview comes from `previewLayout` XML, and [onEnabledExtra] for * extras like weather's refresh-worker scheduling. */@@ -33,6 +34,7 @@ abstract class MaWidgetReceiver<W : GlanceAppWidget>( private val widgetClass: KClass<W>, private val receiverClass: KClass<out GlanceAppWidgetReceiver>, private val hourly: Boolean = true,+ private val requiresNetwork: Boolean = true, private val dateTriggers: Boolean = false, private val previews: Boolean = true, private val widgetFactory: () -> W,@@ -82,6 +84,6 @@ abstract class MaWidgetReceiver<W : GlanceAppWidget>( } private fun ensureScheduled(context: Context) {- if (hourly) context.scheduleHourlyUpdate(widgetClass)+ if (hourly) context.scheduleHourlyUpdate(widgetClass, requiresNetwork) } }
library/widgets/src/main/java/com/vayunmathur/library/widgets/Widgets.kt
diff --git a/library/widgets/src/main/java/com/vayunmathur/library/widgets/Widgets.kt b/library/widgets/src/main/java/com/vayunmathur/library/widgets/Widgets.ktindex c269dcbf93..7ebbe6d55e 100644--- a/library/widgets/src/main/java/com/vayunmathur/library/widgets/Widgets.kt+++ b/library/widgets/src/main/java/com/vayunmathur/library/widgets/Widgets.kt@@ -63,19 +63,25 @@ class GenericWidgetWorker( } } -fun <T : GlanceAppWidget> Context.scheduleHourlyUpdate(widgetClass: KClass<T>) {+fun <T : GlanceAppWidget> Context.scheduleHourlyUpdate(+ widgetClass: KClass<T>,+ requiresNetwork: Boolean = true,+) { val className = widgetClass.qualifiedName ?: return val inputData = workDataOf(GenericWidgetWorker.ARG_WIDGET_CLASS to className) // Hourly refresh is WorkManager periodic work (not Glance's- // updatePeriodMillis): require CONNECTED so the hourly wake-up is- // deferred/coalesced until the device is online instead of firing- // on every offline hour.+ // updatePeriodMillis). Widgets whose data needs the network require+ // CONNECTED so the hourly wake-up is deferred/coalesced until the+ // device is online instead of firing on every offline hour. Offline-data+ // widgets (calendar/today/email/photos read only on-device stores) pass+ // requiresNetwork = false so they still refresh hourly while offline.+ val constraints = Constraints.Builder().apply {+ if (requiresNetwork) setRequiredNetworkType(NetworkType.CONNECTED)+ }.build() val request = PeriodicWorkRequestBuilder<GenericWidgetWorker>(1, TimeUnit.HOURS)- .setConstraints(- Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()- )+ .setConstraints(constraints) .setInputData(inputData) .build()
lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt
diff --git a/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt b/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.ktindex 8c7673d3ce..f12a5e1f05 100644--- a/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt+++ b/lint-rules/src/main/java/com/vayunmathur/lint/PackageStructureDetector.kt@@ -217,30 +217,65 @@ class PackageStructureDetector : Detector(), SourceCodeScanner { /** * One widget, one file: every file directly in the `widget` root must- * declare a widget class (a `MaWidget` / `GlanceAppWidget` subclass,- * not merely its receiver) at top level. Helper-only files in- * `widget` are violations; widget helpers nest inside the widget- * class or its file, and non-Glance app helpers belong to their- * own canonical root. See docs/package-structure.md §3.2.+ * declare exactly one widget class (a `MaWidget` / `GlanceAppWidget`+ * subclass, not merely its receiver) at top level, together with that+ * widget's receiver (`MaWidgetReceiver` / `GlanceAppWidgetReceiver`+ * for the same widget) in the same file. Zero or multiple widget+ * classes, and a widget without its receiver alongside it, are+ * violations. Helper-only files in `widget` are violations; widget+ * helpers nest inside the widget class or its file, and non-Glance+ * app helpers belong to their own canonical root.+ * See docs/package-structure.md §3.2. */ private fun validateWidgetFile(node: UFile, packageName: String): String? { val ktFile = node.sourcePsi as? KtFile ?: return null- val hasWidgetClass = ktFile.declarations- .filterIsInstance<KtClass>()- .any { clazz ->- clazz.superTypeListEntries.any { entry ->- val text = entry.text- text.contains(Regex("""\bMaWidget\s*[<(]""")) ||- text.contains(Regex("""\bGlanceAppWidget\s*\("""))- }+ val topLevelClasses = ktFile.declarations.filterIsInstance<KtClass>()+ fun KtClass.isWidgetClass(): Boolean = superTypeListEntries.any { entry ->+ val text = entry.text+ text.contains(Regex("""\bMaWidget\s*[<(]""")) ||+ text.contains(Regex("""\bGlanceAppWidget\s*\("""))+ }+ fun KtClass.isReceiverClass(): Boolean = superTypeListEntries.any { entry ->+ val text = entry.text+ text.contains(Regex("""\bMaWidgetReceiver\s*[<(]""")) ||+ text.contains(Regex("""\bGlanceAppWidgetReceiver\s*\("""))+ }+ val widgetClasses = topLevelClasses.filter { it.isWidgetClass() }+ if (widgetClasses.size != 1) {+ val found = if (widgetClasses.isEmpty()) {+ "no widget class"+ } else {+ "${widgetClasses.size} widget classes " ++ "[${widgetClasses.mapNotNull { it.name }.joinToString(", ")}]" }- if (hasWidgetClass) return null- return "File in widget package `$packageName` declares no widget class at " +- "top level. One widget, one file: every file in `widget` must declare " +- "its `MaWidget` subclass (with its receiver) at top level; helper-only " +- "files are forbidden — nest helpers inside the widget or move " +- "non-Glance app helpers to their canonical root. " +- "See docs/package-structure.md §3.2."+ return "File in widget package `$packageName` declares $found at " ++ "top level. One widget, one file: every file in `widget` must declare " ++ "exactly one `MaWidget` subclass (with its receiver) at top level; " ++ "helper-only files are forbidden — nest helpers inside the widget or move " ++ "non-Glance app helpers to their canonical root. " ++ "See docs/package-structure.md §3.2."+ }+ val widgetName = widgetClasses.single().name+ val receiverClasses = topLevelClasses.filter { it.isReceiverClass() }+ // Its receiver: a receiver whose supertype names this widget+ // (e.g. `MaWidgetReceiver<PhotoGlanceWidget>(...)`, whose entry+ // text also carries `widgetClass = PhotoGlanceWidget::class`).+ // A bare `GlanceAppWidgetReceiver` subclass also counts.+ val hasOwnReceiver = receiverClasses.any { clazz ->+ clazz.superTypeListEntries.any { entry ->+ val text = entry.text+ (widgetName != null && text.contains(widgetName)) ||+ text.contains(Regex("""\bGlanceAppWidgetReceiver\s*\("""))+ }+ }+ if (!hasOwnReceiver) {+ return "File in widget package `$packageName` declares widget " ++ "`$widgetName` but not its receiver in the same file. One widget, " ++ "one file: every file in `widget` must declare exactly one " ++ "`MaWidget` subclass together with its `MaWidgetReceiver` for " ++ "that widget at top level. See docs/package-structure.md §3.2."+ }+ return null } private fun validateSubpackages(packageName: String, segments: List<String>): String? {
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex 72011f46d6..04c3b10296 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -504,9 +504,19 @@ internal fun Context.syncForegroundInfo( manager.createNotificationChannel( NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW) )+ // Tap opens the app: the ongoing foreground notification was a dead tap before.+ val contentIntent = android.app.PendingIntent.getActivity(+ this,+ notificationId,+ android.content.Intent(this, com.vayunmathur.photos.MainActivity::class.java).apply {+ flags = android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP+ },+ android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE,+ ) val notification = NotificationCompat.Builder(this, channelId) .setContentTitle(title) .setContentText(text)+ .setContentIntent(contentIntent) .setSmallIcon(android.R.drawable.stat_notify_sync) .setOngoing(true) .build()
photos/src/main/java/com/vayunmathur/photos/widget/PhotoGlanceWidget.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/widget/PhotoGlanceWidget.kt b/photos/src/main/java/com/vayunmathur/photos/widget/PhotoGlanceWidget.ktindex d728af4665..05768ca59d 100644--- a/photos/src/main/java/com/vayunmathur/photos/widget/PhotoGlanceWidget.kt+++ b/photos/src/main/java/com/vayunmathur/photos/widget/PhotoGlanceWidget.kt@@ -47,8 +47,23 @@ class PhotoGlanceWidget : MaWidget<List<String>>() { uri?.let { getResizedBitmap(context, it, 600) } } }- bitmap?.let {- Content(it) { uri = uris.randomOrNull() }+ val loaded = bitmap+ if (loaded != null) {+ Content(loaded) { uri = uris.randomOrNull() }+ } else {+ // Empty library or undecodable photo: show the placeholder+ // drawable instead of a blank widget (mirrors PreviewContent).+ Box(+ modifier = GlanceModifier.fillMaxSize(),+ contentAlignment = Alignment.Center+ ) {+ Image(+ provider = ImageProvider(R.drawable.widget_preview_photo),+ contentDescription = null,+ modifier = GlanceModifier.fillMaxSize(),+ contentScale = ContentScale.Crop+ )+ } } } @@ -132,5 +147,6 @@ private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, class PhotoGlanceWidgetReceiver : MaWidgetReceiver<PhotoGlanceWidget>( widgetClass = PhotoGlanceWidget::class, receiverClass = PhotoGlanceWidgetReceiver::class,+ requiresNetwork = false, widgetFactory = ::PhotoGlanceWidget, )
screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.ktindex 5322c98d9f..f66bf8059a 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/widget/ScreenTimeGlanceWidget.kt@@ -60,9 +60,9 @@ class ScreenTimeGlanceWidget : MaWidget<Unit>() { override fun Content(data: Unit) { val context = LocalContext.current val prefs = currentState<Preferences>()- val total = prefs[TotalMinutesKey] ?: 0L+ val total = prefs[TotalMinutesKey] val topLabel = prefs[TopLabelKey]- val topMinutes = prefs[TopMinutesKey] ?: 0L+ val topMinutes = prefs[TopMinutesKey] ScreenTimeWidgetContent( context = context, total = total,@@ -85,9 +85,9 @@ class ScreenTimeGlanceWidget : MaWidget<Unit>() { @Composable private fun ScreenTimeWidgetContent( context: Context,- total: Long,+ total: Long?, topLabel: String?,- topMinutes: Long,+ topMinutes: Long?, ) { Box( modifier = GlanceModifier@@ -117,7 +117,7 @@ private fun ScreenTimeWidgetContent( ), ) Text(- text = formatWidgetMinutes(total),+ text = total?.let { formatWidgetMinutes(it) } ?: "—", style = TextStyle( color = GlanceTheme.colors.onSurface, fontSize = 28.sp,@@ -126,7 +126,16 @@ private fun ScreenTimeWidgetContent( ) if (topLabel != null) { Text(- text = "$topLabel · ${formatWidgetMinutes(topMinutes)}",+ text = "$topLabel · ${topMinutes?.let { formatWidgetMinutes(it) } ?: "—"}",+ style = TextStyle(+ color = GlanceTheme.colors.onSurfaceVariant,+ fontSize = 12.sp,+ textAlign = TextAlign.Center,+ ),+ )+ } else {+ Text(+ text = "—", style = TextStyle( color = GlanceTheme.colors.onSurfaceVariant, fontSize = 12.sp,@@ -186,6 +195,11 @@ object WidgetRefresh { if (topLabel != null) { this[TopLabelKey] = topLabel this[TopMinutesKey] = topMinutes+ } else {+ // No top app: clear the stale label/minutes so+ // a previous app does not survive this refresh.+ remove(TopLabelKey)+ remove(TopMinutesKey) } } }
todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt b/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.ktindex e4dc13bb50..89413a316f 100644--- a/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt+++ b/todo/src/main/java/com/vayunmathur/todo/widget/TodayWidget.kt@@ -16,6 +16,7 @@ import androidx.glance.action.ActionParameters import androidx.glance.action.actionParametersOf import androidx.glance.action.clickable import androidx.glance.appwidget.CheckBox+import androidx.glance.appwidget.updateAll import androidx.glance.appwidget.action.ActionCallback import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.action.actionStartActivity@@ -44,6 +45,8 @@ import com.vayunmathur.todo.domain.TodoView import com.vayunmathur.todo.notifications.ReminderNotifications import com.vayunmathur.todo.platform.IntentRouter import kotlinx.datetime.TimeZone+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext /** Open tasks due today or overdue, as the Today view shows them. */ data class TodayWidgetData(val rows: List<TodayWidgetRow>)@@ -53,7 +56,8 @@ data class TodayWidgetRow(val syncId: String, val title: String, val overdue: Bo /** Home-screen widget listing open tasks due today or overdue, with in-widget completion. */ class TodayWidget : MaWidget<TodayWidgetData>() {- override suspend fun loadData(context: Context, id: GlanceId): TodayWidgetData {+ override suspend fun loadData(context: Context, id: GlanceId): TodayWidgetData =+ withContext(Dispatchers.IO) { val repo = TodoRepository.get(context) val now = System.currentTimeMillis() val zone = TimeZone.currentSystemDefault()@@ -62,8 +66,8 @@ class TodayWidget : MaWidget<TodayWidgetData>() { val rows = model.groups.flatMap { it.rows }.map { row -> TodayWidgetRow(row.todo.syncId, row.todo.title, DueBuckets.isOverdue(row.todo, now, zone)) }- return TodayWidgetData(rows)- }+ TodayWidgetData(rows)+ } override fun previewData(context: Context) = TodayWidgetData( listOf(@@ -158,7 +162,12 @@ class CompleteTaskAction : ActionCallback { val syncId = parameters[SYNC_ID] ?: return val repo = TodoRepository.get(context) val todo: Todo = repo.getBySyncId(syncId) ?: return- if (!todo.done) repo.setDone(todo, true)+ if (!todo.done) {+ repo.setDone(todo, true)+ // Refresh directly: TodoBackground may not be alive in this+ // (widget-host) process, so don't rely on its data-change flow.+ TodayWidget().updateAll(context)+ } } /** Action parameter key carrying the sync id of the task to complete from the widget. */@@ -172,5 +181,6 @@ class TodayWidgetReceiver : MaWidgetReceiver<TodayWidget>( widgetClass = TodayWidget::class, receiverClass = TodayWidgetReceiver::class, dateTriggers = true,+ requiresNetwork = false, widgetFactory = ::TodayWidget, )
weather/src/main/java/com/vayunmathur/weather/widget/WeatherBlobGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherBlobGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherBlobGlanceWidget.ktindex 9555d4a724..4ce6d07066 100644--- a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherBlobGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherBlobGlanceWidget.kt@@ -184,6 +184,10 @@ private fun BlobWeatherBlock(weather: WidgetWeather?, tempColor: Color) { class WeatherBlobGlanceWidgetReceiver : MaWidgetReceiver<WeatherBlobGlanceWidget>( widgetClass = WeatherBlobGlanceWidget::class, receiverClass = WeatherBlobGlanceWidgetReceiver::class,+ // No generic hourly schedule: WeatherRefreshWorker (below/extra) is the single+ // hourly refresher - it fetches fresh forecasts, then updateAll()s BOTH weather+ // widgets. The generic library worker would only re-render the stale cache.+ hourly = false, widgetFactory = ::WeatherBlobGlanceWidget, ) { override fun onEnabledExtra(context: Context) {
weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.ktindex 4e864b2d0a..c2327b89fb 100644--- a/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/widget/WeatherGlanceWidget.kt@@ -240,6 +240,10 @@ private fun WeatherBlock(weather: WidgetWeather?) { class WeatherGlanceWidgetReceiver : MaWidgetReceiver<WeatherGlanceWidget>( widgetClass = WeatherGlanceWidget::class, receiverClass = WeatherGlanceWidgetReceiver::class,+ // No generic hourly schedule: WeatherRefreshWorker (below/extra) is the single+ // hourly refresher - it fetches fresh forecasts, then updateAll()s BOTH weather+ // widgets. The generic library worker would only re-render the stale cache.+ hourly = false, widgetFactory = ::WeatherGlanceWidget, ) { override fun onEnabledExtra(context: Context) {