disco.py 77.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# Copyright (C) 2005-2006 Stéphan Kochen <stephan AT kochen.nl>
# Copyright (C) 2005-2007 Nikos Kouremenos <kourem AT gmail.com>
# Copyright (C) 2005-2014 Yann Leboulanger <asterix AT lagaule.org>
# Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com>
# Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
# Copyright (C) 2007 Stephan Erb <steve-e AT h3c.de>
#
# 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/>.
Tanguy Ortolo's avatar
Tanguy Ortolo committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

# The appearance of the treeview, and parts of the dialog, are controlled by
# AgentBrowser (sub-)classes. Methods that probably should be overridden when
# subclassing are: (look at the docstrings and source for additional info)
# - def cleanup(self) *
# - def _create_treemodel(self) *
# - def _add_actions(self)
# - def _clean_actions(self)
# - def update_theme(self) *
# - def update_actions(self)
# - def default_action(self)
# - def _find_item(self, jid, node)
# - def _add_item(self, jid, node, parent_node, item, force)
# - def _update_item(self, iter_, jid, node, item)
# - def _update_info(self, iter_, jid, node, identities, features, data)
# - def _update_error(self, iter_, jid, node)
#
# * Should call the super class for this method.
# All others do not have to call back to the super class. (but can if they want
# the functionality)
# There are more methods, of course, but this is a basic set.

import types
import weakref
45 46

import nbxmpp
47 48 49 50 51 52 53 54 55 56 57
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf

from gajim import gtkgui_helpers
from gajim import groups
from gajim import adhoc_commands
from gajim import search_window

from gajim.common import app
58
from gajim.common.i18n import _
59
from gajim.common import helpers
60
from gajim.common.const import StyleAttr
61

62 63 64 65
from gajim.gtk.dialogs import ErrorDialog
from gajim.gtk.dialogs import InformationDialog
from gajim.gtk.service_registration import ServiceRegistration

66 67 68 69 70
LABELS = {
    1: _('This service has not yet responded with detailed information'),
    2: _('This service could not respond with detailed information.\n'
         'It is most likely legacy or broken'),
}
Tanguy Ortolo's avatar
Tanguy Ortolo committed
71 72 73 74 75 76

# Dictionary mapping category, type pairs to browser class, image pairs.
# This is a function, so we can call it after the classes are declared.
# For the browser class, None means that the service will only be browsable
# when it advertises disco as it's feature, False means it's never browsable.
def _gen_agent_type_info():
Tanguy Ortolo's avatar
Tanguy Ortolo committed
77
    return {
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
        # Defaults
        (0, 0):                         (None, None),

        # Jabber server
        ('server', 'im'):               (ToplevelAgentBrowser, 'jabber'),
        ('services', 'jabber'):         (ToplevelAgentBrowser, 'jabber'),
        ('hierarchy', 'branch'):        (AgentBrowser, 'jabber'),

        # Services
        ('conference', 'text'):         (MucBrowser, 'conference'),
        ('headline', 'rss'):            (AgentBrowser, 'rss'),
        ('headline', 'weather'):        (False, 'weather'),
        ('gateway', 'weather'):         (False, 'weather'),
        ('_jid', 'weather'):            (False, 'weather'),
        ('gateway', 'sip'):             (False, 'sip'),
        ('directory', 'user'):          (None, 'jud'),
        ('pubsub', 'generic'):          (PubSubBrowser, 'pubsub'),
        ('pubsub', 'service'):          (PubSubBrowser, 'pubsub'),
        ('proxy', 'bytestreams'):       (None, 'bytestreams'), # Socks5 FT proxy
        ('headline', 'newmail'):        (ToplevelAgentBrowser, 'mail'),

        # Transports
        ('conference', 'irc'):          (ToplevelAgentBrowser, 'irc'),
        ('_jid', 'irc'):                (False, 'irc'),
        ('gateway', 'irc'):             (False, 'irc'),
        ('gateway', 'gadu-gadu'):       (False, 'gadu-gadu'),
        ('_jid', 'gadugadu'):           (False, 'gadu-gadu'),
        ('gateway', 'http-ws'):         (False, 'http-ws'),
        ('gateway', 'icq'):             (False, 'icq'),
        ('_jid', 'icq'):                (False, 'icq'),
        ('gateway', 'sms'):             (False, 'sms'),
        ('_jid', 'sms'):                (False, 'sms'),
        ('gateway', 'smtp'):            (False, 'mail'),
        ('gateway', 'mrim'):            (False, 'mrim'),
        ('_jid', 'mrim'):               (False, 'mrim'),
        ('gateway', 'facebook'):        (False, 'facebook'),
        ('_jid', 'facebook'):           (False, 'facebook'),
        ('gateway', 'tv'):              (False, 'tv'),
        ('gateway', 'twitter'):         (False, 'twitter'),
Tanguy Ortolo's avatar
Tanguy Ortolo committed
117
    }
Tanguy Ortolo's avatar
Tanguy Ortolo committed
118

119
# Category type to "human-readable" description string
Tanguy Ortolo's avatar
Tanguy Ortolo committed
120
_cat_to_descr = {
121 122 123
        'other':                _('Others'),
        'gateway':              _('Transports'),
        '_jid':                 _('Transports'),
Tanguy Ortolo's avatar
Tanguy Ortolo committed
124
        #conference is a category for listing mostly groupchats in service discovery
125
        'conference':           _('Conference'),
Tanguy Ortolo's avatar
Tanguy Ortolo committed
126 127 128 129
}


class CacheDictionary:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
130 131 132
    """
    A dictionary that keeps items around for only a specific time.  Lifetime is
    in minutes. Getrefresh specifies whether to refresh when an item is merely
133
    accessed instead of set as well
Tanguy Ortolo's avatar
Tanguy Ortolo committed
134 135
    """

136
    def __init__(self, lifetime, getrefresh=True):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        self.lifetime = lifetime * 1000 * 60
        self.getrefresh = getrefresh
        self.cache = {}

    class CacheItem:
        """
        An object to store cache items and their timeouts
        """
        def __init__(self, value):
            self.value = value
            self.source = None

        def __call__(self):
            return self.value

    def cleanup(self):
153
        for key in list(self.cache.keys()):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
154 155
            item = self.cache[key]
            if item.source:
156
                GLib.source_remove(item.source)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
            del self.cache[key]

    def _expire_timeout(self, key):
        """
        The timeout has expired, remove the object
        """
        if key in self.cache:
            del self.cache[key]
        return False

    def _refresh_timeout(self, key):
        """
        The object was accessed, refresh the timeout
        """
        item = self.cache[key]
        if item.source:
173
            GLib.source_remove(item.source)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
174
        if self.lifetime:
175
            source = GLib.timeout_add_seconds(int(self.lifetime/1000), self._expire_timeout, key)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
            item.source = source

    def __getitem__(self, key):
        item = self.cache[key]
        if self.getrefresh:
            self._refresh_timeout(key)
        return item()

    def __setitem__(self, key, value):
        item = self.CacheItem(value)
        self.cache[key] = item
        self._refresh_timeout(key)

    def __delitem__(self, key):
        item = self.cache[key]
        if item.source:
192
            GLib.source_remove(item.source)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
193 194 195 196
        del self.cache[key]

    def __contains__(self, key):
        return key in self.cache
Tanguy Ortolo's avatar
Tanguy Ortolo committed
197 198 199

_icon_cache = CacheDictionary(15)

200
def get_agent_address(jid, node=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
201 202 203 204 205
    """
    Get an agent's address for displaying in the GUI
    """
    if node:
        return '%s@%s' % (node, str(jid))
206
    return str(jid)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
207

208
class Closure:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
209 210 211
    """
    A weak reference to a callback with arguments as an object

212
    Weak references to methods immediately die, even if the object is still
Tanguy Ortolo's avatar
Tanguy Ortolo committed
213 214 215 216 217 218
    alive. Besides a handy way to store a callback, this provides a workaround
    that keeps a reference to the object instead.

    Userargs and removeargs must be tuples.
    """

219
    def __init__(self, cb, userargs=(), remove=None, removeargs=()):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
220 221 222 223
        self.userargs = userargs
        self.remove = remove
        self.removeargs = removeargs
        if isinstance(cb, types.MethodType):
224 225
            self.meth_self = weakref.ref(cb.__self__, self._remove)
            self.meth_name = cb.__name__
Tanguy Ortolo's avatar
Tanguy Ortolo committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        elif callable(cb):
            self.meth_self = None
            self.cb = weakref.ref(cb, self._remove)
        else:
            raise TypeError('Object is not callable')

    def _remove(self, ref):
        if self.remove:
            self.remove(self, *self.removeargs)

    def __call__(self, *args, **kwargs):
        if self.meth_self:
            obj = self.meth_self()
            cb = getattr(obj, self.meth_name)
        else:
            cb = self.cb()
        args = args + self.userargs
        return cb(*args, **kwargs)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
244 245 246


class ServicesCache:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
247 248 249 250 251 252 253
    """
    Class that caches our query results. Each connection will have it's own
    ServiceCache instance
    """

    def __init__(self, account):
        self.account = account
254 255
        self._items = CacheDictionary(0, getrefresh=False)
        self._info = CacheDictionary(0, getrefresh=False)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        self._subscriptions = CacheDictionary(5, getrefresh=False)
        self._cbs = {}

    def cleanup(self):
        self._items.cleanup()
        self._info.cleanup()

    def _clean_closure(self, cb, type_, addr):
        # A closure died, clean up
        cbkey = (type_, addr)
        try:
            self._cbs[cbkey].remove(cb)
        except KeyError:
            return
        except ValueError:
            return
        # Clean an empty list
        if not self._cbs[cbkey]:
            del self._cbs[cbkey]

276
    def get_icon(self, identities=None, addr=''):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
277 278 279
        """
        Return the icon for an agent
        """
280 281
        if identities is None:
            identities = []
Tanguy Ortolo's avatar
Tanguy Ortolo committed
282
        # Grab the first identity with an icon
283
        quiet = False
Tanguy Ortolo's avatar
Tanguy Ortolo committed
284 285 286 287 288 289 290 291 292 293 294
        for identity in identities:
            try:
                cat, type_ = identity['category'], identity['type']
                info = _agent_type_info[(cat, type_)]
            except KeyError:
                continue
            filename = info[1]
            if filename:
                break
        else:
            # Loop fell through, default to unknown
295 296
            filename = addr.split('.')[0]
            quiet = True
Tanguy Ortolo's avatar
Tanguy Ortolo committed
297 298 299 300
        # Use the cache if possible
        if filename in _icon_cache:
            return _icon_cache[filename]
        # Or load it
301 302 303 304 305 306 307 308 309 310
        pix = gtkgui_helpers.get_icon_pixmap('gajim-agent-' + filename, size=32,
            quiet=quiet)
        if pix:
            # Store in cache
            _icon_cache[filename] = pix
            return pix
        if 'jabber' in _icon_cache:
            return _icon_cache['jabber']
        pix = gtkgui_helpers.get_icon_pixmap('gajim-agent-jabber', size=32)
        _icon_cache['jabber'] = pix
Tanguy Ortolo's avatar
Tanguy Ortolo committed
311 312
        return pix

313
    def get_browser(self, identities=None, features=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
314 315 316
        """
        Return the browser class for an agent
        """
317 318 319 320
        if identities is None:
            identities = []
        if features is None:
            features = []
Tanguy Ortolo's avatar
Tanguy Ortolo committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
        # First pass, we try to find a ToplevelAgentBrowser
        for identity in identities:
            try:
                cat, type_ = identity['category'], identity['type']
                info = _agent_type_info[(cat, type_)]
            except KeyError:
                continue
            browser = info[0]
            if browser and browser == ToplevelAgentBrowser:
                return browser

        # second pass, we haven't found a ToplevelAgentBrowser
        for identity in identities:
            try:
                cat, type_ = identity['category'], identity['type']
                info = _agent_type_info[(cat, type_)]
            except KeyError:
                continue
            browser = info[0]
            if browser:
                return browser
        # NS_BROWSE is deprecated, but we check for it anyways.
        # Some services list it in features and respond to
        # NS_DISCO_ITEMS anyways.
345
        # Allow browsing for unknown types as well.
Tanguy Ortolo's avatar
Tanguy Ortolo committed
346
        if (not features and not identities) or \
347
        nbxmpp.NS_DISCO_ITEMS in features or nbxmpp.NS_BROWSE in features:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
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
            return ToplevelAgentBrowser
        return None

    def get_info(self, jid, node, cb, force=False, nofetch=False, args=()):
        """
        Get info for an agent
        """
        addr = get_agent_address(jid, node)
        # Check the cache
        if addr in self._info and not force:
            args = self._info[addr] + args
            cb(jid, node, *args)
            return
        if nofetch:
            return

        # Create a closure object
        cbkey = ('info', addr)
        cb = Closure(cb, userargs=args, remove=self._clean_closure,
            removeargs=cbkey)
        # Are we already fetching this?
        if cbkey in self._cbs:
            self._cbs[cbkey].append(cb)
        else:
            self._cbs[cbkey] = [cb]
373 374 375
            con = app.connections[self.account]
            con.get_module('Discovery').disco_info(
                jid, node, self._disco_info_received, self._disco_info_error)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

    def get_items(self, jid, node, cb, force=False, nofetch=False, args=()):
        """
        Get a list of items in an agent
        """
        addr = get_agent_address(jid, node)
        # Check the cache
        if addr in self._items and not force:
            args = (self._items[addr],) + args
            cb(jid, node, *args)
            return
        if nofetch:
            return

        # Create a closure object
        cbkey = ('items', addr)
        cb = Closure(cb, userargs=args, remove=self._clean_closure,
393
                     removeargs=cbkey)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
394 395 396 397 398
        # Are we already fetching this?
        if cbkey in self._cbs:
            self._cbs[cbkey].append(cb)
        else:
            self._cbs[cbkey] = [cb]
399 400 401
            con = app.connections[self.account]
            con.get_module('Discovery').disco_items(
                jid, node, self._disco_items_received, self._disco_items_error)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
402

403
    def _disco_info_received(self, from_, identities, features, data, node):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
404 405 406 407
        """
        Callback for when we receive an agent's info
        array is (agent, node, identities, features, data)
        """
Martin's avatar
Martin committed
408 409 410 411
        if not identities:
            # Ejabberd doesn't send identities when using admin nodes
            identities = [{'category': 'server', 'type': 'im', 'name': node}]

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        self._on_agent_info(str(from_), node, identities, features, data)

    def _disco_info_error(self, from_, error):
        """
        Callback for when a query fails. Even after the browse and agents
        namespaces
        """
        addr = get_agent_address(from_)

        # Call callbacks
        cbkey = ('info', addr)
        if cbkey in self._cbs:
            for cb in self._cbs[cbkey]:
                cb(str(from_), '', 0, 0, 0)
            # clean_closure may have beaten us to it
            if cbkey in self._cbs:
                del self._cbs[cbkey]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

    def _on_agent_info(self, fjid, node, identities, features, data):
        addr = get_agent_address(fjid, node)

        # Store in cache
        self._info[addr] = (identities, features, data)

        # Call callbacks
        cbkey = ('info', addr)
        if cbkey in self._cbs:
            for cb in self._cbs[cbkey]:
                cb(fjid, node, identities, features, data)
            # clean_closure may have beaten us to it
            if cbkey in self._cbs:
                del self._cbs[cbkey]

445
    def _disco_items_received(self, from_, node, items):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
446 447 448 449
        """
        Callback for when we receive an agent's items
        array is (agent, node, items)
        """
450
        addr = get_agent_address(from_, node)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
451 452

        # Store in cache
453
        self._items[addr] = items
Tanguy Ortolo's avatar
Tanguy Ortolo committed
454 455 456 457 458

        # Call callbacks
        cbkey = ('items', addr)
        if cbkey in self._cbs:
            for cb in self._cbs[cbkey]:
459
                cb(str(from_), node, items)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
460 461 462 463
            # clean_closure may have beaten us to it
            if cbkey in self._cbs:
                del self._cbs[cbkey]

464
    def _disco_items_error(self, from_, error):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
465 466 467 468
        """
        Callback for when a query fails. Even after the browse and agents
        namespaces
        """
469
        addr = get_agent_address(from_)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
470 471 472 473 474

        # Call callbacks
        cbkey = ('items', addr)
        if cbkey in self._cbs:
            for cb in self._cbs[cbkey]:
475
                cb(str(from_), '', 0)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
476 477 478
            # clean_closure may have beaten us to it
            if cbkey in self._cbs:
                del self._cbs[cbkey]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
479

480

481
class ServiceDiscoveryWindow:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
482 483 484 485 486 487
    """
    Class that represents the Services Discovery window
    """

    def __init__(self, account, jid='', node='', address_entry=False,
    parent=None, initial_identities=None):
488
        self._account = account
Tanguy Ortolo's avatar
Tanguy Ortolo committed
489 490
        self.parent = parent
        if not jid:
491
            jid = app.config.get_per('accounts', account, 'hostname')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
492 493 494 495 496 497 498 499 500 501
            node = ''

        self.jid = None
        self.browser = None
        self.children = []
        self.dying = False
        self.node = None
        self.reloading = False

        # Check connection
502
        if app.connections[account].connected < 2:
503
            ErrorDialog(_('You are not connected to the server'),
Tanguy Ortolo's avatar
Tanguy Ortolo committed
504
_('Without a connection, you can not browse available services'))
505
            raise RuntimeError('You must be connected to browse services')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
506 507 508

        # Get a ServicesCache object.
        try:
509
            self.cache = app.connections[account].services_cache
Tanguy Ortolo's avatar
Tanguy Ortolo committed
510 511
        except AttributeError:
            self.cache = ServicesCache(account)
512
            app.connections[account].services_cache = self.cache
Tanguy Ortolo's avatar
Tanguy Ortolo committed
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

        if initial_identities:
            self.cache._on_agent_info(jid, node, initial_identities, [], None)
        self.xml = gtkgui_helpers.get_gtk_builder('service_discovery_window.ui')
        self.window = self.xml.get_object('service_discovery_window')
        self.services_treeview = self.xml.get_object('services_treeview')
        self.model = None
        # This is more reliable than the cursor-changed signal.
        selection = self.services_treeview.get_selection()
        selection.connect_after('changed',
                self.on_services_treeview_selection_changed)
        self.services_scrollwin = self.xml.get_object('services_scrollwin')
        self.progressbar = self.xml.get_object('services_progressbar')
        self.banner = self.xml.get_object('banner_agent_label')
        self.banner_icon = self.xml.get_object('banner_agent_icon')
        self.banner_eventbox = self.xml.get_object('banner_agent_eventbox')
        self.style_event_id = 0
        self.banner.realize()
        self.action_buttonbox = self.xml.get_object('action_buttonbox')

        # Address combobox
534
        self.address_comboboxtext = None
Tanguy Ortolo's avatar
Tanguy Ortolo committed
535 536
        address_table = self.xml.get_object('address_table')
        if address_entry:
537 538 539 540
            self.address_comboboxtext = self.xml.get_object(
                'address_comboboxtext')
            self.address_comboboxtext_entry = self.xml.get_object(
                'address_entry')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
541

542
            self.latest_addresses = app.config.get(
Tanguy Ortolo's avatar
Tanguy Ortolo committed
543 544 545 546 547 548 549
                'latest_disco_addresses').split()
            if jid in self.latest_addresses:
                self.latest_addresses.remove(jid)
            self.latest_addresses.insert(0, jid)
            if len(self.latest_addresses) > 10:
                self.latest_addresses = self.latest_addresses[0:10]
            for j in self.latest_addresses:
550 551
                self.address_comboboxtext.append_text(j)
            self.address_comboboxtext.get_child().set_text(jid)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
552 553 554 555 556
        else:
            # Don't show it at all if we didn't ask for it
            address_table.set_no_show_all(True)
            address_table.hide()

557 558 559
        accel_group = Gtk.AccelGroup()
        keyval, mod = Gtk.accelerator_parse('<Control>r')
        accel_group.connect(keyval, mod, Gtk.AccelFlags.VISIBLE,
Tanguy Ortolo's avatar
Tanguy Ortolo committed
560 561 562 563 564 565 566 567 568
            self.accel_group_func)
        self.window.add_accel_group(accel_group)

        self._initial_state()
        self.xml.connect_signals(self)
        self.travel(jid, node)
        self.window.show_all()

    @property
569 570
    def account(self):
        return self._account
Tanguy Ortolo's avatar
Tanguy Ortolo committed
571

572 573 574
    @account.setter
    def account(self, value):
        self._account = value
Tanguy Ortolo's avatar
Tanguy Ortolo committed
575 576 577 578
        self.cache.account = value
        if self.browser:
            self.browser.account = value

579 580 581 582
    def on_key_press_event(self, widget, event):
        if event.keyval == Gdk.KEY_Escape:
            self.window.destroy()

Tanguy Ortolo's avatar
Tanguy Ortolo committed
583
    def accel_group_func(self, accel_group, acceleratable, keyval, modifier):
584
        if (modifier & Gdk.ModifierType.CONTROL_MASK) and (keyval == Gdk.KEY_r):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598
            self.reload()

    def _initial_state(self):
        """
        Set some initial state on the window. Separated in a method because it's
        handy to use within browser's cleanup method
        """
        self.progressbar.hide()
        title_text = _('Service Discovery using account %s') % self.account
        self.window.set_title(title_text)
        self._set_window_banner_text(_('Service Discovery'))
        self.banner_icon.clear()
        self.banner_icon.hide() # Just clearing it doesn't work

599 600 601 602
    def _set_window_banner_text(self, text, text_after=None):
        markup = '<span>%s</span>' % (text)
        if text_after is not None:
            markup += '\n<span size="x-small">%s</span>' % text_after
Tanguy Ortolo's avatar
Tanguy Ortolo committed
603 604
        self.banner.set_markup(markup)

605
    def destroy(self, chain=False):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
606 607 608 609 610 611 612 613 614 615 616
        """
        Close the browser. This can optionally close its children and propagate
        to the parent. This should happen on actions like register, or join to
        kill off the entire browser chain
        """
        if self.dying:
            return
        self.dying = True

        # self.browser._get_agent_address() would break when no browser.
        addr = get_agent_address(self.jid, self.node)
617 618
        if addr in app.interface.instances[self.account]['disco']:
            del app.interface.instances[self.account]['disco'][addr]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
619 620 621 622 623 624 625 626 627 628

        if self.browser:
            self.window.hide()
            self.browser.cleanup()
            self.browser = None
        self.window.destroy()

        for child in self.children[:]:
            child.parent = None
            if chain:
629
                child.destroy(chain=chain)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
630 631 632 633 634
                self.children.remove(child)
        if self.parent:
            if self in self.parent.children:
                self.parent.children.remove(self)
            if chain and not self.parent.children:
635
                self.parent.destroy(chain=chain)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                self.parent = None
        else:
            self.cache.cleanup()

    def reload(self):
        if not self.jid:
            return
        self.reloading = True
        self.travel(self.jid, self.node)

    def travel(self, jid, node):
        """
        Travel to an agent within the current services window
        """
        if self.browser:
            self.browser.cleanup()
            self.browser = None
        # Update the window list
        if self.jid:
            old_addr = get_agent_address(self.jid, self.node)
656 657
            if old_addr in app.interface.instances[self.account]['disco']:
                del app.interface.instances[self.account]['disco'][old_addr]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
658
        addr = get_agent_address(jid, node)
659
        app.interface.instances[self.account]['disco'][addr] = self
Tanguy Ortolo's avatar
Tanguy Ortolo committed
660 661 662 663 664 665 666 667 668 669 670 671
        # We need to store these, self.browser is not always available.
        self.jid = jid
        self.node = node
        self.cache.get_info(jid, node, self._travel, force=self.reloading)

    def _travel(self, jid, node, identities, features, data):
        """
        Continuation of travel
        """
        if self.dying or jid != self.jid or node != self.node:
            return
        if not identities:
672
            if not self.address_comboboxtext:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
673 674
                # We can't travel anywhere else.
                self.destroy()
675 676
            ErrorDialog(
                _('The service could not be found'),
677
                _('There is no service at the address you entered, or it is '
678
                  'not responding. Check the address and try again.'),
679
                transient_for=self.window)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
680 681 682
            return
        klass = self.cache.get_browser(identities, features)
        if not klass:
683 684
            ErrorDialog(
                _('The service is not browsable'),
685 686
                _('This type of service does not contain any items to browse.'),
                transient_for=self.window)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
687
            return
688
        if klass is None:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
689 690 691 692 693 694 695 696 697 698 699
            klass = AgentBrowser
        self.browser = klass(self.account, jid, node)
        self.browser.prepare_window(self)
        self.browser.browse(force=self.reloading)
        self.reloading = False

    def open(self, jid, node):
        """
        Open an agent. By default, this happens in a new window
        """
        try:
700
            win = app.interface.instances[self.account]['disco']\
Tanguy Ortolo's avatar
Tanguy Ortolo committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
                    [get_agent_address(jid, node)]
            win.window.present()
            return
        except KeyError:
            pass
        try:
            win = ServiceDiscoveryWindow(self.account, jid, node, parent=self)
        except RuntimeError:
            # Disconnected, perhaps
            return
        self.children.append(win)

    def on_service_discovery_window_destroy(self, widget):
        self.destroy()

    def on_close_button_clicked(self, widget):
        self.destroy()

719 720
    def on_address_comboboxtext_changed(self, widget):
        if self.address_comboboxtext.get_active() != -1:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
721
            # user selected one of the entries so do auto-visit
722
            jid = self.address_comboboxtext_entry.get_text()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
723 724
            try:
                jid = helpers.parse_jid(jid)
725
            except helpers.InvalidFormat as s:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
726
                pritext = _('Invalid Server Name')
727
                ErrorDialog(pritext, str(s))
Tanguy Ortolo's avatar
Tanguy Ortolo committed
728 729 730 731
                return
            self.travel(jid, '')

    def on_go_button_clicked(self, widget):
732
        jid = self.address_comboboxtext_entry.get_text()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
733 734
        try:
            jid = helpers.parse_jid(jid)
735
        except helpers.InvalidFormat as s:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
736
            pritext = _('Invalid Server Name')
737
            ErrorDialog(pritext, str(s),
738
                transient_for=self.window)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
739 740 741 742 743 744 745 746
            return
        if jid == self.jid: # jid has not changed
            return
        if jid in self.latest_addresses:
            self.latest_addresses.remove(jid)
        self.latest_addresses.insert(0, jid)
        if len(self.latest_addresses) > 10:
            self.latest_addresses = self.latest_addresses[0:10]
747
        self.address_comboboxtext.get_model().clear()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
748
        for j in self.latest_addresses:
749 750
            self.address_comboboxtext.append_text(j)
        app.config.set('latest_disco_addresses',
Tanguy Ortolo's avatar
Tanguy Ortolo committed
751 752 753
                ' '.join(self.latest_addresses))
        self.travel(jid, '')

754
    def on_services_treeview_row_activated(self, widget, path, col=0):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
755 756 757 758 759 760
        if self.browser:
            self.browser.default_action()

    def on_services_treeview_selection_changed(self, widget):
        if self.browser:
            self.browser.update_actions()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
761

762 763 764 765
    def _on_entry_key_press_event(self, widget, event):
        if event.keyval == Gdk.KEY_Return or event.keyval == Gdk.KEY_KP_Enter:
            self.on_go_button_clicked(widget)

Tanguy Ortolo's avatar
Tanguy Ortolo committed
766 767

class AgentBrowser:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
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
    """
    Class that deals with browsing agents and appearance of the browser window.
    This class and subclasses should basically be treated as "part" of the
    ServiceDiscoveryWindow class, but had to be separated because this part is
    dynamic
    """

    def __init__(self, account, jid, node):
        self.account = account
        self.jid = jid
        self.node = node
        self._total_items = 0
        self.browse_button = None
        # This is for some timeout callbacks
        self.active = False

    def _get_agent_address(self):
        """
        Get the agent's address for displaying in the GUI
        """
        return get_agent_address(self.jid, self.node)

    def _set_initial_title(self):
        """
        Set the initial window title based on agent address
        """
        self.window.window.set_title(_('Browsing %(address)s using account '
                '%(account)s') % {'address': self._get_agent_address(),
                'account': self.account})
        self.window._set_window_banner_text(self._get_agent_address())

    def _create_treemodel(self):
        """
        Create the treemodel for the services treeview. When subclassing, note
        that the first two columns should ALWAYS be of type string and contain
        the JID and node of the item respectively
        """
        # JID, node, name, address
806 807
        self.model = Gtk.ListStore(str, str, str, str)
        self.model.set_sort_column_id(3, Gtk.SortType.ASCENDING)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
808 809
        self.window.services_treeview.set_model(self.model)
        # Name column
810 811 812 813
        col = Gtk.TreeViewColumn(_('Name'))
        renderer = Gtk.CellRendererText()
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', 2)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
814 815 816
        self.window.services_treeview.insert_column(col, -1)
        col.set_resizable(True)
        # Address column
817 818 819 820
        col = Gtk.TreeViewColumn(_('JID'))
        renderer = Gtk.CellRendererText()
        col.pack_start(renderer, True)
        col.add_attribute(renderer, 'text', 3)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
        self.window.services_treeview.insert_column(col, -1)
        col.set_resizable(True)
        self.window.services_treeview.set_headers_visible(True)

    def _clean_treemodel(self):
        self.model.clear()
        for col in self.window.services_treeview.get_columns():
            self.window.services_treeview.remove_column(col)
        self.window.services_treeview.set_headers_visible(False)

    def _add_actions(self):
        """
        Add the action buttons to the buttonbox for actions the browser can
        perform
        """
836
        self.browse_button = Gtk.Button()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
837 838
        self.browse_button.connect('clicked', self.on_browse_button_clicked)
        self.window.action_buttonbox.add(self.browse_button)
839
        image = Gtk.Image.new_from_icon_name("document-open", Gtk.IconSize.BUTTON)
840
        self.browse_button.set_image(image)
841
        label = _('Browse')
842
        self.browse_button.set_label(label)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        self.browse_button.show_all()

    def _clean_actions(self):
        """
        Remove the action buttons specific to this browser
        """
        if self.browse_button:
            self.browse_button.destroy()
            self.browse_button = None

    def _set_title(self, jid, node, identities, features, data):
        """
        Set the window title based on agent info
        """
        # Set the banner and window title
858 859 860
        name = ''
        if len(identities) > 1:
            # Check if an identity with server category is present
861 862 863
            for _index, identity in enumerate(identities):
                if identity['category'] == 'server' and 'name' in identity:
                    name = identity['name']
864 865 866 867 868
                    break
                elif 'name' in identities[0]:
                    name = identities[0]['name']

        if name:
869
            self.window._set_window_banner_text(self._get_agent_address(), name)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
870 871

        # Add an icon to the banner.
872
        pix = self.cache.get_icon(identities, addr=self._get_agent_address())
Tanguy Ortolo's avatar
Tanguy Ortolo committed
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        self.window.banner_icon.set_from_pixbuf(pix)
        self.window.banner_icon.show()

    def _clean_title(self):
        # Everything done here is done in window._initial_state
        # This is for subclasses.
        pass

    def prepare_window(self, window):
        """
        Prepare the service discovery window. Called when a browser is hooked up
        with a ServiceDiscoveryWindow instance
        """
        self.window = window
        self.cache = window.cache

        self._set_initial_title()
        self._create_treemodel()
        self._add_actions()

        # This is a hack. The buttonbox apparently doesn't care about pack_start
        # or pack_end, so we repack the close button here to make sure it's last
        close_button = self.window.xml.get_object('close_button')
        self.window.action_buttonbox.remove(close_button)
897
        self.window.action_buttonbox.pack_end(close_button, True, True, 0)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
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
        close_button.show_all()

        self.update_actions()

        self.active = True
        self.cache.get_info(self.jid, self.node, self._set_title)

    def cleanup(self):
        """
        Cleanup when the window intends to switch browsers
        """
        self.active = False

        self._clean_actions()
        self._clean_treemodel()
        self._clean_title()

        self.window._initial_state()

    def update_theme(self):
        """
        Called when the default theme is changed
        """
        pass

923
    def on_browse_button_clicked(self, widget=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
924 925 926 927 928 929 930
        """
        When we want to browse an agent: open a new services window with a
        browser for the agent type
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
931
        jid = model[iter_][0]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
932
        if jid:
933
            node = model[iter_][1]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
934 935 936 937 938 939 940 941 942 943 944
            self.window.open(jid, node)

    def update_actions(self):
        """
        When we select a row: activate action buttons based on the agent's info
        """
        if self.browse_button:
            self.browse_button.set_sensitive(False)
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
945 946
        jid = model[iter_][0]
        node = model[iter_][1]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
947
        if jid:
948
            self.cache.get_info(jid, node, self._update_actions, nofetch=True)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

    def _update_actions(self, jid, node, identities, features, data):
        """
        Continuation of update_actions
        """
        if not identities or not self.browse_button:
            return
        klass = self.cache.get_browser(identities, features)
        if klass:
            self.browse_button.set_sensitive(True)

    def default_action(self):
        """
        When we double-click a row: perform the default action on the selected
        item
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
968 969
        jid = model[iter_][0]
        node = model[iter_][1]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
970
        if jid:
971
            self.cache.get_info(jid, node, self._default_action, nofetch=True)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989

    def _default_action(self, jid, node, identities, features, data):
        """
        Continuation of default_action
        """
        if self.cache.get_browser(identities, features):
            # Browse if we can
            self.on_browse_button_clicked()
            return True
        return False

    def browse(self, force=False):
        """
        Fill the treeview with agents, fetching the info if necessary
        """
        self.model.clear()
        self._total_items = self._progress = 0
        self.window.progressbar.show()
990
        self._pulse_timeout = GLib.timeout_add(250, self._pulse_timeout_cb)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
        self.cache.get_items(self.jid, self.node, self._agent_items,
                force=force, args=(force,))

    def _pulse_timeout_cb(self, *args):
        """
        Simple callback to keep the progressbar pulsing
        """
        if not self.active:
            return False
        self.window.progressbar.pulse()
        return True

    def _find_item(self, jid, node):
        """
        Check if an item is already in the treeview. Return an iter to it if so,
        None otherwise
        """
1008
        iter_ = self.model.get_iter_first()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1009
        while iter_:
1010 1011
            cjid = self.model.get_value(iter_, 0)
            cnode = self.model.get_value(iter_, 1)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1012 1013 1014 1015 1016 1017 1018
            if jid == cjid and node == cnode:
                break
            iter_ = self.model.iter_next(iter_)
        if iter_:
            return iter_
        return None

1019 1020 1021
    def add_self_line(self):
        pass

Tanguy Ortolo's avatar
Tanguy Ortolo committed
1022 1023 1024 1025 1026
    def _agent_items(self, jid, node, items, force):
        """
        Callback for when we receive a list of agent items
        """
        self.model.clear()
1027
        self.add_self_line()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1028
        self._total_items = 0
1029
        GLib.source_remove(self._pulse_timeout)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1030 1031 1032
        self.window.progressbar.hide()
        # The server returned an error
        if items == 0:
1033
            if not self.window.address_comboboxtext:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1034 1035
                # We can't travel anywhere else.
                self.window.destroy()
1036
            ErrorDialog(_('The service is not browsable'),
1037 1038
                _('This service does not contain any items to browse.'),
                transient_for=self.window.window)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1039 1040
            return
        # We got a list of items
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
        def fill_partial_rows(items):
            '''Generator to fill the listmodel of a treeview progressively.'''
            self.window.services_treeview.freeze_child_notify()
            for item in items:
                if self.window.dying:
                    yield False
                jid_ = item['jid']
                node_ = item.get('node', '')
                # If such an item is already here: don't add it
                if self._find_item(jid_, node_):
                    continue
                self._total_items += 1
                self._add_item(jid_, node_, node, item, force)
                if (self._total_items % 10) == 0:
                    self.window.services_treeview.thaw_child_notify()
                    yield True
                    self.window.services_treeview.freeze_child_notify()
            self.window.services_treeview.thaw_child_notify()
            #stop idle_add()
            yield False
        loader = fill_partial_rows(items)
1062
        GLib.idle_add(next, loader)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

    def _agent_info(self, jid, node, identities, features, data):
        """
        Callback for when we receive info about an agent's item
        """
        iter_ = self._find_item(jid, node)
        if not iter_:
            # Not in the treeview, stop
            return
        if identities == 0:
            # The server returned an error
            self._update_error(iter_, jid, node)
        else:
            # We got our info
            self._update_info(iter_, jid, node, identities, features, data)
        self.update_actions()

    def _add_item(self, jid, node, parent_node, item, force):
        """
        Called when an item should be added to the model. The result of a
        disco#items query
        """
        self.model.append((jid, node, item.get('name', ''),
                get_agent_address(jid, node)))
1087
        self.cache.get_info(jid, node, self._agent_info, force=force)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

    def _update_item(self, iter_, jid, node, item):
        """
        Called when an item should be updated in the model. The result of a
        disco#items query
        """
        if 'name' in item:
            self.model[iter_][2] = item['name']

    def _update_info(self, iter_, jid, node, identities, features, data):
        """
        Called when an item should be updated in the model with further info.
        The result of a disco#info query
        """
        name = identities[0].get('name', '')
        if name:
            self.model[iter_][2] = name

    def _update_error(self, iter_, jid, node):
        '''Called when a disco#info query failed for an item.'''
        pass
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1109 1110 1111


class ToplevelAgentBrowser(AgentBrowser):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    """
    This browser is used at the top level of a jabber server to browse services
    such as transports, conference servers, etc
    """

    def __init__(self, *args):
        AgentBrowser.__init__(self, *args)
        self._progressbar_sourceid = None
        self._renderer = None
        self._progress = 0
        self.register_button = None
        self.join_button = None
        self.execute_button = None
        self.search_button = None
        # Keep track of our treeview signals
        self._view_signals = []
        self._scroll_signal = None

1130 1131 1132 1133 1134
    def add_self_line(self):
        addr = get_agent_address(self.jid, self.node)
        descr = "<b>%s</b>" % addr
        # Guess which kind of service this is
        identities = []
1135
        type_ = app.get_transport_name_from_jid(self.jid,
1136 1137 1138 1139 1140 1141
            use_config_setting=False)
        if type_:
            identity = {'category': '_jid', 'type': type_}
            identities.append(identity)
        # Set the pixmap for the row
        pix = self.cache.get_icon(identities, addr=addr)
1142
        self.model.append(None, (self.jid, self.node, pix, descr, LABELS[1]))
1143 1144 1145
        # Grab info on the service
        self.cache.get_info(self.jid, self.node, self._agent_info, force=False)

1146
    def _pixbuf_renderer_data_func(self, col, cell, model, iter_, data=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        """
        Callback for setting the pixbuf renderer's properties
        """
        jid = model.get_value(iter_, 0)
        if jid:
            pix = model.get_value(iter_, 2)
            cell.set_property('visible', True)
            cell.set_property('pixbuf', pix)
        else:
            cell.set_property('visible', False)

1158
    def _text_renderer_data_func(self, col, cell, model, iter_, data=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1159 1160 1161 1162 1163 1164 1165 1166 1167
        """
        Callback for setting the text renderer's properties
        """
        jid = model.get_value(iter_, 0)
        markup = model.get_value(iter_, 3)
        state = model.get_value(iter_, 4)
        cell.set_property('markup', markup)
        if jid:
            cell.set_property('cell_background_set', False)
1168 1169
            if state is not None:
                # fetching or error
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1170 1171
                cell.set_property('foreground_set', True)
            else:
1172
                # Normal/success
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1173 1174
                cell.set_property('foreground_set', False)
        else:
1175
            bgcolor = app.css_config.get_value('.gajim-group-row', StyleAttr.BACKGROUND)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1176 1177 1178 1179
            if bgcolor:
                cell.set_property('cell_background_set', True)
            cell.set_property('foreground_set', False)

1180
    def _treemodel_sort_func(self, model, iter1, iter2, data=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1181 1182 1183 1184
        """
        Sort function for our treemode
        """
        # Compare state
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        state1 = model.get_value(iter1, 4)
        state2 = model.get_value(iter2, 4)
        if state1 is not None:
            return 1
        if state2 is not None:
            return -1
        descr1 = model.get_value(iter1, 3)
        descr2 = model.get_value(iter2, 3)
        # Compare strings
        if descr1 > descr2:
            return 1
        if descr1 < descr2:
            return -1
        return 0
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1199 1200 1201

    def _create_treemodel(self):
        # JID, node, icon, description, state
1202
        # state is None on success or has a string
1203
        # from LABELS on error or while fetching
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1204
        view = self.window.services_treeview
1205
        self.model = Gtk.TreeStore(str, str, GdkPixbuf.Pixbuf, str, str)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1206
        self.model.set_sort_func(4, self._treemodel_sort_func)
1207
        self.model.set_sort_column_id(4, Gtk.SortType.ASCENDING)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1208 1209
        view.set_model(self.model)

1210
        col = Gtk.TreeViewColumn()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1211
        # Icon Renderer
1212
        renderer = Gtk.CellRendererPixbuf()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1213
        renderer.set_property('xpad', 6)
1214
        col.pack_start(renderer, False)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1215 1216
        col.set_cell_data_func(renderer, self._pixbuf_renderer_data_func)
        # Text Renderer
1217 1218
        renderer = Gtk.CellRendererText()
        col.pack_start(renderer, True)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1219 1220 1221 1222 1223 1224
        col.set_cell_data_func(renderer, self._text_renderer_data_func)
        renderer.set_property('foreground', 'dark gray')
        # Save this so we can go along with theme changes
        self._renderer = renderer
        self.update_theme()

1225
        view.set_tooltip_column(4)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        view.insert_column(col, -1)
        col.set_resizable(True)

    def _clean_treemodel(self):
        # Disconnect signals
        view = self.window.services_treeview
        for sig in self._view_signals:
            view.disconnect(sig)
        self._view_signals = []
        if self._scroll_signal:
            scrollwin = self.window.services_scrollwin
            scrollwin.disconnect(self._scroll_signal)
            self._scroll_signal = None
        AgentBrowser._clean_treemodel(self)

    def _add_actions(self):
        AgentBrowser._add_actions(self)
1243
        self.execute_button = Gtk.Button()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1244 1245
        self.execute_button.connect('clicked', self.on_execute_button_clicked)
        self.window.action_buttonbox.add(self.execute_button)
1246
        image = Gtk.Image.new_from_icon_name("system-run", Gtk.IconSize.BUTTON)
1247
        self.execute_button.set_image(image)
1248
        label = _('Execute Command')
1249
        self.execute_button.set_label(label)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1250 1251
        self.execute_button.show_all()

1252
        self.register_button = Gtk.Button(label=_("Re_gister"),
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1253 1254 1255 1256 1257
                use_underline=True)
        self.register_button.connect('clicked', self.on_register_button_clicked)
        self.window.action_buttonbox.add(self.register_button)
        self.register_button.show_all()

1258
        self.join_button = Gtk.Button()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1259 1260
        self.join_button.connect('clicked', self.on_join_button_clicked)
        self.window.action_buttonbox.add(self.join_button)
1261
        label = _('Join')
1262
        self.join_button.set_label(label)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1263 1264
        self.join_button.show_all()

1265
        self.search_button = Gtk.Button()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1266 1267
        self.search_button.connect('clicked', self.on_search_button_clicked)
        self.window.action_buttonbox.add(self.search_button)
1268
        image = Gtk.Image.new_from_icon_name("edit-find", Gtk.IconSize.BUTTON)
1269
        self.search_button.set_image(image)
1270
        label = _('Search')
1271
        self.search_button.set_label(label)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
        self.search_button.show_all()

    def _clean_actions(self):
        if self.execute_button:
            self.execute_button.destroy()
            self.execute_button = None
        if self.register_button:
            self.register_button.destroy()
            self.register_button = None
        if self.join_button:
            self.join_button.destroy()
            self.join_button = None
        if self.search_button:
            self.search_button.destroy()
            self.search_button = None
        AgentBrowser._clean_actions(self)

1289
    def on_search_button_clicked(self, widget=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1290 1291 1292 1293 1294 1295
        """
        When we want to search something: open search window
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
1296 1297 1298
        service = model[iter_][0]
        if service in app.interface.instances[self.account]['search']:
            app.interface.instances[self.account]['search'][service].window.\
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1299 1300
                    present()
        else:
1301
            app.interface.instances[self.account]['search'][service] = \
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1302 1303 1304 1305 1306 1307
                    search_window.SearchWindow(self.account, service)

    def cleanup(self):
        AgentBrowser.cleanup(self)

    def update_theme(self):
1308
        bgcolor = app.css_config.get_value('.gajim-group-row', StyleAttr.BACKGROUND)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
        if bgcolor:
            self._renderer.set_property('cell-background', bgcolor)
        self.window.services_treeview.queue_draw()

    def on_execute_button_clicked(self, widget=None):
        """
        When we want to execute a command: open adhoc command window
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
1320 1321
        service = model[iter_][0]
        node = model[iter_][1]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1322 1323
        adhoc_commands.CommandWindow(self.account, service, commandnode=node)

1324
    def on_register_button_clicked(self, widget=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1325 1326 1327 1328 1329 1330 1331
        """
        When we want to register an agent: request information about registering
        with the agent and close the window
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
1332
        jid = model[iter_][0]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1333
        if jid:
1334 1335
            ServiceRegistration(self.account, jid)
            self.window.destroy(chain=True)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1336 1337 1338 1339 1340 1341 1342 1343 1344

    def on_join_button_clicked(self, widget):
        """
        When we want to join an IRC room or create a new MUC room: Opens the
        join_groupchat_window
        """
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
1345
        service = model[iter_][0]
Martin's avatar
Martin committed
1346 1347
        app.interface.join_gc_minimal(self.account, service,
            transient_for=self.window.window)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

    def update_actions(self):
        if self.execute_button:
            self.execute_button.set_sensitive(False)
        if self.register_button:
            self.register_button.set_sensitive(False)
        if self.browse_button:
            self.browse_button.set_sensitive(False)
        if self.join_button:
            self.join_button.set_sensitive(False)
        if self.search_button:
            self.search_button.set_sensitive(False)
        model, iter_ = self.window.services_treeview.get_selection().get_selected()
        if not iter_:
            return
        if not model[iter_][0]:
            # We're on a category row
            return
1366
        if model[iter_][4] is not None:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1367 1368 1369 1370 1371 1372
            # We don't have the info (yet)
            # It's either unknown or a transport, register button should be active
            if self.register_button:
                self.register_button.set_sensitive(True)
            # Guess what kind of service we're dealing with
            if self.browse_button:
1373
                jid = model[iter_][0]
1374 1375
                type_ = app.get_transport_name_from_jid(
                    jid, use_config_setting=False)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
                if type_:
                    identity = {'category': '_jid', 'type': type_}
                    klass = self.cache.get_browser([identity])
                    if klass:
                        self.browse_button.set_sensitive(True)
                else:
                    # We couldn't guess
                    self.browse_button.set_sensitive(True)
        else:
            # Normal case, we have info
            AgentBrowser.update_actions(self)

    def _update_actions(self, jid, node, identities, features, data):
        AgentBrowser._update_actions(self, jid, node, identities, features, data)
1390
        if self.execute_button and nbxmpp.NS_COMMANDS in features:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1391
            self.execute_button.set_sensitive(True)
1392
        if self.search_button and nbxmpp.NS_SEARCH in features:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1393
            self.search_button.set_sensitive(True)
1394
        # Don't authorize to register with a server via disco
1395 1396
        if self.register_button and nbxmpp.NS_REGISTER in features and \
        jid != self.jid:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1397 1398
            # We can register this agent
            registered_transports = []
1399
            jid_list = app.contacts.get_jid_list(self.account)
1400
            for jid_ in jid_list:
1401
                contact = app.contacts.get_first_contact_from_jid(
1402
                        self.account, jid_)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1403
                if _('Transports') in contact.groups:
1404 1405
                    registered_transports.append(jid_)
            registered_transports.append(self.jid)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1406 1407 1408 1409 1410
            if jid in registered_transports:
                self.register_button.set_label(_('_Edit'))
            else:
                self.register_button.set_label(_('Re_gister'))
            self.register_button.set_sensitive(True)
1411
        if self.join_button and nbxmpp.NS_MUC in features:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1412 1413 1414 1415 1416
            self.join_button.set_sensitive(True)

    def _default_action(self, jid, node, identities, features, data):
        if AgentBrowser._default_action(self, jid, node, identities, features, data):
            return True
1417
        if nbxmpp.NS_REGISTER in features:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1418 1419 1420 1421 1422 1423 1424
            # Register if we can't browse
            self.on_register_button_clicked()
            return True
        return False

    def browse(self, force=False):
        self._progress = 0
1425
        AgentBrowser.browse(self, force=force)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436

    def _expand_all(self):
        """
        Expand all items in the treeview
        """
        # GTK apparently screws up here occasionally. :/
        #def expand_all(*args):
        #       self.window.services_treeview.expand_all()
        #       self.expanding = False
        #       return False
        #self.expanding = True
1437
        #GLib.idle_add(expand_all)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1438 1439 1440 1441 1442 1443 1444 1445
        self.window.services_treeview.expand_all()

    def _update_progressbar(self):
        """
        Update the progressbar
        """
        # Refresh this every update
        if self._progressbar_sourceid:
1446
            GLib.source_remove(self._progressbar_sourceid)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1447 1448 1449 1450 1451 1452 1453 1454

        fraction = 0
        if self._total_items:
            self.window.progressbar.set_text(_("Scanning %(current)d / %(total)d.."
                    ) % {'current': self._progress, 'total': self._total_items})
            fraction = float(self._progress) / float(self._total_items)
            if self._progress >= self._total_items:
                # We show the progressbar for just a bit before hiding it.
1455
                id_ = GLib.timeout_add_seconds(2, self._hide_progressbar_cb)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1456 1457 1458 1459
                self._progressbar_sourceid = id_
            else:
                self.window.progressbar.show()
                # Hide the progressbar if we're timing out anyways. (20 secs)
1460
                id_ = GLib.timeout_add_seconds(20, self._hide_progressbar_cb)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
                self._progressbar_sourceid = id_
        self.window.progressbar.set_fraction(fraction)

    def _hide_progressbar_cb(self, *args):
        """
        Simple callback to hide the progressbar a second after we finish
        """
        if self.active:
            self.window.progressbar.hide()
        return False

    def _friendly_category(self, category, type_=None):
        """
1474
        Get the friendly category name
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1475 1476 1477 1478 1479
        """
        cat = None
        if type_:
            # Try type-specific override
            try:
1480
                cat = _cat_to_descr[(category, type_)]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1481 1482 1483 1484
            except KeyError:
                pass
        if not cat:
            try:
1485
                cat = _cat_to_descr[category]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1486
            except KeyError:
1487 1488
                cat = _cat_to_descr['other']
        return cat
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1489 1490 1491 1492 1493

    def _create_category(self, cat, type_=None):
        """
        Creates a category row
        """
1494 1495
        cat = self._friendly_category(cat, type_)
        return self.model.append(None, ('', '', None, cat, None))
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1496 1497 1498 1499 1500

    def _find_category(self, cat, type_=None):
        """
        Looks up a category row and returns the iterator to it, or None
        """
1501 1502
        cat = self._friendly_category(cat, type_)
        iter_ = self.model.get_iter_first()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1503
        while iter_:
1504
            if self.model.get_value(iter_, 3) == cat:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1505 1506 1507 1508 1509 1510 1511 1512
                break
            iter_ = self.model.iter_next(iter_)
        if iter_:
            return iter_
        return None

    def _find_item(self, jid, node):
        iter_ = None
1513
        cat_iter = self.model.get_iter_first()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1514
        while cat_iter and not iter_:
1515 1516
            cjid = self.model.get_value(cat_iter, 0)
            cnode = self.model.get_value(cat_iter, 1)
1517 1518 1519
            if jid == cjid and node == cnode:
                iter_ = cat_iter
                break
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1520 1521
            iter_ = self.model.iter_children(cat_iter)
            while iter_:
1522 1523
                cjid = self.model.get_value(iter_, 0)
                cnode = self.model.get_value(iter_, 1)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
                if jid == cjid and node == cnode:
                    break
                iter_ = self.model.iter_next(iter_)
            cat_iter = self.model.iter_next(cat_iter)
        if iter_:
            return iter_
        return None

    def _add_item(self, jid, node, parent_node, item, force):
        # Row text
        addr = get_agent_address(jid, node)
        if 'name' in item:
            descr = "<b>%s</b>\n%s" % (item['name'], addr)
        else:
            descr = "<b>%s</b>" % addr
        # Guess which kind of service this is
        identities = []
1541 1542
        type_ = app.get_transport_name_from_jid(
            jid, use_config_setting=False)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1543 1544 1545 1546 1547 1548 1549 1550
        if type_:
            identity = {'category': '_jid', 'type': type_}
            identities.append(identity)
            cat_args = ('_jid', type_)
        else:
            # Put it in the 'other' category for now
            cat_args = ('other',)
        # Set the pixmap for the row
1551
        pix = self.cache.get_icon(identities, addr=addr)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1552 1553 1554 1555
        # Put it in the right category
        cat = self._find_category(*cat_args)
        if not cat:
            cat = self._create_category(*cat_args)
1556 1557
        self.model.append(cat, (jid, node, pix, descr, LABELS[1]))
        GLib.idle_add(self._expand_all)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
        # Grab info on the service
        self.cache.get_info(jid, node, self._agent_info, force=force)
        self._update_progressbar()

    def _update_item(self, iter_, jid, node, item):
        addr = get_agent_address(jid, node)
        if 'name' in item:
            descr = "<b>%s</b>\n%s" % (item['name'], addr)
        else:
            descr = "<b>%s</b>" % addr
        self.model[iter_][3] = descr

    def _update_info(self, iter_, jid, node, identities, features, data):
        addr = get_agent_address(jid, node)
1572
        if not identities:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1573
            descr = "<b>%s</b>" % addr
1574 1575 1576 1577 1578 1579
        else:
            name = identities[0].get('name', '')
            if name:
                descr = "<b>%s</b>\n%s" % (name, addr)
            else:
                descr = "<b>%s</b>" % addr
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1580 1581 1582 1583 1584 1585

        # Update progress
        self._progress += 1
        self._update_progressbar()

        # Search for an icon and category we can display
1586
        pix = self.cache.get_icon(identities, addr=addr)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        cat, type_ = None, None
        for identity in identities:
            try:
                cat, type_ = identity['category'], identity['type']
            except KeyError:
                continue
            break

        # Check if we have to move categories
        old_cat_iter = self.model.iter_parent(iter_)
1597
        if not old_cat_iter or self.model.get_value(old_cat_iter, 3) == cat:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1598 1599 1600
            # Already in the right category, just update
            self.model[iter_][2] = pix
            self.model[iter_][3] = descr
1601
            self.model[iter_][4] = None
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1602 1603 1604 1605
            return
        # Not in the right category, move it.
        self.model.remove(iter_)

1606
        old_cat = self.model.get_value(old_cat_iter, 3)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1607 1608 1609 1610 1611 1612 1613 1614 1615
        # Check if the old category is empty
        if not self.model.iter_is_valid(old_cat_iter):
            old_cat_iter = self._find_category(old_cat)
        if not self.model.iter_children(old_cat_iter):
            self.model.remove(old_cat_iter)

        cat_iter = self._find_category(cat, type_)
        if not cat_iter:
            cat_iter = self._create_category(cat, type_)
1616
        self.model.append(cat_iter, (jid, node, pix, descr, None))
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1617 1618 1619
        self._expand_all()

    def _update_error(self, iter_, jid, node):
1620
        self.model[iter_][4] = LABELS[2]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1621 1622
        self._progress += 1
        self._update_progressbar()
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1623 1624 1625


class MucBrowser(AgentBrowser):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
1626 1627 1628 1629 1630 1631 1632 1633 1634
    def __init__<