File: gnome-mines.vala

package info (click to toggle)
gnome-mines 1%3A3.22.2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 18,436 kB
  • ctags: 753
  • sloc: ansic: 9,582; sh: 1,237; makefile: 156; xml: 61
file content (981 lines) | stat: -rw-r--r-- 34,456 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
/*
 * Copyright (C) 2011-2012 Robert Ancell
 *
 * 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 3 of the License, or (at your option) any later
 * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
 * license.
 */

public class Mines : Gtk.Application
{
    /* Settings keys */
    private Settings settings;
    private const string KEY_XSIZE = "xsize";
    private const int XSIZE_MIN = 4;
    private const int XSIZE_MAX = 100;
    private const string KEY_YSIZE = "ysize";
    private const int YSIZE_MIN = 4;
    private const int YSIZE_MAX = 100;
    private const string KEY_NMINES = "nmines";
    private const string KEY_MODE = "mode";

    /* For command-line options */
    private static int game_mode = -1;

    /* Shared Settings keys */
    public static const string KEY_USE_QUESTION_MARKS = "use-question-marks";
    public static const string KEY_USE_OVERMINE_WARNING = "use-overmine-warning";
    public static const string KEY_USE_AUTOFLAG = "use-autoflag";
    public static const string KEY_THEME = "theme";
    public static const string KEY_USE_ANIMATIONS = "use-animations";

    private Gtk.Widget main_screen;
    private Gtk.Button play_pause_button;
    private Gtk.Label play_pause_label;
    private Gtk.Button replay_button;
    private Gtk.Button high_scores_button;
    private Gtk.Button new_game_button;
    private Gtk.AspectFrame minefield_aspect;
    private Gtk.Overlay minefield_overlay;
    private Gtk.Box aspect_child;
    private Gtk.Box buttons_box;
    private Gtk.Box paused_box;
    private Gtk.ScrolledWindow scrolled;
    private Gtk.Stack stack;
    private ThemeSelectorDialog theme_dialog;

    private Gtk.Label clock_label;

    private Menu app_main_menu;

    /* Main window */
    private Gtk.Window window;
    private int window_width;
    private int window_height;
    private bool is_maximized;
    private bool is_tiled;

    /* true when the user has requested the game to pause. */
    private bool pause_requested;

    /* true when the next configure event should be ignored. */
    private bool window_skip_configure;

    /* Game scores */
    private Games.Scores.Context context;

    /* Minefield being played */
    private Minefield minefield;

    /* Minefield widget */
    private MinefieldView minefield_view;

    /* Game status */
    private Gtk.Label flag_label;

    private Gtk.SpinButton mines_spin;
    private SimpleAction new_game_action;
    private SimpleAction repeat_size_action;
    private SimpleAction pause_action;
    private SimpleAction[] size_actions = new SimpleAction[4];
    private Gtk.AspectFrame new_game_screen;
    private Gtk.AspectFrame custom_game_screen;
    private Gtk.CssProvider theme_provider;

    private const OptionEntry[] option_entries =
    {
        { "version", 'v', 0, OptionArg.NONE, null, N_("Print release version and exit"), null },
        { "small",  0, 0, OptionArg.NONE, null, N_("Small game"), null },
        { "medium", 0, 0, OptionArg.NONE, null, N_("Medium game"), null },
        { "big",    0, 0, OptionArg.NONE, null, N_("Big game"), null },
        { null }
    };

    private const GLib.ActionEntry[] action_entries =
    {
        { "new-game",           new_game_cb                                 },
        { "silent-new-game",    silent_new_game_cb                          },
        { "repeat-size",        repeat_size_cb                              },
        { "small-size",         small_size_clicked_cb                       },
        { "medium-size",        medium_size_clicked_cb                      },
        { "large-size",         large_size_clicked_cb                       },
        { "custom-size",        show_custom_game_screen                     },
        { "pause",              toggle_pause_cb                             },
        { "scores",             scores_cb                                   },
        { "preferences",        preferences_cb                              },
        { "quit",               quit_cb                                     },
        { "help",               help_cb                                     },
        { "about",              about_cb                                    }
    };

    public Mines ()
    {
        Object (application_id: "org.gnome.mines", flags: ApplicationFlags.FLAGS_NONE);

        add_main_option_entries (option_entries);
    }

    private void set_game_theme (string theme)
    {
        string theme_path = theme;
        bool is_switch = theme_provider != null;

        if (!Path.is_absolute (theme_path)) {
            theme_path = Path.build_path (Path.DIR_SEPARATOR_S, DATA_DIRECTORY, "themes", theme);
        }
        if (!is_switch) {
            Gtk.IconTheme.get_default ().append_search_path (theme_path);
        } else {
            string[] icon_search_path;
            Gtk.IconTheme.get_default ().get_search_path (out icon_search_path);
            icon_search_path[icon_search_path.length - 1] = theme_path;
            Gtk.IconTheme.get_default ().set_search_path (icon_search_path);
        }

        var theme_css_path = Path.build_filename (theme_path, "theme.css");
        try
        {
            if (is_switch) {
                Gtk.StyleContext.remove_provider_for_screen (Gdk.Screen.get_default (), theme_provider);
            }
            theme_provider = new Gtk.CssProvider ();
            theme_provider.load_from_path (theme_css_path);
            Gtk.StyleContext.add_provider_for_screen (Gdk.Screen.get_default (), theme_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
        }
        catch (GLib.Error e)
        {
            warning ("Error loading css styles from %s: %s", theme_css_path, e.message);
        }
        if (window != null)
        {
            window.get_window ().invalidate_rect (null, true);
            window.queue_draw ();
        }
        Gtk.StyleContext.reset_widgets (Gdk.Screen.get_default ());

        if (theme_dialog != null)
            theme_dialog.queue_draw ();
        if (minefield_view != null)
            minefield_view.refresh ();
    }

    protected override void startup ()
    {
        base.startup ();

        Environment.set_application_name (_("Mines"));

        settings = new Settings ("org.gnome.mines");
        settings.delay ();

        if (game_mode != -1)
            settings.set_int (KEY_MODE, game_mode);

        Gtk.Window.set_default_icon_name ("gnome-mines");

        var css_provider = new Gtk.CssProvider ();
        var css_path = Path.build_filename (DATA_DIRECTORY, "gnome-mines.css");
        try
        {
            css_provider.load_from_path (css_path);
        }
        catch (GLib.Error e)
        {
            warning ("Error loading css styles from %s: %s", css_path, e.message);
        }

        Gtk.StyleContext.add_provider_for_screen (Gdk.Screen.get_default (), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
        var ui_builder = new Gtk.Builder ();
        try
        {
            ui_builder.add_from_file (Path.build_filename (DATA_DIRECTORY, "interface.ui", null));
        }
        catch (Error e)
        {
            warning ("Could not load game UI: %s", e.message);
        }
        settings.changed[KEY_THEME].connect (() => { set_game_theme (settings.get_string (KEY_THEME)); });
        set_game_theme (settings.get_string (KEY_THEME));

        add_action_entries (action_entries, this);
        new_game_action = lookup_action ("new-game") as SimpleAction;
        new_game_action.set_enabled (true);
        repeat_size_action = lookup_action ("repeat-size") as SimpleAction;
        repeat_size_action.set_enabled (false);
        pause_action = lookup_action ("pause") as SimpleAction;
        pause_action.set_enabled (false);

        size_actions[0] = lookup_action ("small-size") as SimpleAction;
        size_actions[1] = lookup_action ("medium-size") as SimpleAction;
        size_actions[2] = lookup_action ("large-size") as SimpleAction;
        size_actions[3] = lookup_action ("custom-size") as SimpleAction;

        add_action (settings.create_action (KEY_USE_OVERMINE_WARNING));
        add_action (settings.create_action (KEY_USE_QUESTION_MARKS));

        window = (Gtk.ApplicationWindow) ui_builder.get_object ("main_window");
        window.size_allocate.connect (size_allocate_cb);
        window.window_state_event.connect (window_state_event_cb);
        window.focus_out_event.connect (window_focus_out_event_cb);
        window.focus_in_event.connect (window_focus_in_event_cb);
        window.set_default_size (settings.get_int ("window-width"), settings.get_int ("window-height"));
        Gtk.Settings.get_default ().gtk_enable_animations = settings.get_boolean ("use-animations");

        if (settings.get_boolean ("window-is-maximized"))
            window.maximize ();
        add_window (window);

        var desktop = Environment.get_variable ("XDG_CURRENT_DESKTOP");
        if (desktop == null || desktop != "Unity")
        {
            var headerbar = new Gtk.HeaderBar ();
            headerbar.show_close_button = true;
            headerbar.set_title (_("Mines"));
            headerbar.show ();
            window.set_titlebar (headerbar);
        }

        bool shell_shows_menubar;
        Gtk.Settings.get_default ().get ("gtk-shell-shows-menubar", out shell_shows_menubar);
        if (!shell_shows_menubar)
        {
            var menu = new Menu ();
            app_main_menu = new Menu ();
            menu.append_section (null, app_main_menu);
            app_main_menu.append (_("_Scores"), "app.scores");
            app_main_menu.append (_("A_ppearance"), "app.preferences");
            var section = new Menu ();
            menu.append_section (null, section);
            section.append (_("_Show Warnings"), "app.%s".printf (KEY_USE_OVERMINE_WARNING));
            section.append (_("_Use Question Flags"), "app.%s".printf (KEY_USE_QUESTION_MARKS));
            section = new Menu ();
            menu.append_section (null, section);
            section.append (_("_Help"), "app.help");
            section.append (_("_About"), "app.about");
            section.append (_("_Quit"), "app.quit");
            set_app_menu (menu);
        }
        else
        {
            var menu = new Menu ();
            var mines_menu = new Menu ();
            menu.append_submenu (_("_Mines"), mines_menu);
            mines_menu.append (_("_New Game"), "app.new-game");
            mines_menu.append (_("_Scores"), "app.scores");
            mines_menu.append (_("A_ppearance"), "app.preferences");
            mines_menu.append (_("_Show Warnings"), "app.%s".printf (KEY_USE_OVERMINE_WARNING));
            mines_menu.append (_("_Use Question Flags"), "app.%s".printf (KEY_USE_QUESTION_MARKS));
            mines_menu.append (_("_Quit"), "app.quit");
            var help_menu = new Menu ();
            menu.append_submenu (_("_Help"), help_menu);
            help_menu.append (_("_Contents"), "app.help");
            help_menu.append (_("_About"), "app.about");
            set_menubar (menu);
        }

        set_accels_for_action ("app.new-game", {"<Primary>n"});
        set_accels_for_action ("app.silent-new-game", {"Escape"});
        set_accels_for_action ("app.repeat-size", {"<Primary>r"});
        set_accels_for_action ("app.small-size", {"1"});
        set_accels_for_action ("app.medium-size", {"2"});
        set_accels_for_action ("app.large-size", {"3"});
        set_accels_for_action ("app.custom-size", {"4"});
        set_accels_for_action ("app.pause", {"Pause"});
        set_accels_for_action ("app.help", {"F1"});
        set_accels_for_action ("app.quit", {"<Primary>q", "<Primary>w"});

        minefield_view = new MinefieldView (settings);
        minefield_view.show ();

        stack = (Gtk.Stack) ui_builder.get_object ("stack");

        scrolled = (Gtk.ScrolledWindow) ui_builder.get_object ("scrolled");
        scrolled.add (minefield_view);
        scrolled.show ();

        minefield_overlay = (Gtk.Overlay) ui_builder.get_object ("minefield_overlay");
        minefield_overlay.show ();

        minefield_aspect = (Gtk.AspectFrame) ui_builder.get_object ("minefield_aspect");
        minefield_aspect.show ();

        paused_box = (Gtk.Box) ui_builder.get_object ("paused_box");
        buttons_box = (Gtk.Box) ui_builder.get_object ("buttons_box");
        aspect_child = (Gtk.Box) ui_builder.get_object ("aspect_child");
        paused_box = (Gtk.Box) ui_builder.get_object ("paused_box");
        paused_box.button_press_event.connect (view_button_press_event);

        minefield_overlay.add_overlay (paused_box);

        main_screen = (Gtk.Widget) ui_builder.get_object ("main_screen");
        main_screen.show_all ();

        /* Initialize New Game Screen */
        startup_new_game_screen (ui_builder);

        /* Initialize Custom Game Screen */
        startup_custom_game_screen (ui_builder);

        context = new Games.Scores.Context.with_importer ("gnome-mines",
                                                          /* Label on the scores dialog */
                                                          _("Minefield:"),
                                                          window,
                                                          create_category_from_key,
                                                          Games.Scores.Style.TIME_LESS_IS_BETTER,
                                                          new Games.Scores.HistoryFileImporter (parse_old_score));

        flag_label = (Gtk.Label) ui_builder.get_object ("flag_label");
        clock_label = (Gtk.Label) ui_builder.get_object ("clock_label");

        play_pause_button = (Gtk.Button) ui_builder.get_object ("play_pause_button");
        play_pause_label = (Gtk.Label) ui_builder.get_object ("play_pause_label");

        high_scores_button = (Gtk.Button) ui_builder.get_object ("high_scores_button");
        replay_button = (Gtk.Button) ui_builder.get_object ("replay_button");
        new_game_button = (Gtk.Button) ui_builder.get_object ("new_game_button");

        if (game_mode != -1)
            start_game ();
    }

    private Games.Scores.Category? create_category_from_key (string key)
    {
        var tokens = key.split ("-");
        if (tokens.length != 3)
            return null;

        var width = int.parse (tokens[0]);
        var height = int.parse (tokens[1]);
        var num_mines = int.parse (tokens[2]);

        if (width <= 0 || height <= 0 || num_mines <= 0)
            return null;

        /* For the scores dialog. First width, then height, then number of mines. */
        return new Games.Scores.Category (key, ngettext ("%d × %d, %d mine",
                                                         "%d × %d, %d mines",
                                                         num_mines).printf (width, height, num_mines));
    }

    private void parse_old_score (string line, out Games.Scores.Score score, out Games.Scores.Category category)
    {
        score = null;
        category = null;

        var tokens = line.split (" ");
        if (tokens.length != 5)
            return;

        var date = Games.Scores.HistoryFileImporter.parse_date (tokens[0]);
        var width = int.parse (tokens[1]);
        var height = int.parse (tokens[2]);
        var num_mines = int.parse (tokens[3]);
        var seconds = int.parse (tokens[4]);

        if (date <= 0 || width <= 0 || height <= 0 || num_mines <= 0 || seconds < 0)
            return;

        score = new Games.Scores.Score (seconds, date);
        category = create_category_from_key (@"$width-$height-$num_mines");
    }

    private void startup_new_game_screen (Gtk.Builder builder)
    {
        new_game_screen =  (Gtk.AspectFrame) builder.get_object ("new_game_screen");

        var button = (Gtk.Button) builder.get_object ("small_size_btn");
        button.clicked.connect (small_size_clicked_cb);

        var label = new Gtk.Label (null);
        label.set_markup (make_minefield_description (8, 8, 10));
        label.set_justify (Gtk.Justification.CENTER);
        button.add (label);

        button = (Gtk.Button) builder.get_object ("medium_size_btn");
        button.clicked.connect (medium_size_clicked_cb);

        label = new Gtk.Label (null);
        label.set_markup (make_minefield_description (16, 16, 40));
        label.set_justify (Gtk.Justification.CENTER);
        button.add (label);

        button = (Gtk.Button) builder.get_object ("large_size_btn");
        button.clicked.connect (large_size_clicked_cb);

        label = new Gtk.Label (null);
        label.set_markup (make_minefield_description (30, 16, 99));
        label.set_justify (Gtk.Justification.CENTER);
        button.add (label);

        button = (Gtk.Button) builder.get_object ("custom_size_btn");
        button.clicked.connect (show_custom_game_screen);

        label = new Gtk.Label (null);
        label.set_markup_with_mnemonic ("<span size='xx-large' weight='heavy'>?</span>\n" + dpgettext2 (null, "board size", _("Custom")));
        label.set_justify (Gtk.Justification.CENTER);
        button.add (label);

        new_game_screen.show_all ();
    }

    private void startup_custom_game_screen (Gtk.Builder builder)
    {
        custom_game_screen =  (Gtk.AspectFrame) builder.get_object ("custom_game_screen");

        var field_width_entry = (Gtk.SpinButton) builder.get_object ("width_spin_btn");
        field_width_entry.set_range (XSIZE_MIN, XSIZE_MAX);
        field_width_entry.value_changed.connect (xsize_spin_cb);
        field_width_entry.set_increments (1, 1);
        field_width_entry.set_value (settings.get_int (KEY_XSIZE));

        var field_height_entry = (Gtk.SpinButton) builder.get_object ("height_spin_btn");
        field_height_entry.set_range (YSIZE_MIN, YSIZE_MAX);
        field_height_entry.value_changed.connect (ysize_spin_cb);
        field_height_entry.set_increments (1, 1);
        field_height_entry.set_value (settings.get_int (KEY_YSIZE));

        mines_spin = (Gtk.SpinButton) builder.get_object ("mines_spin_btn");
        mines_spin.set_range (1, 100);
        mines_spin.set_increments (1, 1);
        mines_spin.value_changed.connect (mines_spin_cb);
        set_mines_limit ();

        var button = (Gtk.Button) builder.get_object ("cancel_btn");
        button.clicked.connect (show_new_game_screen);

        button = (Gtk.Button) builder.get_object ("play_game_btn");
        button.clicked.connect (custom_size_clicked_cb);

        custom_game_screen.show_all ();
    }

    private void size_allocate_cb (Gtk.Allocation allocation)
    {
        if (!is_maximized && !is_tiled && !window_skip_configure)
        {
            window.get_size (out window_width, out window_height);
        }

        window_skip_configure = false;
    }

    private bool window_state_event_cb (Gdk.EventWindowState event)
    {
        if ((event.changed_mask & Gdk.WindowState.MAXIMIZED) != 0)
            is_maximized = (event.new_window_state & Gdk.WindowState.MAXIMIZED) != 0;
        /* We don’t save this state, but track it for saving size allocation */
        if ((event.changed_mask & Gdk.WindowState.TILED) != 0)
            is_tiled = (event.new_window_state & Gdk.WindowState.TILED) != 0;
        return false;
    }

    private bool window_focus_out_event_cb (Gdk.EventFocus event)
    {
        if (minefield != null && minefield.is_clock_started ())
            minefield.paused = true;

        return false;
    }

    private bool window_focus_in_event_cb (Gdk.EventFocus event)
    {
        if (minefield != null && !pause_requested &&
            (theme_dialog == null || theme_dialog.visible == false))
            minefield.paused = false;

        return false;
    }

    private string make_minefield_description (int width, int height, int n_mines)
    {
        var size_label = "%d × %d".printf (width, height);
        var mines_label = ngettext ("<b>%d</b> mine", "<b>%d</b> mines", n_mines).printf (n_mines);
        return "<span size='x-large' weight='ultrabold'>%s</span>\n%s".printf (size_label, mines_label);
    }

    public void start ()
    {
        window.show ();
        show_new_game_screen ();
    }

    protected override void shutdown ()
    {
        base.shutdown ();

        /* Save window state */
        settings.set_int ("window-width", window_width);
        settings.set_int ("window-height", window_height);
        settings.set_boolean (KEY_USE_ANIMATIONS, Gtk.Settings.get_default ().gtk_enable_animations);
        settings.set_boolean ("window-is-maximized", is_maximized);
        settings.apply ();
    }

    protected override int handle_local_options (GLib.VariantDict options)
    {
        if (options.contains ("version"))
        {
            /* NOTE: Is not translated so can be easily parsed */
            stderr.printf ("%1$s %2$s\n", "gnome-mines", VERSION);
            return Posix.EXIT_SUCCESS;
        }

        if (options.contains ("small"))
            game_mode = 0;
        if (options.contains ("medium"))
            game_mode = 1;
        if (options.contains ("big"))
            game_mode = 2;

        /* Activate */
        return -1;
    }

    protected override void activate ()
    {
        window.present ();
    }

    private bool view_button_press_event (Gtk.Widget widget, Gdk.EventButton event)
    {
        /* Cancel pause on click */
        if (minefield.paused)
        {
            minefield.paused = false;
            pause_requested = false;
            return true;
        }

        return false;
    }

    private void quit_cb ()
    {
        window.destroy ();
    }

    private void update_flag_label ()
    {
        flag_label.set_text ("%u/%u".printf (minefield.n_flags, minefield.n_mines));
    }

    private int show_theme_selector ()
    {
        theme_dialog = new ThemeSelectorDialog (window);

        var result = theme_dialog.run ();
        theme_dialog.destroy ();

        return result;
    }

    private void show_scores ()
    {
        context.run_dialog ();
    }

    private void scores_cb ()
    {
        show_scores ();
    }

    private void preferences_cb ()
    {
        show_theme_selector ();
    }

    private void show_custom_game_screen ()
    {
        if (minefield != null)
            return;
        size_actions_toggle (false);
        stack.visible_child_name = "custom_game";
    }

    private bool can_start_new_game ()
    {
        if (minefield != null && minefield.n_cleared > 0 && !minefield.exploded && !minefield.is_complete)
        {
            var was_paused = minefield.paused;
            minefield.paused = true;

            var dialog = new Gtk.MessageDialog (window, Gtk.DialogFlags.MODAL, Gtk.MessageType.QUESTION, Gtk.ButtonsType.NONE, "%s", _("Do you want to start a new game?"));
            dialog.secondary_text = (_("If you start a new game, your current progress will be lost."));
            dialog.add_buttons (_("Keep Current Game"), Gtk.ResponseType.DELETE_EVENT,
                                _("Start New Game"), Gtk.ResponseType.ACCEPT,
                                null);
            var result = dialog.run ();
            dialog.destroy ();
            if (result != Gtk.ResponseType.ACCEPT)
            {
                minefield.paused = was_paused;
                return false;
            }
        }
        return true;
    }

    private void show_new_game_screen ()
    {
        if (stack.visible_child_name == "new_game")
            return;

        if (minefield != null)
        {
            minefield.paused = true;
            pause_requested = false;
            SignalHandler.disconnect_by_func (minefield, null, this);
        }
        minefield = null;

        window.resize (window_width, window_height);

        repeat_size_action.set_enabled (false);
        pause_action.set_enabled (false);

        size_actions_toggle (true);
        stack.visible_child_name = "new_game";
    }

    private void size_actions_toggle (bool enabled)
    {
        for (int i=0; i < size_actions.length; i++)
        {
            size_actions[i].set_enabled (enabled);
        }
    }

    private void start_game ()
    {
        window_skip_configure = true;
        minefield_view.has_focus = true;

        repeat_size_action.set_enabled (false);
        play_pause_label.label = _("_Pause");
        replay_button.label = _("St_art Over");
        play_pause_button.show ();
        high_scores_button.hide ();

        int x, y, n;
        switch (settings.get_int (KEY_MODE))
        {
        case 0:
            x = 8;
            y = 8;
            n = 10;
            break;
        case 1:
            x = 16;
            y = 16;
            n = 40;
            break;
        case 2:
            x = 30;
            y = 16;
            n = 99;
            break;
        default:
        case 3:
            x = settings.get_int (KEY_XSIZE).clamp (XSIZE_MIN, XSIZE_MAX);
            y = settings.get_int (KEY_YSIZE).clamp (YSIZE_MIN, YSIZE_MAX);
            n = settings.get_int (KEY_NMINES).clamp (1, x * y - 10);
            break;
        }

        if (minefield != null)
            SignalHandler.disconnect_by_func (minefield, null, this);
        minefield = new Minefield (x, y, n);
        minefield.marks_changed.connect (marks_changed_cb);
        minefield.explode.connect (explode_cb);
        minefield.cleared.connect (cleared_cb);
        minefield.tick.connect (tick_cb);
        minefield.paused_changed.connect (paused_changed_cb);
        minefield.clock_started.connect (clock_started_cb);

        minefield_view.minefield = minefield;

        int mine_size = int.max ((int) minefield_view.mine_size, 30);
        int request_x = -1, request_y = -1;
        if  (window.get_allocated_width () - scrolled.get_allocated_width () + 30 * x + aspect_child.spacing + buttons_box.get_allocated_width () < Gdk.Screen.width ()) {
            request_x = x * 30 + aspect_child.spacing + 150;
        } else {
            request_x = Gdk.Screen.width () - window.get_allocated_width () + scrolled.get_allocated_width () + aspect_child.spacing + 150;
        }
        if  (window.get_allocated_height () - scrolled.get_allocated_height () + 30 * y < Gdk.Screen.height ()) {
            request_y = y * 30;
        } else {
            request_y = Gdk.Screen.height () - window.get_allocated_height () + scrolled.get_allocated_height ();
        }
        minefield_aspect.set_size_request (request_x, request_y);

        uint width = x * mine_size;
        width += aspect_child.spacing;
        width += uint.max (buttons_box.get_allocated_width (), 150);
        minefield_aspect.ratio = (float) (width) / (y * mine_size);
        minefield_aspect.size_allocate.connect ((allocation) => {
             width = minefield_view.mine_size * x;
             width += aspect_child.spacing;
             width += buttons_box.get_allocated_width ();
             minefield_aspect.ratio = (float) width / (y * minefield_view.mine_size);
        });
        update_flag_label ();

        minefield.paused = false;
        pause_requested = false;

        stack.visible_child_name = "game";
        pause_action.set_enabled (false);

        tick_cb ();
    }

    private void new_game_cb ()
    {
        if (can_start_new_game ())
            show_new_game_screen ();
    }

    private void silent_new_game_cb ()
    {
        if (minefield == null || minefield.n_cleared == 0)
            show_new_game_screen ();
    }

    private void repeat_size_cb ()
    {
        if (can_start_new_game ())
            start_game ();
    }

    private void toggle_pause_cb ()
    {
        if (minefield.paused && !pause_requested)
        {
            pause_requested = true;
        }
        else
        {
            minefield.paused = !minefield.paused;
            pause_requested = minefield.paused;
        }
    }

    private void paused_changed_cb ()
    {
        if (minefield.paused)
            play_pause_label.label = _("_Resume");
        else if (minefield.elapsed > 0)
            play_pause_label.label = _("_Pause");
        paused_box.visible = minefield.paused;
    }

    private void marks_changed_cb (Minefield minefield)
    {
        update_flag_label ();
    }

    private void explode_cb (Minefield minefield)
    {
        game_ended ();
    }

    private void game_ended ()
    {
        replay_button.label = _("Play _Again");
        pause_action.set_enabled (false);
        play_pause_button.hide ();
        high_scores_button.show ();
    }

    private void cleared_cb (Minefield minefield)
    {
        var duration = (uint) (minefield.elapsed + 0.5);
        string key = minefield.width.to_string () + "-" + minefield.height.to_string () + "-" + minefield.n_mines.to_string ();

        new_game_action.set_enabled (false);
        pause_action.set_enabled (false);
        repeat_size_action.set_enabled (false);

        context.add_score.begin (duration, create_category_from_key (key), null, (object, result) => {
            try
            {
                context.add_score.end (result);
            }
            catch (Error e)
            {
                warning ("%s", e.message);
            }
            new_game_action.set_enabled (true);
            show_new_game_screen ();
        });
    }

    private void clock_started_cb ()
    {
        play_pause_label.label = _("_Pause");
        replay_button.sensitive = true;
        pause_action.set_enabled (true);
        repeat_size_action.set_enabled (true);
    }

    private void tick_cb ()
    {
        var elapsed = 0;
        if (minefield != null)
            elapsed = (int) (minefield.elapsed + 0.5);
        var hours = elapsed / 3600;
        var minutes = (elapsed - hours * 3600) / 60;
        var seconds = elapsed - hours * 3600 - minutes * 60;
        if (hours > 0)
            clock_label.set_text ("%02d∶\xE2\x80\x8E%02d∶\xE2\x80\x8E%02d".printf (hours, minutes, seconds));
        else
            clock_label.set_text ("%02d∶\xE2\x80\x8E%02d".printf (minutes, seconds));
    }

    private void about_cb ()
    {
        string[] authors =
        {
            _("Main game:"),
            "Szekeres Istvan (Pista)",
            "Robert Ancell",
            "Robert Roth",
            "",
            _("Score:"),
            "Horacio J. Peña",
            "",
            _("Resizing and SVG support:"),
            "Steve Chaplin",
            "Callum McKenzie",
            null
        };

        string[] artists =
        {
            "Richard Hoelscher",
            null
        };

        string[] documenters =
        {
            "Ekaterina Gerasimova",
            null
        };

        Gtk.show_about_dialog (window,
                               "name", _("Mines"),
                               "version", VERSION,
                               "comments",
                               _("Clear explosive mines off the board"),
                               "copyright",
                               "Copyright © 1997–2008 Free Software Foundation, Inc.",
                               "license-type", Gtk.License.GPL_3_0,
                               "authors", authors,
                               "artists", artists,
                               "documenters", documenters,
                               "translator-credits", _("translator-credits"),
                               "logo-icon-name", "gnome-mines", "website",
                               "https://wiki.gnome.org/Apps/Mines",
                               null);
    }

    private float percent_mines ()
    {
        return 100.0f * (float) settings.get_int (KEY_NMINES) / (settings.get_int (KEY_XSIZE) * settings.get_int (KEY_YSIZE));
    }

    private void set_mines_limit ()
    {
        var size = settings.get_int (KEY_XSIZE) * settings.get_int (KEY_YSIZE);
        var max_mines = (int) Math.round (100.0f * (float) (size - 10) / size);
        var min_mines = int.max (1, (int) Math.round (100.0f / size));
        mines_spin.set_range (min_mines, max_mines);
        mines_spin.set_value ((int) Math.round (percent_mines ()));
    }

    private void xsize_spin_cb (Gtk.SpinButton spin)
    {
        var xsize = spin.get_value_as_int ();
        if (xsize == settings.get_int (KEY_XSIZE))
            return;

        settings.set_int (KEY_XSIZE, xsize);
        set_mines_limit ();
    }

    private void ysize_spin_cb (Gtk.SpinButton spin)
    {
        var ysize = spin.get_value_as_int ();
        if (ysize == settings.get_int (KEY_YSIZE))
            return;

        settings.set_int (KEY_YSIZE, ysize);
        set_mines_limit ();
    }

    private void mines_spin_cb (Gtk.SpinButton spin)
    {
        if (Math.fabs (percent_mines () - spin.get_value ()) <= 0.5f)
            return;

        settings.set_int (KEY_NMINES,
                          (int) Math.round (spin.get_value () * (settings.get_int (KEY_XSIZE) * settings.get_int (KEY_YSIZE)) / 100.0f));
    }

    private void set_mode (int mode)
    {
        if (minefield != null)
            return;

        if (mode != settings.get_int (KEY_MODE))
            settings.set_int (KEY_MODE, mode);

        size_actions_toggle (false);
        start_game ();
    }

    private void small_size_clicked_cb ()
    {
        set_mode (0);
    }

    private void medium_size_clicked_cb ()
    {
        set_mode (1);
    }

    private void large_size_clicked_cb ()
    {
        set_mode (2);
    }

    private void custom_size_clicked_cb ()
    {
        set_mode (3);
    }

    private void help_cb ()
    {
        try
        {
            Gtk.show_uri (window.get_screen (), "help:gnome-mines", Gtk.get_current_event_time ());
        }
        catch (Error e)
        {
            warning ("Failed to show help: %s", e.message);
        }
    }

    public static int main (string[] args)
    {
        Intl.setlocale (LocaleCategory.ALL, "");
        Intl.bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
        Intl.bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
        Intl.textdomain (GETTEXT_PACKAGE);

        var app = new Mines ();
        return app.run (args);
    }
}