1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 package com.android.wallpaper.picker.undo.data.repository
19 
20 import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot
21 import kotlinx.coroutines.flow.Flow
22 import kotlinx.coroutines.flow.MutableStateFlow
23 import kotlinx.coroutines.flow.distinctUntilChanged
24 import kotlinx.coroutines.flow.map
25 
26 /** Encapsulates application state for the undo system. */
27 class UndoRepository {
28     private val snapshotByOwnerId = mutableMapOf<Int, RestorableSnapshot>()
29     private val dirtyOwnerIds = MutableStateFlow(emptySet<Int>())
30 
31     /** Whether any area is "dirty" right now (meaning, it could be undone). */
32     val isAnythingDirty: Flow<Boolean> =
<lambda>null33         dirtyOwnerIds.map { it.isNotEmpty() }.distinctUntilChanged()
34 
35     /** Associates the given snapshot with the area with the given owner ID. */
putSnapshotnull36     fun putSnapshot(ownerId: Int, snapshot: RestorableSnapshot) {
37         snapshotByOwnerId[ownerId] = snapshot
38     }
39 
40     /** Returns the latest snapshot for the area with the given owner ID. */
getSnapshotnull41     fun getSnapshot(ownerId: Int): RestorableSnapshot? {
42         return snapshotByOwnerId[ownerId]
43     }
44 
45     /**
46      * Marks the area with the owner of the given ID as dirty or not dirty.
47      *
48      * A "dirty" area is one that contains changes that can be undone. An area that is not "dirty"
49      * does not currently have pending changes that can be undone.
50      */
putDirtynull51     fun putDirty(ownerId: Int, isDirty: Boolean) {
52         if (isDirty) {
53             dirtyOwnerIds.value = dirtyOwnerIds.value + setOf(ownerId)
54         } else {
55             dirtyOwnerIds.value = dirtyOwnerIds.value - setOf(ownerId)
56         }
57     }
58 
59     /**
60      * Returns the set of IDs for owners of all areas that are currently marked as dirty (meaning
61      * all areas that can currently be undone).
62      */
getAllDirtynull63     fun getAllDirty(): Collection<Int> {
64         return dirtyOwnerIds.value.toSet()
65     }
66 
67     /** Marks all areas as not dirty (meaning they can't be undone). */
clearAllDirtynull68     fun clearAllDirty() {
69         dirtyOwnerIds.value = emptySet()
70     }
71 }
72