Commit f3a751b3 authored by Link Mauve's avatar Link Mauve
Browse files

mypy: Type some more things

This lets us pass under mypy 0.971, and is yet another step towards
mypyc compatibility perhaps.
parent 940f5e0c
......@@ -21,6 +21,7 @@ from typing import (
)
from slixmpp import InvalidJID, JID
from slixmpp.roster import RosterItem
log = logging.getLogger(__name__)
......@@ -74,7 +75,7 @@ class Contact:
to get the resource with the highest priority, etc
"""
def __init__(self, item):
def __init__(self, item: RosterItem):
"""
item: a slixmpp RosterItem pointing to that contact
"""
......@@ -96,7 +97,7 @@ class Contact:
return self.__item.jid
@property
def name(self):
def name(self) -> str:
"""The name of the contact or an empty string."""
return self.__item['name'] or self._name or ''
......@@ -106,26 +107,27 @@ class Contact:
self._name = value
@property
def ask(self):
def ask(self) -> Optional[str]:
if self.__item['pending_out']:
return 'asked'
return None
@property
def pending_in(self):
def pending_in(self) -> bool:
"""We received a subscribe stanza from this contact."""
return self.__item['pending_in']
@pending_in.setter
def pending_in(self, value):
def pending_in(self, value: bool):
self.__item['pending_in'] = value
@property
def pending_out(self):
def pending_out(self) -> bool:
"""We sent a subscribe stanza to this contact."""
return self.__item['pending_out']
@pending_out.setter
def pending_out(self, value):
def pending_out(self, value: bool):
self.__item['pending_out'] = value
@property
......
......@@ -984,7 +984,7 @@ class CommandCore:
bare = JID(jid).bare
except InvalidJID:
return self.core.information('Invalid JID for /impromptu: %s' % args[0], 'Error')
jids.add(bare)
jids.add(JID(bare))
asyncio.create_task(self.core.impromptu(jids))
......
......@@ -276,7 +276,7 @@ class Core:
self.key_func.try_execute = self.try_execute
# Add handlers
xmpp_event_handlers = [
xmpp_event_handlers: List[Tuple[str, Callable[..., Any]]] = [
('attention', self.handler.on_attention),
('carbon_received', self.handler.on_carbon_received),
('carbon_sent', self.handler.on_carbon_sent),
......
......@@ -1180,25 +1180,26 @@ class HandlerCore:
We are sending a new stanza, write it in the xml buffer if needed.
"""
if self.core.xml_tab:
stanza_str = str(stanza)
if PYGMENTS:
xhtml_text = highlight(str(stanza), LEXER, FORMATTER)
xhtml_text = highlight(stanza_str, LEXER, FORMATTER)
poezio_colored = xhtml.xhtml_to_poezio_colors(
xhtml_text, force=True).rstrip('\x19o').strip()
else:
poezio_colored = str(stanza)
poezio_colored = stanza_str
self.core.xml_buffer.add_message(
XMLLog(txt=poezio_colored, incoming=False),
)
try:
if self.core.xml_tab.match_stanza(
ElementBase(ET.fromstring(stanza))):
ElementBase(ET.fromstring(stanza_str))):
self.core.xml_tab.filtered_buffer.add_message(
XMLLog(txt=poezio_colored, incoming=False),
)
except:
# Most of the time what gets logged is whitespace pings. Skip.
# And also skip tab updates.
if stanza.strip() == '':
if stanza_str.strip() == '':
return None
log.debug('', exc_info=True)
......
......@@ -5,14 +5,15 @@ upstream.
TODO: Check that they are fixed and remove those hacks
"""
from slixmpp import ClientXMPP, Message
from slixmpp import Message
from slixmpp.plugins.xep_0184 import XEP_0184
import logging
log = logging.getLogger(__name__)
def _filter_add_receipt_request(self: ClientXMPP, stanza):
def _filter_add_receipt_request(self: XEP_0184, stanza):
"""
Auto add receipt requests to outgoing messages, if:
......
......@@ -184,7 +184,7 @@ class Logger:
self._check_and_create_log_dir(room)
log.debug('Log handle for %s re-created', room)
def _check_and_create_log_dir(self, jid: str,
def _check_and_create_log_dir(self, jid: Union[str, JID],
open_fd: bool = True) -> Optional[IO[str]]:
"""
Check that the directory where we want to log the messages
......
......@@ -130,7 +130,7 @@ def _parse_message(msg: SMessage) -> Dict:
}
def _ignore_private_message(stanza: SMessage, filter_jid: JID) -> bool:
def _ignore_private_message(stanza: SMessage, filter_jid: Optional[JID]) -> bool:
"""Returns True if a MUC-PM should be ignored, as prosody returns
all PMs within the same room.
"""
......
......@@ -426,7 +426,7 @@ class BasePlugin(object, metaclass=SafetyMetaclass):
self.init()
@property
def name(self):
def name(self) -> str:
"""
Get the name (module name) of the plugin.
"""
......
......@@ -234,7 +234,8 @@ class E2EEPlugin(BasePlugin):
for section in config.sections():
value = config.getstr('encryption', section=section)
if value and value == self.encryption_short_name:
self._enabled_tabs[section] = self.encrypt
section_jid = JID(section)
self._enabled_tabs[section_jid] = self.encrypt
def cleanup(self):
ConversationTab.remove_information_element(self.encryption_short_name)
......
......@@ -71,7 +71,7 @@ class Roster:
self.last_modified = datetime.now()
@property
def needs_rebuild(self):
def needs_rebuild(self) -> bool:
return self.last_modified >= self.last_built
def __getitem__(self, key):
......@@ -133,7 +133,7 @@ class Roster:
return False
@property
def jid(self):
def jid(self) -> JID:
"""Our JID"""
return self.__node.jid
......
......@@ -18,21 +18,25 @@ class SizeManager:
self._core = core
@property
def tab_degrade_x(self):
def tab_degrade_x(self) -> bool:
if base_wins.TAB_WIN is None:
raise ValueError
_, x = base_wins.TAB_WIN.getmaxyx()
return x < THRESHOLD_WIDTH_DEGRADE
@property
def tab_degrade_y(self):
def tab_degrade_y(self) -> bool:
if base_wins.TAB_WIN is None:
raise ValueError
y, x = base_wins.TAB_WIN.getmaxyx()
return y < THRESHOLD_HEIGHT_DEGRADE
@property
def core_degrade_x(self):
def core_degrade_x(self) -> bool:
y, x = self._core.stdscr.getmaxyx()
return x < FULL_WIDTH_DEGRADE
@property
def core_degrade_y(self):
def core_degrade_y(self) -> bool:
y, x = self._core.stdscr.getmaxyx()
return y < FULL_HEIGHT_DEGRADE
......@@ -170,15 +170,15 @@ class Tab:
return 1
@property
def info_win(self):
def info_win(self) -> windows.TextWin:
return self.core.information_win
@property
def color(self):
def color(self) -> Union[Tuple[int, int], Tuple[int, int, 'str']]:
return STATE_COLORS[self._state]()
@property
def vertical_color(self):
def vertical_color(self) -> Union[Tuple[int, int], Tuple[int, int, 'str']]:
return VERTICAL_STATE_COLORS[self._state]()
@property
......@@ -492,7 +492,7 @@ class GapTab(Tab):
return 0
@property
def name(self):
def name(self) -> str:
return ''
def refresh(self):
......
......@@ -83,8 +83,8 @@ class ConversationTab(OneToOneTab):
self.update_keys()
@property
def general_jid(self):
return self.jid.bare
def general_jid(self) -> JID:
return JID(self.jid.bare)
def get_info_header(self):
raise NotImplementedError
......
......@@ -556,7 +556,7 @@ class MucTab(ChatTab):
"""
replaced_id = message.message['replace']['id']
if replaced_id != '' and config.get_by_tabname(
'group_corrections', message.room_from):
'group_corrections', JID(message.room_from)):
try:
delayed_date = message.date or datetime.now()
modify_hl = self.modify_message(
......
......@@ -85,14 +85,14 @@ class PrivateTab(OneToOneTab):
return super().remote_user_color()
@property
def general_jid(self):
def general_jid(self) -> JID:
return self.jid
def get_dest_jid(self):
def get_dest_jid(self) -> JID:
return self.jid
@property
def nick(self):
def nick(self) -> str:
return self.get_nick()
def ack_message(self, msg_id: str, msg_jid: JID):
......
......@@ -14,7 +14,7 @@ import ssl
from functools import partial
from os import getenv, path
from pathlib import Path
from typing import Dict, Callable
from typing import Dict, Callable, Union
from slixmpp import JID, InvalidJID
from slixmpp.exceptions import IqError, IqTimeout
......@@ -199,7 +199,7 @@ class RosterInfoTab(Tab):
completion=self.completion_cert_fetch)
@property
def selected_row(self):
def selected_row(self) -> Union[Contact, Resource]:
return self.roster_win.get_selected_row()
@command_args_parser.ignored
......
#!/usr/bin/env python3
# Copyright 2010-2011 Florent Le Coz <louiz@louiz.org>
#
# This file is part of Poezio.
......@@ -391,7 +392,7 @@ class Theme:
}
@property
def ccg_palette(self):
def ccg_palette(self) -> Optional[Dict[float, int]]:
prepare_ccolor_palette(self)
return self.CCG_PALETTE
......
......@@ -2,6 +2,8 @@
Defines a window which contains either an image or a border.
"""
from __future__ import annotations
import curses
from io import BytesIO
......@@ -9,9 +11,6 @@ try:
from PIL import Image
HAS_PIL = True
except ImportError:
class Image: # type: ignore
class Image:
pass
HAS_PIL = False
try:
......
......@@ -278,7 +278,7 @@ class RosterWin(Win):
elif contact.name and contact.name != contact.bare_jid:
display_name = '%s (%s)' % (contact.name, contact.bare_jid)
else:
display_name = contact.bare_jid
display_name = str(contact.bare_jid)
display_name = self.truncate_name(display_name, added) + nb
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment