application.py 24.5 KB
Newer Older
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
# Copyright (C) 2003-2017 Yann Leboulanger <asterix AT lagaule.org>
# Copyright (C) 2004-2005 Vincent Hanquez <tab AT snarc.org>
# Copyright (C) 2005 Alex Podaras <bigpod AT gmail.com>
#                    Norman Rasmussen <norman AT rasmussen.co.za>
#                    Stéphan Kochen <stephan AT kochen.nl>
# Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com>
#                         Alex Mauer <hawke AT hawkesnest.net>
# Copyright (C) 2005-2007 Travis Shirk <travis AT pobox.com>
#                         Nikos Kouremenos <kourem AT gmail.com>
# Copyright (C) 2006 Junglecow J <junglecow AT gmail.com>
#                    Stefan Bethge <stefan AT lanpartei.de>
# Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
# Copyright (C) 2007 Lukas Petrovicky <lukas AT petrovicky.net>
#                    James Newton <redshodan AT gmail.com>
# Copyright (C) 2007-2008 Brendan Taylor <whateley AT gmail.com>
#                         Julien Pivotto <roidelapluie AT gmail.com>
#                         Stephan Erb <steve-e AT h3c.de>
# Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org>
# Copyright (C) 2016-2017 Emmanuel Gil Peyrot <linkmauve AT linkmauve.fr>
#                         Philipp Hörist <philipp AT hoerist.com>
#
# 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/>.
Philipp Hörist's avatar
Philipp Hörist committed
35

36
import time
Philipp Hörist's avatar
Philipp Hörist committed
37
import sys
38 39
from datetime import datetime
from pathlib import Path
Philipp Hörist's avatar
Philipp Hörist committed
40 41
from urllib.parse import unquote

42
import nbxmpp
43 44
from nbxmpp import JID
from nbxmpp.protocol import InvalidJid
45 46 47
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
Philipp Hörist's avatar
Philipp Hörist committed
48

49
import gajim
Philipp Hörist's avatar
Philipp Hörist committed
50
from gajim.common import app
51
from gajim.common import ged
Philipp Hörist's avatar
Philipp Hörist committed
52 53
from gajim.common import configpaths
from gajim.common import logging_helpers
Philipp Hörist's avatar
Philipp Hörist committed
54 55 56
from gajim.common import exceptions
from gajim.common import caps_cache
from gajim.common import logger
57
from gajim.common.i18n import _
Philipp Hörist's avatar
Philipp Hörist committed
58 59 60 61 62 63


class GajimApplication(Gtk.Application):
    '''Main class handling activation and command line.'''

    def __init__(self):
64 65 66 67 68 69
        flags = (Gio.ApplicationFlags.HANDLES_COMMAND_LINE |
                 Gio.ApplicationFlags.HANDLES_OPEN)
        Gtk.Application.__init__(self,
                                 application_id='org.gajim.Gajim',
                                 flags=flags)

70 71 72
        # required to track screensaver state
        self.props.register_session = True

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
        self.add_main_option(
            'version',
            ord('V'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Show the application\'s version'))

        self.add_main_option(
            'quiet',
            ord('q'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Show only critical errors'))

        self.add_main_option(
            'separate',
            ord('s'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Separate profile files completely '
              '(even history database and plugins)'))

        self.add_main_option(
            'verbose',
            ord('v'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Print XML stanzas and other debug information'))

        self.add_main_option(
            'profile',
            ord('p'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.STRING,
            _('Use defined profile in configuration directory'),
            'NAME')

        self.add_main_option(
            'config-path',
            ord('c'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.STRING,
            _('Set configuration directory'),
            'PATH')

        self.add_main_option(
            'loglevel',
            ord('l'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.STRING,
            _('Configure logging system'),
            'LEVEL')

        self.add_main_option(
            'warnings',
            ord('w'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Show all warnings'))

        self.add_main_option(
            'ipython',
            ord('i'),
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Open IPython shell'))

        self.add_main_option(
            'show-next-pending-event',
            0,
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Pops up a window with the next pending event'))

        self.add_main_option(
            'start-chat', 0,
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Start a new chat'))
Philipp Hörist's avatar
Philipp Hörist committed
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        self.add_main_option(
            'simulate-network-lost',
            0,
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Simulate loss of connectivity'))

        self.add_main_option(
            'simulate-network-connected',
            0,
            GLib.OptionFlags.NONE,
            GLib.OptionArg.NONE,
            _('Simulate regaining connectivity'))


Philipp Hörist's avatar
Philipp Hörist committed
168 169 170 171 172 173
        self.add_main_option_entries(self._get_remaining_entry())

        self.connect('handle-local-options', self._handle_local_options)
        self.connect('command-line', self._handle_remote_options)
        self.connect('startup', self._startup)
        self.connect('activate', self._activate)
174 175
        if sys.platform not in ('win32', 'darwin'):
            self.connect("notify::screensaver-active", self._screensaver_active)
Philipp Hörist's avatar
Philipp Hörist committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

        self.interface = None

        GLib.set_prgname('gajim')
        if GLib.get_application_name() != 'Gajim':
            GLib.set_application_name('Gajim')

    @staticmethod
    def _get_remaining_entry():
        option = GLib.OptionEntry()
        option.arg = GLib.OptionArg.STRING_ARRAY
        option.arg_data = None
        option.arg_description = ('[URI …]')
        option.flags = GLib.OptionFlags.NONE
        option.long_name = GLib.OPTION_REMAINING
        option.short_name = 0
        return [option]

194
    def _startup(self, _application):
Philipp Hörist's avatar
Philipp Hörist committed
195 196 197 198 199 200 201 202 203

        # Create and initialize Application Paths & Databases
        app.detect_dependencies()
        configpaths.create_paths()
        try:
            app.logger = logger.Logger()
            caps_cache.initialize(app.logger)
        except exceptions.DatabaseMalformed as error:
            dlg = Gtk.MessageDialog(
204 205 206 207 208 209
                transient_for=None,
                destroy_with_parent=True,
                modal=True,
                message_type=Gtk.MessageType.ERROR,
                buttons=Gtk.ButtonsType.OK,
                text=_('Database Error'))
Philipp Hörist's avatar
Philipp Hörist committed
210 211 212 213 214
            dlg.format_secondary_text(str(error))
            dlg.run()
            dlg.destroy()
            sys.exit()

215 216 217
        from gajim.gtk.util import load_user_iconsets
        load_user_iconsets()

Philipp Hörist's avatar
Philipp Hörist committed
218 219
        # Set Application Menu
        app.app = self
Philipp Hörist's avatar
Philipp Hörist committed
220 221
        from gajim.gtk.util import get_builder
        builder = get_builder('application_menu.ui')
Philipp Hörist's avatar
Philipp Hörist committed
222 223 224 225 226 227 228 229 230
        menubar = builder.get_object("menubar")
        appmenu = builder.get_object("appmenu")
        if app.prefers_app_menu():
            self.set_app_menu(appmenu)
        else:
            # Add it to the menubar instead
            menubar.prepend_submenu('Gajim', appmenu)
        self.set_menubar(menubar)

231
    def _activate(self, _application):
Philipp Hörist's avatar
Philipp Hörist committed
232 233 234 235 236 237 238
        if self.interface is not None:
            self.interface.roster.window.present()
            return
        from gajim.gui_interface import Interface
        self.interface = Interface()
        self.interface.run(self)
        self.add_actions()
239
        self._set_shortcuts()
Philipp Hörist's avatar
Philipp Hörist committed
240 241
        from gajim import gui_menu_builder
        gui_menu_builder.build_accounts_menu()
242
        self.update_app_actions_state()
Philipp Hörist's avatar
Philipp Hörist committed
243

244 245 246 247
        app.ged.register_event_handler('feature-discovered',
                                       ged.CORE,
                                       self._on_feature_discovered)

Philipp Hörist's avatar
Philipp Hörist committed
248
    def _open_uris(self, uris):
249 250 251 252
        accounts = list(app.connections.keys())
        if not accounts:
            return

Philipp Hörist's avatar
Philipp Hörist committed
253 254 255 256 257 258 259 260 261 262 263
        for uri in uris:
            app.log('uri_handler').info('open %s', uri)
            if not uri.startswith('xmpp:'):
                continue
            # remove xmpp:
            uri = uri[5:]
            try:
                jid, cmd = uri.split('?')
            except ValueError:
                # No query argument
                jid, cmd = uri, 'message'
264 265 266 267 268 269 270 271 272 273 274 275 276

            try:
                jid = JID(jid)
            except InvalidJid as error:
                app.log('uri_handler').warning('Invalid JID %s: %s', uri, error)
                continue

            if cmd == 'join' and jid.getResource():
                app.log('uri_handler').warning('Invalid MUC JID %s', uri)
                continue

            jid = str(jid)

Philipp Hörist's avatar
Philipp Hörist committed
277
            if cmd == 'join':
278 279 280 281 282 283 284
                if len(accounts) == 1:
                    self.activate_action(
                        'groupchat-join',
                        GLib.Variant('as', [accounts[0], jid]))
                else:
                    self.activate_action('start-chat', GLib.Variant('s', jid))

Philipp Hörist's avatar
Philipp Hörist committed
285 286
            elif cmd == 'roster':
                self.activate_action('add-contact', GLib.Variant('s', jid))
287

Philipp Hörist's avatar
Philipp Hörist committed
288 289 290 291
            elif cmd.startswith('message'):
                attributes = cmd.split(';')
                message = None
                for key in attributes:
292 293 294 295 296 297
                    if not key.startswith('body'):
                        continue
                    try:
                        message = unquote(key.split('=')[1])
                    except Exception:
                        app.log('uri_handler').error('Invalid URI: %s', cmd)
298

Philipp Hörist's avatar
Philipp Hörist committed
299 300 301
                if len(accounts) == 1:
                    app.interface.new_chat_from_jid(accounts[0], jid, message)
                else:
302
                    self.activate_action('start-chat', GLib.Variant('s', jid))
Philipp Hörist's avatar
Philipp Hörist committed
303 304 305 306 307 308 309 310 311 312

    def do_shutdown(self, *args):
        Gtk.Application.do_shutdown(self)
        # Shutdown GUI and save config
        if hasattr(self.interface, 'roster') and self.interface.roster:
            self.interface.roster.prepare_quit()

        # Commit any outstanding SQL transactions
        app.logger.commit()

313
    def _handle_remote_options(self, _application, command_line):
Philipp Hörist's avatar
Philipp Hörist committed
314 315 316
        # Parse all options that should be executed on a remote instance
        options = command_line.get_options_dict()

317 318 319 320 321
        remote_commands = [
            'ipython',
            'show-next-pending-event',
            'start-chat',
        ]
Philipp Hörist's avatar
Philipp Hörist committed
322 323 324 325 326 327 328 329 330

        remaining = options.lookup_value(GLib.OPTION_REMAINING,
                                         GLib.VariantType.new('as'))

        for cmd in remote_commands:
            if options.contains(cmd):
                self.activate_action(cmd)
                return 0

331 332 333 334 335 336 337 338
        if options.contains('simulate-network-lost'):
            app.interface.network_status_changed(None, False)
            return 0

        if options.contains('simulate-network-connected'):
            app.interface.network_status_changed(None, True)
            return 0

Philipp Hörist's avatar
Philipp Hörist committed
339 340 341 342 343 344 345
        if remaining is not None:
            self._open_uris(remaining.unpack())
            return 0

        self.activate()
        return 0

346
    def _handle_local_options(self,
347
                              _application: Gtk.Application,
Philipp Hörist's avatar
Philipp Hörist committed
348 349
                              options: GLib.VariantDict) -> int:
        # Parse all options that have to be executed before ::startup
350 351 352
        if options.contains('version'):
            print(gajim.__version__)
            return 0
Philipp Hörist's avatar
Philipp Hörist committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366
        if options.contains('profile'):
            # Incorporate profile name into application id
            # to have a single app instance for each profile.
            profile = options.lookup_value('profile').get_string()
            app_id = '%s.%s' % (self.get_application_id(), profile)
            self.set_application_id(app_id)
            configpaths.set_profile(profile)
        if options.contains('separate'):
            configpaths.set_separation(True)
        if options.contains('config-path'):
            path = options.lookup_value('config-path').get_string()
            configpaths.set_config_root(path)

        configpaths.init()
367

368
        if app.get_debug_mode():
369
            # Redirect has to happen before logging init
370
            self._cleanup_debug_logs()
371 372 373 374 375
            self._redirect_output()
            logging_helpers.init()
            logging_helpers.set_verbose()
        else:
            logging_helpers.init()
Philipp Hörist's avatar
Philipp Hörist committed
376 377 378 379 380 381 382 383 384 385 386 387 388

        if options.contains('quiet'):
            logging_helpers.set_quiet()
        if options.contains('verbose'):
            logging_helpers.set_verbose()
        if options.contains('loglevel'):
            loglevel = options.lookup_value('loglevel').get_string()
            logging_helpers.set_loglevels(loglevel)
        if options.contains('warnings'):
            self.show_warnings()

        return -1

389 390
    @staticmethod
    def show_warnings():
Philipp Hörist's avatar
Philipp Hörist committed
391 392 393 394
        import traceback
        import warnings

        def warn_with_traceback(message, category, filename, lineno,
395
                                _file=None, line=None):
Philipp Hörist's avatar
Philipp Hörist committed
396 397 398 399 400 401 402
            traceback.print_stack(file=sys.stderr)
            sys.stderr.write(warnings.formatwarning(message, category,
                                                    filename, lineno, line))

        warnings.showwarning = warn_with_traceback
        warnings.filterwarnings(action="always")

403 404 405
    @staticmethod
    def _redirect_output():
        debug_folder = Path(configpaths.get('DEBUG'))
406
        date = datetime.today().strftime('%d%m%Y-%H%M%S')
407 408 409 410
        filename = '%s-debug.log' % date
        fd = open(debug_folder / filename, 'a')
        sys.stderr = sys.stdout = fd

411 412 413 414 415 416 417 418 419 420
    @staticmethod
    def _cleanup_debug_logs():
        debug_folder = Path(configpaths.get('DEBUG'))
        debug_files = list(debug_folder.glob('*-debug.log*'))
        now = time.time()
        for file in debug_files:
            # Delete everything older than 3 days
            if file.stat().st_ctime < now - 259200:
                file.unlink()

Philipp Hörist's avatar
Philipp Hörist committed
421 422
    def add_actions(self):
        ''' Build Application Actions '''
423
        from gajim import app_actions
Philipp Hörist's avatar
Philipp Hörist committed
424 425 426 427 428 429

        # General Stateful Actions

        act = Gio.SimpleAction.new_stateful(
            'merge', None,
            GLib.Variant.new_boolean(app.config.get('mergeaccounts')))
430
        act.connect('change-state', app_actions.on_merge_accounts)
Philipp Hörist's avatar
Philipp Hörist committed
431 432
        self.add_action(act)

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
        actions = [
            ('quit', app_actions.on_quit),
            ('add-account', app_actions.on_add_account),
            ('manage-proxies', app_actions.on_manage_proxies),
            ('history-manager', app_actions.on_history_manager),
            ('preferences', app_actions.on_preferences),
            ('plugins', app_actions.on_plugins),
            ('xml-console', app_actions.on_xml_console),
            ('file-transfer', app_actions.on_file_transfers),
            ('history', app_actions.on_history),
            ('shortcuts', app_actions.on_keyboard_shortcuts),
            ('features', app_actions.on_features),
            ('content', app_actions.on_contents),
            ('about', app_actions.on_about),
            ('faq', app_actions.on_faq),
            ('ipython', app_actions.toggle_ipython),
            ('show-next-pending-event', app_actions.show_next_pending_event),
            ('start-chat', 's', app_actions.on_new_chat),
            ('accounts', 's', app_actions.on_accounts),
            ('add-contact', 's', app_actions.on_add_contact_jid),
            ('copy-text', 's', app_actions.copy_text),
            ('open-link', 'as', app_actions.open_link),
            ('open-mail', 's', app_actions.open_mail),
            ('create-groupchat', 's', app_actions.on_create_gc),
            ('browse-history', 'a{sv}', app_actions.on_browse_history),
            ('groupchat-join', 'as', app_actions.on_groupchat_join),
Philipp Hörist's avatar
Philipp Hörist committed
459 460
        ]

461 462 463 464 465 466 467
        for action in actions:
            if len(action) == 2:
                action_name, func = action
                variant = None
            else:
                action_name, variant, func = action
                variant = GLib.VariantType.new(variant)
468

469
            act = Gio.SimpleAction.new(action_name, variant)
470
            act.connect('activate', func)
Philipp Hörist's avatar
Philipp Hörist committed
471 472 473
            self.add_action(act)

        accounts_list = sorted(app.config.get_per('accounts'))
474 475
        if not accounts_list:
            return
Philipp Hörist's avatar
Philipp Hörist committed
476 477 478 479 480 481
        if len(accounts_list) > 1:
            for acc in accounts_list:
                self.add_account_actions(acc)
        else:
            self.add_account_actions(accounts_list[0])

482 483
    @staticmethod
    def _get_account_actions(account):
484
        from gajim import app_actions as a
485

486
        if account == 'Local':
487
            return []
488 489

        return [
490
            ('-bookmarks', a.on_bookmarks, 'online', 's'),
491
            ('-start-single-chat', a.on_single_message, 'online', 's'),
Philipp Hörist's avatar
Philipp Hörist committed
492 493
            ('-start-chat', a.start_chat, 'online', 'as'),
            ('-add-contact', a.on_add_contact, 'online', 'as'),
494 495 496 497
            ('-services', a.on_service_disco, 'online', 's'),
            ('-profile', a.on_profile, 'feature', 's'),
            ('-server-info', a.on_server_info, 'online', 's'),
            ('-archive', a.on_mam_preferences, 'feature', 's'),
498
            ('-pep-config', a.on_pep_config, 'online', 's'),
499 500
            ('-sync-history', a.on_history_sync, 'online', 's'),
            ('-privacylists', a.on_privacy_lists, 'feature', 's'),
Philipp Hörist's avatar
Philipp Hörist committed
501
            ('-blocking', a.on_blocking_list, 'feature', 's'),
502 503 504 505 506 507
            ('-send-server-message', a.on_send_server_message, 'online', 's'),
            ('-set-motd', a.on_set_motd, 'online', 's'),
            ('-update-motd', a.on_update_motd, 'online', 's'),
            ('-delete-motd', a.on_delete_motd, 'online', 's'),
            ('-open-event', a.on_open_event, 'always', 'a{sv}'),
            ('-import-contacts', a.on_import_contacts, 'online', 's'),
508 509 510 511
        ]

    def add_account_actions(self, account):
        for action in self._get_account_actions(account):
Philipp Hörist's avatar
Philipp Hörist committed
512 513 514 515 516 517 518 519 520 521 522 523 524
            action_name, func, state, type_ = action
            action_name = account + action_name
            if self.lookup_action(action_name):
                # We already added this action
                continue
            act = Gio.SimpleAction.new(
                action_name, GLib.VariantType.new(type_))
            act.connect("activate", func)
            if state != 'always':
                act.set_enabled(False)
            self.add_action(act)

    def remove_account_actions(self, account):
525
        for action in self._get_account_actions(account):
Philipp Hörist's avatar
Philipp Hörist committed
526 527 528 529
            action_name = account + action[0]
            self.remove_action(action_name)

    def set_account_actions_state(self, account, new_state=False):
530
        for action in self._get_account_actions(account):
Philipp Hörist's avatar
Philipp Hörist committed
531 532 533 534 535 536 537
            action_name, _, state, _ = action
            if not new_state and state in ('online', 'feature'):
                # We go offline
                self.lookup_action(account + action_name).set_enabled(False)
            elif new_state and state == 'online':
                # We go online
                self.lookup_action(account + action_name).set_enabled(True)
538

539 540 541 542 543 544 545
    def update_app_actions_state(self):
        active_accounts = bool(app.get_connected_accounts(exclude_local=True))
        self.lookup_action('create-groupchat').set_enabled(active_accounts)

        enabled_accounts = app.contacts.get_accounts()
        self.lookup_action('start-chat').set_enabled(enabled_accounts)

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
    def _set_shortcuts(self):
        shortcuts = {
            'app.quit': ['<Primary>Q'],
            'app.preferences': ['<Primary>P'],
            'app.plugins': ['<Primary>E'],
            'app.xml-console': ['<Primary><Shift>X'],
            'app.file-transfer': ['<Primary>T'],
            'app.ipython': ['<Primary><Alt>I'],
            'app.start-chat::': ['<Primary>N'],
            'app.accounts::': ['<Alt>A'],
            'app.create-groupchat::': ['<Primary>G'],
            'win.show-roster': ['<Primary>R'],
            'win.show-offline': ['<Primary>O'],
            'win.show-active': ['<Primary>Y'],
            'win.change-nickname': ['<Control><Shift>n'],
            'win.change-subject': ['<Alt>t'],
            'win.escape': ['Escape'],
            'win.browse-history': ['<Control>h'],
            'win.send-file': ['<Control>f'],
            'win.show-contact-info': ['<Control>i'],
            'win.show-emoji-chooser': ['<Alt>m'],
            'win.clear-chat': ['<Control>l'],
            'win.delete-line': ['<Control>u'],
            'win.close-tab': ['<Control>w'],
            'win.move-tab-up': ['<Control><Shift>Page_Up'],
            'win.move-tab-down': ['<Control><Shift>Page_Down'],
            'win.switch-next-tab': ['<Alt>Right'],
            'win.switch-prev-tab': ['<Alt>Left'],
            'win.switch-next-unread-tab-right': ['<Control>Tab',
                                                 '<Control>Page_Down'],
            'win.switch-next-unread-tab-left': ['<Control>ISO_Left_Tab',
                                                '<Control>Page_Up'],
            'win.switch-tab-1': ['<Alt>1', '<Alt>KP_1'],
            'win.switch-tab-2': ['<Alt>2', '<Alt>KP_2'],
            'win.switch-tab-3': ['<Alt>3', '<Alt>KP_3'],
            'win.switch-tab-4': ['<Alt>4', '<Alt>KP_4'],
            'win.switch-tab-5': ['<Alt>5', '<Alt>KP_5'],
            'win.switch-tab-6': ['<Alt>6', '<Alt>KP_6'],
            'win.switch-tab-7': ['<Alt>7', '<Alt>KP_7'],
            'win.switch-tab-8': ['<Alt>8', '<Alt>KP_8'],
            'win.switch-tab-9': ['<Alt>9', '<Alt>KP_9'],
            'win.copy-text': ['<Control><Shift>c'],
        }

        for action, accels in shortcuts.items():
            self.set_accels_for_action(action, accels)

593 594 595 596 597 598 599 600 601 602
    def _on_feature_discovered(self, event):
        if event.feature == nbxmpp.NS_VCARD:
            action = '%s-profile' % event.account
            self.lookup_action(action).set_enabled(True)
        elif event.feature in (nbxmpp.NS_MAM_1, nbxmpp.NS_MAM_2):
            action = '%s-archive' % event.account
            self.lookup_action(action).set_enabled(True)
        elif event.feature == nbxmpp.NS_PRIVACY:
            action = '%s-privacylists' % event.account
            self.lookup_action(action).set_enabled(True)
Philipp Hörist's avatar
Philipp Hörist committed
603 604 605
        elif event.feature == nbxmpp.NS_BLOCKING:
            action = '%s-blocking' % event.account
            self.lookup_action(action).set_enabled(True)
606

607
    def _screensaver_active(self, _application, _param):
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
        '''Signal handler for screensaver active change'''

        active = self.get_property('screensaver-active')

        roster = app.interface.roster

        if not active:
            for account in app.connections:
                if app.account_is_connected(account) and \
                        app.sleeper_state[account] == 'autoaway-forced':
                    # We came back online after screensaver autoaway
                    roster.send_status(account, 'online',
                                       app.status_before_autoaway[account])
                    app.status_before_autoaway[account] = ''
                    app.sleeper_state[account] = 'online'
            return
        if not app.config.get('autoaway'):
            # Don't go auto away if user disabled the option
            return
        for account in app.connections:
            if (account not in app.sleeper_state or
                    not app.sleeper_state[account]):
                continue
            if app.sleeper_state[account] == 'online':
                if not app.account_is_connected(account):
                    continue
                # we save our online status
                app.status_before_autoaway[account] = \
                    app.connections[account].status
                # we go away (no auto status) [we pass True to auto param]
                auto_message = app.config.get('autoaway_message')
                if not auto_message:
                    auto_message = app.connections[account].status
                else:
                    auto_message = auto_message.replace('$S', '%(status)s')
                    auto_message = auto_message.replace('$T', '%(time)s')
                    auto_message = auto_message % {
                        'status': app.status_before_autoaway[account],
                        'time': app.config.get('autoxatime')}
                roster.send_status(account, 'away', auto_message, auto=True)
                app.sleeper_state[account] = 'autoaway-forced'