summaryrefslogtreecommitdiff
path: root/feature/preview/src/main/java/com/google/jetpackcamera/feature/preview/PreviewViewModel.kt
blob: 7066977432021e0b34b842489be08f9a8d4bcec4 (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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
 * 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.google.jetpackcamera.feature.preview

import android.util.Log
import android.view.Display
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview.SurfaceProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.jetpackcamera.domain.camera.CameraUseCase
import com.google.jetpackcamera.feature.preview.ui.ToastMessage
import com.google.jetpackcamera.settings.SettingsRepository
import com.google.jetpackcamera.settings.model.AspectRatio
import com.google.jetpackcamera.settings.model.CaptureMode
import com.google.jetpackcamera.settings.model.DEFAULT_CAMERA_APP_SETTINGS
import com.google.jetpackcamera.settings.model.FlashMode
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

private const val TAG = "PreviewViewModel"

// toast test descriptions
const val IMAGE_CAPTURE_SUCCESS_TOAST_TAG = "ImageCaptureSuccessToast"
const val IMAGE_CAPTURE_FAIL_TOAST_TAG = "ImageCaptureFailureToast"

/**
 * [ViewModel] for [PreviewScreen].
 */
@HiltViewModel
class PreviewViewModel @Inject constructor(
    private val cameraUseCase: CameraUseCase,
    private val settingsRepository: SettingsRepository
    // only reads from settingsRepository. do not push changes to repository from here
) : ViewModel() {

    private val _previewUiState: MutableStateFlow<PreviewUiState> =
        MutableStateFlow(PreviewUiState(currentCameraSettings = DEFAULT_CAMERA_APP_SETTINGS))

    val previewUiState: StateFlow<PreviewUiState> = _previewUiState
    private var runningCameraJob: Job? = null

    private var recordingJob: Job? = null

    init {
        viewModelScope.launch {
            settingsRepository.cameraAppSettings.collect {
                    // TODO: only update settings that were actually changed
                    // currently resets all "quick" settings to stored settings
                    settings ->
                _previewUiState
                    .emit(previewUiState.value.copy(currentCameraSettings = settings))
            }
        }
        initializeCamera()
    }

    private fun initializeCamera() {
        // TODO(yasith): Handle CameraUnavailableException
        Log.d(TAG, "initializeCamera")
        viewModelScope.launch {
            cameraUseCase.initialize(previewUiState.value.currentCameraSettings)
            _previewUiState.emit(
                previewUiState.value.copy(
                    cameraState = CameraState.READY
                )
            )
        }
    }

    fun runCamera(surfaceProvider: SurfaceProvider) {
        Log.d(TAG, "runCamera")
        stopCamera()
        runningCameraJob = viewModelScope.launch {
            // TODO(yasith): Handle Exceptions from binding use cases
            cameraUseCase.runCamera(
                surfaceProvider,
                previewUiState.value.currentCameraSettings
            )
        }
    }

    fun stopCamera() {
        Log.d(TAG, "stopCamera")
        runningCameraJob?.apply {
            if (isActive) {
                cancel()
            }
        }
    }

    fun setFlash(flashMode: FlashMode) {
        viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    currentCameraSettings =
                    previewUiState.value.currentCameraSettings.copy(
                        flashMode = flashMode
                    )
                )
            )
            // apply to cameraUseCase
            cameraUseCase.setFlashMode(previewUiState.value.currentCameraSettings.flashMode)
        }
    }

    fun setAspectRatio(aspectRatio: AspectRatio) {
        stopCamera()
        runningCameraJob = viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    currentCameraSettings =
                    previewUiState.value.currentCameraSettings.copy(
                        aspectRatio = aspectRatio
                    )
                )
            )
            cameraUseCase.setAspectRatio(
                aspectRatio,
                previewUiState.value
                    .currentCameraSettings.isFrontCameraFacing
            )
        }
    }

    // flips the camera opposite to its current direction
    fun flipCamera() {
        flipCamera(
            !previewUiState.value
                .currentCameraSettings.isFrontCameraFacing
        )
    }

    fun toggleCaptureMode() {
        val newCaptureMode = when (previewUiState.value.currentCameraSettings.captureMode) {
            CaptureMode.MULTI_STREAM -> CaptureMode.SINGLE_STREAM
            CaptureMode.SINGLE_STREAM -> CaptureMode.MULTI_STREAM
        }

        stopCamera()
        runningCameraJob = viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    currentCameraSettings =
                    previewUiState.value.currentCameraSettings.copy(
                        captureMode = newCaptureMode
                    )
                )
            )
            // apply to cameraUseCase
            cameraUseCase.setCaptureMode(newCaptureMode)
        }
    }

    // sets the camera to a designated direction
    fun flipCamera(isFacingFront: Boolean) {
        // only flip if 2 directions are available
        if (previewUiState.value.currentCameraSettings.isBackCameraAvailable &&
            previewUiState.value.currentCameraSettings.isFrontCameraAvailable
        ) {
            stopCamera()
            runningCameraJob = viewModelScope.launch {
                _previewUiState.emit(
                    previewUiState.value.copy(
                        currentCameraSettings =
                        previewUiState.value.currentCameraSettings.copy(
                            isFrontCameraFacing = isFacingFront
                        )
                    )
                )
                // apply to cameraUseCase
                cameraUseCase
                    .flipCamera(previewUiState.value.currentCameraSettings.isFrontCameraFacing)
            }
        }
    }

    fun captureImage() {
        Log.d(TAG, "captureImage")
        viewModelScope.launch {
            try {
                cameraUseCase.takePicture()
                // todo: remove toast after postcapture screen implemented
                _previewUiState.emit(
                    previewUiState.value.copy(
                        toastMessageToShow = ToastMessage(
                            stringResource = R.string.toast_image_capture_success,
                            testTag = IMAGE_CAPTURE_SUCCESS_TOAST_TAG
                        )
                    )
                )
                Log.d(TAG, "cameraUseCase.takePicture success")
            } catch (exception: ImageCaptureException) {
                // todo: remove toast after postcapture screen implemented
                _previewUiState.emit(
                    previewUiState.value.copy(
                        toastMessageToShow = ToastMessage(
                            stringResource = R.string.toast_capture_failure,
                            testTag = IMAGE_CAPTURE_FAIL_TOAST_TAG
                        )
                    )
                )
                Log.d(TAG, "cameraUseCase.takePicture error")
                Log.d(TAG, exception.toString())
            }
        }
    }

    fun startVideoRecording() {
        Log.d(TAG, "startVideoRecording")
        recordingJob = viewModelScope.launch {
            try {
                cameraUseCase.startVideoRecording()
                _previewUiState.emit(
                    previewUiState.value.copy(
                        videoRecordingState = VideoRecordingState.ACTIVE
                    )
                )
                Log.d(TAG, "cameraUseCase.startRecording success")
            } catch (exception: IllegalStateException) {
                Log.d(TAG, "cameraUseCase.startVideoRecording error")
                Log.d(TAG, exception.toString())
            }
        }
    }

    fun stopVideoRecording() {
        Log.d(TAG, "stopVideoRecording")
        viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    videoRecordingState = VideoRecordingState.INACTIVE
                )
            )
        }
        cameraUseCase.stopVideoRecording()
        recordingJob?.cancel()
    }

    fun setZoomScale(scale: Float): Float {
        return cameraUseCase.setZoomScale(scale = scale)
    }

    // modify ui values
    fun toggleQuickSettings() {
        toggleQuickSettings(!previewUiState.value.quickSettingsIsOpen)
    }

    private fun toggleQuickSettings(isOpen: Boolean) {
        viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    quickSettingsIsOpen = isOpen
                )
            )
        }
    }

    fun tapToFocus(display: Display, surfaceWidth: Int, surfaceHeight: Int, x: Float, y: Float) {
        cameraUseCase.tapToFocus(
            display = display,
            surfaceWidth = surfaceWidth,
            surfaceHeight = surfaceHeight,
            x = x,
            y = y
        )
    }

    fun onToastShown() {
        viewModelScope.launch {
            _previewUiState.emit(
                previewUiState.value.copy(
                    toastMessageToShow = null
                )
            )
        }
    }
}