Modern Apps git

← Modern-Apps.git

various apps: fix widget previews

Commit
766e558c57a7d8d00e6d289cb582147e696e3e00
Author
Vayun Mathur <[email protected]>
When
2026-07-06 21:18 UTC (5 months ago)
Parents
cf9469d

Diff

calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.ktindex 5dc572a9ab..748f58c0f9 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt@@ -23,6 +23,7 @@ import androidx.compose.ui.Modifier import androidx.core.content.ContextCompat import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.calendar.data.Instance+import com.vayunmathur.calendar.glance.CalendarGlanceWidgetReceiver import com.vayunmathur.calendar.ui.* import com.vayunmathur.calendar.ui.dialogs.* import com.vayunmathur.calendar.util.CalendarViewModel@@ -31,6 +32,7 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.dialog.DatePickerDialog import com.vayunmathur.library.ui.dialog.TimePickerDialogContent import com.vayunmathur.library.util.*+import com.vayunmathur.library.widgets.updateWidgetPreviews import kotlin.time.Instant import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalTime@@ -44,6 +46,7 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        updateWidgetPreviews(CalendarGlanceWidgetReceiver::class)         enableEdgeToEdge()         handleIntent(intent)         setContent {
calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt b/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.ktindex 47bff5b137..9aa6d6b9f5 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt@@ -82,6 +82,51 @@ class CalendarGlanceWidget : GlanceAppWidget() {             }         }     }++    override suspend fun providePreview(context: Context, widgetCategory: Int) {+        provideContent {+            DynamicThemeGlance(context) {+                CalendarPreviewContent()+            }+        }+    }+}++@SuppressLint("RestrictedApi")+@Composable+private fun CalendarPreviewContent() {+    val dateFormatS = LocalDate.Format {+        dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)+        chars(", ")+        monthName(MonthNames.ENGLISH_ABBREVIATED)+        chars(" ")+        day(Padding.NONE)+    }+    val today = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date++    Scaffold(titleBar = {+        TitleBar(ImageProvider(R.drawable.calendar_today_24px), today.format(dateFormatS))+    }) {+        Column(GlanceModifier.fillMaxSize()) {+            CalendarPreviewEvent("Team standup", "9:00 – 9:30 AM", 0xFF4285F4.toInt())+            CalendarPreviewEvent("Lunch with Sam", "12:30 – 1:30 PM", 0xFF34A853.toInt())+            CalendarPreviewEvent("Design review", "3:00 – 4:00 PM", 0xFFEA4335.toInt())+        }+    }+}++@SuppressLint("RestrictedApi")+@Composable+private fun CalendarPreviewEvent(title: String, time: String, color: Int) {+    Row(modifier = GlanceModifier.fillMaxWidth().padding(vertical = 6.dp)) {+        Row(GlanceModifier.background(GlanceTheme.colors.primaryContainer).cornerRadius(6.dp)) {+            Box(GlanceModifier.background(ColorProvider(Color(color))).width(8.dp).fillMaxHeight()) {}+            Column(GlanceModifier.padding(4.dp).fillMaxWidth()) {+                Text(title, style = TextStyle(fontWeight = FontWeight.Bold))+                Text(time, style = defaultTextStyle.copy(color = GlanceTheme.colors.onPrimaryContainer))+            }+        }+    } } @SuppressLint("RestrictedApi") @Composable
calendar/src/main/res/values/strings.xml
diff --git a/calendar/src/main/res/values/strings.xml b/calendar/src/main/res/values/strings.xmlindex 623f09671f..06341ce5b4 100644--- a/calendar/src/main/res/values/strings.xml+++ b/calendar/src/main/res/values/strings.xml@@ -1,5 +1,6 @@ <resources>     <string name="app_name">Calendar</string>+    <string name="calendar_widget_description">Upcoming events at a glance — tap to open Calendar</string>      <!-- Common actions -->     <string name="ok">OK</string>
calendar/src/main/res/xml/calendar_glance_widget_info.xml
diff --git a/calendar/src/main/res/xml/calendar_glance_widget_info.xml b/calendar/src/main/res/xml/calendar_glance_widget_info.xmlindex 0907f75d3e..b9157eb03d 100644--- a/calendar/src/main/res/xml/calendar_glance_widget_info.xml+++ b/calendar/src/main/res/xml/calendar_glance_widget_info.xml@@ -4,6 +4,7 @@     android:minHeight="110dp"     android:updatePeriodMillis="0"     android:initialLayout="@layout/glance_widget_initial_layout"+    android:description="@string/calendar_widget_description"     android:resizeMode="horizontal|vertical"     android:widgetCategory="home_screen" /> 
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 126cb13a95..d41200c831 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -32,8 +32,10 @@ import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.lifecycleScope import androidx.core.net.toUri import com.vayunmathur.email.data.EmailSyncWorker+import com.vayunmathur.email.widget.EmailWidgetReceiver import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.*+import com.vayunmathur.library.widgets.updateWidgetPreviews import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.launch import kotlinx.serialization.Serializable@@ -43,6 +45,7 @@ class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState) +        updateWidgetPreviews(EmailWidgetReceiver::class)         handleIntent(intent)         // Wake the outbox sender on every cold start: if the process was killed         // between scheduled retries, this is what gets it going again.
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 f04ce19b7d..1e344e1c14 100644--- a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt+++ b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt@@ -48,6 +48,31 @@ class EmailWidget : GlanceAppWidget() {         }     } +    override suspend fun providePreview(context: Context, widgetCategory: Int) {+        val sample = listOf(+            EmailMessage(+                accountEmail = "[email protected]", folderName = "INBOX", id = 1,+                subject = "Lunch tomorrow?", from = "Alex Johnson <[email protected]>",+                date = "Jul 6", body = "Are we still on for noon at the usual place?",+            ),+            EmailMessage(+                accountEmail = "[email protected]", folderName = "INBOX", id = 2,+                subject = "Q3 report is ready", from = "Priya Patel <[email protected]>",+                date = "Jul 5", body = "I've attached the final numbers for review.",+            ),+            EmailMessage(+                accountEmail = "[email protected]", folderName = "INBOX", id = 3,+                subject = "Your weekly digest", from = "Tech Weekly <[email protected]>",+                date = "Jul 5", body = "Top stories and updates from this week.",+            ),+        )+        provideContent {+            DynamicThemeGlance(context) {+                EmailWidgetContent(sample)+            }+        }+    }+     @SuppressLint("RestrictedApi")     @Composable     private fun EmailWidgetContent(messages: List<EmailMessage>) {
email/src/main/res/values/strings.xml
diff --git a/email/src/main/res/values/strings.xml b/email/src/main/res/values/strings.xmlindex 2b549b999a..b165e47418 100644--- a/email/src/main/res/values/strings.xml+++ b/email/src/main/res/values/strings.xml@@ -1,5 +1,6 @@ <resources>     <string name="app_name">Email</string>+    <string name="email_widget_description">Recent messages from your unified inbox — tap to open Email</string>          <!-- MainActivity strings -->     <string name="all_accounts">All Accounts</string>
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 82153127cd..a4fbc028f0 100644--- a/email/src/main/res/xml/email_widget_info.xml+++ b/email/src/main/res/xml/email_widget_info.xml@@ -3,5 +3,6 @@     android:initialLayout="@layout/glance_default_loading_layout"     android:minWidth="200dp"     android:minHeight="150dp"+    android:description="@string/email_widget_description"     android:resizeMode="horizontal|vertical"     android:widgetCategory="home_screen" />
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 5980dfe602..fef6233b6c 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -51,7 +51,7 @@ credentials = "1.6.0" # Special Features (PDF, Maps, Health, Crypto) biometric = "1.2.0-alpha05" pdfViewer = "1.0.0-alpha19"-glance = "1.1.1"+glance = "1.2.0-rc01" connectClient = "1.2.0-alpha04" healthServicesClient = "1.1.0-alpha05" wearTiles = "1.4.1"
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 2097594eb5..edb35a8514 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@@ -1,12 +1,14 @@ package com.vayunmathur.library.widgets  import android.content.Context+import android.os.Build import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.glance.GlanceId import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetManager+import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.state.updateAppWidgetState import androidx.glance.appwidget.updateAll import androidx.glance.state.GlanceStateDefinition@@ -87,6 +89,57 @@ fun <T : GlanceAppWidget> Context.updateWidget(widgetClass: KClass<T>) {     ) } +/**+ * Worker that pushes composable widget previews to the system so they appear in the+ * launcher's widget picker. Backed by Glance's [GlanceAppWidgetManager.setWidgetPreviews],+ * which renders the receiver's [GlanceAppWidget.providePreview] content. The underlying+ * platform API only exists on Android 15+ (API 35); on older releases this is a no-op.+ */+class WidgetPreviewWorker(+    context: Context,+    workerParams: WorkerParameters+) : CoroutineWorker(context, workerParams) {++    override suspend fun doWork(): Result {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) return Result.success()+        val className = inputData.getString(ARG_RECEIVER_CLASS) ?: return Result.failure()+        return try {+            @Suppress("UNCHECKED_CAST")+            val receiverClass = Class.forName(className).kotlin as KClass<out GlanceAppWidgetReceiver>+            GlanceAppWidgetManager(applicationContext).setWidgetPreviews(receiverClass)+            Result.success()+        } catch (e: Exception) {+            Result.failure()+        }+    }++    companion object {+        const val ARG_RECEIVER_CLASS = "receiver_class_name"+    }+}++/**+ * Registers composable previews for [receiverClass] with the system widget picker.+ * Safe and cheap to call on every app launch: it dedups within a session and the+ * platform rate-limits repeated registrations. No-op below Android 15.+ */+fun <T : GlanceAppWidgetReceiver> Context.updateWidgetPreviews(receiverClass: KClass<T>) {+    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) return+    val className = receiverClass.qualifiedName ?: return++    val inputData = workDataOf(WidgetPreviewWorker.ARG_RECEIVER_CLASS to className)++    val request = OneTimeWorkRequestBuilder<WidgetPreviewWorker>()+        .setInputData(inputData)+        .build()++    WorkManager.getInstance(this).enqueueUniqueWork(+        "${className}_preview",+        ExistingWorkPolicy.KEEP,+        request+    )+}+ /**  * GlanceStateDefinition that stores data as JSON in Preferences DataStore.  * Use this for widgets that need to store complex state objects.
photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex 9229c6e3bd..5ad16f0946 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -57,10 +57,12 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.library.widgets.updateWidgetPreviews import com.vayunmathur.photos.data.FaceDao import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotoDao import com.vayunmathur.photos.data.PhotoDatabase+import com.vayunmathur.photos.glance.PhotoGlanceWidgetReceiver import com.vayunmathur.photos.ui.GalleryPage import com.vayunmathur.photos.ui.MapPage import com.vayunmathur.photos.ui.PeoplePage@@ -101,6 +103,7 @@ class MainActivity : FragmentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        updateWidgetPreviews(PhotoGlanceWidgetReceiver::class)         enableEdgeToEdge()         val db = buildDatabase<PhotoDatabase>()         photoDao = db.photoDao()
photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.ktindex dcf0b86ab2..6b81b71380 100644--- a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt+++ b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt@@ -24,6 +24,7 @@ import androidx.glance.layout.ContentScale import androidx.glance.layout.fillMaxSize import com.vayunmathur.library.widgets.DynamicThemeGlance import com.vayunmathur.library.util.buildDatabase+import com.vayunmathur.photos.R import com.vayunmathur.photos.data.PhotoDatabase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext@@ -48,6 +49,24 @@ class PhotoGlanceWidget : GlanceAppWidget() {             }         }     }++    override suspend fun providePreview(context: Context, widgetCategory: Int) {+        provideContent {+            DynamicThemeGlance(context) {+                Box(+                    modifier = GlanceModifier.fillMaxSize(),+                    contentAlignment = Alignment.Center+                ) {+                    Image(+                        provider = ImageProvider(R.drawable.widget_preview_photo),+                        contentDescription = null,+                        modifier = GlanceModifier.fillMaxSize(),+                        contentScale = ContentScale.Crop+                    )+                }+            }+        }+    } }  @Composable
photos/src/main/res/drawable/widget_preview_photo.xml
diff --git a/photos/src/main/res/drawable/widget_preview_photo.xml b/photos/src/main/res/drawable/widget_preview_photo.xmlnew file mode 100644index 0000000000..7d4a4b7e21--- /dev/null+++ b/photos/src/main/res/drawable/widget_preview_photo.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Placeholder "photo" shown in the widget picker preview, since the live widget+     renders a random image from the user's gallery that isn't available at preview time. -->+<shape xmlns:android="http://schemas.android.com/apk/res/android"+    android:shape="rectangle">+    <gradient+        android:angle="135"+        android:startColor="@android:color/system_accent1_400"+        android:centerColor="@android:color/system_accent2_300"+        android:endColor="@android:color/system_accent3_200"+        android:type="linear" />+</shape>
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex eec174ead0..c13dbe366f 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -1,5 +1,6 @@ <resources>     <string name="app_name">Photos</string>+    <string name="photo_widget_description">A rotating photo from your gallery — tap to shuffle</string>     <string name="title_edit_photo">Edit Photo</string>     <string name="action_save">Save</string>     <string name="action_save_as_copy">Save as Copy</string>
photos/src/main/res/xml/photo_glance_widget_info.xml
diff --git a/photos/src/main/res/xml/photo_glance_widget_info.xml b/photos/src/main/res/xml/photo_glance_widget_info.xmlindex 0907f75d3e..d68ff6d909 100644--- a/photos/src/main/res/xml/photo_glance_widget_info.xml+++ b/photos/src/main/res/xml/photo_glance_widget_info.xml@@ -4,6 +4,7 @@     android:minHeight="110dp"     android:updatePeriodMillis="0"     android:initialLayout="@layout/glance_widget_initial_layout"+    android:description="@string/photo_widget_description"     android:resizeMode="horizontal|vertical"     android:widgetCategory="home_screen" /> 
weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 6fd960001c..5108ba0e7f 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -13,7 +13,9 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.library.widgets.updateWidgetPreviews import com.vayunmathur.weather.data.WeatherDatabase+import com.vayunmathur.weather.glance.WeatherGlanceWidgetReceiver import com.vayunmathur.weather.ui.HomePage import com.vayunmathur.weather.ui.SearchLocationPage import com.vayunmathur.weather.ui.WeatherMapPage@@ -29,6 +31,7 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        updateWidgetPreviews(WeatherGlanceWidgetReceiver::class)         enableEdgeToEdge()         setContent {             DynamicTheme {
weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.ktindex 70943676e9..79bc53b326 100644--- a/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt+++ b/weather/src/main/java/com/vayunmathur/weather/glance/WeatherGlanceWidget.kt@@ -80,6 +80,14 @@ class WeatherGlanceWidget : GlanceAppWidget() {         }     } +    override suspend fun providePreview(context: Context, widgetCategory: Int) {+        provideContent {+            DynamicThemeGlance(context) {+                Content(WidgetWeather(temperatureCelsius = 22.0, weatherCode = 1, isDay = true))+            }+        }+    }+     private suspend fun loadWeatherSnapshot(context: Context): WidgetWeather? {         return try {             val db = context.buildDatabase<WeatherDatabase>(dbName = "weather-db")
weather/src/main/res/values/strings.xml
diff --git a/weather/src/main/res/values/strings.xml b/weather/src/main/res/values/strings.xmlindex f4dafc5c49..2cf7d28c78 100644--- a/weather/src/main/res/values/strings.xml+++ b/weather/src/main/res/values/strings.xml@@ -1,5 +1,6 @@ <resources>     <string name="app_name">Weather</string>+    <string name="weather_widget_description">Current time, date, and weather at a glance — tap for the forecast</string>     <string name="search_location">Search location</string>     <string name="confirm_delete">Confirm delete</string>     <string name="city_name_hint">City name</string>
weather/src/main/res/xml/weather_glance_widget_info.xml
diff --git a/weather/src/main/res/xml/weather_glance_widget_info.xml b/weather/src/main/res/xml/weather_glance_widget_info.xmlindex 1e9579c2cd..5b60d60520 100644--- a/weather/src/main/res/xml/weather_glance_widget_info.xml+++ b/weather/src/main/res/xml/weather_glance_widget_info.xml@@ -6,5 +6,6 @@     android:targetCellHeight="1"     android:updatePeriodMillis="0"     android:initialLayout="@layout/glance_widget_initial_layout"+    android:description="@string/weather_widget_description"     android:resizeMode="horizontal"     android:widgetCategory="home_screen" />