summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormathieui <mathieui@mathieui.net>2014-04-06 19:52:59 +0200
committermathieui <mathieui@mathieui.net>2014-04-06 19:58:57 +0200
commite216fd2112c796bd625730f711861b7361f6fe9f (patch)
tree942239b0bf00dec0f9afd9e036a1bcedf449e6d3
parent218c71dfbfb9f564eb1ec2a966df24eef2efbdec (diff)
downloadpoezio-e216fd2112c796bd625730f711861b7361f6fe9f.tar.gz
poezio-e216fd2112c796bd625730f711861b7361f6fe9f.tar.bz2
poezio-e216fd2112c796bd625730f711861b7361f6fe9f.tar.xz
poezio-e216fd2112c796bd625730f711861b7361f6fe9f.zip
Code cleanup
fixes whitespace issues, some builtin overrides, and some enormous lines might make poezio run nanoseconds faster!
-rw-r--r--src/bookmark.py25
-rw-r--r--src/common.py4
-rw-r--r--src/config.py3
-rw-r--r--src/connection.py6
-rw-r--r--src/core/core.py10
-rw-r--r--src/core/handlers.py10
-rwxr-xr-xsrc/daemon.py10
-rwxr-xr-xsrc/keyboard.py2
-rw-r--r--src/multiuserchat.py3
-rw-r--r--src/plugin_manager.py2
-rw-r--r--src/poezio_shlex.py2
-rw-r--r--src/roster.py10
-rw-r--r--src/tabs/muclisttab.py2
-rw-r--r--src/text_buffer.py16
-rw-r--r--src/theming.py42
-rw-r--r--src/windows.py148
16 files changed, 172 insertions, 123 deletions
diff --git a/src/bookmark.py b/src/bookmark.py
index fa013d1e..0fdd1cde 100644
--- a/src/bookmark.py
+++ b/src/bookmark.py
@@ -11,13 +11,13 @@ bookmarks, both local and remote.
import logging
from sys import version_info
-from sleekxmpp.plugins.xep_0048 import *
+from sleekxmpp.plugins.xep_0048 import Bookmarks, Conference
from common import safeJID
from config import config
log = logging.getLogger(__name__)
-def iter(xml, tag=''):
+def xml_iter(xml, tag=''):
if version_info[1] >= 2:
return xml.iter(tag)
else:
@@ -88,10 +88,10 @@ class Bookmark(object):
name = el.get('name')
autojoin = True if el.get('autojoin', 'false').lower() in ('true', '1') else False
nick = None
- for n in iter(el, 'nick'):
- nick = nick.text
+ for n in xml_iter(el, 'nick'):
+ nick = n.text
password = None
- for p in iter(el, 'password'):
+ for p in xml_iter(el, 'password'):
password = p.text
return Bookmark(jid, name, autojoin, nick, password, method)
@@ -117,7 +117,7 @@ def remove(value):
def stanza_storage(method):
"""Generate a <storage/> stanza with the conference elements."""
storage = Bookmarks()
- for b in filter(lambda b: b.method == method, bookmarks):
+ for b in (b for bookmark in bookmark if b.method == method):
storage.append(b.stanza())
return storage
@@ -142,16 +142,15 @@ def save_remote(xmpp, method=preferred):
else:
xmpp.plugin['xep_0048'].set_bookmarks(stanza_storage('pep'),
method='xep_0223')
- except:
- import traceback
- log.error("Could not save the bookmarks:\n%s" % traceback.format_exc())
+ except Exception:
+ log.error("Could not save the bookmarks:", exc_info=True)
return False
return True
def save_local():
"""Save the local bookmarks."""
- all = ''.join(bookmark.local() for bookmark in bookmarks if bookmark.method is 'local')
- config.set_and_save('rooms', all)
+ local = ''.join(bookmark.local() for bookmark in bookmarks if bookmark.method is 'local')
+ config.set_and_save('rooms', local)
def save(xmpp, core=None):
"""Save all the bookmarks."""
@@ -171,7 +170,7 @@ def get_pep(xmpp):
iq = xmpp.plugin['xep_0048'].get_bookmarks(method='xep_0223', block=True)
except:
return False
- for conf in iter(iq.xml, '{storage:bookmarks}conference'):
+ for conf in xml_iter(iq.xml, '{storage:bookmarks}conference'):
b = Bookmark.parse_from_element(conf, method='pep')
if not get_by_jid(b.jid):
bookmarks.append(b)
@@ -183,7 +182,7 @@ def get_privatexml(xmpp):
iq = xmpp.plugin['xep_0048'].get_bookmarks(method='xep_0049', block=True)
except:
return False
- for conf in iter(iq.xml, '{storage:bookmarks}conference'):
+ for conf in xml_iter(iq.xml, '{storage:bookmarks}conference'):
b = Bookmark.parse_from_element(conf, method='privatexml')
if not get_by_jid(b.jid):
bookmarks.append(b)
diff --git a/src/common.py b/src/common.py
index 1ec2a42a..e9fe05c8 100644
--- a/src/common.py
+++ b/src/common.py
@@ -205,7 +205,7 @@ def datetime_tuple(timestamp):
tz_msg = timestamp[15:]
try:
ret = datetime.strptime(date, '%Y%m%dT%H%M%S')
- except Exception as e:
+ except Exception:
ret = datetime.now()
# add the message timezone if any
try:
@@ -215,7 +215,7 @@ def datetime_tuple(timestamp):
tz_msg = tz_msg.tm_hour * 3600 + tz_msg.tm_min * 60
tz_msg = timedelta(seconds=tz_mod * tz_msg)
ret -= tz_msg
- except Exception as e:
+ except Exception:
pass # ignore if we got a badly-formatted offset
# convert UTC to local time, with DST etc.
if time.daylight and time.localtime().tm_isdst:
diff --git a/src/config.py b/src/config.py
index 12710e1e..1bfad784 100644
--- a/src/config.py
+++ b/src/config.py
@@ -143,9 +143,6 @@ class Config(RawConfigParser):
Our own way to save write the value in the file
Just find the right section, and then find the
right option, and edit it.
-
- TODO: make it write also new values in the file, not just what did already
- exist
"""
if path.exists(self.file_name):
df = open(self.file_name, 'r', encoding='utf-8')
diff --git a/src/connection.py b/src/connection.py
index 40c5f0ed..bf84bd6d 100644
--- a/src/connection.py
+++ b/src/connection.py
@@ -105,10 +105,12 @@ class Connection(sleekxmpp.ClientXMPP):
'version': options.version}
if config.get('send_os_info', True):
info['os'] = common.get_os_info()
- self.plugin['xep_0030'].set_identities(identities=set([('client', 'pc', None,'Poezio')]))
+ self.plugin['xep_0030'].set_identities(
+ identities=set([('client', 'pc', None, 'Poezio')]))
else:
info = {'name': '', 'version': ''}
- self.plugin['xep_0030'].set_identities(identities=set([('client', 'pc', None,'')]))
+ self.plugin['xep_0030'].set_identities(
+ identities=set([('client', 'pc', None, '')]))
self.register_plugin('xep_0092', pconfig=info)
if config.get('send_time', True):
self.register_plugin('xep_0202')
diff --git a/src/core/core.py b/src/core/core.py
index 1a496466..079a8515 100644
--- a/src/core/core.py
+++ b/src/core/core.py
@@ -175,7 +175,7 @@ class Core(object):
'_dnd': lambda: self.command_status('dnd'),
'_xa': lambda: self.command_status('xa'),
##### Custom actions ########
- '_exc_': lambda arg: self.try_execute(arg),
+ '_exc_': self.try_execute,
}
self.key_func.update(key_func)
@@ -193,8 +193,8 @@ class Core(object):
self.xmpp.add_event_handler("groupchat_config_status", self.on_status_codes)
self.xmpp.add_event_handler("groupchat_subject", self.on_groupchat_subject)
self.xmpp.add_event_handler("message", self.on_message)
- self.xmpp.add_event_handler("got_online" , self.on_got_online)
- self.xmpp.add_event_handler("got_offline" , self.on_got_offline)
+ self.xmpp.add_event_handler("got_online", self.on_got_online)
+ self.xmpp.add_event_handler("got_offline", self.on_got_offline)
self.xmpp.add_event_handler("roster_update", self.on_roster_update)
self.xmpp.add_event_handler("changed_status", self.on_presence)
self.xmpp.add_event_handler("presence_error", self.on_presence_error)
@@ -429,7 +429,7 @@ class Core(object):
res = []
current = []
for char in char_list:
- assert(len(char) > 0)
+ assert len(char) > 0
# Transform that stupid char into what we actually meant
if char == '\x1f':
char = '^/'
@@ -859,7 +859,7 @@ class Core(object):
return False
elif new_pos <= 0:
return False
- elif new_pos ==old_pos:
+ elif new_pos == old_pos:
return False
elif not self.tabs[old_pos]:
return False
diff --git a/src/core/handlers.py b/src/core/handlers.py
index 5b5cc6af..076bd986 100644
--- a/src/core/handlers.py
+++ b/src/core/handlers.py
@@ -222,7 +222,7 @@ def on_nick_received(self, message):
if item.xml.find('{http://jabber.org/protocol/nick}nick'):
contact.name = item['nick']['nick']
else:
- contact.name= ''
+ contact.name = ''
def on_gaming_event(self, message):
"""
@@ -343,7 +343,7 @@ def on_tune_event(self, message):
old_tune = contact.tune
if item.xml.find('{http://jabber.org/protocol/tune}tune'):
item = item['tune']
- contact.tune = {
+ contact.tune = {
'artist': item['artist'],
'length': item['length'],
'rating': item['rating'],
@@ -812,9 +812,9 @@ def on_session_start(self, event):
self.initial_joins.append(bm.jid)
histo_length = config.get('muc_history_length', 20)
if histo_length == -1:
- histo_length= None
+ histo_length = None
if histo_length is not None:
- histo_length= str(histo_length)
+ histo_length = str(histo_length)
# do not join rooms that do not have autojoin
# but display them anyway
if bm.autojoin:
@@ -845,7 +845,7 @@ def on_status_codes(self, message):
hide_unavailable = '103' in status_codes
non_priv = '104' in status_codes
logging_on = '170' in status_codes
- logging_off= '171' in status_codes
+ logging_off = '171' in status_codes
non_anon = '172' in status_codes
semi_anon = '173' in status_codes
full_anon = '174' in status_codes
diff --git a/src/daemon.py b/src/daemon.py
index 717dfd63..1b976282 100755
--- a/src/daemon.py
+++ b/src/daemon.py
@@ -50,22 +50,22 @@ class Executor(threading.Thread):
command.pop(-1)
def run(self):
- log.info('executing %s' % (self.command,))
+ log.debug('executing %s', self.command)
stdout = None
if self.filename:
try:
stdout = open(self.filename, self.redirection_mode)
- except (OSError, IOError) as e:
- log.error('Could not open redirection file: %s (%s)' % (self.filename, e,))
+ except (OSError, IOError):
+ log.error('Could not open redirection file: %s', self.filename, exc_info=True)
return
try:
subprocess.call(self.command, stdout=stdout)
except:
- import traceback
if self.remote:
+ import traceback
print(traceback.format_exc())
else:
- log.error('Could not execute %s:\n%s', self.command, traceback.format_exc())
+ log.error('Could not execute %s:', self.command, exc_info=True)
def main():
while True:
diff --git a/src/keyboard.py b/src/keyboard.py
index 34b1c185..94eba47f 100755
--- a/src/keyboard.py
+++ b/src/keyboard.py
@@ -110,7 +110,6 @@ def get_char_list_new(s):
pass
except ValueError: # invalid input
log.debug('Invalid character entered.')
- pass
else:
key = 'M-%s' % part
# and an even more special case for keys like
@@ -123,7 +122,6 @@ def get_char_list_new(s):
pass
except ValueError:
log.debug('Invalid character entered.')
- pass
else:
key = '%s-%s' % (key, part)
if key == '\x7f' or key == '\x08':
diff --git a/src/multiuserchat.py b/src/multiuserchat.py
index d69daf42..93fde819 100644
--- a/src/multiuserchat.py
+++ b/src/multiuserchat.py
@@ -91,7 +91,8 @@ def leave_groupchat(xmpp, jid, own_nick, msg):
try:
xmpp.plugin['xep_0045'].leaveMUC(jid, own_nick, msg)
except KeyError:
- log.debug("muc.leave_groupchat: could not leave the room %s" % jid)
+ log.debug("muc.leave_groupchat: could not leave the room %s",
+ jid, exc_info=True)
def set_user_role(xmpp, jid, nick, reason, role, callback=None):
"""
diff --git a/src/plugin_manager.py b/src/plugin_manager.py
index 45fccb10..28dde603 100644
--- a/src/plugin_manager.py
+++ b/src/plugin_manager.py
@@ -290,7 +290,7 @@ class PluginManager(object):
else:
self.core.xmpp.del_event_handler(event_name, handler)
eh = self.event_handlers[module_name]
- eh = list(filter(lambda e : e != (event_name, handler), eh))
+ eh = list(filter(lambda e: e != (event_name, handler), eh))
def completion_load(self, the_input):
"""
diff --git a/src/poezio_shlex.py b/src/poezio_shlex.py
index d2025c2e..086b0707 100644
--- a/src/poezio_shlex.py
+++ b/src/poezio_shlex.py
@@ -94,7 +94,7 @@ class shlex(object):
print("shlex: popping token " + repr(tok))
return tok
# No pushback. Get a token.
- start, end, raw = self.read_token()
+ start, end, raw = self.read_token()
return start, end, raw
def read_token(self):
diff --git a/src/roster.py b/src/roster.py
index b306bd07..eb898e5e 100644
--- a/src/roster.py
+++ b/src/roster.py
@@ -76,8 +76,7 @@ class Roster(object):
self.__node[jid].send_presence(ptype='unavailable')
self.__node.remove(jid)
except (IqError, IqTimeout):
- import traceback
- log.debug('IqError when removing %s:\n%s', jid, traceback.format_exc())
+ log.debug('IqError when removing %s:', jid, exc_info=True)
def __delitem__(self, jid):
"""Remove a contact from the roster view"""
@@ -120,10 +119,7 @@ class Roster(object):
def get_groups(self, sort=''):
"""Return a list of the RosterGroups"""
group_list = sorted(
- filter(
- lambda x: bool(x),
- self.groups.values()
- ),
+ (group for group in self.groups.values() if group),
key=lambda x: x.name.lower() if x.name else ''
)
@@ -189,7 +185,7 @@ class Roster(object):
"""
folded_groups = ':'.join([group.name for group in self.groups.values()\
if group.folded])
- log.debug('folded:%s\n' %folded_groups)
+ log.debug('folded:%s\n', folded_groups)
return config.silent_set('folded_roster_groups', folded_groups, 'var')
def get_nb_connected_contacts(self):
diff --git a/src/tabs/muclisttab.py b/src/tabs/muclisttab.py
index 5a9eea8b..b82f4a23 100644
--- a/src/tabs/muclisttab.py
+++ b/src/tabs/muclisttab.py
@@ -123,7 +123,7 @@ class MucListTab(Tab):
for item in substanza['substanzas']:
if isinstance(item, DiscoItem):
yield (item['jid'], item['node'], item['name'])
- items = [ (item[0].split('@')[0],
+ items = [(item[0].split('@')[0],
item[0],
item[2] or '', '') for item in get_items()]
self.listview.set_lines(items)
diff --git a/src/text_buffer.py b/src/text_buffer.py
index 919fbe8c..b2915a61 100644
--- a/src/text_buffer.py
+++ b/src/text_buffer.py
@@ -21,7 +21,8 @@ from theming import get_theme
message_fields = 'txt nick_color time str_time nickname user identifier highlight me old_message revisions jid'
Message = collections.namedtuple('Message', message_fields)
-class CorrectionError(Exception): pass
+class CorrectionError(Exception):
+ pass
def other_elems(self):
acc = ['Message(']
@@ -29,16 +30,16 @@ def other_elems(self):
fields.remove('old_message')
for field in fields:
acc.append('%s=%s' % (field, repr(getattr(self, field))))
- return (', '.join(acc) + ', old_message=')
+ return ', '.join(acc) + ', old_message='
def repr_message(self):
init = other_elems(self)
acc = [init]
- next = self.old_message
+ next_message = self.old_message
rev = 1
- while next:
- acc.append(other_elems(next))
- next = next.old_message
+ while next_message:
+ acc.append(other_elems(next_message))
+ next_message = next_message.old_message
rev += 1
acc.append('None')
while rev:
@@ -69,7 +70,8 @@ class TextBuffer(object):
return self.messages[-1] if self.messages else None
- def make_message(self, txt, time, nickname, nick_color, history, user, identifier, str_time=None, highlight=False, old_message=None, revisions=0, jid=None):
+ @staticmethod
+ def make_message(txt, time, nickname, nick_color, history, user, identifier, str_time=None, highlight=False, old_message=None, revisions=0, jid=None):
time = time or datetime.now()
me = False
if txt.startswith('/me '):
diff --git a/src/theming.py b/src/theming.py
index af8c7d36..2993b8d3 100644
--- a/src/theming.py
+++ b/src/theming.py
@@ -226,7 +226,43 @@ class Theme(object):
# A list of colors randomly attributed to nicks in MUCs
# Setting more colors makes it harder to have two nicks with the same color,
# avoiding confusions.
- LIST_COLOR_NICKNAMES = [(1, -1), (2, -1), (3, -1), (4, -1), (5, -1), (6, -1), (9, -1), (10, -1), (11, -1), (12, -1), (13, -1), (14, -1), (19, -1), (20, -1), (21, -1), (22, -1), (23, -1), (24, -1), (25, -1), (26, -1), (27, -1), (28, -1), (29, -1), (30, -1), (31, -1), (32, -1), (33, -1), (34, -1), (35, -1), (36, -1), (37, -1), (38, -1), (39, -1), (40, -1), (41, -1), (42, -1), (43, -1), (44, -1), (45, -1), (46, -1), (47, -1), (48, -1), (49, -1), (50, -1), (51, -1), (54, -1), (55, -1), (56, -1), (57, -1), (58, -1), (60, -1), (61, -1), (62, -1), (63, -1), (64, -1), (65, -1), (66, -1), (67, -1), (68, -1), (69, -1), (70, -1), (71, -1), (72, -1), (73, -1), (74, -1), (75, -1), (76, -1), (77, -1), (78, -1), (79, -1), (80, -1), (81, -1), (82, -1), (83, -1), (84, -1), (85, -1), (86, -1), (87, -1), (88, -1), (89, -1), (90, -1), (91, -1), (92, -1), (93, -1), (94, -1), (95, -1), (96, -1), (97, -1), (98, -1), (99, -1), (100, -1), (101, -1), (103, -1), (104, -1), (105, -1), (106, -1), (107, -1), (108, -1), (109, -1), (110, -1), (111, -1), (112, -1), (113, -1), (114, -1), (115, -1), (116, -1), (117, -1), (118, -1), (119, -1), (120, -1), (121, -1), (122, -1), (123, -1), (124, -1), (125, -1), (126, -1), (127, -1), (128, -1), (129, -1), (130, -1), (131, -1), (132, -1), (133, -1), (134, -1), (135, -1), (136, -1), (137, -1), (138, -1), (139, -1), (140, -1), (141, -1), (142, -1), (143, -1), (144, -1), (145, -1), (146, -1), (147, -1), (148, -1), (149, -1), (150, -1), (151, -1), (152, -1), (153, -1), (154, -1), (155, -1), (156, -1), (157, -1), (158, -1), (159, -1), (160, -1), (161, -1), (162, -1), (163, -1), (164, -1), (165, -1), (166, -1), (167, -1), (168, -1), (169, -1), (170, -1), (171, -1), (172, -1), (173, -1), (174, -1), (175, -1), (176, -1), (177, -1), (178, -1), (179, -1), (180, -1), (181, -1), (182, -1), (183, -1), (184, -1), (185, -1), (186, -1), (187, -1), (188, -1), (189, -1), (190, -1), (191, -1), (192, -1), (193, -1), (196, -1), (197, -1), (198, -1), (199, -1), (200, -1), (201, -1), (202, -1), (203, -1), (204, -1), (205, -1), (206, -1), (207, -1), (208, -1), (209, -1), (210, -1), (211, -1), (212, -1), (213, -1), (214, -1), (215, -1), (216, -1), (217, -1), (218, -1), (219, -1), (220, -1), (221, -1), (222, -1), (223, -1), (224, -1), (225, -1), (226, -1), (227, -1)]
+ LIST_COLOR_NICKNAMES = [
+ (1, -1), (2, -1), (3, -1), (4, -1), (5, -1), (6, -1), (9, -1),
+ (10, -1), (11, -1), (12, -1), (13, -1), (14, -1), (19, -1),
+ (20, -1), (21, -1), (22, -1), (23, -1), (24, -1), (25, -1),
+ (26, -1), (27, -1), (28, -1), (29, -1), (30, -1), (31, -1),
+ (32, -1), (33, -1), (34, -1), (35, -1), (36, -1), (37, -1),
+ (38, -1), (39, -1), (40, -1), (41, -1), (42, -1), (43, -1),
+ (44, -1), (45, -1), (46, -1), (47, -1), (48, -1), (49, -1),
+ (50, -1), (51, -1), (54, -1), (55, -1), (56, -1), (57, -1),
+ (58, -1), (60, -1), (61, -1), (62, -1), (63, -1), (64, -1),
+ (65, -1), (66, -1), (67, -1), (68, -1), (69, -1), (70, -1),
+ (71, -1), (72, -1), (73, -1), (74, -1), (75, -1), (76, -1),
+ (77, -1), (78, -1), (79, -1), (80, -1), (81, -1), (82, -1),
+ (83, -1), (84, -1), (85, -1), (86, -1), (87, -1), (88, -1),
+ (89, -1), (90, -1), (91, -1), (92, -1), (93, -1), (94, -1),
+ (95, -1), (96, -1), (97, -1), (98, -1), (99, -1), (100, -1),
+ (101, -1), (103, -1), (104, -1), (105, -1), (106, -1), (107, -1),
+ (108, -1), (109, -1), (110, -1), (111, -1), (112, -1), (113, -1),
+ (114, -1), (115, -1), (116, -1), (117, -1), (118, -1), (119, -1),
+ (120, -1), (121, -1), (122, -1), (123, -1), (124, -1), (125, -1),
+ (126, -1), (127, -1), (128, -1), (129, -1), (130, -1), (131, -1),
+ (132, -1), (133, -1), (134, -1), (135, -1), (136, -1), (137, -1),
+ (138, -1), (139, -1), (140, -1), (141, -1), (142, -1), (143, -1),
+ (144, -1), (145, -1), (146, -1), (147, -1), (148, -1), (149, -1),
+ (150, -1), (151, -1), (152, -1), (153, -1), (154, -1), (155, -1),
+ (156, -1), (157, -1), (158, -1), (159, -1), (160, -1), (161, -1),
+ (162, -1), (163, -1), (164, -1), (165, -1), (166, -1), (167, -1),
+ (168, -1), (169, -1), (170, -1), (171, -1), (172, -1), (173, -1),
+ (174, -1), (175, -1), (176, -1), (177, -1), (178, -1), (179, -1),
+ (180, -1), (181, -1), (182, -1), (183, -1), (184, -1), (185, -1),
+ (186, -1), (187, -1), (188, -1), (189, -1), (190, -1), (191, -1),
+ (192, -1), (193, -1), (196, -1), (197, -1), (198, -1), (199, -1),
+ (200, -1), (201, -1), (202, -1), (203, -1), (204, -1), (205, -1),
+ (206, -1), (207, -1), (208, -1), (209, -1), (210, -1), (211, -1),
+ (212, -1), (213, -1), (214, -1), (215, -1), (216, -1), (217, -1),
+ (218, -1), (219, -1), (220, -1), (221, -1), (222, -1), (223, -1),
+ (224, -1), (225, -1), (226, -1), (227, -1)]
# This is your own nickname
COLOR_OWN_NICK = (254, -1)
@@ -474,9 +510,7 @@ def reload_theme():
update_themes_dir()
if __name__ == '__main__':
- """
- Display some nice text with nice colors
- """
+ # Display some nice text with nice colors
s = curses.initscr()
curses.start_color()
curses.use_default_colors()
diff --git a/src/windows.py b/src/windows.py
index b7817583..cbd661ec 100644
--- a/src/windows.py
+++ b/src/windows.py
@@ -38,14 +38,16 @@ import collections
from theming import get_theme, to_curses_attr, read_tuple
FORMAT_CHAR = '\x19'
-# These are non-printable chars, so they should never appear in the input, I
-# guess. But maybe we can find better chars that are even less reasky.
-format_chars = ['\x0E', '\x0F', '\x10', '\x11', '\x12','\x13', '\x14', '\x15','\x16', '\x17', '\x18']
+# These are non-printable chars, so they should never appear in the input,
+# I guess. But maybe we can find better chars that are even less risky.
+format_chars = ['\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13',
+ '\x14', '\x15', '\x16', '\x17', '\x18']
+# different colors allowed in the input
allowed_color_digits = ('0', '1', '2', '3', '4', '5', '6', '7')
-# msg is a reference to the corresponding Message tuple. text_start and text_end are the position
-# delimiting the text in this line.
-# first is a bool telling if this is the first line of the message.
+
+# msg is a reference to the corresponding Message tuple. text_start and
+# text_end are the position delimiting the text in this line.
Line = collections.namedtuple('Line', 'msg start_pos end_pos prepend')
g_lock = RLock()
@@ -133,6 +135,9 @@ class Win(object):
try:
self._win.addnstr(*args)
except:
+ # this actually mostly returns ERR, but works.
+ # more specifically, when the added string reaches the end
+ # of the screen.
pass
def addstr(self, *args):
@@ -202,7 +207,7 @@ class Win(object):
Write colored spaces until the end of line
"""
(y, x) = self._win.getyx()
- size = self.width-x
+ size = self.width - x
if color:
self.addnstr(' '*size, size, to_curses_attr(color))
else:
@@ -234,7 +239,7 @@ class UserList(Win):
self.addstr(y, self.width-2, '++', to_curses_attr(get_theme().COLOR_MORE_INDICATOR))
def refresh(self, users):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
if config.get("hide_user_list", False):
return # do not refresh if this win is hidden.
with g_lock:
@@ -254,7 +259,9 @@ class UserList(Win):
for user in users[self.pos:]:
self.draw_role_affiliation(y, user)
self.draw_status_chatstate(y, user)
- self.addstr(y, 2, poopt.cut_by_columns(user.nick, self.width-2), to_curses_attr(user.color))
+ self.addstr(y, 2,
+ poopt.cut_by_columns(user.nick, self.width - 2),
+ to_curses_attr(user.color))
if config.get('user_list_sort', 'desc').lower() == 'asc':
y -= 1
else:
@@ -294,10 +301,11 @@ class UserList(Win):
def resize(self, height, width, y, x):
with g_lock:
+ separator = to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR)
self._resize(height, width, y, x)
- self._win.attron(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))
+ self._win.attron(separator)
self._win.vline(0, 0, curses.ACS_VLINE, self.height)
- self._win.attroff(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))
+ self._win.attroff(separator)
class Topic(Win):
def __init__(self):
@@ -305,7 +313,7 @@ class Topic(Win):
self._message = ''
def refresh(self, topic=None):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
if topic:
@@ -328,7 +336,7 @@ class GlobalInfoBar(Win):
Win.__init__(self)
def refresh(self):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
self.addstr(0, 0, "[", to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
@@ -338,7 +346,11 @@ class GlobalInfoBar(Win):
show_nums = config.get('show_tab_numbers', True)
use_nicks = config.get('use_tab_nicks', True)
# ignore any remaining gap tabs if the feature is not enabled
- sorted_tabs = [tab for tab in self.core.tabs if tab] if not create_gaps else self.core.tabs[:]
+ if create_gaps:
+ sorted_tabs = self.core.tabs[:]
+ else:
+ sorted_tabs = [tab for tab in self.core.tabs if tab]
+
for nb, tab in enumerate(sorted_tabs):
if not tab: continue
color = tab.color
@@ -395,15 +407,20 @@ class VerticalGlobalInfoBar(Win):
sorted_tabs = sorted_tabs[pos-height//2 : pos+height//2]
for y, tab in enumerate(sorted_tabs):
color = tab.vertical_color
- self.addstr(y if config.get('vertical_tab_list_sort', 'desc') != 'asc' else height - y - 1, 0, "%2d" % tab.nb, to_curses_attr(get_theme().COLOR_VERTICAL_TAB_NUMBER))
+
+ if not config.get('vertical_tab_list_sort', 'desc') != 'asc':
+ y = height - y - 1
+ self.addstr(y, 0, "%2d" % tab.nb,
+ to_curses_attr(get_theme().COLOR_VERTICAL_TAB_NUMBER))
self.addstr('.')
if use_nicks:
self.addnstr("%s" % tab.get_nick(), width - 4, to_curses_attr(color))
else:
self.addnstr("%s" % tab.get_name(), width - 4, to_curses_attr(color))
- self._win.attron(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))
+ separator = to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR)
+ self._win.attron(separator)
self._win.vline(0, width-1, curses.ACS_VLINE, height)
- self._win.attroff(to_curses_attr(get_theme().COLOR_VERTICAL_SEPARATOR))
+ self._win.attroff(separator)
self._refresh()
class InfoWin(Win):
@@ -435,11 +452,12 @@ class XMLInfoWin(InfoWin):
log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
+ bar = to_curses_attr(get_theme().COLOR_INFORMATION_BAR)
if not filter_t:
- self.addstr('[No filter]', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
+ self.addstr('[No filter]', bar)
else:
info = '[%s] %s' % (filter_t, filter)
- self.addstr(info, to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
+ self.addstr(info, bar)
self.print_scroll_position(window)
self.finish_line(get_theme().COLOR_INFORMATION_BAR)
self._refresh()
@@ -453,7 +471,7 @@ class PrivateInfoWin(InfoWin):
InfoWin.__init__(self)
def refresh(self, name, window, chatstate, informations):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
self.write_room_name(name)
@@ -492,7 +510,7 @@ class MucListInfoWin(InfoWin):
self.message = message
def refresh(self, name=None, window=None):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
if name:
@@ -517,7 +535,7 @@ class ConversationInfoWin(InfoWin):
# contact can be None, if we receive a message
# from someone not in our roster. In this case, we display
# only the maximum information from the message we can get.
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
jid = safeJID(jid)
if contact:
if jid.resource:
@@ -526,8 +544,8 @@ class ConversationInfoWin(InfoWin):
resource = contact.get_highest_priority_resource()
else:
resource = None
- # if contact is None, then resource is None too: user is not in the roster
- # so we know almost nothing about it
+ # if contact is None, then resource is None too:
+ # user is not in the roster so we know almost nothing about it
# If contact is a Contact, then
# resource can now be a Resource: user is in the roster and online
# or resource is None: user is in the roster but offline
@@ -548,7 +566,8 @@ class ConversationInfoWin(InfoWin):
value returned by the callbacks.
"""
for key in informations:
- self.addstr(informations[key](jid), to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
+ self.addstr(informations[key](jid),
+ to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
def write_resource_information(self, resource):
"""
@@ -591,7 +610,8 @@ class DynamicConversationInfoWin(ConversationInfoWin):
"""
Just displays the resource in an other color
"""
- log.debug("write_contact_jid DynamicConversationInfoWin, jid: %s" % jid.resource)
+ log.debug("write_contact_jid DynamicConversationInfoWin, jid: %s",
+ jid.resource)
self.addstr('[', to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
self.addstr(jid.bare, to_curses_attr(get_theme().COLOR_CONVERSATION_NAME))
if jid.resource:
@@ -606,7 +626,7 @@ class ConversationStatusMessageWin(InfoWin):
InfoWin.__init__(self)
def refresh(self, jid, contact):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
jid = safeJID(jid)
if contact:
if jid.resource:
@@ -634,7 +654,7 @@ class MucInfoWin(InfoWin):
InfoWin.__init__(self)
def refresh(self, room, window=None):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
self.write_room_name(room)
@@ -748,7 +768,7 @@ class TextWin(Win):
self.hl_pos += 1
else:
self.hl_pos = hl_size
- log.debug("self.hl_pos = %s" % self.hl_pos)
+ log.debug("self.hl_pos = %s", self.hl_pos)
hl = self.highlights[self.hl_pos]
pos = None
while not pos:
@@ -761,7 +781,7 @@ class TextWin(Win):
self.pos = 0
return
hl = self.highlights[0]
- self.pos = len(self.built_lines) - pos - self.height
+ self.pos = len(self.built_lines) - pos - self.height
if self.pos < 0 or self.pos >= len(self.built_lines):
self.pos = 0
@@ -775,13 +795,13 @@ class TextWin(Win):
log.debug('Going to the previous highlight…')
if not self.highlights or self.hl_pos <= 0:
self.hl_pos = float('nan')
- self.pos = 0
+ self.pos = 0
return
if self.hl_pos != self.hl_pos:
self.hl_pos = len(self.highlights) - 1
elif self.hl_pos > 0:
self.hl_pos -= 1
- log.debug("self.hl_pos = %s" % self.hl_pos)
+ log.debug("self.hl_pos = %s", self.hl_pos)
hl = self.highlights[self.hl_pos]
pos = None
while not pos:
@@ -831,7 +851,7 @@ class TextWin(Win):
# review all the highlights since the separator was placed, in
# the correct order.
self.hl_pos = len(self.highlights) - self.nb_of_highlights_after_separator - 1
- log.debug("self.hl_pos = %s" % self.hl_pos)
+ log.debug("self.hl_pos = %s", self.hl_pos)
def remove_line_separator(self):
"""
@@ -871,7 +891,7 @@ class TextWin(Win):
if highlight:
self.highlights.append(lines[0])
self.nb_of_highlights_after_separator += 1
- log.debug("Number of highlights after separator is now %s" % \
+ log.debug("Number of highlights after separator is now %s",
self.nb_of_highlights_after_separator)
if clean:
while len(self.built_lines) > self.lines_nb_limit:
@@ -1053,7 +1073,7 @@ class TextWin(Win):
lines = self.build_message(message, timestamp=with_timestamps)
for line in lines:
self.built_lines.insert(index, line)
- index +=1
+ index += 1
break
def __del__(self):
@@ -1071,7 +1091,7 @@ class HelpText(Win):
self.txt = text
def refresh(self, txt=None):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
if txt:
self.txt = txt
with g_lock:
@@ -1104,7 +1124,7 @@ class YesNoInput(Win):
self.value = False
def refresh(self, txt=None):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
if txt:
self.txt = txt
with g_lock:
@@ -1195,7 +1215,7 @@ class Input(Win):
"""
Whether or not the cursor is at the end of the text.
"""
- assert(len(self.text) >= self.pos)
+ assert len(self.text) >= self.pos
if len(self.text) == self.pos:
return True
return False
@@ -1308,7 +1328,7 @@ class Input(Win):
if reset:
self.reset_completion()
self.pos = len(self.text)
- assert(self.is_cursor_at_end())
+ assert self.is_cursor_at_end()
self.rewrite_text()
return True
@@ -1491,7 +1511,6 @@ class Input(Win):
"""
Normal completion
"""
- (y, x) = self._win.getyx()
pos = self.pos
if pos < len(self.text) and after.endswith(' ') and self.text[pos] == ' ':
after = after[:-1] # remove the last space if we are already on a space
@@ -1520,12 +1539,12 @@ class Input(Win):
pos -= end
hit = self.hit_list[0] # take the first hit
self.text = self.text[:pos] + hit + after + self.text[pos:]
- for i in range(end):
+ for _ in range(end):
try:
self.key_left(reset=False)
except:
pass
- for i in range(len(hit + after)):
+ for _ in range(len(hit) + len(after)):
self.key_right(reset=False)
self.rewrite_text()
@@ -1607,10 +1626,11 @@ class Input(Win):
self.addstr_colored_lite(displayed_text)
# Fill the rest of the line with the input color
if self.color:
- (y, x) = self._win.getyx()
- size = self.width-x
- self.addnstr(' '*size, size, to_curses_attr(self.color))
- self.addstr(0, poopt.wcswidth(displayed_text[:self.pos-self.view_pos]), '')
+ (_, x) = self._win.getyx()
+ size = self.width - x
+ self.addnstr(' ' * size, size, to_curses_attr(self.color))
+ self.addstr(0,
+ poopt.wcswidth(displayed_text[:self.pos-self.view_pos]), '')
if self.color:
self._win.attroff(to_curses_attr(self.color))
curses.curs_set(1)
@@ -1631,14 +1651,14 @@ class Input(Win):
else:
self.view_pos = self.pos - 25
if self.pos >= self.view_pos + self.width - 1:
- self.view_pos = self.pos - self.width + 12
+ self.view_pos = self.pos - self.width + 12
if self.view_pos < 0:
self.view_pos = 0
assert(self.pos > self.view_pos and
self.pos < self.view_pos + self.width)
def refresh(self):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
self.rewrite_text()
def clear_text(self):
@@ -1745,7 +1765,7 @@ class MessageInput(HistoryInput):
self.last_completion = None
self.histo_pos = -1
self.key_func["KEY_UP"] = self.key_up
- self.key_func["M-A"] = self.key_up
+ self.key_func["M-A"] = self.key_up
self.key_func["KEY_DOWN"] = self.key_down
self.key_func["M-B"] = self.key_down
self.key_func['^C'] = self.enter_attrib
@@ -1794,7 +1814,7 @@ class CommandInput(HistoryInput):
self.key_func['^G'] = self.abort
self.key_func['^C'] = self.abort
self.key_func["KEY_UP"] = self.key_up
- self.key_func["M-A"] = self.key_up
+ self.key_func["M-A"] = self.key_up
self.key_func["KEY_DOWN"] = self.key_down
self.key_func["M-B"] = self.key_down
self.histo_pos = -1
@@ -1816,7 +1836,7 @@ class CommandInput(HistoryInput):
@property
def history_disabled(self):
- return ('KEY_UP' not in self.key_func and 'KEY_DOWN' not in self.key_func)
+ return 'KEY_UP' not in self.key_func and 'KEY_DOWN' not in self.key_func
def success(self):
"""
@@ -1874,7 +1894,7 @@ class VerticalSeparator(Win):
self._refresh()
def refresh(self):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
self.rewrite_line()
class RosterWin(Win):
@@ -1989,7 +2009,7 @@ class RosterWin(Win):
We display a number of lines from the roster cache
(and rebuild it if needed)
"""
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
self.build_roster_cache(roster)
with g_lock:
# make sure we are within bounds
@@ -2009,7 +2029,7 @@ class RosterWin(Win):
for item in roster_view:
draw_selected = False
- if y -2 + self.start_pos == self.pos:
+ if y -2 + self.start_pos == self.pos:
draw_selected = True
self.selected_row = item
@@ -2042,9 +2062,9 @@ class RosterWin(Win):
The header at the top
"""
self.addstr('Roster: %s/%s contacts' % (
- roster.get_nb_connected_contacts(),
- len(roster))
- ,to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
+ roster.get_nb_connected_contacts(),
+ len(roster)),
+ to_curses_attr(get_theme().COLOR_INFORMATION_BAR))
self.finish_line(get_theme().COLOR_INFORMATION_BAR)
def draw_group(self, y, group, colored):
@@ -2086,7 +2106,7 @@ class RosterWin(Win):
presence = resource.presence
nb = ' (%s)' % len(contact)
color = theme.color_show(presence)
- added = 2 + len(theme.CHAR_STATUS) + len(nb)
+ added = 2 + len(theme.CHAR_STATUS) + len(nb)
self.addstr(y, 0, ' ')
self.addstr(theme.CHAR_STATUS, to_curses_attr(color))
@@ -2233,7 +2253,7 @@ class ContactInfoWin(Win):
self.finish_line(get_theme().COLOR_INFORMATION_BAR)
def refresh(self, selected_row):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
if isinstance(selected_row, RosterGroup):
@@ -2288,7 +2308,7 @@ class ListWin(Win):
elif asc:
self.lines.sort(key=lambda x: x[col_name])
else:
- self.lines.sort(key=lambda x: x[col_name],reverse=True)
+ self.lines.sort(key=lambda x: x[col_name], reverse=True)
self.refresh()
curses.doupdate()
@@ -2406,7 +2426,7 @@ class ColumnHeaderWin(Win):
return self._columns
def refresh(self):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
x = 0
@@ -2427,13 +2447,13 @@ class ColumnHeaderWin(Win):
x += size
self._refresh()
- def sel_column(self,dic):
+ def sel_column(self, dic):
self._column_sel = dic
def get_sel_column(self):
return self._column_sel
- def set_order(self,order):
+ def set_order(self, order):
self._column_order = self._column_sel
self._column_order_asc = order
@@ -2492,7 +2512,7 @@ class SimpleTextWin(Win):
self.built_lines.append(line)
def refresh(self):
- log.debug('Refresh: %s',self.__class__.__name__)
+ log.debug('Refresh: %s', self.__class__.__name__)
with g_lock:
self._win.erase()
for y, line in enumerate(self.built_lines):