geary-controller.vala 127 KB
Newer Older
1 2
/*
 * Copyright 2016 Software Freedom Conservancy Inc.
3
 * Copyright 2016-2018 Michael Gratton <mike@vee.net>
4 5
 *
 * This software is licensed under the GNU Lesser General Public License
6
 * (version 2.1 or later). See the COPYING file in this distribution.
7 8
 */

9

10 11 12
/**
 * Primary controller for a Geary application instance.
 */
13
public class GearyController : Geary.BaseObject {
14

15
    // Named actions.
16 17 18 19 20 21 22 23 24 25
    public const string ACTION_NEW_MESSAGE = "new-message";
    public const string ACTION_REPLY_TO_MESSAGE = "reply-to-message";
    public const string ACTION_REPLY_ALL_MESSAGE = "reply-all-message";
    public const string ACTION_FORWARD_MESSAGE = "forward-message";
    public const string ACTION_ARCHIVE_CONVERSATION = "archive-conv";
    public const string ACTION_TRASH_CONVERSATION = "trash-conv";
    public const string ACTION_DELETE_CONVERSATION = "delete-conv";
    public const string ACTION_EMPTY_SPAM = "empty-spam";
    public const string ACTION_EMPTY_TRASH = "empty-trash";
    public const string ACTION_UNDO = "undo";
26
    public const string ACTION_REDO = "redo";
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    public const string ACTION_FIND_IN_CONVERSATION = "conv-find";
    public const string ACTION_ZOOM = "zoom";
    public const string ACTION_SHOW_MARK_MENU = "mark-message-menu";
    public const string ACTION_MARK_AS_READ = "mark-message-read";
    public const string ACTION_MARK_AS_UNREAD = "mark-message-unread";
    public const string ACTION_MARK_AS_STARRED = "mark-message-starred";
    public const string ACTION_MARK_AS_UNSTARRED = "mark-message-unstarred";
    public const string ACTION_MARK_AS_SPAM = "mark-message-spam";
    public const string ACTION_MARK_AS_NOT_SPAM = "mark-message-not-spam";
    public const string ACTION_COPY_MENU = "show-copy-menu";
    public const string ACTION_MOVE_MENU = "show-move-menu";
    public const string ACTION_SEARCH = "search-conv";
    public const string ACTION_CONVERSATION_LIST = "focus-conv-list";
    public const string ACTION_TOGGLE_SEARCH = "toggle-search";
    public const string ACTION_TOGGLE_FIND = "toggle-find";

    // Properties
44
    public const string PROP_CURRENT_CONVERSATION ="current-conversations";
45 46
    public const string PROP_SELECTED_CONVERSATIONS ="selected-conversations";

47
    public const int MIN_CONVERSATION_COUNT = 50;
48

49
    private const int SELECT_FOLDER_TIMEOUT_USEC = 100 * 1000;
50

51
    private const string PROP_ATTEMPT_OPEN_ACCOUNT = "attempt-open-account";
52

53
    private const uint MAX_AUTH_ATTEMPTS = 3;
54

55 56 57 58 59 60 61 62 63 64
    private static string untitled_file_name;


    static construct {
        // Translators: File name used in save chooser when saving
        // attachments that do not otherwise have a name.
        GearyController.untitled_file_name = _("Untitled");
    }


65 66 67 68 69
    internal class AccountContext : Geary.BaseObject {

        public Geary.Account account { get; private set; }
        public Geary.Folder? inbox = null;
        public Geary.App.EmailStore store { get; private set; }
70 71 72 73 74

        public bool authentication_failed = false;
        public bool authentication_prompting = false;
        public uint authentication_attempts = 0;

75 76 77
        public bool tls_validation_failed = false;
        public bool tls_validation_prompting = false;

78 79 80 81 82 83 84
        public Cancellable cancellable { get; private set; default = new Cancellable(); }

        public AccountContext(Geary.Account account) {
            this.account = account;
            this.store = new Geary.App.EmailStore(account);
        }

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        public Geary.Account.Status get_effective_status() {
            Geary.Account.Status current = this.account.current_status;
            Geary.Account.Status effective = 0;
            if (current.is_online()) {
                effective |= ONLINE;
            }
            if (current.has_service_problem()) {
                // Only retain this flag if the problem isn't auth or
                // cert related, that is handled elsewhere.
                Geary.ClientService.Status incoming =
                    account.incoming.current_status;
                Geary.ClientService.Status outgoing =
                    account.outgoing.current_status;
                if (incoming != AUTHENTICATION_FAILED &&
                    incoming != TLS_VALIDATION_FAILED &&
                    outgoing != AUTHENTICATION_FAILED &&
                    outgoing != TLS_VALIDATION_FAILED) {
                    effective |= SERVICE_PROBLEM;
                }
            }
            return effective;
        }

108 109 110
    }


111 112
    public weak GearyApplication application { get; private set; } // circular ref

113
    public Accounts.Manager? account_manager { get; private set; default = null; }
114

115 116 117 118 119
    /** Application-wide {@link Application.CertificateManager} instance. */
    public Application.CertificateManager? certificate_manager {
        get; private set; default = null;
    }

120 121
    public MainWindow? main_window { get; private set; default = null; }

122
    public Geary.App.ConversationMonitor? current_conversations { get; private set; default = null; }
123

124
    public AutostartManager? autostart_manager { get; private set; default = null; }
125

126 127 128
    public Application.AvatarStore? avatar_store {
        get; private set; default = null;
    }
129

130
    private Geary.Account? current_account = null;
131 132 133
    private Gee.Map<Geary.AccountInformation,AccountContext> accounts =
        new Gee.HashMap<Geary.AccountInformation,AccountContext>();

134 135 136 137
    // Created when controller is opened, cancelled and nulled out
    // when closed.
    private GLib.Cancellable? open_cancellable = null;

138
    private Geary.Folder? current_folder = null;
139
    private Cancellable cancellable_folder = new Cancellable();
140
    private Cancellable cancellable_search = new Cancellable();
141
    private Cancellable cancellable_open_account = new Cancellable();
142
    private Cancellable cancellable_context_dependent_buttons = new Cancellable();
143
    private ContactListStoreCache contact_list_store_cache = new ContactListStoreCache();
144 145
    private Gee.Set<Geary.App.Conversation> selected_conversations = new Gee.HashSet<Geary.App.Conversation>();
    private Geary.App.Conversation? last_deleted_conversation = null;
146
    private Gee.LinkedList<ComposerWidget> composer_widgets = new Gee.LinkedList<ComposerWidget>();
147 148 149
    private NewMessagesMonitor? new_messages_monitor = null;
    private NewMessagesIndicator? new_messages_indicator = null;
    private UnityLauncher? unity_launcher = null;
150
    private Libnotify? libnotify = null;
151
    private uint select_folder_timeout_id = 0;
152
    private int64 next_folder_select_allowed_usec = 0;
153
    private Geary.Nonblocking.Mutex select_folder_mutex = new Geary.Nonblocking.Mutex();
Eric Gregory's avatar
Eric Gregory committed
154
    private Geary.Folder? previous_non_search_folder = null;
155
    private UpgradeDialog upgrade_dialog;
156
    private Gee.List<string> pending_mailtos = new Gee.ArrayList<string>();
157 158

    private uint operation_count = 0;
159
    private Geary.Revokable? revokable = null;
160

161
    // List of windows we're waiting to close before Geary closes.
162
    private Gee.List<ComposerWidget> waiting_to_close = new Gee.ArrayList<ComposerWidget>();
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

    private const ActionEntry[] win_action_entries = {
        {ACTION_NEW_MESSAGE,           on_new_message                  },
        {ACTION_CONVERSATION_LIST,     on_conversation_list            },
        {ACTION_FIND_IN_CONVERSATION,  on_find_in_conversation_action  },
        {ACTION_SEARCH,                on_search_activated             },
        {ACTION_EMPTY_SPAM,            on_empty_spam                   },
        {ACTION_EMPTY_TRASH,           on_empty_trash                  },
        {ACTION_UNDO,                  on_revoke                       },
        // Message actions
        {ACTION_REPLY_TO_MESSAGE,      on_reply_to_message_action   },
        {ACTION_REPLY_ALL_MESSAGE,     on_reply_all_message_action  },
        {ACTION_FORWARD_MESSAGE,       on_forward_message_action    },
        {ACTION_ARCHIVE_CONVERSATION,  on_archive_conversation      },
        {ACTION_TRASH_CONVERSATION,    on_trash_conversation        },
        {ACTION_DELETE_CONVERSATION,   on_delete_conversation       },
        {ACTION_COPY_MENU,             on_show_copy_menu            },
        {ACTION_MOVE_MENU,             on_show_move_menu            },
        // Message marking actions
        {ACTION_SHOW_MARK_MENU,     on_show_mark_menu           },
        {ACTION_MARK_AS_READ,       on_mark_as_read             },
        {ACTION_MARK_AS_UNREAD,     on_mark_as_unread           },
        {ACTION_MARK_AS_STARRED,    on_mark_as_starred          },
        {ACTION_MARK_AS_UNSTARRED,  on_mark_as_unstarred        },
        {ACTION_MARK_AS_SPAM,       on_mark_as_spam_toggle      },
        {ACTION_MARK_AS_NOT_SPAM,   on_mark_as_spam_toggle      },
        // Message viewer
        {ACTION_ZOOM,  on_zoom,  "s"  },
    };

193 194 195 196 197 198 199 200 201 202
    /**
     * Fired when the currently selected account has changed.
     */
    public signal void account_selected(Geary.Account? account);
    
    /**
     * Fired when the currently selected folder has changed.
     */
    public signal void folder_selected(Geary.Folder? folder);
    
203 204 205 206 207
    /**
     * Fired when the number of conversations changes.
     */
    public signal void conversation_count_changed(int count);
    
208 209 210 211 212
    /**
     * Fired when the search text is changed according to the controller.  This accounts
     * for a brief typmatic delay.
     */
    public signal void search_text_changed(string keywords);
213 214 215 216 217 218

    /**
     * Constructs a new instance of the controller.
     */
    public GearyController(GearyApplication application) {
        this.application = application;
219
    }
220

221 222 223
    ~GearyController() {
        assert(current_account == null);
    }
224

225 226 227
    /**
     * Starts the controller and brings up Geary.
     */
228
    public async void open_async(GLib.Cancellable? cancellable) {
229 230
        Geary.Engine engine = this.application.engine;

231 232 233
        // This initializes the IconFactory, important to do before
        // the actions are created (as they refer to some of Geary's
        // custom icons)
234
        IconFactory.instance.init();
235

236 237
        apply_app_menu_fix();

238 239
        this.open_cancellable = new GLib.Cancellable();

240
        // Listen for attempts to close the application.
241
        this.application.exiting.connect(on_application_exiting);
242

243 244 245
        // Create DB upgrade dialog.
        upgrade_dialog = new UpgradeDialog();
        upgrade_dialog.notify[UpgradeDialog.PROP_VISIBLE_NAME].connect(display_main_window_if_ready);
246

247 248
        // Initialise WebKit and WebViews
        ClientWebView.init_web_context(
249
            this.application.config,
250
            this.application.get_web_extensions_dir(),
251
            this.application.get_user_cache_directory().get_child("web-resources"),
252 253
            Args.log_debug
        );
254
        try {
255 256 257 258 259
            ClientWebView.load_scripts();
            ComposerWebView.load_resources();
            ConversationWebView.load_resources(
                this.application.get_user_config_directory()
            );
260
        } catch (Error err) {
261
            error("Error loading web resources: %s", err.message);
262 263
        }

264 265 266
        this.avatar_store = new Application.AvatarStore(
            this.application.config,
            this.application.get_user_cache_directory()
267 268
        );

269
        // Create the main window (must be done after creating actions.)
270
        main_window = new MainWindow(this.application);
271
        main_window.retry_service_problem.connect(on_retry_service_problem);
272
        main_window.on_shift_key.connect(on_shift_key);
273
        main_window.notify["has-toplevel-focus"].connect(on_has_toplevel_focus);
274 275 276

        setup_actions();

277
        enable_message_buttons(false);
278

279 280
        engine.account_available.connect(on_account_available);

281
        // Connect to various UI signals.
282
        main_window.conversation_list_view.conversations_selected.connect(on_conversations_selected);
Eric Gregory's avatar
Eric Gregory committed
283
        main_window.conversation_list_view.conversation_activated.connect(on_conversation_activated);
284
        main_window.conversation_list_view.load_more.connect(on_load_more);
285
        main_window.conversation_list_view.mark_conversations.connect(on_mark_conversations);
286
        main_window.conversation_list_view.visible_conversations_changed.connect(on_visible_conversations_changed);
287
        main_window.folder_list.folder_selected.connect(on_folder_selected);
288 289 290 291
        main_window.folder_list.copy_conversation.connect(on_copy_conversation);
        main_window.folder_list.move_conversation.connect(on_move_conversation);
        main_window.main_toolbar.copy_folder_menu.folder_selected.connect(on_copy_conversation);
        main_window.main_toolbar.move_folder_menu.folder_selected.connect(on_move_conversation);
292
        main_window.search_bar.search_text_changed.connect((text) => { do_search(text); });
293 294 295
        main_window.conversation_viewer.conversation_added.connect(
            on_conversation_view_added
        );
296
        new_messages_monitor = new NewMessagesMonitor(should_notify_new_messages);
297
        main_window.folder_list.set_new_messages_monitor(new_messages_monitor);
298

299 300 301 302 303
        // New messages indicator (Ubuntuism)
        new_messages_indicator = NewMessagesIndicator.create(new_messages_monitor);
        new_messages_indicator.application_activated.connect(on_indicator_activated_application);
        new_messages_indicator.composer_activated.connect(on_indicator_activated_composer);
        new_messages_indicator.inbox_activated.connect(on_indicator_activated_inbox);
304

305
        unity_launcher = new UnityLauncher(new_messages_monitor);
306 307 308 309 310

        this.libnotify = new Libnotify(
            this.new_messages_monitor, this.avatar_store
        );
        this.libnotify.invoked.connect(on_libnotify_invoked);
311 312 313

        this.main_window.conversation_list_view.grab_focus();

314
        // instantiate here to ensure that Config is initialized and ready
315 316
        this.autostart_manager = new AutostartManager(this.application);

317 318
        // initialize revokable
        save_revokable(null, null);
319 320 321

        // Migrate configuration if necessary.
        try {
322 323
            Migrate.xdg_config_dir(this.application.get_user_data_directory(),
                this.application.get_user_config_directory());
324 325 326 327
        } catch (Error e) {
            error("Error migrating configuration directories: %s", e.message);
        }

328 329
        // Hook up cert, accounts and credentials machinery

330 331 332
        this.certificate_manager = yield new Application.CertificateManager(
            this.application.get_user_data_directory().get_child("pinned-certs"),
            cancellable
333
        );
334

335 336 337 338 339 340 341
        SecretMediator? libsecret = null;
        try {
            libsecret = yield new SecretMediator(this.application, cancellable);
        } catch (GLib.Error err) {
            error("Error opening libsecret: %s", err.message);
        }

342
        this.account_manager = new Accounts.Manager(
343
            libsecret,
344 345 346
            this.application.get_user_config_directory(),
            this.application.get_user_data_directory()
        );
347 348
        this.account_manager.account_added.connect(
            on_account_added
349
        );
350 351
        this.account_manager.account_status_changed.connect(
            on_account_status_changed
352
        );
353 354 355
        this.account_manager.account_removed.connect(
            on_account_removed
        );
356 357 358
        this.account_manager.report_problem.connect(
            on_report_problem
        );
359 360 361 362 363 364 365

        try {
            yield this.account_manager.connect_goa(cancellable);
        } catch (GLib.Error err) {
            warning("Error opening GOA: %s", err.message);
        }

366
        // Start the engine and load our accounts
367 368 369 370 371
        try {
            yield engine.open_async(
                this.application.get_resource_directory(), cancellable
            );
            yield this.account_manager.load_accounts(cancellable);
372
            if (engine.get_accounts().size == 0) {
373 374 375 376 377 378
                this.application.show_accounts();
                if (engine.get_accounts().size == 0) {
                    // User cancelled without creating an account, so
                    // nothing else to do but exit.
                    this.application.quit();
                }
379 380
            }
        } catch (Error e) {
381
            warning("Error opening Geary.Engine instance: %s", e.message);
382
        }
383 384 385 386

        // Expunge any deleted accounts in the background, so we're
        // not blocking the app continuing to open.
        this.expunge_accounts.begin();
387
    }
388

389
    /**
390 391
     * At the moment, this is non-reversible, i.e. once closed a GearyController cannot be
     * re-opened.
392
     */
393
    public async void close_async() {
394 395 396 397 398
        // Cancel internal processes early so they don't block
        // shutdown
        this.open_cancellable.cancel();
        this.open_cancellable = null;

399
        Geary.Engine.instance.account_available.disconnect(on_account_available);
400

401 402 403 404
        // Release folder and conversations in the main window
        on_conversations_selected(new Gee.HashSet<Geary.App.Conversation>());
        on_folder_selected(null);

405
        // Disconnect from various UI signals.
406 407 408 409 410 411 412 413 414 415
        main_window.conversation_list_view.conversations_selected.disconnect(on_conversations_selected);
        main_window.conversation_list_view.conversation_activated.disconnect(on_conversation_activated);
        main_window.conversation_list_view.load_more.disconnect(on_load_more);
        main_window.conversation_list_view.mark_conversations.disconnect(on_mark_conversations);
        main_window.conversation_list_view.visible_conversations_changed.disconnect(on_visible_conversations_changed);
        main_window.folder_list.folder_selected.disconnect(on_folder_selected);
        main_window.folder_list.copy_conversation.disconnect(on_copy_conversation);
        main_window.folder_list.move_conversation.disconnect(on_move_conversation);
        main_window.main_toolbar.copy_folder_menu.folder_selected.disconnect(on_copy_conversation);
        main_window.main_toolbar.move_folder_menu.folder_selected.disconnect(on_move_conversation);
416 417 418
        main_window.conversation_viewer.conversation_added.disconnect(
            on_conversation_view_added
        );
419

420 421
        // hide window while shutting down, as this can take a few seconds under certain conditions
        main_window.hide();
422 423 424 425 426 427 428 429

        // Release monitoring early so held resources can be freed up
        this.libnotify = null;
        this.new_messages_indicator = null;
        this.unity_launcher = null;
        this.new_messages_monitor.clear_folders();
        this.new_messages_monitor = null;

430 431
        // drop the Revokable, which will commit it if necessary
        save_revokable(null, null);
432

433
        this.cancellable_open_account.cancel();
434

435 436 437
        // Close the ConversationMonitor
        if (current_conversations != null) {
            debug("Stopping conversation monitor for %s...",
438
                  this.current_conversations.base_folder.to_string());
439
            try {
440
                yield this.current_conversations.stop_monitoring_async(null);
441
            } catch (Error err) {
442 443
                debug(
                    "Error closing conversation monitor %s at shutdown: %s",
444
                    this.current_conversations.base_folder.to_string(),
445 446
                    err.message
                );
447
            }
448 449

            this.current_conversations = null;
450
        }
451

452 453 454 455 456 457
        // Create an array of known accounts so the loops below do not
        // explode if accounts are removed while iterating.
        AccountContext[] accounts = this.accounts.values.to_array();

        // Close all inboxes. Launch these in parallel first so we're
        // not wasting time waiting for each one to close. The account
458
        // will wait around for them to actually close.
459 460 461
        foreach (AccountContext context in accounts) {
            Geary.Folder? inbox = context.inbox;
            if (inbox != null) {
462
                debug("Closing inbox: %s...", inbox.to_string());
463 464 465 466 467 468 469 470 471 472 473
                inbox.close_async.begin(null, (obj, ret) => {
                        try {
                            inbox.close_async.end(ret);
                        } catch (Error err) {
                            debug(
                                "Error closing Inbox %s at shutdown: %s",
                                inbox.to_string(), err.message
                            );
                        }
                    });
                context.inbox = null;
474 475
            }
        }
476

477 478 479
        // Close all Accounts. Again, this is done in parallel to
        // minimise time taken to close, but here use a barrier to
        // wait for all to actually finish closing.
480 481
        Geary.Nonblocking.CountingSemaphore close_barrier =
            new Geary.Nonblocking.CountingSemaphore(null);
482
        foreach (AccountContext context in accounts) {
483
            close_barrier.acquire();
484 485 486 487 488 489 490
            this.close_account.begin(
                context.account.information,
                (obj, ret) => {
                    this.close_account.end(ret);
                    close_barrier.blind_notify();
                }
            );
491 492 493 494 495 496
        }
        try {
            yield close_barrier.wait_async();
        } catch (Error err) {
            debug("Error waiting at shutdown barrier: %s", err.message);
        }
497

498 499
        // Turn off the lights and lock the door behind you
        try {
500
            debug("Closing Engine...");
501
            yield Geary.Engine.instance.close_async(null);
502
            debug("Closed Engine");
503 504 505
        } catch (Error err) {
            message("Error closing Geary Engine instance: %s", err.message);
        }
506

507 508
        this.account_manager.account_added.disconnect(
            on_account_added
509
        );
510 511
        this.account_manager.account_status_changed.disconnect(
            on_account_status_changed
512
        );
513 514 515
        this.account_manager.account_removed.disconnect(
            on_account_removed
        );
516 517
        this.account_manager = null;

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        this.application.remove_window(this.main_window);
        this.main_window.destroy();
        this.main_window = null;

        this.upgrade_dialog = null;

        this.current_account = null;
        this.current_folder = null;

        this.previous_non_search_folder = null;

        this.selected_conversations = new Gee.HashSet<Geary.App.Conversation>();
        this.last_deleted_conversation = null;

        this.pending_mailtos.clear();
        this.composer_widgets.clear();
        this.waiting_to_close.clear();

        this.autostart_manager = null;

538 539 540
        this.avatar_store.close();
        this.avatar_store = null;

541 542

        debug("Closed GearyController");
543
    }
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

    /**
     * Opens a new, blank composer.
     */
    public void compose() {
        create_compose_widget(ComposerWidget.ComposeType.NEW_MESSAGE);
    }

    /**
     * Opens or queues a new composer addressed to a specific email address.
     */
    public void compose_mailto(string mailto) {
        if (current_account == null) {
            // Schedule the send for after we have an account open.
            pending_mailtos.add(mailto);
        } else {
            create_compose_widget(ComposerWidget.ComposeType.NEW_MESSAGE, null, null, mailto);
        }
    }

564 565
    /** Expunges removed accounts while the controller remains open. */
    internal async void expunge_accounts() {
566
        try {
567 568
            yield this.account_manager.expunge_accounts(this.open_cancellable);
        } catch (GLib.Error err) {
569 570 571
            report_problem(
                new Geary.ProblemReport(Geary.ProblemType.GENERIC_ERROR, err)
            );
572
        }
573 574
    }

575 576 577 578 579 580 581 582 583
    // Fix for clients having both:
    //   * disabled Gtk/ShellShowsAppMenu setting
    //   * no 'menu' setting in Gtk/DecorationLayout
    // See https://bugzilla.gnome.org/show_bug.cgi?id=770617
    private void apply_app_menu_fix() {
        Gtk.Settings? settings = Gtk.Settings.get_default();

        if (settings == null) {
            warning("Couldn't fetch Gtk default settings");
584
            return;
585 586
        }

587
        string decoration_layout = settings.gtk_decoration_layout ?? "";
588 589 590 591 592 593 594 595 596
        if (!decoration_layout.contains("menu")) {
            string prefix = "menu:";
            if (decoration_layout.contains(":")) {
                prefix = (decoration_layout.has_prefix(":")) ? "menu" : "menu,";
            }
            settings.gtk_decoration_layout = prefix + settings.gtk_decoration_layout;
        }
    }

597
    private void setup_actions() {
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        this.main_window.add_action_entries(win_action_entries, this);

        add_window_accelerators(ACTION_MARK_AS_READ, { "<Ctrl>I", "<Shift>I" });
        add_window_accelerators(ACTION_MARK_AS_UNREAD, { "<Ctrl>U", "<Shift>U" });
        add_window_accelerators(ACTION_MARK_AS_STARRED, { "S" });
        add_window_accelerators(ACTION_MARK_AS_UNSTARRED, { "D" });
        add_window_accelerators(ACTION_MARK_AS_SPAM, { "<Ctrl>J", "exclam" }); // Exclamation mark (!)
        add_window_accelerators(ACTION_MARK_AS_NOT_SPAM, { "<Ctrl>J", "exclam" });
        add_window_accelerators(ACTION_COPY_MENU, { "L" });
        add_window_accelerators(ACTION_MOVE_MENU, { "M" });
        add_window_accelerators(ACTION_NEW_MESSAGE, { "<Ctrl>N", "N" });
        add_window_accelerators(ACTION_REPLY_TO_MESSAGE, { "<Ctrl>R", "R" });
        add_window_accelerators(ACTION_REPLY_ALL_MESSAGE, { "<Ctrl><Shift>R", "<Shift>R" });
        add_window_accelerators(ACTION_FORWARD_MESSAGE, { "<Ctrl>L", "F" });
        add_window_accelerators(ACTION_FIND_IN_CONVERSATION, { "<Ctrl>F", "slash" });
        add_window_accelerators(ACTION_ARCHIVE_CONVERSATION, { "A" });
        add_window_accelerators(ACTION_TRASH_CONVERSATION, { "Delete", "BackSpace" });
        add_window_accelerators(ACTION_DELETE_CONVERSATION, { "<Shift>Delete", "<Shift>BackSpace" });
        add_window_accelerators(ACTION_UNDO, { "<Ctrl>Z" });
617
        add_window_accelerators(ACTION_REDO, { "<Ctrl><Shift>Z" });
618 619 620 621 622 623 624 625 626
        add_window_accelerators(ACTION_ZOOM+("('in')"), { "<Ctrl>equal", "equal" });
        add_window_accelerators(ACTION_ZOOM+("('out')"), { "<Ctrl>minus", "minus" });
        add_window_accelerators(ACTION_ZOOM+("('normal')"), { "<Ctrl>0", "0" });
        add_window_accelerators(ACTION_SEARCH, { "<Ctrl>S" });
        add_window_accelerators(ACTION_CONVERSATION_LIST, { "<Ctrl>B" });
    }

    private void add_window_accelerators(string action, string[] accelerators, Variant? param = null) {
        this.application.set_accels_for_action("win."+action, accelerators);
627
    }
628

629
    private void open_account(Geary.Account account) {
630 631 632
        account.information.authentication_failure.connect(
            on_authentication_failure
        );
633
        account.information.untrusted_host.connect(on_untrusted_host);
634 635 636
        account.notify["current-status"].connect(
            on_account_status_notify
        );
637
        account.report_problem.connect(on_report_problem);
638
        connect_account_async.begin(account, cancellable_open_account);
639

640 641
        ContactListStore list_store = this.contact_list_store_cache.create(account.get_contact_store());
        account.contacts_loaded.connect(list_store.set_sort_function);
642
    }
643

644 645
    private async void close_account(Geary.AccountInformation config) {
        AccountContext? context = this.accounts.get(config);
646
        if (context != null) {
647 648 649 650
            Geary.Account account = context.account;
            Geary.ContactStore contact_store = account.get_contact_store();
            ContactListStore list_store =
                this.contact_list_store_cache.get(contact_store);
651

652
            account.contacts_loaded.disconnect(list_store.set_sort_function);
653 654
            this.contact_list_store_cache.unset(contact_store);

655
            if (this.current_account == account) {
656 657 658 659 660 661 662 663
                this.current_account = null;

                previous_non_search_folder = null;
                main_window.search_bar.set_search_text(""); // Reset search.

                cancel_folder();
            }

664 665 666
            // Stop updating status and showing errors when closing
            // the account - the user doesn't care any more
            account.report_problem.disconnect(on_report_problem);
667 668 669
            account.information.authentication_failure.disconnect(
                on_authentication_failure
            );
670
            account.information.untrusted_host.disconnect(on_untrusted_host);
671 672 673
            account.notify["current-status"].disconnect(
                on_account_status_notify
            );
674

675
            yield disconnect_account_async(context);
676 677
        }
    }
678

679 680
    private void report_problem(Geary.ProblemReport report) {
        debug("Problem reported: %s", report.to_string());
681

682 683
        if (report.error == null ||
            !(report.error.thrown is IOError.CANCELLED)) {
684 685 686 687 688 689 690
            MainWindowInfoBar info_bar = new MainWindowInfoBar.for_problem(report);
            info_bar.retry.connect(on_retry_problem);
            this.main_window.show_infobar(info_bar);
        }
    }

    private void update_account_status() {
691 692 693 694
        // Start off assuming all accounts are online and error free
        // (i.e. no status issues to indicate) and proceed until
        // proven incorrect.
        Geary.Account.Status effective_status = ONLINE;
695
        bool has_auth_error = false;
696
        bool has_cert_error = false;
697
        Geary.Account? service_problem_source = null;
698
        foreach (AccountContext context in this.accounts.values) {
699 700 701 702 703 704 705 706 707
            Geary.Account.Status status = context.get_effective_status();
            if (!status.is_online()) {
                effective_status &= ~Geary.Account.Status.ONLINE;
            }
            if (status.has_service_problem()) {
                effective_status |= SERVICE_PROBLEM;
                if (service_problem_source == null) {
                    service_problem_source = context.account;
                }
708 709
            }
            has_auth_error |= context.authentication_failed;
710
            has_cert_error |= context.tls_validation_failed;
711 712 713 714 715
        }

        foreach (Gtk.Window window in this.application.get_windows()) {
            MainWindow? main = window as MainWindow;
            if (main != null) {
716
                main.update_account_status(
717 718 719 720
                    effective_status,
                    has_auth_error,
                    has_cert_error,
                    service_problem_source
721
                );
722
            }
723 724
        }
    }
725

726 727
    private bool is_currently_prompting() {
        return this.accounts.values.fold<bool>(
728 729 730 731 732
            (ctx, seed) => (
                ctx.authentication_prompting |
                ctx.tls_validation_prompting |
                seed
            ),
733 734 735 736 737 738 739 740 741 742 743 744 745
            false
        );
    }

    private async void prompt_for_password(AccountContext context,
                                           Geary.ServiceInformation service) {
        Geary.AccountInformation account = context.account.information;
        bool is_incoming = (service == account.incoming);
        Geary.Credentials credentials = is_incoming
            ? account.incoming.credentials
            : account.get_outgoing_credentials();

        bool handled = true;
746
        if (context.authentication_attempts > MAX_AUTH_ATTEMPTS ||
747
            credentials == null) {
748 749 750 751
            // We have run out of authentication attempts or have
            // been asked for creds but don't even have a login. So
            // just bail out immediately and flag the account as
            // needing attention.
752
            handled = false;
753 754 755
        } else if (this.account_manager.is_goa_account(account)) {
            context.authentication_prompting = true;
            try {
756 757
                yield account.load_incoming_credentials(context.cancellable);
                yield account.load_outgoing_credentials(context.cancellable);
758 759 760 761 762 763 764 765 766 767 768 769 770
            } catch (GLib.Error err) {
                // Bail out right away, but probably should be opening
                // the GOA control panel.
                handled = false;
                report_problem(
                    new Geary.AccountProblemReport(
                        Geary.ProblemType.GENERIC_ERROR,
                        account,
                        err
                    )
                );
            }
            context.authentication_prompting = false;
771 772 773 774 775 776 777
        } else {
            context.authentication_prompting = true;
            this.application.present();
            PasswordDialog password_dialog = new PasswordDialog(
                this.application.get_active_window(),
                account,
                service
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
            if (password_dialog.run()) {
                service.credentials = service.credentials.copy_with_token(
                    password_dialog.password
                );
                service.remember_password = password_dialog.remember_password;

                // The update the credentials for the service that the
                // credentials actually came from
                Geary.ServiceInformation creds_service =
                    credentials == account.incoming.credentials
                    ? account.incoming
                    : account.outgoing;
                SecretMediator libsecret = (SecretMediator) account.mediator;
                try {
                    yield libsecret.update_token(
                        account, creds_service, context.cancellable
                    );
                    // Update the actual service in the engine though
                    yield this.application.engine.update_account_service(
                        account, service, context.cancellable
                    );
                } catch (GLib.IOError.CANCELLED err) {
                    // all good
                } catch (GLib.Error err) {
                    report_problem(
                        new Geary.ServiceProblemReport(
                            Geary.ProblemType.GENERIC_ERROR,
                            account,
                            service,
                            err
                        )
                    );
                }
                context.authentication_attempts++;
            } else {
                // User cancelled, bail out unconditionally
                handled = false;
            }
            context.authentication_prompting = false;
        }

        if (!handled) {
            context.authentication_attempts = 0;
            context.authentication_failed = true;
            update_account_status();
        }
    }

827 828 829 830 831 832 833 834 835
    private async void prompt_untrusted_host(AccountContext context,
                                             Geary.ServiceInformation service,
                                             Geary.Endpoint endpoint,
                                             GLib.TlsConnection cx) {
        if (Args.revoke_certs) {
            // XXX
        }

        context.tls_validation_prompting = true;
836 837 838 839 840 841
        try {
            yield this.certificate_manager.prompt_pin_certificate(
                this.main_window,
                context.account.information,
                service,
                endpoint,
842
                false,
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
                context.cancellable
            );
            context.tls_validation_failed = false;
        } catch (Application.CertificateManagerError.UNTRUSTED err) {
            // Don't report an error here, the user simply declined.
            context.tls_validation_failed = true;
        } catch (Application.CertificateManagerError err) {
            // Assume validation is now good, but report the error
            // since the cert may not have been saved
            context.tls_validation_failed = false;
            report_problem(
                new Geary.ServiceProblemReport(
                    Geary.ProblemType.UNTRUSTED,
                    context.account.information,
                    service,
                    err
                )
            );
        }
862 863 864 865 866

        context.tls_validation_prompting = false;
        update_account_status();
    }

Charles Lindsay's avatar
Charles Lindsay committed
867 868 869
    private void on_account_email_removed(Geary.Folder folder, Gee.Collection<Geary.EmailIdentifier> ids) {
        if (folder.special_folder_type == Geary.SpecialFolderType.OUTBOX) {
            main_window.status_bar.deactivate_message(StatusBar.Message.OUTBOX_SEND_FAILURE);
870
            main_window.status_bar.deactivate_message(StatusBar.Message.OUTBOX_SAVE_SENT_MAIL_FAILED);
Charles Lindsay's avatar
Charles Lindsay committed
871 872 873 874 875 876 877 878 879 880 881
            libnotify.clear_error_notification();
        }
    }
    
    private void on_sending_started() {
        main_window.status_bar.activate_message(StatusBar.Message.OUTBOX_SENDING);
    }
    
    private void on_sending_finished() {
        main_window.status_bar.deactivate_message(StatusBar.Message.OUTBOX_SENDING);
    }
882 883 884 885 886 887 888 889 890 891

    private async void connect_account_async(Geary.Account account, Cancellable? cancellable = null) {
        AccountContext context = new AccountContext(account);

        // XXX Need to set this early since
        // on_folders_available_unavailable expects it to be there
        this.accounts.set(account.information, context);

        account.email_sent.connect(on_sent);
        account.email_removed.connect(on_account_email_removed);
892
        account.folders_available_unavailable.connect(on_folders_available_unavailable);
Charles Lindsay's avatar
Charles Lindsay committed
893 894
        account.sending_monitor.start.connect(on_sending_started);
        account.sending_monitor.finish.connect(on_sending_finished);
895

896 897 898 899 900 901 902 903
        bool retry = false;
        do {
            try {
                account.set_data(PROP_ATTEMPT_OPEN_ACCOUNT, true);
                yield account.open_async(cancellable);
                retry = false;
            } catch (Error open_err) {
                debug("Unable to open account %s: %s", account.to_string(), open_err.message);
904

905
                if (open_err is Geary.EngineError.CORRUPT) {
906
                    retry = yield account_database_error_async(account);
907
                }
908 909

                if (!retry) {
910 911 912 913 914 915 916 917 918
                    report_problem(
                        new Geary.AccountProblemReport(
                            Geary.ProblemType.GENERIC_ERROR,
                            account.information,
                            open_err
                        )
                    );

                    this.account_manager.disable_account(account.information);
919 920
                    this.accounts.unset(account.information);
                }
921 922
            }
        } while (retry);
923

924
        main_window.folder_list.set_user_folders_root_name(account, _("Labels"));
925
        display_main_window_if_ready();
926
        update_account_status();
927
    }
928

929 930 931 932 933 934 935
    // Returns true if the caller should try opening the account again
    private async bool account_database_error_async(Geary.Account account) {
        bool retry = true;
        
        // give the user two options: reset the Account local store, or exit Geary.  A third
        // could be done to leave the Account in an unopened state, but we don't currently
        // have provisions for that.
936
        QuestionDialog dialog = new QuestionDialog(main_window,
937
            _("Unable to open the database for %s").printf(account.information.id),
938
            _("There was an error opening the local mail database for this account. This is possibly due to corruption of the database file in this directory:\n\n%s\n\nGeary can rebuild the database and re-synchronize with the server or exit.\n\nRebuilding the database will destroy all local email and its attachments. <b>The mail on the your server will not be affected.</b>")
939
                .printf(account.information.data_dir.get_path()),
940 941 942 943 944 945 946 947
            _("_Rebuild"), _("E_xit"));
        dialog.use_secondary_markup(true);
        switch (dialog.run()) {
            case Gtk.ResponseType.OK:
                // don't use Cancellable because we don't want to interrupt this process
                try {
                    yield account.rebuild_async();
                } catch (Error err) {
948
                    ErrorDialog errdialog = new ErrorDialog(main_window,
949
                        _("Unable to rebuild database for “%s”").printf(account.information.id),
950
                        _("Error during rebuild:\n\n%s").printf(err.message));
951
                    errdialog.run();
952 953 954 955 956 957 958 959 960
                    
                    retry = false;
                }
            break;
            
            default:
                retry = false;
            break;
        }
961

962 963
        return retry;
    }
964

965 966 967 968 969 970 971 972
    private async void disconnect_account_async(AccountContext context, Cancellable? cancellable = null) {
        debug("Disconnecting account: %s", context.account.information.id);

        Geary.Account account = context.account;

        // Guard against trying to disconnect the account twice
        this.accounts.unset(account.information);

973 974 975 976
        // Now the account is not in the accounts map, reset any
        // status notifications for it
        update_account_status();

977 978
        account.email_sent.disconnect(on_sent);
        account.email_removed.disconnect(on_account_email_removed);
979
        account.folders_available_unavailable.disconnect(on_folders_available_unavailable);
Charles Lindsay's avatar
Charles Lindsay committed
980 981
        account.sending_monitor.start.disconnect(on_sending_started);
        account.sending_monitor.finish.disconnect(on_sending_finished);
982

983
        main_window.folder_list.remove_account(account);
984 985 986 987

        context.cancellable.cancel();
        Geary.Folder? inbox = context.inbox;
        if (inbox != null) {
988
            try {
989
                yield inbox.close_async(cancellable);
990 991
            } catch (Error close_inbox_err) {
                debug("Unable to close monitored inbox: %s", close_inbox_err.message);
992
            }
993
            context.inbox = null;
994
        }
995

996 997 998 999
        try {
            yield account.close_async(cancellable);
        } catch (Error close_err) {
            debug("Unable to close account %s: %s", account.to_string(), close_err.message);
1000
        }
1001 1002

        debug("Account closed: %s", account.to_string());
1003
    }
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    /**
     * Returns true if we've attempted to open all accounts at this point.
     */
    private bool did_attempt_open_all_accounts() {
        try {
            foreach (Geary.AccountInformation info in Geary.Engine.instance.get_accounts().values) {
                Geary.Account a = Geary.Engine.instance.get_account_instance(info);
                if (a.get_data<bool?>(PROP_ATTEMPT_OPEN_ACCOUNT) == null)
                    return false;
            }
        } catch(Error e) {
            error("Could not open accounts: %s", e.message);
        }
        
        return true;
    }
    
    /**
     * Displays the main window if we're ready.  Otherwise does nothing.
     */
    private void display_main_window_if_ready() {
1026 1027 1028
        if (did_attempt_open_all_accounts() &&
            !upgrade_dialog.visible &&
            !cancellable_open_account.is_cancelled() &&
1029
            !Args.hidden_startup)
1030
            main_window.show();
1031 1032
    }
    
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    /**
     * Returns the number of accounts that exist in Geary.  Note that not all accounts may be
     * open.  Zero is returned on an error.
     */
    public int get_num_accounts() {
        try {
            return Geary.Engine.instance.get_accounts().size;
        } catch (Error e) {
            debug("Error getting number of accounts: %s", e.message);
        }
        
        return 0; // on error
    }
1046

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    private bool is_inbox_descendant(Geary.Folder target) {
        bool is_descendent = false;

        Geary.Account account = target.account;
        Geary.Folder? inbox = null;
        try {
            inbox = account.get_special_folder(Geary.SpecialFolderType.INBOX);
        } catch (Error err) {
            debug("Failed to get inbox for account %s", account.information.id);
        }

        if (inbox != null) {
            is_descendent = inbox.path.is_descendant(target.path);
        }
        return is_descendent;
    }

1064 1065 1066
    // Update widgets and such to match capabilities of the current folder ... sensitivity is handled
    // by other utility methods
    private void update_ui() {
1067 1068 1069
        main_window.main_toolbar.selected_conversations = this.selected_conversations.size;
        main_window.main_toolbar.show_trash_button = current_folder_supports_trash() ||
                                                    !(current_folder is Geary.FolderSupport.Remove);
1070
    }
1071

1072
    private void on_folder_selected(Geary.Folder? folder) {
1073
        debug("Folder %s selected", folder != null ? folder.to_string() : "(null)");
1074
        if (folder == null) {
1075
            this.current_folder = null;
1076
            main_window.conversation_list_view.set_model(null);
1077
            main_window.main_toolbar.folder = null;
1078
            folder_selected(null);
1079 1080
        } else if (folder != this.current_folder) {
            this.main_window.conversation_viewer.show_loading();
1081
            get_window_action(ACTION_FIND_IN_CONVERSATION).set_enabled(false);
1082
            enable_message_buttons(false);
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
            // To prevent the user from selecting folders too quickly,
            // we prevent additional selection changes to occur until
            // after a timeout has expired from the last one
            int64 now = get_monotonic_time();
            int64 diff = now - this.next_folder_select_allowed_usec;
            if (diff < SELECT_FOLDER_TIMEOUT_USEC) {
                // only start timeout if another timeout is not
                // running ... this means the user can click madly and
                // will see the last clicked-on folder 100ms after the
                // first one was clicked on
                if (this.select_folder_timeout_id == 0) {
                    this.select_folder_timeout_id = Timeout.add(
                        (uint) (diff / 1000),
                        () => {
                            this.select_folder_timeout_id = 0;
                            this.next_folder_select_allowed_usec = 0;
                            if (folder != this.current_folder) {
                                do_select_folder.begin(
                                    folder, on_select_folder_completed
                                );
                            }
                            return false;
                        });
                }
            } else {
                do_select_folder.begin(folder, on_select_folder_completed);
                this.next_folder_select_allowed_usec =
                    now + SELECT_FOLDER_TIMEOUT_USEC;
            }
1113
        }
1114
    }
1115

1116
    private async void do_select_folder(Geary.Folder folder) throws Error {
1117 1118
        debug("Switching to %s...", folder.to_string());
        
1119
        closed_folder();
1120
        
1121 1122 1123 1124
        // This function is not reentrant.  It should be, because it can be
        // called reentrant-ly if you select folders quickly enough.  This
        // mutex lock is a bandaid solution to make the function safe to
        // reenter.
1125
        int mutex_token = yield select_folder_mutex.claim_async(cancellable_folder);
1126

1127 1128 1129
        // clear Revokable, as Undo is only available while a folder is selected
        save_revokable(null, null);
        
1130
        // stop monitoring for conversations and close the folder
1131
        if (current_conversations != null) {
1132
            yield current_conversations.stop_monitoring_async(null);
1133
            current_conversations = null;
1134 1135
        }
        
1136 1137 1138 1139 1140
        // re-enable copy/move to the last selected folder
        if (current_folder != null) {
            main_window.main_toolbar.copy_folder_menu.enable_disable_folder(current_folder, true);
            main_window.main_toolbar.move_folder_menu.enable_disable_folder(current_folder, true);
        }
1141 1142 1143 1144 1145 1146 1147

        this.current_folder = folder;

        if (this.current_account != folder.account) {
            this.current_account = folder.account;
            account_selected(this.current_account);

1148 1149 1150 1151 1152 1153 1154
            // If we were waiting for an account to be selected before issuing mailtos, do that now.
            if (pending_mailtos.size > 0) {
                foreach(string mailto in pending_mailtos)
                    compose_mailto(mailto);
                
                pending_mailtos.clear();
            }
1155 1156 1157 1158 1159 1160 1161

            main_window.main_toolbar.copy_folder_menu.clear();
            main_window.main_toolbar.move_folder_menu.clear();
            foreach(Geary.Folder f in current_folder.account.list_folders()) {
                main_window.main_toolbar.copy_folder_menu.add_folder(f);
                main_window.main_toolbar.move_folder_menu.add_folder(f);
            }
1162
        }
1163
        
1164
        folder_selected(current_folder);
Eric Gregory's avatar
Eric Gregory committed
1165
        
1166 1167 1168
        if (!(current_folder is Geary.SearchFolder))
            previous_non_search_folder = current_folder;
        
1169
        // disable copy/move to the new folder
1170 1171
        main_window.main_toolbar.copy_folder_menu.enable_disable_folder(current_folder, false);
        main_window.main_toolbar.move_folder_menu.enable_disable_folder(current_folder, false);
1172
        
1173
        update_ui();
1174 1175 1176 1177

        current_conversations = new Geary.App.ConversationMonitor(
            current_folder,
            Geary.Folder.OpenFlags.NO_DELAY,
1178 1179 1180 1181 1182 1183
            // Include fields for the conversation viewer as well so
            // conversations can be displayed without having to go
            // back to the db
            ConversationListStore.REQUIRED_FIELDS |
            ConversationListBox.REQUIRED_FIELDS |
            ConversationEmail.REQUIRED_FOR_CONSTRUCT,
1184 1185
            MIN_CONVERSATION_COUNT
        );
1186

1187
        current_conversations.scan_completed.connect(on_scan_completed);
1188
        current_conversations.scan_error.connect(on_scan_error);
1189

1190 1191
        current_conversations.scan_completed.connect(on_conversation_count_changed);
        current_conversations.conversations_added.connect(on_conversation_count_changed);
1192
        current_conversations.conversations_removed.connect(on_conversation_count_changed);
1193 1194 1195 1196 1197 1198 1199

        clear_new_messages("do_select_folder", null);

        yield this.current_conversations.start_monitoring_async(
            this.cancellable_folder
        );

1200
        select_folder_mutex.release(ref mutex_token);
1201 1202
        
        debug("Switched to %s", folder.to_string());
1203
    }
1204

1205
    private void on_conversation_count_changed() {
1206
        if (this.current_conversations != null) {
1207
            ConversationListView list = this.main_window.conversation_list_view;
1208
            ConversationViewer viewer = this.main_window.conversation_viewer;
1209
            int count = this.current_conversations.size;
1210 1211 1212
            if (count == 0) {
                // Let the user know if there's no available conversations
                if (this.current_folder is Geary.SearchFolder) {
1213
                    viewer.show_empty_search();
1214
                } else {
1215
                    viewer.show_empty_folder();
1216
                }
1217
                enable_message_buttons(false);
1218 1219
            } else {
                // When not doing autoselect, we never get
1220 1221 1222 1223
                // conversations_selected firing from the convo list, so
                // we need to stop the loading spinner here
                if (!this.application.config.autoselect &&
                    list.get_selection().count_selected_rows() == 0) {
1224 1225 1226
                    viewer.show_none_selected();
                    enable_message_buttons(false);
                }
1227 1228 1229
            }
            conversation_count_changed(count);
        }
1230
    }
1231

1232
    private void on_libnotify_invoked(Geary.Folder? folder, Geary.Email? email) {
1233 1234
        new_messages_monitor.clear_all_new_messages();
        
1235
        if (folder == null || email == null || !can_switch_conversation_view())
1236 1237
            return;
        
1238
        main_window.folder_list.select_folder(folder);
1239
        Geary.App.Conversation? conversation = current_conversations.get_by_email_identifier(email.id);
1240
        if (conversation != null)
1241
            main_window.conversation_list_view.select_conversation(conversation);
1242
    }
1243

1244
    private void on_indicator_activated_application(uint32 timestamp) {
1245
        this.application.present();
1246
    }
1247

1248
    private void on_indicator_activated_composer(uint32 timestamp) {
1249
        on_indicator_activated_application(timestamp);
1250
        on_new_message(null);
1251 1252
    }
    
1253
    private void on_indicator_activated_inbox(Geary.Folder folder, uint32 timestamp) {
1254
        on_indicator_activated_application(timestamp);
1255
        main_window.folder_list.select_folder(folder);
1256
    }
1257
    
1258 1259
    private void on_load_more() {
        debug("on_load_more");
1260
        current_conversations.min_window_count += MIN_CONVERSATION_COUNT;
1261 1262 1263 1264 1265 1266 1267 1268 1269
    }
    
    private void on_select_folder_completed(Object? source, AsyncResult result) {
        try {
            do_select_folder.end(result);
        } catch (Error err) {
            debug("Unable to select folder: %s", err.message);
        }
    }
1270

1271
    private void on_conversations_selected(Gee.Set<Geary.App.Conversation> selected) {
1272
        this.selected_conversations = selected;
1273
        get_window_action(ACTION_FIND_IN_CONVERSATION).set_enabled(false);
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
        ConversationViewer viewer = this.main_window.conversation_viewer;
        if (this.current_folder != null && !viewer.is_composer_visible) {
            switch(selected.size) {
            case 0:
                enable_message_buttons(false);
                viewer.show_none_selected();
                break;

            case 1:
                // Cancel existing avatar loads before loading new
                // convo since that will start loading more avatars
1285 1286 1287 1288 1289
                Geary.App.Conversation convo = Geary.Collection.get_first(
                    selected
                );
                Geary.App.EmailStore? store = get_store_for_folder(
                    convo.base_folder
1290
                );
1291 1292 1293 1294 1295 1296 1297

                // It's possible for a conversation with zero email to
                // be selected, when it has just evaporated after its
                // last email was removed but the conversation monitor
                // hasn't signalled its removal yet. In this case,
                // just don't load it since it will soon disappear.
                if (store != null && convo.get_count() > 0) {
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
                    viewer.load_conversation.begin(
                        convo,
                        store,
                        this.avatar_store,
                        (obj, ret) => {
                            try {
                                viewer.load_conversation.end(ret);
                                enable_message_buttons(true);
                                get_window_action(
                                    ACTION_FIND_IN_CONVERSATION
                                ).set_enabled(true);
1309 1310
                            } catch (GLib.IOError.CANCELLED err) {
                                // All good
1311 1312 1313 1314 1315 1316 1317
                            } catch (Error err) {
                                debug("Unable to load conversation: %s",
                                      err.message);
                            }
                        }
                    );
                }
1318 1319 1320 1321 1322 1323 1324
                break;

            default:
                enable_multiple_message_buttons();
                viewer.show_multiple_selected();
                break;
            }
1325
        }
1326
    }
1327

1328
    private void on_conversation_activated(Geary.App.Conversation activated) {
Eric Gregory's avatar
Eric Gregory committed
1329 1330 1331 1332
        // Currently activating a conversation is only available for drafts folders.
        if (current_folder == null || current_folder.special_folder_type !=
            Geary.SpecialFolderType.DRAFTS)
            return;
1333

Eric Gregory's avatar
Eric Gregory committed
1334
        // TODO: Determine how to map between conversations and drafts correctly.
1335 1336 1337 1338 1339 1340
        Geary.Email draft = activated.get_latest_recv_email(
            Geary.App.Conversation.Location.IN_FOLDER
        );
        create_compose_widget(
            ComposerWidget.ComposeType.NEW_MESSAGE, draft, null, null, true
        );
Eric Gregory's avatar
Eric Gregory committed
1341
    }
Michael Gratton's avatar