diff --git a/app/build.gradle.kts b/app/build.gradle.kts index b96a84d..71bd556 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -244,6 +244,7 @@ dependencies { implementation(libs.floret.core.crash) implementation(libs.floret.identity) implementation(libs.floret.components) + implementation(libs.floret.glance) debugImplementation(libs.androidx.ui.tooling) debugImplementation(libs.androidx.ui.test.manifest) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 997cb36..40c05bd 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -185,6 +185,20 @@ android:resource="@xml/appwidget_info_tasks" /> + + + + + + + + return NavRequest.NewTask() + ACTION_NEW_TASK -> return NavRequest.NewTask( + listId = intent.getLongExtra(EXTRA_PRESET_LIST_ID, -1L).takeIf { it > 0L }, + ) ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY) ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST) ?.let { name -> SmartList.entries.firstOrNull { it.name == name } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt index b9f56e3..a090218 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AgendulaNavHost.kt @@ -52,7 +52,8 @@ fun AgendulaNavHost( nav.navigate(Dest.Settings.build(Dest.Settings.SECTION_ACCOUNTS)) { launchSingleTop = true } is NavRequest.OpenAccount -> nav.navigate(Dest.Settings.buildAccount(navRequest.accountId)) { launchSingleTop = true } - is NavRequest.NewTask -> nav.navigate(Dest.TaskEdit.buildNew(title = navRequest.title)) + is NavRequest.NewTask -> + nav.navigate(Dest.TaskEdit.buildNew(presetListId = navRequest.listId, title = navRequest.title)) is NavRequest.OpenSmart -> nav.navigate(Dest.TaskList.build(TaskFilter.Smart(navRequest.list))) { launchSingleTop = true } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt index d4c94d9..41cb335 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/NavRequest.kt @@ -18,8 +18,11 @@ sealed interface NavRequest { /** One account's detail — where "sign in again" lives. */ data class OpenAccount(val accountId: Long) : NavRequest - /** A new task, optionally titled with text shared from another app. */ - data class NewTask(val title: String? = null) : NavRequest + /** + * A new task, optionally titled with text shared from another app, or + * preset to a list — a widget's own add button, when it shows one list. + */ + data class NewTask(val title: String? = null, val listId: Long? = null) : NavRequest /** One of the smart lists — the launcher's "Today" shortcut, a widget header. */ data class OpenSmart(val list: SmartList) : NavRequest diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidget.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidget.kt new file mode 100644 index 0000000..847e2d6 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidget.kt @@ -0,0 +1,215 @@ +package de.jeanlucmakiola.agendula.widget + +import android.content.Context +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.glance.ColorFilter +import androidx.glance.GlanceId +import androidx.glance.GlanceModifier +import androidx.glance.GlanceTheme +import androidx.glance.Image +import androidx.glance.ImageProvider +import androidx.glance.LocalContext +import androidx.glance.LocalSize +import androidx.glance.action.actionParametersOf +import androidx.glance.action.clickable +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.SizeMode +import androidx.glance.appwidget.action.actionRunCallback +import androidx.glance.appwidget.action.actionStartActivity +import androidx.glance.appwidget.provideContent +import androidx.glance.appwidget.state.getAppWidgetState +import androidx.glance.currentState +import androidx.glance.layout.Alignment +import androidx.glance.layout.Box +import androidx.glance.layout.Column +import androidx.glance.layout.Row +import androidx.glance.layout.Spacer +import androidx.glance.layout.fillMaxSize +import androidx.glance.layout.height +import androidx.glance.layout.padding +import androidx.glance.layout.size +import androidx.glance.state.PreferencesGlanceStateDefinition +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextAlign +import androidx.glance.text.TextStyle +import de.jeanlucmakiola.agendula.MainActivity +import de.jeanlucmakiola.agendula.R +import de.jeanlucmakiola.agendula.domain.SmartList +import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.ui.theme.AgendulaDarkFallback +import de.jeanlucmakiola.agendula.ui.theme.AgendulaLightFallback +import de.jeanlucmakiola.floret.glance.FloretGlanceTheme +import de.jeanlucmakiola.floret.glance.WidgetActionButton +import de.jeanlucmakiola.floret.glance.WidgetActionStyle +import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.glance.WidgetSurface +import de.jeanlucmakiola.floret.glance.WidgetThemeMode +import de.jeanlucmakiola.floret.time.formatDateTimeCompact +import de.jeanlucmakiola.floret.time.formatTime +import de.jeanlucmakiola.floret.glance.R as GlanceR +import kotlinx.coroutines.flow.first + +/** + * "At a glance" — a small widget that leads with the single thing worth seeing + * without opening the app: the next open task today, or (too small to show one) + * just a quick-add button. Always Today + overdue, since a tiny widget has no + * room for a filter picker of its own — see [TaskWidgetConfigActivity] for + * background/theme. + */ +class GlanceTaskWidget : GlanceAppWidget() { + + override val stateDefinition = PreferencesGlanceStateDefinition + + override val sizeMode = SizeMode.Responsive(setOf(CompactSize, RegularSize)) + + override suspend fun provideGlance(context: Context, id: GlanceId) { + val state = getAppWidgetState(context, PreferencesGlanceStateDefinition, id) + val initial = runCatching { context.taskWidgetData(FILTER, false).first() } + .getOrDefault(TaskWidgetData.Unavailable) + provideContent { + val background = parseWidgetBackground(currentState(WIDGET_BACKGROUND_KEY)) + val themeOverride = parseWidgetThemeOverride(currentState(WIDGET_THEME_KEY)) + val data by remember { context.taskWidgetData(FILTER, false) }.collectAsState(initial = initial) + val ready = data as? TaskWidgetData.Ready ?: initial as? TaskWidgetData.Ready + FloretGlanceTheme( + lightScheme = AgendulaLightFallback, + darkScheme = AgendulaDarkFallback, + dynamicColor = ready?.dynamicColor ?: true, + mode = ready?.effectiveThemeMode(themeOverride) ?: WidgetThemeMode.SYSTEM, + ) { + GlanceTaskWidgetBody(data, background) + } + } + } + + private companion object { + val FILTER = TaskFilter.Smart(SmartList.TODAY) + val CompactSize = DpSize(56.dp, 56.dp) + val RegularSize = DpSize(110.dp, 110.dp) + } +} + +@Composable +private fun GlanceTaskWidgetBody(data: TaskWidgetData?, background: WidgetBackground) { + val context = LocalContext.current + val ready = data as? TaskWidgetData.Ready + val compact = LocalSize.current.width < 90.dp + WidgetSurface(background = background) { + if (compact || ready == null) { + Box(modifier = GlanceModifier.fillMaxSize(), contentAlignment = Alignment.Center) { + WidgetActionButton( + icon = ImageProvider(GlanceR.drawable.floret_ic_widget_add), + contentDescription = context.getString(R.string.new_task), + action = actionStartActivity(MainActivity.newTaskIntent(context)), + style = WidgetActionStyle.FILLED, + ) + } + } else { + Column( + modifier = GlanceModifier.fillMaxSize().padding(8.dp), + ) { + GlanceSummary(ready) + Spacer(GlanceModifier.height(6.dp)) + val next = ready.rows.firstOrNull() + if (next == null) { + Text( + text = context.getString(R.string.widget_glance_no_tasks), + style = TextStyle(color = GlanceTheme.colors.onSurfaceVariant, fontSize = 12.sp), + ) + } else { + GlanceNextTaskRow(next, ready.use24Hour) + } + } + } + } +} + +@Composable +private fun GlanceSummary(ready: TaskWidgetData.Ready) { + val context = LocalContext.current + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = "${ready.rows.size}", + style = TextStyle(color = GlanceTheme.colors.primary, fontSize = 24.sp, fontWeight = FontWeight.Medium), + ) + Column(modifier = GlanceModifier.defaultWeight().padding(start = 6.dp)) { + Text( + text = context.getString(R.string.smart_today), + style = TextStyle(color = GlanceTheme.colors.onSurface, fontSize = 12.sp), + ) + if (ready.overdueCount > 0) { + Text( + text = context.resources.getQuantityString( + R.plurals.widget_glance_overdue_count, ready.overdueCount, ready.overdueCount, + ), + style = TextStyle(color = GlanceTheme.colors.error, fontSize = 11.sp), + ) + } + } + WidgetActionButton( + icon = ImageProvider(GlanceR.drawable.floret_ic_widget_add), + contentDescription = context.getString(R.string.new_task), + action = actionStartActivity(MainActivity.newTaskIntent(context)), + style = WidgetActionStyle.TONAL, + ) + } +} + +@Composable +private fun GlanceNextTaskRow(row: WidgetTaskRow, use24Hour: Boolean) { + val context = LocalContext.current + val title = row.title.ifBlank { context.getString(R.string.task_untitled) } + Row(modifier = GlanceModifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = GlanceModifier.size(32.dp).clickable( + actionRunCallback( + actionParametersOf( + CompleteTaskAction.TaskIdKey to row.taskId, + CompleteTaskAction.OccurrenceKey to + (row.occurrenceStart?.toEpochMilliseconds() ?: CompleteTaskAction.NO_OCCURRENCE), + ), + ), + ), + contentAlignment = Alignment.Center, + ) { + Image( + provider = ImageProvider(GlanceR.drawable.floret_ic_widget_check), + contentDescription = context.getString(R.string.widget_complete_task, title), + colorFilter = ColorFilter.tint(GlanceTheme.colors.onSurfaceVariant), + modifier = GlanceModifier.size(18.dp), + ) + } + Column( + modifier = GlanceModifier.defaultWeight().padding(start = 4.dp) + .clickable( + actionStartActivity( + MainActivity.taskIntent(context, row.taskId, row.occurrenceStart?.toEpochMilliseconds()), + ), + ), + ) { + Text( + text = title, + maxLines = 2, + style = TextStyle(color = GlanceTheme.colors.onSurface, fontSize = 13.sp), + ) + row.due?.let { due -> + Text( + text = due.formatDateTimeCompact(row.isAllDay, use24Hour).ifBlank { due.formatTime(use24Hour) }, + maxLines = 1, + style = TextStyle( + color = if (row.isOverdue) GlanceTheme.colors.error else GlanceTheme.colors.onSurfaceVariant, + fontSize = 11.sp, + textAlign = TextAlign.Start, + ), + ) + } + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidgetReceiver.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidgetReceiver.kt new file mode 100644 index 0000000..67e2f65 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/GlanceTaskWidgetReceiver.kt @@ -0,0 +1,27 @@ +package de.jeanlucmakiola.agendula.widget + +import android.appwidget.AppWidgetManager +import android.content.Context +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import de.jeanlucmakiola.floret.glance.WidgetRollover + +/** Host-facing receiver for [GlanceTaskWidget]; also keeps the midnight rollover armed. */ +class GlanceTaskWidgetReceiver : GlanceAppWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = GlanceTaskWidget() + + override fun onEnabled(context: Context) { + super.onEnabled(context) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) + } + + override fun onDisabled(context: Context) { + super.onDisabled(context) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) + } + + override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { + super.onUpdate(context, appWidgetManager, appWidgetIds) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidget.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidget.kt index 59df7b0..d2e781f 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidget.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidget.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.glance.ColorFilter @@ -48,17 +49,30 @@ import androidx.glance.text.Text import androidx.glance.text.TextStyle import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R -import de.jeanlucmakiola.agendula.data.prefs.ThemeMode import de.jeanlucmakiola.agendula.domain.TaskFilter +import de.jeanlucmakiola.agendula.ui.theme.AgendulaDarkFallback +import de.jeanlucmakiola.agendula.ui.theme.AgendulaLightFallback import de.jeanlucmakiola.floret.components.pastelize +import de.jeanlucmakiola.floret.glance.FloretGlanceTheme +import de.jeanlucmakiola.floret.glance.WidgetActionButton +import de.jeanlucmakiola.floret.glance.WidgetActionStyle +import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.glance.WidgetGroupedRow +import de.jeanlucmakiola.floret.glance.WidgetHeader +import de.jeanlucmakiola.floret.glance.WidgetMessage +import de.jeanlucmakiola.floret.glance.WidgetSurface +import de.jeanlucmakiola.floret.glance.WidgetThemeMode import de.jeanlucmakiola.floret.time.formatDateTimeCompact import de.jeanlucmakiola.floret.time.formatTime +import de.jeanlucmakiola.floret.glance.R as GlanceR import kotlinx.coroutines.flow.first import kotlin.time.Instant /** - * "Tasks" home-screen widget: one smart list (Today by default) or one real - * list per instance, with a checkbox to complete each task in place. + * "Tasks" home-screen widget: one smart list (Today by default) or one or more + * real lists per instance, with a tonal container per section — grouped by + * list, or by due bucket (Overdue / Today / Tomorrow / Later / No date) — and a + * check to complete each task in place. * * The data is collected live inside the composition rather than loaded once in * the `provideGlance` preamble: an `update` on a running session only @@ -69,7 +83,7 @@ class TaskWidget : GlanceAppWidget() { override val stateDefinition = PreferencesGlanceStateDefinition - override val sizeMode = SizeMode.Single + override val sizeMode = SizeMode.Responsive(setOf(CompactSize, RegularSize)) override suspend fun provideGlance(context: Context, id: GlanceId) { val state = getAppWidgetState(context, PreferencesGlanceStateDefinition, id) @@ -80,17 +94,26 @@ class TaskWidget : GlanceAppWidget() { provideContent { val filter = parseWidgetFilter(currentState(WIDGET_FILTER_KEY)) val groupByList = currentState(WIDGET_GROUP_BY_LIST_KEY) ?: false + val background = parseWidgetBackground(currentState(WIDGET_BACKGROUND_KEY)) + val themeOverride = parseWidgetThemeOverride(currentState(WIDGET_THEME_KEY)) val data by remember(filter, groupByList) { context.taskWidgetData(filter, groupByList) } .collectAsState(initial = if (filter == initialFilter && groupByList == initialGroupByList) initial else null) val ready = data as? TaskWidgetData.Ready ?: initial as? TaskWidgetData.Ready - AgendulaGlanceTheme( + FloretGlanceTheme( + lightScheme = AgendulaLightFallback, + darkScheme = AgendulaDarkFallback, dynamicColor = ready?.dynamicColor ?: true, - themeMode = ready?.themeMode ?: ThemeMode.SYSTEM, + mode = ready?.effectiveThemeMode(themeOverride) ?: WidgetThemeMode.SYSTEM, ) { - TaskWidgetBody(filter, data) + TaskWidgetBody(filter, data, background) } } } + + private companion object { + val CompactSize = DpSize(110.dp, 110.dp) + val RegularSize = DpSize(250.dp, 110.dp) + } } /** Completes the tapped task — just the one occurrence for a recurring series. */ @@ -112,28 +135,12 @@ class CompleteTaskAction : ActionCallback { } } -/** A row in the widget's list: a task, or (grouped widgets) a list-name header. */ -private sealed interface WidgetListItem { - data class Header(val listId: Long, val name: String) : WidgetListItem - data class TaskItem(val row: WidgetTaskRow) : WidgetListItem -} - -/** Inserts a [WidgetListItem.Header] before each run of same-list rows. */ -private fun groupedItems(rows: List, listNames: Map): List { - val result = mutableListOf() - var lastListId: Long? = null - for (row in rows) { - if (row.listId != lastListId) { - result += WidgetListItem.Header(row.listId, listNames[row.listId].orEmpty()) - lastListId = row.listId - } - result += WidgetListItem.TaskItem(row) - } - return result -} - @Composable -private fun TaskWidgetBody(filter: TaskFilter, data: TaskWidgetData?) { +private fun TaskWidgetBody( + filter: TaskFilter, + data: TaskWidgetData?, + background: WidgetBackground, +) { val context = LocalContext.current val ready = data as? TaskWidgetData.Ready val title = when (filter) { @@ -141,41 +148,51 @@ private fun TaskWidgetBody(filter: TaskFilter, data: TaskWidgetData?) { is TaskFilter.OfList, is TaskFilter.OfLists -> ready?.singleListName ?: context.getString(R.string.widget_tasks_label) } - Column( - modifier = GlanceModifier - .fillMaxSize() - .background(GlanceTheme.colors.widgetBackground) - .padding(horizontal = 8.dp, vertical = 6.dp), - ) { - Header(title, filter) - Spacer(GlanceModifier.height(4.dp)) - when (data) { - null -> Unit - TaskWidgetData.Unavailable -> Message(context.getString(R.string.widget_unavailable)) - is TaskWidgetData.Ready -> - if (data.rows.isEmpty()) { - Message(context.getString(R.string.widget_empty)) - } else { - val items = if (data.groupByList) { - groupedItems(data.rows, data.listNames) + WidgetSurface(background = background) { + Column( + modifier = GlanceModifier.fillMaxSize().padding(horizontal = 8.dp, vertical = 6.dp), + ) { + TaskWidgetHeader(title, filter, ready?.singleListId) + Spacer(GlanceModifier.height(4.dp)) + when (data) { + null -> Unit + TaskWidgetData.Unavailable -> WidgetMessage(context.getString(R.string.widget_unavailable)) + is TaskWidgetData.Ready -> + if (data.rows.isEmpty()) { + WidgetMessage(context.getString(R.string.widget_empty)) } else { - data.rows.map { WidgetListItem.TaskItem(it) } - } - LazyColumn(modifier = GlanceModifier.fillMaxSize()) { - items(items.size) { index -> - when (val item = items[index]) { - is WidgetListItem.Header -> ListHeader(item.name) - is WidgetListItem.TaskItem -> TaskRow(item.row, data.use24Hour) + val sections = widgetSections( + data.rows, + data.groupByList, + data.listNames, + ) { kind -> context.getString(dueBucketLabel(kind)) } + LazyColumn(modifier = GlanceModifier.fillMaxSize()) { + items(sections.size) { index -> + when (val section = sections[index]) { + is WidgetSection.Header -> SectionHeader(section.name) + is WidgetSection.TaskItem -> + WidgetGroupedRow(position = section.position) { + TaskRow(section.row, data.use24Hour) + } + } } } } - } + } } } } +private fun dueBucketLabel(kind: DueKind?): Int = when (kind) { + DueKind.PAST -> R.string.widget_section_overdue + DueKind.TODAY -> R.string.home_due_today + DueKind.TOMORROW -> R.string.home_due_tomorrow + DueKind.LATER -> R.string.widget_section_later + null -> R.string.widget_section_no_date +} + @Composable -private fun ListHeader(name: String) { +private fun SectionHeader(name: String) { Text( text = name, maxLines = 1, @@ -189,7 +206,7 @@ private fun ListHeader(name: String) { } @Composable -private fun Header(title: String, filter: TaskFilter) { +private fun TaskWidgetHeader(title: String, filter: TaskFilter, singleListId: Long?) { val context = LocalContext.current val open = when (filter) { is TaskFilter.Smart -> MainActivity.smartListIntent(context, filter.list) @@ -199,35 +216,16 @@ private fun Header(title: String, filter: TaskFilter) { is TaskFilter.OfLists -> filter.listIds.singleOrNull()?.let { MainActivity.listIntent(context, it) } ?: Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } - Row( - modifier = GlanceModifier.fillMaxWidth().padding(start = 8.dp), - verticalAlignment = Alignment.CenterVertically, + WidgetHeader( + title = title, + titleAction = actionStartActivity(open), ) { - Text( - text = title, - maxLines = 1, - style = TextStyle( - color = GlanceTheme.colors.primary, - fontSize = 16.sp, - fontWeight = FontWeight.Medium, - ), - modifier = GlanceModifier.defaultWeight().clickable(actionStartActivity(open)), + WidgetActionButton( + icon = ImageProvider(GlanceR.drawable.floret_ic_widget_add), + contentDescription = context.getString(R.string.new_task), + action = actionStartActivity(MainActivity.newTaskIntent(context, singleListId)), + style = WidgetActionStyle.TONAL, ) - Box( - modifier = GlanceModifier - .size(40.dp) - .cornerRadius(20.dp) - .background(GlanceTheme.colors.primaryContainer) - .clickable(actionStartActivity(MainActivity.newTaskIntent(context))), - contentAlignment = Alignment.Center, - ) { - Image( - provider = ImageProvider(R.drawable.ic_widget_add), - contentDescription = context.getString(R.string.new_task), - colorFilter = ColorFilter.tint(GlanceTheme.colors.onPrimaryContainer), - modifier = GlanceModifier.size(22.dp), - ) - } } } @@ -239,19 +237,19 @@ private fun TaskRow(row: WidgetTaskRow, use24Hour: Boolean) { MainActivity.taskIntent(context, row.taskId, row.occurrenceStart?.toEpochMilliseconds()), ) Row( - modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp), + modifier = GlanceModifier.fillMaxWidth().padding(vertical = 2.dp, horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = GlanceModifier .width(4.dp) - .height(32.dp) + .height(28.dp) .cornerRadius(2.dp) .background(ColorProvider(day = pastelize(row.color, false), night = pastelize(row.color, true))), ) {} Box( modifier = GlanceModifier - .size(40.dp) + .size(48.dp) .clickable( actionRunCallback( actionParametersOf( @@ -264,7 +262,7 @@ private fun TaskRow(row: WidgetTaskRow, use24Hour: Boolean) { contentAlignment = Alignment.Center, ) { Image( - provider = ImageProvider(R.drawable.ic_widget_checkbox), + provider = ImageProvider(GlanceR.drawable.floret_ic_widget_check), contentDescription = context.getString(R.string.widget_complete_task, title), colorFilter = ColorFilter.tint(GlanceTheme.colors.onSurfaceVariant), modifier = GlanceModifier.size(22.dp), @@ -294,19 +292,6 @@ private fun TaskRow(row: WidgetTaskRow, use24Hour: Boolean) { } } -@Composable -private fun Message(text: String) { - Box( - modifier = GlanceModifier.fillMaxSize().padding(16.dp), - contentAlignment = Alignment.Center, - ) { - Text( - text = text, - style = TextStyle(color = GlanceTheme.colors.onSurfaceVariant, fontSize = 14.sp), - ) - } -} - /** "Today · 14:00", "Tomorrow", or the compact date; `null` without a due date. */ private fun dueText(context: Context, row: WidgetTaskRow, use24Hour: Boolean): String? { val due = row.due ?: return null diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetConfigActivity.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetConfigActivity.kt index 64fc4cb..a82474e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetConfigActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetConfigActivity.kt @@ -46,10 +46,13 @@ import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme import de.jeanlucmakiola.floret.components.FullScreenPicker import de.jeanlucmakiola.floret.components.GroupedRow import de.jeanlucmakiola.floret.components.GroupedSectionHeader +import de.jeanlucmakiola.floret.components.OptionPicker import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SelectedCheck import de.jeanlucmakiola.floret.components.pastelize import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.glance.WidgetThemeMode import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.launch @@ -86,10 +89,14 @@ class TaskWidgetConfigActivity : ComponentActivity() { val lists by remember { listsFlow }.collectAsState(initial = emptyList()) var current by remember { mutableStateOf(null) } var groupByList by remember { mutableStateOf(false) } + var background by remember { mutableStateOf(WidgetBackground.SOLID) } + var themeOverride by remember { mutableStateOf(null) } LaunchedEffect(glanceId) { val state = getAppWidgetState(this@TaskWidgetConfigActivity, PreferencesGlanceStateDefinition, glanceId) current = parseWidgetFilter(state[WIDGET_FILTER_KEY]) groupByList = state[WIDGET_GROUP_BY_LIST_KEY] ?: false + background = parseWidgetBackground(state[WIDGET_BACKGROUND_KEY]) + themeOverride = parseWidgetThemeOverride(state[WIDGET_THEME_KEY]) } val dark = when (settings.themeMode) { ThemeMode.SYSTEM -> isSystemInDarkTheme() @@ -104,11 +111,18 @@ class TaskWidgetConfigActivity : ComponentActivity() { selected = current ?: DEFAULT_WIDGET_FILTER, groupByList = groupByList, onGroupByListChange = { groupByList = it }, + background = background, + onBackgroundChange = { background = it }, + themeOverride = themeOverride, + onThemeOverrideChange = { themeOverride = it }, onSave = { filter -> lifecycleScope.launch { updateAppWidgetState(this@TaskWidgetConfigActivity, glanceId) { it[WIDGET_FILTER_KEY] = filter.widgetStorageValue() it[WIDGET_GROUP_BY_LIST_KEY] = groupByList + it[WIDGET_BACKGROUND_KEY] = background.name + themeOverride?.let { mode -> it[WIDGET_THEME_KEY] = mode.name } + ?: it.remove(WIDGET_THEME_KEY) } TaskWidget().update(this@TaskWidgetConfigActivity, glanceId) setResult(RESULT_OK, resultIntent(appWidgetId)) @@ -132,9 +146,15 @@ private fun WidgetFilterPicker( dark: Boolean, groupByList: Boolean, onGroupByListChange: (Boolean) -> Unit, + background: WidgetBackground, + onBackgroundChange: (WidgetBackground) -> Unit, + themeOverride: WidgetThemeMode?, + onThemeOverrideChange: (WidgetThemeMode?) -> Unit, onSave: (TaskFilter) -> Unit, onDismiss: () -> Unit, ) { + var showBackgroundPicker by remember { mutableStateOf(false) } + var showThemePicker by remember { mutableStateOf(false) } // Smart lists and real lists are mutually exclusive; only real lists support // picking more than one. `selectedLists` empty + `selectedSmart` non-null is // a smart-list pick; the reverse (or both empty, before the stored filter @@ -202,6 +222,41 @@ private fun WidgetFilterPicker( ) } } + Spacer(Modifier.height(24.dp)) + GroupedRow( + title = stringResource(R.string.widget_config_background), + summary = stringResource(backgroundLabel(background)), + position = Position.Top, + onClick = { showBackgroundPicker = true }, + ) + GroupedRow( + title = stringResource(R.string.widget_config_theme), + summary = stringResource(themeOverrideLabel(themeOverride)), + position = Position.Bottom, + onClick = { showThemePicker = true }, + ) + } + + if (showBackgroundPicker) { + OptionPicker( + title = stringResource(R.string.widget_config_background), + options = WidgetBackground.entries, + selected = background, + label = { stringResource(backgroundLabel(it)) }, + summary = { stringResource(backgroundHint(it)) }, + onSelect = onBackgroundChange, + onDismiss = { showBackgroundPicker = false }, + ) + } + if (showThemePicker) { + OptionPicker( + title = stringResource(R.string.widget_config_theme), + options = listOf(null, WidgetThemeMode.LIGHT, WidgetThemeMode.DARK), + selected = themeOverride, + label = { stringResource(themeOverrideLabel(it)) }, + onSelect = onThemeOverrideChange, + onDismiss = { showThemePicker = false }, + ) } } @@ -211,3 +266,22 @@ internal fun smartListLabel(list: SmartList): Int = when (list) { SmartList.OVERDUE -> R.string.smart_overdue else -> R.string.smart_all } + +private fun backgroundLabel(background: WidgetBackground): Int = when (background) { + WidgetBackground.SOLID -> R.string.widget_config_background_solid + WidgetBackground.TINTED -> R.string.widget_config_background_tinted + WidgetBackground.TRANSPARENT -> R.string.widget_config_background_transparent +} + +private fun backgroundHint(background: WidgetBackground): Int = when (background) { + WidgetBackground.SOLID -> R.string.widget_config_background_solid_hint + WidgetBackground.TINTED -> R.string.widget_config_background_tinted_hint + WidgetBackground.TRANSPARENT -> R.string.widget_config_background_transparent_hint +} + +private fun themeOverrideLabel(mode: WidgetThemeMode?): Int = when (mode) { + null -> R.string.widget_config_theme_follow_app + WidgetThemeMode.LIGHT -> R.string.widget_config_theme_light + WidgetThemeMode.DARK -> R.string.widget_config_theme_dark + WidgetThemeMode.SYSTEM -> R.string.widget_config_theme_follow_app +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetReceiver.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetReceiver.kt index e0a0263..112fa3b 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetReceiver.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetReceiver.kt @@ -4,6 +4,7 @@ import android.appwidget.AppWidgetManager import android.content.Context import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver +import de.jeanlucmakiola.floret.glance.WidgetRollover /** Host-facing receiver for [TaskWidget]; also keeps the midnight rollover armed. */ class TaskWidgetReceiver : GlanceAppWidgetReceiver() { @@ -11,17 +12,17 @@ class TaskWidgetReceiver : GlanceAppWidgetReceiver() { override fun onEnabled(context: Context) { super.onEnabled(context) - WidgetRolloverScheduler.sync(context) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) } override fun onDisabled(context: Context) { super.onDisabled(context) - WidgetRolloverScheduler.sync(context) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) } /** Self-heal on the system's `updatePeriodMillis` wake-up, should the alarm have been dropped. */ override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { super.onUpdate(context, appWidgetManager, appWidgetIds) - WidgetRolloverScheduler.sync(context) + WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetUpdater.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetUpdater.kt index 7a3869f..c313b9c 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetUpdater.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/TaskWidgetUpdater.kt @@ -5,6 +5,7 @@ import androidx.glance.appwidget.updateAll import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.agendula.data.di.ApplicationScope import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource +import de.jeanlucmakiola.floret.glance.WidgetRollover import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview @@ -36,7 +37,9 @@ class TaskWidgetUpdater @Inject constructor( scope.launch(Dispatchers.IO) { requests.receiveAsFlow().debounce(DEBOUNCE_MILLIS).collect { redraw() } } - scope.launch(Dispatchers.IO) { runCatching { WidgetRolloverScheduler.sync(context) } } + scope.launch(Dispatchers.IO) { + runCatching { WidgetRollover.sync(context, WIDGET_RECEIVER_CLASSES, ::widgetRolloverPendingIntent) } + } // The process may have been started by a change it never heard about. requestRefresh() } @@ -48,7 +51,9 @@ class TaskWidgetUpdater @Inject constructor( private suspend fun redraw() { runCatching { - if (WidgetRolloverScheduler.hasPlacedWidgets(context)) TaskWidget().updateAll(context) + if (!WidgetRollover.hasPlacedWidgets(context, WIDGET_RECEIVER_CLASSES)) return@runCatching + TaskWidget().updateAll(context) + GlanceTaskWidget().updateAll(context) } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt index becd60b..a8f69c9 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetData.kt @@ -11,6 +11,10 @@ import de.jeanlucmakiola.agendula.domain.Task import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.calendarDate import de.jeanlucmakiola.agendula.domain.comparator +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.components.positionOf +import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.glance.WidgetThemeMode import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.combine @@ -25,16 +29,38 @@ internal val WIDGET_FILTER_KEY = stringPreferencesKey("task_filter") /** Per-instance Glance state key: group a multi-list widget's rows under list headers. */ internal val WIDGET_GROUP_BY_LIST_KEY = booleanPreferencesKey("group_by_list") +/** Per-instance Glance state key holding the widget's [WidgetBackground] ([name]); unset = [WidgetBackground.SOLID]. */ +internal val WIDGET_BACKGROUND_KEY = stringPreferencesKey("widget_background") + +/** Per-instance Glance state key holding a [WidgetThemeMode] override; unset = follow the app's own theme setting. */ +internal val WIDGET_THEME_KEY = stringPreferencesKey("widget_theme") + internal val DEFAULT_WIDGET_FILTER: TaskFilter = TaskFilter.Smart(SmartList.TODAY) +internal fun parseWidgetBackground(raw: String?): WidgetBackground = + raw?.let { runCatching { WidgetBackground.valueOf(it) }.getOrNull() } ?: WidgetBackground.SOLID + +/** `null` means "follow the app's own theme setting" — resolved by the caller against [TaskWidgetData.Ready.themeMode]. */ +internal fun parseWidgetThemeOverride(raw: String?): WidgetThemeMode? = + raw?.let { runCatching { WidgetThemeMode.valueOf(it) }.getOrNull() } + +internal fun TaskWidgetData.Ready.effectiveThemeMode(override: WidgetThemeMode?): WidgetThemeMode = + override ?: when (themeMode) { + ThemeMode.SYSTEM -> WidgetThemeMode.SYSTEM + ThemeMode.LIGHT -> WidgetThemeMode.LIGHT + ThemeMode.DARK -> WidgetThemeMode.DARK + } + /** The smart lists a widget can show, in picker order. */ internal val WIDGET_SMART_LISTS = listOf(SmartList.TODAY, SmartList.UPCOMING, SmartList.OVERDUE, SmartList.ALL) /** * Upper bound on rows, so the serialized RemoteViews stays well inside the - * binder transaction limit however long the list is. + * binder transaction limit however long the list is. Lower than the old flat + * list's 60: each row is now wrapped in its own tonal container, so the + * per-row view count is higher for the same visual density (calendula#214). */ -internal const val MAX_WIDGET_ROWS = 60 +internal const val MAX_WIDGET_ROWS = 40 internal fun TaskFilter.widgetStorageValue(): String = when (this) { is TaskFilter.OfList -> "list:$listId" @@ -108,9 +134,67 @@ sealed interface TaskWidgetData { is TaskFilter.OfLists -> filter.listIds.singleOrNull()?.let(listNames::get) is TaskFilter.Smart -> null } + + /** The one list's id, when [filter] names exactly one real list — seeds a widget's add button. */ + val singleListId: Long? = when (filter) { + is TaskFilter.OfList -> filter.listId + is TaskFilter.OfLists -> filter.listIds.singleOrNull() + is TaskFilter.Smart -> null + } + + val overdueCount: Int = rows.count { it.isOverdue } } } +/** A run of rows in the widget's list: a task (with its [Position] within the run's card), or a run's header. */ +internal sealed interface WidgetSection { + data class Header(val key: String, val name: String) : WidgetSection + data class TaskItem(val row: WidgetTaskRow, val position: Position) : WidgetSection +} + +/** One headed run: its header's stable [key] and display [name], and the rows under it. */ +private data class WidgetRun(val key: String, val name: String, val rows: List) + +/** Each [WidgetRun] as its own [WidgetSection.Header] followed by its rows, positioned within that run's card. */ +private fun headedRuns(runs: List): List = + runs.flatMap { run -> + listOf(WidgetSection.Header(run.key, run.name)) + + run.rows.mapIndexed { index, row -> WidgetSection.TaskItem(row, positionOf(index, run.rows.size)) } + } + +/** + * [rows] split into headed runs: one per list when [groupByList] is on + * (already sorted that way by [widgetRows]), otherwise one per [DueKind] + * bucket — "Overdue" / "Today" / "Tomorrow" / "Later" / "No date" — in that + * fixed order, since [rows] isn't due-sorted. Each run becomes one + * [WidgetGroupedRow][de.jeanlucmakiola.floret.glance.WidgetGroupedRow] card. + */ +internal fun widgetSections( + rows: List, + groupByList: Boolean, + listNames: Map, + dueBucketLabel: (DueKind?) -> String, +): List { + if (groupByList) { + val runs = mutableListOf() + var current: MutableList? = null + for (row in rows) { + if (current == null || runs.last().key != "list:${row.listId}") { + current = mutableListOf() + runs += WidgetRun("list:${row.listId}", listNames[row.listId].orEmpty(), current) + } + current.add(row) + } + return headedRuns(runs) + } + val buckets = rows.groupBy { it.dueKind } + val runs = DueKind.entries.plus(null).mapNotNull { kind -> + buckets[kind]?.takeIf { it.isNotEmpty() } + ?.let { WidgetRun("due:${kind?.name.orEmpty()}", dueBucketLabel(kind), it) } + } + return headedRuns(runs) +} + /** * Open rows for [tasks], sorted the way the app sorts them, then grouped by list * when [groupByList] is on (stable, so each list's own order survives). A diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverScheduler.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverScheduler.kt deleted file mode 100644 index 2c646c4..0000000 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverScheduler.kt +++ /dev/null @@ -1,83 +0,0 @@ -package de.jeanlucmakiola.agendula.widget - -import android.app.AlarmManager -import android.app.PendingIntent -import android.appwidget.AppWidgetManager -import android.content.ComponentName -import android.content.Context -import android.content.Intent -import androidx.core.content.getSystemService -import kotlinx.datetime.DateTimeUnit -import kotlinx.datetime.TimeZone -import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.plus -import kotlinx.datetime.toLocalDateTime -import kotlin.time.Clock -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.seconds -import kotlin.time.Instant - -/** - * The app's own wake-up for the next local midnight, so "Today" on the widget - * flips over on the day boundary. `ACTION_DATE_CHANGED` isn't delivered to - * manifest receivers since Android 8, which is why this exists. - * - * One inexact alarm at a time, re-armed by every firing: `setAndAllowWhileIdle` - * needs no permission and survives doze, and a rollover a few minutes late is - * invisible on a sleeping screen. - */ -object WidgetRolloverScheduler { - - /** Fire just after midnight, so an early delivery doesn't still read the old date. */ - internal val ROLLOVER_SLACK = 5.seconds - - /** Arm the next rollover, or cancel it when no widget is placed. Idempotent. */ - fun sync(context: Context) { - val appContext = context.applicationContext - val alarmManager = appContext.getSystemService() ?: return - val pendingIntent = rolloverPendingIntent(appContext) - if (!hasPlacedWidgets(appContext)) { - alarmManager.cancel(pendingIntent) - return - } - val triggerAt = nextRolloverAt(Clock.System.now(), TimeZone.currentSystemDefault()) - alarmManager.setAndAllowWhileIdle( - AlarmManager.RTC_WAKEUP, triggerAt.toEpochMilliseconds(), pendingIntent, - ) - } - - /** - * The instant just after the next local midnight following [now] in [zone]. - * Uses the actual start of day, so it holds where DST skips midnight or a - * date-line move skips a whole date. - */ - fun nextRolloverAt(now: Instant, zone: TimeZone): Instant { - val date = now.toLocalDateTime(zone).date - var days = 1 - while (days <= MAX_LOOKAHEAD_DAYS) { - val candidate = date.plus(days, DateTimeUnit.DAY).atStartOfDayIn(zone) + ROLLOVER_SLACK - if (candidate > now) return candidate - days++ - } - // Unreachable for any real zone; an hour rather than the slack so it can't loop. - return now + 1.hours - } - - fun hasPlacedWidgets(context: Context): Boolean { - val manager = AppWidgetManager.getInstance(context) ?: return false - return manager.getAppWidgetIds(ComponentName(context, TaskWidgetReceiver::class.java)).isNotEmpty() - } - - private fun rolloverPendingIntent(context: Context): PendingIntent = - PendingIntent.getBroadcast( - context, - ROLLOVER_REQUEST_CODE, - Intent(context, WidgetUpdateReceiver::class.java) - .setAction(WidgetUpdateReceiver.ACTION_ROLLOVER), - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, - ) - - private const val ROLLOVER_REQUEST_CODE = 0x0DA1 - - private const val MAX_LOOKAHEAD_DAYS = 3 -} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetTheme.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetTheme.kt deleted file mode 100644 index 5dcc3d7..0000000 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetTheme.kt +++ /dev/null @@ -1,39 +0,0 @@ -package de.jeanlucmakiola.agendula.widget - -import android.os.Build -import androidx.compose.material3.dynamicDarkColorScheme -import androidx.compose.material3.dynamicLightColorScheme -import androidx.compose.runtime.Composable -import androidx.glance.GlanceTheme -import androidx.glance.LocalContext -import androidx.glance.material3.ColorProviders -import de.jeanlucmakiola.agendula.data.prefs.ThemeMode -import de.jeanlucmakiola.agendula.ui.theme.AgendulaDarkFallback -import de.jeanlucmakiola.agendula.ui.theme.AgendulaLightFallback - -private val AgendulaGlanceColors = ColorProviders( - light = AgendulaLightFallback, - dark = AgendulaDarkFallback, -) - -/** - * Glance counterpart of `AgendulaTheme`: Material You on API 31+ when dynamic - * colour is on, the brand fallback schemes otherwise. On [ThemeMode.SYSTEM] it - * draws only from colour-role tokens, so light/dark follows the system without a - * redraw; a forced light or dark theme pins one scheme for both. - */ -@Composable -fun AgendulaGlanceTheme(dynamicColor: Boolean, themeMode: ThemeMode, content: @Composable () -> Unit) { - val dynamic = dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S - val context = LocalContext.current - val colors = when (themeMode) { - ThemeMode.SYSTEM -> if (dynamic) GlanceTheme.colors else AgendulaGlanceColors - ThemeMode.LIGHT -> ColorProviders( - if (dynamic) dynamicLightColorScheme(context) else AgendulaLightFallback, - ) - ThemeMode.DARK -> ColorProviders( - if (dynamic) dynamicDarkColorScheme(context) else AgendulaDarkFallback, - ) - } - GlanceTheme(colors = colors, content = content) -} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetUpdateReceiver.kt b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetUpdateReceiver.kt index ceb1cab..af0d21e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetUpdateReceiver.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/widget/WidgetUpdateReceiver.kt @@ -1,56 +1,41 @@ package de.jeanlucmakiola.agendula.widget -import android.content.BroadcastReceiver +import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.glance.appwidget.updateAll -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.launch +import de.jeanlucmakiola.floret.glance.FloretWidgetUpdateReceiver +import de.jeanlucmakiola.floret.glance.WidgetRollover + +/** Both home-screen widgets' receiver classes — the set [WidgetRollover] checks for placed instances. */ +internal val WIDGET_RECEIVER_CLASSES: List> = + listOf(TaskWidgetReceiver::class.java, GlanceTaskWidgetReceiver::class.java) + +internal const val ACTION_WIDGET_ROLLOVER = "de.jeanlucmakiola.agendula.widget.ROLLOVER" + +private const val ROLLOVER_REQUEST_CODE = 0x0DA1 + +internal fun widgetRolloverPendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast( + context, + ROLLOVER_REQUEST_CODE, + Intent(context, WidgetUpdateReceiver::class.java).setAction(ACTION_WIDGET_ROLLOVER), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, +) /** - * Redraws the task widget when its day or its language goes stale, and keeps the - * midnight rollover armed. Task data changes don't come through here — see + * Redraws both widgets when their day or language goes stale, and keeps the + * midnight rollover armed — the app-specific glue around + * [FloretWidgetUpdateReceiver]. Task data changes don't come through here — see * [TaskWidgetUpdater]. - * - * Exported for the system broadcasts; an extra redraw from another app is harmless. */ -class WidgetUpdateReceiver : BroadcastReceiver() { - override fun onReceive(context: Context, intent: Intent) { - if (intent.action !in HANDLED_ACTIONS) return - val appContext = context.applicationContext - val rearm = intent.action in REARM_ACTIONS - // The host redraws the widget itself after these two. - val redraw = intent.action !in REARM_ONLY_ACTIONS - val pending = goAsync() - CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { - try { - if (rearm) WidgetRolloverScheduler.sync(appContext) - if (redraw && WidgetRolloverScheduler.hasPlacedWidgets(appContext)) { - TaskWidget().updateAll(appContext) - } - } finally { - pending.finish() - } - } - } +class WidgetUpdateReceiver : FloretWidgetUpdateReceiver() { + override val rolloverAction = ACTION_WIDGET_ROLLOVER + override val widgetReceiverClasses = WIDGET_RECEIVER_CLASSES - companion object { - const val ACTION_ROLLOVER = "de.jeanlucmakiola.agendula.widget.ROLLOVER" + override fun rolloverPendingIntent(context: Context): PendingIntent = widgetRolloverPendingIntent(context) - private val REARM_ONLY_ACTIONS = setOf( - Intent.ACTION_BOOT_COMPLETED, - Intent.ACTION_MY_PACKAGE_REPLACED, - ) - - internal val REARM_ACTIONS = REARM_ONLY_ACTIONS + setOf( - ACTION_ROLLOVER, - Intent.ACTION_TIME_CHANGED, - Intent.ACTION_TIMEZONE_CHANGED, - Intent.ACTION_DATE_CHANGED, - ) - - internal val HANDLED_ACTIONS = REARM_ACTIONS + Intent.ACTION_LOCALE_CHANGED + override suspend fun redraw(context: Context) { + TaskWidget().updateAll(context) + GlanceTaskWidget().updateAll(context) } } diff --git a/app/src/main/res/drawable/ic_widget_add.xml b/app/src/main/res/drawable/ic_widget_add.xml deleted file mode 100644 index 4797a8b..0000000 --- a/app/src/main/res/drawable/ic_widget_add.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/app/src/main/res/drawable/ic_widget_checkbox.xml b/app/src/main/res/drawable/ic_widget_checkbox.xml deleted file mode 100644 index 8ffa575..0000000 --- a/app/src/main/res/drawable/ic_widget_checkbox.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - diff --git a/app/src/main/res/layout/widget_preview_glance.xml b/app/src/main/res/layout/widget_preview_glance.xml new file mode 100644 index 0000000..9395daf --- /dev/null +++ b/app/src/main/res/layout/widget_preview_glance.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/widget_preview_tasks.xml b/app/src/main/res/layout/widget_preview_tasks.xml index d9d14bc..8836ce2 100644 --- a/app/src/main/res/layout/widget_preview_tasks.xml +++ b/app/src/main/res/layout/widget_preview_tasks.xml @@ -30,7 +30,7 @@ android:padding="9dp" android:contentDescription="@null" android:background="@drawable/preview_add_bg" - android:src="@drawable/ic_widget_add" + android:src="@drawable/floret_ic_widget_add" android:tint="@color/widget_preview_on_primary_container" /> @@ -52,7 +52,7 @@ android:layout_marginStart="9dp" android:layout_marginEnd="9dp" android:contentDescription="@null" - android:src="@drawable/ic_widget_checkbox" + android:src="@drawable/floret_ic_widget_check" android:tint="@color/widget_preview_variant" /> Smart lists Group by list Show each list\'s tasks under its own heading + Overdue + Later + No date + Background + Solid + Fills the widget with the theme\'s surface colour + Tinted + A softer, tonal fill + Transparent + No fill — tasks stay readable in their own containers + Theme + Follow app + Light + Dark + At a glance + Your next task, or a quick way to add one + Nothing due today + + %1$d overdue + %1$d overdue + diff --git a/app/src/main/res/xml/appwidget_info_glance.xml b/app/src/main/res/xml/appwidget_info_glance.xml new file mode 100644 index 0000000..8aa1523 --- /dev/null +++ b/app/src/main/res/xml/appwidget_info_glance.xml @@ -0,0 +1,15 @@ + + diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetDataTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetDataTest.kt index 61dc4c7..2156df3 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetDataTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetDataTest.kt @@ -1,12 +1,16 @@ package de.jeanlucmakiola.agendula.widget import com.google.common.truth.Truth.assertThat +import de.jeanlucmakiola.agendula.data.prefs.ThemeMode import de.jeanlucmakiola.agendula.domain.SmartList import de.jeanlucmakiola.agendula.domain.TaskFilter import de.jeanlucmakiola.agendula.domain.TaskSorting import de.jeanlucmakiola.agendula.domain.TaskStatus import de.jeanlucmakiola.agendula.domain.allDayInstantOf import de.jeanlucmakiola.agendula.domain.testTask +import de.jeanlucmakiola.floret.components.Position +import de.jeanlucmakiola.floret.glance.WidgetBackground +import de.jeanlucmakiola.floret.glance.WidgetThemeMode import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.LocalDateTime @@ -132,4 +136,92 @@ class WidgetDataTest { ) assertThat(rows.map { it.title }).containsExactly("a-soon", "a-later", "b-later").inOrder() } + + // --- sections ---------------------------------------------------------- + + private fun row(id: Long, listId: Long = 1, dueKind: DueKind? = null, overdue: Boolean = false) = WidgetTaskRow( + taskId = id, + listId = listId, + occurrenceStart = null, + title = "t$id", + due = null, + isAllDay = false, + dueKind = dueKind, + isOverdue = overdue, + color = 0, + ) + + @Test + fun `due buckets appear in a fixed order and skip empty ones`() { + val rows = listOf( + row(1, dueKind = DueKind.LATER), + row(2, dueKind = DueKind.PAST, overdue = true), + row(3, dueKind = DueKind.TODAY), + ) + val sections = widgetSections(rows, groupByList = false, listNames = emptyMap()) { it?.name ?: "none" } + assertThat(sections.filterIsInstance().map { it.name }) + .containsExactly("PAST", "TODAY", "LATER").inOrder() + } + + @Test + fun `a bucket of one row is Alone, a bucket of several has Top Middle Bottom`() { + val rows = listOf(row(1, dueKind = DueKind.TODAY), row(2, dueKind = DueKind.TODAY), row(3, dueKind = DueKind.TODAY)) + val sections = widgetSections(rows, groupByList = false, listNames = emptyMap()) { "x" } + val positions = sections.filterIsInstance().map { it.position } + assertThat(positions).containsExactly(Position.Top, Position.Middle, Position.Bottom).inOrder() + } + + @Test + fun `grouping by list keeps the widgetRows order and headers each run once`() { + val rows = listOf(row(1, listId = 1), row(2, listId = 1), row(3, listId = 2)) + val sections = widgetSections(rows, groupByList = true, listNames = mapOf(1L to "Alpha", 2L to "Beta")) { "x" } + assertThat(sections.filterIsInstance().map { it.name }).containsExactly("Alpha", "Beta").inOrder() + assertThat(sections.filterIsInstance().map { it.row.taskId }).containsExactly(1L, 2L, 3L).inOrder() + } + + // --- per-widget background / theme -------------------------------------- + + @Test + fun `an unset background is Solid, and round-trips`() { + assertThat(parseWidgetBackground(null)).isEqualTo(WidgetBackground.SOLID) + WidgetBackground.entries.forEach { assertThat(parseWidgetBackground(it.name)).isEqualTo(it) } + assertThat(parseWidgetBackground("garbage")).isEqualTo(WidgetBackground.SOLID) + } + + @Test + fun `an unset theme override follows the app, Light and Dark pin regardless`() { + assertThat(parseWidgetThemeOverride(null)).isNull() + assertThat(parseWidgetThemeOverride("garbage")).isNull() + assertThat(parseWidgetThemeOverride("LIGHT")).isEqualTo(WidgetThemeMode.LIGHT) + assertThat(parseWidgetThemeOverride("DARK")).isEqualTo(WidgetThemeMode.DARK) + } + + private fun readyWithTheme(appTheme: ThemeMode) = TaskWidgetData.Ready( + filter = DEFAULT_WIDGET_FILTER, + listNames = emptyMap(), + rows = emptyList(), + groupByList = false, + dynamicColor = true, + themeMode = appTheme, + use24Hour = true, + ) + + @Test + fun `no override resolves to whatever the app's own theme means`() { + assertThat(readyWithTheme(ThemeMode.DARK).effectiveThemeMode(null)).isEqualTo(WidgetThemeMode.DARK) + assertThat(readyWithTheme(ThemeMode.SYSTEM).effectiveThemeMode(null)).isEqualTo(WidgetThemeMode.SYSTEM) + } + + @Test + fun `an override wins over the app's own theme`() { + assertThat(readyWithTheme(ThemeMode.DARK).effectiveThemeMode(WidgetThemeMode.LIGHT)).isEqualTo(WidgetThemeMode.LIGHT) + } + + @Test + fun `overdue count only counts overdue rows`() { + val ready = readyWithTheme(ThemeMode.SYSTEM).copy( + rows = listOf(row(1, overdue = true), row(2, overdue = false), row(3, overdue = true)), + ) + assertThat(ready.overdueCount).isEqualTo(2) + } } diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverSchedulerTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverSchedulerTest.kt deleted file mode 100644 index 9769a0a..0000000 --- a/app/src/test/java/de/jeanlucmakiola/agendula/widget/WidgetRolloverSchedulerTest.kt +++ /dev/null @@ -1,179 +0,0 @@ -package de.jeanlucmakiola.agendula.widget - -import android.content.Intent -import com.google.common.truth.Truth.assertThat -import kotlinx.datetime.LocalDate -import kotlinx.datetime.LocalDateTime -import kotlinx.datetime.TimeZone -import kotlinx.datetime.atStartOfDayIn -import kotlinx.datetime.toInstant -import kotlinx.datetime.toLocalDateTime -import org.junit.jupiter.api.Test -import kotlin.time.Duration -import kotlin.time.Duration.Companion.hours -import kotlin.time.Duration.Companion.minutes -import kotlin.time.Instant - -/** The "when is the next local midnight" arithmetic, especially where midnight is not 00:00. */ -class WidgetRolloverSchedulerTest { - - private val berlin = TimeZone.of("Europe/Berlin") - - private fun at(local: String, zone: TimeZone): Instant = - LocalDateTime.parse(local).toInstant(zone) - - private fun nextRollover(local: String, zone: TimeZone = berlin): Instant = - WidgetRolloverScheduler.nextRolloverAt(at(local, zone), zone) - - // --- the ordinary day ---------------------------------------------------- - - @Test - fun `midday rolls over at the coming midnight`() { - val next = nextRollover("2026-08-27T12:00:00") - assertThat(next).isEqualTo(at("2026-08-28T00:00:05", berlin)) - } - - @Test - fun `a second before midnight still targets tonight, not tomorrow night`() { - val next = nextRollover("2026-08-27T23:59:59") - assertThat(next).isEqualTo(at("2026-08-28T00:00:05", berlin)) - } - - @Test - fun `at midnight exactly the target is the next day, never the current instant`() { - // Re-arming after a firing must move a whole day on, or the widget wakes - // itself in a tight loop. - val now = at("2026-08-28T00:00:00", berlin) - val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin) - assertThat(next).isEqualTo(at("2026-08-29T00:00:05", berlin)) - assertThat(next - now).isGreaterThan(Duration.ZERO) - } - - @Test - fun `re-arming from the slack instant itself moves a full day on`() { - // What actually happens in practice: the receiver runs at midnight + slack. - val now = at("2026-08-28T00:00:05", berlin) - assertThat(WidgetRolloverScheduler.nextRolloverAt(now, berlin)) - .isEqualTo(at("2026-08-29T00:00:05", berlin)) - } - - @Test - fun `the result is always in the future for every minute of a day`() { - val zone = berlin - // Spans Berlin's 2024 spring-forward: the likeliest source of a target - // in the past, i.e. an alarm that fires immediately, forever. - var probe = LocalDateTime.parse("2024-03-29T00:00:00").toInstant(zone) - val end = LocalDateTime.parse("2024-04-01T00:00:00").toInstant(zone) - while (probe < end) { - assertThat(WidgetRolloverScheduler.nextRolloverAt(probe, zone)).isGreaterThan(probe) - probe += 1.minutes - } - } - - // --- daylight saving ----------------------------------------------------- - - @Test - fun `spring forward keeps the rollover one day away, not one hour short`() { - // Berlin skipped 02:00-03:00 on 31 March 2024, so that day was 23h long. - // A rollover computed as "now + 24h" would land at 01:00 on 1 April. - val now = at("2024-03-30T12:00:00", berlin) - val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin) - assertThat(next).isEqualTo(at("2024-03-31T00:00:05", berlin)) - assertThat(next - now).isLessThan(24.hours) - } - - @Test - fun `fall back does not overshoot into the repeated hour`() { - // Berlin repeated 02:00-03:00 on 27 October 2024: a 25h day, so - // "now + 24h" would land at 23:00 on the 26th and never roll over. - val now = at("2024-10-26T12:00:00", berlin) - val next = WidgetRolloverScheduler.nextRolloverAt(now, berlin) - assertThat(next).isEqualTo(at("2024-10-27T00:00:05", berlin)) - assertThat(next.toLocalDateTime(berlin).date).isEqualTo(LocalDate.parse("2024-10-27")) - } - - @Test - fun `a zone that repeats midnight takes the first start of day`() { - // Sao Paulo used to end DST by moving 00:00 back to 23:00, so the day - // began twice. Pinned as the accepted trade: the widget runs an hour - // ahead until the next redraw. No live zone does this since 2019. - val saoPaulo = TimeZone.of("America/Sao_Paulo") - val next = WidgetRolloverScheduler.nextRolloverAt( - at("2018-02-16T12:00:00", saoPaulo), saoPaulo, - ) - val local = next.toLocalDateTime(saoPaulo) - assertThat(local.date).isEqualTo(LocalDate.parse("2018-02-17")) - assertThat(local.hour).isEqualTo(0) - } - - @Test - fun `a zone where midnight does not exist rolls over at the real start of day`() { - // Cuba starts DST at 00:00, so 11 March 2018 began at 01:00 in Havana. - // Targeting a literal 00:00 there would arm an instant on the wrong day. - val havana = TimeZone.of("America/Havana") - val next = WidgetRolloverScheduler.nextRolloverAt(at("2018-03-10T12:00:00", havana), havana) - val local = next.toLocalDateTime(havana) - assertThat(local.date).isEqualTo(LocalDate.parse("2018-03-11")) - assertThat(local.hour).isEqualTo(1) - assertThat(local.minute).isEqualTo(0) - // And it is genuinely the first instant of that date, not a guess. - assertThat(next).isEqualTo( - LocalDate.parse("2018-03-11").atStartOfDayIn(havana) + - WidgetRolloverScheduler.ROLLOVER_SLACK, - ) - } - - // --- timezone changes ---------------------------------------------------- - - @Test - fun `the same instant rolls over at different times in different zones`() { - // TIMEZONE_CHANGED must re-arm to the new local midnight: the arithmetic - // follows the zone, not a cached offset. - val instant = at("2026-08-27T12:00:00", berlin) - val tokyo = TimeZone.of("Asia/Tokyo") - val berlinNext = WidgetRolloverScheduler.nextRolloverAt(instant, berlin) - val tokyoNext = WidgetRolloverScheduler.nextRolloverAt(instant, tokyo) - assertThat(tokyoNext).isNotEqualTo(berlinNext) - assertThat(tokyoNext).isLessThan(berlinNext) - assertThat(tokyoNext.toLocalDateTime(tokyo).hour).isEqualTo(0) - } - - @Test - fun `a half-hour offset zone still lands on its own midnight`() { - val kathmandu = TimeZone.of("Asia/Kathmandu") - val next = WidgetRolloverScheduler.nextRolloverAt( - at("2026-08-27T12:00:00", kathmandu), kathmandu, - ) - val local = next.toLocalDateTime(kathmandu) - assertThat(local.date.toString()).isEqualTo("2026-08-28") - assertThat(local.hour).isEqualTo(0) - } - - // --- the wiring ---------------------------------------------------------- - - @Test - fun `the receiver actually handles the action the alarm is sent with`() { - // The single point where the whole fix would die silently: the alarm - // fires, the receiver drops it on the action guard, nothing redraws. - assertThat(WidgetUpdateReceiver.HANDLED_ACTIONS) - .contains(WidgetUpdateReceiver.ACTION_ROLLOVER) - } - - @Test - fun `a language change redraws without re-arming`() { - assertThat(WidgetUpdateReceiver.HANDLED_ACTIONS).contains(Intent.ACTION_LOCALE_CHANGED) - assertThat(WidgetUpdateReceiver.REARM_ACTIONS).doesNotContain(Intent.ACTION_LOCALE_CHANGED) - } - - @Test - fun `everything that loses the alarm re-arms it`() { - assertThat(WidgetUpdateReceiver.REARM_ACTIONS).containsAtLeast( - WidgetUpdateReceiver.ACTION_ROLLOVER, - Intent.ACTION_BOOT_COMPLETED, - Intent.ACTION_MY_PACKAGE_REPLACED, - Intent.ACTION_TIME_CHANGED, - Intent.ACTION_TIMEZONE_CHANGED, - Intent.ACTION_DATE_CHANGED, - ) - } -} diff --git a/floret-kit b/floret-kit index db4be68..836d8e6 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit db4be68dad7d5aff2ca16bddfc5cb22fb96ea447 +Subproject commit 836d8e6be0ed5cd44f5f550dc127247ee44dd601 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 407694a..263000f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -177,6 +177,7 @@ floret-core-locale = { group = "de.jeanlucmakiola.floret", name = "core-locale" floret-core-crash = { group = "de.jeanlucmakiola.floret", name = "core-crash" } floret-identity = { group = "de.jeanlucmakiola.floret", name = "identity" } floret-components = { group = "de.jeanlucmakiola.floret", name = "components" } +floret-glance = { group = "de.jeanlucmakiola.floret", name = "glance" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }