summaryrefslogtreecommitdiff
path: root/src/com/android/customization/picker/clock/data/repository/ClockPickerRepositoryImpl.kt
blob: be6c6cbd34d881a60813b1a6e59c1fb9e5704dd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.android.customization.picker.clock.data.repository

import android.provider.Settings
import androidx.annotation.ColorInt
import androidx.annotation.IntRange
import com.android.customization.picker.clock.shared.ClockSize
import com.android.customization.picker.clock.shared.model.ClockMetadataModel
import com.android.systemui.plugins.ClockMetadata
import com.android.systemui.shared.clocks.ClockRegistry
import com.android.wallpaper.settings.data.repository.SecureSettingsRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.shareIn
import org.json.JSONObject

/** Implementation of [ClockPickerRepository], using [ClockRegistry]. */
class ClockPickerRepositoryImpl(
    private val secureSettingsRepository: SecureSettingsRepository,
    private val registry: ClockRegistry,
    scope: CoroutineScope,
    mainDispatcher: CoroutineDispatcher,
) : ClockPickerRepository {

    @OptIn(ExperimentalCoroutinesApi::class)
    override val allClocks: Flow<List<ClockMetadataModel>> =
        callbackFlow {
                fun send() {
                    val allClocks =
                        registry
                            .getClocks()
                            .filter { "NOT_IN_USE" !in it.clockId }
                            .map { it.toModel() }
                    trySend(allClocks)
                }

                val listener =
                    object : ClockRegistry.ClockChangeListener {
                        override fun onAvailableClocksChanged() {
                            send()
                        }
                    }
                registry.registerClockChangeListener(listener)
                send()
                awaitClose { registry.unregisterClockChangeListener(listener) }
            }
            .flowOn(mainDispatcher)
            .mapLatest { allClocks ->
                // Loading list of clock plugins can cause many consecutive calls of
                // onAvailableClocksChanged(). We only care about the final fully-initiated clock
                // list. Delay to avoid unnecessary too many emits.
                delay(100)
                allClocks
            }

    /** The currently-selected clock. This also emits the clock color information. */
    override val selectedClock: Flow<ClockMetadataModel> =
        callbackFlow {
                fun send() {
                    val currentClockId = registry.currentClockId
                    val metadata = registry.settings?.metadata
                    val model =
                        registry
                            .getClocks()
                            .find { clockMetadata -> clockMetadata.clockId == currentClockId }
                            ?.toModel(
                                selectedColorId = metadata?.getSelectedColorId(),
                                colorTone = metadata?.getColorTone()
                                        ?: ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS,
                                seedColor = registry.seedColor
                            )
                    trySend(model)
                }

                val listener =
                    object : ClockRegistry.ClockChangeListener {
                        override fun onCurrentClockChanged() {
                            send()
                        }

                        override fun onAvailableClocksChanged() {
                            send()
                        }
                    }
                registry.registerClockChangeListener(listener)
                send()
                awaitClose { registry.unregisterClockChangeListener(listener) }
            }
            .flowOn(mainDispatcher)
            .mapNotNull { it }

    override suspend fun setSelectedClock(clockId: String) {
        registry.mutateSetting { oldSettings ->
            val newSettings = oldSettings.copy(clockId = clockId)
            newSettings.metadata = oldSettings.metadata
            newSettings
        }
    }

    override suspend fun setClockColor(
        selectedColorId: String?,
        @IntRange(from = 0, to = 100) colorToneProgress: Int,
        @ColorInt seedColor: Int?,
    ) {
        registry.mutateSetting { oldSettings ->
            val newSettings = oldSettings.copy(seedColor = seedColor)
            newSettings.metadata =
                oldSettings.metadata
                    .put(KEY_METADATA_SELECTED_COLOR_ID, selectedColorId)
                    .put(KEY_METADATA_COLOR_TONE_PROGRESS, colorToneProgress)
            newSettings
        }
    }

    override val selectedClockSize: SharedFlow<ClockSize> =
        secureSettingsRepository
            .intSetting(
                name = Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK,
                defaultValue = DEFAULT_CLOCK_SIZE,
            )
            .map { setting -> setting == 1 }
            .map { isDynamic -> if (isDynamic) ClockSize.DYNAMIC else ClockSize.SMALL }
            .shareIn(
                scope = scope,
                started = SharingStarted.WhileSubscribed(),
                replay = 1,
            )

    override suspend fun setClockSize(size: ClockSize) {
        secureSettingsRepository.set(
            name = Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK,
            value = if (size == ClockSize.DYNAMIC) 1 else 0,
        )
    }

    private fun JSONObject.getSelectedColorId(): String? {
        return if (this.isNull(KEY_METADATA_SELECTED_COLOR_ID)) {
            null
        } else {
            this.getString(KEY_METADATA_SELECTED_COLOR_ID)
        }
    }

    private fun JSONObject.getColorTone(): Int {
        return this.optInt(
            KEY_METADATA_COLOR_TONE_PROGRESS,
            ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS
        )
    }

    /** By default, [ClockMetadataModel] has no color information unless specified. */
    private fun ClockMetadata.toModel(
        selectedColorId: String? = null,
        @IntRange(from = 0, to = 100) colorTone: Int = 0,
        @ColorInt seedColor: Int? = null,
    ): ClockMetadataModel {
        return ClockMetadataModel(
            clockId = clockId,
            name = name,
            selectedColorId = selectedColorId,
            colorToneProgress = colorTone,
            seedColor = seedColor,
        )
    }

    companion object {
        // The selected color in the color option list
        private const val KEY_METADATA_SELECTED_COLOR_ID = "metadataSelectedColorId"

        // The color tone to apply to the selected color
        private const val KEY_METADATA_COLOR_TONE_PROGRESS = "metadataColorToneProgress"

        // The default clock size is 1, which means dynamic
        private const val DEFAULT_CLOCK_SIZE = 1
    }
}