File: ViewFinderOverlay.qml

package info (click to toggle)
lomiri-camera-app 4.0.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 5,092 kB
  • sloc: cpp: 1,671; javascript: 27; makefile: 16; sh: 12
file content (1292 lines) | stat: -rw-r--r-- 50,873 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
/*
 * Copyright 2014 Canonical Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import QtQuick 2.12
import QtQuick.Window 2.2
import Lomiri.Components 1.3
import Lomiri.Components.Popups 1.3
import QtMultimedia 5.9
import QtPositioning 5.2
import QtSensors 5.0
import CameraApp 0.1
import Qt.labs.settings 1.0
import QtGraphicalEffects 1.0

Item {
    id: viewFinderOverlay

    property Camera camera
    property bool touchAcquired: bottomEdge.pressed || zoomPinchArea.active
    property real revealProgress: noSpaceHint.visible ? 1.0 : bottomEdge.progress
    property var controls: controls
    property var settings: settings
    property bool readyForCapture
    property int sensorOrientation
    // Sometimes the value is FlashVideoLight, sometimes it's FlashTorch
    property int videoFlashOnValue: Camera.FlashVideoLight

    function showFocusRing(x, y) {
        focusRing.center = Qt.point(x, y);
        focusRing.show();
    }

    Settings {
        id: settings

        property int flashMode: Camera.FlashAuto
        property bool gpsEnabled: false
        property bool hdrEnabled: false
        property bool videoFlashOn: false
        // Left for compatibility
        property int videoFlashMode: -1
        property int selfTimerDelay: 0
        property int encodingQuality: 2 // QMultimedia.NormalQuality
        property bool gridEnabled: false
        property bool preferRemovableStorage: false
        property bool playShutterSound: true
        property bool shutterVibration: false
        property var photoResolutions
        property var videoResolutions
        // Left for compatibility
        property string videoResolution: ""
        property bool dateStampImages: false
        property string dateStampFormat: Qt.locale().dateFormat(Locale.ShortFormat)
        property color dateStampColor: LomiriColors.orange;
        property real dateStampOpacity: 1.0;
        property int dateStampAlign :  Qt.AlignBottom | Qt.AlignRight;

        Component.onCompleted: {
            if (!photoResolutions) photoResolutions = {}

            if (!videoResolutions) {
                videoResolutions = {}
                if (videoResolution)
                    // Migrate old value into default camera
                    setVideoResolution(videoResolution);
            }

            if (videoFlashMode != -1) {
                videoFlashOn = (videoFlashMode != Camera.FlashOff);
                videoFlashMode = -1;
            }
        }

        onPhotoResolutionsChanged: updateViewfinderResolution();
        onVideoResolutionsChanged: updateViewfinderResolution();

        onFlashModeChanged: if (flashMode != Camera.FlashOff) hdrEnabled = false;
        onHdrEnabledChanged: if (hdrEnabled) flashMode = Camera.FlashOff
    }

    Binding {
        target: camera.flash
        property: "mode"
        value: settings.flashMode
        when: camera.captureMode == Camera.CaptureStillImage
    }

    Binding {
        target: camera.flash
        property: "mode"
        value: settings.videoFlashOn && viewFinderView.inView ? videoFlashOnValue : Camera.FlashOff
        when: camera.captureMode == Camera.CaptureVideo
    }

    Binding {
        target: camera.advanced
        property: "hdrEnabled"
        value: settings.hdrEnabled
    }

    Binding {
        target: camera.advanced
        property: "encodingQuality"
        value: settings.encodingQuality
    }

    Binding {
        target: camera.videoRecorder
        property: "resolution"
        value: settings.videoResolutions[camera.deviceId] || Qt.size(-1, -1)
    }

    Binding {
        target: camera.imageCapture
        property: "resolution"
        value: settings.photoResolutions[camera.deviceId] || Qt.size(-1, -1)
    }

    // FIXME: where's the proper location for this?
    function updateViewfinderResolution() {
        var EPSILON = 0.02;
        var supportedViewfinderResolutions = camera.supportedViewfinderResolutions();

        if (supportedViewfinderResolutions.length === 0) {
            console.log("updateViewfinderResolution: viewfinder resolutions is not known yet.");
            return;
        }

        var targetResolution = stringToSize(
            camera.captureMode === Camera.CaptureStillImage
                ? settings.photoResolutions[camera.deviceId]
                : settings.videoResolutions[camera.deviceId]
        );

        if (!targetResolution) {
            // Resolution has not been selected yet.
            return;
        }

        var targetAspectRatio = targetResolution.width / targetResolution.height;
        var selectedResolution;

        // Select the highest resolution with matching aspect ratio.
        for (var i = 0; i < supportedViewfinderResolutions.length; i++) {
            var currentResolution = supportedViewfinderResolutions[i];
            var currentAspectRatio = currentResolution.width / currentResolution.height;

            if (Math.abs(targetAspectRatio - currentAspectRatio) > EPSILON)
                continue;

            if (!selectedResolution ||
                    currentResolution.width > selectedResolution.width) {
                selectedResolution = currentResolution;
            }
        }

        if (!selectedResolution) {
            // This is strange. Not sure why this would happen.
            console.log("updateViewfinderResolution: cannot find suitable viewfinder resolution. Use the default one.");
            selectedResolution = supportedViewfinderResolutions[0];
        }

        console.log("updateViewfinderResolution: For target resolution " +
                    sizeToString(targetResolution) + ", select " +
                    sizeToString(selectedResolution) + " for viewfinder resolution.");

        camera.viewfinder.resolution =
                Qt.size(selectedResolution.width, selectedResolution.height);
    }

    function updateVideoFlashOnValue() {
        if (camera.captureMode != Camera.CaptureVideo) {
            // The value can be probed only in video mode.
            return;
        }

        var supportedModes = camera.flash.supportedModes;
        for (var i = 0; i < supportedModes.length; i++) {
            if (supportedModes[i] === Camera.FlashVideoLight ||
                    supportedModes[i] === Camera.FlashTorch) {
                videoFlashOnValue = supportedModes[i];
                return;
            }
        }
    }

    Connections {
        target: camera.imageCapture
        onImageCaptured: {
           if(settings.shutterVibration) {
               Haptics.play({intensity:0.25,duration:LomiriAnimation.SnapDuration/3});
           }
        }
    }

    Connections {
        target: camera.flash
        onSupportedModesChanged: { updateVideoFlashOnValue(); }
    }

    Connections {
        target: camera
        onCaptureModeChanged: {
            updateViewfinderResolution();
        }

        onCameraStatusChanged: {
            // Supported viewfinder resolution is guaranteed to be known at
            // ActiveStatus, if not earlier.
            if (camera.cameraStatus == Camera.LoadedStatus
                || camera.cameraStatus == Camera.ActiveStatus) {
                updateViewfinderResolution();
            }
        }
    }

    function resolutionToLabel(resolution) {
        // takes in a resolution string (e.g. "1920x1080") and returns a nicer
        // form of it for display in the UI: "1080p"
        return resolution.split("x").pop() + "p";
    }

    function sizeToString(size) {
        return size.width + "x" + size.height;
    }

    function stringToSize(resolution) {
        var r = resolution.split("x");
        return Qt.size(r[0], r[1]);
    }

    function sizeToAspectRatio(size) {
        var ratio = Math.max(size.width, size.height) / Math.min(size.width, size.height);
        var maxDenominator = 12;
        var epsilon;
        var numerator;
        var denominator;
        var bestDenominator;
        var bestEpsilon = 10000;
        for (denominator = 2; denominator <= maxDenominator; denominator++) {
            numerator = ratio * denominator;
            epsilon = Math.abs(Math.round(numerator) - numerator);
            if (epsilon < bestEpsilon) {
                bestEpsilon = epsilon;
                bestDenominator = denominator;
            }
        }
        numerator = Math.round(ratio * bestDenominator);
        return "%1:%2".arg(numerator).arg(bestDenominator);
    }

    function sizeToMegapixels(size) {
        var megapixels = (size.width * size.height) / 1000000;
        return parseFloat(megapixels.toFixed(1))
    }

    function trimNumberToFit(numberStr, digits) {
        return (""+numberStr).substr(0,digits).replace(/\.$/,"");
    }

    function updateVideoResolutionOptions() {
        // Clear and refill videoResolutionOptionsModel with available resolutions
        // Try to only display well known resolutions: 1080p, 720p and 480p
        videoResolutionOptionsModel.clear();
        var supported = camera.advanced.videoSupportedResolutions;
        var wellKnown = ["1920x1080", "1280x720", "640x480"];

        var supportedFiltered = supported.filter(function (resolution) {
            return wellKnown.indexOf(resolution) !== -1;
        });

        if (supportedFiltered.length === 0)
            supportedFiltered = supported.slice();

        // Sort resolutions from low to high, but then insert them into model
        // in reverse order (so that highest resolution appear first).
        supportedFiltered.sort(function(a, b) {
            return a.split("x")[0] - b.split("x")[0];
        });

        for (var i=0; i<supportedFiltered.length; i++) {
            var resolution = supportedFiltered[i];
            var option = {"icon": "",
                          "label": resolutionToLabel(resolution),
                          "value": resolution};
            videoResolutionOptionsModel.insert(0, option);
        }

        // If resolution setting chosen is not supported select the highest available resolution
        if (supportedFiltered.length > 0
                && supportedFiltered.indexOf(settings.videoResolutions[camera.deviceId]) === -1) {
            setVideoResolution(supportedFiltered[supportedFiltered.length - 1]);
        }
    }

    function updatePhotoResolutionOptions() {
        // Clear and refill photoResolutionOptionsModel with available resolutions
        photoResolutionOptionsModel.clear();


        //Change to Size object and sort the resolutions by megapixel ( in reverse order so it goes from top high to  bottom low )
        var sortedResolutions = [];
        for(var i in camera.advanced.imageSupportedResolutions) {
            sortedResolutions.push( stringToSize(camera.advanced.imageSupportedResolutions[i]) );
        }
        sortedResolutions.sort(function(a, b) { return sizeToMegapixels(b) - sizeToMegapixels(a) });

        for(var i in sortedResolutions) {
            var res = sortedResolutions[i];
            photoResolutionOptionsModel.insert(i,{"icon": "",
                                                   "label": "%1 (%2MP)".arg(sizeToAspectRatio(res))
                                                                       .arg(sizeToMegapixels(res)),
                                                   "value": sizeToString(res)});
        }

        // If resolution setting is not supported select the resolution automatically
        var photoResolution = settings.photoResolutions[camera.deviceId];
        if (!isPhotoResolutionAnOption(photoResolution)) {
            setPhotoResolution(getAutomaticPhotoResolution());
        }

    }

    function setPhotoResolution(resolution) {
        var size = stringToSize(resolution);
        if (size.width > 0 && size.height > 0
            && resolution != settings.photoResolutions[camera.deviceId]) {
            settings.photoResolutions[camera.deviceId] = resolution;
            // FIXME: resetting the value of the property 'photoResolutions' is
            // necessary to ensure that a change notification signal is emitted
            settings.photoResolutions = settings.photoResolutions;
        }
    }

    function setVideoResolution(resolution) {
        if (resolution !== settings.videoResolutions[camera.deviceId]) {
            settings.videoResolutions[camera.deviceId] = resolution;
            // FIXME: resetting the value of the property 'videoResolutions' is
            // necessary to ensure that a change notification signal is emitted
            settings.videoResolutions = settings.videoResolutions;
        }
    }

    function getAutomaticPhotoResolution() {
        var fittingResolution = sizeToString(camera.advanced.fittingResolution);
        var maximumResolution = sizeToString(camera.advanced.maximumResolution);
        if (isPhotoResolutionAnOption(fittingResolution)) {
            return fittingResolution;
        } else {
            return maximumResolution;
        }
    }

    function isPhotoResolutionAnOption(resolution) {
        for (var i=0; i<photoResolutionOptionsModel.count; i++) {
            var option = photoResolutionOptionsModel.get(i);
            if (option.value == resolution) {
                return true;
            }
        }
        return false;
    }

    Connections {
        target: camera.advanced
        onVideoSupportedResolutionsChanged: updateVideoResolutionOptions();
        onImageSupportedResolutionsChanged: updatePhotoResolutionOptions();
        onFittingResolutionChanged: updatePhotoResolutionOptions();
        onMaximumResolutionChanged: updatePhotoResolutionOptions();
    }

    Connections {
        target: camera
        onDeviceIdChanged: {
            // Clear viewfinder resolution settings as it might not be supported
            // by the new device.
            camera.viewfinder.resolution = Qt.size(-1, -1);
        }
    }

    function optionsOverlayClose() {
        print("optionsOverlayClose")
        if (optionsOverlayLoader.item.valueSelectorOpened) {
            optionsOverlayLoader.item.closeValueSelector();
        } else {
            bottomEdge.close();
        }
    }

    MouseArea {
        id: bottomEdgeClose
        anchors.fill: parent
        onClicked: optionsOverlayClose()
        enabled: !camera.timedCaptureInProgress
    }

    OrientationHelper {
        id: bottomEdgeOrientation
        transitionEnabled: bottomEdge.opened

        Panel {
            id: bottomEdge
            anchors {
                right: parent.right
                left: parent.left
                bottom: parent.bottom
            }
            height: optionsOverlayLoader.height
            onOpenedChanged: optionsOverlayLoader.item.closeValueSelector()
            enabled: camera.videoRecorder.recorderState == CameraRecorder.StoppedState
                     && !camera.photoCaptureInProgress && !camera.timedCaptureInProgress
            opacity: enabled ? 1.0 : 0.3
            property bool ready: optionsOverlayLoader.status == Loader.Ready

            /* At startup, opened is false and 'bottomEdge.height' is 0 until
               optionsOverlayLoader has finished loading. When that happens
               'bottomEdge.height' becomes non 0 and 'bottomEdge.position' which
               depends on bottomEdge.height eventually reaches the value
               'bottomEdge.height'. Unfortunately during that short period 'progress'
               has an incorrect value and unfortunate consequences/bugs occur.
               That makes it important to only compute progress when 'opened' is true.

               Ref.: https://bugs.launchpad.net/ubuntu/+source/camera-app/+bug/1472903
            */
            property real progress: bottomEdge.height ? (bottomEdge.height - bottomEdge.position) / bottomEdge.height : 0
            property list<ListModel> options: [
                ListModel {
                    id: gpsOptionsModel

                    property string settingsProperty: "gpsEnabled"
                    property string icon: "location"
                    property string label: ""
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(gpsOptionsModel, settings.gpsEnabled)
                    property bool available: true
                    property bool visible: true
                    property bool showInIndicators: true
                    property bool colorize: !positionSource.isPrecise

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("On")
                        value: true
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Off")
                        value: false
                    }
                },
                ListModel {
                    id: flashOptionsModel

                    property string settingsProperty: "flashMode"
                    property string icon: ""
                    property string label: ""
                    property bool isToggle: false
                    property int selectedIndex: bottomEdge.indexForValue(flashOptionsModel, settings.flashMode)
                    property bool available: camera.advanced.hasFlash
                    property bool visible: camera.captureMode == Camera.CaptureStillImage
                    property bool showInIndicators: true

                    ListElement {
                        icon: "flash-on"
                        label: QT_TR_NOOP("On")
                        value: Camera.FlashOn
                    }
                    ListElement {
                        icon: "flash-auto"
                        label: QT_TR_NOOP("Auto")
                        value: Camera.FlashAuto
                    }
                    ListElement {
                        icon: "flash-off"
                        label: QT_TR_NOOP("Off")
                        value: Camera.FlashOff
                    }
                },
                ListModel {
                    id: videoFlashOptionsModel

                    property string settingsProperty: "videoFlashOn"
                    property string icon: ""
                    property string label: ""
                    property bool isToggle: false
                    property int selectedIndex: bottomEdge.indexForValue(videoFlashOptionsModel, settings.videoFlashOn)
                    property bool available: camera.advanced.hasFlash
                    property bool visible: camera.captureMode == Camera.CaptureVideo
                    property bool showInIndicators: true

                    ListElement {
                        icon: "torch-on"
                        label: QT_TR_NOOP("On")
                        value: true
                    }
                    ListElement {
                        icon: "torch-off"
                        label: QT_TR_NOOP("Off")
                        value: false
                    }
                },
                ListModel {
                    id: hdrOptionsModel

                    property string settingsProperty: "hdrEnabled"
                    property string icon: ""
                    property string label: i18n.tr("HDR")
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(hdrOptionsModel, settings.hdrEnabled)
                    property bool available: camera.advanced.hasHdr
                    property bool visible: camera.captureMode === Camera.CaptureStillImage
                    property bool showInIndicators: true

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("On")
                        value: true
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Off")
                        value: false
                    }
                },
                ListModel {
                    id: selfTimerOptionsModel

                    property string settingsProperty: "selfTimerDelay"
                    property string icon: ""
                    property string iconSource: "assets/self_timer.svg"
                    property string label: ""
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(selfTimerOptionsModel, settings.selfTimerDelay)
                    property bool available: true
                    property bool visible: true
                    property bool showInIndicators: true

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Off")
                        value: 0
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("5 seconds")
                        value: 5
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("15 seconds")
                        value: 15
                    }
                },
                ListModel {
                    id: encodingQualityOptionsModel

                    property string settingsProperty: "encodingQuality"
                    property string icon: "stock_image"
                    property string label: ""
                    property bool isToggle: false
                    property int selectedIndex: bottomEdge.indexForValue(encodingQualityOptionsModel, settings.encodingQuality)
                    property bool available: true
                    property bool visible: camera.captureMode == Camera.CaptureStillImage
                    property bool showInIndicators: false

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Fine Quality")
                        value: 4 // QMultimedia.VeryHighQuality
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("High Quality")
                        value: 3 // QMultimedia.HighQuality
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Normal Quality")
                        value: 2 // QMultimedia.NormalQuality
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Basic Quality")
                        value: 1 // QMultimedia.LowQuality
                    }
                },
                ListModel {
                    id: gridOptionsModel

                    property string settingsProperty: "gridEnabled"
                    property string icon: ""
                    property string iconSource: "assets/grid_lines.svg"
                    property string label: ""
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(gridOptionsModel, settings.gridEnabled)
                    property bool available: true
                    property bool visible: true

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("On")
                        value: true
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Off")
                        value: false
                    }
                },
                ListModel {
                    id: removableStorageOptionsModel

                    property string settingsProperty: "preferRemovableStorage"
                    property string icon: ""
                    // TRANSLATORS: this will be displayed on an small button so for it to fit it should be less then 3 characters long.
                    property string label: i18n.tr("SD")
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(removableStorageOptionsModel, settings.preferRemovableStorage)
                    property bool available: StorageLocations.removableStoragePresent
                    property bool visible: available

                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Save to SD Card")
                        value: true
                    }
                    ListElement {
                        icon: ""
                        label: QT_TR_NOOP("Save internally")
                        value: false
                    }
                },
                ListModel {
                    id: videoResolutionOptionsModel

                    function setSettingProperty(value) {
                        setVideoResolution(value);
                    }

                    property string icon: ""
                    property string label: "HD"
                    property bool isToggle: false
                    property int selectedIndex: bottomEdge.indexForValue(videoResolutionOptionsModel,
                                                    settings.videoResolutions[camera.deviceId])
                    property bool available: true
                    property bool visible: camera.captureMode == Camera.CaptureVideo
                    property bool showInIndicators: false
                },
                ListModel {
                    id: shutterSoundOptionsModel

                    function setSettingProperty(value) {
                        settings.shutterVibration = value & 0x1;
                        settings.playShutterSound = value & 0x2;
                    }

                    property string settingsProperty: "playShutterSound"
                    property string icon: ""
                    property string label: ""
                    property bool isToggle: true
                    property int selectedIndex: bottomEdge.indexForValue(shutterSoundOptionsModel, 2 * settings.playShutterSound  + settings.shutterVibration)
                    property bool available: true
                    property bool visible: camera.captureMode === Camera.CaptureStillImage
                    property bool showInIndicators: false

                    ListElement {
                        icon: "audio-volume-high"
                        label: QT_TR_NOOP("On")
                        value: 2
                    }
                    ListElement {
                        iconSource: "assets/vibrate.png"
                        label: QT_TR_NOOP("Vibrate")
                        value: 1
                    }
                    ListElement {
                        icon: "audio-volume-muted"
                        label: QT_TR_NOOP("Off")
                        value: 0
                    }
                },
                ListModel {
                    id: photoResolutionOptionsModel

                    function setSettingProperty(value) {
                        setPhotoResolution(value);
                    }

                    property string icon: ""
                    property string label: "%1MP".arg(trimNumberToFit(sizeToMegapixels(stringToSize(settings.photoResolutions[camera.deviceId])),3))
                    property bool isToggle: false
                    property int selectedIndex: bottomEdge.indexForValue(photoResolutionOptionsModel, settings.photoResolutions[camera.deviceId])
                    property bool available: true
                    property bool visible: camera.captureMode == Camera.CaptureStillImage
                    property bool showInIndicators: false
                }
            ]

            /* FIXME: StorageLocations.removableStoragePresent is not updated dynamically.
               Workaround that by reading it when the bottom edge is opened/closed.
            */
            Connections {
                target: bottomEdge
                onOpenedChanged: StorageLocations.updateRemovableStorageInfo()
            }

            function indexForValue(model, value) {
                var i;
                var element;
                for (i=0; i<model.count; i++) {
                    element = model.get(i);
                    if (element.value === value) {
                        return i;
                    }
                }

                return -1;
            }

            BottomEdgeIndicators {
                id: bottomEdgeIndicators
                options: bottomEdge.options
                anchors {
                    horizontalCenter: parent.horizontalCenter
                    bottom: parent.top
                }
                opacity: bottomEdge.pressed || bottomEdge.opened ? 0.0 : 1.0
                Behavior on opacity { LomiriNumberAnimation {} }
            }

            Loader {
                id: optionsOverlayLoader
                anchors {
                    left: parent.left
                    right: parent.right
                    top: parent.top
                }
                asynchronous: true
                sourceComponent: Component {
                    OptionsOverlay {
                        options: bottomEdge.options
                    }
                }
            }

            triggerSize: units.gu(3)

            Item {
                /* Use the 'trigger' feature of Panel so that tapping on the Panel
                   can be acted upon */
                id: clickReceiver
                anchors.fill: parent
                anchors.topMargin: -bottomEdge.triggerSize

                function trigger() {
                    if (bottomEdge.opened) {
                        optionsOverlayClose();
                    } else {
                        bottomEdge.open();
                    }
                }
            }
        }
    }

    OrientationSensor {
        id: orientationSensor
        active: true
    }

    Item {
        id: controls

        anchors {
            left: parent.left
            right: parent.right
        }
        height: parent.height
        y: Screen.angleBetween(Screen.primaryOrientation, Screen.orientation) == 0 ? bottomEdge.position - bottomEdge.height : 0
        opacity: 1 - bottomEdge.progress
        visible: opacity != 0.0
        enabled: !bottomEdge.progress

        Behavior on opacity { LomiriNumberAnimation { duration: LomiriAnimation.FastDuration}}

        function timedShoot(secs) {
            camera.timedCaptureInProgress = true;
            timedShootFeedback.start();
            shootingTimer.remainingSecs = secs;
            shootingTimer.start();
        }

        function cancelTimedShoot() {
            if (camera.timedCaptureInProgress) {
                camera.timedCaptureInProgress = false;
                shootingTimer.stop();
                timedShootFeedback.stop();
            }
        }

        function shoot() {
            // Note that orientation now means the clockwise rotation of the image.
            var orientation = 0;
            if (orientationSensor.reading != null) {
                switch (orientationSensor.reading.orientation) {
                    case OrientationReading.TopUp:
                        orientation = 0;
                        break;
                    case OrientationReading.TopDown:
                        orientation = 180;
                        break;
                    case OrientationReading.LeftUp:
                        orientation = 270;
                        break;
                    case OrientationReading.RightUp:
                        orientation = 90;
                        break;
                    default:
                        /* Workaround for OrientationSensor not setting a valid value until
                           the device is rotated.
                           Ref.: https://bugs.launchpad.net/qtubuntu-sensors/+bug/1429865

                           Note that the value returned by Screen.angleBetween is valid if
                           the orientation lock is not engaged.
                           Ref.: https://bugs.launchpad.net/camera-app/+bug/1422762
                        */
                        orientation = Screen.angleBetween(Screen.primaryOrientation, Screen.orientation);
                        break;
                }
            }

            if (camera.position === Camera.FrontFace) {
                // Clockwise device becomes counter-clockwise camera
                orientation = 360 - orientation;
            }

            // account for the orientation of the sensor
            orientation += viewFinderOverlay.sensorOrientation;

            // Ensure that the orientation is positive and within range.
            orientation = (orientation + 360) % 360;

            if (camera.captureMode == Camera.CaptureVideo) {
                if (main.contentExportMode) {
                    camera.videoRecorder.outputLocation = StorageLocations.temporaryLocation;
                } else if (StorageLocations.removableStoragePresent && settings.preferRemovableStorage) {
                    camera.videoRecorder.outputLocation = StorageLocations.removableStorageVideosLocation;
                } else {
                    camera.videoRecorder.outputLocation = StorageLocations.videosLocation;
                }

                if (camera.videoRecorder.recorderState == CameraRecorder.StoppedState) {
                    camera.videoRecorder.setMetadata("Orientation", orientation);
                    camera.videoRecorder.setMetadata("Date", new Date());
                    camera.videoRecorder.record();
                }
            } else {
                if (!main.contentExportMode) {
                    shootFeedback.start();
                }
                camera.photoCaptureInProgress = true;
                camera.imageCapture.setMetadata("Orientation", orientation);
                camera.imageCapture.setMetadata("Date", new Date());
                var position = positionSource.position;
                if (settings.gpsEnabled && positionSource.isPrecise) {
                    camera.imageCapture.setMetadata("GPSLatitude", position.coordinate.latitude);
                    camera.imageCapture.setMetadata("GPSLongitude", position.coordinate.longitude);
                    camera.imageCapture.setMetadata("GPSTimeStamp", position.timestamp);
                    camera.imageCapture.setMetadata("GPSProcessingMethod", "GPS");
                    if (position.altitudeValid) {
                        camera.imageCapture.setMetadata("GPSAltitude", position.coordinate.altitude);
                    }
                }

                if (main.contentExportMode) {
                    camera.imageCapture.captureToLocation(StorageLocations.temporaryLocation);
                } else if (StorageLocations.removableStoragePresent && settings.preferRemovableStorage) {
                    camera.imageCapture.captureToLocation(StorageLocations.removableStoragePicturesLocation);
                } else {
                    camera.imageCapture.captureToLocation(StorageLocations.picturesLocation);
                }
            }
        }

        function switchCamera() {
            camera.switchInProgress = true;
            //                viewFinderGrab.sourceItem = viewFinder;
            viewFinderGrab.x = viewFinder.x;
            viewFinderGrab.y = viewFinder.y;
            viewFinderGrab.width = viewFinder.width;
            viewFinderGrab.height = viewFinder.height;
            viewFinderGrab.visible = true;
            viewFinderGrab.scheduleUpdate();
        }

        function completeSwitch() {
            viewFinderSwitcherAnimation.restart();
            camera.switchInProgress = false;
            zoomControl.value = camera.currentZoom;
        }

        function changeRecordMode() {
            if (camera.captureMode == Camera.CaptureVideo) camera.videoRecorder.stop()
            camera.captureMode = (camera.captureMode == Camera.CaptureVideo) ? Camera.CaptureStillImage : Camera.CaptureVideo
            zoomControl.value = camera.currentZoom
        }

        Connections {
            target: Qt.application
            onActiveChanged: if (active) zoomControl.value = camera.currentZoom
        }

        Timer {
            id: shootingTimer
            repeat: true
            triggeredOnStart: true

            property int remainingSecs: 0

            onTriggered: {
                if (remainingSecs == 0) {
                    running = false;
                    camera.timedCaptureInProgress = false;
                    controls.shoot();
                    timedShootFeedback.stop();
                } else {
                    timedShootFeedback.showRemainingSecs(remainingSecs);
                    remainingSecs--;
                }
            }
        }

        PositionSource {
            id: positionSource
            updateInterval: 1000
            active: settings.gpsEnabled
            property bool isPrecise: valid
                                     && position.latitudeValid
                                     && position.longitudeValid
                                     && (!position.horizontalAccuracyValid ||
                                          position.horizontalAccuracy <= 100)
        }

        PostProcessOperations {
            id: postProcessOperations
        }

        Connections {
            target: camera.imageCapture
            onReadyChanged: {
                if (camera.imageCapture.ready) {
                    if (camera.switchInProgress) {
                        controls.completeSwitch();
                    }
                }
            }
            onImageSaved : {
                if(path && settings.dateStampImages && !main.contentExportMode) {
                    postProcessOperations.addDateStamp(path,
                                                       viewFinderOverlay.settings.dateStampFormat,
                                                       viewFinderOverlay.settings.dateStampColor,
                                                       viewFinderOverlay.settings.dateStampOpacity,
                                                       viewFinderOverlay.settings.dateStampAlign);
                }
            }
        }

        CircleButton {
            id: recordModeButton
            objectName: "recordModeButton"

            anchors {
                right: shootButton.left
                rightMargin: units.gu(7.5)
                bottom: parent.bottom
                bottomMargin: units.gu(6)
            }

            iconName: (camera.captureMode == Camera.CaptureStillImage) ? "camcorder" : "camera-symbolic"
            onClicked: controls.changeRecordMode()
            enabled: camera.videoRecorder.recorderState == CameraRecorder.StoppedState && !main.contentExportMode
                     && !camera.photoCaptureInProgress && !camera.timedCaptureInProgress
        }

        ShootButton {
            id: shootButton

            anchors {
                bottom: parent.bottom
                // account for the bottom shadow in the asset
                bottomMargin: units.gu(5) - units.dp(6)
                horizontalCenter: parent.horizontalCenter
            }

            enabled: (
                (camera.captureMode == Camera.CaptureVideo
                    && camera.videoRecorder.recorderStatus == CameraRecorder.RecordingStatus) ||
                (viewFinderOverlay.readyForCapture && !storageMonitor.diskSpaceCriticallyLow
                     && !camera.timedCaptureInProgress)
            )
            state: (camera.captureMode == Camera.CaptureVideo) ?
                   ((camera.videoRecorder.recorderState == CameraRecorder.StoppedState) ? "record_off" : "record_on") :
                   "camera"
            onClicked: {
                if (camera.captureMode == Camera.CaptureVideo && camera.videoRecorder.recorderState == CameraRecorder.RecordingState) {
                    camera.videoRecorder.stop();
                } else {
                    if (settings.selfTimerDelay > 0) {
                        controls.timedShoot(settings.selfTimerDelay);
                    } else {
                        controls.shoot();
                    }
                }
            }
            rotation: Screen.angleBetween(Screen.primaryOrientation, Screen.orientation)
            Behavior on rotation {
                RotationAnimator {
                    duration: LomiriAnimation.BriskDuration
                    easing: LomiriAnimation.StandardEasing
                    direction: RotationAnimator.Shortest
                }
            }
        }

        CircleButton {
            id: swapButton
            objectName: "swapButton"

            anchors {
                left: shootButton.right
                leftMargin: units.gu(7.5)
                bottom: parent.bottom
                bottomMargin: units.gu(6)
            }

            enabled: !camera.switchInProgress && camera.videoRecorder.recorderState == CameraRecorder.StoppedState
                     && !camera.photoCaptureInProgress && !camera.timedCaptureInProgress
            iconName: "camera-flip"
            onClicked: controls.switchCamera()
        }


        PinchArea {
            id: zoomPinchArea
            anchors {
                top: parent.top
                topMargin: bottomEdgeIndicators.height
                bottom: shootButton.top
                bottomMargin: bottomEdgeIndicators.height
                left: parent.left
                leftMargin: bottomEdgeIndicators.height
                right: parent.right
                rightMargin: bottomEdgeIndicators.height
            }

            property real initialZoom
            property real minimumScale: 0.3
            property real maximumScale: 3.0
            property bool active: false

            enabled: !camera.photoCaptureInProgress && !camera.timedCaptureInProgress
            onPinchStarted: {
                active = true;
                initialZoom = zoomControl.value;
                zoomControl.show();
            }
            onPinchUpdated: {
                zoomControl.show();
                var scaleFactor = MathUtils.projectValue(pinch.scale, 1.0, maximumScale, 0.0, zoomControl.maximumValue);
                zoomControl.value = MathUtils.clamp(initialZoom + scaleFactor, zoomControl.minimumValue, zoomControl.maximumValue);
            }
            onPinchFinished: {
                active = false;
            }


            MouseArea {
                id: manualFocusMouseArea
                anchors.fill: parent
                objectName: "manualFocusMouseArea"
                enabled: camera.focus.isFocusPointModeSupported(Camera.FocusPointCustom) &&
                         !camera.photoCaptureInProgress && !camera.timedCaptureInProgress
                onClicked: {
                    // mouse.x/y is relative to this item. Convert to be relative to the overlay,
                    // which in turn is relative to viewFinderView, where camera's VideoOutput resides.
                    var mappedPoint = mapToItem(viewFinderOverlay, mouse.x, mouse.y);
                    camera.manualFocus(mappedPoint.x, mappedPoint.y);
                    mouse.accepted = false;
                }
            }
        }

        ZoomControl {
            id: zoomControl

            anchors {
                bottom: shootButton.top
                bottomMargin: units.gu(2)
                left: parent.left
                right: parent.right
                leftMargin: recordModeButton.x
                rightMargin: parent.width - (swapButton.x + swapButton.width)
            }
            maximumValue: camera.maximumZoom

            Binding { target: camera; property: "currentZoom"; value: zoomControl.value }
        }

        StopWatch {
            id: stopWatch

            anchors {
                top: parent.top
                topMargin: units.gu(6)
                horizontalCenter: parent.horizontalCenter
            }
            opacity: camera.videoRecorder.recorderState == CameraRecorder.StoppedState ? 0.0 : 1.0
            Behavior on opacity { LomiriNumberAnimation {} }
            visible: opacity != 0
            time: camera.videoRecorder.duration / 1000
        }

        FocusRing {
            id: focusRing
        }

        CircleButton {
            id: exportBackButton
            objectName: "exportBackButton"

            anchors {
                top: parent.top
                topMargin: units.gu(4)
                left: recordModeButton.left
            }

            iconName: visible ? "go-previous" : ""
            visible: main.contentExportMode
            enabled: main.contentExportMode
            onClicked: main.cancelExport()
        }
    }

    ProcessingFeedback {
        anchors {
            top: parent.top
            topMargin: units.gu(2)
            left: parent.left
            leftMargin: units.gu(2)
        }
        processing: camera.photoCaptureInProgress
    }

    StorageMonitor {
        id: storageMonitor
        location: (StorageLocations.removableStoragePresent && settings.preferRemovableStorage) ?
                   StorageLocations.removableStorageLocation : StorageLocations.videosLocation
        onDiskSpaceLowChanged: if (storageMonitor.diskSpaceLow && !storageMonitor.diskSpaceCriticallyLow) {
                                   PopupUtils.open(freeSpaceLowDialogComponent);
                               }
        onDiskSpaceCriticallyLowChanged: if (storageMonitor.diskSpaceCriticallyLow) {
                                             camera.videoRecorder.stop();
                                         }
        onIsWriteableChanged: if (!isWriteable && !diskSpaceLow && !main.contentExportMode) {
                                  PopupUtils.open(readOnlyMediaDialogComponent);
                              }
    }

    NoSpaceHint {
        id: noSpaceHint
        objectName: "noSpace"
        anchors.fill: parent
        visible: storageMonitor.diskSpaceCriticallyLow
    }

    Component {
        id: freeSpaceLowDialogComponent
        Dialog {
            id: freeSpaceLowDialog
            objectName: "lowSpaceDialog"
            title: i18n.tr("Low storage space")
            text: i18n.tr("You are running out of storage space. To continue without interruptions, free up storage space now.")
            Button {
                text: i18n.tr("Cancel")
                onClicked: PopupUtils.close(freeSpaceLowDialog)
            }
        }
    }

    Component {
         id: readOnlyMediaDialogComponent
         Dialog {
             id: readOnlyMediaDialog
             objectName: "readOnlyMediaDialog"
             title: i18n.tr("External storage not writeable")
             text: i18n.tr("It does not seem possible to write to your external storage media. Trying to eject and insert it again might solve the issue, or you might need to format it.")
             Button {
                 text: i18n.tr("Cancel")
                 onClicked: PopupUtils.close(readOnlyMediaDialog)
             }
         }
    }

    Connections {
        id: permissionErrorMonitor
        property var currentPermissionsDialog: null
        target: camera
        onError: {
            if (errorCode == Camera.ServiceMissingError) {
                if (currentPermissionsDialog == null) {
                    currentPermissionsDialog = PopupUtils.open(noPermissionsDialogComponent);
                }
                camera.failedToConnect = true;
            }
        }
        onCameraStateChanged: {
            if (camera.cameraState != Camera.UnloadedState) {
                if (currentPermissionsDialog != null) {
                    PopupUtils.close(currentPermissionsDialog);
                    currentPermissionsDialog = null;
                }
                camera.failedToConnect = false;
            } else {
                camera.photoCaptureInProgress = false;
            }
        }
    }

    Component {
        id: noPermissionsDialogComponent
        Dialog {
            id: noPermissionsDialog
            objectName: "noPermissionsDialog"
            title: i18n.tr("Cannot access camera")
            text: i18n.tr("Camera app doesn't have permission to access the camera hardware or another error occurred.\n\nIf granting permission does not resolve this problem, reboot your device.")
            Button {
                text: i18n.tr("Edit Permissions")
                color: theme.palette.normal.focus
                onClicked: {
                    Qt.openUrlExternally("settings:///system/security-privacy?service=camera");
                    PopupUtils.close(noPermissionsDialog);
                    permissionErrorMonitor.currentPermissionsDialog = null;
                }
            }
            Button {
                text: i18n.tr("Cancel")
                onClicked: {
                    PopupUtils.close(noPermissionsDialog);
                    permissionErrorMonitor.currentPermissionsDialog = null;
                }
            }
        }
    }

    FastBlur {
        id: viewFinderSwitcherBlurred
        anchors.fill: parent
        property real finalRadius: 67
        property real finalOpacity: 1.0
        radius: photoRollHint.visible ? finalRadius : viewFinderOverlay.revealProgress * finalRadius
        opacity: photoRollHint.visible ? finalOpacity : (1.0 - viewFinderOverlay.revealProgress) * finalOpacity + finalOpacity
        source: viewFinderSwitcher !== null ? viewFinderSwitcher : null
        z:-1
        visible:  appSettings.blurEffects && radius !== 0
        transparentBorder:false
        Behavior on radius { LomiriNumberAnimation { duration: LomiriAnimation.SnapDuration} }
    }

    Rectangle {
        id: viewFinderOverlayTint
        anchors.fill:parent
        property real finalOpacity: 0.25
        property real tintOpacity : viewFinderOverlay.revealProgress * finalOpacity
        visible: viewFinderOverlay.revealProgress > 0
        opacity:tintOpacity
        color: LomiriColors.jet
        z:-1
    }
}