-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.android.ts
1063 lines (952 loc) · 32.9 KB
/
index.android.ts
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
/**********************************************************************************
* (c) 2017, nStudio, LLC & LiveShopper, LLC
*
* Version 1.1.0 team@nStudio.io
**********************************************************************************/
import * as permissions from 'nativescript-permissions';
import { AndroidActivityResultEventData, AndroidApplication, Application, Device, ImageAsset, Utils, View } from '@nativescript/core';
import { CameraPlusBase, CameraVideoQuality, CLog, GetSetProperty, ICameraOptions, ICameraPlusEvents, IChooseOptions, IVideoOptions, WhiteBalance } from './common';
import * as CamHelpers from './helpers';
import { SelectedAsset } from './selected-asset';
export * from './common';
export { CameraVideoQuality, WhiteBalance } from './common';
import fancycamera = com.github.triniwiz.fancycamera;
const REQUEST_VIDEO_CAPTURE = 999;
const WRAP_CONTENT = -2;
const ALIGN_PARENT_TOP = 10;
const ALIGN_PARENT_BOTTOM = 12;
const ALIGN_PARENT_LEFT = 9;
const ALIGN_PARENT_RIGHT = 11;
const CENTER_HORIZONTAL = 14;
const DIRECTORY_PICTURES = 'DIRECTORY_PICTURES';
const DIRECTORY_MOVIES = 'DIRECTORY_MOVIES';
const FOCUS_MODE_AUTO = 'auto';
const FOCUS_MODE_EDOF = 'edof';
const FOCUS_MODE_CONTINUOUS_PICTURE = 'continuous-picture';
const FOCUS_MODE_CONTINUOUS_VIDEO = 'continuous-video';
const FLASH_MODE_ON = 'on';
const FLASH_MODE_OFF = 'off';
const CAMERA_FACING_FRONT = 1; // front camera
const CAMERA_FACING_BACK = 0; // rear camera
const RESULT_CODE_PICKER_IMAGES = 941;
const RESULT_OK = -1;
// AndroidX support
// Snapshot-friendly functions
const CAMERA = () => android.Manifest.permission.CAMERA;
const RECORD_AUDIO = () => android.Manifest.permission.RECORD_AUDIO;
const READ_EXTERNAL_STORAGE = () => android.Manifest.permission.READ_EXTERNAL_STORAGE;
const WRITE_EXTERNAL_STORAGE = () => android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
// Since these device.* properties resolve directly to the android.* namespace,
// the snapshot will fail if they resolve during import, so must be done via a function
const DEVICE_INFO_STRING = () => `Device: ${Device.manufacturer} ${Device.model} on SDK: ${Device.sdkVersion}`;
export class CameraPlus extends CameraPlusBase {
// @GetSetProperty() public camera: android.hardware.Camera;
// Snapshot-friendly, since the decorator will include the snapshot-unknown object "android"
private _camera: fancycamera.FancyCamera;
private _cameraId;
@GetSetProperty()
public flashOnIcon: string = 'ic_flash_on_white';
@GetSetProperty()
public flashOffIcon: string = 'ic_flash_off_white';
@GetSetProperty()
public toggleCameraIcon: string = 'ic_switch_camera_white';
@GetSetProperty()
public confirmPhotos: boolean = true;
@GetSetProperty()
public saveToGallery: boolean = false;
@GetSetProperty()
public takePicIcon: string = 'ic_camera_white';
@GetSetProperty()
public galleryIcon: string = 'ic_photo_library_white';
@GetSetProperty()
public insetButtons: boolean = false;
@GetSetProperty()
public insetButtonsPercent: number = 0.1;
@GetSetProperty()
public enableVideo: boolean;
@GetSetProperty()
public isRecording: boolean;
public events: ICameraPlusEvents;
private _nativeView: android.widget.RelativeLayout;
private _owner: WeakRef<any>;
private _mediaRecorder: android.media.MediaRecorder;
private _textureSurface: android.view.Surface;
private _textureView: android.view.TextureView;
private _surface: android.graphics.SurfaceTexture; // reference to surface to ensure toggling the camera works correctly
private _flashBtn: android.widget.ImageButton = null; // reference to native flash button
private _takePicBtn: android.widget.ImageButton = null; // reference to native take picture button
private _toggleCamBtn: android.widget.ImageButton = null; // reference to native toggle camera button
private _galleryBtn: android.widget.ImageButton = null; // reference to native open gallery button
private _videoOptions: IVideoOptions;
private _videoPath: string;
readonly _context; // defining this to pass TS warning, NS provides the context during lifecycle
_lastCameraOptions: ICameraOptions[];
constructor() {
super();
this._camera = null;
this._textureSurface = null;
this.flashOnIcon = this.flashOnIcon ? this.flashOnIcon : 'ic_flash_on_white';
this.flashOffIcon = this.flashOffIcon ? this.flashOffIcon : 'ic_flash_off_white';
this.toggleCameraIcon = this.toggleCameraIcon ? this.toggleCameraIcon : 'ic_switch_camera_white';
this.takePicIcon = this.takePicIcon ? this.takePicIcon : 'ic_camera_alt_white';
this.galleryIcon = this.galleryIcon ? this.galleryIcon : 'ic_photo_library_white';
this.cameraId = CameraPlus.defaultCamera === 'front' ? CAMERA_FACING_FRONT : CAMERA_FACING_BACK;
this._onLayoutChangeListener = this._onLayoutChangeFn.bind(this);
this._permissionListener = this._permissionListenerFn.bind(this);
this._lastCameraOptions = [];
}
private isVideoEnabled() {
return this.enableVideo === true || CameraPlus.enableVideo;
}
// @ts-ignore
get ratio() {
return this._camera ? this._camera.getRatio() : '4:3';
}
set ratio(value: string) {
if (this._camera) {
this._camera.setRatio(value);
}
}
// @ts-ignore
get zoom() {
return this._camera ? this._camera.getZoom() : 0;
}
set zoom(value: number) {
if (this._camera) {
this._camera.setZoom(value);
}
}
// @ts-ignore
set whiteBalance(value: WhiteBalance | string) {
if (this._camera) {
switch (value) {
case WhiteBalance.Cloudy:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Cloudy);
break;
case WhiteBalance.Fluorescent:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Fluorescent);
break;
case WhiteBalance.Incandescent:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Incandescent);
break;
case WhiteBalance.Shadow:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Shadow);
break;
case WhiteBalance.Sunny:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Sunny);
break;
case WhiteBalance.Twilight:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Twilight);
break;
case WhiteBalance.WarmFluorescent:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.WarmFluorescent);
break;
default:
this._camera.setWhiteBalance(fancycamera.WhiteBalance.Auto);
break;
}
}
}
get whiteBalance(): WhiteBalance | string {
if (this._camera) {
switch (this._camera.getWhiteBalance()) {
case fancycamera.WhiteBalance.Cloudy:
return WhiteBalance.Cloudy;
case fancycamera.WhiteBalance.Fluorescent:
return WhiteBalance.Fluorescent;
case fancycamera.WhiteBalance.Incandescent:
return WhiteBalance.Incandescent;
case fancycamera.WhiteBalance.Shadow:
return WhiteBalance.Shadow;
case fancycamera.WhiteBalance.Sunny:
return WhiteBalance.Sunny;
case fancycamera.WhiteBalance.Twilight:
return WhiteBalance.Twilight;
case fancycamera.WhiteBalance.WarmFluorescent:
return WhiteBalance.WarmFluorescent;
default:
return WhiteBalance.Auto;
}
}
return WhiteBalance.Auto;
}
/**
* @param ratio get the sizes for a given ratio, i.e. '16:9'.
*/
public getAvailablePictureSizes(ratio: string): string[] {
const sizes = [];
if (this._camera && typeof ratio === 'string') {
const nativeSizes: any = this._camera.getAvailablePictureSizes(ratio);
for (const size of nativeSizes) {
sizes.push(`${size.getWidth()}x${size.getHeight()}`);
}
}
return sizes;
}
public getSupportedRatios(): string[] {
const ratios = [];
if (this._camera) {
const nativeRatios = this._camera.getGetSupportedRatios();
for (let i = 0; i < nativeRatios.length; i++) {
const ratio = nativeRatios[i];
ratios.push(ratio);
}
}
return ratios;
}
// @ts-ignore
set pictureSize(value: string) {
if (this._camera) {
this._camera.setPictureSize(value);
}
}
get pictureSize(): string {
return this._camera ? this._camera.getPictureSize() : '0x0';
}
get camera() {
return this._camera;
}
/**
* Create the native view
*/
public createNativeView() {
// create the Android RelativeLayout
Application.android.on('activityRequestPermissions', this._permissionListener);
this._nativeView = new android.widget.RelativeLayout(this._context);
this._camera = new fancycamera.FancyCamera(this._context);
this._camera.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT));
this._nativeView.addView(this._camera);
return this._nativeView;
}
private _onLayoutChangeFn(args) {
const size = this.getActualSize();
CLog('xml width/height:', size.width + 'x' + size.height);
this._initDefaultButtons();
}
private _onLayoutChangeListener: any;
private _permissionListener: any;
private _permissionListenerFn(args) {
if (this._camera) {
CLog('', this._camera.hasCameraPermission() || this._camera.hasPermission());
if (this._camera.hasCameraPermission() || this._camera.hasPermission()) {
this._camera.startPreview();
}
}
}
public initNativeView() {
super.initNativeView();
this.on(View.layoutChangedEvent, this._onLayoutChangeListener);
const listenerImpl = (fancycamera.CameraEventListenerUI as any).extend({
owner: null,
onReady(): void {},
onCameraCloseUI(): void {},
onCameraError(message: string, ex: java.lang.Exception): void {
console.log('onCameraError', message);
ex.printStackTrace();
const owner = this.owner ? this.owner.get() : null;
if (owner) {
owner._lastCameraOptions.shift();
CLog(message, null);
owner.sendEvent(CameraPlus.errorEvent, null, message);
if (owner.isRecording) {
owner.isRecording = false;
}
}
},
async onCameraPhotoUI(event?: java.io.File) {
const owner = this.owner ? this.owner.get() : null;
const file = event;
const options = owner._lastCameraOptions.shift();
let confirmPic;
let confirmPicRetakeText;
let confirmPicSaveText;
let saveToGallery;
let reqWidth;
let reqHeight;
let shouldKeepAspectRatio;
let shouldAutoSquareCrop = owner.autoSquareCrop;
const density = Utils.layout.getDisplayDensity();
if (options) {
confirmPic = options.confirm ? true : false;
confirmPicRetakeText = options.confirmRetakeText ? options.confirmRetakeText : owner.confirmRetakeText;
confirmPicSaveText = options.confirmSaveText ? options.confirmSaveText : owner.confirmSaveText;
saveToGallery = options.saveToGallery ? true : false;
reqWidth = options.width ? options.width * density : 0;
reqHeight = options.height ? options.height * density : reqWidth;
shouldKeepAspectRatio = Utils.isNullOrUndefined(options.keepAspectRatio) ? true : options.keepAspectRatio;
shouldAutoSquareCrop = !!options.autoSquareCrop;
} else {
// use xml property getters or their defaults
CLog('Using property getters for defaults, no options.');
confirmPic = owner.confirmPhotos;
saveToGallery = owner.saveToGallery;
}
if (confirmPic === true) {
owner.sendEvent(CameraPlus.confirmScreenShownEvent);
const result = await CamHelpers.createImageConfirmationDialog(file.getAbsolutePath(), confirmPicRetakeText, confirmPicSaveText).catch((ex) => {
CLog('Error createImageConfirmationDialog', ex);
});
owner.sendEvent(CameraPlus.confirmScreenDismissedEvent);
CLog(`confirmation result = ${result}`);
if (result !== true) {
file.delete();
return;
}
const asset = CamHelpers.assetFromPath(file.getAbsolutePath(), reqWidth, reqHeight, shouldKeepAspectRatio);
owner.sendEvent(CameraPlus.photoCapturedEvent, asset);
return;
} else {
const asset = CamHelpers.assetFromPath(file.getAbsolutePath(), reqWidth, reqHeight, shouldKeepAspectRatio);
owner.sendEvent(CameraPlus.photoCapturedEvent, asset);
return;
}
},
onCameraOpenUI(): void {
const owner = this.owner ? this.owner.get() : null;
if (owner) {
owner._initDefaultButtons();
if (owner._togglingCamera) {
owner.sendEvent(CameraPlus.toggleCameraEvent, owner.camera);
owner._ensureCorrectFlashIcon();
owner._togglingCamera = true;
} else {
owner.sendEvent('loaded', owner.camera);
}
}
},
onCameraVideoStartUI(): void {
const owner = this.owner ? this.owner.get() : null;
if (owner) {
owner.isRecording = true;
owner.sendEvent(CameraPlus.videoRecordingStartedEvent, owner.camera);
}
},
onCameraVideoUI(event?: java.io.File): void {
const owner = this.owner ? this.owner.get() : null;
if (owner) {
owner.sendEvent(CameraPlus.videoRecordingReadyEvent, event.getAbsolutePath());
CLog(`Recording complete`);
owner.isRecording = false;
}
},
onCameraAnalysisUI(imageAnalysis: fancycamera.ImageAnalysis): void {},
});
const listener = new listenerImpl();
listener.owner = new WeakRef(this);
this._camera.setListener(listener);
this.cameraId = this._cameraId;
}
disposeNativeView() {
CLog('disposeNativeView.');
this.off(View.layoutChangedEvent, this._onLayoutChangeListener);
Application.android.off('activityRequestPermissions', this._permissionListener);
this.releaseCamera();
super.disposeNativeView();
}
get cameraId() {
return this._cameraId;
}
set cameraId(id: any) {
if (this._camera) {
switch (id) {
case CAMERA_FACING_FRONT:
this._camera.setPosition(fancycamera.CameraPosition.FRONT);
this._cameraId = CAMERA_FACING_FRONT;
break;
default:
this._camera.setPosition(fancycamera.CameraPosition.BACK);
this._cameraId = CAMERA_FACING_BACK;
break;
}
}
this._cameraId = id;
}
/**
* Takes a picture with from the camera preview.
*/
public takePicture(options?: ICameraOptions): void {
if (this._camera) {
options = options || {};
CLog(JSON.stringify(options));
const hasCamPerm = this.hasCameraPermission();
if (!hasCamPerm) {
CLog('Application does not have permission to use Camera.');
return;
}
if (!!options.useCameraOptions && typeof options.width === 'number' && typeof options.height === 'number') {
(this._camera as any).setOverridePhotoWidth(options.width);
(this._camera as any).setOverridePhotoHeight(options.height);
}
this._camera.setSaveToGallery(!!options.saveToGallery);
this._camera.setAutoSquareCrop(!!options.autoSquareCrop);
this._lastCameraOptions.push(options);
this._camera.takePhoto();
}
}
private releaseCamera() {
if (this._camera) {
this._camera.release();
}
}
// @ts-ignore
public get autoFocus(): boolean {
return this._camera ? this._camera.getAutoFocus() : false;
}
public set autoFocus(focus: boolean) {
if (this._camera) {
this._camera.setAutoFocus(focus);
}
}
_togglingCamera = false;
/**
* Toggle the opened camera. Only supported on devices with multiple cameras.
*/
public toggleCamera() {
if (this._camera) {
this._togglingCamera = true;
this._camera.toggleCamera();
const camNumber = this.getNumberOfCameras();
if (camNumber <= 1) {
CLog(`Android Device has ${camNumber} camera.`);
return;
}
this.sendEvent(CameraPlus.toggleCameraEvent, this.camera);
// need to check flash mode when toggling...
// front cam may not have flash - and just ensure the correct icon shows
this._ensureCorrectFlashIcon();
// try to set focus mode when camera gets toggled
this._ensureFocusMode();
}
}
public async record(options?: IVideoOptions) {
options = options || {};
if (this._camera) {
this._camera.setDisableHEVC(!!options.disableHEVC);
this._camera.setSaveToGallery(!!options.saveToGallery);
switch (options.quality) {
case CameraVideoQuality.HIGHEST:
this._camera.setQuality(fancycamera.Quality.HIGHEST);
break;
case CameraVideoQuality.LOWEST:
this._camera.setQuality(fancycamera.Quality.LOWEST);
break;
case CameraVideoQuality.MAX_2160P:
this._camera.setQuality(fancycamera.Quality.MAX_2160P);
break;
case CameraVideoQuality.MAX_1080P:
this._camera.setQuality(fancycamera.Quality.MAX_1080P);
break;
case CameraVideoQuality.MAX_720P:
this._camera.setQuality(fancycamera.Quality.MAX_720P);
break;
case CameraVideoQuality.QVGA:
this._camera.setQuality(fancycamera.Quality.QVGA);
break;
default:
this._camera.setQuality(fancycamera.Quality.MAX_480P);
break;
}
// -1 uses profile value;
this._camera.setMaxAudioBitRate(options.androidMaxAudioBitRate || -1);
this._camera.setMaxVideoBitrate(options.androidMaxVideoBitRate || -1);
this._camera.setMaxVideoFrameRate(options.androidMaxFrameRate || -1);
const permResult = await this.requestVideoRecordingPermissions();
CLog(permResult);
this._camera.startRecording();
}
}
/**
* Stop recording video
*/
public stop(): void {
this.stopRecording();
}
public stopRecording() {
if (this._camera) {
CLog(`*** stopping mediaRecorder ***`);
this._camera.stopRecording();
}
}
/**
* Open the device image picker
* @param options
*/
public chooseFromLibrary(options?: IChooseOptions): Promise<any> {
return new Promise((resolve, reject) => {
try {
const createThePickerIntent = () => {
const intent = new android.content.Intent() as android.content.Intent;
intent.setType('*/*');
if (!options) {
options = {
showImages: true,
showVideos: this.isVideoEnabled(),
};
}
if (options.showImages === undefined) {
options.showImages = true;
}
if (options.showVideos === undefined) {
options.showVideos = true;
}
let length = 0;
if (options.showImages) {
length++;
}
if (options.showVideos) {
length++;
}
const mimetypes = Array.create(java.lang.String, length);
let index = 0;
if (options.showImages) {
mimetypes[index] = 'image/*';
index++;
}
if (options.showVideos) {
mimetypes[index] = 'video/*';
}
// not in platform-declaration typings
intent.putExtra(android.content.Intent.EXTRA_MIME_TYPES, mimetypes);
intent.setAction('android.intent.action.GET_CONTENT');
// set the multiple picker mode
if (this.galleryPickerMode === 'multiple') {
intent.putExtra('android.intent.extra.ALLOW_MULTIPLE', true);
}
const onImagePickerResultEventListener = (event: AndroidActivityResultEventData) => {
if (event.requestCode === RESULT_CODE_PICKER_IMAGES && event.resultCode === RESULT_OK) {
try {
const data: android.content.Intent = event.intent;
const selectedImages = this.getSelectedImages(data);
this.sendEvent(CameraPlus.imagesSelectedEvent, selectedImages);
resolve(selectedImages);
} catch (error) {
CLog(error);
this.sendEvent(CameraPlus.errorEvent, error, 'Error with the image picker result.');
reject(error);
}
} else {
const error = new Error(`Image picker activity result code ${event.resultCode}`);
this.sendEvent(CameraPlus.errorEvent, error, error.message);
reject(error);
}
// Cleanup, remove bound listener.
Application.android.off(AndroidApplication.activityResultEvent, onImagePickerResultEventListener);
};
// Bind listener
Application.android.on(AndroidApplication.activityResultEvent, onImagePickerResultEventListener);
// Start the intent
Application.android.foregroundActivity.startActivityForResult(intent, RESULT_CODE_PICKER_IMAGES);
};
// Ensure storage permissions
if (!this.hasStoragePermissions()) {
permissions.requestPermissions([READ_EXTERNAL_STORAGE(), WRITE_EXTERNAL_STORAGE()]).then(() => {
if (!this.hasStoragePermissions()) {
const error = new Error('request for storage permissions denied');
this.sendEvent(CameraPlus.errorEvent, error, 'Error choosing an image from the device library.');
reject(error);
} else {
createThePickerIntent();
}
});
return;
}
createThePickerIntent();
} catch (e) {
this.sendEvent(CameraPlus.errorEvent, e, 'Error choosing an image from the device library.');
reject(e);
}
});
}
/**
* Collect images from intent and return a collection of Image Assets.
*
* @param intent
*/
private getSelectedImages(intent: android.content.Intent): ImageAsset[] {
const selectedImages: ImageAsset[] = [];
const clipData = intent.getClipData();
const imageFromUri = (uri: globalAndroid.net.Uri) => {
const selectedAssetUri = new SelectedAsset(uri).fileUri;
return new ImageAsset(selectedAssetUri);
};
if (clipData !== null) {
for (let i = 0; i < clipData.getItemCount(); i++) {
const clipItem = clipData.getItemAt(i);
const uri = clipItem.getUri();
const asset = imageFromUri(uri);
selectedImages.push(asset);
}
} else {
const uri = intent.getData();
const asset = imageFromUri(uri);
selectedImages.push(asset);
}
return selectedImages;
}
/**
* Toggles the flash mode of the camera.
*/
public toggleFlash() {
if (this._camera) {
// @ts-ignore
this._camera.toggleFlash();
}
}
/**
* Request permission to use device camera.
* @param explanation
*/
public requestCameraPermissions(explanation: string = ''): Promise<boolean> {
return new Promise((resolve, reject) => {
permissions
.requestPermission(CAMERA(), explanation)
.then(() => {
resolve(true);
})
.catch((err) => {
this.sendEvent(CameraPlus.errorEvent, err, 'Error requesting Camera permissions.');
reject(false);
});
});
}
/**
* Returns true if the CAMERA permission has been granted.
*/
public hasCameraPermission(): boolean {
return permissions.hasPermission(CAMERA());
}
/**
* Request permission to use record audio for video.
* @param explanation
*/
public requestAudioPermissions(explanation: string = ''): Promise<boolean> {
return new Promise((resolve, reject) => {
permissions
.requestPermission(RECORD_AUDIO(), explanation)
.then(() => {
resolve(true);
})
.catch((err) => {
this.sendEvent(CameraPlus.errorEvent, err, 'Error requesting Audio permission.');
reject(false);
});
});
}
/**
* Returns true if the RECORD_AUDIO permission has been granted.
*/
public hasAudioPermission(): boolean {
return permissions.hasPermission(RECORD_AUDIO());
}
/**
* Request permission to read/write to external storage.
* @param explanation
*/
public requestStoragePermissions(explanation: string = ''): Promise<boolean> {
return new Promise((resolve, reject) => {
permissions
.requestPermissions([WRITE_EXTERNAL_STORAGE(), READ_EXTERNAL_STORAGE()], explanation)
.then(() => {
resolve(true);
})
.catch((err) => {
this.sendEvent(CameraPlus.errorEvent, err, 'Error requesting Storage permissions.');
reject(false);
});
});
}
/**
* Returns true if the WRITE_EXTERNAL_STORAGE && READ_EXTERNAL_STORAGE permissions have been granted.
*/
public hasStoragePermissions(): boolean {
const writePerm = permissions.hasPermission(WRITE_EXTERNAL_STORAGE());
const readPerm = permissions.hasPermission(READ_EXTERNAL_STORAGE());
if (writePerm === true && readPerm === true) {
return true;
} else {
return false;
}
}
public requestVideoRecordingPermissions(explanation: string = ''): Promise<boolean> {
return new Promise(async (resolve, reject) => {
permissions
.requestPermissions([WRITE_EXTERNAL_STORAGE(), RECORD_AUDIO()], explanation)
.then(() => {
resolve(true);
})
.catch((err) => {
this.sendEvent(CameraPlus.errorEvent, err, 'Error requesting Video permissions.');
reject(false);
});
});
}
public hasVideoRecordingPermissions() {
const writePerm = permissions.hasPermission(WRITE_EXTERNAL_STORAGE());
const audio = permissions.hasPermission(RECORD_AUDIO());
if (writePerm === true && audio === true) {
return true;
} else {
return false;
}
}
/**
* Gets current camera selection
*/
public getCurrentCamera(): 'front' | 'rear' {
if (!this._camera) return 'rear';
switch (this._camera.getPosition()) {
case fancycamera.CameraPosition.FRONT:
return 'front';
default:
return 'rear';
}
}
/**
* Check if the device has a camera
*/
public isCameraAvailable() {
if (Utils.ad.getApplicationContext().getPackageManager().hasSystemFeature('android.hardware.camera')) {
return true;
} else {
return false;
}
}
/**
* Returns number of cameras on device
*/
public getNumberOfCameras(): number {
if (!this._camera) return 0;
return this._camera.getNumberOfCameras();
}
/**
* Check if device has flash modes
* @param camera
*/
public hasFlash() {
if (!this._camera) {
return false;
}
return this._camera.getHasFlash();
}
/**
* Return the current flash mode of the device. Will return null if the flash mode is not supported by device.
*/
public getFlashMode() {
if (this.hasFlash()) {
if (this._camera.getFlashMode() !== fancycamera.CameraFlashMode.OFF) {
return 'on';
}
return 'off';
}
return null;
}
/**
* Helper method to ensure the correct icon (on/off) is shown on flash.
* Useful when toggling cameras.
*/
_ensureCorrectFlashIcon() {
// get current flash mode and set correct image drawable
const currentFlashMode = this.getFlashMode();
CLog('_ensureCorrectFlashIcon flash mode', currentFlashMode);
// if the flash mode is null then we need to remove the button from the parent layout
if (currentFlashMode === null) {
// if we have the button - remove it from parent
if (this._flashBtn) {
this._flashBtn.setVisibility(android.view.View.GONE);
}
return;
}
// ensure flashBtn is here - if currentFlashMode is null then don't show/assign the flash button
if (this._flashBtn === undefined || this._flashBtn === null) {
return;
}
// make sure we have our flash icon button visible - sometimes toggling might set to GONE
this._flashBtn.setVisibility(android.view.View.VISIBLE);
// reset the image in the button first
this._flashBtn.setImageResource(android.R.color.transparent);
const flashIcon = currentFlashMode === FLASH_MODE_OFF ? this.flashOffIcon : this.flashOnIcon;
const imageDrawable = CamHelpers.getImageDrawable(flashIcon);
this._flashBtn.setImageResource(imageDrawable);
}
private _ensureFocusMode() {
// setup autoFocus if possible
}
private _initFlashButton() {
this._flashBtn = CamHelpers.createImageButton();
// set correct flash icon on button
this._ensureCorrectFlashIcon();
const shape = CamHelpers.createTransparentCircleDrawable();
this._flashBtn.setBackgroundDrawable(shape);
const ref = new WeakRef(this);
this._flashBtn.setOnClickListener(
new android.view.View.OnClickListener({
onClick: (args) => {
const owner = ref.get();
if (owner) {
owner.toggleFlash();
owner._ensureCorrectFlashIcon();
}
},
})
);
const flashParams = new android.widget.RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
if (this.insetButtons === true) {
// need to get the width of the screen
const layoutWidth = this._nativeView.getWidth();
CLog(`layoutWidth = ${layoutWidth}`);
const xMargin = layoutWidth * this.insetButtonsPercent;
const layoutHeight = this._nativeView.getHeight();
CLog(`layoutHeight = ${layoutHeight}`);
const yMargin = layoutHeight * this.insetButtonsPercent;
// add margin to left and top where the button is positioned
flashParams.setMargins(xMargin, yMargin, 8, 8);
} else {
flashParams.setMargins(8, 8, 8, 8);
}
flashParams.addRule(ALIGN_PARENT_TOP);
flashParams.addRule(ALIGN_PARENT_LEFT);
this._nativeView.addView(this._flashBtn, flashParams);
}
private _initGalleryButton() {
this._galleryBtn = CamHelpers.createImageButton();
const openGalleryDrawable = CamHelpers.getImageDrawable(this.galleryIcon);
this._galleryBtn.setImageResource(openGalleryDrawable);
const shape = CamHelpers.createTransparentCircleDrawable();
this._galleryBtn.setBackgroundDrawable(shape);
const ref = new WeakRef(this);
this._galleryBtn.setOnClickListener(
new android.view.View.OnClickListener({
onClick: (args) => {
const owner = ref.get();
if (owner) {
owner.chooseFromLibrary();
}
},
})
);
const galleryParams = new android.widget.RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
if (this.insetButtons === true) {
const layoutWidth = this._nativeView.getWidth();
CLog(`layoutWidth = ${layoutWidth}`);
const xMargin = layoutWidth * this.insetButtonsPercent;
const layoutHeight = this._nativeView.getHeight();
CLog(`layoutHeight = ${layoutHeight}`);
const yMargin = layoutHeight * this.insetButtonsPercent;
// add margin to bottom and left where button is positioned
galleryParams.setMargins(xMargin, 8, 8, yMargin);
} else {
galleryParams.setMargins(8, 8, 8, 8);
}
galleryParams.addRule(ALIGN_PARENT_BOTTOM);
galleryParams.addRule(ALIGN_PARENT_LEFT);
this._nativeView.addView(this._galleryBtn, galleryParams);
}
private _initToggleCameraButton() {
this._toggleCamBtn = CamHelpers.createImageButton();
const switchCameraDrawable = CamHelpers.getImageDrawable(this.toggleCameraIcon);
this._toggleCamBtn.setImageResource(switchCameraDrawable);
const shape = CamHelpers.createTransparentCircleDrawable();
this._toggleCamBtn.setBackgroundDrawable(shape);
const ref = new WeakRef(this);
this._toggleCamBtn.setOnClickListener(
new android.view.View.OnClickListener({
onClick: (view: android.view.View) => {
const owner = ref.get();
if (owner) {
owner.toggleCamera();
}
},
})
);
const toggleCamParams = new android.widget.RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
if (this.insetButtons === true) {
const layoutWidth = this._nativeView.getWidth();
CLog(`layoutWidth = ${layoutWidth}`);
const xMargin = layoutWidth * this.insetButtonsPercent;
const layoutHeight = this._nativeView.getHeight();
CLog(`layoutHeight = ${layoutHeight}`);
const yMargin = layoutHeight * this.insetButtonsPercent;
toggleCamParams.setMargins(8, yMargin, xMargin, 8);
} else {
toggleCamParams.setMargins(8, 8, 8, 8);
}
toggleCamParams.addRule(ALIGN_PARENT_TOP);
toggleCamParams.addRule(ALIGN_PARENT_RIGHT);
this._nativeView.addView(this._toggleCamBtn, toggleCamParams);
}
private _initTakePicButton() {
this._takePicBtn = CamHelpers.createImageButton();
const takePicDrawable = CamHelpers.getImageDrawable(this.takePicIcon);
this._takePicBtn.setImageResource(takePicDrawable); // set the icon
const shape = CamHelpers.createTransparentCircleDrawable();
this._takePicBtn.setBackgroundDrawable(shape); // set the transparent background
const ref = new WeakRef(this);
this._takePicBtn.setOnClickListener(
new android.view.View.OnClickListener({
onClick: (args) => {
CLog(`The default Take Picture event will attempt to save the image to gallery.`);
const opts = {
saveToGallery: true,
confirm: this.confirmPhotos ? true : false,
autoSquareCrop: this.autoSquareCrop,
};
const owner = ref.get();
if (owner) {
owner.takePicture(opts);
}