Welcome to mirror list, hosted at ThFree Co, Russian Federation.

main.py « gtk « gajim - dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 40038c90b92c5efa6102a8d267c375d61912bbe7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# This file is part of Gajim.
#
# Gajim is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 only.
#
# Gajim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

from typing import Any
from typing import cast
from typing import Generator
from typing import Optional

import logging

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import Gio

from nbxmpp import JID

from gajim.common import app
from gajim.common import events
from gajim.common import ged
from gajim.common.client import Client
from gajim.common.const import Direction
from gajim.common.const import Display
from gajim.common.const import SimpleClientState
from gajim.common.ged import EventHelper
from gajim.common.i18n import _
from gajim.common.modules.bytestream import is_transfer_active
from gajim.plugins.pluginmanager import PluginManifest
from gajim.plugins.repository import PluginRepository

from .account_side_bar import AccountSideBar
from .app_side_bar import AppSideBar
from .workspace_side_bar import WorkspaceSideBar
from .main_stack import MainStack
from .call_window import CallWindow
from .chat_list import ChatList
from .dialogs import DialogButton
from .dialogs import ConfirmationDialog
from .dialogs import ConfirmationCheckDialog
from .types import ControlT
from .builder import get_builder
from .util import get_app_window
from .util import get_key_theme
from .util import resize_window
from .util import restore_main_window_position
from .util import save_main_window_position
from .util import open_window
from .util import set_urgency_hint
from .structs import AccountJidParam
from .structs import AddChatActionParams
from .structs import actionmethod

log = logging.getLogger('gajim.gui.main')


class MainWindow(Gtk.ApplicationWindow, EventHelper):
    def __init__(self) -> None:
        Gtk.ApplicationWindow.__init__(self)
        EventHelper.__init__(self)
        self.set_application(app.app)
        self.set_title('Gajim')
        self.set_default_icon_name('org.gajim.Gajim')

        app.window = self

        self._startup_finished: bool = False

        self._ui = get_builder('main.ui')

        self.add(self._ui.main_grid)

        self._main_stack = MainStack()
        self._ui.main_grid.add(self._main_stack)

        self._chat_page = self._main_stack.get_chat_page()

        self._app_page = self._main_stack.get_app_page()
        self._app_side_bar = AppSideBar(self._app_page)
        self._ui.app_box.add(self._app_side_bar)

        self._workspace_side_bar = WorkspaceSideBar(self._chat_page)
        self._ui.workspace_scrolled.add(self._workspace_side_bar)

        self._account_side_bar = AccountSideBar()
        self._ui.account_box.add(self._account_side_bar)

        self.connect('motion-notify-event', self._on_window_motion_notify)
        self.connect('notify::is-active', self._on_window_active)
        self.connect('delete-event', self._on_window_delete)
        self.connect('window-state-event', self._on_window_state_changed)

        self._ui.connect_signals(self)

        self.register_events([
            ('presence-received', ged.GUI1, self._on_event),
            ('message-sent', ged.GUI1, self._on_event),
            ('message-received', ged.CORE, self._on_message_received),
            ('mam-message-received', ged.CORE, self._on_event),
            ('gc-message-received', ged.CORE, self._on_event),
            ('message-updated', ged.CORE, self._on_event),
            ('message-moderated', ged.CORE, self._on_event),
            ('receipt-received', ged.GUI1, self._on_event),
            ('displayed-received', ged.GUI1, self._on_event),
            ('read-state-sync', ged.GUI1, self._on_read_state_sync),
            ('message-error', ged.GUI1, self._on_event),
            ('muc-disco-update', ged.GUI1, self._on_event),
            ('call-started', ged.GUI1, self._on_call_started),
            ('call-stopped', ged.GUI1, self._on_event),
            ('jingle-request-received', ged.GUI1, self._on_jingle_request),
            ('file-request-received', ged.GUI1, self._on_file_request),
            ('file-request-sent', ged.GUI1, self._on_event),
            ('account-enabled', ged.GUI1, self._on_account_enabled),
            ('account-disabled', ged.GUI1, self._on_account_disabled),
            ('allow-gajim-update-check', ged.GUI1, self._on_allow_gajim_update),
            ('gajim-update-available', ged.GUI1,
             self._on_gajim_update_available),
            ('roster-item-exchange', ged.GUI1, self._on_roster_item_exchange),
            ('plain-connection', ged.GUI1, self._on_plain_connection),
            ('password-required', ged.GUI1, self._on_password_required),
            ('http-auth', ged.GUI1, self._on_http_auth),
            ('muc-added', ged.GUI1, self._on_muc_added),
        ])

        app.plugin_repository.connect('plugin-updates-available',
                                      self._on_plugin_updates_available)
        app.plugin_repository.connect('auto-update-finished',
                                      self._on_plugin_auto_update_finished)

        self._check_for_account()
        self._load_chats()
        self._load_unread_counts()
        self._add_actions()
        self._add_actions2()

        self._prepare_window()

        chat_list_stack = self._chat_page.get_chat_list_stack()
        app.app.systray.connect_unread_widget(chat_list_stack,
                                              'unread-count-changed')

        for client in app.get_clients():
            client.connect_signal('state-changed',
                                  self._on_client_state_changed)

    def is_minimized(self) -> bool:
        if app.is_display(Display.WAYLAND):
            # There is no way to discover if a window is minimized on wayland
            return False

        window = self.get_window()
        assert window is not None
        return bool(Gdk.WindowState.ICONIFIED & window.get_state())

    def is_withdrawn(self) -> bool:
        window = self.get_window()
        assert window is not None
        return bool(Gdk.WindowState.WITHDRAWN & window.get_state())

    def hide(self) -> None:
        save_main_window_position()
        Gtk.ApplicationWindow.hide(self)

    def show(self) -> None:
        restore_main_window_position()
        self.present_with_time(Gtk.get_current_event_time())

    def minimize(self) -> None:
        self.iconify()

    def unminimize(self) -> None:
        self.deiconify()
        self.present_with_time(Gtk.get_current_event_time())

    def _prepare_window(self) -> None:
        window_width = app.settings.get('mainwin_width')
        window_height = app.settings.get('mainwin_height')
        resize_window(self, window_width, window_height)
        restore_main_window_position()

        self.set_skip_taskbar_hint(not app.settings.get('show_in_taskbar'))
        self.show_all()

        show_main_window = app.settings.get('show_main_window_on_startup')
        if show_main_window == 'never':
            self.hide()

        elif (show_main_window == 'last_state' and
                not app.settings.get('is_window_visible')):
            self.hide()

    def _on_account_enabled(self, event: events.AccountEnabled) -> None:
        self._account_side_bar.add_account(event.account)
        self._main_stack.add_account_page(event.account)
        client = app.get_client(event.account)
        client.connect_signal('state-changed', self._on_client_state_changed)

    def _on_account_disabled(self, event: events.AccountDisabled) -> None:
        workspace_id = self._workspace_side_bar.get_first_workspace()
        self.activate_workspace(workspace_id)
        self._account_side_bar.remove_account(event.account)
        self._main_stack.remove_account_page(event.account)
        self._main_stack.remove_chats_for_account(event.account)

    def update_account_unread_count(self, account: str, count: int) -> None:
        self._account_side_bar.update_unread_count(account, count)

    def _on_client_state_changed(self,
                                 client: Client,
                                 _signal_name: str,
                                 state: SimpleClientState) -> None:

        app.app.set_account_actions_state(client.account, state.is_connected)
        app.app.update_app_actions_state()

    def _on_allow_gajim_update(self,
                               event: events.AllowGajimUpdateCheck) -> None:
        self.add_app_message(event.name)

    def _on_gajim_update_available(self,
                                   event: events.GajimUpdateAvailable) -> None:
        self.add_app_message(event.name, event.version)

    @staticmethod
    def _on_roster_item_exchange(event: events.RosterItemExchangeEvent) -> None:
        open_window('RosterItemExchange',
                    account=event.client.account,
                    action=event.action,
                    exchange_list=event.exchange_items_list,
                    jid_from=event.jid)

    @staticmethod
    def _on_plain_connection(event: events.PlainConnection) -> None:
        ConfirmationDialog(
            _('Insecure Connection'),
            _('Insecure Connection'),
            _('You are about to connect to the account %(account)s '
              '(%(server)s) using an insecure connection method. This means '
              'conversations will not be encrypted. Connecting PLAIN is '
              'strongly discouraged.') % {
                  'account': event.account,
                  'server': app.get_hostname_from_account(event.account)},
            [DialogButton.make('Cancel',
                               text=_('_Abort'),
                               callback=event.abort),
             DialogButton.make('Remove',
                               text=_('_Connect Anyway'),
                               callback=event.connect)]).show()

    @staticmethod
    def _on_password_required(event: events.PasswordRequired) -> None:
        open_window('PasswordDialog', event=event)

    @staticmethod
    def _on_http_auth(event: events.HttpAuth) -> None:
        def _response(answer: str) -> None:
            event.client.get_module('HTTPAuth').build_http_auth_answer(
                event.stanza, answer)

        account = event.client.account
        message = _('HTTP (%(method)s) Authorization '
                    'for %(url)s (ID: %(id)s)') % {
                        'method': event.data.method,
                        'url': event.data.url,
                        'id': event.data.id}
        sec_msg = _('Do you accept this request?')
        if app.get_number_of_connected_accounts() > 1:
            sec_msg = _('Do you accept this request (account: %s)?') % account
        if event.data.body:
            sec_msg = event.data.body + '\n' + sec_msg
        message = message + '\n' + sec_msg

        ConfirmationDialog(
            _('Authorization Request'),
            _('HTTP Authorization Request'),
            message,
            [DialogButton.make('Cancel',
                               text=_('_No'),
                               callback=_response,
                               args=['no']),
             DialogButton.make('Accept',
                               callback=_response,
                               args=['yes'])]).show()

    def _on_muc_added(self, event: events.MucAdded) -> None:
        if self.chat_exists(event.account, event.jid):
            return

        self.add_group_chat(event.account, event.jid)

    def _add_actions(self) -> None:
        actions = [
            ('add-workspace', 's', self._add_workspace),
            ('edit-workspace', 's', self._edit_workspace),
            ('remove-workspace', None, self._remove_workspace),
            ('activate-workspace', 's', self._activate_workspace),
            ('add-chat', 'a{sv}', self._add_chat),
            ('add-group-chat', 'as', self._add_group_chat),
            ('add-to-roster', 'a{sv}', self._add_to_roster),
        ]

        for action in actions:
            action_name, variant, func = action
            if variant is not None:
                variant = GLib.VariantType.new(variant)
            act = Gio.SimpleAction.new(action_name, variant)
            act.connect('activate', func)
            self.add_action(act)

    def _add_actions2(self) -> None:
        actions = [
            'change-nickname',
            'change-subject',
            'escape',
            'send-file',
            'show-contact-info',
            'show-emoji-chooser',
            'clear-chat',
            'delete-line',
            'close-tab',
            'switch-next-tab',
            'switch-prev-tab',
            'switch-next-unread-tab'
            'switch-prev-unread-tab',
            'switch-tab-1',
            'switch-tab-2',
            'switch-tab-3',
            'switch-tab-4',
            'switch-tab-5',
            'switch-tab-6',
            'switch-tab-7',
            'switch-tab-8',
            'switch-tab-9',
            'toggle-chat-list',
        ]

        disabled_for_emacs = (
            'send-file',
            'close-tab'
        )

        key_theme = get_key_theme()

        for action in actions:
            if key_theme == 'Emacs' and action in disabled_for_emacs:
                continue
            act = Gio.SimpleAction.new(action, None)
            act.connect('activate', self._on_action)
            self.add_action(act)

    def _on_action(self,
                   action: Gio.SimpleAction,
                   _param: Optional[GLib.Variant]) -> Optional[int]:

        action_name = action.get_name()
        log.info('Activate action: %s', action_name)

        if action_name == 'escape' and self._chat_page.hide_search():
            return None

        control = self.get_active_control()
        if control is not None:

            res = control.delegate_action(action_name)
            if res != Gdk.EVENT_PROPAGATE:
                return res

            if action_name == 'escape':
                if app.settings.get('escape_key_closes'):
                    self._chat_page.remove_chat(control.account,
                                                control.contact.jid)
                    return None

            elif action_name == 'close-tab':
                self._chat_page.remove_chat(control.account,
                                            control.contact.jid)
                return None

        if action_name == 'switch-next-tab':
            self.select_next_chat(Direction.NEXT)

        elif action_name == 'switch-prev-tab':
            self.select_next_chat(Direction.PREV)

        elif action_name == 'switch-next-unread-tab':
            self.select_next_chat(Direction.NEXT, unread_first=True)

        elif action_name == 'switch-prev-unread-tab':
            self.select_next_chat(Direction.PREV, unread_first=True)

        elif action_name.startswith('switch-tab-'):
            number = int(action_name[-1]) - 1
            self.select_chat_number(number)

        elif action_name == 'toggle-chat-list':
            self._toggle_chat_list()

        return None

    def _toggle_chat_list(self) -> None:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        chat_list = chat_list_stack.get_current_chat_list()
        if chat_list is not None:
            if chat_list.is_visible():
                self._ui.toggle_chat_list_button.set_tooltip_text(
                    _('Show chat list'))
                self._ui.toggle_chat_list_icon.set_from_icon_name(
                    'go-next-symbolic', Gtk.IconSize.BUTTON)
            else:
                self._ui.toggle_chat_list_button.set_tooltip_text(
                    _('Hide chat list'))
                self._ui.toggle_chat_list_icon.set_from_icon_name(
                    'go-previous-symbolic', Gtk.IconSize.BUTTON)
        self._chat_page.toggle_chat_list()

    def _on_window_motion_notify(self,
                                 _widget: Gtk.ApplicationWindow,
                                 _event: Gdk.EventMotion
                                 ) -> None:
        control = self.get_active_control()
        if control is None:
            return

        if self.get_property('has-toplevel-focus'):
            client = app.get_client(control.account)
            client.get_module('Chatstate').set_mouse_activity(
                control.contact, control.msg_textview.has_text())

    def _on_window_delete(self,
                          _widget: Gtk.ApplicationWindow,
                          _event: Gdk.Event
                          ) -> int:

        action = app.settings.get('action_on_close')
        if action == 'hide':
            self.hide()
            return Gdk.EVENT_STOP

        if action == 'minimize':
            self.minimize()
            return Gdk.EVENT_STOP

        if not app.settings.get('confirm_on_window_delete'):
            self.quit()
            return Gdk.EVENT_STOP

        def _on_ok(is_checked: bool) -> None:
            if is_checked:
                app.settings.set('confirm_on_window_delete', False)
            self.quit()

        ConfirmationCheckDialog(
            _('Quit Gajim'),
            _('You are about to quit Gajim'),
            _('Are you sure you want to quit Gajim?'),
            _('_Don’t ask again'),
            [DialogButton.make('Cancel'),
             DialogButton.make('Remove',
                               text=_('_Quit'),
                               callback=_on_ok)]).show()

        return Gdk.EVENT_STOP

    def _on_window_state_changed(self,
                                 window: MainWindow,
                                 event: Gdk.EventWindowState) -> None:

        states = Gdk.WindowState.WITHDRAWN | Gdk.WindowState.ICONIFIED
        if states & event.changed_mask:
            is_withdrawn = bool(Gdk.WindowState.WITHDRAWN &
                                event.new_window_state)
            is_iconified = bool(Gdk.WindowState.ICONIFIED &
                                event.new_window_state)
            log.debug('Window state changed: ICONIFIED: %s, WITHDRAWN: %s',
                      is_iconified, is_withdrawn)

            app.settings.set('is_window_visible', not is_withdrawn)

    def _set_startup_finished(self) -> None:
        self._startup_finished = True
        self._chat_page.set_startup_finished()

    def _load_unread_counts(self) -> None:
        chats = app.storage.cache.get_unread()
        chat_list_stack = self._chat_page.get_chat_list_stack()

        for chat in chats:
            chat_list_stack.set_chat_unread_count(
                chat.account,
                chat.jid,
                chat.count)

    def show_account_page(self, account: str) -> None:
        self._app_side_bar.unselect_all()
        self._workspace_side_bar.unselect_all()
        self._account_side_bar.activate_account_page(account)
        self._main_stack.show_account(account)

    def get_active_workspace(self) -> Optional[str]:
        return self._workspace_side_bar.get_active_workspace()

    def is_chat_active(self, account: str, jid: JID) -> bool:
        if not self.get_property('has-toplevel-focus'):
            return False
        return self._chat_page.is_chat_active(account, jid)

    def _add_workspace(self,
                       _action: Gio.SimpleAction,
                       param: GLib.Variant) -> None:

        workspace_id = param.get_string()
        if workspace_id is not None:
            self.add_workspace(workspace_id)

    def add_workspace(self, workspace_id: str) -> None:
        self._workspace_side_bar.add_workspace(workspace_id)
        self._chat_page.add_chat_list(workspace_id)

        if self._startup_finished:
            self.activate_workspace(workspace_id)
            self._workspace_side_bar.store_workspace_order()

    def _edit_workspace(self,
                        _action: Gio.SimpleAction,
                        param: GLib.Variant) -> None:
        workspace_id = param.get_string() or None
        if workspace_id is None:
            workspace_id = self.get_active_workspace()
        open_window('WorkspaceDialog', workspace_id=workspace_id)

    def _remove_workspace(self,
                          _action: Gio.SimpleAction,
                          _param: Optional[GLib.Variant]) -> None:

        workspace_id = self.get_active_workspace()
        if workspace_id is not None:
            self.remove_workspace(workspace_id)

    def remove_workspace(self, workspace_id: str) -> None:
        was_active = self.get_active_workspace() == workspace_id

        success = self._workspace_side_bar.remove_workspace(workspace_id)
        if not success:
            return

        if was_active:
            new_active_id = self._workspace_side_bar.get_first_workspace()
            self.activate_workspace(new_active_id)

        self._chat_page.remove_chat_list(workspace_id)
        app.settings.remove_workspace(workspace_id)

    def _activate_workspace(self,
                            _action: Gio.SimpleAction,
                            param: GLib.Variant) -> None:

        workspace_id = param.get_string()
        if workspace_id is not None:
            self.activate_workspace(workspace_id)

    def activate_workspace(self, workspace_id: str) -> None:
        self._app_side_bar.unselect_all()
        self._account_side_bar.unselect_all()
        self._main_stack.show_chats(workspace_id)
        self._workspace_side_bar.activate_workspace(workspace_id)

    def update_workspace(self, workspace_id: str) -> None:
        self._chat_page.update_workspace(workspace_id)
        self._workspace_side_bar.update_avatar(workspace_id)

    def get_chat_list(self, workspace_id: str) -> ChatList:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        return chat_list_stack.get_chatlist(workspace_id)

    def move_chat_to_new_workspace(self,
                                   account: str,
                                   jid: JID
                                   ) -> None:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        current_chatlist = cast(ChatList, chat_list_stack.get_visible_child())
        type_ = current_chatlist.get_chat_type(account, jid)
        if type_ is None:
            return
        current_chatlist.remove_chat(account, jid)

        workspace_id = app.settings.add_workspace(_('My Workspace'))
        app.window.add_workspace(workspace_id)
        new_chatlist = self.get_chat_list(workspace_id)
        new_chatlist.add_chat(account, jid, type_)
        chat_list_stack.store_open_chats(current_chatlist.workspace_id)
        chat_list_stack.store_open_chats(workspace_id)

    def _add_group_chat(self,
                        _action: Gio.SimpleAction,
                        param: GLib.Variant) -> None:

        account, jid, select = param.unpack()
        self.add_group_chat(account, JID.from_string(jid), select)

    def add_group_chat(self, account: str, jid: JID,
                       select: bool = False) -> None:
        workspace_id = self.get_active_workspace()
        if workspace_id is None:
            workspace_id = self._workspace_side_bar.get_first_workspace()
        self._chat_page.add_chat_for_workspace(workspace_id,
                                               account,
                                               jid,
                                               'groupchat',
                                               select=select)

    def _add_chat(self,
                  _action: Gio.SimpleAction,
                  param: GLib.Variant) -> None:

        params = AddChatActionParams.from_variant(param)
        self.add_chat(params.account, params.jid, params.type, params.select)

    def add_chat(self,
                 account: str,
                 jid: JID,
                 type_: str,
                 select: bool = False,
                 workspace: str = 'default') -> None:
        if workspace == 'current':
            workspace_id = self.get_active_workspace()
            if workspace_id is None:
                workspace_id = self._workspace_side_bar.get_first_workspace()
        else:
            workspace_id = self._workspace_side_bar.get_first_workspace()
        self._chat_page.add_chat_for_workspace(workspace_id,
                                               account,
                                               jid,
                                               type_,
                                               select=select)

    def add_private_chat(self,
                         account: str,
                         jid: JID,
                         select: bool = False) -> None:
        # Try to add private chat to the same workspace the MUC resides in
        chat_list_stack = self._chat_page.get_chat_list_stack()
        chat_list = chat_list_stack.find_chat(account, jid.new_as_bare())
        if chat_list is not None:
            workspace_id = chat_list.workspace_id
        else:
            workspace_id = self._workspace_side_bar.get_first_workspace()

        self._chat_page.add_chat_for_workspace(workspace_id,
                                               account,
                                               jid,
                                               'pm',
                                               select=select)

    def select_chat(self, account: str, jid: JID) -> None:
        self._app_side_bar.unselect_all()
        self._account_side_bar.unselect_all()
        self._main_stack.show_chat_page()
        self._chat_page.select_chat(account, jid)

    def select_next_chat(self, direction: Direction,
                         unread_first: bool = False) -> None:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        chat_list = chat_list_stack.get_current_chat_list()
        if chat_list is not None:
            chat_list.select_next_chat(direction, unread_first)

    def select_chat_number(self, number: int) -> None:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        chat_list = chat_list_stack.get_current_chat_list()
        if chat_list is not None:
            chat_list.select_chat_number(number)

    @actionmethod
    def _add_to_roster(self,
                       _action: Gio.SimpleAction,
                       params: AccountJidParam) -> None:

        open_window('AddContact', account=params.account, jid=params.jid)

    def show_app_page(self) -> None:
        self._account_side_bar.unselect_all()
        self._workspace_side_bar.unselect_all()
        self._main_stack.show_app_page()

    def add_app_message(self,
                        category: str,
                        message: Optional[str] = None) -> None:
        self._app_page.add_app_message(category, message)

    def get_control(self, account: str, jid: JID) -> Optional[ControlT]:
        return self._chat_page.get_control(account, jid)

    def get_controls(self, account: Optional[str] = None
                     ) -> Generator[ControlT, None, None]:
        return self._chat_page.get_controls(account)

    def get_active_control(self) -> Optional[ControlT]:
        return self._chat_page.get_active_control()

    def is_chat_loaded(self, account: str, jid: JID) -> bool:
        return self._chat_page.is_chat_loaded(account, jid)

    def chat_exists(self, account: str, jid: JID) -> bool:
        return self._chat_page.chat_exists(account, jid)

    def get_total_unread_count(self) -> int:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        return chat_list_stack.get_total_unread_count()

    def get_chat_unread_count(self,
                              account: str,
                              jid: JID,
                              include_silent: bool = False
                              ) -> int:
        chat_list_stack = self._chat_page.get_chat_list_stack()
        count = chat_list_stack.get_chat_unread_count(
            account, jid, include_silent)
        return count or 0

    def mark_as_read(self, account: str, jid: JID,
                     send_marker: bool = True) -> None:
        set_urgency_hint(self, False)
        control = self.get_control(account, jid)
        if control is not None:
            # Send displayed marker and
            # reset jump to bottom button unread counter
            control.mark_as_read(send_marker=send_marker)
        # Reset chat list unread counter (emits unread-count-changed)
        chat_list_stack = self._chat_page.get_chat_list_stack()
        chat_list_stack.mark_as_read(account, jid)

    def _on_window_active(self,
                          window: Gtk.ApplicationWindow,
                          _param: Any
                          ) -> None:
        is_active = window.get_property('is-active')
        if not is_active:
            return

        set_urgency_hint(self, False)
        control = self.get_active_control()
        if control is None:
            return

        if control.get_autoscroll():
            self.mark_as_read(control.account, control.contact.jid)

    @staticmethod
    def contact_info(account: str, jid: str) -> None:
        client = app.get_client(account)
        contact = client.get_module('Contacts').get_contact(jid)
        open_window('ContactInfo', account=account, contact=contact)

    @staticmethod
    def execute_command(account: str, jid: str) -> None:
        # TODO: Resource?
        open_window('AdHocCommands', account=account, jid=jid)

    def block_contact(self, account: str, jid: str) -> None:
        client = app.get_client(account)

        contact = client.get_module('Contacts').get_contact(jid)
        if contact.is_blocked:
            client.get_module('Blocking').unblock([jid])
            return

        # TODO: Keep "confirm_block" setting?
        def _block_contact(report: Optional[str] = None) -> None:
            client.get_module('Blocking').block([contact.jid], report)
            self._chat_page.remove_chat(account, contact.jid)

        ConfirmationDialog(
            _('Block Contact'),
            _('Really block this contact?'),
            _('You will appear offline for this contact and you '
              'will not receive further messages.'),
            [DialogButton.make('Cancel'),
             DialogButton.make('OK',
                               text=_('_Report Spam'),
                               callback=_block_contact,
                               kwargs={'report': 'spam'}),
             DialogButton.make('Remove',
                               text=_('_Block'),
                               callback=_block_contact)],
            modal=False).show()

    def remove_contact(self, account: str, jid: JID) -> None:
        client = app.get_client(account)

        def _remove_contact():
            self._chat_page.remove_chat(account, jid)
            client.get_module('Roster').delete_item(jid)

        contact = client.get_module('Contacts').get_contact(jid)
        sec_text = _('You are about to remove %(name)s (%(jid)s) from '
                     'your contact list.\n') % {
                         'name': contact.name,
                         'jid': jid}

        ConfirmationDialog(
            _('Remove Contact'),
            _('Remove contact from contact list'),
            sec_text,
            [DialogButton.make('Cancel'),
             DialogButton.make('Remove',
                               callback=_remove_contact)]).show()

    @staticmethod
    def _check_for_account() -> None:
        accounts = app.settings.get_accounts()
        if not accounts:
            def _open_wizard():
                open_window('AccountWizard')

            GLib.idle_add(_open_wizard)

    def _load_chats(self) -> None:
        for workspace_id in app.settings.get_workspaces():
            self.add_workspace(workspace_id)
            self._chat_page.load_workspace_chats(workspace_id)

        workspace_id = self._workspace_side_bar.get_first_workspace()
        self.activate_workspace(workspace_id)

        self._set_startup_finished()

    def _on_event(self, event: events.MainEventT) -> None:
        if not self.chat_exists(event.account, event.jid):
            return

        self._main_stack.process_event(event)

    def _on_message_received(self, event: events.MessageReceived) -> None:
        if not self.chat_exists(event.account, event.jid):
            if not event.properties.body:
                # Don’t open control on chatstate etc.
                return

            if event.properties.is_muc_pm:
                self.add_private_chat(event.account,
                                      event.properties.jid)

            else:
                jid = event.properties.jid.new_as_bare()
                self.add_chat(event.account, jid, 'contact')

        self._main_stack.process_event(event)

    def _on_read_state_sync(self, event: events.ReadStateSync) -> None:
        if event.is_muc_pm:
            jid = JID.from_string(event.jid.bare)
        else:
            jid = event.jid

        control = self.get_control(event.account, jid)
        if control is None:
            return

        if event.marker_id != control.last_msg_id:
            return

        self.mark_as_read(event.account, jid, send_marker=False)

    def _on_call_started(self, event: events.CallStarted) -> None:
        # Make sure there is only one window
        win = get_app_window('CallWindow')
        if win is not None:
            win.destroy()
        CallWindow(event.account, event.resource_jid)

    def _on_jingle_request(self, event: events.JingleRequestReceived) -> None:
        if not self.chat_exists(event.account, event.jid):
            for item in event.contents:
                if item.media not in ('audio', 'video'):
                    return
                self.add_chat(event.account, event.jid, 'contact')
                break

        self._main_stack.process_event(event)

    def _on_file_request(self, event: events.FileRequestReceivedEvent) -> None:
        if not self.chat_exists(event.account, event.jid):
            self.add_chat(event.account, event.jid, 'contact')

        self._main_stack.process_event(event)

    def quit(self) -> None:
        save_main_window_position()
        window_width, window_height = self.get_size()
        app.settings.set('mainwin_width', window_width)
        app.settings.set('mainwin_height', window_height)
        app.settings.save()

        def on_continue2(message: Optional[str]) -> None:
            if 'file_transfers' not in app.interface.instances:
                app.app.start_shutdown(message=message)
                return
            # check if there is an active file transfer
            files_props = app.interface.instances['file_transfers'].files_props
            transfer_active = False
            for x in files_props:
                for y in files_props[x]:
                    if is_transfer_active(files_props[x][y]):
                        transfer_active = True
                        break

            if transfer_active:
                ConfirmationDialog(
                    _('Stop File Transfers'),
                    _('You still have running file transfers'),
                    _('If you quit now, the file(s) being transferred will '
                      'be lost.\n'
                      'Do you still want to quit?'),
                    [DialogButton.make('Cancel'),
                     DialogButton.make('Remove',
                                       text=_('_Quit'),
                                       callback=app.app.start_shutdown,
                                       kwargs={'message': message})]).show()
                return
            app.app.start_shutdown(message=message)

        def on_continue(message: Optional[str]) -> None:
            if message is None:
                # user pressed Cancel to change status message dialog
                return

            # Check for unread messages
            if self.get_total_unread_count():
                ConfirmationDialog(
                    _('Unread Messages'),
                    _('You still have unread messages'),
                    _('Messages will only be available for reading them later '
                      'if storing chat history is enabled and if the contact '
                      'is in your contact list.'),
                    [DialogButton.make('Cancel'),
                     DialogButton.make('Remove',
                                       text=_('_Quit'),
                                       callback=on_continue2,
                                       args=[message])]).show()
                return
            on_continue2(message)

        on_continue('')

    def _on_plugin_updates_available(self,
                                     _repository: PluginRepository,
                                     _signal_name: str,
                                     manifests: list[PluginManifest]) -> None:
        self._app_page.add_plugin_update_message(manifests)

    def _on_plugin_auto_update_finished(self,
                                        _repository: PluginRepository,
                                        _signal_name: str) -> None:
        self.add_app_message('plugin-updates-finished')