1 /*
<lambda>null2  * Copyright (C) 2024 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 package com.android.systemui.haptics.slider
18 
19 import androidx.annotation.FloatRange
20 import kotlinx.coroutines.flow.Flow
21 import kotlinx.coroutines.flow.MutableStateFlow
22 import kotlinx.coroutines.flow.asStateFlow
23 import kotlinx.coroutines.flow.update
24 
25 /** A stateful producer of [SliderEvent] */
26 class SliderStateProducer : SliderEventProducer {
27 
28     /** The current event of a slider */
29     private val _currentEvent = MutableStateFlow(SliderEvent(SliderEventType.NOTHING, 0f))
30 
31     override fun produceEvents(): Flow<SliderEvent> = _currentEvent.asStateFlow()
32 
33     fun onProgressChanged(fromUser: Boolean, @FloatRange(from = 0.0, to = 1.0) progress: Float) {
34         val eventType =
35             if (fromUser) SliderEventType.PROGRESS_CHANGE_BY_USER
36             else SliderEventType.PROGRESS_CHANGE_BY_PROGRAM
37 
38         _currentEvent.value = SliderEvent(eventType, progress)
39     }
40 
41     fun onStartTracking(fromUser: Boolean) {
42         val eventType =
43             if (fromUser) SliderEventType.STARTED_TRACKING_TOUCH
44             else SliderEventType.STARTED_TRACKING_PROGRAM
45         _currentEvent.update { previousEvent ->
46             SliderEvent(eventType, previousEvent.currentProgress)
47         }
48     }
49 
50     fun onStopTracking(fromUser: Boolean) {
51         val eventType =
52             if (fromUser) SliderEventType.STOPPED_TRACKING_TOUCH
53             else SliderEventType.STOPPED_TRACKING_PROGRAM
54         _currentEvent.update { previousEvent ->
55             SliderEvent(eventType, previousEvent.currentProgress)
56         }
57     }
58 
59     fun resetWithProgress(@FloatRange(from = 0.0, to = 1.0) progress: Float) {
60         _currentEvent.value = SliderEvent(SliderEventType.NOTHING, progress)
61     }
62 }
63