/* * Copyright (C) 2025 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.eyedropper.ui.touchscreen import android.graphics.Bitmap import android.graphics.Color import androidx.compose.ui.geometry.Offset import androidx.lifecycle.SavedStateHandle import com.android.eyedropper.ui.BaseEyeDropperViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlin.math.roundToInt import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update /** * [BaseEyeDropperViewModel] subclass that manages additional touchscreen UX specific state: * * (1) In contrast to desktop UI, the touchscreen UI reticle dynamically displays the color it * currently hovers over. Thus we persist color at [bitmapPointerPosition] as state * (2) In contrast to desktop UI, the touchscreen UI reticle has different states depending on if * it's being dragged (show/hide arrows, show/hide color). Thus we persist if it's being dragged. * * On initialization, we initialize the reticle to the center. */ @HiltViewModel class TouchscreenViewModel @Inject constructor( savedStateHandle: SavedStateHandle ) : BaseEyeDropperViewModel(savedStateHandle) { private var _uiState = MutableStateFlow(TouchscreenReticleState()) val uiState = _uiState.asStateFlow() /** * Set initial reticle ring color. */ override fun initialize( bitmap: Bitmap, onColorSelected: (Int) -> Unit, onSelectionCanceled: () -> Unit ) { val isFirstInititialization = !isInitialized.value // store b/c super.init will set -> true super.initialize(bitmap, onColorSelected, onSelectionCanceled) // If first init, initialize reticle to center. Else super.init wouldve restored already if (isFirstInititialization && bitmapPointerPosition.value == Offset.Unspecified) { val initialX = bitmap.width / 2f val initialY = bitmap.height / 2f updateBitmapPointerPosition(Offset(initialX, initialY)) updateHoveredColor(initialX, initialY) } } override fun updateBitmapPointerPosition(newOffset: Offset) { super.updateBitmapPointerPosition(newOffset) updateHoveredColor(newOffset.x, newOffset.y) } fun updateDragging(isDragging: Boolean) { _uiState.update { it.copy(isDragging = isDragging) } } fun updateHoveredColor(x: Float, y: Float) { val currBitmap = androidBitmap ?: return var colorInt = Color.WHITE if (uiState.value.isDragging) { if (x.roundToInt() in 0..