-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
camera_picker_state.dart
2021 lines (1917 loc) · 68.5 KB
/
camera_picker_state.dart
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The FlutterCandies author. All rights reserved.
// Use of this source code is governed by an Apache license that can be found
// in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:camera/camera.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'package:wechat_picker_library/wechat_picker_library.dart';
import '../constants/config.dart';
import '../constants/enums.dart';
import '../delegates/camera_picker_text_delegate.dart';
import '../internals/methods.dart';
import '../internals/singleton.dart';
import '../widgets/camera_focus_point.dart';
import '../widgets/camera_picker.dart';
import '../widgets/camera_picker_viewer.dart';
import '../widgets/camera_progress_button.dart';
const Color _lockedColor = Colors.orangeAccent;
const Duration _kDuration = Duration(milliseconds: 300);
class CameraPickerState extends State<CameraPicker>
with WidgetsBindingObserver {
/// The controller for the current camera.
/// 当前相机实例的控制器
CameraController get controller => innerController!;
CameraController? innerController;
/// Whether the access to the camera or the audio session
/// has been denied by the platform.
bool accessDenied = false;
/// Available cameras.
/// 可用的相机实例
List<CameraDescription> cameras = [];
/// Whether the controller is handling method calls.
/// 相机控制器是否在处理方法调用
bool isControllerBusy = false;
/// A [Completer] lock to keep the initialization only runs once at a time.
Completer<void>? initializeLock;
/// The [Duration] for record detection. (200ms)
/// 检测是否开始录制的时长 (200毫秒)
final Duration recordDetectDuration = const Duration(milliseconds: 200);
/// The last exposure point offset on the screen.
/// 最后一次手动聚焦的点坐标
final ValueNotifier<Offset?> lastExposurePoint = ValueNotifier<Offset?>(null);
/// The last pressed position on the shooting button before starts recording.
/// 在开始录像前,最后一次在拍照按钮按下的位置
Offset? lastShootingButtonPressedPosition;
/// Whether the focus point is displaying.
/// 是否正在展示当前的聚焦点
final ValueNotifier<bool> isFocusPointDisplays = ValueNotifier<bool>(false);
final ValueNotifier<bool> isFocusPointFadeOut = ValueNotifier<bool>(false);
/// Current exposure offset.
/// 当前曝光值
final ValueNotifier<double> currentExposureOffset = ValueNotifier<double>(0);
final ValueNotifier<double> currentExposureSliderOffset =
ValueNotifier<double>(0);
double maxAvailableExposureOffset = 0;
double minAvailableExposureOffset = 0;
double exposureStep = 0;
/// The maximum available value for zooming.
/// 最大可用缩放值
double maxAvailableZoom = 1;
/// The minimum available value for zooming.
/// 最小可用缩放值
double minAvailableZoom = 1;
/// Counting pointers (number of user fingers on screen).
/// 屏幕上的触摸点计数
int pointers = 0;
double currentZoom = 1;
double baseZoom = 1;
/// The index of the current cameras. Defaults to `0`.
/// 当前相机的索引。默认为0
int currentCameraIndex = 0;
/// Whether the [buildCaptureButton] should animate according to the gesture.
/// 拍照按钮是否需要执行动画
///
/// This happens when the [buildCaptureButton] is being long pressed.
/// It will animate for video recording state.
/// 当长按拍照按钮时,会进入准备录制视频的状态,此时需要执行动画。
bool isShootingButtonAnimate = false;
/// Whether the [buildCaptureButton] is being tapped down.
/// 拍照按钮是否已经按下
bool isCaptureButtonTapDown = false;
/// The [Timer] for keep the [lastExposurePoint] displays.
/// 用于控制上次手动聚焦点显示的计时器
Timer? exposurePointDisplayTimer;
Timer? exposureModeDisplayTimer;
Timer? exposureFadeOutTimer;
/// The [Timer] for record start detection.
/// 用于检测是否开始录制的计时器
///
/// When the [buildCaptureButton] started animate, this [Timer] will start
/// at the same time. When the time is more than [recordDetectDuration],
/// which means we should start recoding, the timer finished.
/// 当拍摄按钮开始执行动画时,定时器会同时启动。时长超过检测时长时,定时器完成。
Timer? recordDetectTimer;
/// The [Timer] for record countdown.
/// 用于录制视频倒计时的计时器
///
/// Stop record When the record time reached the [maximumRecordingDuration].
/// However, if there's no limitation on record time, this will be useless.
/// 当录像时间达到了最大时长,将通过定时器停止录像。
/// 但如果录像时间没有限制,定时器将不会起作用。
Timer? recordCountdownTimer;
/// The [Stopwatch] to monitor if the record has reached
/// the minimum record duration requirement.
/// 录像时长计时器,用来检测是否达到了最短录制时长。
final Stopwatch recordStopwatch = Stopwatch();
/// Initialized with all the flash modes for each camera. If a flash mode is
/// not valid, it is removed from the list.
/// 使用每个相机的所有闪光灯模式进行初始化。
/// 如果闪光灯模式无效,则将其从列表中删除。
final Map<CameraDescription, List<FlashMode>> validFlashModes =
<CameraDescription, List<FlashMode>>{};
////////////////////////////////////////////////////////////////////////////
////////////////////////////// Global Getters //////////////////////////////
////////////////////////////////////////////////////////////////////////////
CameraPickerConfig get pickerConfig => widget.pickerConfig;
/// Whether the camera preview should be scaled during captures.
/// 拍摄过程中相机预览是否需要缩放
bool get enableScaledPreview => pickerConfig.enableScaledPreview;
/// Whether the picker can record video.
/// 选择器是否可以录像
bool get enableRecording => pickerConfig.enableRecording;
/// Whether the picker only enables video recording.
/// 选择器是否只可以录像
bool get onlyEnableRecording =>
enableRecording && pickerConfig.onlyEnableRecording;
/// Whether allow the record can start with single tap.
/// 选择器是否可以单击录像
bool get enableTapRecording =>
onlyEnableRecording && pickerConfig.enableTapRecording;
/// No audio integration required when it's only for camera.
/// 在仅允许拍照时不需要启用音频
bool get enableAudio => enableRecording && pickerConfig.enableAudio;
/// Whether the picker needs to prepare for video recording on iOS.
/// 是否需要为 iOS 的录制视频执行准备操作
bool get shouldPrepareForVideoRecording =>
enableRecording && enableAudio && Platform.isIOS;
bool get enablePullToZoomInRecord =>
enableRecording && pickerConfig.enablePullToZoomInRecord;
/// Whether the recording restricted to a specific duration.
/// 录像是否有限制的时长
bool get isRecordingRestricted =>
pickerConfig.maximumRecordingDuration != null;
/// The minimum recording duration limit.
/// 录制视频的最短时长限制。
///
/// If the maximum duration is less than the minimum, use the maximum instead.
/// 如果最大时长大于最小时长,则使用最大时长。
Duration get minimumRecordingDuration {
if (pickerConfig.maximumRecordingDuration != null &&
pickerConfig.maximumRecordingDuration! <
pickerConfig.minimumRecordingDuration) {
return pickerConfig.maximumRecordingDuration!;
}
return pickerConfig.minimumRecordingDuration;
}
/// Whether the capture button is displaying.
bool get shouldCaptureButtonDisplay =>
isCaptureButtonTapDown &&
(innerController?.value.isRecordingVideo ?? false) &&
isRecordingRestricted;
/// Whether the camera preview should be rotated.
bool get isCameraRotated => pickerConfig.cameraQuarterTurns % 4 != 0;
int get cameraQuarterTurns => pickerConfig.cameraQuarterTurns;
/// A getter to the current [CameraDescription].
/// 获取当前相机实例
CameraDescription get currentCamera => cameras.elementAt(currentCameraIndex);
/// If there's no theme provided from the user, use [CameraPicker.themeData] .
/// 如果用户未提供主题,通过 [CameraPicker.themeData] 创建。
late final ThemeData theme =
pickerConfig.theme ?? CameraPicker.themeData(defaultThemeColorWeChat);
CameraPickerTextDelegate get textDelegate => Singleton.textDelegate;
/// If controller methods were failed to called for camera descriptions,
/// it will be recorded as invalid and never gets called again.
///
/// 如果相机实例的某个方法调用失败,该方法会被记录并且不会再被调用。
final invalidControllerMethods = <CameraDescription, Set<String>>{};
bool retriedAfterInvalidInitialize = false;
/// Subscribe to the accelerometer.
StreamSubscription<AccelerometerEvent>? accelerometerSubscription;
/// The locked capture orientation of the current camera instance.
DeviceOrientation? lockedCaptureOrientation;
/// The calculated capture actions section height.
double? lastCaptureActionsEffectiveHeight;
@override
void initState() {
super.initState();
ambiguate(WidgetsBinding.instance)?.addObserver(this);
Singleton.textDelegate = widget.pickerConfig.textDelegate ??
cameraPickerTextDelegateFromLocale(widget.locale);
initCameras();
initAccelerometerSubscription();
}
@override
void dispose() {
ambiguate(WidgetsBinding.instance)?.removeObserver(this);
final c = innerController;
innerController = null;
c?.dispose();
currentExposureOffset.dispose();
currentExposureSliderOffset.dispose();
lastExposurePoint.dispose();
isFocusPointDisplays.dispose();
isFocusPointFadeOut.dispose();
exposurePointDisplayTimer?.cancel();
exposureModeDisplayTimer?.cancel();
exposureFadeOutTimer?.cancel();
recordDetectTimer?.cancel();
recordCountdownTimer?.cancel();
accelerometerSubscription?.cancel();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final CameraController? c = innerController;
if (state == AppLifecycleState.resumed && !accessDenied) {
initCameras(
cameraDescription: cameras.elementAtOrNull(currentCameraIndex),
);
} else if (c == null || !c.value.isInitialized) {
// App state changed before we got the chance to initialize.
return;
} else if (state == AppLifecycleState.inactive) {
c.dispose();
innerController = null;
isControllerBusy = false;
}
}
/// Adjust the proper scale type according to the [constraints].
/// 根据 [constraints] 获取相机预览适用的缩放。
double effectiveCameraScale(
BoxConstraints constraints,
CameraController? controller,
) {
if (controller == null) {
return 1;
}
final int turns = cameraQuarterTurns;
final String orientation = controller.value.deviceOrientation.toString();
// Fetch the biggest size from the constraints.
Size size = constraints.biggest;
// Flip the size when the preview needs to turn with an odd count of quarters.
if ((turns.isOdd && orientation.contains('portrait')) ||
(turns.isEven && orientation.contains('landscape'))) {
size = size.flipped;
}
// Calculate scale depending on the size and camera ratios.
double scale = size.aspectRatio * controller.value.aspectRatio;
// Prevent scaling down.
if (scale < 1) {
scale = 1 / scale;
}
return scale;
}
/// Wraps [CameraController] methods with invalid controls.
/// Returns the [fallback] value if invalid and [T] is non-void.
///
/// 对于 [CameraController] 的方法增加是否无效的控制。
/// 如果 [T] 是非 void 且方法无效,返回 [fallback]。
Future<T?> wrapControllerMethod<T>(
String key,
Future<T> Function() method, {
CameraDescription? description,
VoidCallback? onError,
T? fallback,
}) async {
description ??= currentCamera;
if (invalidControllerMethods[description]!.contains(key)) {
return fallback;
}
try {
return await method();
} catch (e) {
invalidControllerMethods[description]!.add(key);
onError?.call();
rethrow;
}
}
/// Initialize cameras instances.
/// 初始化相机实例
Future<void> initCameras({
CameraDescription? cameraDescription,
bool ignoreLocks = false,
}) {
if (initializeLock != null && !ignoreLocks) {
return initializeLock!.future;
}
final lock = ignoreLocks ? initializeLock! : Completer<void>();
if (lock != initializeLock) {
initializeLock = lock;
}
Future(() async {
// Save the current controller to a local variable.
final CameraController? c = innerController;
// Dispose at last to avoid disposed usage with assertions.
if (c != null) {
innerController = null;
await c.dispose();
}
// Then request a new frame to unbind the controller from elements.
safeSetState(() {
maxAvailableZoom = 1;
minAvailableZoom = 1;
currentZoom = 1;
baseZoom = 1;
// Meanwhile, cancel the existed exposure point and mode display.
exposurePointDisplayTimer?.cancel();
exposureModeDisplayTimer?.cancel();
exposureFadeOutTimer?.cancel();
isFocusPointDisplays.value = false;
isFocusPointFadeOut.value = false;
lastExposurePoint.value = null;
currentExposureOffset.value = 0;
currentExposureSliderOffset.value = 0;
lockedCaptureOrientation = pickerConfig.lockCaptureOrientation;
});
await Future.microtask(() {});
// When the [cameraDescription] is null, which means this is the first
// time initializing cameras, so available cameras should be fetched.
if (cameraDescription == null) {
cameras = await availableCameras();
}
// After cameras fetched, judge again with the list is empty or not to
// ensure there is at least an available camera for use.
if (cameraDescription == null && cameras.isEmpty) {
handleErrorWithHandler(
CameraException(
'No CameraDescription found.',
'No cameras are available in the controller.',
),
StackTrace.current,
pickerConfig.onError,
);
return;
}
initFlashModesForCameras();
final int preferredIndex = cameras.indexWhere(
(CameraDescription e) =>
e.lensDirection == pickerConfig.preferredLensDirection,
);
final int index;
if (preferredIndex != -1 && c == null) {
index = preferredIndex;
currentCameraIndex = preferredIndex;
} else {
index = currentCameraIndex;
}
// Initialize the controller with the given resolution preset.
final description = cameraDescription ?? cameras[index];
invalidControllerMethods[description] ??= <String>{};
final CameraController newController = CameraController(
description,
pickerConfig.resolutionPreset,
enableAudio: enableAudio,
imageFormatGroup: pickerConfig.imageFormatGroup,
);
try {
final Stopwatch stopwatch = Stopwatch()..start();
await newController.initialize();
stopwatch.stop();
realDebugPrint(
"${stopwatch.elapsed} for controller's initialization.",
);
// Call recording preparation first.
if (shouldPrepareForVideoRecording) {
stopwatch
..reset()
..start();
await newController.prepareForVideoRecording();
stopwatch.stop();
realDebugPrint("${stopwatch.elapsed} for recording's preparation.");
}
// Then call other asynchronous methods.
stopwatch
..reset()
..start();
await Future.wait(
<Future<void>>[
wrapControllerMethod(
'getExposureOffsetStepSize',
() => newController.getExposureOffsetStepSize(),
description: description,
fallback: exposureStep,
).then((value) => exposureStep = value!),
wrapControllerMethod(
'getMaxExposureOffset',
() => newController.getMaxExposureOffset(),
description: description,
fallback: maxAvailableExposureOffset,
).then((value) => maxAvailableExposureOffset = value!),
wrapControllerMethod(
'getMinExposureOffset',
() => newController.getMinExposureOffset(),
description: description,
fallback: minAvailableExposureOffset,
).then((value) => minAvailableExposureOffset = value!),
wrapControllerMethod(
'getMaxZoomLevel',
() => newController.getMaxZoomLevel(),
description: description,
fallback: maxAvailableZoom,
).then((value) => maxAvailableZoom = value!),
wrapControllerMethod(
'getMinZoomLevel',
() => newController.getMinZoomLevel(),
description: description,
fallback: minAvailableZoom,
).then((value) => minAvailableZoom = value!),
wrapControllerMethod(
'getMinZoomLevel',
() => newController.getMinZoomLevel(),
description: description,
fallback: minAvailableZoom,
).then((value) => minAvailableZoom = value!),
if (pickerConfig.lockCaptureOrientation != null)
wrapControllerMethod<void>(
'lockCaptureOrientation',
() => newController.lockCaptureOrientation(
pickerConfig.lockCaptureOrientation,
),
description: description,
),
// Do not set flash modes for the front camera.
if (description.lensDirection != CameraLensDirection.front &&
pickerConfig.preferredFlashMode != FlashMode.auto)
wrapControllerMethod<void>(
'setFlashMode',
() => newController.setFlashMode(
pickerConfig.preferredFlashMode,
),
description: description,
onError: () {
validFlashModes[description]?.remove(
pickerConfig.preferredFlashMode,
);
},
),
],
eagerError: false,
);
stopwatch.stop();
realDebugPrint("${stopwatch.elapsed} for config's update.");
innerController = newController;
lock.complete();
} catch (e, s) {
accessDenied = e is CameraException && e.code.contains('Access');
if (!accessDenied) {
if (!retriedAfterInvalidInitialize) {
retriedAfterInvalidInitialize = true;
Future.delayed(Duration.zero, () {
initCameras(
cameraDescription: cameraDescription,
ignoreLocks: true,
);
});
} else {
retriedAfterInvalidInitialize = false;
lock.completeError(e, s);
}
} else {
lock.completeError(e, s);
}
}
});
return lock.future.catchError((e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
}).whenComplete(() {
initializeLock = null;
safeSetState(() {});
});
}
/// Starts to listen on accelerometer events.
void initAccelerometerSubscription() {
try {
final stream = accelerometerEventStream();
accelerometerSubscription = stream.listen(handleAccelerometerEvent);
} catch (e, s) {
realDebugPrint(
'The device does not seem to support accelerometer. '
'The captured files orientation might be incorrect.',
);
handleErrorWithHandler(e, s, pickerConfig.onError);
}
}
/// Lock capture orientation according to the current status of the device,
/// which enables the captured file stored the correct orientation.
void handleAccelerometerEvent(AccelerometerEvent event) {
if (!mounted ||
pickerConfig.lockCaptureOrientation != null ||
innerController == null ||
!controller.value.isInitialized ||
controller.value.isPreviewPaused ||
controller.value.isRecordingVideo ||
controller.value.isTakingPicture) {
return;
}
final x = event.x, y = event.y, z = event.z;
final DeviceOrientation? newOrientation;
if (x.abs() > y.abs() && x.abs() > z.abs()) {
if (x > 0) {
newOrientation = DeviceOrientation.landscapeLeft;
} else {
newOrientation = DeviceOrientation.landscapeRight;
}
} else if (y.abs() > x.abs() && y.abs() > z.abs()) {
if (y > 0) {
newOrientation = DeviceOrientation.portraitUp;
} else {
newOrientation = DeviceOrientation.portraitDown;
}
} else {
newOrientation = null;
}
// Throttle.
if (newOrientation != null && lockedCaptureOrientation != newOrientation) {
lockedCaptureOrientation = newOrientation;
realDebugPrint('Locking new capture orientation: $newOrientation');
controller.lockCaptureOrientation(newOrientation);
}
}
/// Initializes the flash modes in [validFlashModes] for each
/// [CameraDescription].
/// 为每个 [CameraDescription] 在 [validFlashModes] 中初始化闪光灯模式。
void initFlashModesForCameras() {
for (final CameraDescription camera in cameras) {
if (!validFlashModes.containsKey(camera)) {
// Mind the order of this list as it has an impact on the switch cycle.
// Do not use FlashMode.values.
validFlashModes[camera] = <FlashMode>[
FlashMode.auto,
FlashMode.always,
FlashMode.torch,
FlashMode.off,
];
}
}
}
/// Switch cameras in order. When the [currentCameraIndex] reached the length
/// of cameras, start from the beginning.
/// 按顺序切换相机。当达到相机数量时从头开始。
void switchCameras() {
// Skip switching when taking picture or recording video.
if (controller.value.isTakingPicture || controller.value.isRecordingVideo) {
return;
}
final preferredCameras = CameraLensDirection.values
.map((e) => cameras.firstWhereOrNull((c) => c.lensDirection == e))
.whereType<CameraDescription>()
.map((e) => cameras.indexOf(e))
.toList();
int index = preferredCameras.indexOf(currentCameraIndex);
++index;
if (index == preferredCameras.length) {
index = 0;
}
currentCameraIndex = preferredCameras[index];
initCameras(cameraDescription: currentCamera);
}
/// Obtain the next camera description for semantics.
CameraDescription get nextCameraDescription {
final int nextIndex = currentCameraIndex + 1;
if (nextIndex == cameras.length) {
return cameras[0];
}
return cameras[nextIndex];
}
/// The method to switch between flash modes.
/// 切换闪光灯模式的方法
Future<void> switchFlashesMode(CameraValue value) async {
final List<FlashMode> flashModes = validFlashModes[currentCamera]!;
if (flashModes.isEmpty) {
// Unlikely event that no flash mode is valid for current camera.
handleErrorWithHandler(
CameraException(
'No FlashMode found.',
'No flash modes are available with the camera.',
),
StackTrace.current,
pickerConfig.onError,
);
return;
}
final int currentFlashModeIndex = flashModes.indexOf(value.flashMode);
final int nextFlashModeIndex;
if (currentFlashModeIndex + 1 >= flashModes.length) {
nextFlashModeIndex = 0;
} else {
nextFlashModeIndex = currentFlashModeIndex + 1;
}
final FlashMode nextFlashMode = flashModes[nextFlashModeIndex];
try {
await controller.setFlashMode(nextFlashMode);
} catch (e, s) {
// Remove the flash mode that throws an exception.
validFlashModes[currentCamera]!.remove(nextFlashMode);
switchFlashesMode(value);
handleErrorWithHandler(e, s, pickerConfig.onError);
}
}
Future<void> zoom(double scale) async {
if (maxAvailableZoom == minAvailableZoom) {
return;
}
if (recordDetectTimer?.isActive ?? false) {
return;
}
final double zoom = (baseZoom * scale).clamp(
minAvailableZoom,
maxAvailableZoom,
);
if (zoom == currentZoom) {
return;
}
currentZoom = zoom;
try {
await controller.setZoomLevel(currentZoom);
} catch (e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
}
}
/// Handle when the scale gesture start.
/// 处理缩放开始的手势
void handleScaleStart(ScaleStartDetails details) {
baseZoom = currentZoom;
}
/// Handle when the double tap scale details is updating.
/// 处理双指缩放更新
Future<void> handleScaleUpdate(ScaleUpdateDetails details) async {
// When there are not exactly two fingers on screen don't scale
if (innerController == null || pointers != 2) {
return;
}
zoom(details.scale * 2 - 1);
}
void restartExposurePointDisplayTimer() {
exposurePointDisplayTimer?.cancel();
exposurePointDisplayTimer = Timer(const Duration(seconds: 5), () {
lastExposurePoint.value = null;
});
}
void restartExposureModeDisplayTimer() {
exposureModeDisplayTimer?.cancel();
exposureModeDisplayTimer = Timer(const Duration(seconds: 2), () {
isFocusPointDisplays.value = false;
});
}
void restartExposureFadeOutTimer() {
isFocusPointFadeOut.value = false;
exposureFadeOutTimer?.cancel();
exposureFadeOutTimer = Timer(const Duration(seconds: 2), () {
isFocusPointFadeOut.value = true;
});
}
/// Use the specific [mode] to update the exposure mode.
/// 设置曝光模式
Future<void> switchExposureMode() async {
final ExposureMode mode = controller.value.exposureMode;
final ExposureMode newMode;
if (mode == ExposureMode.auto) {
newMode = ExposureMode.locked;
} else {
newMode = ExposureMode.auto;
}
exposurePointDisplayTimer?.cancel();
if (newMode == ExposureMode.auto) {
exposurePointDisplayTimer = Timer(const Duration(seconds: 5), () {
lastExposurePoint.value = null;
});
}
try {
await controller.setExposureMode(newMode);
} catch (e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
} finally {
restartExposureModeDisplayTimer();
restartExposureFadeOutTimer();
}
}
/// Use the [position] to set exposure and focus.
/// 通过点击点的 [position] 设置曝光和对焦。
Future<void> setExposureAndFocusPoint(
Offset position,
BoxConstraints constraints,
) async {
isFocusPointDisplays.value = false;
if (enableScaledPreview) {
// Ignore point update when the new point is less than 8% and higher than
// 92% of the screen's height.
if (position.dy < constraints.maxHeight / 12 ||
position.dy > constraints.maxHeight / 12 * 11) {
return;
}
}
realDebugPrint(
'Setting new exposure point (x: ${position.dx}, y: ${position.dy})',
);
lastExposurePoint.value = position;
restartExposurePointDisplayTimer();
currentExposureOffset.value = 0;
currentExposureSliderOffset.value = 0;
restartExposureFadeOutTimer();
isFocusPointFadeOut.value = false;
try {
await Future.wait(<Future<void>>[
wrapControllerMethod<void>(
'setExposureOffset',
() => controller.setExposureOffset(0),
),
controller.setExposureOffset(0),
if (controller.value.exposureMode == ExposureMode.locked)
wrapControllerMethod<void>(
'setExposureMode',
() => controller.setExposureMode(ExposureMode.auto),
),
]);
final Offset newPoint = lastExposurePoint.value!.scale(
1 / constraints.maxWidth,
1 / constraints.maxHeight,
);
await Future.wait(<Future<void>>[
if (controller.value.exposurePointSupported)
controller.setExposurePoint(newPoint),
if (controller.value.focusPointSupported)
controller.setFocusPoint(newPoint),
]);
} catch (e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
}
}
/// Update the exposure offset using the exposure controller.
/// 使用曝光控制器更新曝光值
Future<void> updateExposureOffset(double value) async {
final previousSliderOffsetValue = currentExposureSliderOffset.value;
currentExposureSliderOffset.value = value;
// Normalize the new exposure value if exposures have steps.
if (exposureStep > 0) {
final double inv = 1.0 / exposureStep;
double roundedOffset = (value * inv).roundToDouble() / inv;
if (roundedOffset > maxAvailableExposureOffset) {
roundedOffset = (value * inv).floorToDouble() / inv;
} else if (roundedOffset < minAvailableExposureOffset) {
roundedOffset = (value * inv).ceilToDouble() / inv;
}
value = roundedOffset;
}
if (value == currentExposureOffset.value ||
value < minAvailableExposureOffset ||
value > maxAvailableExposureOffset) {
return;
}
final previousOffsetValue = currentExposureOffset.value;
currentExposureOffset.value = value;
bool hasError = false;
try {
realDebugPrint('Updating the exposure offset value: $value');
// Use [CameraPlatform] explicitly to reduce channel calls.
await wrapControllerMethod(
'setExposureOffset',
() => CameraPlatform.instance.setExposureOffset(
controller.cameraId,
value,
),
);
} catch (e, s) {
hasError = true;
currentExposureSliderOffset.value = previousSliderOffsetValue;
currentExposureOffset.value = previousOffsetValue;
handleErrorWithHandler(e, s, pickerConfig.onError);
} finally {
if (!hasError && !isFocusPointDisplays.value) {
isFocusPointDisplays.value = true;
}
restartExposurePointDisplayTimer();
restartExposureModeDisplayTimer();
restartExposureFadeOutTimer();
}
}
/// Request to set the focus and the exposure point on the [localPosition],
/// [lock] to lock the exposure mode at the same time.
/// 将对焦和曝光设置为给定的点 [localPosition],[lock] 控制是否同时锁定曝光模式。
Future<void> requestFocusAndExposureOnPosition(
Offset localPosition,
BoxConstraints constraints, {
bool lock = false,
}) async {
// Only call exposure point updates when the controller is initialized.
if (innerController?.value.isInitialized ?? false) {
Feedback.forTap(context);
await setExposureAndFocusPoint(localPosition, constraints);
if (lock) {
await switchExposureMode();
}
}
}
/// Update the scale value while the user is shooting.
/// 用户在录制时通过滑动更新缩放
void onShootingButtonMove(
PointerMoveEvent event,
BoxConstraints constraints,
) {
lastShootingButtonPressedPosition ??= event.position;
if (innerController?.value.isRecordingVideo == true) {
// First calculate relative offset.
final Offset offset = event.position - lastShootingButtonPressedPosition!;
// Then turn negative,
// multiply double with 10 * 1.5 - 1 = 14,
// plus 1 to ensure always scale.
final double scale = offset.dy / constraints.maxHeight * -14 + 1;
zoom(scale);
}
}
/// The picture will only taken when [CameraValue.isInitialized],
/// and the camera is not taking pictures.
/// 仅当初始化成功且相机未在拍照时拍照。
Future<void> takePicture() async {
if (!controller.value.isInitialized) {
handleErrorWithHandler(
StateError('Camera has not initialized.'),
StackTrace.current,
pickerConfig.onError,
);
}
if (isControllerBusy) {
return;
}
setState(() {
isControllerBusy = true;
});
final ExposureMode previousExposureMode = controller.value.exposureMode;
try {
await Future.wait(<Future<void>>[
wrapControllerMethod<void>(
'setFocusMode',
() => controller.setFocusMode(FocusMode.locked),
).catchError((e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
}),
if (previousExposureMode != ExposureMode.locked)
wrapControllerMethod<void>(
'setExposureMode',
() => controller.setExposureMode(ExposureMode.locked),
).catchError((e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
}),
]);
final XFile file = await controller.takePicture();
await controller.pausePreview();
final bool? isCapturedFileHandled = pickerConfig.onXFileCaptured?.call(
file,
CameraPickerViewType.image,
);
if (isCapturedFileHandled ?? false) {
return;
}
final AssetEntity? entity = await pushToViewer(
file: file,
viewType: CameraPickerViewType.image,
);
if (entity != null) {
if (pickerConfig.onPickConfirmed case final onPickConfirmed?) {
onPickConfirmed(entity);
} else {
return Navigator.of(context).pop(entity);
}
}
wrapControllerMethod<void>(
'setFocusMode',
() => controller.setFocusMode(FocusMode.auto),
);
if (previousExposureMode != ExposureMode.locked) {
wrapControllerMethod<void>(
'setExposureMode',
() => controller.setExposureMode(previousExposureMode),
);
}
await controller.resumePreview();
} catch (e, s) {
handleErrorWithHandler(e, s, pickerConfig.onError);
} finally {
safeSetState(() {
isControllerBusy = false;
isShootingButtonAnimate = false;
});
}
}
/// When the [buildCaptureButton]'s `onLongPress` called,
/// the [recordDetectTimer] will be initialized for the press time detection.
/// If the duration reached to same as [recordDetectDuration] and the timer is
/// still active, start recording video.
/// 当 [buildCaptureButton] 触发了长按,初始化一个定时器来实现时间检测。如果长按时间
/// 达到了 [recordDetectDuration] 且定时器未被销毁,则开始录制视频。
void recordDetection() {
recordDetectTimer = Timer(recordDetectDuration, () {
startRecordingVideo();
safeSetState(() {});
});
setState(() {
isShootingButtonAnimate = true;
});
}
/// This will be given to the [Listener] in the [buildCaptureButton]. When it's
/// called, which means no more pressing on the button, cancel the timer and
/// reset the status.
/// 这个方法会赋值给 [buildCaptureButton] 中的 [Listener]。当按钮释放了点击后,定时器
/// 将被取消,并且状态会重置。
void recordDetectionCancel(PointerUpEvent event) {
recordDetectTimer?.cancel();
if (innerController?.value.isRecordingVideo == true) {
stopRecordingVideo();
}
}
/// Set record file path and start recording.
/// 设置拍摄文件路径并开始录制视频
Future<void> startRecordingVideo() async {
if (isControllerBusy) {
return;
}
isControllerBusy = true;