Skip to content
Snippets Groups Projects
disco.py 66.2 KiB
Newer Older
# -*- coding: utf-8 -*-
roidelapluie's avatar
roidelapluie committed
## src/disco.py
roidelapluie's avatar
roidelapluie committed
## Copyright (C) 2005-2006 Stéphan Kochen <stephan AT kochen.nl>
roidelapluie's avatar
roidelapluie committed
## Copyright (C) 2005-2007 Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2005-2008 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
roidelapluie's avatar
roidelapluie committed
## 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
roidelapluie's avatar
roidelapluie committed
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.

# 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, 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)
nkour's avatar
nkour committed
# There are more methods, of course, but this is a basic set.
import types
import weakref
import gobject
import gtk
import pango
import gtkgui_helpers
import search_window

from common import gajim
from common import xmpp
from common.exceptions import GajimGeneralException

# 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():
	return {
		# Defaults
nkour's avatar
nkour committed
		(0, 0):							(None, None),
nkour's avatar
nkour committed
		('server', 'im'):				(ToplevelAgentBrowser, 'jabber.png'),
		('services', 'jabber'):		(ToplevelAgentBrowser, 'jabber.png'),
		('hierarchy', 'branch'):	(AgentBrowser, 'jabber.png'),
shteef's avatar
shteef committed
		('conference', 'text'):		(MucBrowser, 'conference.png'),
nkour's avatar
nkour committed
		('headline', 'rss'):			(AgentBrowser, 'rss.png'),
shteef's avatar
shteef committed
		('headline', 'weather'):	(False, 'weather.png'),
		('gateway', 'weather'):		(False, 'weather.png'),
nkour's avatar
nkour committed
		('_jid', 'weather'):			(False, 'weather.png'),
shteef's avatar
shteef committed
		('directory', 'user'):		(None, 'jud.png'),
		('pubsub', 'generic'):		(PubSubBrowser, 'pubsub.png'),
		('pubsub', 'service'):		(PubSubBrowser, 'pubsub.png'),
		('proxy', 'bytestreams'):	(None, 'bytestreams.png'), # Socks5 FT proxy
		('headline', 'newmail'):	(ToplevelAgentBrowser, 'mail.png'),
		('conference', 'irc'):		(ToplevelAgentBrowser, 'irc.png'),
nkour's avatar
nkour committed
		('_jid', 'irc'):				(False, 'irc.png'),
		('gateway', 'aim'):			(False, 'aim.png'),
nkour's avatar
nkour committed
		('_jid', 'aim'):				(False, 'aim.png'),
		('gateway', 'gadu-gadu'):	(False, 'gadu-gadu.png'),
		('_jid', 'gadugadu'):		(False, 'gadu-gadu.png'),
		('gateway', 'http-ws'):		(False, 'http-ws.png'),
		('gateway', 'icq'):			(False, 'icq.png'),
nkour's avatar
nkour committed
		('_jid', 'icq'):				(False, 'icq.png'),
		('gateway', 'msn'):			(False, 'msn.png'),
nkour's avatar
nkour committed
		('_jid', 'msn'):				(False, 'msn.png'),
		('gateway', 'sms'):			(False, 'sms.png'),
nkour's avatar
nkour committed
		('_jid', 'sms'):				(False, 'sms.png'),
		('gateway', 'smtp'):			(False, 'mail.png'),
		('gateway', 'yahoo'):		(False, 'yahoo.png'),
		('_jid', 'yahoo'):			(False, 'yahoo.png'),
		('gateway', 'mrim'):			(False, 'mrim.png'),
		('_jid', 'mrim'):				(False, 'mrim.png'),
	}

# Category type to "human-readable" description string, and sort priority
_cat_to_descr = {
	'other':			(_('Others'),	2),
	'gateway':		(_('Transports'),	0),
	'_jid':			(_('Transports'),	0),
	#conference is a category for listing mostly groupchats in service discovery
	'conference':	(_('Conference'),	1),
}


class CacheDictionary:
	'''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 accessed instead of set aswell.'''
	def __init__(self, lifetime, getrefresh = True):
		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):
		for key in self.cache.keys():
			item = self.cache[key]
			if item.source:
				gobject.source_remove(item.source)
			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:
			gobject.source_remove(item.source)
		if self.lifetime:
			source = gobject.timeout_add_seconds(self.lifetime/1000, self._expire_timeout, key)
			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:
			gobject.source_remove(item.source)
		del self.cache[key]

	def __contains__(self, key):
		return key in self.cache
	has_key = __contains__

_icon_cache = CacheDictionary(15)

def get_agent_address(jid, node = None):
	'''Returns an agent's address for displaying in the GUI.'''
	if node:
		return '%s@%s' % (node, str(jid))
	else:
		return str(jid)

class Closure(object):
	'''A weak reference to a callback with arguments as an object.

	Weak references to methods immediatly die, even if the object is still
	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.'''
	def __init__(self, cb, userargs = (), remove = None, removeargs = ()):
		self.userargs = userargs
		self.remove = remove
		self.removeargs = removeargs
		if isinstance(cb, types.MethodType):
			self.meth_self = weakref.ref(cb.im_self, self._remove)
			self.meth_name = cb.func_name
		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)


class ServicesCache:
	'''Class that caches our query results. Each connection will have it's own
	ServiceCache instance.'''
	def __init__(self, account):
		self.account = account
		self._items = CacheDictionary(0, getrefresh = False)
		self._info = CacheDictionary(0, getrefresh = False)
		self._subscriptions = CacheDictionary(5, getrefresh=False)
	def cleanup(self):
		self._items.cleanup()
		self._info.cleanup()

	def _clean_closure(self, cb, type_, addr):
		# A closure died, clean up
		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]
		'''Return the icon for an agent.'''
		# Grab the first identity with an icon
		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
			info = _agent_type_info[(0, 0)]
			filename = info[1]
		if not filename: # we don't have an image to show for this type
		# Use the cache if possible
		if filename in _icon_cache:
			return _icon_cache[filename]
		# Or load it
		filepath = os.path.join(gajim.DATA_DIR, 'pixmaps', 'agents', filename)
		pix = gtk.gdk.pixbuf_new_from_file(filepath)
		# Store in cache
		_icon_cache[filename] = pix
		return pix
	def get_browser(self, identities=[], features=[]):
		'''Return the browser class for an agent.'''
		# 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.
		# Allow browsing for unknown types aswell.
		if (not features and not identities) or \
		xmpp.NS_DISCO_ITEMS in features or xmpp.NS_BROWSE in features:

	def get_info(self, jid, node, cb, force = False, nofetch = False, args = ()):
		addr = get_agent_address(jid, node)
		# Check the cache
			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?
			self._cbs[cbkey].append(cb)
		else:
			self._cbs[cbkey] = [cb]
			gajim.connections[self.account].discoverInfo(jid, node)

	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
			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,
				removeargs = cbkey)
		# Are we already fetching this?
			self._cbs[cbkey].append(cb)
		else:
			self._cbs[cbkey] = [cb]
			gajim.connections[self.account].discoverItems(jid, node)

	def agent_info(self, jid, node, identities, features, data):
		'''Callback for when we receive an agent's info.'''
		addr = get_agent_address(jid, node)

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

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

	def agent_items(self, jid, node, items):
		'''Callback for when we receive an agent's items.'''
		addr = get_agent_address(jid, node)

		# Store in cache
		self._items[addr] = items

		# Call callbacks
		cbkey = ('items', addr)
			for cb in self._cbs[cbkey]:
				cb(jid, node, items)
			# clean_closure may have beaten us to it
	def agent_info_error(self, jid):
		'''Callback for when a query fails. (even after the browse and agents
		namespaces)'''
		addr = get_agent_address(jid)

		# Call callbacks
			for cb in self._cbs[cbkey]:
				cb(jid, '', 0, 0, 0)
			# clean_closure may have beaten us to it
	def agent_items_error(self, jid):
		'''Callback for when a query fails. (even after the browse and agents
		namespaces)'''
		addr = get_agent_address(jid)

		# Call callbacks
			for cb in self._cbs[cbkey]:
				cb(jid, '', 0)
			# clean_closure may have beaten us to it
# object is needed so that @property works
	'''Class that represents the Services Discovery window.'''
	def __init__(self, account, jid = '', node = '',
			address_entry = False, parent = None):
		self.account = account
		self.parent = parent
		if not jid:
			jid = gajim.config.get_per('accounts', account, 'hostname')
			node = ''
		self.jid = None
		self.browser = None
		self.children = []
		self.dying = False
		# Check connection
		if gajim.connections[account].connected < 2:
			dialogs.ErrorDialog(_('You are not connected to the server'),
_('Without a connection, you can not browse available services'))
			raise RuntimeError, 'You must be connected to browse services'

		# Get a ServicesCache object.
		try:
			self.cache = gajim.connections[account].services_cache
		except AttributeError:
			self.cache = ServicesCache(account)
			gajim.connections[account].services_cache = self.cache

		self.xml = gtkgui_helpers.get_glade('service_discovery_window.glade')
		self.window = self.xml.get_widget('service_discovery_window')
		self.services_treeview = self.xml.get_widget('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_widget('services_scrollwin')
		self.progressbar = self.xml.get_widget('services_progressbar')
		self.banner = self.xml.get_widget('banner_agent_label')
		self.banner_icon = self.xml.get_widget('banner_agent_icon')
		self.banner_eventbox = self.xml.get_widget('banner_agent_eventbox')
		self.style_event_id = 0
dkirov's avatar
dkirov committed
		self.banner.realize()
		self.paint_banner()
		self.action_buttonbox = self.xml.get_widget('action_buttonbox')

		# Address combobox
		self.address_comboboxentry = None
		address_table = self.xml.get_widget('address_table')
			self.address_comboboxentry = self.xml.get_widget(
				'address_comboboxentry')
			self.address_comboboxentry_entry = self.address_comboboxentry.child
			self.address_comboboxentry_entry.set_activates_default(True)

			liststore = gtk.ListStore(str)
			self.address_comboboxentry.set_model(liststore)
			self.latest_addresses = gajim.config.get(
				'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:
				self.address_comboboxentry.append_text(j)
			self.address_comboboxentry.child.set_text(jid)
		else:
			# Don't show it at all if we didn't ask for it
			address_table.set_no_show_all(True)
			address_table.hide()

		self._initial_state()
		self.xml.signal_autoconnect(self)
		self.travel(jid, node)
		self.window.show_all()
		return self.account
	def _set_account(self, value):
		self.account = value
		self.cache.account = value
		if self.browser:
			self.browser.account = value
	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.'''
		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
	def _set_window_banner_text(self, text, text_after = None):
		theme = gajim.config.get('roster_theme')
		bannerfont = gajim.config.get_per('themes', theme, 'bannerfont')
		bannerfontattrs = gajim.config.get_per('themes', theme,
			'bannerfontattrs')
		if bannerfont:
			font = pango.FontDescription(bannerfont)
		else:
			font = pango.FontDescription('Normal')
		if bannerfontattrs:
			# B is attribute set by default
			if 'B' in bannerfontattrs:
				font.set_weight(pango.WEIGHT_HEAVY)
			if 'I' in bannerfontattrs:
				font.set_style(pango.STYLE_ITALIC)
		font_attrs = 'font_desc="%s"' % font.to_string()
		font_size = font.get_size()
		# in case there is no font specified we use x-large font size
		if font_size == 0:
			font_attrs = '%s size="large"' % font_attrs
		markup = '<span %s>%s</span>' % (font_attrs, text)
		if text_after:
			font.set_weight(pango.WEIGHT_NORMAL)
			markup = '%s\n<span font_desc="%s" size="small">%s</span>' % \
									(markup, font.to_string(), text_after)
		self.banner.set_markup(markup)
		'''Repaint the banner with theme color'''
		theme = gajim.config.get('roster_theme')
		bgcolor = gajim.config.get_per('themes', theme, 'bannerbgcolor')
		textcolor = gajim.config.get_per('themes', theme, 'bannertextcolor')
		self.disconnect_style_event()
		if bgcolor:
			color = gtk.gdk.color_parse(bgcolor)
			self.banner_eventbox.modify_bg(gtk.STATE_NORMAL, color)
			default_bg = False
			default_bg = True
		if textcolor:
			color = gtk.gdk.color_parse(textcolor)
			self.banner.modify_fg(gtk.STATE_NORMAL, color)
			default_fg = False
			default_fg = True
		if default_fg or default_bg:
			self._on_style_set_event(self.banner, None, default_fg, default_bg)
		if self.browser:
			self.browser.update_theme()
	def disconnect_style_event(self):
		if self.style_event_id:
			self.banner.disconnect(self.style_event_id)
			self.style_event_id = 0
	def connect_style_event(self, set_fg = False, set_bg = False):
		self.disconnect_style_event()
		self.style_event_id = self.banner.connect('style-set',
					self._on_style_set_event, set_fg, set_bg)
	def _on_style_set_event(self, widget, style, *opts):
		''' set style of widget from style class *.Frame.Eventbox
			opts[0] == True -> set fg color
			opts[1] == True -> set bg color	'''
		self.disconnect_style_event()
		if opts[1]:
			bg_color = widget.style.bg[gtk.STATE_SELECTED]
			self.banner_eventbox.modify_bg(gtk.STATE_NORMAL, bg_color)
		if opts[0]:
			fg_color = widget.style.fg[gtk.STATE_SELECTED]
			self.banner.modify_fg(gtk.STATE_NORMAL, fg_color)
		self.banner.ensure_style()
		self.connect_style_event(opts[0], opts[1])
	def destroy(self, chain = False):
		'''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)
		if addr in gajim.interface.instances[self.account]['disco']:
			del gajim.interface.instances[self.account]['disco'][addr]

		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:
				child.destroy(chain = chain)
				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:
				self.parent.destroy(chain = chain)
				self.parent = None
	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)
			if old_addr in gajim.interface.instances[self.account]['disco']:
				del gajim.interface.instances[self.account]['disco'][old_addr]
		addr = get_agent_address(jid, node)
		gajim.interface.instances[self.account]['disco'][addr] = self
		# 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)
	def _travel(self, jid, node, identities, features, data):
		'''Continuation of travel.'''
shteef's avatar
shteef committed
		if self.dying or jid != self.jid or node != self.node:
			return
		if not identities:
			if not self.address_comboboxentry:
				# We can't travel anywhere else.
				self.destroy()
			dialogs.ErrorDialog(_('The service could not be found'),
_('There is no service at the address you entered, or it is not responding. Check the address and try again.'))
			return
		klass = self.cache.get_browser(identities, features)
		if not klass:
			dialogs.ErrorDialog(_('The service is not browsable'),
_('This type of service does not contain any items to browse.'))
			return
		elif klass is None:
			klass = AgentBrowser
		self.browser = klass(self.account, jid, node)
		self.browser.prepare_window(self)
		self.browser.browse()
	def open(self, jid, node):
		'''Open an agent. By default, this happens in a new window.'''
			win = gajim.interface.instances[self.account]['disco']\
				[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()

	def on_address_comboboxentry_changed(self, widget):
		if self.address_comboboxentry.get_active() != -1:
			# user selected one of the entries so do auto-visit
			jid = self.address_comboboxentry.child.get_text().decode('utf-8')
			try:
				jid = helpers.parse_jid(jid)
			except helpers.InvalidFormat, s:
				pritext = _('Invalid Server Name')
				dialogs.ErrorDialog(pritext, str(s))
				return
	def on_go_button_clicked(self, widget):
		jid = self.address_comboboxentry.child.get_text().decode('utf-8')
		try:
			jid = helpers.parse_jid(jid)
		except helpers.InvalidFormat, s:
			pritext = _('Invalid Server Name')
			dialogs.ErrorDialog(pritext, str(s))
			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]
		self.address_comboboxentry.get_model().clear()
		for j in self.latest_addresses:
			self.address_comboboxentry.append_text(j)
		gajim.config.set('latest_disco_addresses',
			' '.join(self.latest_addresses))
		gajim.interface.save_config()
		self.travel(jid, '')

	def on_services_treeview_row_activated(self, widget, path, col = 0):
		if self.browser:
			self.browser.default_action()
	def on_services_treeview_selection_changed(self, widget):
		if self.browser:
			self.browser.update_actions()
	'''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
	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):
		'''Returns 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
		self.model = gtk.ListStore(str, str, str, str)
		self.model.set_sort_column_id(3, gtk.SORT_ASCENDING)
		self.window.services_treeview.set_model(self.model)
		# Name column
		col = gtk.TreeViewColumn(_('Name'))
		renderer = gtk.CellRendererText()
		col.pack_start(renderer)
		col.set_attributes(renderer, text = 2)
		self.window.services_treeview.insert_column(col, -1)
		col.set_resizable(True)
		# Address column
		col = gtk.TreeViewColumn(_('JID'))
		renderer = gtk.CellRendererText()
		col.pack_start(renderer)
		col.set_attributes(renderer, text = 3)
		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)
		'''Add the action buttons to the buttonbox for actions the browser can
		perform.'''
		self.browse_button = gtk.Button()
		image = gtk.image_new_from_stock(gtk.STOCK_OPEN, gtk.ICON_SIZE_BUTTON)
		label = gtk.Label(_('_Browse'))
		label.set_use_underline(True)
		hbox = gtk.HBox()
		hbox.pack_start(image, False, True, 6)
		hbox.pack_end(label, True, True)
		self.browse_button.add(hbox)
		self.browse_button.connect('clicked', self.on_browse_button_clicked)
		self.window.action_buttonbox.add(self.browse_button)
		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
		if 'name' in identities[0]:
			name = identities[0]['name']
			self.window._set_window_banner_text(self._get_agent_address(), name)
		# Add an icon to the banner.
		self.window.banner_icon.set_from_pixbuf(pix)
		self.window.banner_icon.show()
		# 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_widget('close_button')
		self.window.action_buttonbox.remove(close_button)
		self.window.action_buttonbox.pack_end(close_button)
		close_button.show_all()
		self.active = True
		self.cache.get_info(self.jid, self.node, self._set_title)
		'''Cleanup when the window intends to switch browsers.'''
		self._clean_actions()
		self._clean_treemodel()
		self._clean_title()
		self.window._initial_state()
		'''Called when the default theme is changed.'''
	def on_browse_button_clicked(self, widget = None):
		'''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_:
		jid = model[iter_][0].decode('utf-8')
			node = model[iter_][1].decode('utf-8')
			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_:
		jid = model[iter_][0].decode('utf-8')
		node = model[iter_][1].decode('utf-8')
		if jid:
			self.cache.get_info(jid, node, self._update_actions, nofetch = True)
	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_:
		jid = model[iter_][0].decode('utf-8')
		node = model[iter_][1].decode('utf-8')
		if jid:
			self.cache.get_info(jid, node, self._default_action, nofetch = True)
	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()
		self._pulse_timeout = gobject.timeout_add(250, self._pulse_timeout_cb)
		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.'''
		iter_ = self.model.get_iter_root()
		while iter_:
			cjid = self.model.get_value(iter_, 0).decode('utf-8')
			cnode = self.model.get_value(iter_, 1).decode('utf-8')
			if jid == cjid and node == cnode:
				break
			iter_ = self.model.iter_next(iter_)
		if iter_:
			return iter_
	def _agent_items(self, jid, node, items, force):
		'''Callback for when we receive a list of agent items.'''
		self.model.clear()
		self._total_items = 0
		gobject.source_remove(self._pulse_timeout)
		self.window.progressbar.hide()
		# The server returned an error
		if items == 0:
			if not self.window.address_comboboxentry:
				# We can't travel anywhere else.
				self.window.destroy()
			dialogs.ErrorDialog(_('The service is not browsable'),
_('This service does not contain any items to browse.'))
			return
		# We got a list of items
		self.window.services_treeview.set_model(None)
		for item in items:
			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, item, force)
		self.window.services_treeview.set_model(self.model)
	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)
			self._update_info(iter_, jid, node, identities, features, data)
	def _add_item(self, jid, 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)))
		self.cache.get_info(jid, node, self._agent_info, force = force)
	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. (seldom)'''
	def _update_info(self, iter_, jid, node, identities, features, data):