-
Notifications
You must be signed in to change notification settings - Fork 629
/
ScanFragment.kt
282 lines (240 loc) · 8.59 KB
/
ScanFragment.kt
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
package com.stripe.android.stripecardscan.scanui
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.PointF
import android.util.Log
import android.util.Size
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RestrictTo
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.stripe.android.stripecardscan.R
import com.stripe.android.camera.CameraAdapter
import com.stripe.android.camera.CameraPreviewImage
import com.stripe.android.camera.DefaultCameraErrorListener
import com.stripe.android.stripecardscan.camera.getCameraAdapter
import com.stripe.android.camera.framework.Stats
import com.stripe.android.core.storage.StorageFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.CoroutineContext
private const val PERMISSION_RATIONALE_SHOWN = "permission_rationale_shown"
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
abstract class ScanFragment : Fragment(), CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main
internal val scanStat = Stats.trackTask("scan_activity")
private val permissionStat = Stats.trackTask("camera_permission")
protected var isFlashlightOn: Boolean = false
private set
internal val cameraAdapter by lazy { buildCameraAdapter() }
private val cameraErrorListener by lazy {
DefaultCameraErrorListener(requireActivity()) { t -> scanFailure(t) }
}
/**
* The listener which will handle the results from the scan.
*/
internal abstract val resultListener: ScanResultListener
private val storage by lazy {
StorageFactory.getStorageInstance(requireActivity(), "scan_camera_permissions")
}
private val cameraPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
launch { permissionStat.trackResult("success") }
prepareCamera { onCameraReady() }
} else {
launch { permissionStat.trackResult("failure") }
showPermissionDenied()
}
}
override fun onStart() {
super.onStart()
Stats.startScan()
context?.let {
if (!CameraAdapter.isCameraSupported(it)) {
showCameraNotSupported()
}
}
}
override fun onResume() {
super.onResume()
hideSystemUi()
launch {
delay(1500)
hideSystemUi()
}
if (!cameraAdapter.isBoundToLifecycle()) {
ensurePermissionAndStartCamera()
}
}
protected open fun hideSystemUi() {
// Prevent screenshots and keep the screen on while scanning.
activity?.window?.setFlags(
WindowManager.LayoutParams.FLAG_SECURE +
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_SECURE +
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
)
}
override fun onPause() {
super.onPause()
setFlashlightState(false)
}
/**
* Ensure that the camera permission is available. If so, start the camera. If not, request it.
*/
protected open fun ensurePermissionAndStartCamera() {
when {
ContextCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.CAMERA,
) == PackageManager.PERMISSION_GRANTED -> {
launch { permissionStat.trackResult("success") }
prepareCamera { onCameraReady() }
}
storage.getBoolean(
PERMISSION_RATIONALE_SHOWN,
false,
) -> showPermissionDenied()
else -> requestCameraPermission()
}
}
/**
* Show text explaining that the camera is not available.
*/
protected open fun showCameraNotSupported() {
instructionsText.visibility = View.VISIBLE
instructionsText.setText(R.string.stripe_error_camera_unsupported)
scanFailure()
}
/**
* Show text for why we are requesting camera permissions when the permission
* has been denied.
*/
protected open fun showPermissionDenied() {
instructionsText.visibility = View.VISIBLE
instructionsText.setText(R.string.stripe_camera_permission_settings_message)
storage.storeValue(PERMISSION_RATIONALE_SHOWN, true)
}
/**
* Request permission to use the camera.
*/
protected open fun requestCameraPermission() {
cameraPermissionLauncher.launch(
Manifest.permission.CAMERA
)
}
/**
* Turn the flashlight on or off.
*/
protected open fun toggleFlashlight() {
isFlashlightOn = !isFlashlightOn
setFlashlightState(isFlashlightOn)
// TODO: this should be reported as part of scanstats, but is not yet supported
}
/**
* Toggle between available cameras.
*/
protected open fun toggleCamera() {
cameraAdapter.changeCamera()
// TODO: this should probably be reported as part of scanstats, but is not yet supported
}
/**
* Called when the flashlight state has changed.
*/
protected abstract fun onFlashlightStateChanged(flashlightOn: Boolean)
/**
* Turn the flashlight on or off.
*/
private fun setFlashlightState(on: Boolean) {
cameraAdapter.setTorchState(on)
isFlashlightOn = on
onFlashlightStateChanged(on)
}
/**
* Cancel scanning due to a camera error.
*/
protected open fun scanFailure(cause: Throwable? = null) {
Log.e(LOG_TAG, "Canceling scan due to error", cause)
runBlocking { scanStat.trackResult("scan_failure") }
resultListener.failed(cause)
closeScanner()
}
/**
* The scan has been closed by the user.
*/
protected open fun userClosedScanner() {
runBlocking { scanStat.trackResult("user_canceled") }
resultListener.userCanceled(CancellationReason.Closed)
closeScanner()
}
/**
* Close the scanner.
*/
protected open fun closeScanner() {
setFlashlightState(false)
}
/**
* Prepare to start the camera. Once the camera is ready, [onCameraReady] must be called.
*/
protected abstract fun prepareCamera(onCameraReady: () -> Unit)
protected open fun onCameraReady() {
instructionsText.visibility = View.GONE
cameraAdapter.bindToLifecycle(this)
val torchStat = Stats.trackTask("torch_supported")
cameraAdapter.withFlashSupport {
launch { torchStat.trackResult(if (it) "supported" else "unsupported") }
setFlashlightState(cameraAdapter.isTorchOn())
onFlashSupported(it)
}
// TODO: this should probably be reported as part of scanstats, but is not yet supported
cameraAdapter.withSupportsMultipleCameras {
onSupportsMultipleCameras(it)
}
launch { onCameraStreamAvailable(cameraAdapter.getImageStream()) }
}
/**
* Perform an action when the flash is supported
*/
protected abstract fun onFlashSupported(supported: Boolean)
/**
* Perform an action when the camera support is determined
*/
protected abstract fun onSupportsMultipleCameras(supported: Boolean)
protected open fun setFocus(point: PointF) {
cameraAdapter.setFocus(point)
}
/**
* Generate a camera adapter
*/
internal open fun buildCameraAdapter(): CameraAdapter<CameraPreviewImage<Bitmap>> =
getCameraAdapter(
activity = requireActivity(),
previewView = previewFrame,
minimumResolution = minimumAnalysisResolution,
cameraErrorListener = cameraErrorListener,
)
protected abstract val previewFrame: ViewGroup
protected abstract val instructionsText: TextView
protected abstract val minimumAnalysisResolution: Size
/**
* A stream of images from the camera is available to be processed.
*/
protected abstract suspend fun onCameraStreamAvailable(
cameraStream: Flow<CameraPreviewImage<Bitmap>>,
)
internal companion object {
private val LOG_TAG = ScanFragment::class.java.simpleName
}
}