summaryrefslogtreecommitdiff
path: root/src/cheese-window.vala
blob: e2264fdfcb0e75200fbfb8201959d908797d8ff8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
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
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
/*
 * Copyright © 2010 Yuvaraj Pandian T <yuvipanda@yuvi.in>
 * Copyright © 2010 daniel g. siegel <dgsiegel@gnome.org>
 * Copyright © 2008 Filippo Argiolas <filippo.argiolas@gmail.com>
 *
 * Licensed under the GNU General Public License Version 2
 *
 * 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; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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/>.
 */

using Gtk;
using Gdk;
using GtkClutter;
using Clutter;
using Config;
using Eog;
using Gst;
using CanberraGtk;

const int FULLSCREEN_TIMEOUT_INTERVAL = 5 * 1000;
const uint EFFECTS_PER_PAGE = 9;

[GtkTemplate (ui = "/org/gnome/Cheese/cheese-main-window.ui")]
public class Cheese.MainWindow : Gtk.ApplicationWindow
{
    private const GLib.ActionEntry actions[] = {
        { "file-open", on_file_open },
        { "file-saveas", on_file_saveas },
        { "file-trash", on_file_trash },
        { "file-delete", on_file_delete },
        { "effects-next", on_effects_next },
        { "effects-previous", on_effects_previous }
    };

    private MediaMode current_mode;

    private Clutter.Script clutter_builder;

    private Gtk.Builder header_bar_ui = new Gtk.Builder.from_resource ("/org/gnome/Cheese/headerbar.ui");

    private Gtk.HeaderBar header_bar;

    private GLib.Settings settings;

    [GtkChild]
    private unowned GtkClutter.Embed viewport_widget;
    [GtkChild]
    private unowned Gtk.Widget main_vbox;
    private Eog.ThumbNav thumb_nav;
    private Cheese.ThumbView thumb_view;
    [GtkChild]
    private unowned Gtk.Box thumbnails_right;
    [GtkChild]
    private unowned Gtk.Box thumbnails_bottom;
    [GtkChild]
    private unowned Gtk.Widget leave_fullscreen_button_box;
    [GtkChild]
    private unowned Gtk.Button take_action_button;
    [GtkChild]
    private unowned Gtk.Image take_action_button_image;
    [GtkChild]
    private unowned Gtk.ToggleButton effects_toggle_button;
    [GtkChild]
    private unowned Gtk.Widget buttons_area;
    [GtkChild]
    private unowned Gtk.Button switch_camera_button;
    private Gtk.Menu thumbnail_popup;

    private Clutter.Stage viewport;
    private Clutter.Actor viewport_layout;
    private Clutter.Actor video_preview;
    private Clutter.BinLayout viewport_layout_manager;
    private Clutter.Text countdown_layer;
    private Clutter.Actor background_layer;
    private Clutter.Text error_layer;
    private Clutter.Text timeout_layer;

  private Clutter.Actor current_effects_grid;
  private uint current_effects_page = 0;
  private List<Clutter.Actor> effects_grids;

  private bool is_fullscreen;
  private bool is_wide_mode;
  private bool is_recording;       /* Video Recording Flag */
  private bool is_bursting;
  private bool is_effects_selector_active;
  private bool action_cancelled;
    private bool was_maximized;

  private Cheese.Camera   camera;
  private Cheese.FileUtil fileutil;
  private Cheese.Flash    flash;

  private Cheese.EffectsManager    effects_manager;

  private Cheese.Effect selected_effect;

  /**
   * Responses from the delete files confirmation dialog.
   *
   * @param SKIP skip a single file
   * @param SKIP_ALL skill all following files
   */
  enum DeleteResponse
  {
    SKIP = 1,
    SKIP_ALL = 2
  }

    public MainWindow (Gtk.Application application)
    {
        GLib.Object (application: application);

        header_bar = header_bar_ui.get_object ("header_bar") as Gtk.HeaderBar;
        header_bar.visible = true;
        this.set_titlebar (header_bar);
    }

    private void set_window_title (string title)
    {
        header_bar.set_title (title);
        this.set_title (title);
    }

    private bool on_window_state_change_event (Gtk.Widget widget,
                                               Gdk.EventWindowState event)
    {
        was_maximized = (((event.new_window_state - event.changed_mask)
                          & Gdk.WindowState.MAXIMIZED) != 0);

        window_state_event.disconnect (on_window_state_change_event);
        return false;
    }

    private void do_thumb_view_popup_menu ()
    {
        thumbnail_popup.popup_at_pointer (null);
    }

    private bool on_thumb_view_popup_menu ()
    {
        do_thumb_view_popup_menu ();

        return true;
    }

    /**
    * Popup a context menu when right-clicking on a thumbnail.
    *
    * @param iconview the thumbnail view that emitted the signal
    * @param event the event
    * @return false to allow further processing of the event, true to indicate
    * that the event was handled completely
    */
    public bool on_thumbnail_button_press_event (Gtk.Widget iconview,
                                                 Gdk.EventButton event)
    {
        Gtk.TreePath path;
        path = thumb_view.get_path_at_pos ((int) event.x, (int) event.y);

        if (path == null)
        {
            return false;
        }

        if (!thumb_view.path_is_selected (path))
        {
            thumb_view.unselect_all ();
            thumb_view.select_path (path);
            thumb_view.set_cursor (path, null, false);
        }

        if (event.type == Gdk.EventType.BUTTON_PRESS)
        {
            Gdk.Event* button_press = (Gdk.Event*)(event);

            if (button_press->triggers_context_menu ())
            {
                do_thumb_view_popup_menu ();
                return true;
            }
        }
        else if (event.type == Gdk.EventType.2BUTTON_PRESS)
        {
            on_file_open ();
            return true;
        }

        return false;
    }

  /**
   * Open an image associated with a thumbnail in the default application.
   */
  private void on_file_open ()
  {
    string filename, uri;

    Gdk.Screen screen;
    filename = thumb_view.get_selected_image ();

    if (filename == null)
      return;                     /* Nothing selected. */

    try
    {
      uri    = GLib.Filename.to_uri (filename);
      screen = this.get_screen ();
      Gtk.show_uri (screen, uri, Gtk.get_current_event_time ());
    }
    catch (Error err)
    {
      MessageDialog error_dialog = new MessageDialog (this,
                                                      Gtk.DialogFlags.MODAL |
                                                      Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                                      Gtk.MessageType.ERROR,
                                                      Gtk.ButtonsType.OK,
                                                      _("Could not open %s"),
                                                      filename);

      error_dialog.run ();
      error_dialog.destroy ();
    }
  }

  /**
   * Delete the requested image or images in the thumbview from storage.
   *
   * A confirmation dialog is shown to the user before deleting any files.
   */
  private void on_file_delete ()
  {
    int response;
    int error_response;
    bool skip_all_errors = false;

    var files = thumb_view.get_selected_images_list ();
    var files_length = files.length ();

    var confirmation_dialog = new MessageDialog.with_markup (this,
      Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
      Gtk.MessageType.WARNING, Gtk.ButtonsType.NONE,
      GLib.ngettext("Are you sure you want to permanently delete the file?",
        "Are you sure you want to permanently delete %d files?",
        files_length), files_length);
    confirmation_dialog.add_button (_("_Cancel"), Gtk.ResponseType.CANCEL);
    confirmation_dialog.add_button (_("_Delete"), Gtk.ResponseType.ACCEPT);
    confirmation_dialog.format_secondary_text ("%s",
      GLib.ngettext("If you delete an item, it will be permanently lost",
        "If you delete the items, they will be permanently lost",
        files_length));

    response = confirmation_dialog.run ();
    if (response == Gtk.ResponseType.ACCEPT)
    {
      foreach (var file in files)
      {
        if (file == null)
          return;

        try
        {
          file.delete (null);
        }
        catch (Error err)
        {
          warning ("Unable to delete file: %s", err.message);

          if (!skip_all_errors) {
            var error_dialog = new MessageDialog (this,
              Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
              Gtk.MessageType.ERROR, Gtk.ButtonsType.NONE,
              _("Could not delete %s"), file.get_path ());

            error_dialog.add_button (_("_Cancel"), Gtk.ResponseType.CANCEL);
            error_dialog.add_button (_("Skip"), DeleteResponse.SKIP);
            error_dialog.add_button (_("Skip all"), DeleteResponse.SKIP_ALL);

            error_response = error_dialog.run ();
            if (error_response == DeleteResponse.SKIP_ALL) {
              skip_all_errors = true;
            } else if (error_response == Gtk.ResponseType.CANCEL) {
              break;
            }

            error_dialog.destroy ();
          }
        }
      }
    }
    confirmation_dialog.destroy ();
  }

  /**
   * Move the requested image in the thumbview to the trash.
   *
   * A confirmation dialog is shown to the user before moving the file.
   */
  private void on_file_trash ()
  {
    File file;

    GLib.List<GLib.File> files = thumb_view.get_selected_images_list ();

    for (int i = 0; i < files.length (); i++)
    {
      file = files<GLib.File>.nth (i).data;
      if (file == null)
        return;

      try
      {
        file.trash (null);
      }
      catch (Error err)
      {
        MessageDialog error_dialog = new MessageDialog (this,
                                                        Gtk.DialogFlags.MODAL |
                                                        Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                                        Gtk.MessageType.ERROR,
                                                        Gtk.ButtonsType.OK,
                                                        _("Could not move %s to trash"),
                                                        file.get_path ());

        error_dialog.run ();
        error_dialog.destroy ();
      }
    }
  }

  /**
   * Save the selected file in the thumbview to an alternate storage location.
   *
   * A file chooser dialog is shown to the user, asking where the file should
   * be saved and the filename.
   */
  private void on_file_saveas ()
  {
    string            filename, basename;
    FileChooserDialog save_as_dialog;
    int               response;

    filename = thumb_view.get_selected_image ();
    if (filename == null)
      return;                    /* Nothing selected. */

    save_as_dialog = new FileChooserDialog (_("Save File"),
                                            this,
                                            Gtk.FileChooserAction.SAVE,
                                            _("_Cancel"), Gtk.ResponseType.CANCEL,
                                            _("Save"), Gtk.ResponseType.ACCEPT,
                                            null);

    save_as_dialog.do_overwrite_confirmation = true;
    basename                                 = GLib.Filename.display_basename (filename);
    save_as_dialog.set_current_name (basename);
    save_as_dialog.set_current_folder (GLib.Environment.get_home_dir ());

    response = save_as_dialog.run ();

    save_as_dialog.hide ();
    if (response == Gtk.ResponseType.ACCEPT)
    {
      string target_filename;
      target_filename = save_as_dialog.get_filename ();

      File src  = File.new_for_path (filename);
      File dest = File.new_for_path (target_filename);

      try
      {
        src.copy (dest, FileCopyFlags.OVERWRITE, null, null);
      }
      catch (Error err)
      {
        MessageDialog error_dialog = new MessageDialog (this,
                                                        Gtk.DialogFlags.MODAL |
                                                        Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                                        Gtk.MessageType.ERROR,
                                                        Gtk.ButtonsType.OK,
                                                        _("Could not save %s"),
                                                        target_filename);

        error_dialog.run ();
        error_dialog.destroy ();
      }
    }
    save_as_dialog.destroy ();
  }

    /**
     * Toggle fullscreen mode.
     *
     * @param fullscreen whether the window should be fullscreen
     */
    public void set_fullscreen (bool fullscreen)
    {
        set_fullscreen_mode (fullscreen);
    }

    /**
     * Make the media capture mode actions sensitive.
     */
    private void enable_mode_change ()
    {
        var mode = this.application.lookup_action ("mode") as SimpleAction;
        mode.set_enabled (true);
        var effects = this.application.lookup_action ("effects") as SimpleAction;
        effects.set_enabled (true);
        var preferences = this.application.lookup_action ("preferences") as SimpleAction;
        preferences.set_enabled (true);
    }

    /**
     * Make the media capture mode actions insensitive.
     */
    private void disable_mode_change ()
    {
        var mode = this.application.lookup_action ("mode") as SimpleAction;
        mode.set_enabled (false);
        var effects = this.application.lookup_action ("effects") as SimpleAction;
        effects.set_enabled (false);
        var preferences = this.application.lookup_action ("preferences") as SimpleAction;
        preferences.set_enabled (false);
    }

  /**
   * Set the capture resolution, based on the current capture mode.
   *
   * @param mode the current capture mode (photo, video or burst)
   */
  private void set_resolution(MediaMode mode)
  {
    if (camera == null)
      return;

    var formats = camera.get_video_formats ();

    if (formats == null)
      return;
    
    unowned Cheese.VideoFormat format;
    int width = 0;
    int height = 0;

    switch (mode)
    {
      case MediaMode.PHOTO:
      case MediaMode.BURST:
        width  = settings.get_int ("photo-x-resolution");
        height = settings.get_int ("photo-y-resolution");
        break;
      case MediaMode.VIDEO:
        width  = settings.get_int ("video-x-resolution");
        height = settings.get_int ("video-y-resolution");
        break;
    }

    for (int i = 0; i < formats.length (); i++)
    {
      format = formats<VideoFormat>.nth (i).data;
      if (width == format.width && height == format.height)
      {
        camera.set_video_format (format);
        break;
      }
    }
  }

  private TimeoutSource fullscreen_timeout;
  /**
   * Clear the fullscreen activity timeout.
   */
  private void clear_fullscreen_timeout ()
  {
    if (fullscreen_timeout != null)
    {
      fullscreen_timeout.destroy ();
      fullscreen_timeout = null;
    }
  }

  /**
   * Set the fullscreen timeout, for hiding the UI if there is no mouse
   * movement.
   */
  private void set_fullscreen_timeout ()
  {
    fullscreen_timeout = new TimeoutSource (FULLSCREEN_TIMEOUT_INTERVAL);
    fullscreen_timeout.attach (null);
    fullscreen_timeout.set_callback (() => {buttons_area.hide ();
                                            clear_fullscreen_timeout ();
                                            this.fullscreen ();
                                            return true; });
  }

    /**
     * Show the UI in fullscreen if there is any mouse activity.
     *
     * Start a new timeout at the end of every mouse pointer movement. All
     * timeouts will be cancelled, except one created during the last movement
     * event. Show() is called even if the button is not hidden.
     *
     * @param viewport the widget to check for mouse activity on
     * @param e the (unused) event
     */
    private bool fullscreen_motion_notify_callback (Gtk.Widget viewport,
                                                    EventMotion e)
    {
        clear_fullscreen_timeout ();
        this.unfullscreen ();
        this.maximize ();
        buttons_area.show ();
        set_fullscreen_timeout ();
        return true;
    }

  /**
   * Enable or disable fullscreen mode to the requested state.
   *
   * @param fullscreen_mode whether to enable or disable fullscreen mode
   */
  private void set_fullscreen_mode (bool fullscreen)
  {
    /* After the first time the window has been shown using this.show_all (),
     * the value of leave_fullscreen_button_box.no_show_all should be set to false
     * So that the next time leave_fullscreen_button_box.show_all () is called, the button is actually shown
     * FIXME: If this code can be made cleaner/clearer, please do */

    is_fullscreen = fullscreen;
    if (fullscreen)
    {
            window_state_event.connect (on_window_state_change_event);

      if (is_wide_mode)
      {
        thumbnails_right.hide ();
      }
      else
      {
        thumbnails_bottom.hide ();
      }
      leave_fullscreen_button_box.no_show_all = false;
      leave_fullscreen_button_box.show_all ();

      this.fullscreen ();
      viewport_widget.motion_notify_event.connect (fullscreen_motion_notify_callback);
      set_fullscreen_timeout ();
    }
    else
    {
      if (is_wide_mode)
      {
        thumbnails_right.show_all ();
      }
      else
      {
        thumbnails_bottom.show_all ();
      }
      leave_fullscreen_button_box.hide ();

      /* Stop timer so buttons_area does not get hidden after returning from
       * fullscreen mode */
      clear_fullscreen_timeout ();
      /* Show the buttons area anyway - it might've been hidden in fullscreen mode */
      buttons_area.show ();
      viewport_widget.motion_notify_event.disconnect (fullscreen_motion_notify_callback);
      this.unfullscreen ();

            if (was_maximized)
            {
                this.maximize ();
            }
            else
            {
                this.unmaximize ();
            }
    }
  }

  /**
   * Enable or disable wide mode to the requested state.
   *
   * @param wide_mode whether to enable or disable wide mode
   */
  public void set_wide_mode (bool wide_mode)
  {
    is_wide_mode = wide_mode;

    /* keep the viewport to its current size while rearranging the ui,
     * so that thumbview moves from right to bottom and viceversa
     * while the rest of the window stays unchanged */
    Gtk.Allocation alloc;
    viewport_widget.get_allocation (out alloc);
    viewport_widget.set_size_request (alloc.width, alloc.height);

    if (is_wide_mode)
    {
      thumb_view.set_vertical (true);
      thumb_nav.set_vertical (true);
      if (thumbnails_bottom.get_children () != null)
      {
        thumbnails_bottom.remove (thumb_nav);
      }
      thumbnails_right.add (thumb_nav);

            if (!is_fullscreen)
            {
                thumbnails_right.show_all ();
                thumbnails_bottom.hide ();
            }
    }
    else
    {
      thumb_view.set_vertical (false);
      thumb_nav.set_vertical (false);
      if (thumbnails_right.get_children () != null)
      {
        thumbnails_right.remove (thumb_nav);
      }
      thumbnails_bottom.add (thumb_nav);

            if (!is_fullscreen)
            {
                thumbnails_bottom.show_all ();
                thumbnails_right.hide ();
            }
    }

    /* handy trick to keep the window to the desired size while not
     * requesting a fixed one. This way the window is resized to its
     * natural size (particularly with the constraints imposed by the
     * viewport, see above) but can still be shrinked down */

    Gtk.Requisition req;
    this.get_preferred_size(out req, out req);
    this.resize (req.width, req.height);
    viewport_widget.set_size_request (-1, -1);
  }

  /**
   * Make sure that the layout manager manages the entire stage.
   *
   * @param actor unused
   * @param box unused
   * @param flags unused
   */
  public void on_stage_resize (Clutter.Actor           actor,
                               Clutter.ActorBox        box,
                               Clutter.AllocationFlags flags)
  {
    this.viewport_layout.set_size (viewport.width, viewport.height);
    this.background_layer.set_size (viewport.width, viewport.height);
    this.timeout_layer.set_position (video_preview.width/3 + viewport.width/2,
                                viewport.height-20);
  }

  /**
   * The method to call when the countdown is finished.
   */
  private void finish_countdown_callback ()
  {
    if (action_cancelled == false)
    {
      string file_name = fileutil.get_new_media_filename (this.current_mode);

      if (settings.get_boolean ("flash"))
      {
        this.flash.fire ();
      }
      CanberraGtk.play_for_widget (this.main_vbox, 0,
                                   Canberra.PROP_EVENT_ID, "camera-shutter",
                                   Canberra.PROP_MEDIA_ROLE, "event",
                                   Canberra.PROP_EVENT_DESCRIPTION, _("Shutter sound"),
                                   null);
      this.camera.take_photo (file_name);
    }

    if (current_mode == MediaMode.PHOTO)
    {
      enable_mode_change ();
    }
  }

  Countdown current_countdown;
  /**
   * Start to take a photo, starting a countdown if it is enabled.
   */
  public void take_photo ()
  {
    if (settings.get_boolean ("countdown"))
    {
      if (current_mode == MediaMode.PHOTO)
      {
        disable_mode_change ();
      }

      current_countdown = new Countdown (this.countdown_layer);
      current_countdown.start (finish_countdown_callback);
    }
    else
    {
      finish_countdown_callback ();
    }
  }

  private int  burst_count;
  private uint burst_callback_id;

  /**
   * Take a photo during burst mode, and increment the burst count.
   *
   * @return true if there are more photos to be taken in the current burst,
   * false otherwise
   */
  private bool burst_take_photo ()
  {
    if (is_bursting && burst_count < settings.get_int ("burst-repeat"))
    {
      this.take_photo ();
      burst_count++;
      return true;
    }
    else
    {
      toggle_photo_bursting (false);
      return false;
    }
  }

    /**
     * Cancel the current action (if any)
     */
    private bool cancel_running_action ()
    {
        if ((current_countdown != null && current_countdown.running)
            || is_bursting || is_recording)
        {
            action_cancelled = true;

            switch (current_mode)
            {
                case MediaMode.PHOTO:
                    current_countdown.stop ();
                    finish_countdown_callback ();
                    break;
                case MediaMode.BURST:
                    toggle_photo_bursting (false);
                    break;
                case MediaMode.VIDEO:
                    toggle_video_recording (false);
                    break;
            }

            action_cancelled = false;

            return true;
        }

        return false;
    }

  /**
   * Cancel the current activity if the escape key is pressed.
   *
   * @param event the key event, to check which key was pressed
   * @return false, to allow further processing of the event
   */
  private bool on_key_release (Gdk.EventKey event)
  {
    string key;

    key = Gdk.keyval_name (event.keyval);
    if (strcmp (key, "Escape") == 0)
    {
      if (cancel_running_action ())
      {
        return false;
      }
      else if (is_effects_selector_active)
      {
        effects_toggle_button.set_active (false);
      }
    }
    return false;
  }

  /**
   * Toggle whether video recording is active.
   *
   * @param is_start whether to start video recording
   */
  public void toggle_video_recording (bool is_start)
  {
    if (is_start)
    {
      camera.start_video_recording (fileutil.get_new_media_filename (this.current_mode));
      /* Will be called every 1 second while
       * update_timeout_layer returns true.
       */
      Timeout.add_seconds (1, update_timeout_layer);
      take_action_button.tooltip_text = _("Stop recording");
      take_action_button_image.set_from_icon_name ("media-playback-stop-symbolic", Gtk.IconSize.BUTTON);
      this.is_recording = true;
      this.disable_mode_change ();
    }
    else
    {
      camera.stop_video_recording ();
      /* The timeout_layer always shows the "00:00:00"
       * string when not recording, in order to notify
       * the user about two things:
       *   + The user is making use of the recording mode.
       *   + The user is currently not recording.
       */
      timeout_layer.text = "00:00:00";
      take_action_button.tooltip_text = _("Record a video");
      take_action_button_image.set_from_icon_name ("camera-web-symbolic", Gtk.IconSize.BUTTON);
      this.is_recording = false;
      this.enable_mode_change ();
    }
  }

  /**
   * Update the timeout layer displayed timer.
   *
   * @return false, if the source, Timeout.add_seconds (used
   * in the toogle_video_recording method), should be removed.
   */
  private bool update_timeout_layer ()
  {
    if (is_recording) {
      timeout_layer.text = camera.get_recorded_time ();
      return true;
    }
    else
      return false;
  }

  /**
   * Toggle whether photo bursting is active.
   *
   * @param is_start whether to start capturing a photo burst
   */
  public void toggle_photo_bursting (bool is_start)
  {
    if (is_start)
    {
      is_bursting = true;
      this.disable_mode_change ();
      // FIXME: Set the effects action to be inactive.
      take_action_button.tooltip_text = _("Stop taking pictures");
      burst_take_photo ();

      /* Use the countdown duration if it is greater than the burst delay, plus
       * about 500 ms for taking the photo. */
      var burst_delay = settings.get_int ("burst-delay");
      var countdown_duration = 500 + settings.get_int ("countdown-duration") * 1000;
      if ((burst_delay - countdown_duration) < 1000 && settings.get_boolean ("countdown"))
      {
        burst_callback_id = GLib.Timeout.add (countdown_duration, burst_take_photo);
      }
      else
      {
        burst_callback_id = GLib.Timeout.add (burst_delay, burst_take_photo);
      }
    }
    else
    {
      if (current_countdown != null && current_countdown.running)
        current_countdown.stop ();

      is_bursting = false;
      this.enable_mode_change ();
      take_action_button.tooltip_text = _("Take multiple photos");
      burst_count = 0;
      fileutil.reset_burst ();
      GLib.Source.remove (burst_callback_id);
    }
  }

    /**
     * Take a photo or burst of photos, or record a video, based on the current
     * capture mode.
     */
    public void shoot ()
    {
        switch (current_mode)
        {
            case MediaMode.PHOTO:
                take_photo ();
                break;
            case MediaMode.VIDEO:
                toggle_video_recording (!is_recording);
                break;
            case MediaMode.BURST:
                toggle_photo_bursting (!is_bursting);
                break;
            default:
                assert_not_reached ();
        }
    }

    /**
     * Show an error.
     *
     * @param error the error to display, or null to hide the error layer
     */
    public void show_error (string? error)
    {
        if (error != null)
        {
            current_effects_grid.hide ();
            video_preview.hide ();
            error_layer.text = error;
            error_layer.show ();
        }
        else
        {
            error_layer.hide ();

            if (is_effects_selector_active)
            {
                current_effects_grid.show ();
            }
            else
            {
                video_preview.show ();
            }
        }
    }

    /**
     * Toggle the display of the effect selector.
     *
     * @param effects whether effects should be enabled
     */
    public void set_effects (bool effects)
    {
        toggle_effects_selector (effects);
    }

  /**
   * Change the selected effect, as a new one was selected.
   *
   * @param tap unused
   * @param source the actor (with associated effect) that was selected
   */
  public void on_selected_effect_change (Clutter.TapAction tap,
                                         Clutter.Actor source)
  {
    /* Disable the effects selector after selecting an effect. */
    effects_toggle_button.set_active (false);

    selected_effect = source.get_data ("effect");
    camera.set_effect (selected_effect);
    settings.set_string ("selected-effect", selected_effect.name);
  }

    /**
     * Navigate back one page of effects.
     */
    private void on_effects_previous ()
    {
        if (is_previous_effects_page ())
        {
            activate_effects_page ((int)current_effects_page - 1);
        }
    }

    /**
     * Navigate forward one page of effects.
     */
    private void on_effects_next ()
    {
        if (is_next_effects_page ())
        {
            activate_effects_page ((int)current_effects_page + 1);
        }
    }

  /**
   * Switch to the supplied page of effects.
   *
   * @param number the effects page to switch to
   */
  private void activate_effects_page (int number)
  {
    if (!is_effects_selector_active)
      return;
    current_effects_page = number;
    if (viewport_layout.get_children ().index (current_effects_grid) != -1)
    {
      viewport_layout.remove_child (current_effects_grid);
    }
    current_effects_grid = effects_grids.nth_data (number);
    current_effects_grid.opacity = 0;
    viewport_layout.add_child (current_effects_grid);
    current_effects_grid.save_easing_state ();
    current_effects_grid.set_easing_mode (Clutter.AnimationMode.LINEAR);
    current_effects_grid.set_easing_duration (500);
    current_effects_grid.opacity = 255;
    current_effects_grid.restore_easing_state ();


    uint i = 0;
    foreach (var effect in effects_manager.effects)
    {
        uint page_nr = i / EFFECTS_PER_PAGE;
        if (page_nr == number)
        {
            if (!effect.is_preview_connected ())
            {
                Clutter.Actor texture = effect.get_data<Clutter.Actor> ("texture");
                camera.connect_effect_texture (effect, texture);
            }
            effect.enable_preview ();
        }
        else
        {
            if (effect.is_preview_connected ())
            {
                effect.disable_preview ();
            }
        }

	    i++;
    }

    setup_effects_page_switch_sensitivity ();
  }

    /**
     * Control the sensitivity of the effects page navigation buttons.
     */
    private void setup_effects_page_switch_sensitivity ()
    {
        var effects_next = this.lookup_action ("effects-next") as SimpleAction;
        var effects_previous = this.lookup_action ("effects-previous") as SimpleAction;

        effects_next.set_enabled (is_effects_selector_active
                                  && is_next_effects_page ());
        effects_previous.set_enabled (is_effects_selector_active
                                      && is_previous_effects_page ());
    }

    private bool is_next_effects_page ()
    {
        // Calculate the number of effects visible up to the current page.
        return (current_effects_page + 1) * EFFECTS_PER_PAGE < effects_manager.effects.length ();
    }

    private bool is_previous_effects_page ()
    {
        return current_effects_page != 0;
    }

    /**
     * Toggle the visibility of the effects selector.
     *
     * @param active whether the selector should be active
     */
    private void toggle_effects_selector (bool active)
    {
        is_effects_selector_active = active;

        if (effects_grids.length () == 0)
        {
            show_error (active ? _("No effects found") : null);
        }
        else if (active)
        {
            video_preview.hide ();
            current_effects_grid.show ();
            activate_effects_page ((int)current_effects_page);
        }
        else
        {
            current_effects_grid.hide ();
            video_preview.show ();
        }

        camera.toggle_effects_pipeline (active);
        setup_effects_page_switch_sensitivity ();
        update_header_bar_title ();
    }

  /**
   * Create the effects selector.
   */
  private void setup_effects_selector ()
  {
    if (current_effects_grid == null)
    {
      effects_manager = new EffectsManager ();
      effects_manager.load_effects ();

      /* Must initialize effects_grids before returning, as it is dereferenced later, bug 654671. */
      effects_grids = new List<Clutter.Actor> ();

      if (effects_manager.effects.length () == 0)
      {
        warning ("gnome-video-effects is not installed.");
        return;
      }

      foreach (var effect in effects_manager.effects)
      {
          Clutter.GridLayout grid_layout = new GridLayout ();
          var grid = new Clutter.Actor ();
          grid.set_layout_manager (grid_layout);
          effects_grids.append (grid);
          grid_layout.set_column_spacing (10);
          grid_layout.set_row_spacing (10);
      }

      uint i = 0;
      foreach (var effect in effects_manager.effects)
      {
        Clutter.Actor texture = new Clutter.Actor ();
        Clutter.BinLayout layout = new Clutter.BinLayout (Clutter.BinAlignment.CENTER,
                                                          Clutter.BinAlignment.CENTER);
        var box = new Clutter.Actor ();
        box.set_layout_manager (layout);
        Clutter.Text      text = new Clutter.Text ();
        var rect = new Clutter.Actor ();

        rect.opacity = 128;
        rect.background_color = Clutter.Color.from_string ("black");

        texture.content_gravity = Clutter.ContentGravity.RESIZE_ASPECT;
        box.add_child (texture);
        box.reactive = true;
        box.min_height = 40;
        box.min_width = 50;
        var tap = new Clutter.TapAction ();
        box.add_action (tap);
        tap.tap.connect (on_selected_effect_change);
        box.set_data ("effect", effect);
        effect.set_data ("texture", texture);

        text.text  = effect.name;
        text.color = Clutter.Color.from_string ("white");

        rect.height = text.height + 5;
        rect.x_align = Clutter.ActorAlign.FILL;
        rect.y_align = Clutter.ActorAlign.END;
        rect.x_expand = true;
        rect.y_expand = true;
        box.add_child (rect);

        text.x_align = Clutter.ActorAlign.CENTER;
        text.y_align = Clutter.ActorAlign.END;
        text.x_expand = true;
        text.y_expand = true;
        box.add_child (text);

        var grid_layout = effects_grids.nth_data (i / EFFECTS_PER_PAGE).layout_manager as GridLayout;
        grid_layout.attach (box, ((int)(i % EFFECTS_PER_PAGE)) % 3,
                            ((int)(i % EFFECTS_PER_PAGE)) / 3, 1, 1);

        i++;
      }

      setup_effects_page_switch_sensitivity ();
      current_effects_grid = effects_grids.nth_data (0);
    }
  }

    /**
     * Update the UI when the camera starts playing.
     */
    public void camera_state_change_playing ()
    {
        show_error (null);

        Effect effect = effects_manager.get_effect (settings.get_string ("selected-effect"));
        if (effect != null)
        {
            camera.set_effect (effect);
        }
    }

    /**
     * Report an error as the camerabin switched to the NULL state.
     */
    public void camera_state_change_null ()
    {
        cancel_running_action ();

        if (!error_layer.visible)
        {
            show_error (_("There was an error playing video from the webcam"));
        }
    }

  /**
   * Select next camera in list and activate it.
   */
  public void on_switch_camera_clicked ()
  {
      unowned Cheese.CameraDevice selected;
      unowned Cheese.CameraDevice next = null;
      GLib.GenericArray<unowned Cheese.CameraDevice> cameras;
      uint i;

      if (camera == null)
      {
          return;
      }

      selected = camera.get_selected_device ();

      if (selected == null)
      {
          return;
      }

      cameras = camera.get_camera_devices ();

      for (i = 0; i < cameras.length; i++)
      {
          next = cameras.get (i);

          if (next == selected)
          {
              break;
          }
      }

      if (i + 1 < cameras.length)
      {
          next = cameras.get (i + 1);
      }
      else
      {
          next = cameras.get (0);
      }

      if (next == selected)
      {
          /* Next is the same device.... */
          return;
      }

      camera.set_device (next);
      camera.switch_camera_device ();
  }

  /**
   * Set switch camera buttons visible state.
   */
  public void set_switch_camera_button_state ()
  {
      unowned Cheese.CameraDevice selected;
      GLib.GenericArray<unowned Cheese.CameraDevice> cameras;

      if (camera == null)
      {
          switch_camera_button.set_visible (false);
          return;
      }

      selected = camera.get_selected_device ();

      if (selected == null)
      {
          switch_camera_button.set_visible (false);
          return;
      }

      cameras = camera.get_camera_devices ();

      if (cameras.length > 1)
      {
         switch_camera_button.set_visible (true);
         return;
      }

      switch_camera_button.set_visible (false);
  }

  /**
   * Load the UI from the GtkBuilder description.
   */
  public void setup_ui ()
  {
        clutter_builder = new Clutter.Script ();
    fileutil        = new FileUtil ();
    flash           = new Flash (this);
    settings        = new GLib.Settings ("org.gnome.Cheese");

        var menu = application.get_menu_by_id ("thumbview-menu");
        thumbnail_popup = new Gtk.Menu.from_model (menu);
        
        application.set_accels_for_action ("app.quit", {"<Primary>q"});
        application.set_accels_for_action ("app.fullscreen", {"F11"});
        application.set_accels_for_action ("win.file-open", {"<Primary>o"});
        application.set_accels_for_action ("win.file-saveas", {"<Primary>s"});
        application.set_accels_for_action ("win.file-trash", {"Delete"});
        application.set_accels_for_action ("win.file-delete", {"<Shift>Delete"});

        this.add_action_entries (actions, this);

        try
        {
            clutter_builder.load_from_resource ("/org/gnome/Cheese/cheese-viewport.json");
        }
        catch (Error err)
        {
            error ("Error: %s", err.message);
        }

        viewport = viewport_widget.get_stage () as Clutter.Stage;

        video_preview = clutter_builder.get_object ("video_preview") as Clutter.Actor;
        viewport_layout = clutter_builder.get_object ("viewport_layout") as Clutter.Actor;
        viewport_layout_manager = clutter_builder.get_object ("viewport_layout_manager") as Clutter.BinLayout;
        countdown_layer = clutter_builder.get_object ("countdown_layer") as Clutter.Text;
        background_layer = clutter_builder.get_object ("background") as Clutter.Actor;
        error_layer = clutter_builder.get_object ("error_layer") as Clutter.Text;
        timeout_layer = clutter_builder.get_object ("timeout_layer") as Clutter.Text;

    video_preview.request_mode      = Clutter.RequestMode.HEIGHT_FOR_WIDTH;
    viewport.add_child (background_layer);
    viewport_layout.set_layout_manager (viewport_layout_manager);

    viewport.add_child (viewport_layout);
    viewport.add_child (timeout_layer);

    viewport.allocation_changed.connect (on_stage_resize);

    thumb_view = new Cheese.ThumbView ();
    thumb_nav  = new Eog.ThumbNav (thumb_view, false);
        thumbnail_popup.attach_to_widget (thumb_view, null);
        thumb_view.popup_menu.connect (on_thumb_view_popup_menu);

        Gtk.CssProvider css;
        try
        {
            var file = File.new_for_uri ("resource:///org/gnome/Cheese/cheese.css");
            css = new Gtk.CssProvider ();
            css.load_from_file (file);
        }
        catch (Error e)
        {
            // TODO: Use parsing-error signal.
            error ("Error parsing CSS: %s\n", e.message);
        }

    Gtk.StyleContext.add_provider_for_screen (screen, css, STYLE_PROVIDER_PRIORITY_USER);

    thumb_view.button_press_event.connect (on_thumbnail_button_press_event);

    switch_camera_button.clicked.connect (on_switch_camera_clicked);

    /* needed for the sizing tricks in set_wide_mode (allocation is 0
     * if the widget is not realized */
    viewport_widget.realize ();

    set_wide_mode (false);

    setup_effects_selector ();

    this.key_release_event.connect (on_key_release);
  }

    public Clutter.Actor get_video_preview ()
    {
        return video_preview;
    }

  /**
   * Setup the thumbview thumbnail monitors.
   */
  public void start_thumbview_monitors ()
  {
    thumb_view.start_monitoring_video_path (fileutil.get_video_path ());
    thumb_view.start_monitoring_photo_path (fileutil.get_photo_path ());
  }

    /**
     * Set the current media mode (photo, video or burst).
     *
     * @param mode the media mode to set
     */
    public void set_current_mode (MediaMode mode)
    {
        current_mode = mode;

        set_resolution (current_mode);
        update_header_bar_title ();
        timeout_layer.hide ();

        switch (current_mode)
        {
            case MediaMode.PHOTO:
                take_action_button.tooltip_text = _("Take a photo using a webcam");
                break;

            case MediaMode.VIDEO:
                take_action_button.tooltip_text = _("Record a video using a webcam");
                timeout_layer.text = "00:00:00";
                timeout_layer.show ();
                break;

            case MediaMode.BURST:
                take_action_button.tooltip_text = _("Take multiple photos using a webcam");
                break;
        }
    }

     /**
     * Set the header bar title.
     */
    private void update_header_bar_title ()
    {
        if (is_effects_selector_active)
        {
            set_window_title (_("Choose an Effect"));
        }
        else
        {
            switch (current_mode)
            {
                case MediaMode.PHOTO:
                    set_window_title (_("Take a Photo"));
                    break;

                case MediaMode.VIDEO:
                    set_window_title (_("Record a Video"));
                    break;

                case MediaMode.BURST:
                    set_window_title (_("Take Multiple Photos"));
                    break;
            }
        }
    }
    /**
     * Set the camera.
     *
     * @param camera the camera to set
     */
    public void set_camera (Camera camera)
    {
        this.camera = camera;
        set_switch_camera_button_state ();
     }
}