swell-foop.vala 15.6 KB
Newer Older
Robert Ancell's avatar
Robert Ancell committed
1 2 3 4 5 6 7 8 9 10
/*
 * Copyright (C) 2010-2013 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 2 of the License, or (at your option) any later
 * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
 * license.
 */

Sophia Yu's avatar
Sophia Yu committed
11 12 13 14 15 16
public class SwellFoop : Gtk.Application
{
    /* Application settings */
    private Settings settings;

    /* Main window */
17 18 19 20
    private Gtk.Window window;

    /* Game history */
    private History history;
Sophia Yu's avatar
Sophia Yu committed
21 22 23 24 25 26 27 28 29 30 31 32

    /* Game being played */
    private Game? game = null;

    /* Rendering of game */
    private GameView view;

    private Clutter.Stage stage;
    private GtkClutter.Embed clutter_embed;

    private Gtk.Dialog? preferences_dialog = null;

33
    private Gtk.HeaderBar headerbar;
Sophia Yu's avatar
Sophia Yu committed
34

35 36
    private bool game_in_progress = true;

Sophia Yu's avatar
Sophia Yu committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    /* Store size options */
    public Size[] sizes;

    private const GLib.ActionEntry[] action_entries =
    {
        { "new-game",      new_game_cb    },
        { "scores",        scores_cb      },
        { "preferences",   preferences_cb },
        { "help",          help_cb        },
        { "about",         about_cb       },
        { "quit",          quit_cb        }
    };

    /* Constructor */
    public SwellFoop ()
    {
        Object (application_id: "org.gnome.swell-foop", flags: ApplicationFlags.FLAGS_NONE);
    }

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

Michael Catanzaro's avatar
Michael Catanzaro committed
60 61
        Gtk.Settings.get_default ().set ("gtk-application-prefer-dark-theme", true);

Sophia Yu's avatar
Sophia Yu committed
62 63 64
        settings = new Settings ("org.gnome.swell-foop");

        add_action_entries (action_entries, this);
Arnaud B.'s avatar
Arnaud B. committed
65 66 67
        set_accels_for_action ("app.new-game", {"<Primary>n"});
        set_accels_for_action ("app.help", {"F1"});
        set_accels_for_action ("app.quit", {"<Primary>q"});
Sophia Yu's avatar
Sophia Yu committed
68 69

        /* Create the main window */
70 71
        window = new Gtk.ApplicationWindow (this);
        window.set_title (_("Swell Foop"));
72
        window.icon_name = "swell-foop";
73
        window.resizable = false;
74
        window.set_events (window.get_events () | Gdk.EventMask.KEY_PRESS_MASK | Gdk.EventMask.KEY_RELEASE_MASK);
Sophia Yu's avatar
Sophia Yu committed
75 76 77

        var vbox = new Gtk.Box (Gtk.Orientation.VERTICAL, 0);
        vbox.show ();
78
        window.add (vbox);
Sophia Yu's avatar
Sophia Yu committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

        /* Create the menus */
        var menu = new Menu ();
        var section = new Menu ();
        menu.append_section (null, section);
        section.append (_("_New Game"), "app.new-game");
        section.append (_("_Scores"), "app.scores");
        section.append (_("_Preferences"), "app.preferences");
        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);

94 95 96 97 98 99 100
        /* Create a headerbar */
        headerbar = new Gtk.HeaderBar ();
        headerbar.show ();
        headerbar.title = _("Swell Foop");
        headerbar.show_close_button = true;
        window.set_titlebar (headerbar);

101 102
        if (Gtk.Settings.get_default ().gtk_shell_shows_app_menu)
        {
103
            var new_game_button = new Gtk.Button.from_icon_name ("view-refresh-symbolic", Gtk.IconSize.SMALL_TOOLBAR);
104
            new_game_button.valign = Gtk.Align.CENTER;
105
            new_game_button.action_name = "app.new-game";
106
            new_game_button.tooltip_text = _("Start a new game");
107
            new_game_button.show ();
108
            headerbar.pack_start (new_game_button);
109
        }
Sophia Yu's avatar
Sophia Yu committed
110 111 112 113 114 115 116 117 118 119

        /* show the current score */
        update_score_cb (0);

        /* Create a clutter renderer widget */
        clutter_embed = new GtkClutter.Embed ();
        clutter_embed.show ();
        vbox.pack_start (clutter_embed, true, true);

        stage = (Clutter.Stage) clutter_embed.get_stage ();
120
        stage.background_color = Clutter.Color.from_string ("#000000");  /* background color is black */
Sophia Yu's avatar
Sophia Yu committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

        /* Initialize the options for sizes */
        sizes = new Size[3];
        sizes[0] = { "small", _("Small"), 6, 5 };
        sizes[1] = { "normal", _("Normal"), 15, 10 };
        sizes[2] = { "large", _("Large"), 20, 15 };

        /* Create an instance of game with initial values for row, column and color */
        game = new Game (get_size ().rows, get_size ().columns, settings.get_int ("colors"));

        /* Game score change will be sent to the main window and show in the score label */
        game.update_score.connect (update_score_cb);
        game.complete.connect (complete_cb);

        /* Create an instance of game view. This follow the Model-View-Controller paradigm */
        view = new GameView ();
        /* Initialize the themes needed by actors */
        view.theme_name = settings.get_string ("theme");
        view.is_zealous = settings.get_boolean ("zealous");
        view.game = game;
141
        stage.add_child (view);
Sophia Yu's avatar
Sophia Yu committed
142 143 144 145 146 147
        /* Request an appropriate size for the game view */
        stage.set_size (view.width, view.height);
        clutter_embed.set_size_request ((int) stage.width, (int) stage.height);

        /* When the mouse leaves the window we need to update the view */
        clutter_embed.leave_notify_event.connect (view.board_left_cb);
148

149 150
        history = new History (Path.build_filename (Environment.get_user_data_dir (), "swell-foop", "history"));
        history.load ();
151 152

        window.key_press_event.connect (key_press_event_cb);
153 154
    }

155
    private bool key_press_event_cb (Gtk.Widget widget, Gdk.EventKey event)
156 157 158
    {
        switch (event.keyval)
        {
159
            case Gdk.Key.F2:
160 161
                new_game ();
                break;
162
            case Gdk.Key.Up:
163 164
                view.cursor_move (0, 1);
                break;
165
            case Gdk.Key.Down:
166 167
                view.cursor_move (0, -1);
                break;
168
            case Gdk.Key.Left:
169 170
                view.cursor_move (-1, 0);
                break;
171
            case Gdk.Key.Right:
172 173
                view.cursor_move (1, 0);
                break;
174
            case Gdk.Key.space:
175
            case Gdk.Key.Return:
176
                view.cursor_click ();
177
                return true; //handle this one to avoid activating the toolbar button
178 179 180 181 182
            default:
                break;
        }

        return false;
Sophia Yu's avatar
Sophia Yu committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    }

    private Size get_size ()
    {
        for (var i = 0; i < sizes.length; i++)
        {
            if (sizes[i].id == settings.get_string ("size"))
                return sizes[i];
        }

        return sizes[0];
    }

    private void update_score_cb (int points_awarded)
    {
        var score = 0;
        if (game != null)
            score = game.score;

Michael Catanzaro's avatar
Michael Catanzaro committed
202
        headerbar.subtitle = _("Score: %u").printf (score);
Sophia Yu's avatar
Sophia Yu committed
203 204 205 206
    }

    private void complete_cb ()
    {
207 208 209 210
        var date = new DateTime.now_local ();
        var entry = new HistoryEntry (date, game.columns, game.rows, game.color_num, game.score);
        history.add (entry);
        history.save ();
211
        game_in_progress = false;
Sophia Yu's avatar
Sophia Yu committed
212 213 214 215 216 217 218
    }

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

        /* Record the score if the game isn't over. */
219
        if (game != null && !game.has_completed() && game.score > 0)
220
            complete_cb ();
Sophia Yu's avatar
Sophia Yu committed
221 222 223 224
    }

    protected override void activate ()
    {
225
        window.present ();
Sophia Yu's avatar
Sophia Yu committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239
    }

    public void preferences_cb ()
    {
        /* Show existing dialog */
        if (preferences_dialog != null)
        {
            preferences_dialog.present ();
            return;
        }

        var preferences_builder = new Gtk.Builder ();
        try
        {
240
            preferences_builder.add_from_file (Path.build_filename (DATADIR, "preferences.ui", null));
Sophia Yu's avatar
Sophia Yu committed
241 242 243 244 245 246 247
        }
        catch (Error e)
        {
            warning ("Could not load preferences UI: %s", e.message);
        }

        preferences_dialog = (Gtk.Dialog) preferences_builder.get_object ("preferences");
248
        preferences_dialog.transient_for = window;
William Jon McCann's avatar
William Jon McCann committed
249
        preferences_dialog.modal = true;
Sophia Yu's avatar
Sophia Yu committed
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

        /* Theme */
        var theme_combo = preferences_builder.get_object ("theme-selector") as Gtk.ComboBox;
        var model = (Gtk.ListStore) theme_combo.model;
        Gtk.TreeIter iter;
        model.append (out iter);
        model.set (iter, 0, _("Colors"), 1, "colors", -1);
        if (settings.get_string ("theme") == "colors")
            theme_combo.set_active_iter (iter);
        model.append (out iter);
        model.set (iter, 0, _("Shapes and Colors"), 1, "shapesandcolors", -1);
        if (settings.get_string ("theme") == "shapesandcolors")
            theme_combo.set_active_iter (iter);

        /* Board size */
        var size_combo = preferences_builder.get_object ("size-selector") as Gtk.ComboBox;
        model = (Gtk.ListStore) size_combo.model;
        for (int i = 0; i < sizes.length; i++)
        {
            model.append (out iter);
            model.set (iter, 0, sizes[i].name, 1, sizes[i].id, -1);
            if (settings.get_string ("size") == sizes[i].id)
                size_combo.set_active_iter (iter);
        }

        /* Number of colors */
        ((Gtk.SpinButton) preferences_builder.get_object ("colors-spinner")).value = settings.get_int ("colors");

        /* Zealous moves */
        ((Gtk.CheckButton) preferences_builder.get_object ("zealous-checkbox")).active = settings.get_boolean ("zealous");

        preferences_builder.connect_signals (this);
        preferences_dialog.response.connect (preferences_response_cb);
        preferences_dialog.present ();
    }

    [CCode (cname = "G_MODULE_EXPORT select_theme", instance_pos = -1)]
    public void select_theme (Gtk.ComboBox theme_combo)
    {
        Gtk.TreeIter iter;
        if (!theme_combo.get_active_iter (out iter))
            return;
        string new_theme;
        theme_combo.model.get (iter, 1, out new_theme, -1);

        if (new_theme == settings.get_string ("theme"))
            return;

        settings.set_string ("theme", new_theme);

        view.theme_name = new_theme;
    }

    [CCode (cname = "G_MODULE_EXPORT set_zealous_animation", instance_pos = -1)]
    public void set_zealous_animation (Gtk.CheckButton button)
    {
        settings.set_boolean ("zealous", button.active);
307
        view.is_zealous = settings.get_boolean ("zealous");
Sophia Yu's avatar
Sophia Yu committed
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
    }

    [CCode (cname = "G_MODULE_EXPORT update_size", instance_pos = -1)]
    public void update_size (Gtk.ComboBox size_combo)
    {
        Gtk.TreeIter iter;
        if (!size_combo.get_active_iter (out iter))
            return;
        string new_size;
        size_combo.model.get (iter, 1, out new_size, -1);

        if (new_size == settings.get_string ("size"))
            return;

        settings.set_string ("size", new_size);
        new_game ();
    }

    [CCode (cname = "G_MODULE_EXPORT update_colors", instance_pos = -1)]
    public void update_colors (Gtk.SpinButton button)
    {
        int new_colors = (int) button.get_value();

        if (new_colors == settings.get_int ("colors"))
            return;

        settings.set_int ("colors", new_colors);
        new_game ();
    }

    private void preferences_response_cb ()
    {
        preferences_dialog.destroy ();
        preferences_dialog = null;
    }

    public void show ()
    {
346
        window.show ();
Sophia Yu's avatar
Sophia Yu committed
347 348 349 350
    }

    private void new_game_cb ()
    {
351 352 353 354
        if (game_in_progress)
            show_new_game_confirmation_dialog ();
        else
            new_game ();
Sophia Yu's avatar
Sophia Yu committed
355 356 357 358
    }

    private void scores_cb ()
    {
359 360 361 362 363 364
        var dialog = new ScoreDialog (history);
        dialog.modal = true;
        dialog.transient_for = window;

        dialog.run ();
        dialog.destroy ();
Sophia Yu's avatar
Sophia Yu committed
365 366 367 368
    }

    private void quit_cb ()
    {
369
        window.destroy ();
Sophia Yu's avatar
Sophia Yu committed
370 371 372 373 374 375
    }

    private void help_cb ()
    {
        try
        {
376
            Gtk.show_uri (window.get_screen (), "help:swell-foop", Gtk.get_current_event_time ());
Sophia Yu's avatar
Sophia Yu committed
377 378 379 380 381 382 383 384 385 386 387 388 389
        }
        catch (Error e)
        {
            warning ("Failed to show help: %s", e.message);
        }
    }

    private void about_cb ()
    {
        string[] authors = { "Tim Horton", "Sophia Yu", null };
        string[] artists = { "Tim Horton", null };
        string[] documenters = { null };

390
        Gtk.show_about_dialog (window,
Sophia Yu's avatar
Sophia Yu committed
391 392 393
                               "program-name", _("Swell Foop"),
                               "version", VERSION,
                               "comments",
394
                               _("I want to play that game!\nYou know, they all light-up and you click on them and they vanish!\n\nSwell Foop is a part of GNOME Games."),
Sophia Yu's avatar
Sophia Yu committed
395
                               "copyright", _("Copyright \xc2\xa9 2009 Tim Horton"),
396
                               "license-type", Gtk.License.GPL_2_0,
Sophia Yu's avatar
Sophia Yu committed
397 398 399 400
                               "authors", authors,
                               "artists", artists,
                               "documenters", documenters,
                               "translator-credits", _("translator-credits"),
401
                               "logo-icon-name", "swell-foop",
402
                               "website", "https://wiki.gnome.org/Apps/Swell%20Foop",
Sophia Yu's avatar
Sophia Yu committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                               null);
    }

    public void new_game ()
    {
        game = new Game (get_size ().rows,
                         get_size ().columns,
                         settings.get_int ("colors"));
        game.update_score.connect (update_score_cb);
        game.complete.connect (complete_cb);
        view.theme_name = settings.get_string ("theme");
        view.game = game;
        view.is_zealous = settings.get_boolean ("zealous");

        stage.set_size (view.width, view.height);
        clutter_embed.set_size_request ( (int) stage.width, (int) stage.height);

420 421
        game_in_progress = true;

Sophia Yu's avatar
Sophia Yu committed
422 423 424
        update_score_cb (0);
    }

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
    private void show_new_game_confirmation_dialog ()
    {
        var dialog = new Gtk.MessageDialog.with_markup (window,
                                                        Gtk.DialogFlags.MODAL,
                                                        Gtk.MessageType.QUESTION,
                                                        Gtk.ButtonsType.NONE,
                                                        "<span weight=\"bold\" size=\"larger\">%s</span>",
                                                        _("Abandon this game to start a new one?"));
        dialog.add_button (_("_Cancel"), Gtk.ResponseType.CANCEL);
        dialog.add_button (_("_New Game"), Gtk.ResponseType.YES);

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

        if (result == Gtk.ResponseType.YES)
            new_game ();
    }

Sophia Yu's avatar
Sophia Yu committed
443 444 445 446 447 448 449
    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);

450 451 452 453 454 455
        if (GtkClutter.init (ref args) != Clutter.InitError.SUCCESS)
        {
            warning ("Failed to initialise Clutter");
            return Posix.EXIT_FAILURE;
        }

Jiro Matsuzawa's avatar
Jiro Matsuzawa committed
456
        var context = new OptionContext (null);
457
        context.set_translation_domain (GETTEXT_PACKAGE);
Sophia Yu's avatar
Sophia Yu committed
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

        context.add_group (Gtk.get_option_group (true));
        context.add_group (Clutter.get_option_group_without_init ());

        try
        {
            context.parse (ref args);
        }
        catch (Error e)
        {
            stderr.printf ("%s\n", e.message);
            return Posix.EXIT_FAILURE;
        }

        Environment.set_application_name (_("Swell Foop"));

        Gtk.Window.set_default_icon_name ("swellfoop");

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

/* An array will store multiply game size options. */
public struct Size
{
    public string id;
    public string name;
    public int    columns;
    public int    rows;
}