diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt b/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt index 4eefc0b..4c44da5 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/MainActivity.kt @@ -43,6 +43,8 @@ import de.jeanlucmakiola.floret.crash.submitCrashReport import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import javax.inject.Inject /** @@ -67,6 +69,9 @@ class MainActivity : ComponentActivity() { // A notification tap's destination, handed to the nav host and cleared once taken. private var navRequest by mutableStateOf(null) + // A request arrived after launch, so the start destination mustn't land on top of it. + private var navigatedSinceLaunch = false + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -82,7 +87,12 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() // Every view is a launcher shortcut, kept up with the views as they change. lifecycleScope.launch { - settingsPrefs.views.collect { views -> AppShortcuts.publish(this@MainActivity, views) } + settingsPrefs.views + .map { views -> views.map { Triple(it.id, it.name, it.icon) } to views } + .distinctUntilChanged { a, b -> a.first == b.first } + .collect { (_, views) -> + withContext(Dispatchers.Default) { AppShortcuts.publish(this@MainActivity, views) } + } } // The stored setting, never the view model's placeholder: a night mode @@ -106,7 +116,8 @@ class MainActivity : ComponentActivity() { is TaskFilter.Saved -> NavRequest.OpenFilter(filter.id) else -> null } - if (push != null && navRequest == null) navRequest = push + // Not over something the user, or another intent, opened meanwhile. + if (push != null && !navigatedSinceLaunch) navRequest = push } } } @@ -163,6 +174,7 @@ class MainActivity : ComponentActivity() { super.onNewIntent(intent) setIntent(intent) navRequestOf(intent)?.let { + navigatedSinceLaunch = true switchViewFor(it) navRequest = it } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt index f55aa9e..68c59cc 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/SettingsPrefs.kt @@ -638,18 +638,24 @@ class SettingsPrefs @Inject constructor( /** * Stores [view] in place of the one with its id, or after the others; an id of - * 0 makes a new one. Returns the view's id. Ids are never handed out twice, so + * 0 makes a new one. Returns the view's id, or `null` when the views are stored + * by another version and can't be written. Ids are never handed out twice, so * a launcher shortcut to a deleted view can't open a newer one. */ - suspend fun saveView(view: View): Long { - var id = view.id + suspend fun saveView(view: View): Long? { + var id: Long? = view.id dataStore.edit { p -> - if (id <= 0) { - val taken = ViewCodec.decode(p[VIEWS], modeOf(p).name).maxOfOrNull { it.id } ?: View.HOME_ID - id = maxOf(p[VIEW_NEXT_ID] ?: 0L, taken + 1) - p[VIEW_NEXT_ID] = id + 1 + if (!ViewCodec.writable(p[VIEWS])) { + id = null + return@edit } - p[VIEWS] = ViewCodec.upsert(p[VIEWS], view.copy(id = id), modeOf(p).name) + if (view.id <= 0) { + val taken = maxOf(ViewCodec.maxId(p[VIEWS]) ?: 0L, View.HOME_ID) + val next = maxOf(p[VIEW_NEXT_ID] ?: 0L, taken + 1) + p[VIEW_NEXT_ID] = next + 1 + id = next + } + p[VIEWS] = ViewCodec.upsert(p[VIEWS], view.copy(id = id!!), modeOf(p).name) } return id } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt index 0596f6e..5f1d82d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/prefs/ViewCodec.kt @@ -101,6 +101,12 @@ internal object ViewCodec { return layout.copy(chunks = written).text() } + /** Whether a layout stored as [raw] can be written: nothing stored, or this version's. */ + fun writable(raw: String?): Boolean = Layout.of(raw) != null + + /** The highest view id in [raw], read from every view line, also one that doesn't read otherwise. */ + fun maxId(raw: String?): Long? = Layout.of(raw)?.chunks?.mapNotNull { it.id }?.maxOrNull() + /** [raw] without the view [id]; another version's layout is returned as it is. */ fun remove(raw: String?, id: Long): String { val layout = Layout.of(raw) ?: return raw.orEmpty() diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 1c7cdbd..5c97c2a 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -102,7 +102,7 @@ import de.jeanlucmakiola.agendula.ui.tasklist.TaskListViewModel import de.jeanlucmakiola.agendula.ui.tasklist.UndoReceipt import de.jeanlucmakiola.agendula.ui.tasklist.rememberTaskRows import de.jeanlucmakiola.agendula.ui.tasklist.taskRows -import de.jeanlucmakiola.agendula.ui.views.ScopeInputChip +import de.jeanlucmakiola.agendula.ui.views.ScopeChipRow import de.jeanlucmakiola.agendula.ui.views.ViewSwitcher import de.jeanlucmakiola.agendula.ui.views.viewName import de.jeanlucmakiola.floret.components.IconInfoCard @@ -137,7 +137,7 @@ import java.time.ZoneId fun ListsScreen( onOpenFilter: (TaskFilter, Long?) -> Unit, onOpenTask: (Task) -> Unit, - onNewTask: () -> Unit, + onNewTask: (Long?) -> Unit, onOpenSettings: () -> Unit, onManageViews: () -> Unit, onEditView: (Long) -> Unit, @@ -217,7 +217,7 @@ fun ListsScreen( // The FAB would otherwise float over the search results. if (!searchActive) { ExtendedFloatingActionButton( - onClick = if (noLists) ({ newList = true }) else onNewTask, + onClick = if (noLists) ({ newList = true }) else ({ onNewTask(content?.newTaskList) }), icon = { Icon(Icons.Rounded.Add, contentDescription = null) }, text = { Text(stringResource(if (noLists) R.string.list_add else R.string.new_task)) @@ -286,23 +286,18 @@ fun ListsScreen( .height(SnackChipHeight), contentAlignment = Alignment.CenterStart, ) { - if (undo != null && blockModel != null) { - SnackChip( - visible = true, - message = stringResource( - if (undo is UndoReceipt.Completed) R.string.task_completed else R.string.task_deleted, - ), - actionLabel = stringResource(R.string.undo), - onAction = blockModel::undo, - ) - } else { - SnackChip( - visible = writeFailure != null, - message = stringResource( - listWriteFailureMessage(writeFailure ?: ListWriteFailure.SAVE), - ), - ) - } + // One chip: a refused list write, else the task block's undo. + val failure = writeFailure + SnackChip( + visible = failure != null || undo != null, + message = when { + failure != null -> stringResource(listWriteFailureMessage(failure)) + undo is UndoReceipt.Completed -> stringResource(R.string.task_completed) + else -> stringResource(R.string.task_deleted) + }, + actionLabel = if (failure == null && undo != null) stringResource(R.string.undo) else null, + onAction = if (failure == null && undo != null) blockModel?.let { it::undo } else null, + ) } } } @@ -332,6 +327,8 @@ fun ListsScreen( title = stringResource(R.string.view_choose_source), state = content, withSmartLists = true, + // A progress block shows Today only, for now. + todayOnly = choosingBlock.type == BlockType.PROGRESS, onPick = { source -> viewModel.chooseSource(content.view, choosingBlock.id, source) }, onDismiss = { choosingSourceFor = null }, ) @@ -401,7 +398,7 @@ private fun ListsContent( } rows.forEach { row -> val block = row.first() - if (block.id in state.goneSources && row.size == 1) { + if (block.id in state.goneSources && block.type !in TILES) { item(key = "${block.id}-gone") { Notice( text = stringResource(R.string.view_source_gone), @@ -924,9 +921,7 @@ private fun SearchResults( LazyColumn(modifier = Modifier.fillMaxSize()) { if (scope != null) { item(key = "scope") { - Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 8.dp)) { - ScopeInputChip(name = viewName(scope.name, scope.id), icon = scope.icon, onDrop = onDropScope) - } + ScopeChipRow(viewName(scope.name, scope.id), scope.icon, onDrop = onDropScope) } } if (results.isEmpty()) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt index 12592ee..b00dcdf 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsViewModel.kt @@ -136,6 +136,8 @@ sealed interface ListsUiState { val allTasks: List = emptyList(), /** [allTasks] within the view's scope, where a search in a scoped view starts. */ val scopedTasks: List = allTasks, + /** The list a new task goes to, so it shows in the view: the scope's one list, if it keeps tasks to one. */ + val newTaskList: Long? = null, ) : ListsUiState { fun sectionsFor(block: Block): HomeSections = if (block.ignoreScope) unscopedSections else sections } @@ -216,6 +218,7 @@ internal fun homeContent( lists = lists, allTasks = allTasks, scopedTasks = if (scope == AppliedScope.None) allTasks else allTasks.filter { scope.admits(it, clock) }, + newTaskList = scope.lists?.singleOrNull()?.takeIf { it in listIds }, ) } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt index aa90339..48a99d3 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/SourcePicker.kt @@ -35,6 +35,7 @@ internal fun SourcePicker( withSmartLists: Boolean, onPick: (BlockSource) -> Unit, onDismiss: () -> Unit, + todayOnly: Boolean = false, ) { val sections = state.unscopedSections val pick = { source: BlockSource -> @@ -44,15 +45,17 @@ internal fun SourcePicker( FullScreenPicker(title = title, onDismiss = onDismiss) { if (withSmartLists) { GroupedSectionHeader(stringResource(R.string.view_source_smart)) - SmartList.entries.forEachIndexed { index, smart -> + val smarts = if (todayOnly) listOf(SmartList.TODAY) else SmartList.entries + smarts.forEachIndexed { index, smart -> GroupedRow( title = stringResource(smartListLabel(smart)), - position = positionOf(index, SmartList.entries.size), + position = positionOf(index, smarts.size), leading = { Icon(Icons.AutoMirrored.Rounded.ListAlt, contentDescription = null) }, onClick = { pick(BlockSource.Smart(smart)) }, ) } } + if (todayOnly) return@FullScreenPicker sections.groups.forEach { group -> GroupedSectionHeader(group.accountName) group.lists.forEachIndexed { index, overview -> 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 f1bdafa..9fe89ae 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 @@ -131,7 +131,7 @@ fun AgendulaNavHost( ListsScreen( onOpenFilter = { filter, scopeViewId -> nav.navigate(Dest.TaskList.build(filter, scopeViewId)) }, onOpenTask = { task -> nav.navigate(task.detailRoute()) }, - onNewTask = { nav.navigate(Dest.TaskEdit.buildNew()) }, + onNewTask = { listId -> nav.navigate(Dest.TaskEdit.buildNew(presetListId = listId)) }, onNewFilter = { nav.navigate(Dest.FilterEdit.build()) }, onOpenSettings = { nav.navigate(Dest.SETTINGS) }, onManageViews = { nav.navigate(Dest.MANAGE_VIEWS) }, diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AppShortcuts.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AppShortcuts.kt index ab53acf..e53ba80 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AppShortcuts.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/navigation/AppShortcuts.kt @@ -19,6 +19,7 @@ import androidx.core.graphics.drawable.IconCompat import de.jeanlucmakiola.agendula.MainActivity import de.jeanlucmakiola.agendula.R import de.jeanlucmakiola.agendula.domain.View +import de.jeanlucmakiola.agendula.ui.views.unnamedViewLabel import de.jeanlucmakiola.agendula.ui.views.vector /** @@ -30,11 +31,15 @@ import de.jeanlucmakiola.agendula.ui.views.vector */ object AppShortcuts { - /** The views last published, for a republish that doesn't come with them. */ - @Volatile private var views: List = emptyList() + /** The views last published, for a republish that doesn't come with them; `null` before the first. */ + @Volatile private var lastViews: List? = null - fun publish(context: Context, views: List = this.views) { - this.views = views + /** + * Publishes the shortcuts with [views]. Without them, before the views were + * ever published, only the fixed shortcuts are refreshed and the views' + * left as they are, rather than wiped. + */ + fun publish(context: Context, views: List? = lastViews) { val fixed = listOf( ShortcutInfoCompat.Builder(context, "new_task") .setShortLabel(context.getString(R.string.shortcut_new_task)) @@ -49,11 +54,14 @@ object AppShortcuts { .setRank(1) .build(), ) + if (views == null) { + fixed.forEach { runCatching { ShortcutManagerCompat.pushDynamicShortcut(context, it) } } + return + } + lastViews = views val room = runCatching { ShortcutManagerCompat.getMaxShortcutCountPerActivity(context) }.getOrDefault(fixed.size) val viewShortcuts = views.take((room - fixed.size).coerceAtLeast(0)).mapIndexed { index, view -> - val label = view.name.ifBlank { - context.getString(if (view.id == View.HOME_ID) R.string.view_home else R.string.view_unnamed) - } + val label = view.name.ifBlank { context.getString(unnamedViewLabel(view.id)) } ShortcutInfoCompat.Builder(context, "view_${view.id}") .setShortLabel(label) .setIcon(IconCompat.createWithBitmap(shortcutBitmap(context, view.icon.vector))) @@ -62,6 +70,16 @@ object AppShortcuts { .build() } runCatching { ShortcutManagerCompat.setDynamicShortcuts(context, fixed + viewShortcuts) } + // A deleted view's shortcut pinned to the home screen stays there; it is disabled instead. + val kept = views.mapTo(HashSet()) { "view_${it.id}" } + runCatching { + val gone = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_PINNED) + .map { it.id } + .filter { it.startsWith("view_") && it !in kept } + if (gone.isNotEmpty()) { + ShortcutManagerCompat.disableShortcuts(context, gone, context.getString(R.string.view_shortcut_gone)) + } + } } /** Tells the launcher a view's shortcut was used, so it can rank it. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt index 05944ac..1328021 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListScreen.kt @@ -137,7 +137,8 @@ import de.jeanlucmakiola.agendula.ui.common.priorityAccent import de.jeanlucmakiola.agendula.ui.lists.ListEditorSheet import de.jeanlucmakiola.agendula.ui.lists.listWriteFailureMessage import de.jeanlucmakiola.agendula.ui.lists.ListWriteFailure -import de.jeanlucmakiola.agendula.ui.views.ScopeInputChip +import de.jeanlucmakiola.agendula.ui.views.ScopeChipRow +import de.jeanlucmakiola.agendula.ui.lists.smartListLabel import de.jeanlucmakiola.agendula.ui.views.viewName import de.jeanlucmakiola.floret.components.Position import de.jeanlucmakiola.floret.components.SnackChip @@ -501,7 +502,18 @@ private fun TaskListBody( ), ) { state.scope?.let { scope -> - item(key = "scope") { ScopeChipRow(scope, onDrop = viewModel::dropScope) } + item(key = "scope") { + ScopeChipRow(viewName(scope.name, scope.viewId), scope.icon, onDrop = viewModel::dropScope) + // A scope list since deleted matches nothing here either; say so rather than show less quietly. + if (scope.listsGone) { + Text( + stringResource(R.string.view_scope_list_gone), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp).padding(bottom = 8.dp), + ) + } + } } if (state.tasks.isEmpty()) { val empty = if (state.hiddenByRange && state.selectedTags.isEmpty()) { @@ -515,14 +527,6 @@ private fun TaskListBody( } } -/** The removable chip naming the view whose scope narrows a task screen. */ -@Composable -private fun ScopeChipRow(scope: ScopeChip, onDrop: () -> Unit) { - Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 8.dp)) { - ScopeInputChip(name = viewName(scope.name, scope.viewId), icon = scope.icon, onDrop = onDrop) - } -} - /** * A task screen's rows as grouped and folded: what [taskRows] lays out. Holds * which parents are expanded, and reports the ones whose subtasks it has to @@ -583,7 +587,8 @@ internal fun rememberTaskRows( ) // Parents the user expanded to reveal their subtasks inline. Children are // grouped from the same flat task set the list already holds. - var expandedParents by rememberSaveable { mutableStateOf(emptySet()) } + // Per model: home hosts a different one for each view's task list. + var expandedParents by rememberSaveable(viewModel) { mutableStateOf(emptySet()) } val childrenByParent = remember(state.tasks) { state.tasks.filter { it.isSubtask }.groupBy { it.parentId!! } } @@ -596,7 +601,7 @@ internal fun rememberTaskRows( val parent = tasksById[id] parent != null && (childrenByParent[id]?.size ?: 0) != parent.subtaskTotal }.toSet() - LaunchedEffect(parentsNeedingChildren) { viewModel.setLazyChildParents(parentsNeedingChildren) } + LaunchedEffect(viewModel, parentsNeedingChildren) { viewModel.setLazyChildParents(parentsNeedingChildren) } val lazyChildren by viewModel.lazyChildren.collectAsStateWithLifecycle() return TaskRows( state = state, @@ -1533,16 +1538,7 @@ private fun titleFor(filter: TaskFilter, name: String?): String = when (filter) // Several lists at once only exists for the widget, which never routes here. is TaskFilter.OfLists -> error("OfLists has no task-list screen") is TaskFilter.Tagged -> filter.tag - is TaskFilter.Smart -> stringResource( - when (filter.list) { - SmartList.TODAY -> R.string.smart_today - SmartList.UPCOMING -> R.string.smart_upcoming - SmartList.OVERDUE -> R.string.smart_overdue - SmartList.ALL -> R.string.smart_all - SmartList.NO_DATE -> R.string.smart_no_date - SmartList.COMPLETED -> R.string.smart_completed - }, - ) + is TaskFilter.Smart -> stringResource(smartListLabel(filter.list)) } @Composable diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt index 683623e..3a6336a 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/tasklist/TaskListViewModel.kt @@ -357,7 +357,8 @@ class TaskListViewModel @Inject constructor( val content = state.value as? TaskListUiState.Content ?: return val view = pinnedViewOf(content.list, content.savedFilter) ?: return viewModelScope.launch { - viewSession.switchTo(settingsPrefs.saveView(view)) + val id = settingsPrefs.saveView(view) ?: return@launch + viewSession.switchTo(id) onPinned() } } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt index 9a8bd37..3c6c7df 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/EditViewScreen.kt @@ -63,6 +63,7 @@ fun EditViewScreen( ) { val draft by viewModel.draft.collectAsStateWithLifecycle() val listNames by viewModel.listNames.collectAsStateWithLifecycle() + val saveFailed by viewModel.saveFailed.collectAsStateWithLifecycle() val view = draft val isNew = view?.id == 0L var choosingIcon by rememberSaveable { mutableStateOf(false) } @@ -91,6 +92,14 @@ fun EditViewScreen( onNameChange = viewModel::rename, onImeAction = save, ) + if (saveFailed) { + Text( + stringResource(R.string.view_save_failed), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = GroupedListInset).padding(top = 8.dp), + ) + } GroupedSectionHeader(stringResource(R.string.view_section_icon)) GroupedRow( diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/StartDestinationRow.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/StartDestinationRow.kt index aaa6b46..e4747ad 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/StartDestinationRow.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/StartDestinationRow.kt @@ -153,9 +153,13 @@ private fun StartDestinationPicker( /** What [destination] is called; one since deleted reads as Home, where the app then opens. */ @Composable -private fun startLabel(destination: StartDestination, choices: StartChoices): String = when (destination) { - StartDestination.LastUsed -> stringResource(R.string.start_last_used) - is StartDestination.View -> choices.views.firstOrNull { it.id == destination.id }?.let { viewName(it.name, it.id) } - is StartDestination.List -> choices.lists.firstOrNull { it.id == destination.id }?.name - is StartDestination.Filter -> choices.filters.firstOrNull { it.id == destination.id }?.name -} ?: choices.views.firstOrNull()?.let { viewName(it.name, it.id) } ?: stringResource(R.string.view_home) +private fun startLabel(destination: StartDestination, choices: StartChoices): String? { + val home = choices.views.firstOrNull()?.let { viewName(it.name, it.id) } ?: stringResource(R.string.view_home) + return when (destination) { + StartDestination.LastUsed -> stringResource(R.string.start_last_used) + is StartDestination.View -> choices.views.firstOrNull { it.id == destination.id }?.let { viewName(it.name, it.id) } ?: home + // Lists may not have loaded, or may not read: no name rather than a wrong one. + is StartDestination.List -> choices.lists.firstOrNull { it.id == destination.id }?.name + is StartDestination.Filter -> choices.filters.firstOrNull { it.id == destination.id }?.name ?: home + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt index 7bf76c8..e68d26e 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewSession.kt @@ -54,20 +54,25 @@ class ViewSession @Inject constructor( * filter to open over it, if it is one that still exists. */ suspend fun start(): TaskFilter? { + val picked = chosen.value try { val destination = prefs.startDestination.first() val views = prefs.views.first().mapTo(HashSet()) { it.id } val filters = prefs.savedFilters.first().mapTo(HashSet()) { it.id } val lastUsed = prefs.activeViewId.first() - // The view doesn't depend on the lists, so home shows before they are read. - val viewId = destination.plan(views, lastUsed, null, filters).viewId - if (viewId != lastUsed || chosen.value != null) switchTo(viewId) - _starting.value = false - if (destination !is StartDestination.List) return destination.plan(views, lastUsed, null, filters).push - val lists = withTimeoutOrNull(LISTS_TIMEOUT_MS) { - runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull() + // Only a list needs the lists read; home waits for it, so the list can't land over a screen opened meanwhile. + val lists = if (destination is StartDestination.List) { + withTimeoutOrNull(LISTS_TIMEOUT_MS) { + runCatching { repository.taskLists().first().mapTo(HashSet()) { it.id } }.getOrNull() + } + } else { + null } - return destination.plan(views, lastUsed, lists, filters).push + val plan = destination.plan(views, lastUsed, lists, filters) + // A view picked while this ran, by a shortcut, wins. + if (picked != chosen.value) return null + if (plan.viewId != lastUsed || picked != null) switchTo(plan.viewId) + return plan.push } finally { _starting.value = false } diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewVisuals.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewVisuals.kt index b4ded5d..95ed13d 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewVisuals.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewVisuals.kt @@ -1,7 +1,11 @@ package de.jeanlucmakiola.agendula.ui.views import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.ui.unit.dp import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.MenuBook import androidx.compose.material.icons.rounded.AccountTree @@ -149,8 +153,18 @@ val ViewIcon.label: Int * and shows the translated "Home"; another view left without a name shows "View". */ @Composable -fun viewName(name: String, viewId: Long): String = name.ifBlank { - stringResource(if (viewId == View.HOME_ID) R.string.view_home else R.string.view_unnamed) +fun viewName(name: String, viewId: Long): String = name.ifBlank { stringResource(unnamedViewLabel(viewId)) } + +/** What a view left without a name is called: Home's translated name, or "View". */ +@StringRes +fun unnamedViewLabel(viewId: Long): Int = if (viewId == View.HOME_ID) R.string.view_home else R.string.view_unnamed + +/** [ScopeInputChip] on its own row, at the inset of the content below it. */ +@Composable +fun ScopeChipRow(name: String, icon: ViewIcon, onDrop: () -> Unit) { + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 8.dp)) { + ScopeInputChip(name = name, icon = icon, onDrop = onDrop) + } } /** The removable chip a scope shows as: the view's icon and name, ✕ to drop it. */ diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt index 02e21a8..44a1624 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/views/ViewsViewModels.kt @@ -8,7 +8,6 @@ import de.jeanlucmakiola.agendula.data.tasks.TasksRepository import de.jeanlucmakiola.agendula.domain.View import de.jeanlucmakiola.agendula.domain.ViewIcon import de.jeanlucmakiola.agendula.domain.newView -import de.jeanlucmakiola.agendula.domain.reordered import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -41,7 +40,7 @@ class ManageViewsViewModel @Inject constructor( /** Puts the views in the order of [ids]; Home stays first. */ fun reorder(ids: List) = viewModelScope.launch { - settingsPrefs.reorderViews(views.value.reordered(ids).map { it.id }) + settingsPrefs.reorderViews(ids) } } @@ -67,6 +66,11 @@ class EditViewViewModel @Inject constructor( private var bound = false private var saving = false + private val _saveFailed = MutableStateFlow(false) + + /** Set when the views are stored in a form this version can't write; the screen says so. */ + val saveFailed: StateFlow = _saveFailed.asStateFlow() + fun bind(viewId: Long) { if (bound) return bound = true @@ -98,6 +102,11 @@ class EditViewViewModel @Inject constructor( val view = stored?.copy(name = draft.name.trim(), icon = draft.icon, quickAdd = draft.quickAdd) ?: draft.copy(id = 0, name = draft.name.trim()) val id = settingsPrefs.saveView(view) + saving = false + if (id == null) { + _saveFailed.value = true + return@launch + } if (stored == null) session.switchTo(id) onSaved() } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8a15b1b..6558a2c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1104,6 +1104,8 @@ Delete view Delete “%1$s”? The view and its layout go. Its tasks, lists and filters stay. + The views were saved by another version of Agendula and can’t be changed here. + This view was deleted View icon Suggested More diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt index 015c8f9..f30de20 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/prefs/ViewPrefsTest.kt @@ -42,7 +42,7 @@ class ViewPrefsTest { val second = prefs.saveView(pinnedView(0, "B", ViewIcon.LIST, Rule.InList(setOf(3L)))) assertThat(first).isEqualTo(2L) assertThat(second).isEqualTo(3L) - prefs.deleteView(second) + prefs.deleteView(second!!) assertThat(prefs.saveView(newView(0, "C"))).isEqualTo(4L) assertThat(prefs.views.first().map { it.name }).containsExactly("", "A", "C").inOrder() assertThat(prefs.views.first()[1]).isEqualTo(newView(2, "A")) @@ -52,14 +52,14 @@ class ViewPrefsTest { fun `saving a view replaces it in place`() = runBlocking { val id = prefs.saveView(newView(0, "A")) prefs.saveView(newView(0, "B")) - prefs.saveView(newView(id, "Renamed")) + prefs.saveView(newView(id!!, "Renamed")) assertThat(prefs.views.first().map { it.name }).containsExactly("", "Renamed", "B").inOrder() } @Test fun `Home stays first and can't be deleted`() = runBlocking { - val a = prefs.saveView(newView(0, "A")) - val b = prefs.saveView(newView(0, "B")) + val a = prefs.saveView(newView(0, "A"))!! + val b = prefs.saveView(newView(0, "B"))!! prefs.reorderViews(listOf(b, a, View.HOME_ID)) assertThat(prefs.views.first().map { it.id }).containsExactly(View.HOME_ID, b, a).inOrder() prefs.deleteView(View.HOME_ID) @@ -70,7 +70,7 @@ class ViewPrefsTest { @Test fun `deleting the last used or start view falls back to Home`() = runBlocking { - val id = prefs.saveView(newView(0, "A")) + val id = prefs.saveView(newView(0, "A"))!! prefs.setActiveView(id) prefs.setStartDestination(StartDestination.View(id)) assertThat(prefs.activeViewId.first()).isEqualTo(id) @@ -100,4 +100,18 @@ class ViewPrefsTest { assertThat(decodeStart(encodeStart(StartDestination.List(5), "OWN"), "OWN")).isEqualTo(StartDestination.List(5)) assertThat(encodeStart(StartDestination.List(5), "OWN")).isEqualTo("list:OWN:5") } + + @Test + fun `a new id passes a stored view that doesn't read, and another version's views aren't written`() = runBlocking { + val store = MemoryDataStore() + val prefs = SettingsPrefs(store, ProviderResolver(NoProviders)) + store.data.value = androidx.datastore.preferences.core.preferencesOf( + ViewsMigration.KEY to "v1\nview|1|Home|HOME|1|\nview|7|broken", + ) + assertThat(prefs.saveView(newView(0, "A"))).isEqualTo(8L) + + store.data.value = androidx.datastore.preferences.core.preferencesOf(ViewsMigration.KEY to "v2\nview|1|x|HOME|1|") + assertThat(prefs.saveView(newView(0, "B"))).isNull() + assertThat(store.data.value[ViewsMigration.KEY]).isEqualTo("v2\nview|1|x|HOME|1|") + } }