Fix no-else-return pylint errors

This commit is contained in:
Philipp Hörist 2018-09-18 10:14:04 +02:00 committed by Philipp Hörist
parent b9edcceb4c
commit dad5331bf2
45 changed files with 407 additions and 405 deletions

View File

@ -1081,7 +1081,7 @@ class ChatControl(ChatControlBase):
if self.contact.jid == app.get_jid_from_account(self.account): if self.contact.jid == app.get_jid_from_account(self.account):
return return
elif chatstate_setting == 'composing_only' and state != 'active' and\ if chatstate_setting == 'composing_only' and state != 'active' and\
state != 'composing': state != 'composing':
return return

View File

@ -610,11 +610,11 @@ class ChatControlBase(MessageControl, ChatCommandProcessor, CommandTools):
self.parent_win.move_to_next_unread_tab(False) self.parent_win.move_to_next_unread_tab(False)
return True return True
# SHIFT + PAGE_[UP|DOWN]: send to conv_textview # SHIFT + PAGE_[UP|DOWN]: send to conv_textview
elif event.keyval == Gdk.KEY_Page_Down or \ if event.keyval == Gdk.KEY_Page_Down or \
event.keyval == Gdk.KEY_Page_Up: event.keyval == Gdk.KEY_Page_Up:
self.conv_textview.tv.event(event) self.conv_textview.tv.event(event)
return True return True
elif event.get_state() & Gdk.ModifierType.CONTROL_MASK: if event.get_state() & Gdk.ModifierType.CONTROL_MASK:
if event.keyval == Gdk.KEY_Tab: # CTRL + TAB if event.keyval == Gdk.KEY_Tab: # CTRL + TAB
self.parent_win.move_to_next_unread_tab(True) self.parent_win.move_to_next_unread_tab(True)
return True return True

View File

@ -43,7 +43,7 @@ class StandardCommonCommands(CommandContainer):
@command(overlap=True) @command(overlap=True)
@doc(_("Show help on a given command or a list of available commands if -a is given")) @doc(_("Show help on a given command or a list of available commands if -a is given"))
def help(self, cmd=None, all=False): def help(self, cmd=None, all_=False):
if cmd: if cmd:
cmd = self.get_command(cmd) cmd = self.get_command(cmd)
@ -58,7 +58,8 @@ class StandardCommonCommands(CommandContainer):
text.append(usage) text.append(usage)
return '\n\n'.join(text) return '\n\n'.join(text)
elif all:
if all_:
for cmd_ in self.list_commands(): for cmd_ in self.list_commands():
names = ', '.join(cmd_.names) names = ', '.join(cmd_.names)
description = cmd_.extract_description() description = cmd_.extract_description()

View File

@ -356,8 +356,7 @@ def get_resource_from_jid(jid):
jids = jid.split('/', 1) jids = jid.split('/', 1)
if len(jids) > 1: if len(jids) > 1:
return jids[1] # abc@doremi.org/res/res-continued return jids[1] # abc@doremi.org/res/res-continued
else: return ''
return ''
def get_number_of_accounts(): def get_number_of_accounts():
""" """
@ -481,14 +480,13 @@ def get_transport_name_from_jid(jid, use_config_setting = True):
if host in ('irc', 'icq', 'sms', 'weather', 'mrim', 'facebook'): if host in ('irc', 'icq', 'sms', 'weather', 'mrim', 'facebook'):
return host return host
elif host == 'gg': if host == 'gg':
return 'gadu-gadu' return 'gadu-gadu'
elif host == 'jit': if host == 'jit':
return 'icq' return 'icq'
elif host == 'facebook': if host == 'facebook':
return 'facebook' return 'facebook'
else: return None
return None
def jid_is_transport(jid): def jid_is_transport(jid):
# if not '@' or '@' starts the jid then it is transport # if not '@' or '@' starts the jid then it is transport

View File

@ -71,12 +71,11 @@ def client_supports(client_caps, requested_feature):
supported_features = cache_item.features supported_features = cache_item.features
if requested_feature in supported_features: if requested_feature in supported_features:
return True return True
elif not supported_features and cache_item.status in (NEW, QUERIED, FAKED): if not supported_features and cache_item.status in (NEW, QUERIED, FAKED):
# assume feature is supported, if we don't know yet, what the client # assume feature is supported, if we don't know yet, what the client
# is capable of # is capable of
return requested_feature not in FEATURE_BLACKLIST return requested_feature not in FEATURE_BLACKLIST
else: return False
return False
def create_suitable_client_caps(node, caps_hash, hash_method, fjid=None): def create_suitable_client_caps(node, caps_hash, hash_method, fjid=None):
""" """
@ -478,7 +477,7 @@ class MucCapsCache:
try: try:
if nbxmpp.NS_MAM_2 in self.cache[jid].features: if nbxmpp.NS_MAM_2 in self.cache[jid].features:
return nbxmpp.NS_MAM_2 return nbxmpp.NS_MAM_2
elif nbxmpp.NS_MAM_1 in self.cache[jid].features: if nbxmpp.NS_MAM_1 in self.cache[jid].features:
return nbxmpp.NS_MAM_1 return nbxmpp.NS_MAM_1
except (KeyError, AttributeError): except (KeyError, AttributeError):
return return

View File

@ -537,15 +537,13 @@ class Config:
return None return None
if type_[0] == 'boolean': if type_[0] == 'boolean':
return self.is_valid_bool(val) return self.is_valid_bool(val)
elif type_[0] == 'integer': if type_[0] == 'integer':
return self.is_valid_int(val) return self.is_valid_int(val)
elif type_[0] == 'string': if type_[0] == 'string':
return self.is_valid_string(val) return self.is_valid_string(val)
else: if re.match(type_[1], val):
if re.match(type_[1], val): return val
return val return None
else:
return None
def set(self, optname, value): def set(self, optname, value):
if optname not in self.__options[1]: if optname not in self.__options[1]:

View File

@ -165,7 +165,7 @@ class CommonConnection:
self.gpg.password = None self.gpg.password = None
if signed == 'KEYEXPIRED': if signed == 'KEYEXPIRED':
return 'expired' return 'expired'
elif signed == 'BAD_PASSPHRASE': if signed == 'BAD_PASSPHRASE':
return 'bad_pass' return 'bad_pass'
return 'ok' return 'ok'
@ -600,11 +600,11 @@ class Connection(CommonConnection, ConnectionHandlers):
if self.registered_name: if self.registered_name:
# This returns the full jid we received on the bind event # This returns the full jid we received on the bind event
return self.registered_name return self.registered_name
else:
if warn: if warn:
log.warning('only bare JID available') log.warning('only bare JID available')
# This returns the bare jid # This returns the bare jid
return nbxmpp.JID(app.get_jid_from_account(self.name)) return nbxmpp.JID(app.get_jid_from_account(self.name))
def reconnect(self): def reconnect(self):
# Do not try to reco while we are already trying # Do not try to reco while we are already trying
@ -804,14 +804,14 @@ class Connection(CommonConnection, ConnectionHandlers):
if len(hosts_lowest_prio) == 1: if len(hosts_lowest_prio) == 1:
return hosts_lowest_prio[0] return hosts_lowest_prio[0]
else:
rndint = random.randint(0, sum(h['weight'] for h in hosts_lowest_prio)) rndint = random.randint(0, sum(h['weight'] for h in hosts_lowest_prio))
weightsum = 0 weightsum = 0
for host in sorted(hosts_lowest_prio, key=operator.itemgetter( for host in sorted(hosts_lowest_prio,
'weight')): key=operator.itemgetter('weight')):
weightsum += host['weight'] weightsum += host['weight']
if weightsum >= rndint: if weightsum >= rndint:
return host return host
def connect(self, data=None): def connect(self, data=None):
""" """

View File

@ -281,15 +281,13 @@ class ConnectionHandlersBase:
if pm: if pm:
return self.make_new_session(fjid, thread_id, type_='pm') return self.make_new_session(fjid, thread_id, type_='pm')
else: return self.make_new_session(fjid, thread_id)
return self.make_new_session(fjid, thread_id)
def find_session(self, jid, thread_id): def find_session(self, jid, thread_id):
try: try:
if not thread_id: if not thread_id:
return self.find_null_session(jid) return self.find_null_session(jid)
else: return self.sessions[jid][thread_id]
return self.sessions[jid][thread_id]
except KeyError: except KeyError:
return None return None
@ -324,10 +322,9 @@ class ConnectionHandlersBase:
if chat_sessions: if chat_sessions:
# return the session that we last sent a message in # return the session that we last sent a message in
return sorted(chat_sessions, key=operator.attrgetter('last_send'))[ return sorted(chat_sessions,
-1] key=operator.attrgetter('last_send'))[-1]
else: return None
return None
def get_latest_session(self, jid): def get_latest_session(self, jid):
""" """

View File

@ -88,8 +88,7 @@ class CommonContact(XMPPEntity):
# show, so we can be sure it's existant. Otherwise, we still # show, so we can be sure it's existant. Otherwise, we still
# return caps for a contact that has no resources left. # return caps for a contact that has no resources left.
return False return False
else: return caps_cache.client_supports(self.client_caps, requested_feature)
return caps_cache.client_supports(self.client_caps, requested_feature)
class Contact(CommonContact): class Contact(CommonContact):
@ -136,14 +135,13 @@ class Contact(CommonContact):
def get_shown_groups(self): def get_shown_groups(self):
if self.is_observer(): if self.is_observer():
return [_('Observers')] return [_('Observers')]
elif self.is_groupchat(): if self.is_groupchat():
return [_('Groupchats')] return [_('Groupchats')]
elif self.is_transport(): if self.is_transport():
return [_('Transports')] return [_('Transports')]
elif not self.groups: if not self.groups:
return [_('General')] return [_('General')]
else: return self.groups
return self.groups
def is_hidden_from_roster(self): def is_hidden_from_roster(self):
""" """
@ -415,8 +413,7 @@ class LegacyContactsAPI:
# Only called if self has no attr_name # Only called if self has no attr_name
if hasattr(self._metacontact_manager, attr_name): if hasattr(self._metacontact_manager, attr_name):
return getattr(self._metacontact_manager, attr_name) return getattr(self._metacontact_manager, attr_name)
else: raise AttributeError(attr_name)
raise AttributeError(attr_name)
def create_gc_contact(self, room_jid, account, name='', show='', status='', def create_gc_contact(self, room_jid, account, name='', show='', status='',
role='', affiliation='', jid='', resource='', avatar_sha=None): role='', affiliation='', jid='', resource='', avatar_sha=None):

View File

@ -53,8 +53,7 @@ if app.is_installed('GPG'):
if key['trust'] not in ('f', 'u'): if key['trust'] not in ('f', 'u'):
if key['keyid'][-8:] not in self.always_trust: if key['keyid'][-8:] not in self.always_trust:
return '', 'NOT_TRUSTED ' + key['keyid'][-8:] return '', 'NOT_TRUSTED ' + key['keyid'][-8:]
else: trust = True
trust = True
result = super(GnuPG, self).encrypt(str_.encode('utf8'), recipients, result = super(GnuPG, self).encrypt(str_.encode('utf8'), recipients,
always_trust=trust, passphrase=self.passphrase) always_trust=trust, passphrase=self.passphrase)

View File

@ -180,9 +180,8 @@ def parse_resource(resource):
try: try:
if HAS_PRECIS_I18N: if HAS_PRECIS_I18N:
return resource.encode('Nickname').decode('utf-8') return resource.encode('Nickname').decode('utf-8')
else: from nbxmpp.stringprepare import resourceprep
from nbxmpp.stringprepare import resourceprep return resourceprep.prepare(resource)
return resourceprep.prepare(resource)
except UnicodeError: except UnicodeError:
raise InvalidFormat('Invalid character in resource.') raise InvalidFormat('Invalid character in resource.')
@ -254,13 +253,11 @@ def prep(user, server, resource):
if user: if user:
if resource: if resource:
return '%s@%s/%s' % (user, server, resource) return '%s@%s/%s' % (user, server, resource)
else: return '%s@%s' % (user, server)
return '%s@%s' % (user, server)
else: if resource:
if resource: return '%s/%s' % (server, resource)
return '%s/%s' % (server, resource) return server
else:
return server
def windowsify(s): def windowsify(s):
if os.name == 'nt': if os.name == 'nt':
@ -333,11 +330,11 @@ def get_uf_show(show, use_mnemonic = False):
def get_css_show_color(show): def get_css_show_color(show):
if show in ('online', 'chat', 'invisible'): if show in ('online', 'chat', 'invisible'):
return 'status-online' return 'status-online'
elif show in ('offline', 'not in roster', 'requested'): if show in ('offline', 'not in roster', 'requested'):
return None return None
elif show in ('xa', 'dnd'): if show in ('xa', 'dnd'):
return 'status-dnd' return 'status-dnd'
elif show == 'away': if show == 'away':
return 'status-away' return 'status-away'
def get_uf_sub(sub): def get_uf_sub(sub):
@ -434,14 +431,14 @@ def get_uf_chatstate(chatstate):
""" """
if chatstate == 'active': if chatstate == 'active':
return _('is paying attention to the conversation') return _('is paying attention to the conversation')
elif chatstate == 'inactive': if chatstate == 'inactive':
return _('is doing something else') return _('is doing something else')
elif chatstate == 'composing': if chatstate == 'composing':
return _('is composing a message…') return _('is composing a message…')
elif chatstate == 'paused': if chatstate == 'paused':
#paused means he or she was composing but has stopped for a while #paused means he or she was composing but has stopped for a while
return _('paused composing a message') return _('paused composing a message')
elif chatstate == 'gone': if chatstate == 'gone':
return _('has closed the chat window or tab') return _('has closed the chat window or tab')
return '' return ''
@ -456,8 +453,7 @@ def is_in_path(command, return_abs_path=False):
if command in os.listdir(directory): if command in os.listdir(directory):
if return_abs_path: if return_abs_path:
return os.path.join(directory, command) return os.path.join(directory, command)
else: return True
return True
except OSError: except OSError:
# If the user has non directories in his path # If the user has non directories in his path
pass pass
@ -724,7 +720,7 @@ def check_soundfile_path(file_, dirs=None):
if not file_: if not file_:
return None return None
elif os.path.exists(file_): if os.path.exists(file_):
return file_ return file_
for d in dirs: for d in dirs:
@ -766,7 +762,7 @@ def play_sound_file(path_to_soundfile):
path_to_soundfile = check_soundfile_path(path_to_soundfile) path_to_soundfile = check_soundfile_path(path_to_soundfile)
if path_to_soundfile is None: if path_to_soundfile is None:
return return
elif sys.platform == 'win32' and HAS_SOUND: if sys.platform == 'win32' and HAS_SOUND:
try: try:
winsound.PlaySound(path_to_soundfile, winsound.PlaySound(path_to_soundfile,
winsound.SND_FILENAME|winsound.SND_ASYNC) winsound.SND_FILENAME|winsound.SND_ASYNC)
@ -831,14 +827,14 @@ def statuses_unified():
return False return False
return True return True
def get_icon_name_to_show(contact, account = None): def get_icon_name_to_show(contact, account=None):
""" """
Get the icon name to show in online, away, requested, etc Get the icon name to show in online, away, requested, etc
""" """
if account and app.events.get_nb_roster_events(account, contact.jid): if account and app.events.get_nb_roster_events(account, contact.jid):
return 'event' return 'event'
if account and app.events.get_nb_roster_events(account, if account and app.events.get_nb_roster_events(
contact.get_full_jid()): account, contact.get_full_jid()):
return 'event' return 'event'
if account and account in app.interface.minimized_controls and \ if account and account in app.interface.minimized_controls and \
contact.jid in app.interface.minimized_controls[account] and app.interface.\ contact.jid in app.interface.minimized_controls[account] and app.interface.\
@ -847,8 +843,7 @@ def get_icon_name_to_show(contact, account = None):
if account and contact.jid in app.gc_connected[account]: if account and contact.jid in app.gc_connected[account]:
if app.gc_connected[account][contact.jid]: if app.gc_connected[account][contact.jid]:
return 'muc_active' return 'muc_active'
else: return 'muc_inactive'
return 'muc_inactive'
if contact.jid.find('@') <= 0: # if not '@' or '@' starts the jid ==> agent if contact.jid.find('@') <= 0: # if not '@' or '@' starts the jid ==> agent
return contact.show return contact.show
if contact.sub in ('both', 'to'): if contact.sub in ('both', 'to'):
@ -956,7 +951,7 @@ def get_chat_control(account, contact):
if contact.resource: if contact.resource:
full_jid_with_resource += '/' + contact.resource full_jid_with_resource += '/' + contact.resource
highest_contact = app.contacts.get_contact_with_highest_priority( highest_contact = app.contacts.get_contact_with_highest_priority(
account, contact.jid) account, contact.jid)
# Look for a chat control that has the given resource, or default to # Look for a chat control that has the given resource, or default to
# one without resource # one without resource
@ -965,12 +960,14 @@ def get_chat_control(account, contact):
if ctrl: if ctrl:
return ctrl return ctrl
elif highest_contact and highest_contact.resource and \
contact.resource != highest_contact.resource: if (highest_contact and
highest_contact.resource and
contact.resource != highest_contact.resource):
return None return None
else:
# unknown contact or offline message # unknown contact or offline message
return app.interface.msg_win_mgr.get_control(contact.jid, account) return app.interface.msg_win_mgr.get_control(contact.jid, account)
def get_notification_icon_tooltip_dict(): def get_notification_icon_tooltip_dict():
""" """
@ -1122,20 +1119,20 @@ def get_current_show(account):
def get_iconset_path(iconset): def get_iconset_path(iconset):
if os.path.isdir(os.path.join(configpaths.get('DATA'), 'iconsets', iconset)): if os.path.isdir(os.path.join(configpaths.get('DATA'), 'iconsets', iconset)):
return os.path.join(configpaths.get('DATA'), 'iconsets', iconset) return os.path.join(configpaths.get('DATA'), 'iconsets', iconset)
elif os.path.isdir(os.path.join(configpaths.get('MY_ICONSETS'), iconset)): if os.path.isdir(os.path.join(configpaths.get('MY_ICONSETS'), iconset)):
return os.path.join(configpaths.get('MY_ICONSETS'), iconset) return os.path.join(configpaths.get('MY_ICONSETS'), iconset)
def get_mood_iconset_path(iconset): def get_mood_iconset_path(iconset):
if os.path.isdir(os.path.join(configpaths.get('DATA'), 'moods', iconset)): if os.path.isdir(os.path.join(configpaths.get('DATA'), 'moods', iconset)):
return os.path.join(configpaths.get('DATA'), 'moods', iconset) return os.path.join(configpaths.get('DATA'), 'moods', iconset)
elif os.path.isdir( if os.path.isdir(
os.path.join(configpaths.get('MY_MOOD_ICONSETS'), iconset)): os.path.join(configpaths.get('MY_MOOD_ICONSETS'), iconset)):
return os.path.join(configpaths.get('MY_MOOD_ICONSETS'), iconset) return os.path.join(configpaths.get('MY_MOOD_ICONSETS'), iconset)
def get_activity_iconset_path(iconset): def get_activity_iconset_path(iconset):
if os.path.isdir(os.path.join(configpaths.get('DATA'), 'activities', iconset)): if os.path.isdir(os.path.join(configpaths.get('DATA'), 'activities', iconset)):
return os.path.join(configpaths.get('DATA'), 'activities', iconset) return os.path.join(configpaths.get('DATA'), 'activities', iconset)
elif os.path.isdir(os.path.join(configpaths.get('MY_ACTIVITY_ICONSETS'), if os.path.isdir(os.path.join(configpaths.get('MY_ACTIVITY_ICONSETS'),
iconset)): iconset)):
return os.path.join(configpaths.get('MY_ACTIVITY_ICONSETS'), iconset) return os.path.join(configpaths.get('MY_ACTIVITY_ICONSETS'), iconset)
@ -1143,7 +1140,7 @@ def get_transport_path(transport):
if os.path.isdir(os.path.join(configpaths.get('DATA'), 'iconsets', 'transports', if os.path.isdir(os.path.join(configpaths.get('DATA'), 'iconsets', 'transports',
transport)): transport)):
return os.path.join(configpaths.get('DATA'), 'iconsets', 'transports', transport) return os.path.join(configpaths.get('DATA'), 'iconsets', 'transports', transport)
elif os.path.isdir(os.path.join(configpaths.get('MY_ICONSETS'), 'transports', if os.path.isdir(os.path.join(configpaths.get('MY_ICONSETS'), 'transports',
transport)): transport)):
return os.path.join(configpaths.get('MY_ICONSETS'), 'transports', transport) return os.path.join(configpaths.get('MY_ICONSETS'), 'transports', transport)
# No transport folder found, use default jabber one # No transport folder found, use default jabber one

View File

@ -181,15 +181,15 @@ class ConnectionJingle:
if contact.supports(nbxmpp.NS_HASHES_2): if contact.supports(nbxmpp.NS_HASHES_2):
if contact.supports(nbxmpp.NS_HASHES_BLAKE2B_512): if contact.supports(nbxmpp.NS_HASHES_BLAKE2B_512):
return 'blake2b-512' return 'blake2b-512'
elif contact.supports(nbxmpp.NS_HASHES_BLAKE2B_256): if contact.supports(nbxmpp.NS_HASHES_BLAKE2B_256):
return 'blake2b-256' return 'blake2b-256'
elif contact.supports(nbxmpp.NS_HASHES_SHA3_512): if contact.supports(nbxmpp.NS_HASHES_SHA3_512):
return 'sha3-512' return 'sha3-512'
elif contact.supports(nbxmpp.NS_HASHES_SHA3_256): if contact.supports(nbxmpp.NS_HASHES_SHA3_256):
return 'sha3-256' return 'sha3-256'
elif contact.supports(nbxmpp.NS_HASHES_SHA512): if contact.supports(nbxmpp.NS_HASHES_SHA512):
return 'sha-512' return 'sha-512'
elif contact.supports(nbxmpp.NS_HASHES_SHA256): if contact.supports(nbxmpp.NS_HASHES_SHA256):
return 'sha-256' return 'sha-256'
return None return None
@ -202,11 +202,8 @@ class ConnectionJingle:
if media: if media:
if media not in ('audio', 'video', 'file'): if media not in ('audio', 'video', 'file'):
return tuple() return tuple()
else: return (session for session in sessions if session.get_content(media))
return (session for session in sessions if \ return sessions
session.get_content(media))
else:
return sessions
def set_file_info(self, file_): def set_file_info(self, file_):
# Saves information about the files we have transferred in case they need # Saves information about the files we have transferred in case they need
@ -228,9 +225,8 @@ class ConnectionJingle:
if sid: if sid:
if sid in self._sessions: if sid in self._sessions:
return self._sessions[sid] return self._sessions[sid]
else: return None
return None if media:
elif media:
if media not in ('audio', 'video', 'file'): if media not in ('audio', 'video', 'file'):
return None return None
for session in self._sessions.values(): for session in self._sessions.values():

View File

@ -470,7 +470,7 @@ class JingleVideo(JingleRTPContent):
def get_content(desc): def get_content(desc):
if desc['media'] == 'audio': if desc['media'] == 'audio':
return JingleAudio return JingleAudio
elif desc['media'] == 'video': if desc['media'] == 'video':
return JingleVideo return JingleVideo
contents[nbxmpp.NS_JINGLE_RTP] = get_content contents[nbxmpp.NS_JINGLE_RTP] = get_content

View File

@ -362,9 +362,8 @@ class Logger:
if jid.find('/') > -1: if jid.find('/') > -1:
possible_room_jid = jid.split('/', 1)[0] possible_room_jid = jid.split('/', 1)[0]
return self.jid_is_room_jid(possible_room_jid) return self.jid_is_room_jid(possible_room_jid)
else: # it's not a full jid, so it's not a pm one
# it's not a full jid, so it's not a pm one return False
return False
def jid_is_room_jid(self, jid): def jid_is_room_jid(self, jid):
""" """
@ -465,21 +464,21 @@ class Logger:
if show == 'online': if show == 'online':
return ShowConstant.ONLINE return ShowConstant.ONLINE
elif show == 'chat': if show == 'chat':
return ShowConstant.CHAT return ShowConstant.CHAT
elif show == 'away': if show == 'away':
return ShowConstant.AWAY return ShowConstant.AWAY
elif show == 'xa': if show == 'xa':
return ShowConstant.XA return ShowConstant.XA
elif show == 'dnd': if show == 'dnd':
return ShowConstant.DND return ShowConstant.DND
elif show == 'offline': if show == 'offline':
return ShowConstant.OFFLINE return ShowConstant.OFFLINE
elif show is None: if show is None:
return ShowConstant.ONLINE return ShowConstant.ONLINE
else: # invisible in GC when someone goes invisible # invisible in GC when someone goes invisible
# it's a RFC violation .... but we should not crash # it's a RFC violation .... but we should not crash
return None return None
def convert_human_transport_type_to_db_api_values(self, type_): def convert_human_transport_type_to_db_api_values(self, type_):
""" """

View File

@ -24,11 +24,10 @@ def parseLogLevel(arg):
""" """
if arg.isdigit(): if arg.isdigit():
return int(arg) return int(arg)
elif arg.isupper() and hasattr(logging, arg): if arg.isupper() and hasattr(logging, arg):
return getattr(logging, arg) return getattr(logging, arg)
else: print(_('%s is not a valid loglevel') % repr(arg))
print(_('%s is not a valid loglevel') % repr(arg)) return 0
return 0
def parseLogTarget(arg): def parseLogTarget(arg):
""" """
@ -39,12 +38,11 @@ def parseLogTarget(arg):
arg = arg.lower() arg = arg.lower()
if not arg: if not arg:
return 'gajim' return 'gajim'
elif arg.startswith('.'): if arg.startswith('.'):
return arg[1:] return arg[1:]
elif arg.startswith('gajim'): if arg.startswith('gajim'):
return arg return arg
else: return 'gajim.' + arg
return 'gajim.' + arg
def parseAndSetLogLevels(arg): def parseAndSetLogLevels(arg):
""" """

View File

@ -36,8 +36,7 @@ class AbstractPEP:
if items: if items:
log.debug('Received PEP "user %s" from %s', cls.type_, jid) log.debug('Received PEP "user %s" from %s', cls.type_, jid)
return cls(jid, account, items) return cls(jid, account, items)
else: return None
return None
def __init__(self, jid, account, items): def __init__(self, jid, account, items):
self.data, self._retracted = self._extract_info(items) self.data, self._retracted = self._extract_info(items)

View File

@ -554,8 +554,8 @@ class ConnectionSocks5Bytestream(ConnectionBytestream):
} }
proxyhost_dicts.append(host_dict) proxyhost_dicts.append(host_dict)
return proxyhost_dicts return proxyhost_dicts
else:
return [] return []
def _result_socks5_sid(self, sid, hash_id): def _result_socks5_sid(self, sid, hash_id):
""" """

View File

@ -288,7 +288,7 @@ class HostTester(Socks5, IdleObject):
if self.state == 0: if self.state == 0:
self.do_connect() self.do_connect()
return return
elif self.state == 1: # send initially: version and auth types if self.state == 1: # send initially: version and auth types
data = self._get_auth_buff() data = self._get_auth_buff()
self.send_raw(data) self.send_raw(data)
else: else:
@ -408,7 +408,7 @@ class ReceiverTester(Socks5, IdleObject):
if self.state == 0: if self.state == 0:
self.do_connect() self.do_connect()
return return
elif self.state == 1: # send initially: version and auth types if self.state == 1: # send initially: version and auth types
data = self._get_auth_buff() data = self._get_auth_buff()
self.send_raw(data) self.send_raw(data)
else: else:

View File

@ -213,7 +213,7 @@ class SocksQueue:
if 'idx' in host: if 'idx' in host:
if host['state'] >= 0: if host['state'] >= 0:
return return
elif host['state'] == -2: if host['state'] == -2:
unused_hosts = True unused_hosts = True
if unused_hosts: if unused_hosts:
for host in file_props.streamhosts: for host in file_props.streamhosts:
@ -541,12 +541,12 @@ class Socks5:
self.connected = False self.connected = False
return None return None
# win32 needs this # win32 needs this
elif errnum not in (10056, EISCONN) or self.state != 0: if errnum not in (10056, EISCONN) or self.state != 0:
return None return None
else: # socket is already connected # socket is already connected
self._sock.setblocking(False) self._sock.setblocking(False)
self._send=self._sock.send self._send=self._sock.send
self._recv=self._sock.recv self._recv=self._sock.recv
self.buff = '' self.buff = ''
self.connected = True self.connected = True
self.file_props.connected = True self.file_props.connected = True
@ -1312,7 +1312,7 @@ class Socks5Client(Socks5):
if self.state == 0: if self.state == 0:
self.do_connect() self.do_connect()
return return
elif self.state == 1: # send initially: version and auth types if self.state == 1: # send initially: version and auth types
self.send_raw(self._get_auth_buff()) self.send_raw(self._get_auth_buff())
elif self.state == 3: # send 'connect' request elif self.state == 3: # send 'connect' request
self.send_raw(self._get_request_buff(self._get_sha1_auth())) self.send_raw(self._get_request_buff(self._get_sha1_auth()))

View File

@ -474,14 +474,16 @@ class P2PConnection(IdleObject, PlugIn):
errors += (errno.WSAEINVAL,) errors += (errno.WSAEINVAL,)
if errnum in errors: if errnum in errors:
return return
# win32 needs this # win32 needs this
elif errnum not in (0, 10056, errno.EISCONN) or self.state != 0: if errnum not in (0, 10056, errno.EISCONN) or self.state != 0:
log.error('Could not connect to %s: %s [%s]', str(self.host), log.error('Could not connect to %s: %s [%s]', str(self.host),
errnum, errstr) errnum, errstr)
self.connect_to_next_ip() self.connect_to_next_ip()
return return
else: # socket is already connected
self._sock.setblocking(False) # socket is already connected
self._sock.setblocking(False)
self.state = 1 # connected self.state = 1 # connected
# we are connected # we are connected
self.on_connect(self) self.on_connect(self)

View File

@ -259,7 +259,7 @@ class Zeroconf:
def replace_show(self, show): def replace_show(self, show):
if show in ['chat', 'online', '']: if show in ['chat', 'online', '']:
return 'avail' return 'avail'
elif show == 'xa': if show == 'xa':
return 'away' return 'away'
return show return show
@ -336,8 +336,7 @@ class Zeroconf:
self.announced = False self.announced = False
return True return True
else: return False
return False
except dbus.DBusException: except dbus.DBusException:
log.debug("Can't remove service. That should not happen") log.debug("Can't remove service. That should not happen")
@ -485,8 +484,7 @@ class Zeroconf:
txt, reply_handler=self.service_updated_callback, txt, reply_handler=self.service_updated_callback,
error_handler=self.error_callback) error_handler=self.error_callback)
return True return True
else: return False
return False
# END Zeroconf # END Zeroconf

View File

@ -257,7 +257,7 @@ class Zeroconf:
def replace_show(self, show): def replace_show(self, show):
if show in ['chat', 'online', '']: if show in ['chat', 'online', '']:
return 'avail' return 'avail'
elif show == 'xa': if show == 'xa':
return 'away' return 'away'
return show return show
@ -327,9 +327,9 @@ class Zeroconf:
# start browsing # start browsing
if self.browse_domain(): if self.browse_domain():
return True return True
else:
self.disconnect() self.disconnect()
return False return False
def disconnect(self): def disconnect(self):
if self.connected: if self.connected:
@ -362,8 +362,7 @@ class Zeroconf:
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning: if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
log.info('Service not running') log.info('Service not running')
return False return False
else: log.error('Error while browsing for services. %s', error)
log.error('Error while browsing for services. %s', error)
return True return True
# resolve_all() is called every X seconds and querys for new clients # resolve_all() is called every X seconds and querys for new clients
@ -401,8 +400,7 @@ class Zeroconf:
if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning: if error.errorCode == pybonjour.kDNSServiceErr_ServiceNotRunning:
log.info('Service not running') log.info('Service not running')
return False return False
else: log.error('Error in query for TXT records. %s', error)
log.error('Error in query for TXT records. %s', error)
finally: finally:
if query_sdRef: if query_sdRef:
query_sdRef.close() query_sdRef.close()

View File

@ -93,10 +93,8 @@ class TextViewImage(Gtk.Image):
if self._selected: if self._selected:
if has_focus(parent): if has_focus(parent):
return Gtk.StateType.SELECTED return Gtk.StateType.SELECTED
else: return Gtk.StateType.ACTIVE
return Gtk.StateType.ACTIVE return Gtk.StateType.NORMAL
else:
return Gtk.StateType.NORMAL
def _update_selected(self): def _update_selected(self):
selected = self._get_selected() selected = self._get_selected()
@ -759,41 +757,42 @@ class ConversationTextview(GObject.GObject):
kind = 'sth_at_sth' kind = 'sth_at_sth'
else: else:
word = self.tv.get_buffer().get_text(begin_iter, end_iter, True) word = self.tv.get_buffer().get_text(begin_iter, end_iter, True)
if event.button.button == 3: # right click if event.button.button == 3: # right click
self.make_link_menu(event, kind, word) self.make_link_menu(event, kind, word)
return True return True
else:
self.plugin_modified = False
app.plugin_manager.extension_point(
'hyperlink_handler', word, kind, self,
self.tv.get_toplevel())
if self.plugin_modified:
return
# we launch the correct application self.plugin_modified = False
if kind == 'xmpp': app.plugin_manager.extension_point(
word = word[5:] 'hyperlink_handler', word, kind, self,
if '?' in word: self.tv.get_toplevel())
(jid, action) = word.split('?') if self.plugin_modified:
if action == 'join': return
app.interface.join_gc_minimal(self.account, jid)
else: # we launch the correct application
self.on_start_chat_activate(None, jid) if kind == 'xmpp':
word = word[5:]
if '?' in word:
(jid, action) = word.split('?')
if action == 'join':
app.interface.join_gc_minimal(self.account, jid)
else: else:
self.on_start_chat_activate(None, word) self.on_start_chat_activate(None, jid)
# handle geo:-URIs
elif word[:4] == 'geo:':
location = word[4:]
lat, _, lon = location.partition(',')
if lon == '':
return
uri = 'https://www.openstreetmap.org/?' \
'mlat=%(lat)s&mlon=%(lon)s&zoom=16' % \
{'lat': lat, 'lon': lon}
helpers.launch_browser_mailer(kind, uri)
# other URIs
else: else:
helpers.launch_browser_mailer(kind, word) self.on_start_chat_activate(None, word)
# handle geo:-URIs
elif word[:4] == 'geo:':
location = word[4:]
lat, _, lon = location.partition(',')
if lon == '':
return
uri = 'https://www.openstreetmap.org/?' \
'mlat=%(lat)s&mlon=%(lon)s&zoom=16' % \
{'lat': lat, 'lon': lon}
helpers.launch_browser_mailer(kind, uri)
# other URIs
else:
helpers.launch_browser_mailer(kind, word)
def detect_and_print_special_text(self, otext, other_tags, graphics=True, def detect_and_print_special_text(self, otext, other_tags, graphics=True,
iter_=None, additional_data=None): iter_=None, additional_data=None):
@ -1274,7 +1273,7 @@ class ConversationTextview(GObject.GObject):
def detect_other_text_tag(self, text, kind): def detect_other_text_tag(self, text, kind):
if kind == 'status': if kind == 'status':
return kind return kind
elif text.startswith('/me ') or text.startswith('/me\n'): if text.startswith('/me ') or text.startswith('/me\n'):
return kind return kind
def print_time(self, text, kind, tim, simple, direction_mark, other_tags_for_time, iter_): def print_time(self, text, kind, tim, simple, direction_mark, other_tags_for_time, iter_):
@ -1389,8 +1388,7 @@ class ConversationTextview(GObject.GObject):
if self.plugin_modified: if self.plugin_modified:
if not mark: if not mark:
return buffer_.get_end_iter() return buffer_.get_end_iter()
else: return buffer_.get_iter_at_mark(mark)
return buffer_.get_iter_at_mark(mark)
if not mark: if not mark:
iter_ = buffer_.get_end_iter() iter_ = buffer_.get_end_iter()

View File

@ -311,9 +311,9 @@ class ChooseGPGKeyDialog:
value2 = model[iter2][1] value2 = model[iter2][1]
if value1 == _('None'): if value1 == _('None'):
return -1 return -1
elif value2 == _('None'): if value2 == _('None'):
return 1 return 1
elif value1 < value2: if value1 < value2:
return -1 return -1
return 1 return 1
@ -570,13 +570,13 @@ class TimeoutDialog:
if self.countdown_left <= 0: if self.countdown_left <= 0:
self.on_timeout() self.on_timeout()
return False return False
self.dialog.set_title('%s [%s]' % (self.title_text, self.dialog.set_title('%s [%s]' % (
str(self.countdown_left))) self.title_text, str(self.countdown_left)))
self.countdown_left -= 1 self.countdown_left -= 1
return True return True
else:
self.dialog.set_title(self.title_text) self.dialog.set_title(self.title_text)
return False return False
class ChangeStatusMessageDialog(TimeoutDialog): class ChangeStatusMessageDialog(TimeoutDialog):
def __init__(self, on_response, show=None, show_pep=True): def __init__(self, on_response, show=None, show_pep=True):
@ -970,12 +970,12 @@ class SynchroniseSelectAccountDialog:
ErrorDialog(_('This account is not connected to the server'), ErrorDialog(_('This account is not connected to the server'),
_('You cannot synchronize with an account unless it is connected.')) _('You cannot synchronize with an account unless it is connected.'))
return return
else:
try: try:
SynchroniseSelectContactsDialog(self.account, remote_account) SynchroniseSelectContactsDialog(self.account, remote_account)
except GajimGeneralException: except GajimGeneralException:
# if we showed ErrorDialog, there will not be dialog instance # if we showed ErrorDialog, there will not be dialog instance
return return
self.dialog.destroy() self.dialog.destroy()
@staticmethod @staticmethod
@ -1609,8 +1609,7 @@ class VoIPCallReceivedDialog:
def get_dialog(cls, jid, sid): def get_dialog(cls, jid, sid):
if (jid, sid) in cls.instances: if (jid, sid) in cls.instances:
return cls.instances[(jid, sid)] return cls.instances[(jid, sid)]
else: return None
return None
def set_secondary_text(self): def set_secondary_text(self):
if 'audio' in self.content_types and 'video' in self.content_types: if 'audio' in self.content_types and 'video' in self.content_types:

View File

@ -196,14 +196,13 @@ class CacheDictionary:
_icon_cache = CacheDictionary(15) _icon_cache = CacheDictionary(15)
def get_agent_address(jid, node = None): def get_agent_address(jid, node=None):
""" """
Get an agent's address for displaying in the GUI Get an agent's address for displaying in the GUI
""" """
if node: if node:
return '%s@%s' % (node, str(jid)) return '%s@%s' % (node, str(jid))
else: return str(jid)
return str(jid)
class Closure: class Closure:
""" """
@ -668,18 +667,20 @@ _('Without a connection, you can not browse available services'))
if not self.address_comboboxtext: if not self.address_comboboxtext:
# We can't travel anywhere else. # We can't travel anywhere else.
self.destroy() self.destroy()
ErrorDialog(_('The service could not be found'), ErrorDialog(
_('The service could not be found'),
_('There is no service at the address you entered, or it is ' _('There is no service at the address you entered, or it is '
'not responding. Check the address and try again.'), 'not responding. Check the address and try again.'),
transient_for=self.window) transient_for=self.window)
return return
klass = self.cache.get_browser(identities, features) klass = self.cache.get_browser(identities, features)
if not klass: if not klass:
ErrorDialog(_('The service is not browsable'), ErrorDialog(
_('The service is not browsable'),
_('This type of service does not contain any items to browse.'), _('This type of service does not contain any items to browse.'),
transient_for=self.window) transient_for=self.window)
return return
elif klass is None: if klass is None:
klass = AgentBrowser klass = AgentBrowser
self.browser = klass(self.account, jid, node) self.browser = klass(self.account, jid, node)
self.browser.prepare_window(self) self.browser.prepare_window(self)

View File

@ -383,7 +383,7 @@ class FileTransfersWindow:
ErrorDialog( ErrorDialog(
_('Cannot overwrite existing file "%s"' % file_name), _('Cannot overwrite existing file "%s"' % file_name),
_('A file with this name already exists and you do not ' _('A file with this name already exists and you do not '
'have permission to overwrite it.')) 'have permission to overwrite it.'))
return return
stat = os.stat(file_path) stat = os.stat(file_path)
dl_size = stat.st_size dl_size = stat.st_size
@ -393,7 +393,7 @@ class FileTransfersWindow:
def on_response(response): def on_response(response):
if response < 0: if response < 0:
return return
elif response == 100: if response == 100:
file_props.offset = dl_size file_props.offset = dl_size
self._start_receive(file_path, account, contact, file_props) self._start_receive(file_path, account, contact, file_props)
@ -402,16 +402,17 @@ class FileTransfersWindow:
propose_resume=not dl_finished, on_response=on_response) propose_resume=not dl_finished, on_response=on_response)
dialog.set_destroy_with_parent(True) dialog.set_destroy_with_parent(True)
return return
else:
dirname = os.path.dirname(file_path) dirname = os.path.dirname(file_path)
if not os.access(dirname, os.W_OK) and os.name != 'nt': if not os.access(dirname, os.W_OK) and os.name != 'nt':
# read-only bit is used to mark special folder under # read-only bit is used to mark special folder under
# windows, not to mark that a folder is read-only. # windows, not to mark that a folder is read-only.
# See ticket #3587 # See ticket #3587
ErrorDialog(_('Directory "%s" is not writable') % \ ErrorDialog(
dirname, _('You do not have permission to create files ' _('Directory "%s" is not writable') % dirname,
'in this directory.')) _('You do not have permission to create files '
return 'in this directory.'))
return
self._start_receive(file_path, account, contact, file_props) self._start_receive(file_path, account, contact, file_props)
con = app.connections[account] con = app.connections[account]
@ -535,7 +536,8 @@ class FileTransfersWindow:
def _get_eta_and_speed(self, full_size, transfered_size, file_props): def _get_eta_and_speed(self, full_size, transfered_size, file_props):
if not file_props.transfered_size: if not file_props.transfered_size:
return 0., 0. return 0., 0.
elif len(file_props.transfered_size) == 1:
if len(file_props.transfered_size) == 1:
speed = round(float(transfered_size) / file_props.elapsed_time) speed = round(float(transfered_size) / file_props.elapsed_time)
else: else:
# first and last are (time, transfered_size) # first and last are (time, transfered_size)

View File

@ -880,7 +880,7 @@ class GroupchatControl(ChatControlBase):
show2 = cshow[gc_contact2.show] show2 = cshow[gc_contact2.show]
if show1 < show2: if show1 < show2:
return -1 return -1
elif show1 > show2: if show1 > show2:
return 1 return 1
# We compare names # We compare names
name1 = gc_contact1.get_shown_name() name1 = gc_contact1.get_shown_name()
@ -2184,12 +2184,11 @@ class GroupchatControl(ChatControlBase):
self.msg_textview.grab_focus() self.msg_textview.grab_focus()
def get_role(self, nick): def get_role(self, nick):
gc_contact = app.contacts.get_gc_contact(self.account, self.room_jid, gc_contact = app.contacts.get_gc_contact(
nick) self.account, self.room_jid, nick)
if gc_contact: if gc_contact:
return gc_contact.role return gc_contact.role
else: return 'visitor'
return 'visitor'
def minimizable(self): def minimizable(self):
if self.force_non_minimizable: if self.force_non_minimizable:
@ -2245,8 +2244,9 @@ class GroupchatControl(ChatControlBase):
if chatstate_setting == 'disabled': if chatstate_setting == 'disabled':
return return
elif chatstate_setting == 'composing_only' and state != 'active' and\ if (chatstate_setting == 'composing_only' and
state != 'composing': state != 'active' and
state != 'composing'):
return return
# if the new state we wanna send (state) equals # if the new state we wanna send (state) equals
@ -2814,7 +2814,7 @@ class GroupchatControl(ChatControlBase):
self.mk_menu(event, iter_) self.mk_menu(event, iter_)
return True return True
elif event.button == 2: # middle click if event.button == 2: # middle click
widget.get_selection().select_path(path) widget.get_selection().select_path(path)
iter_ = self.model.get_iter(path) iter_ = self.model.get_iter(path)
if path.get_depth() == 2: if path.get_depth() == 2:
@ -2822,25 +2822,25 @@ class GroupchatControl(ChatControlBase):
self._start_private_message(nick) self._start_private_message(nick)
return True return True
elif event.button == 1: # left click if event.button == 1: # left click
if app.single_click and not event.get_state() & Gdk.ModifierType.SHIFT_MASK: if app.single_click and not event.get_state() & Gdk.ModifierType.SHIFT_MASK:
self.on_row_activated(widget, path) self.on_row_activated(widget, path)
return True return True
else:
iter_ = self.model.get_iter(path) iter_ = self.model.get_iter(path)
nick = self.model[iter_][Column.NICK] nick = self.model[iter_][Column.NICK]
if not nick in app.contacts.get_nick_list(self.account, if not nick in app.contacts.get_nick_list(
self.room_jid): self.account, self.room_jid):
# it's a group # it's a group
if x < 27: if x < 27:
if widget.row_expanded(path): if widget.row_expanded(path):
widget.collapse_row(path) widget.collapse_row(path)
else: else:
widget.expand_row(path, False) widget.expand_row(path, False)
elif event.get_state() & Gdk.ModifierType.SHIFT_MASK: elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
self.append_nick_in_msg_textview(self.msg_textview, nick) self.append_nick_in_msg_textview(self.msg_textview, nick)
self.msg_textview.grab_focus() self.msg_textview.grab_focus()
return True return True
def append_nick_in_msg_textview(self, widget, nick): def append_nick_in_msg_textview(self, widget, nick):
self.msg_textview.remove_placeholder() self.msg_textview.remove_placeholder()

View File

@ -209,12 +209,10 @@ class GtkAvatarChooserDialog(BaseAvatarChooserDialog, GtkFileChooserDialog):
def FileChooserDialog(*args, **kwargs): def FileChooserDialog(*args, **kwargs):
if _require_native(): if _require_native():
return NativeFileOpenDialog(*args, **kwargs) return NativeFileOpenDialog(*args, **kwargs)
else: return GtkFileOpenDialog(*args, **kwargs)
return GtkFileOpenDialog(*args, **kwargs)
def AvatarChooserDialog(*args, **kwargs): def AvatarChooserDialog(*args, **kwargs):
if _require_native(): if _require_native():
return NativeAvatarChooserDialog(*args, **kwargs) return NativeAvatarChooserDialog(*args, **kwargs)
else: return GtkAvatarChooserDialog(*args, **kwargs)
return GtkAvatarChooserDialog(*args, **kwargs)

View File

@ -425,13 +425,15 @@ class HistoryWindow:
self.calendar.select_month(gtk_m, self.first_day.year) self.calendar.select_month(gtk_m, self.first_day.year)
self.calendar.select_day(self.first_day.day) self.calendar.select_day(self.first_day.day)
return return
elif widget is self.button_last_day:
if widget is self.button_last_day:
gtk_m = gtk_month( gtk_m = gtk_month(
self.last_day.month) self.last_day.month)
self.calendar.select_month(gtk_m, self.last_day.year) self.calendar.select_month(gtk_m, self.last_day.year)
self.calendar.select_day(self.last_day.day) self.calendar.select_day(self.last_day.day)
return return
elif widget is self.button_previous_day:
if widget is self.button_previous_day:
end_date = self.first_day end_date = self.first_day
timedelta = datetime.timedelta(days=-1) timedelta = datetime.timedelta(days=-1)
if end_date >= _date: if end_date >= _date:
@ -640,8 +642,8 @@ class HistoryWindow:
if text == '': if text == '':
self.results_window.set_property('visible', False) self.results_window.set_property('visible', False)
return return
else:
self.results_window.set_property('visible', True) self.results_window.set_property('visible', True)
# perform search in preselected jids # perform search in preselected jids
# jids are preselected with the query_entry # jids are preselected with the query_entry

View File

@ -115,26 +115,30 @@ class StartChatDialog(Gtk.ApplicationWindow):
if event.keyval in (Gdk.KEY_Down, Gdk.KEY_Tab): if event.keyval in (Gdk.KEY_Down, Gdk.KEY_Tab):
self.search_entry.emit('next-match') self.search_entry.emit('next-match')
return True return True
elif (event.state == Gdk.ModifierType.SHIFT_MASK and
if (event.state == Gdk.ModifierType.SHIFT_MASK and
event.keyval == Gdk.KEY_ISO_Left_Tab): event.keyval == Gdk.KEY_ISO_Left_Tab):
self.search_entry.emit('previous-match') self.search_entry.emit('previous-match')
return True return True
elif event.keyval == Gdk.KEY_Up:
if event.keyval == Gdk.KEY_Up:
self.search_entry.emit('previous-match') self.search_entry.emit('previous-match')
return True return True
elif event.keyval == Gdk.KEY_Escape:
if event.keyval == Gdk.KEY_Escape:
if self.search_entry.get_text() != '': if self.search_entry.get_text() != '':
self.search_entry.emit('stop-search') self.search_entry.emit('stop-search')
else: else:
self.destroy() self.destroy()
return True return True
elif event.keyval == Gdk.KEY_Return:
if event.keyval == Gdk.KEY_Return:
row = self.listbox.get_selected_row() row = self.listbox.get_selected_row()
if row is not None: if row is not None:
row.emit('activate') row.emit('activate')
return True return True
else:
self.search_entry.grab_focus_without_selecting() self.search_entry.grab_focus_without_selecting()
def _start_new_chat(self, row): def _start_new_chat(self, row):
if row.new: if row.new:

View File

@ -402,8 +402,7 @@ class Option(Gtk.ListBoxRow):
def __eq__(self, other): def __eq__(self, other):
if isinstance(other, ChooseOption): if isinstance(other, ChooseOption):
return other.option == self._option return other.option == self._option
else: return other._option == self._option
return other._option == self._option
class ChooseOption(Gtk.ListBoxRow): class ChooseOption(Gtk.ListBoxRow):

View File

@ -127,7 +127,7 @@ def init():
def get_os_info(): def get_os_info():
if os.name == 'nt' or sys.platform == 'darwin': if os.name == 'nt' or sys.platform == 'darwin':
return platform.system() + " " + platform.release() return platform.system() + " " + platform.release()
elif os.name == 'posix': if os.name == 'posix':
try: try:
import distro import distro
return distro.name(pretty=True) return distro.name(pretty=True)

View File

@ -75,11 +75,10 @@ def get_icon_pixmap(icon_name, size=16, color=None, quiet=False):
def get_icon_path(icon_name, size=16): def get_icon_path(icon_name, size=16):
try: try:
icon_info = gtk_icon_theme.lookup_icon(icon_name, size, 0) icon_info = gtk_icon_theme.lookup_icon(icon_name, size, 0)
if icon_info == None: if icon_info is None:
log.error('Icon not found: %s', icon_name) log.error('Icon not found: %s', icon_name)
return '' return ''
else: return icon_info.get_filename()
return icon_info.get_filename()
except GLib.GError as error: except GLib.GError as error:
log.error('Unable to find icon %s: %s', icon_name, str(error)) log.error('Unable to find icon %s: %s', icon_name, str(error))
@ -439,9 +438,9 @@ def scale_with_ratio(size, width, height):
if height > width: if height > width:
ratio = height / float(width) ratio = height / float(width)
return int(size / ratio), size return int(size / ratio), size
else:
ratio = width / float(height) ratio = width / float(height)
return size, int(size / ratio) return size, int(size / ratio)
def scale_pixbuf(pixbuf, size): def scale_pixbuf(pixbuf, size):
width, height = scale_with_ratio(size, width, height = scale_with_ratio(size,
@ -607,34 +606,37 @@ def get_pep_as_pixbuf(pep_class):
mood = received_mood if received_mood in MOODS else 'unknown' mood = received_mood if received_mood in MOODS else 'unknown'
pixbuf = load_mood_icon(mood).get_pixbuf() pixbuf = load_mood_icon(mood).get_pixbuf()
return pixbuf return pixbuf
elif pep_class == PEPEventType.TUNE:
if pep_class == PEPEventType.TUNE:
icon = get_icon_pixmap('audio-x-generic', quiet=True) icon = get_icon_pixmap('audio-x-generic', quiet=True)
if not icon: if not icon:
path = os.path.join(configpaths.get('DATA'), 'emoticons', 'static', path = os.path.join(
'music.png') configpaths.get('DATA'), 'emoticons', 'static', 'music.png')
return GdkPixbuf.Pixbuf.new_from_file(path) return GdkPixbuf.Pixbuf.new_from_file(path)
return icon return icon
elif pep_class == PEPEventType.ACTIVITY:
if pep_class == PEPEventType.ACTIVITY:
pep_ = pep_class.data pep_ = pep_class.data
activity = pep_['activity'] activity = pep_['activity']
has_known_activity = activity in ACTIVITIES has_known_activity = activity in ACTIVITIES
has_known_subactivity = (has_known_activity and ('subactivity' in pep_) has_known_subactivity = (has_known_activity and
and (pep_['subactivity'] in ACTIVITIES[activity])) 'subactivity' in pep_ and
pep_['subactivity'] in ACTIVITIES[activity])
if has_known_activity: if has_known_activity:
if has_known_subactivity: if has_known_subactivity:
subactivity = pep_['subactivity'] subactivity = pep_['subactivity']
return load_activity_icon(activity, subactivity).get_pixbuf() return load_activity_icon(activity, subactivity).get_pixbuf()
else: return load_activity_icon(activity).get_pixbuf()
return load_activity_icon(activity).get_pixbuf() return load_activity_icon('unknown').get_pixbuf()
else:
return load_activity_icon('unknown').get_pixbuf() if pep_class == PEPEventType.LOCATION:
elif pep_class == PEPEventType.LOCATION:
icon = get_icon_pixmap('applications-internet', quiet=True) icon = get_icon_pixmap('applications-internet', quiet=True)
if not icon: if not icon:
icon = get_icon_pixmap('gajim-earth') icon = get_icon_pixmap('gajim-earth')
return icon return icon
return None return None
def get_iconset_name_for(name): def get_iconset_name_for(name):

View File

@ -1631,8 +1631,7 @@ class Interface:
if jid in self.minimized_controls[account]: if jid in self.minimized_controls[account]:
self.roster.on_groupchat_maximized(None, jid, account) self.roster.on_groupchat_maximized(None, jid, account)
return return
else: ctrl = self.msg_win_mgr.get_gc_control(jid, account)
ctrl = self.msg_win_mgr.get_gc_control(jid, account)
elif type_ in ('printed_chat', 'chat', ''): elif type_ in ('printed_chat', 'chat', ''):
# '' is for log in/out notifications # '' is for log in/out notifications
@ -2424,31 +2423,32 @@ class Interface:
received_mood = pep_obj.data['mood'] received_mood = pep_obj.data['mood']
mood = received_mood if received_mood in MOODS else 'unknown' mood = received_mood if received_mood in MOODS else 'unknown'
return gtkgui_helpers.load_mood_icon(mood).get_pixbuf() return gtkgui_helpers.load_mood_icon(mood).get_pixbuf()
elif pep_obj == PEPEventType.TUNE:
if pep_obj == PEPEventType.TUNE:
path = os.path.join( path = os.path.join(
configpaths.get('DATA'), 'emoticons', 'static', 'music.png') configpaths.get('DATA'), 'emoticons', 'static', 'music.png')
return GdkPixbuf.Pixbuf.new_from_file(path) return GdkPixbuf.Pixbuf.new_from_file(path)
elif pep_obj == PEPEventType.ACTIVITY:
if pep_obj == PEPEventType.ACTIVITY:
pep_ = pep_obj.data pep_ = pep_obj.data
activity = pep_['activity'] activity = pep_['activity']
has_known_activity = activity in ACTIVITIES has_known_activity = activity in ACTIVITIES
has_known_subactivity = (has_known_activity and ('subactivity' in has_known_subactivity = (has_known_activity and
pep_) and (pep_['subactivity'] in ACTIVITIES[activity])) 'subactivity' in pep_ and
pep_['subactivity'] in ACTIVITIES[activity])
if has_known_activity: if has_known_activity:
if has_known_subactivity: if has_known_subactivity:
subactivity = pep_['subactivity'] subactivity = pep_['subactivity']
return gtkgui_helpers.load_activity_icon(activity, return gtkgui_helpers.load_activity_icon(
subactivity).get_pixbuf() activity, subactivity).get_pixbuf()
else: return gtkgui_helpers.load_activity_icon(activity).get_pixbuf()
return gtkgui_helpers.load_activity_icon(activity).\ return gtkgui_helpers.load_activity_icon('unknown').get_pixbuf()
get_pixbuf()
else: if pep_obj == PEPEventType.LOCATION:
return gtkgui_helpers.load_activity_icon('unknown').get_pixbuf() icon = gtkgui_helpers.get_icon_pixmap(
elif pep_obj == PEPEventType.LOCATION: 'applications-internet', quiet=True)
icon = gtkgui_helpers.get_icon_pixmap('applications-internet',
quiet=True)
return icon return icon
@staticmethod @staticmethod
@ -2823,8 +2823,9 @@ class PassphraseRequest:
def create_dialog(self, account): def create_dialog(self, account):
title = _('Passphrase Required') title = _('Passphrase Required')
second = _('Enter OpenPGP key passphrase for key %(keyid)s (account ' second = _('Enter OpenPGP key passphrase for key %(keyid)s '
'%(account)s).') % {'keyid': self.keyid, 'account': account} '(account %(account)s).') % {'keyid': self.keyid,
'account': account}
def _cancel(): def _cancel():
# user cancelled, continue without GPG # user cancelled, continue without GPG
@ -2836,10 +2837,12 @@ class PassphraseRequest:
# passphrase is good # passphrase is good
self.complete(passphrase) self.complete(passphrase)
return return
elif result == 'expired':
ErrorDialog(_('OpenPGP key expired'), if result == 'expired':
ErrorDialog(
_('OpenPGP key expired'),
_('Your OpenPGP key has expired, you will be connected to ' _('Your OpenPGP key has expired, you will be connected to '
'%s without OpenPGP.') % account) '%s without OpenPGP.') % account)
# Don't try to connect with GPG # Don't try to connect with GPG
app.connections[account].continue_connect_info[2] = False app.connections[account].continue_connect_info[2] = False
self.complete(None) self.complete(None)
@ -2847,15 +2850,16 @@ class PassphraseRequest:
if count < 3: if count < 3:
# ask again # ask again
dialogs.PassphraseDialog(_('Wrong Passphrase'), dialogs.PassphraseDialog(
_('Wrong Passphrase'),
_('Please retype your OpenPGP passphrase or press Cancel.'), _('Please retype your OpenPGP passphrase or press Cancel.'),
ok_handler=(_ok, count + 1), cancel_handler=_cancel) ok_handler=(_ok, count + 1), cancel_handler=_cancel)
else: else:
# user failed 3 times, continue without GPG # user failed 3 times, continue without GPG
self.complete(None) self.complete(None)
self.dialog = dialogs.PassphraseDialog(title, second, ok_handler=(_ok, self.dialog = dialogs.PassphraseDialog(
1), cancel_handler=_cancel) title, second, ok_handler=(_ok, 1), cancel_handler=_cancel)
self.dialog_created = True self.dialog_created = True

View File

@ -338,8 +338,7 @@ class HistoryManager:
row = self.cur.fetchone() row = self.cur.fetchone()
if row is None: if row is None:
return False return False
else: return True
return True
def _jid_is_room_type(self, jid): def _jid_is_room_type(self, jid):
""" """

View File

@ -191,10 +191,9 @@ for _name in BLOCK_HEAD:
def _parse_css_color(color): def _parse_css_color(color):
if color.startswith('rgb(') and color.endswith(')'): if color.startswith('rgb(') and color.endswith(')'):
r, g, b = [int(c)*257 for c in color[4:-1].split(',')] red, green, blue = [int(c)*257 for c in color[4:-1].split(',')]
return Gdk.Color(r, g, b) return Gdk.Color(red, green, blue)
else: return Gdk.color_parse(color)
return Gdk.color_parse(color)
def style_iter(style): def style_iter(style):
return ([x.strip() for x in item.split(':', 1)] for item in style.split(';')\ return ([x.strip() for x in item.split(':', 1)] for item in style.split(';')\
@ -990,20 +989,20 @@ class HtmlTextView(Gtk.TextView):
if event.button == 3: # right click if event.button == 3: # right click
self.make_link_menu(event, kind, word) self.make_link_menu(event, kind, word)
return True return True
else:
# we launch the correct application # we launch the correct application
if kind == 'xmpp': if kind == 'xmpp':
word = word[5:] word = word[5:]
if '?' in word: if '?' in word:
(jid, action) = word.split('?') (jid, action) = word.split('?')
if action == 'join': if action == 'join':
self.on_join_group_chat_menuitem_activate(None, jid) self.on_join_group_chat_menuitem_activate(None, jid)
else:
self.on_start_chat_activate(None, jid)
else: else:
self.on_start_chat_activate(None, word) self.on_start_chat_activate(None, jid)
else: else:
helpers.launch_browser_mailer(kind, word) self.on_start_chat_activate(None, word)
else:
helpers.launch_browser_mailer(kind, word)
def _hyperlink_handler(self, texttag, widget, event, iter_, kind): def _hyperlink_handler(self, texttag, widget, event, iter_, kind):
# self.hyperlink_handler can be overwritten, so call it when needed # self.hyperlink_handler can be overwritten, so call it when needed

View File

@ -344,8 +344,7 @@ class MessageTextView(Gtk.TextView):
if modified: if modified:
return '<p>' + self.make_clickable_urls(text) + '</p>' return '<p>' + self.make_clickable_urls(text) + '</p>'
else: return None
return None
def replace_emojis(self): def replace_emojis(self):
theme = app.config.get('emoticons_theme') theme = app.config.get('emoticons_theme')

View File

@ -427,23 +427,28 @@ class MessageWindow:
new = 0 new = 0
self.notebook.set_current_page(new) self.notebook.set_current_page(new)
return True return True
elif keyval == Gdk.KEY_Left: # ALT + LEFT
if keyval == Gdk.KEY_Left: # ALT + LEFT
new = self.notebook.get_current_page() - 1 new = self.notebook.get_current_page() - 1
if new < 0: if new < 0:
new = self.notebook.get_n_pages() - 1 new = self.notebook.get_n_pages() - 1
self.notebook.set_current_page(new) self.notebook.set_current_page(new)
return True return True
elif chr(keyval) in st: # ALT + 1,2,3..
if chr(keyval) in st: # ALT + 1,2,3..
self.notebook.set_current_page(st.index(chr(keyval))) self.notebook.set_current_page(st.index(chr(keyval)))
return True return True
elif keyval == Gdk.KEY_m: # ALT + M show emoticons menu
if keyval == Gdk.KEY_m: # ALT + M show emoticons menu
control.emoticons_button.get_popover().show() control.emoticons_button.get_popover().show()
return True return True
elif control.type_id == message_control.TYPE_GC and \
keyval == Gdk.KEY_t: # ALT + t if (control.type_id == message_control.TYPE_GC and
keyval == Gdk.KEY_t): # ALT + t
self.window.lookup_action( self.window.lookup_action(
'change-subject-%s' % control.control_id).activate() 'change-subject-%s' % control.control_id).activate()
return True return True
# Close tab bindings # Close tab bindings
elif keyval == Gdk.KEY_Escape and \ elif keyval == Gdk.KEY_Escape and \
app.config.get('escape_key_closes'): # Escape app.config.get('escape_key_closes'): # Escape
@ -837,20 +842,22 @@ class MessageWindow:
self.move_to_next_unread_tab(False) self.move_to_next_unread_tab(False)
return True return True
# SHIFT + PAGE_[UP|DOWN]: send to conv_textview # SHIFT + PAGE_[UP|DOWN]: send to conv_textview
elif event.keyval in (Gdk.KEY_Page_Down, Gdk.KEY_Page_Up): if event.keyval in (Gdk.KEY_Page_Down, Gdk.KEY_Page_Up):
control.conv_textview.tv.event(event) control.conv_textview.tv.event(event)
return True return True
elif event.get_state() & Gdk.ModifierType.CONTROL_MASK: elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:
if event.keyval == Gdk.KEY_Tab: # CTRL + TAB if event.keyval == Gdk.KEY_Tab: # CTRL + TAB
self.move_to_next_unread_tab(True) self.move_to_next_unread_tab(True)
return True return True
# Ctrl+PageUP / DOWN has to be handled by notebook # Ctrl+PageUP / DOWN has to be handled by notebook
elif event.keyval == Gdk.KEY_Page_Down: if event.keyval == Gdk.KEY_Page_Down:
self.move_to_next_unread_tab(True) self.move_to_next_unread_tab(True)
return True return True
elif event.keyval == Gdk.KEY_Page_Up: if event.keyval == Gdk.KEY_Page_Up:
self.move_to_next_unread_tab(False) self.move_to_next_unread_tab(False)
return True return True
if event.keyval in (Gdk.KEY_Shift_L, Gdk.KEY_Shift_R, if event.keyval in (Gdk.KEY_Shift_L, Gdk.KEY_Shift_R,
Gdk.KEY_Control_L, Gdk.KEY_Control_R, Gdk.KEY_Caps_Lock, Gdk.KEY_Control_L, Gdk.KEY_Control_R, Gdk.KEY_Caps_Lock,
Gdk.KEY_Shift_Lock, Gdk.KEY_Meta_L, Gdk.KEY_Meta_R, Gdk.KEY_Shift_Lock, Gdk.KEY_Meta_L, Gdk.KEY_Meta_R,
@ -1043,13 +1050,17 @@ class MessageWindowMgr(GObject.GObject):
if resource: if resource:
key += '/' + resource key += '/' + resource
return key return key
elif self.mode == self.ONE_MSG_WINDOW_ALWAYS:
if self.mode == self.ONE_MSG_WINDOW_ALWAYS:
return self.MAIN_WIN return self.MAIN_WIN
elif self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER:
if self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER:
return self.ROSTER_MAIN_WIN return self.ROSTER_MAIN_WIN
elif self.mode == self.ONE_MSG_WINDOW_PERACCT:
if self.mode == self.ONE_MSG_WINDOW_PERACCT:
return acct return acct
elif self.mode == self.ONE_MSG_WINDOW_PERTYPE:
if self.mode == self.ONE_MSG_WINDOW_PERTYPE:
return type_ return type_
def create_window(self, contact, acct, type_, resource = None): def create_window(self, contact, acct, type_, resource = None):
@ -1195,7 +1206,7 @@ class MessageWindowMgr(GObject.GObject):
if x < 0 or y < 0 or width < 0 or height < 0: if x < 0 or y < 0 or width < 0 or height < 0:
return return
elif self.mode == self.ONE_MSG_WINDOW_PERACCT: if self.mode == self.ONE_MSG_WINDOW_PERACCT:
acct = msg_win.account acct = msg_win.account
elif self.mode == self.ONE_MSG_WINDOW_PERTYPE: elif self.mode == self.ONE_MSG_WINDOW_PERTYPE:
type_ = msg_win.type_ type_ = msg_win.type_

View File

@ -78,12 +78,11 @@ class MusicTrackListener(GObject.GObject):
Gio.DBusCallFlags.NONE, Gio.DBusCallFlags.NONE,
-1, -1,
None) None)
except GLib.Error as e: except GLib.Error as error:
if e.domain == 'g-dbus-error-quark': if error.domain == 'g-dbus-error-quark':
log.debug("Could not list names: %s", e.message) log.debug("Could not list names: %s", error.message)
return return
else: raise
raise
for name in result[0]: for name in result[0]:
if name.startswith(MPRIS_PLAYER_PREFIX): if name.startswith(MPRIS_PLAYER_PREFIX):
@ -186,12 +185,11 @@ class MusicTrackListener(GObject.GObject):
Gio.DBusCallFlags.NONE, Gio.DBusCallFlags.NONE,
-1, -1,
None) None)
except GLib.Error as e: except GLib.Error as error:
if e.domain == 'g-dbus-error-quark': if error.domain == 'g-dbus-error-quark':
log.debug("Could not enable music listener: %s", e.message) log.debug("Could not enable music listener: %s", error.message)
return None return None
else: raise
raise
else: else:
info = self._properties_extract(result[0]) info = self._properties_extract(result[0])
return info return info

View File

@ -148,8 +148,7 @@ class Notification:
elif obj.notif_type == 'pres': elif obj.notif_type == 'pres':
if obj.transport_name is not None: if obj.transport_name is not None:
return '%s-%s' % (obj.transport_name, obj.show) return '%s-%s' % (obj.transport_name, obj.show)
else: return gtkgui_helpers.get_iconset_name_for(obj.show)
return gtkgui_helpers.get_iconset_name_for(obj.show)
def popup(self, event_type, jid, account, type_='', icon_name=None, def popup(self, event_type, jid, account, type_='', icon_name=None,
title=None, text=None, timeout=-1, room_jid=None): title=None, text=None, timeout=-1, room_jid=None):

View File

@ -159,8 +159,7 @@ class GenericOption(Gtk.Grid):
def do_get_property(self, prop): def do_get_property(self, prop):
if prop.name == 'option-value': if prop.name == 'option-value':
return self.option_value return self.option_value
else: raise AttributeError('unknown property %s' % prop.name)
raise AttributeError('unknown property %s' % prop.name)
def do_set_property(self, prop, value): def do_set_property(self, prop, value):
if prop.name == 'option-value': if prop.name == 'option-value':
@ -177,23 +176,25 @@ class GenericOption(Gtk.Grid):
return return
if type_ == OptionType.VALUE: if type_ == OptionType.VALUE:
return value return value
elif type_ == OptionType.CONFIG:
if type_ == OptionType.CONFIG:
return app.config.get(value) return app.config.get(value)
elif type_ == OptionType.ACCOUNT_CONFIG:
if type_ == OptionType.ACCOUNT_CONFIG:
if value == 'password': if value == 'password':
return passwords.get_password(account) return passwords.get_password(account)
elif value == 'no_log_for': if value == 'no_log_for':
no_log = app.config.get_per( no_log = app.config.get_per(
'accounts', account, 'no_log_for').split() 'accounts', account, 'no_log_for').split()
return account not in no_log return account not in no_log
else: return app.config.get_per('accounts', account, value)
return app.config.get_per('accounts', account, value)
elif type_ == OptionType.ACTION: if type_ == OptionType.ACTION:
if value.startswith('-'): if value.startswith('-'):
return account + value return account + value
return value return value
else:
raise ValueError('Wrong OptionType?') raise ValueError('Wrong OptionType?')
def set_value(self, state): def set_value(self, state):
if self.type_ == OptionType.CONFIG: if self.type_ == OptionType.CONFIG:

View File

@ -115,8 +115,7 @@ class PluginManager(metaclass=Singleton):
def _plugin_has_entry_in_global_config(self, plugin): def _plugin_has_entry_in_global_config(self, plugin):
if app.config.get_per('plugins', plugin.short_name) is None: if app.config.get_per('plugins', plugin.short_name) is None:
return False return False
else: return True
return True
@log_calls('PluginManager') @log_calls('PluginManager')
def _create_plugin_entry_in_global_config(self, plugin): def _create_plugin_entry_in_global_config(self, plugin):

View File

@ -877,9 +877,7 @@ class RosterWindow:
del app.interface.minimized_controls[account][jid] del app.interface.minimized_controls[account][jid]
self.remove_contact(jid, account, force=True, backend=True, maximize=maximize) self.remove_contact(jid, account, force=True, backend=True, maximize=maximize)
return True return True
else: return False
return False
# FIXME: This function is yet unused! Port to new API # FIXME: This function is yet unused! Port to new API
def add_transport(self, jid, account): def add_transport(self, jid, account):
@ -1362,14 +1360,17 @@ class RosterWindow:
def _is_pep_shown_in_roster(self, pep_type): def _is_pep_shown_in_roster(self, pep_type):
if pep_type == 'mood': if pep_type == 'mood':
return app.config.get('show_mood_in_roster') return app.config.get('show_mood_in_roster')
elif pep_type == 'activity':
if pep_type == 'activity':
return app.config.get('show_activity_in_roster') return app.config.get('show_activity_in_roster')
elif pep_type == 'tune':
if pep_type == 'tune':
return app.config.get('show_tunes_in_roster') return app.config.get('show_tunes_in_roster')
elif pep_type == 'geoloc':
if pep_type == 'geoloc':
return app.config.get('show_location_in_roster') return app.config.get('show_location_in_roster')
else:
return False return False
def draw_all_pep_types(self, jid, account, contact=None): def draw_all_pep_types(self, jid, account, contact=None):
for pep_type in self._pep_type_to_model_column: for pep_type in self._pep_type_to_model_column:
@ -1803,7 +1804,7 @@ class RosterWindow:
return 1 return 1
if show1 < show2: if show1 < show2:
return -1 return -1
elif show1 > show2: if show1 > show2:
return 1 return 1
# We compare names # We compare names
cmp_result = locale.strcoll(name1.lower(), name2.lower()) cmp_result = locale.strcoll(name1.lower(), name2.lower())
@ -1971,17 +1972,20 @@ class RosterWindow:
session=event.session, form_node=event.form_node) session=event.session, form_node=event.form_node)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'file-request':
if event.type_ == 'file-request':
contact = app.contacts.get_contact_with_highest_priority(account, contact = app.contacts.get_contact_with_highest_priority(account,
jid) jid)
ft.show_file_request(account, contact, event.file_props) ft.show_file_request(account, contact, event.file_props)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ in ('file-request-error', 'file-send-error'):
if event.type_ in ('file-request-error', 'file-send-error'):
ft.show_send_error(event.file_props) ft.show_send_error(event.file_props)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ in ('file-error', 'file-stopped'):
if event.type_ in ('file-error', 'file-stopped'):
msg_err = '' msg_err = ''
if event.file_props.error == -1: if event.file_props.error == -1:
msg_err = _('Remote contact stopped transfer') msg_err = _('Remote contact stopped transfer')
@ -1990,34 +1994,41 @@ class RosterWindow:
ft.show_stopped(jid, event.file_props, error_msg=msg_err) ft.show_stopped(jid, event.file_props, error_msg=msg_err)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'file-hash-error':
if event.type_ == 'file-hash-error':
ft.show_hash_error(jid, event.file_props, account) ft.show_hash_error(jid, event.file_props, account)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'file-completed':
if event.type_ == 'file-completed':
ft.show_completed(jid, event.file_props) ft.show_completed(jid, event.file_props)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'gc-invitation':
if event.type_ == 'gc-invitation':
dialogs.InvitationReceivedDialog(account, event.room_jid, dialogs.InvitationReceivedDialog(account, event.room_jid,
event.jid_from, event.password, event.reason, event.jid_from, event.password, event.reason,
is_continued=event.is_continued) is_continued=event.is_continued)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'subscription_request':
if event.type_ == 'subscription_request':
dialogs.SubscriptionRequestWindow(jid, event.text, account, dialogs.SubscriptionRequestWindow(jid, event.text, account,
event.nick) event.nick)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'unsubscribed':
if event.type_ == 'unsubscribed':
app.interface.show_unsubscribed_dialog(account, event.contact) app.interface.show_unsubscribed_dialog(account, event.contact)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
elif event.type_ == 'jingle-incoming':
if event.type_ == 'jingle-incoming':
dialogs.VoIPCallReceivedDialog(account, event.peerjid, event.sid, dialogs.VoIPCallReceivedDialog(account, event.peerjid, event.sid,
event.content_types) event.content_types)
app.events.remove_events(account, jid, event) app.events.remove_events(account, jid, event)
return True return True
return False return False
################################################################################ ################################################################################
@ -3244,7 +3255,7 @@ class RosterWindow:
if model.iter_has_child(iter_) and self.tree.row_expanded(path): if model.iter_has_child(iter_) and self.tree.row_expanded(path):
self.tree.collapse_row(path) self.tree.collapse_row(path)
return True return True
elif path.get_depth() > 1: if path.get_depth() > 1:
self.tree.set_cursor(path[:-1]) self.tree.set_cursor(path[:-1])
return True return True
elif event.keyval == Gdk.KEY_Right: elif event.keyval == Gdk.KEY_Right:
@ -3291,7 +3302,7 @@ class RosterWindow:
self.send_pep(account, pep_dict) self.send_pep(account, pep_dict)
dialogs.ChangeStatusMessageDialog(on_response, status) dialogs.ChangeStatusMessageDialog(on_response, status)
return True return True
elif keyval == Gdk.KEY_k: # CTRL + k if keyval == Gdk.KEY_k: # CTRL + k
self.enable_rfilter('') self.enable_rfilter('')
def on_roster_treeview_button_press_event(self, widget, event): def on_roster_treeview_button_press_event(self, widget, event):
@ -3313,7 +3324,7 @@ class RosterWindow:
self.tree.get_selection().select_path(path) self.tree.get_selection().select_path(path)
return self.show_treeview_menu(event) return self.show_treeview_menu(event)
elif event.button == 2: # Middle click if event.button == 2: # Middle click
try: try:
model, list_of_paths = self.tree.get_selection().\ model, list_of_paths = self.tree.get_selection().\
get_selected_rows() get_selected_rows()
@ -3349,7 +3360,7 @@ class RosterWindow:
dialogs.ChangeStatusMessageDialog(on_response, show) dialogs.ChangeStatusMessageDialog(on_response, show)
return True return True
elif event.button == 1: # Left click if event.button == 1: # Left click
model = self.modelfilter model = self.modelfilter
type_ = model[path][Column.TYPE] type_ = model[path][Column.TYPE]
# x_min is the x start position of status icon column # x_min is the x start position of status icon column
@ -3357,8 +3368,9 @@ class RosterWindow:
x_min = AvatarSize.ROSTER x_min = AvatarSize.ROSTER
else: else:
x_min = 0 x_min = 0
if app.single_click and not event.get_state() & Gdk.ModifierType.SHIFT_MASK and \ if (app.single_click and
not event.get_state() & Gdk.ModifierType.CONTROL_MASK: not event.get_state() & Gdk.ModifierType.SHIFT_MASK and
not event.get_state() & Gdk.ModifierType.CONTROL_MASK):
# Don't handle double click if we press icon of a metacontact # Don't handle double click if we press icon of a metacontact
titer = model.get_iter(path) titer = model.get_iter(path)
if x > x_min and x < x_min + 27 and type_ == 'contact' and \ if x > x_min and x < x_min + 27 and type_ == 'contact' and \
@ -3373,19 +3385,19 @@ class RosterWindow:
# chat window # chat window
self.clicked_path = path self.clicked_path = path
return return
else:
if type_ == 'group' and x < 27:
# first cell in 1st column (the arrow SINGLE clicked)
if self.tree.row_expanded(path):
self.tree.collapse_row(path)
else:
self.expand_group_row(path)
elif type_ == 'contact' and x > x_min and x < x_min + 27: if type_ == 'group' and x < 27:
if self.tree.row_expanded(path): # first cell in 1st column (the arrow SINGLE clicked)
self.tree.collapse_row(path) if self.tree.row_expanded(path):
else: self.tree.collapse_row(path)
self.tree.expand_row(path, False) else:
self.expand_group_row(path)
elif type_ == 'contact' and x > x_min and x < x_min + 27:
if self.tree.row_expanded(path):
self.tree.collapse_row(path)
else:
self.tree.expand_row(path, False)
def expand_group_row(self, path): def expand_group_row(self, path):
self.tree.expand_row(path, False) self.tree.expand_row(path, False)

View File

@ -133,9 +133,9 @@ class StatusIcon:
icon_name = gtkgui_helpers.get_iconset_name_for('event') icon_name = gtkgui_helpers.get_iconset_name_for('event')
self.status_icon.set_from_icon_name(icon_name) self.status_icon.set_from_icon_name(icon_name)
return return
else:
if app.config.get('trayicon') == 'on_event': if app.config.get('trayicon') == 'on_event':
self.status_icon.set_visible(False) self.status_icon.set_visible(False)
icon_name = gtkgui_helpers.get_iconset_name_for(self.status) icon_name = gtkgui_helpers.get_iconset_name_for(self.status)
self.status_icon.set_from_icon_name(icon_name) self.status_icon.set_from_icon_name(icon_name)

View File

@ -586,7 +586,7 @@ class RosterTooltip(Gtk.Window, StatusTable):
""" """
if contact.ask == 'subscribe': if contact.ask == 'subscribe':
return 'requested' return 'requested'
elif contact.sub in ('both', 'to', ''): if contact.sub in ('both', 'to', ''):
return contact.show return contact.show
return 'not in roster' return 'not in roster'