diff options
author | Philipp Hörist <philipp@hoerist.com> | 2023-05-28 14:56:11 +0300 |
---|---|---|
committer | Philipp Hörist <philipp@hoerist.com> | 2023-05-28 15:49:49 +0300 |
commit | dc0e24693622b8b475fb4cc82866166c1bec50d8 (patch) | |
tree | 7eee1cf7732b0d653d8db1bd8b54b91b71eca122 | |
parent | 9a7f27ea9b7ceed516fc96732953a8c02bed47f3 (diff) |
cq: Use union operator everywhere
170 files changed, 1124 insertions, 1376 deletions
diff --git a/gajim/common/app.py b/gajim/common/app.py index 7eb9b6871..2f1fa89d2 100644 --- a/gajim/common/app.py +++ b/gajim/common/app.py @@ -29,7 +29,6 @@ from __future__ import annotations import typing from typing import Any from typing import cast -from typing import Optional import gc import logging @@ -298,7 +297,7 @@ def detect_dependencies() -> None: log('gajim').info('Used language: %s', LANG) -def detect_desktop_env() -> Optional[str]: +def detect_desktop_env() -> str | None: if sys.platform in ('win32', 'darwin'): return sys.platform @@ -334,7 +333,7 @@ def get_jid_without_resource(jid: str) -> str: def get_number_of_connected_accounts( - accounts_list: Optional[list[str]] = None) -> int: + accounts_list: list[str] | None = None) -> int: ''' Returns the number of connected accounts. You can optionally pass an accounts_list and if you do those will be checked, else all will be checked @@ -425,7 +424,7 @@ def account_is_available(account: str) -> bool: def get_transport_name_from_jid( jid: str, - use_config_setting: bool = True) -> Optional[str]: + use_config_setting: bool = True) -> str | None: ''' Returns 'gg', 'irc' etc @@ -539,7 +538,7 @@ def get_debug_mode() -> bool: return debug_enabled.exists() -def get_stored_bob_data(algo_hash: str) -> Optional[bytes]: +def get_stored_bob_data(algo_hash: str) -> bytes | None: try: return bob_cache[algo_hash] except KeyError: diff --git a/gajim/common/application.py b/gajim/common/application.py index 2fca8439c..47838928a 100644 --- a/gajim/common/application.py +++ b/gajim/common/application.py @@ -13,9 +13,7 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional from typing import TextIO -from typing import Union import cProfile import json @@ -259,12 +257,12 @@ class CoreApplication(ged.EventHelper): import warnings os.environ['GAJIM_LEAK'] = 'true' - def warn_with_traceback(message: Union[Warning, str], + def warn_with_traceback(message: Warning | str, category: type[Warning], filename: str, lineno: int, - _file: Optional[TextIO] = None, - line: Optional[str] = None) -> None: + _file: TextIO | None = None, + line: str | None = None) -> None: traceback.print_stack(file=sys.stderr) sys.stderr.write(warnings.formatwarning(message, category, @@ -353,7 +351,7 @@ class CoreApplication(ged.EventHelper): username = 'anon' account_label = f'anon@{domain}' - config: dict[str, Union[str, int, bool]] = { + config: dict[str, str | int | bool] = { 'name': username, 'resource': f'gajim.{get_random_string(8)}', 'account_label': account_label, @@ -428,7 +426,7 @@ class CoreApplication(ged.EventHelper): def change_status(self, status: str, - account: Optional[str] = None + account: str | None = None ) -> None: if account is not None: diff --git a/gajim/common/call_manager.py b/gajim/common/call_manager.py index 852e894ad..6f7b6aed9 100644 --- a/gajim/common/call_manager.py +++ b/gajim/common/call_manager.py @@ -1,7 +1,5 @@ from __future__ import annotations -from typing import Optional - import logging import time @@ -29,19 +27,18 @@ log = logging.getLogger('gajim.c.call_manager') class CallManager(EventHelper): def __init__(self) -> None: EventHelper.__init__(self) - self._account: Optional[str] = None - self._resource_jid: Optional[JID] = None + self._account: str | None = None + self._resource_jid: JID | None = None - self._jingle_audio_sid: Optional[str] = None - self._jingle_video_sid: Optional[str] = None + self._jingle_audio_sid: str | None = None + self._jingle_video_sid: str | None = None self._jingle_audio_state: JingleState = JingleState.NULL self._jingle_video_state: JingleState = JingleState.NULL # Helper for upgrading voice call to voice + video without # having to show a new call row - self._incoming_video_event: Optional[ - events.JingleRequestReceived] = None + self._incoming_video_event: events.JingleRequestReceived | None = None # pylint: disable=line-too-long self.register_events([ @@ -156,8 +153,8 @@ class CallManager(EventHelper): def _set_jingle_state(self, jingle_type: str, state: JingleState, - sid: Optional[str] = None, - reason: Optional[str] = None + sid: str | None = None, + reason: str | None = None ) -> None: if state in ( JingleState.CONNECTING, @@ -216,8 +213,8 @@ class CallManager(EventHelper): def _stop_jingle(self, account: str, full_jid: JID, - sid: Optional[str] = None, - reason: Optional[str] = None + sid: str | None = None, + reason: str | None = None ) -> None: if self._jingle_audio_sid and sid in (self._jingle_audio_sid, None): self._close_jingle_content(account, full_jid, 'audio') @@ -233,7 +230,7 @@ class CallManager(EventHelper): account: str, full_jid: JID, jingle_type: str, - shutdown: Optional[bool] = False + shutdown: bool | None = False ) -> None: if jingle_type == 'audio': if self._jingle_audio_sid is None: @@ -273,7 +270,7 @@ class CallManager(EventHelper): def _get_audio_content(self, account: str, jid: JID - ) -> Optional[JingleAudio]: + ) -> JingleAudio | None: client = app.get_client(account) session = client.get_module('Jingle').get_jingle_session( str(jid), self._jingle_audio_sid) @@ -355,7 +352,7 @@ class CallManager(EventHelper): if video is not None: session.approve_content('video') - def get_active_call_jid(self) -> Optional[JID]: + def get_active_call_jid(self) -> JID | None: return self._resource_jid @staticmethod diff --git a/gajim/common/cert_store.py b/gajim/common/cert_store.py index f501e6aa6..93d155350 100644 --- a/gajim/common/cert_store.py +++ b/gajim/common/cert_store.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import logging from pathlib import Path @@ -87,7 +85,7 @@ class CertificateStore: @staticmethod def _on_certificate_write_finished(_successful: bool, - error: Optional[GLib.Error], + error: GLib.Error | None, path: Path): if error is not None: log.error("Can't store certificate: %s", error.message) diff --git a/gajim/common/client.py b/gajim/common/client.py index 54de2c340..626e65612 100644 --- a/gajim/common/client.py +++ b/gajim/common/client.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import time @@ -63,7 +62,7 @@ from gajim.gtk.util import open_window log = logging.getLogger('gajim.client') -IgnoredTlsErrorsT = Optional[set[Gio.TlsCertificateFlags]] +IgnoredTlsErrorsT = set[Gio.TlsCertificateFlags] | None class Client(Observable): @@ -144,7 +143,7 @@ class Client(Observable): return self._client.features @property - def local_address(self) -> Optional[str]: + def local_address(self) -> str | None: address = self._client.local_address if address is not None: return address.to_string().split(':')[0] diff --git a/gajim/common/commands.py b/gajim/common/commands.py index f5da1317c..e8a3ae0c0 100644 --- a/gajim/common/commands.py +++ b/gajim/common/commands.py @@ -15,7 +15,6 @@ from typing import Any from typing import Callable from typing import NoReturn -from typing import Optional import argparse import io @@ -248,7 +247,7 @@ class ChatCommands(Observable): def _change_affiliation(self, nick_or_address: str, affiliation: str, - reason: Optional[str]) -> None: + reason: str | None) -> None: contact = self._check_if_joined() @@ -285,7 +284,7 @@ class ChatCommands(Observable): def _affiliate_command(self, args: Any) -> None: self._change_affiliation(args.who, args.affiliation, None) - def _change_role(self, nick: str, role: str, reason: Optional[str]) -> None: + def _change_role(self, nick: str, role: str, reason: str | None) -> None: contact = self._check_if_joined() diff --git a/gajim/common/configpaths.py b/gajim/common/configpaths.py index a9d1cbfcd..0de32dc65 100644 --- a/gajim/common/configpaths.py +++ b/gajim/common/configpaths.py @@ -23,8 +23,6 @@ from __future__ import annotations from typing import cast from typing import Generator -from typing import Optional -from typing import Union import importlib.resources import os @@ -39,7 +37,7 @@ from gajim.common.const import PathLocation from gajim.common.const import PathType from gajim.common.i18n import _ -PathTupleT = tuple[Optional[PathLocation], Path, Optional[PathType]] +PathTupleT = tuple[PathLocation | None, Path, PathType | None] def get(key: str) -> Path: @@ -103,7 +101,7 @@ class ConfigPaths: self._paths: dict[str, PathTupleT] = {} self.profile = '' self.profile_separation = False - self.custom_config_root: Optional[Path] = None + self.custom_config_root: Path | None = None if os.name == 'nt': if gajim.IS_PORTABLE: @@ -156,9 +154,9 @@ class ConfigPaths: def add(self, name: str, - path: Union[Path, str], - location: Optional[PathLocation] = None, - path_type: Optional[PathType] = None, + path: Path | str, + location: PathLocation | None = None, + path_type: PathType | None = None, unique: bool = False) -> None: path = Path(path) diff --git a/gajim/common/const.py b/gajim/common/const.py index f3e5e91e2..dd1e6b3c1 100644 --- a/gajim/common/const.py +++ b/gajim/common/const.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import NamedTuple -from typing import Optional -from typing import Union from enum import Enum from enum import IntEnum @@ -244,7 +242,7 @@ class XmppUriQuery(Enum): JOIN = 'join' @staticmethod - def from_str(s: str) -> Optional[XmppUriQuery]: + def from_str(s: str) -> XmppUriQuery | None: try: return XmppUriQuery(s) except ValueError: @@ -1127,7 +1125,7 @@ class PresenceShowExt(Enum): def is_offline(self): return self == PresenceShowExt.OFFLINE - def __lt__(self, other: Union[PresenceShowExt, PresenceShow]) -> bool: + def __lt__(self, other: PresenceShowExt | PresenceShow) -> bool: if isinstance(other, PresenceShowExt): return False if not isinstance(other, PresenceShow): # pyright: ignore diff --git a/gajim/common/dbus/file_manager.py b/gajim/common/dbus/file_manager.py index f0a9ed887..bf4d2fe7f 100644 --- a/gajim/common/dbus/file_manager.py +++ b/gajim/common/dbus/file_manager.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional import logging @@ -31,7 +30,7 @@ class DBusFileManager(metaclass=Singleton): ''' def __init__(self) -> None: - self._proxy: Optional[Gio.DBusProxy] + self._proxy: Gio.DBusProxy | None Gio.DBusProxy.new_for_bus( Gio.BusType.SESSION, Gio.DBusProxyFlags.DO_NOT_AUTO_START_AT_CONSTRUCTION, diff --git a/gajim/common/dbus/location.py b/gajim/common/dbus/location.py index 383525bf2..d1db2b472 100644 --- a/gajim/common/dbus/location.py +++ b/gajim/common/dbus/location.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging from datetime import datetime @@ -41,7 +40,7 @@ log = logging.getLogger('gajim.c.dbus.location') class LocationListener: - _instance: Optional[LocationListener] = None + _instance: LocationListener | None = None @classmethod def get(cls) -> LocationListener: @@ -54,16 +53,16 @@ class LocationListener: def __init__(self) -> None: self._data: dict[str, Any] = {} self.location_info: dict[str, Any] = {} - self.simple: Optional[Geoclue.Simple] = None - self._current_location: Optional[LocationData] = None + self.simple: Geoclue.Simple | None = None + self._current_location: LocationData | None = None self._running = False - def _emit(self, info: Optional[LocationData]) -> None: + def _emit(self, info: LocationData | None) -> None: self._current_location = info app.ged.raise_event(LocationChanged(info=info)) @property - def current_location(self) -> Optional[LocationData]: + def current_location(self) -> LocationData | None: return self._current_location def _on_location_update(self, simple: Geoclue.Simple, *args: Any) -> None: diff --git a/gajim/common/dbus/logind.py b/gajim/common/dbus/logind.py index ea14a9720..07deb078d 100644 --- a/gajim/common/dbus/logind.py +++ b/gajim/common/dbus/logind.py @@ -21,7 +21,6 @@ Documentation: https://www.freedesktop.org/wiki/Software/systemd/inhibit from __future__ import annotations from typing import Any -from typing import Optional import logging import os @@ -36,7 +35,7 @@ log = logging.getLogger('gajim.c.dbus.logind') class LogindListener: - _instance: Optional[LogindListener] = None + _instance: LogindListener | None = None @classmethod def get(cls) -> LogindListener: @@ -46,7 +45,7 @@ class LogindListener: def __init__(self) -> None: # file descriptor object of the inhibitor - self._inhibit_fd: Optional[int] = None + self._inhibit_fd: int | None = None Gio.bus_watch_name( Gio.BusType.SYSTEM, diff --git a/gajim/common/dbus/music_track.py b/gajim/common/dbus/music_track.py index 7b767e02c..96d9aad5d 100644 --- a/gajim/common/dbus/music_track.py +++ b/gajim/common/dbus/music_track.py @@ -22,7 +22,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from typing import TypedDict import logging @@ -48,7 +47,7 @@ class TrackProperties(TypedDict, total=False): class MusicTrackListener: - _instance: Optional[MusicTrackListener] = None + _instance: MusicTrackListener | None = None @classmethod def get(cls) -> MusicTrackListener: @@ -58,19 +57,19 @@ class MusicTrackListener: def __init__(self) -> None: self.players: dict[str, int] = {} - self.connection: Optional[Gio.DBusConnection] = None - self._current_tune: Optional[TuneData] = None + self.connection: Gio.DBusConnection | None = None + self._current_tune: TuneData | None = None self._running = False if sys.platform not in ('win32', 'darwin'): self.start() - def _emit(self, info: Optional[TuneData]) -> None: + def _emit(self, info: TuneData | None) -> None: self._current_tune = info app.ged.raise_event(MusicTrackChanged(info=info)) @property - def current_tune(self) -> Optional[TuneData]: + def current_tune(self) -> TuneData | None: return self._current_tune def start(self): @@ -181,7 +180,7 @@ class MusicTrackListener: self._get_playing_track(user_data[0]) @staticmethod - def _get_music_info(properties: TrackProperties) -> Optional[TuneData]: + def _get_music_info(properties: TrackProperties) -> TuneData | None: meta = properties.get('Metadata') if meta is None or not meta: return None diff --git a/gajim/common/dbus/system_style.py b/gajim/common/dbus/system_style.py index 52f78f7e9..8a8995f0c 100644 --- a/gajim/common/dbus/system_style.py +++ b/gajim/common/dbus/system_style.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional import logging import sys @@ -32,7 +31,7 @@ log = logging.getLogger('gajim.c.dbus.system_style') class SystemStyleListener: def __init__(self, callback: Callable[..., None]) -> None: - self._prefer_dark: Optional[bool] = None + self._prefer_dark: bool | None = None self._callback = callback if sys.platform in ('win32', 'darwin'): @@ -72,7 +71,7 @@ class SystemStyleListener: def _signal_setting_changed(self, _proxy: Gio.DBusProxy, - _sender_name: Optional[str], + _sender_name: str | None, signal_name: str, parameters: GLib.Variant, *_user_data: Any @@ -88,5 +87,5 @@ class SystemStyleListener: app.ged.raise_event(StyleChanged()) @property - def prefer_dark(self) -> Optional[bool]: + def prefer_dark(self) -> bool | None: return self._prefer_dark diff --git a/gajim/common/events.py b/gajim/common/events.py index ba5b19e52..bce0e5018 100644 --- a/gajim/common/events.py +++ b/gajim/common/events.py @@ -17,7 +17,6 @@ from __future__ import annotations import typing from typing import Any from typing import Callable -from typing import Optional from typing import Union from dataclasses import dataclass @@ -116,10 +115,10 @@ class Notification(ApplicationEvent): type: str title: str text: str - jid: Optional[Union[JID, str]] = None - sub_type: Optional[str] = None - sound: Optional[str] = None - icon_name: Optional[str] = None + jid: JID | str | None = None + sub_type: str | None = None + sound: str | None = None + icon_name: str | None = None @dataclass @@ -153,13 +152,13 @@ class SignedIn(ApplicationEvent): @dataclass class LocationChanged(ApplicationEvent): name: str = field(init=False, default='location-changed') - info: Optional[LocationData] + info: LocationData | None @dataclass class MusicTrackChanged(ApplicationEvent): name: str = field(init=False, default='music-track-changed') - info: Optional[TuneData] + info: TuneData | None @dataclass @@ -169,12 +168,12 @@ class MessageSent(ApplicationEvent): jid: JID message: str message_id: str - msg_log_id: Optional[int] - chatstate: Optional[str] + msg_log_id: int | None + chatstate: str | None timestamp: float additional_data: AdditionalDataDict - label: Optional[SecurityLabel] - correct_id: Optional[str] + label: SecurityLabel | None + correct_id: str | None play_sound: bool @@ -374,7 +373,7 @@ class MessageUpdated(ApplicationEvent): account: str jid: JID msgtxt: str - nickname: Optional[str] + nickname: str | None properties: Any correct_id: str @@ -415,9 +414,9 @@ class MessageReceived(ApplicationEvent): stanza_id: str fjid: str resource: str | None - delayed: Optional[float] - msg_log_id: Optional[int] - displaymarking: Optional[Displaymarking] + delayed: float | None + msg_log_id: int | None + displaymarking: Displaymarking | None @dataclass @@ -502,8 +501,8 @@ class CallUpdated(ApplicationEvent): jingle_type: str audio_state: JingleState video_state: JingleState - audio_sid: Optional[str] - video_sid: Optional[str] + audio_sid: str | None + video_sid: str | None @dataclass @@ -564,7 +563,7 @@ class MucDecline(ApplicationEvent): account: str muc: JID from_: JID - reason: Optional[str] + reason: str | None @dataclass @@ -574,11 +573,11 @@ class MucInvitation(ApplicationEvent): info: Any muc: JID from_: JID - reason: Optional[str] - password: Optional[str] + reason: str | None + password: str | None type: InviteType continued: bool - thread: Optional[str] + thread: str | None @dataclass @@ -604,9 +603,6 @@ class PingReply(ApplicationEvent): seconds: float -PingEventT = Union[PingSent, PingReply, PingError] - - @dataclass class SecCatalogReceived(ApplicationEvent): name: str = field(init=False, default='sec-catalog-received') @@ -630,9 +626,9 @@ class PresenceReceived(ApplicationEvent): id_: str fjid: str timestamp: float - avatar_sha: Optional[str] - user_nick: Optional[str] - idle_time: Optional[float] + avatar_sha: str | None + user_nick: str | None + idle_time: float | None show: str new_show: str old_show: str @@ -725,17 +721,17 @@ class MUCRoomPresenceError(ApplicationEvent): class MUCRoomKicked(ApplicationEvent): name: str = field(init=False, default='muc-room-kicked') timestamp: float - status_codes: Optional[set[StatusCode]] - reason: Optional[str] - actor: Optional[str] + status_codes: set[StatusCode] | None + reason: str | None + actor: str | None @dataclass class MUCRoomDestroyed(ApplicationEvent): name: str = field(init=False, default='muc-room-destroyed') timestamp: float - reason: Optional[str] - alternate: Optional[JID] + reason: str | None + alternate: JID | None @dataclass @@ -744,7 +740,7 @@ class MUCUserJoined(ApplicationEvent): timestamp: float is_self: bool nick: str - status_codes: Optional[set[StatusCode]] + status_codes: set[StatusCode] | None @dataclass @@ -753,9 +749,9 @@ class MUCUserLeft(ApplicationEvent): timestamp: float is_self: bool nick: str - status_codes: Optional[set[StatusCode]] - reason: Optional[str] - actor: Optional[str] + status_codes: set[StatusCode] | None + reason: str | None + actor: str | None @dataclass @@ -765,8 +761,8 @@ class MUCUserRoleChanged(ApplicationEvent): is_self: bool nick: str role: Role - reason: Optional[str] - actor: Optional[str] + reason: str | None + actor: str | None @dataclass @@ -776,8 +772,8 @@ class MUCUserAffiliationChanged(ApplicationEvent): is_self: bool nick: str affiliation: Affiliation - reason: Optional[str] - actor: Optional[str] + reason: str | None + actor: str | None @dataclass diff --git a/gajim/common/file_props.py b/gajim/common/file_props.py index 52b65a4f1..2c26c0b31 100644 --- a/gajim/common/file_props.py +++ b/gajim/common/file_props.py @@ -22,7 +22,6 @@ from __future__ import annotations from typing import Callable from typing import ClassVar from typing import Literal -from typing import Optional class FilesProp: @@ -38,7 +37,7 @@ class FilesProp: return fp @classmethod - def getFileProp(cls, account: str, sid: str) -> Optional[FileProp]: + def getFileProp(cls, account: str, sid: str) -> FileProp | None: return cls._files_props.get((account, sid)) @classmethod @@ -54,7 +53,7 @@ class FilesProp: def getFilePropByType(cls, type_: Literal['r', 's'], sid: str - ) -> Optional[FileProp]: + ) -> FileProp | None: # This method should be deleted. Getting fileprop by type and sid is not # unique enough. More than one fileprop might have the same type and sid files_prop = cls.getAllFileProp() @@ -64,7 +63,7 @@ class FilesProp: return None @classmethod - def getFilePropBySid(cls, sid: str) -> Optional[FileProp]: + def getFilePropBySid(cls, sid: str) -> FileProp | None: # This method should be deleted. It is kept to make things compatible # This method should be replaced and instead get the file_props by # account and sid @@ -78,7 +77,7 @@ class FilesProp: def getFilePropByTransportSid(cls, account: str, sid: str - ) -> Optional[FileProp]: + ) -> FileProp | None: files_prop = cls.getAllFileProp() for fp in files_prop: if fp.account == account and fp.transport_sid == sid: @@ -124,38 +123,38 @@ class FileProp: self.proxy_sender = None self.proxy_receiver = None self.streamhost_used = None - self.failure_cb: Optional[Callable[[str], None]] = None + self.failure_cb: Callable[[str], None] | None = None self.disconnect_cb = None - self.continue_cb: Optional[Callable[..., None]] = None - self.sha_str: Optional[str] = None + self.continue_cb: Callable[..., None] | None = None + self.sha_str: str | None = None # transfer type: 's' for sending and 'r' for receiving - self.type_: Optional[Literal['r', 's']] = None - self.error: Optional[int] = None + self.type_: Literal['r', 's'] | None = None + self.error: int | None = None self.elapsed_time: float = 0 # Elapsed time of the file transfer - self.last_time: Optional[float] = None - self.received_len: Optional[int] = None - self.file_name: Optional[str] = None # full file path - self.name: Optional[str] = None - self.date: Optional[str] = None - self.desc: Optional[str] = None - self.offset: Optional[int] = None - self.sender: Optional[str] = None - self.receiver: Optional[str] = None - self.tt_account: Optional[str] = None - self.size: Optional[int] = None + self.last_time: float | None = None + self.received_len: int | None = None + self.file_name: str | None = None # full file path + self.name: str | None = None + self.date: str | None = None + self.desc: str | None = None + self.offset: int | None = None + self.sender: str | None = None + self.receiver: str | None = None + self.tt_account: str | None = None + self.size: int | None = None self._sid = sid - self.transport_sid: Optional[str] = None + self.transport_sid: str | None = None self.account = account - self.mime_type: Optional[str] = None - self.algo: Optional[str] = None - self.direction: Optional[Literal['<', '>']] = None - self.syn_id: Optional[str] = None - self.seq: Optional[int] = None - self.hash_: Optional[str] = None - self.fd: Optional[int] = None + self.mime_type: str | None = None + self.algo: str | None = None + self.direction: Literal['<', '>'] | None = None + self.syn_id: str | None = None + self.seq: int | None = None + self.hash_: str | None = None + self.fd: int | None = None # Type of the session, if it is 'jingle' or 'si' - self.session_type: Optional[str] = None - self.request_id: Optional[str] = None + self.session_type: str | None = None + self.request_id: str | None = None self.proxyhosts = None self.dstaddr = None diff --git a/gajim/common/filetransfer.py b/gajim/common/filetransfer.py index 8c34d1bf2..d5e1b6e81 100644 --- a/gajim/common/filetransfer.py +++ b/gajim/common/filetransfer.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional from gajim.common.const import FTState from gajim.common.helpers import Observable @@ -31,7 +30,7 @@ class FileTransfer(Observable): self._state = FTState.INIT self._error_text: str = '' - self._error_domain: Optional[str] = None + self._error_domain: str | None = None @property def account(self) -> str: @@ -50,7 +49,7 @@ class FileTransfer(Observable): return self._error_text @property - def error_domain(self) -> Optional[str]: + def error_domain(self) -> str | None: return self._error_domain def get_progress(self) -> float: diff --git a/gajim/common/helpers.py b/gajim/common/helpers.py index c31c9118c..f448e05d4 100644 --- a/gajim/common/helpers.py +++ b/gajim/common/helpers.py @@ -29,9 +29,7 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional from typing import TYPE_CHECKING -from typing import Union import collections import copy @@ -164,7 +162,7 @@ def ascii_to_idn(host: str) -> str: return '.'.join(converted_labels) -def parse_resource(resource: str) -> Optional[str]: +def parse_resource(resource: str) -> str | None: ''' Perform stringprep on resource and return it ''' @@ -199,7 +197,7 @@ def get_uf_sub(sub: str) -> str: return p_('Contact subscription', 'Unknown') -def get_uf_ask(ask: Union[str, None]) -> str: +def get_uf_ask(ask: str | None) -> str: if ask is None: return p_('Contact subscription', 'None') @@ -209,7 +207,7 @@ def get_uf_ask(ask: Union[str, None]) -> str: return ask -def get_uf_role(role: Union[Role, str], plural: bool = False) -> str: +def get_uf_role(role: Role | str, plural: bool = False) -> str: ''' plural determines if you get Moderators or Moderator''' if not isinstance(role, str): role = role.value @@ -231,7 +229,7 @@ def get_uf_role(role: Union[Role, str], plural: bool = False) -> str: return '' -def get_uf_affiliation(affiliation: Union[Affiliation, str], +def get_uf_affiliation(affiliation: Affiliation | str, plural: bool = False ) -> str: '''Get a nice and translated affilition for muc''' @@ -256,7 +254,7 @@ def get_uf_affiliation(affiliation: Union[Affiliation, str], def get_uf_relative_time(date_time: datetime, - now: Optional[datetime] = None + now: datetime | None = None ) -> str: if now is None: # used by unittest @@ -301,7 +299,7 @@ def from_one_line(msg: str) -> str: return msg.replace('\\\\', '\\') -def chatstate_to_string(chatstate: Optional[Chatstate]) -> str: +def chatstate_to_string(chatstate: Chatstate | None) -> str: if chatstate is None: return '' @@ -386,7 +384,7 @@ def generate_qr_code(content: str) -> GdkPixbuf.Pixbuf | None: def play_sound(sound_event: str, - account: Optional[str] = None, + account: str | None = None, force: bool = False, loop: bool = False) -> None: @@ -399,8 +397,8 @@ def play_sound(sound_event: str, def check_soundfile_path(file_: str, - dirs: Optional[list[Path]] = None - ) -> Optional[Path]: + dirs: list[Path] | None = None + ) -> Path | None: ''' Check if the sound file exists @@ -425,8 +423,8 @@ def check_soundfile_path(file_: str, return None -def strip_soundfile_path(file_: Union[Path, str], - dirs: Optional[list[Path]] = None, +def strip_soundfile_path(file_: Path | str, + dirs: list[Path] | None = None, abs_: bool = True): ''' Remove knowns paths from a sound file @@ -526,7 +524,7 @@ def statuses_unified() -> bool: return True -def get_full_jid_from_iq(iq_obj: Iq) -> Optional[str]: +def get_full_jid_from_iq(iq_obj: Iq) -> str | None: ''' Return the full jid (with resource) from an iq ''' @@ -536,7 +534,7 @@ def get_full_jid_from_iq(iq_obj: Iq) -> Optional[str]: return parse_jid(str(iq_obj.getFrom())) -def get_jid_from_iq(iq_obj: Iq) -> Optional[str]: +def get_jid_from_iq(iq_obj: Iq) -> str | None: ''' Return the jid (without resource) from an iq ''' @@ -676,7 +674,7 @@ def jid_is_blocked(account: str, jid: str) -> bool: return jid in client.get_module('Blocking').blocked -def get_subscription_request_msg(account: Optional[str] = None) -> str: +def get_subscription_request_msg(account: str | None = None) -> str: if account is None: return _('I would like to add you to my contact list.') @@ -691,7 +689,7 @@ def get_subscription_request_msg(account: Optional[str] = None) -> str: def get_retraction_text(account: str, moderator_jid: str, - reason: Optional[str]) -> str: + reason: str | None) -> str: client = app.get_client(account) contact = client.get_module('Contacts').get_contact( @@ -702,14 +700,14 @@ def get_retraction_text(account: str, return text -def get_global_proxy() -> Optional[ProxyData]: +def get_global_proxy() -> ProxyData | None: proxy_name = app.settings.get('global_proxy') if not proxy_name: return None return get_proxy(proxy_name) -def get_account_proxy(account: str, fallback=True) -> Optional[ProxyData]: +def get_account_proxy(account: str, fallback=True) -> ProxyData | None: proxy_name = app.settings.get_account_setting(account, 'proxy') if proxy_name: return get_proxy(proxy_name) @@ -719,7 +717,7 @@ def get_account_proxy(account: str, fallback=True) -> Optional[ProxyData]: return None -def get_proxy(proxy_name: str) -> Optional[ProxyData]: +def get_proxy(proxy_name: str) -> ProxyData | None: try: settings = app.settings.get_proxy_settings(proxy_name) except ValueError: @@ -735,7 +733,7 @@ def get_proxy(proxy_name: str) -> Optional[ProxyData]: password=password) -def determine_proxy() -> Optional[ProxyData]: +def determine_proxy() -> ProxyData | None: # Use this method to find a proxy for non-account related http requests # When there is no global proxy and at least one active account does # not use a proxy, we assume no proxy is necessary. @@ -771,8 +769,8 @@ def call_counter(func): def load_json(path: Path, - key: Optional[str] = None, - default: Optional[Any] = None) -> Any: + key: str | None = None, + default: Any | None = None) -> Any: try: with path.open('r', encoding='utf8') as file: json_dict = json.loads(file.read()) @@ -794,7 +792,7 @@ class AdditionalDataDict(collections.UserDict): return full_path.split(':') return [full_path] - def set_value(self, full_path: str, key: str, value: Optional[str]) -> None: + def set_value(self, full_path: str, key: str, value: str | None) -> None: path_childs = self._get_path_childs(full_path) _dict = self.data for path in path_childs: @@ -808,7 +806,7 @@ class AdditionalDataDict(collections.UserDict): def get_value(self, full_path: str, key: str, - default: Optional[str] = None) -> Optional[Any]: + default: str | None = None) -> Any | None: path_childs = self._get_path_childs(full_path) _dict = self.data @@ -1040,7 +1038,7 @@ _xmpp_query_type_handlers = { @catch_exceptions -def open_uri(uri: Union[URI, str], account: Optional[str] = None) -> None: +def open_uri(uri: URI | str, account: str | None = None) -> None: if not isinstance(uri, URI): uri = parse_uri(uri) @@ -1133,7 +1131,7 @@ def show_in_folder(path: Path) -> None: open_directory(path.parent) -def filesystem_path_from_uri(uri: str) -> Optional[Path]: +def filesystem_path_from_uri(uri: str) -> Path | None: puri = parse_uri(uri) if puri.type != URIType.FILE: return None @@ -1144,7 +1142,7 @@ def filesystem_path_from_uri(uri: str) -> Optional[Path]: return Path(puri.data['path']) -def get_file_path_from_dnd_dropped_uri(text: str) -> Optional[Path]: +def get_file_path_from_dnd_dropped_uri(text: str) -> Path | None: uri = text.strip('\r\n\x00') # remove \r\n and NULL return filesystem_path_from_uri(uri) @@ -1184,7 +1182,7 @@ def geo_provider_from_location(lat: str, lon: str) -> str: return f'https://www.openstreetmap.org/?mlat={lat}&mlon={lon}&zoom=16' -def get_resource(account: str) -> Optional[str]: +def get_resource(account: str) -> str | None: resource = app.settings.get_account_setting(account, 'resource') if not resource: return None @@ -1196,7 +1194,7 @@ def get_resource(account: str) -> Optional[str]: return resource -def get_default_muc_config() -> dict[str, Union[bool, str]]: +def get_default_muc_config() -> dict[str, bool | str]: return { # XEP-0045 options 'muc#roomconfig_allowinvites': True, @@ -1218,7 +1216,7 @@ def get_default_muc_config() -> dict[str, Union[bool, str]]: } -def validate_jid(jid: Union[str, JID], type_: Optional[str] = None) -> JID: +def validate_jid(jid: str | JID, type_: str | None = None) -> JID: try: jid = JID.from_string(str(jid)) except InvalidJid as error: @@ -1236,7 +1234,7 @@ def validate_jid(jid: Union[str, JID], type_: Optional[str] = None) -> JID: raise ValueError(f'Not a {type_} JID') -def to_user_string(error: Union[CommonError, StanzaError]) -> str: +def to_user_string(error: CommonError | StanzaError) -> str: text = error.get_text(get_rfc5646_lang()) if text: return text @@ -1262,7 +1260,7 @@ def get_groupchat_name(client: types.Client, jid: JID) -> str: def is_affiliation_change_allowed(self_contact: types.GroupchatParticipant, contact: types.GroupchatParticipant, - target_aff: Union[str, Affiliation]) -> bool: + target_aff: str | Affiliation) -> bool: if isinstance(target_aff, str): target_aff = Affiliation(target_aff) @@ -1305,13 +1303,13 @@ def get_tls_error_phrases(tls_errors: set[Gio.TlsCertificateFlags] class Observable: - def __init__(self, log_: Union[logging.Logger, LogAdapter, None] = None): + def __init__(self, log_: logging.Logger | LogAdapter | None = None): self._log = log_ self._callbacks: types.ObservableCbDict = defaultdict(list) def __disconnect(self, obj: Any, - signals: Optional[set[str]] = None + signals: set[str] | None = None ) -> None: def _remove(handlers: list[weakref.WeakMethod[types.AnyCallableT]] @@ -1335,7 +1333,7 @@ class Observable: def multi_disconnect(self, obj: Any, - signals: Optional[set[str]] + signals: set[str] | None ) -> None: self.__disconnect(obj, signals) @@ -1387,8 +1385,8 @@ class Observable: def write_file_async( path: Path, data: bytes, - callback: Callable[[bool, Optional[GLib.Error], Any], Any], - user_data: Optional[Any] = None): + callback: Callable[[bool, GLib.Error | None, Any], Any], + user_data: Any | None = None): def _on_write_finished(outputstream: Gio.OutputStream, result: Gio.AsyncResult, @@ -1424,10 +1422,10 @@ def write_file_async( def load_file_async(path: Path, - callback: Callable[[Optional[bytes], - Optional[GLib.Error], - Optional[Any]], Any], - user_data: Optional[Any] = None) -> None: + callback: Callable[[bytes | None, + GLib.Error | None, + Any | None], Any], + user_data: Any | None = None) -> None: def _on_load_finished(file: Gio.File, result: Gio.AsyncResult) -> None: @@ -1449,9 +1447,10 @@ def get_x509_cert_from_gio_cert(cert: Gio.TlsCertificate) -> x509.Certificate: glib_bytes.get_data(), default_backend()) -def get_custom_host(account: str) -> Optional[tuple[str, - ConnectionProtocol, - ConnectionType]]: +def get_custom_host( + account: str +) -> tuple[str, ConnectionProtocol, ConnectionType] | None: + if not app.settings.get_account_setting(account, 'use_custom_host'): return None host = app.settings.get_account_setting(account, 'custom_host') @@ -1488,7 +1487,7 @@ def get_idle_status_message(state: str, status_message: str) -> str: } -def get_group_chat_nick(account: str, room_jid: Union[JID, str]) -> str: +def get_group_chat_nick(account: str, room_jid: JID | str) -> str: client = app.get_client(account) bookmark = client.get_module('Bookmarks').get_bookmark(room_jid) diff --git a/gajim/common/i18n.py b/gajim/common/i18n.py index aaa26b683..746056473 100644 --- a/gajim/common/i18n.py +++ b/gajim/common/i18n.py @@ -21,7 +21,6 @@ from __future__ import annotations from typing import cast -from typing import Optional import gettext import importlib.resources @@ -58,13 +57,13 @@ def get_default_lang() -> str: return locale.getdefaultlocale()[0] or 'en' -def get_rfc5646_lang(lang: Optional[str] = None) -> str: +def get_rfc5646_lang(lang: str | None = None) -> str: if lang is None: lang = LANG return lang.replace('_', '-') -def get_short_lang_code(lang: Optional[str] = None) -> str: +def get_short_lang_code(lang: str | None = None) -> str: if lang is None: lang = LANG return lang[:2] @@ -92,8 +91,8 @@ def p_(context: str, message: str) -> str: def ngettext(s_sing: str, s_plural: str, n: int, - replace_sing: Optional[str] = None, - replace_plural: Optional[str] = None) -> str: + replace_sing: str | None = None, + replace_plural: str | None = None) -> str: ''' Use as: i18n.ngettext( diff --git a/gajim/common/idle.py b/gajim/common/idle.py index 4522085f0..5241d33f2 100644 --- a/gajim/common/idle.py +++ b/gajim/common/idle.py @@ -22,7 +22,6 @@ from __future__ import annotations from typing import cast -from typing import Optional import ctypes import ctypes.util @@ -323,7 +322,7 @@ class IdleMonitorManager(GObject.Object): return self.state == IdleState.UNKNOWN @staticmethod - def _get_idle_monitor() -> Optional[IdleMonitor]: + def _get_idle_monitor() -> IdleMonitor | None: if sys.platform == 'win32': return Windows() diff --git a/gajim/common/jingle_content.py b/gajim/common/jingle_content.py index 7a5d45c65..e9e155832 100644 --- a/gajim/common/jingle_content.py +++ b/gajim/common/jingle_content.py @@ -20,7 +20,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional from typing import TYPE_CHECKING import nbxmpp @@ -56,8 +55,8 @@ class JingleContent: def __init__(self, session: JingleSession, - transport: Optional[JingleTransport], - senders: Optional[str] + transport: JingleTransport | None, + senders: str | None ) -> None: self.session = session @@ -65,13 +64,13 @@ class JingleContent: # will be filled by JingleSession.add_content() # don't uncomment these lines, we will catch more buggy code then # (a JingleContent not added to session shouldn't send anything) - self.creator: Optional[str] = None - self.name: Optional[str] = None + self.creator: str | None = None + self.name: str | None = None self.accepted = False self.sent = False self.negotiated = False - self.media: Optional[str] = None + self.media: str | None = None self.senders = senders if self.senders is None: @@ -81,10 +80,10 @@ class JingleContent: self.allow_sending = True # These were found by the Politie - self.file_props: Optional[FileProp] = None + self.file_props: FileProp | None = None self.callbacks: dict[str, list[Callable[ - [nbxmpp.Node, nbxmpp.Node, Optional[nbxmpp.Node], str], + [nbxmpp.Node, nbxmpp.Node, nbxmpp.Node | None, str], None]]] = { # these are called when *we* get stanzas 'content-accept': [self.__on_transport_info, @@ -122,7 +121,7 @@ class JingleContent: def __on_content_accept(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: self.on_negotiated() @@ -140,8 +139,8 @@ class JingleContent: def on_stanza(self, stanza: nbxmpp.Node, - content: Optional[nbxmpp.Node], - error: Optional[nbxmpp.Node], + content: nbxmpp.Node | None, + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -154,7 +153,7 @@ class JingleContent: def __on_transport_replace(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: content.addChild(node=self.transport.make_transport()) @@ -162,7 +161,7 @@ class JingleContent: def __on_transport_info(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -174,7 +173,7 @@ class JingleContent: self.add_remote_candidates(candidates) def __content(self, - payload: Optional[list[nbxmpp.Node]] = None + payload: list[nbxmpp.Node] | None = None ) -> nbxmpp.Node: ''' Build a XML content-wrapper for our data @@ -213,7 +212,7 @@ class JingleContent: def __fill_jingle_stanza(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' diff --git a/gajim/common/jingle_ft.py b/gajim/common/jingle_ft.py index b9a8670e2..a5ebb0009 100644 --- a/gajim/common/jingle_ft.py +++ b/gajim/common/jingle_ft.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from typing import TYPE_CHECKING import logging @@ -77,8 +76,8 @@ class JingleFileTransfer(JingleContent): def __init__(self, session: JingleSession, file_props: FileProp, - transport: Optional[JingleTransport] = None, - senders: Optional[str] = None + transport: JingleTransport | None = None, + senders: str | None = None ) -> None: JingleContent.__init__(self, session, transport, senders) @@ -136,7 +135,7 @@ class JingleFileTransfer(JingleContent): def __state_changed(self, nextstate: State, - args: Optional[dict[str, Any]] = None + args: dict[str, Any] | None = None ) -> None: # Executes the next state action and sets the next state current_state = self.state @@ -149,7 +148,7 @@ class JingleFileTransfer(JingleContent): def __on_session_initiate(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.debug('Jingle FT request received') @@ -258,7 +257,7 @@ class JingleFileTransfer(JingleContent): def __on_session_initiate_sent(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: pass @@ -283,7 +282,7 @@ class JingleFileTransfer(JingleContent): } self.session.connection.get_module('Jingle').set_file_info(file_info) - def _compute_hash(self) -> Optional[nbxmpp.Hashes2]: + def _compute_hash(self) -> nbxmpp.Hashes2 | None: # Calculates the hash and returns a xep-300 hash stanza if self.file_props.algo is None: return @@ -311,7 +310,7 @@ class JingleFileTransfer(JingleContent): def __on_session_accept(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_session_accept') @@ -347,7 +346,7 @@ class JingleFileTransfer(JingleContent): def __on_session_terminate(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_session_terminate') @@ -355,7 +354,7 @@ class JingleFileTransfer(JingleContent): def __on_session_info(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: pass @@ -363,7 +362,7 @@ class JingleFileTransfer(JingleContent): def __on_transport_accept(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_transport_accept') @@ -371,7 +370,7 @@ class JingleFileTransfer(JingleContent): def __on_transport_replace(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_transport_replace') @@ -379,7 +378,7 @@ class JingleFileTransfer(JingleContent): def __on_transport_reject(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_transport_reject') @@ -387,7 +386,7 @@ class JingleFileTransfer(JingleContent): def __on_transport_info(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_transport_info') @@ -443,7 +442,7 @@ class JingleFileTransfer(JingleContent): def __on_iq_result(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: log.info('__on_iq_result') @@ -463,7 +462,7 @@ class JingleFileTransfer(JingleContent): def __transport_setup(self, stanza: nbxmpp.Node, content: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: # Sets up a few transport specific things for the file transfer diff --git a/gajim/common/jingle_ftstates.py b/gajim/common/jingle_ftstates.py index a356d20ff..d954c6557 100644 --- a/gajim/common/jingle_ftstates.py +++ b/gajim/common/jingle_ftstates.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from typing import TYPE_CHECKING import logging @@ -43,7 +42,7 @@ class JingleFileTransferStates: def __init__(self, jingleft: JingleFileTransfer) -> None: self.jft = jingleft - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: ''' This method MUST be overridden by a subclass ''' @@ -55,7 +54,7 @@ class StateInitialized(JingleFileTransferStates): This state initializes the file transfer ''' - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: if self.jft.weinitiate: # update connection's fileprops self.jft._listen_host() @@ -93,7 +92,7 @@ class StateCandSent(JingleFileTransferStates): content.addChild(node=transport) self.jft.session.send_transport_info(content) - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: self._send_candidate(args) @@ -120,7 +119,7 @@ class StateCandReceived(JingleFileTransferStates): # We save the candidate nominated by peer self.jft.nominated_cand['peer-cand'] = streamhost_used - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: self._recv_candidate(args) @@ -131,7 +130,7 @@ class StateCandSentAndRecv(StateCandSent, StateCandReceived): we should execute the action of when we receive or send a candidate. ''' - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: if args['sendCand']: self._send_candidate(args) else: @@ -143,7 +142,7 @@ class StateTransportReplace(JingleFileTransferStates): This state initiates transport replace ''' - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: self.jft.session.transport_replace() @@ -230,7 +229,7 @@ class StateTransfering(JingleFileTransferStates): app.socks5queue.send_file(self.jft.file_props, self.jft.session.connection.name, mode) - def action(self, args: Optional[dict[str, Any]] = None) -> None: + def action(self, args: dict[str, Any] | None = None) -> None: if self.jft.transport.type_ == TransportType.IBB: self._start_ibb_transfer(self.jft.session.connection) elif self.jft.transport.type_ == TransportType.SOCKS5: diff --git a/gajim/common/jingle_rtp.py b/gajim/common/jingle_rtp.py index d317beea2..ebcda169d 100644 --- a/gajim/common/jingle_rtp.py +++ b/gajim/common/jingle_rtp.py @@ -21,7 +21,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import Iterator -from typing import Optional import logging import socket @@ -56,7 +55,7 @@ class JingleRTPContent(JingleContent): def __init__(self, session: JingleSession, media: str, - transport: Optional[JingleTransport] = None + transport: JingleTransport | None = None ) -> None: if transport is None: transport = JingleTransportICEUDP(None) @@ -67,17 +66,17 @@ class JingleRTPContent(JingleContent): 'audio': Farstream.MediaType.AUDIO, 'video': Farstream.MediaType.VIDEO}[media] - self.pipeline: Optional[Gst.Pipeline] = None - self.src_bin: Optional[Gst.Bin] = None + self.pipeline: Gst.Pipeline | None = None + self.src_bin: Gst.Bin | None = None self.stream_failed_once = False self.candidates_ready = False # True when local candidates are prepared # TODO - self.conference: Optional[Farstream.Conference] = None - self.funnel: Optional[Gst.Element] = None - self.p2psession: Optional[Farstream.Session] = None - self.p2pstream: Optional[Farstream.Stream] = None + self.conference: Farstream.Conference | None = None + self.funnel: Gst.Element | None = None + self.p2psession: Farstream.Session | None = None + self.p2pstream: Farstream.Stream | None = None self.available_gst_plugins: list[str] = [] gst_plugin_registry = Gst.Registry.get() @@ -143,7 +142,7 @@ class JingleRTPContent(JingleContent): config_key: str, pipeline: str, text: str - ) -> Optional[Gst.Bin]: + ) -> Gst.Bin | None: pipeline = pipeline % app.settings.get(config_key) log.debug('Pipeline: %s', str(pipeline)) try: @@ -288,7 +287,7 @@ class JingleRTPContent(JingleContent): self.pipeline.set_state(Gst.State.PLAYING) @staticmethod - def get_fallback_src() -> Optional[Gst.Element]: + def get_fallback_src() -> Gst.Element | None: return Gst.ElementFactory.make('fakesrc', None) def on_negotiated(self) -> None: @@ -309,7 +308,7 @@ class JingleRTPContent(JingleContent): def __on_remote_codecs(self, _stanza: nbxmpp.Node, content: nbxmpp.Node, - _error: Optional[nbxmpp.Node], + _error: nbxmpp.Node | None, _action: str ) -> None: ''' @@ -380,7 +379,7 @@ class JingleAudio(JingleRTPContent): def __init__(self, session: JingleSession, - transport: Optional[JingleTransport] = None + transport: JingleTransport | None = None ) -> None: JingleRTPContent.__init__(self, session, 'audio', transport) self.setup_stream() @@ -500,7 +499,7 @@ class JingleAudio(JingleRTPContent): class JingleVideo(JingleRTPContent): def __init__(self, session: JingleSession, - transport: Optional[JingleTransport] = None + transport: JingleTransport | None = None ) -> None: JingleRTPContent.__init__(self, session, 'video', transport) self.sink = None @@ -578,7 +577,7 @@ class JingleVideo(JingleRTPContent): self.pipeline, Gst.DebugGraphDetails.ALL, str(filename)) @staticmethod - def get_fallback_src() -> Optional[Gst.Bin]: + def get_fallback_src() -> Gst.Bin | None: # TODO: Use avatar? pipeline = ('videotestsrc is-live=true ! video/x-raw,framerate=10/1 ! ' 'videoconvert') diff --git a/gajim/common/jingle_session.py b/gajim/common/jingle_session.py index d450fb44e..b2066931b 100644 --- a/gajim/common/jingle_session.py +++ b/gajim/common/jingle_session.py @@ -30,7 +30,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional from typing import TYPE_CHECKING import logging @@ -115,8 +114,8 @@ class JingleSession: con: Client, weinitiate: bool, jid: str, - iq_id: Optional[str] = None, - sid: Optional[str] = None, + iq_id: str | None = None, + sid: str | None = None, werequest: bool = False ) -> None: ''' @@ -157,7 +156,7 @@ class JingleSession: # use .prepend() to add new callbacks, especially when you're going # to send error instead of ack self.callbacks: dict[str, list[Callable[ - [nbxmpp.Node, nbxmpp.Node, Optional[nbxmpp.Node], str], + [nbxmpp.Node, nbxmpp.Node, nbxmpp.Node | None, str], None]]] = { 'content-accept': [self.__ack, self.__on_content_accept, @@ -216,13 +215,13 @@ class JingleSession: reason.addChild('cancel') self._session_terminate(reason) - def approve_content(self, media: str, name: Optional[str] = None) -> None: + def approve_content(self, media: str, name: str | None = None) -> None: content = self.get_content(media, name) if content: content.accepted = True self.on_session_state_changed(content) - def reject_content(self, media: str, name: Optional[str] = None) -> None: + def reject_content(self, media: str, name: str | None = None) -> None: content = self.get_content(media, name) if content: if self.state == JingleStates.ACTIVE: @@ -242,9 +241,9 @@ class JingleSession: self._session_terminate(reason) def get_content(self, - media: Optional[str] = None, - name: Optional[str] = None - ) -> Optional[JingleContent]: + media: str | None = None, + name: str | None = None + ) -> JingleContent | None: if media is None: return None for content in self.contents.values(): @@ -281,7 +280,7 @@ class JingleSession: def remove_content(self, creator: str, name: str, - reason: Optional[nbxmpp.Node] = None + reason: nbxmpp.Node | None = None ) -> None: ''' Remove the content `name` created by `creator` @@ -298,7 +297,7 @@ class JingleSession: def modify_content(self, creator: str, name: str, - transport: Optional[JingleTransport] = None + transport: JingleTransport | None = None ) -> None: ''' Currently used for transport replacement @@ -313,7 +312,7 @@ class JingleSession: content.accepted = True def on_session_state_changed(self, - content: Optional[JingleContent] = None + content: JingleContent | None = None ) -> None: if self.state == JingleStates.ENDED: # Session not yet started, only one action possible: @@ -432,7 +431,7 @@ class JingleSession: def __ack(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -476,7 +475,7 @@ class JingleSession: def __on_transport_replace(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: for content in jingle.iterTags('content'): @@ -519,7 +518,7 @@ class JingleSession: def __on_session_info(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: # TODO: active, (un)hold, (un)mute @@ -550,7 +549,7 @@ class JingleSession: def __on_content_remove(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: for content in jingle.iterTags('content'): @@ -571,7 +570,7 @@ class JingleSession: def __on_session_accept(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: # FIXME @@ -582,7 +581,7 @@ class JingleSession: @staticmethod def __on_content_accept(stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -598,7 +597,7 @@ class JingleSession: def __on_content_add(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: if self.state == JingleStates.ENDED: @@ -616,7 +615,7 @@ class JingleSession: def __on_session_initiate(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -713,7 +712,7 @@ class JingleSession: def __broadcast(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -746,7 +745,7 @@ class JingleSession: def __on_session_terminate(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: self.connection.get_module('Jingle').delete_jingle_session(self.sid) @@ -774,7 +773,7 @@ class JingleSession: def __broadcast_all(self, stanza: nbxmpp.Node, jingle: nbxmpp.Node, - error: Optional[nbxmpp.Node], + error: nbxmpp.Node | None, action: str ) -> None: ''' @@ -788,7 +787,7 @@ class JingleSession: ) -> tuple[ list[JingleContent], list[tuple[str, str]], - Optional[str]]: + str | None]: # TODO: Needs some reworking contents: list[JingleContent] = [] contents_rejected: list[tuple[str, str]] = [] @@ -824,9 +823,9 @@ class JingleSession: return (contents, contents_rejected, failure_reason) def __dispatch_error(self, - error: Optional[str] = None, - text: Optional[str] = None, - type_: Optional[str] = None + error: str | None = None, + text: str | None = None, + type_: str | None = None ) -> None: if text: text = '%s (%s)' % (error, text) @@ -856,7 +855,7 @@ class JingleSession: def __make_jingle(self, action: str, - reason: Optional[nbxmpp.Node] = None + reason: nbxmpp.Node | None = None ) -> tuple[Iq, nbxmpp.Node]: stanza = nbxmpp.Iq(typ='set', to=nbxmpp.JID.from_string(self.peerjid), frm=self.ourjid) @@ -873,10 +872,10 @@ class JingleSession: def __send_error(self, stanza: nbxmpp.Node, - error: Optional[str], - jingle_error: Optional[str] = None, - text: Optional[str] = None, - type_: Optional[str] = None + error: str | None, + jingle_error: str | None = None, + text: str | None = None, + type_: str | None = None ) -> None: err_stanza = nbxmpp.Error(stanza, '%s %s' % (Namespace.STANZAS, error)) err = err_stanza.getTag('error') @@ -927,7 +926,7 @@ class JingleSession: self.collect_iq_id(stanza.getID()) self.state = JingleStates.ACTIVE - def __session_info(self, payload: Optional[nbxmpp.Node] = None) -> None: + def __session_info(self, payload: nbxmpp.Node | None = None) -> None: assert self.state != JingleStates.ENDED stanza, jingle = self.__make_jingle('session-info') if payload: @@ -941,7 +940,7 @@ class JingleSession: # it isn't being called explicitly. self.__session_info(payload) - def _session_terminate(self, reason: Optional[nbxmpp.Node] = None) -> None: + def _session_terminate(self, reason: nbxmpp.Node | None = None) -> None: stanza, jingle = self.__make_jingle('session-terminate', reason=reason) self.__broadcast_all(stanza, jingle, None, 'session-terminate-sent') if self.connection.connection and self.connection.state.is_available: @@ -989,7 +988,7 @@ class JingleSession: def __content_remove(self, content: JingleContent, - reason: Optional[nbxmpp.Node] = None + reason: nbxmpp.Node | None = None ) -> None: assert self.state != JingleStates.ENDED if self.connection.connection and self.connection.state.is_available: diff --git a/gajim/common/jingle_transport.py b/gajim/common/jingle_transport.py index e1df1542a..818418077 100644 --- a/gajim/common/jingle_transport.py +++ b/gajim/common/jingle_transport.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import socket @@ -75,10 +74,10 @@ class JingleTransport: self.candidates: list[dict[str, Any]] = [] self.remote_candidates: list[dict[str, Any]] = [] - self.connection: Optional[Client] = None - self.file_props: Optional[FileProp] = None - self.ourjid: Optional[str] = None - self.sid: Optional[str] = None + self.connection: Client | None = None + self.file_props: FileProp | None = None + self.ourjid: str | None = None + self.sid: str | None = None def _iter_candidates(self): for candidate in self.candidates: @@ -90,7 +89,7 @@ class JingleTransport: ''' def make_transport(self, - candidates: Optional[list[dict[str, Any]]] = None + candidates: list[dict[str, Any]] | None = None ) -> nbxmpp.Node: ''' Build a transport stanza with the given candidates (or self.candidates @@ -130,11 +129,11 @@ class JingleTransportSocks5(JingleTransport): Socks5 transport in jingle scenario Note: Don't forget to call set_file_props after initialization ''' - def __init__(self, node: Optional[nbxmpp.Node] = None) -> None: + def __init__(self, node: nbxmpp.Node | None = None) -> None: JingleTransport.__init__(self, TransportType.SOCKS5) self.connection = None self.remote_candidates: list[dict[str, Any]] = [] - self.sid: Optional[str] = None + self.sid: str | None = None if node and node.getAttr('sid'): self.sid = node.getAttr('sid') @@ -152,7 +151,7 @@ class JingleTransportSocks5(JingleTransport): return nbxmpp.Node('candidate', attrs=attrs) def make_transport(self, - candidates: Optional[list[dict[str, Any]]] = None, + candidates: list[dict[str, Any]] | None = None, add_candidates: bool = True ) -> nbxmpp.Node: if add_candidates: @@ -211,7 +210,7 @@ class JingleTransportSocks5(JingleTransport): type_preference = 126 priority = (2**16) * type_preference - hosts: set[Optional[str]] = set() + hosts: set[str | None] = set() local_ip_cand: list[dict[str, Any]] = [] my_ip = self.connection.local_address @@ -353,7 +352,7 @@ class JingleTransportSocks5(JingleTransport): self._add_candidates(proxy_cand) - def get_content(self) -> Optional[JingleContent]: + def get_content(self) -> JingleContent | None: sesn = self.connection.get_module('Jingle').get_jingle_session( self.ourjid, self.file_props.sid) for content in sesn.contents.values(): @@ -411,8 +410,8 @@ class JingleTransportSocks5(JingleTransport): class JingleTransportIBB(JingleTransport): def __init__(self, - node: Optional[nbxmpp.Node] = None, - block_sz: Optional[str] = None + node: nbxmpp.Node | None = None, + block_sz: str | None = None ) -> None: JingleTransport.__init__(self, TransportType.IBB) @@ -423,7 +422,7 @@ class JingleTransportIBB(JingleTransport): self.block_sz = '4096' self.connection = None - self.sid: Optional[str] = None + self.sid: str | None = None if node and node.getAttr('sid'): self.sid = node.getAttr('sid') @@ -436,7 +435,7 @@ class JingleTransportIBB(JingleTransport): class JingleTransportICEUDP(JingleTransport): - def __init__(self, node: Optional[nbxmpp.Node]) -> None: + def __init__(self, node: nbxmpp.Node | None) -> None: JingleTransport.__init__(self, TransportType.ICEUDP) def make_candidate(self, candidate) -> nbxmpp.Node: @@ -467,7 +466,7 @@ class JingleTransportICEUDP(JingleTransport): return nbxmpp.Node('candidate', attrs=attrs) def make_transport(self, - candidates: Optional[list[dict[str, Any]]] = None + candidates: list[dict[str, Any]] | None = None ) -> nbxmpp.Node: transport = JingleTransport.make_transport(self, candidates) transport.setNamespace(Namespace.JINGLE_ICE_UDP) diff --git a/gajim/common/logging_helpers.py b/gajim/common/logging_helpers.py index 3e9e2577f..3cc5e9d7e 100644 --- a/gajim/common/logging_helpers.py +++ b/gajim/common/logging_helpers.py @@ -15,7 +15,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Callable -from typing import Optional import logging import os @@ -142,8 +141,8 @@ class FancyFormatter(logging.Formatter): } def __init__(self, - fmt: Optional[str] = None, - datefmt: Optional[str] = None, + fmt: str | None = None, + datefmt: str | None = None, use_color: bool = False) -> None: logging.Formatter.__init__(self, fmt, datefmt) self.use_color = use_color diff --git a/gajim/common/modules/annotations.py b/gajim/common/modules/annotations.py index fd277c474..76b460c94 100644 --- a/gajim/common/modules/annotations.py +++ b/gajim/common/modules/annotations.py @@ -14,8 +14,6 @@ # XEP-0145: Annotations -from typing import Optional -from typing import Union from nbxmpp.errors import MalformedStanzaError from nbxmpp.errors import StanzaError @@ -38,7 +36,7 @@ class Annotations(BaseModule): def __init__(self, con: ConnectionT) -> None: BaseModule.__init__(self, con) - self._annotations: dict[Union[JID, str], AnnotationNote] = {} + self._annotations: dict[JID | str, AnnotationNote] = {} def request_annotations(self) -> None: self._nbxmpp('Annotations').request_annotations( @@ -55,7 +53,7 @@ class Annotations(BaseModule): for note in annotations: self._annotations[note.jid] = note - def get_note(self, jid: str) -> Optional[AnnotationNote]: + def get_note(self, jid: str) -> AnnotationNote | None: return self._annotations.get(jid) def set_note(self, note: AnnotationNote) -> None: diff --git a/gajim/common/modules/base.py b/gajim/common/modules/base.py index fe5a52b6d..f378f256d 100644 --- a/gajim/common/modules/base.py +++ b/gajim/common/modules/base.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging from functools import partial @@ -48,7 +47,7 @@ class BaseModule(EventHelper): self._account = con.account self._log = self._set_logger(plugin) self._nbxmpp_callbacks: dict[str, Any] = {} - self._stored_publish: Optional[types.AnyCallableT] = None + self._stored_publish: types.AnyCallableT | None = None self.handlers: list[StanzaHandler] = [] @classmethod @@ -81,7 +80,7 @@ class BaseModule(EventHelper): return getattr(module, key) return partial(getattr(module, key), callback=callback) - def _nbxmpp(self, module_name: Optional[str] = None): + def _nbxmpp(self, module_name: str | None = None): if not app.account_is_connected(self._account): self._log.warning('Account not connected, can’t use nbxmpp method') return Mock() diff --git a/gajim/common/modules/bits_of_binary.py b/gajim/common/modules/bits_of_binary.py index e1d9e5d35..7ff2744fb 100644 --- a/gajim/common/modules/bits_of_binary.py +++ b/gajim/common/modules/bits_of_binary.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import hashlib import logging @@ -127,7 +126,7 @@ class BitsOfBinary(BaseModule): iq, self._on_bob_received, {'cid': cid}) -def parse_bob_data(stanza: Iq) -> Optional[Path]: +def parse_bob_data(stanza: Iq) -> Path | None: data_node = stanza.getTag('data', namespace=Namespace.BOB) if data_node is None: return None @@ -201,7 +200,7 @@ def parse_bob_data(stanza: Iq) -> Optional[Path]: return filepath -def store_bob_data(bob_data: Optional[BobData]) -> Optional[Path]: +def store_bob_data(bob_data: BobData | None) -> Path | None: if bob_data is None: return None diff --git a/gajim/common/modules/bookmarks.py b/gajim/common/modules/bookmarks.py index 26ed07b95..3d86b04d3 100644 --- a/gajim/common/modules/bookmarks.py +++ b/gajim/common/modules/bookmarks.py @@ -18,8 +18,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union from gi.repository import GLib from nbxmpp.namespaces import Namespace @@ -197,7 +195,7 @@ class Bookmarks(BaseModule): return set_ @staticmethod - def _convert_to_dict(bookmarks: Optional[list[BookmarkData]] + def _convert_to_dict(bookmarks: list[BookmarkData] | None ) -> types.BookmarksDict: _dict: types.BookmarksDict = {} if not bookmarks: @@ -207,7 +205,7 @@ class Bookmarks(BaseModule): _dict[bookmark.jid] = bookmark return _dict - def get_bookmark(self, jid: Union[str, JID]) -> Optional[BookmarkData]: + def get_bookmark(self, jid: str | JID) -> BookmarkData | None: return self._bookmarks.get(cast(JID, jid)) def request_bookmarks(self) -> None: @@ -302,13 +300,13 @@ class Bookmarks(BaseModule): else: self.store_bookmarks(self.bookmarks) - def get_name_from_bookmark(self, jid: Union[str, JID]) -> Optional[str]: + def get_name_from_bookmark(self, jid: str | JID) -> str | None: bookmark = self._bookmarks.get(cast(JID, jid)) if bookmark is None: return bookmark return bookmark.name - def is_bookmark(self, jid: Union[str, JID]) -> bool: + def is_bookmark(self, jid: str | JID) -> bool: return jid in self._bookmarks def _remove_timeouts(self) -> None: diff --git a/gajim/common/modules/bytestream.py b/gajim/common/modules/bytestream.py index d68768328..efac156b9 100644 --- a/gajim/common/modules/bytestream.py +++ b/gajim/common/modules/bytestream.py @@ -27,7 +27,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import socket @@ -130,7 +129,7 @@ class Bytestream(BaseModule): return file_props.receiver.jid + '/' + file_props.receiver.resource @staticmethod - def _ft_get_from(iq_obj: Iq) -> Optional[str]: + def _ft_get_from(iq_obj: Iq) -> str | None: return helpers.get_full_jid_from_iq(iq_obj) @staticmethod @@ -183,7 +182,7 @@ class Bytestream(BaseModule): session.cancel_session() def send_success_connect_reply(self, - streamhost: Optional[dict[str, Any]] + streamhost: dict[str, Any] | None ) -> None: ''' Send reply to the initiator of FT that we made a connection @@ -230,7 +229,7 @@ class Bytestream(BaseModule): for file_props in FilesProp.getAllFileProp(): self.remove_transfer(file_props) - def remove_transfer(self, file_props: Optional[FileProp]) -> None: + def remove_transfer(self, file_props: FileProp | None) -> None: if file_props is None: return self.disconnect_transfer(file_props) @@ -519,7 +518,7 @@ class Bytestream(BaseModule): sid: str, error: str, error_type: str, - msg: Optional[str] = None + msg: str | None = None ) -> None: ''' Called when there is an error establishing BS connection, or when diff --git a/gajim/common/modules/caps.py b/gajim/common/modules/caps.py index 02f5cc72d..48271a084 100644 --- a/gajim/common/modules/caps.py +++ b/gajim/common/modules/caps.py @@ -21,7 +21,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional import weakref from collections import defaultdict @@ -82,7 +81,7 @@ class Caps(BaseModule): self._queued_tasks_by_jid[task.entity.jid] = task app.task_manager.add_task(task) - def _get_task(self, jid: JID) -> Optional[EntityCapsTask]: + def _get_task(self, jid: JID) -> EntityCapsTask | None: return self._queued_tasks_by_jid.get(jid) def _get_similar_tasks(self, task: EntityCapsTask) -> set[EntityCapsTask]: diff --git a/gajim/common/modules/chat_markers.py b/gajim/common/modules/chat_markers.py index 08d2ac1a1..9e9f76c5b 100644 --- a/gajim/common/modules/chat_markers.py +++ b/gajim/common/modules/chat_markers.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from nbxmpp.namespaces import Namespace from nbxmpp.protocol import JID @@ -134,7 +133,7 @@ class ChatMarkers(BaseModule): def send_displayed_marker(self, contact: types.ChatContactT, message_id: str, - stanza_id: Optional[str]) -> None: + stanza_id: str | None) -> None: if not self._is_sending_marker_allowed(contact): return @@ -145,7 +144,7 @@ class ChatMarkers(BaseModule): @staticmethod def _determine_marker_id(contact: types.ChatContactT, message_id: str, - stanza_id: Optional[str] + stanza_id: str | None ) -> str: if stanza_id is None: diff --git a/gajim/common/modules/chatstates.py b/gajim/common/modules/chatstates.py index 2fdd011b9..255ccda63 100644 --- a/gajim/common/modules/chatstates.py +++ b/gajim/common/modules/chatstates.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import time from functools import wraps @@ -246,7 +245,7 @@ class Chatstate(BaseModule): def get_active_chatstate(self, contact: types.ChatContactT - ) -> Optional[str]: + ) -> str | None: # determines if we add 'active' on outgoing messages if contact.settings.get('send_chatstate') == 'disabled': return None diff --git a/gajim/common/modules/contacts.py b/gajim/common/modules/contacts.py index 151c2dbd8..0bd16ff40 100644 --- a/gajim/common/modules/contacts.py +++ b/gajim/common/modules/contacts.py @@ -16,9 +16,7 @@ from __future__ import annotations from typing import Any from typing import Iterator -from typing import Optional from typing import overload -from typing import Union from datetime import datetime from datetime import timezone @@ -111,7 +109,7 @@ class Contacts(BaseModule): def __init__(self, client: types.Client) -> None: BaseModule.__init__(self, client) - self._contacts: dict[JID, Union[BareContact, GroupchatContact]] = {} + self._contacts: dict[JID, BareContact | GroupchatContact] = {} self._con.connect_signal('state-changed', self._on_client_state_changed) self._con.connect_signal('resume-failed', self._on_client_resume_failed) @@ -127,7 +125,7 @@ class Contacts(BaseModule): if state.is_disconnected: self._reset_presence() - def add_chat_contact(self, jid: Union[str, JID]) -> BareContact: + def add_chat_contact(self, jid: str | JID) -> BareContact: if isinstance(jid, str): jid = JID.from_string(jid) @@ -143,7 +141,7 @@ class Contacts(BaseModule): self._contacts[jid] = contact return contact - def add_group_chat_contact(self, jid: Union[str, JID]) -> GroupchatContact: + def add_group_chat_contact(self, jid: str | JID) -> GroupchatContact: if isinstance(jid, str): jid = JID.from_string(jid) @@ -160,7 +158,7 @@ class Contacts(BaseModule): self._contacts[jid] = contact return contact - def add_private_contact(self, jid: Union[str, JID]) -> GroupchatParticipant: + def add_private_contact(self, jid: str | JID) -> GroupchatParticipant: if isinstance(jid, str): jid = JID.from_string(jid) @@ -179,9 +177,8 @@ class Contacts(BaseModule): return contact.add_resource(jid.resource) def add_contact(self, - jid: Union[str, JID], - groupchat: bool = False) -> Union[BareContact, - GroupchatContact]: + jid: str | JID, + groupchat: bool = False) -> BareContact | GroupchatContact: if isinstance(jid, str): jid = JID.from_string(jid) @@ -198,7 +195,7 @@ class Contacts(BaseModule): return contact def get_contact(self, - jid: Union[str, JID], + jid: str | JID, groupchat: bool = False ) -> types.ContactT: @@ -218,8 +215,9 @@ class Contacts(BaseModule): contact = contact.get_resource(resource) return contact - def get_bare_contact(self, jid: Union[str, JID]) -> Union[BareContact, - GroupchatContact]: + def get_bare_contact(self, + jid: str | JID + ) -> BareContact | GroupchatContact: '''This method gives direct access to the contacts dict. This is helpful when performance is essential. In difference to get_contact() this method does not create contacts nor can it handle @@ -230,10 +228,9 @@ class Contacts(BaseModule): def get_contacts_with_domain(self, domain: str - ) -> list[Union[BareContact, - GroupchatContact]]: + ) -> list[BareContact | GroupchatContact]: - contacts: list[Union[BareContact, GroupchatContact]] = [] + contacts: list[BareContact | GroupchatContact] = [] for contact in self._contacts.values(): if contact.jid.domain == domain: contacts.append(contact) @@ -283,15 +280,16 @@ class CommonContact(Observable): def account(self) -> str: return self._account - def _on_signal(self, - _contact: Union[BareContact, - ResourceContact, - GroupchatContact, - GroupchatParticipant], - signal_name: str, - *args: Any, - **kwargs: Any - ) -> None: + def _on_signal( + self, + _contact: (BareContact | + ResourceContact | + GroupchatContact | + GroupchatParticipant), + signal_name: str, + *args: Any, + **kwargs: Any + ) -> None: self.notify(signal_name, *args, **kwargs) def supports(self, requested_feature: str) -> bool: @@ -329,7 +327,7 @@ class CommonContact(Observable): return self._jid @property - def chatstate(self) -> Optional[Chatstate]: + def chatstate(self) -> Chatstate | None: return None @property @@ -432,7 +430,7 @@ class BareContact(CommonContact): return max(show_values) @property - def chatstate(self) -> Optional[Chatstate]: + def chatstate(self) -> Chatstate | None: chatstates = {contact.chatstate for contact in self._resources.values()} chatstates.discard(None) if not chatstates: @@ -460,14 +458,14 @@ class BareContact(CommonContact): assert self._jid.localpart is not None return self._jid.localpart - def get_tune(self) -> Optional[TuneData]: + def get_tune(self) -> TuneData | None: return self._module('UserTune').get_contact_tune(self._jid) - def get_location(self) -> Optional[LocationData]: + def get_location(self) -> LocationData | None: return self._module('UserLocation').get_contact_location(self._jid) @property - def avatar_sha(self) -> Optional[str]: + def avatar_sha(self) -> str | None: return app.storage.cache.get_contact( self._account, self._jid, 'avatar') @@ -537,14 +535,14 @@ class BareContact(CommonContact): return disco_info.is_gateway @property - def ask(self) -> Optional[str]: + def ask(self) -> str | None: item = self._module('Roster').get_item(self._jid) if item is None: return None return item.ask @property - def subscription(self) -> Optional[str]: + def subscription(self) -> str | None: item = self._module('Roster').get_item(self._jid) if item is None: return None @@ -604,7 +602,7 @@ class ResourceContact(CommonContact): return self._jid.resource @property - def identity_type(self) -> Optional[str]: + def identity_type(self) -> str | None: disco_info = app.storage.cache.get_last_disco_info(self._jid) if disco_info is None: return None @@ -643,7 +641,7 @@ class ResourceContact(CommonContact): return self._presence.priority @property - def idle_time(self) -> Optional[float]: + def idle_time(self) -> float | None: return self._presence.idle_time @property @@ -686,7 +684,7 @@ class GroupchatContact(CommonContact): return disco_info.is_irc @property - def muc_context(self) -> Optional[str]: + def muc_context(self) -> str | None: disco_info = self.get_disco() if disco_info is None: return None @@ -748,13 +746,13 @@ class GroupchatContact(CommonContact): return get_groupchat_name(client, self._jid) @property - def avatar_sha(self) -> Optional[str]: + def avatar_sha(self) -> str | None: return app.storage.cache.get_muc(self._account, self._jid, 'avatar') def set_avatar_sha(self, sha: str) -> None: app.storage.cache.set_muc(self._account, self._jid, 'avatar', sha) - def get_avatar(self, size: int, scale: int) -> Optional[cairo.ImageSurface]: + def get_avatar(self, size: int, scale: int) -> cairo.ImageSurface | None: transport_icon = None disco_info = self.get_disco() if disco_info is not None: @@ -783,28 +781,28 @@ class GroupchatContact(CommonContact): for contact in self._resources.values(): contact.notify('chatstate-update') - def get_self(self) -> Optional[GroupchatParticipant]: + def get_self(self) -> GroupchatParticipant | None: nick = self.nickname if nick is None: return None return self.get_resource(nick) @property - def nickname(self) -> Optional[str]: + def nickname(self) -> str | None: muc_data = self._module('MUC').get_muc_data(self._jid) if muc_data is None: return None return muc_data.nick @property - def occupant_jid(self) -> Optional[JID]: + def occupant_jid(self) -> JID | None: muc_data = self._module('MUC').get_muc_data(self._jid) if muc_data is None: return None return muc_data.occupant_jid @property - def subject(self) -> Optional[MucSubject]: + def subject(self) -> MucSubject | None: muc_data = self._module('MUC').get_muc_data(self._jid) if muc_data is None: return None @@ -839,7 +837,7 @@ class GroupchatContact(CommonContact): client = app.get_client(self._account) return client.get_module('MUC').get_joined_users(self._jid) - def get_disco(self, max_age: int = 0) -> Optional[DiscoInfo]: + def get_disco(self, max_age: int = 0) -> DiscoInfo | None: return app.storage.cache.get_last_disco_info(self.jid, max_age=max_age) def can_notify(self) -> bool: @@ -891,7 +889,7 @@ class GroupchatParticipant(CommonContact): return self._module('Contacts').get_bare_contact(self.jid.bare) @property - def muc_context(self) -> Optional[str]: + def muc_context(self) -> str | None: return self.room.muc_context @property @@ -916,7 +914,7 @@ class GroupchatParticipant(CommonContact): return self._presence.status @property - def idle_time(self) -> Optional[float]: + def idle_time(self) -> float | None: return self._presence.idle_time @property @@ -925,10 +923,10 @@ class GroupchatParticipant(CommonContact): return self._jid.resource @property - def real_jid(self) -> Optional[JID]: + def real_jid(self) -> JID | None: return self._presence.real_jid - def get_real_contact(self) -> Optional[BareContact]: + def get_real_contact(self) -> BareContact | None: jid = self._presence.real_jid if jid is None: return None @@ -974,9 +972,9 @@ class GroupchatParticipant(CommonContact): return 'pm' -def can_add_to_roster(contact: Union[BareContact, - GroupchatContact, - GroupchatParticipant]) -> bool: +def can_add_to_roster( + contact: BareContact | GroupchatContact | GroupchatParticipant +) -> bool: if isinstance(contact, GroupchatContact): return False diff --git a/gajim/common/modules/delimiter.py b/gajim/common/modules/delimiter.py index e8b4773d4..e4aaa092e 100644 --- a/gajim/common/modules/delimiter.py +++ b/gajim/common/modules/delimiter.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Generator -from typing import Optional from nbxmpp.errors import is_error @@ -40,7 +39,7 @@ class Delimiter(BaseModule): self.delimiter = '::' @as_task - def get_roster_delimiter(self) -> Generator[Optional[str], None, None]: + def get_roster_delimiter(self) -> Generator[str | None, None, None]: _task = yield # noqa: F841 delimiter = yield self.request_delimiter() diff --git a/gajim/common/modules/discovery.py b/gajim/common/modules/discovery.py index b0c5b9ed5..1569b08fb 100644 --- a/gajim/common/modules/discovery.py +++ b/gajim/common/modules/discovery.py @@ -16,9 +16,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import nbxmpp from nbxmpp.errors import is_error from nbxmpp.errors import StanzaError @@ -60,15 +57,15 @@ class Discovery(BaseModule): ns=Namespace.DISCO_ITEMS), ] - self._account_info: Optional[DiscoInfo] = None - self._server_info: Optional[DiscoInfo] = None + self._account_info: DiscoInfo | None = None + self._server_info: DiscoInfo | None = None @property - def account_info(self) -> Optional[DiscoInfo]: + def account_info(self) -> DiscoInfo | None: return self._account_info @property - def server_info(self) -> Optional[DiscoInfo]: + def server_info(self) -> DiscoInfo | None: return self._server_info def discover_server_items(self) -> None: @@ -204,7 +201,7 @@ class Discovery(BaseModule): @as_task def disco_muc(self, - jid: Union[JID, str], + jid: JID | str, request_vcard: bool = False, allow_redirect: bool = False ): diff --git a/gajim/common/modules/gateway.py b/gajim/common/modules/gateway.py index 59db0bed9..d1d79916e 100644 --- a/gajim/common/modules/gateway.py +++ b/gajim/common/modules/gateway.py @@ -16,8 +16,6 @@ from __future__ import annotations -from typing import Optional - import nbxmpp from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Iq @@ -74,7 +72,7 @@ class Gateway(BaseModule): def request_gateway_prompt(self, jid: str, - prompt: Optional[str] = None + prompt: str | None = None ) -> None: typ_ = 'get' if prompt: diff --git a/gajim/common/modules/http_auth.py b/gajim/common/modules/http_auth.py index 3d993dc5c..d2f48e962 100644 --- a/gajim/common/modules/http_auth.py +++ b/gajim/common/modules/http_auth.py @@ -16,8 +16,6 @@ from __future__ import annotations -from typing import Union - import nbxmpp from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Iq @@ -50,8 +48,8 @@ class HTTPAuth(BaseModule): def _http_auth(self, _con: types.xmppClient, - stanza: Union[Iq, Message], - properties: Union[IqProperties, MessageProperties] + stanza: Iq | Message, + properties: IqProperties | MessageProperties ) -> None: if not properties.is_http_auth: return @@ -70,7 +68,7 @@ class HTTPAuth(BaseModule): raise nbxmpp.NodeProcessed def build_http_auth_answer(self, - stanza: Union[Iq, Message], + stanza: Iq | Message, answer: str ) -> None: if answer == 'yes': diff --git a/gajim/common/modules/httpupload.py b/gajim/common/modules/httpupload.py index 25597417a..aecd89495 100644 --- a/gajim/common/modules/httpupload.py +++ b/gajim/common/modules/httpupload.py @@ -18,7 +18,6 @@ from __future__ import annotations from typing import Callable from typing import cast -from typing import Optional import mimetypes import os @@ -64,9 +63,9 @@ class HTTPUpload(BaseModule): BaseModule.__init__(self, con) self.available = False - self.component: Optional[JID] = None - self.httpupload_namespace: Optional[str] = None - self.max_file_size: Optional[float] = None # max file size in bytes + self.component: JID | None = None + self.httpupload_namespace: str | None = None + self.max_file_size: float | None = None # max file size in bytes self._requests_in_progress: dict[int, HTTPRequest] = {} @@ -93,7 +92,7 @@ class HTTPUpload(BaseModule): def get_running_transfers(self, contact: types.ChatContactT - ) -> Optional[set[HTTPFileTransfer]]: + ) -> set[HTTPFileTransfer] | None: return self._running_transfers.get((contact.account, contact.jid)) @@ -125,7 +124,7 @@ class HTTPUpload(BaseModule): def _make_transfer(self, path: Path, - encryption: Optional[str], + encryption: str | None, contact: types.ChatContactT, ) -> HTTPFileTransfer: @@ -352,7 +351,7 @@ class HTTPFileTransfer(FileTransfer): path: str, contact: types.ContactT, mime: str, - encryption: Optional[str], + encryption: str | None, groupchat: bool ) -> None: @@ -364,11 +363,11 @@ class HTTPFileTransfer(FileTransfer): self._contact = contact self._mime = mime - self.put_uri: Optional[str] = None - self.get_uri: Optional[str] = None - self._uri_transform_func: Optional[Callable[[str], str]] = None + self.put_uri: str | None = None + self.get_uri: str | None = None + self._uri_transform_func: Callable[[str], str] | None = None - self._data: Optional[bytes] = None + self._data: bytes | None = None self._headers: dict[str, str] = {} self._is_encrypted = False @@ -398,7 +397,7 @@ class HTTPFileTransfer(FileTransfer): return self._groupchat @property - def encryption(self) -> Optional[str]: + def encryption(self) -> str | None: return self._encryption @property diff --git a/gajim/common/modules/jingle.py b/gajim/common/modules/jingle.py index 1882846a5..e4c60f965 100644 --- a/gajim/common/modules/jingle.py +++ b/gajim/common/modules/jingle.py @@ -31,7 +31,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging @@ -205,7 +204,7 @@ class Jingle(BaseModule): jid: str, file_props: FileProp, request: bool = False - ) -> Optional[str]: + ) -> str | None: logger.info('start file transfer with file: %s', file_props) contact = self._con.get_module('Contacts').get_contact(jid) jingle = JingleSession(self._con, @@ -240,7 +239,7 @@ class Jingle(BaseModule): return transfer.transport.sid @staticmethod - def __hash_support(contact: types.ResourceContact) -> Optional[str]: + def __hash_support(contact: types.ResourceContact) -> str | None: if contact.supports(Namespace.HASHES_2): if contact.supports(Namespace.HASHES_BLAKE2B_512): return 'blake2b-512' @@ -257,9 +256,9 @@ class Jingle(BaseModule): return None def get_jingle_sessions(self, - jid: Optional[str], - sid: Optional[str] = None, - media: Optional[str] = None + jid: str | None, + sid: str | None = None, + media: str | None = None ) -> list[JingleSession]: if sid: return [se for se in self._sessions.values() if se.sid == sid] @@ -278,10 +277,10 @@ class Jingle(BaseModule): def get_file_info(self, peerjid: str, - hash_: Optional[str] = None, - name: Optional[str] = None, - _account: Optional[str] = None - ) -> Optional[dict[str, Any]]: + hash_: str | None = None, + name: str | None = None, + _account: str | None = None + ) -> dict[str, Any] | None: if hash_: for file in self.files: # DEBUG # if f['hash'] == '1294809248109223': @@ -295,9 +294,9 @@ class Jingle(BaseModule): def get_jingle_session(self, jid: str, - sid: Optional[str] = None, - media: Optional[str] = None - ) -> Optional[JingleSession]: + sid: str | None = None, + media: str | None = None + ) -> JingleSession | None: if sid is not None: if sid in self._sessions: return self._sessions[sid] diff --git a/gajim/common/modules/mam.py b/gajim/common/modules/mam.py index 40e45ac5c..aa262394b 100644 --- a/gajim/common/modules/mam.py +++ b/gajim/common/modules/mam.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import time from datetime import datetime @@ -136,7 +135,7 @@ class MAM(BaseModule): def _get_unique_id(self, properties: MessageProperties - ) -> tuple[Optional[str], Optional[str]]: + ) -> tuple[str | None, str | None]: if properties.type.is_groupchat: return properties.mam.id, None @@ -156,7 +155,7 @@ class MAM(BaseModule): @staticmethod def _get_stanza_id(properties: MessageProperties, archive_jid: str - ) -> Optional[StanzaIDData]: + ) -> StanzaIDData | None: for stanza_id in properties.stanza_ids: if stanza_id.by == archive_jid: return stanza_id @@ -343,7 +342,7 @@ class MAM(BaseModule): self._mam_query_ids[jid] = query_id return query_id - def _get_query_params(self) -> tuple[Optional[str], Optional[datetime]]: + def _get_query_params(self) -> tuple[str | None, datetime | None]: own_jid = self._con.get_own_jid().bare archive = app.storage.archive.get_archive_infos(own_jid) @@ -366,7 +365,7 @@ class MAM(BaseModule): def _get_muc_query_params(self, jid: JID, threshold: SyncThreshold - ) -> tuple[Optional[str], Optional[datetime]]: + ) -> tuple[str | None, datetime | None]: archive = app.storage.archive.get_archive_infos(jid) mam_id = None @@ -498,8 +497,8 @@ class MAM(BaseModule): @as_task def _execute_query(self, jid: JID, - mam_id: Optional[str], - start_date: Optional[datetime] + mam_id: str | None, + start_date: datetime | None ): _task = yield # noqa: F841 @@ -539,8 +538,8 @@ class MAM(BaseModule): def request_archive_interval(self, start_date: datetime, end_date: datetime, - after: Optional[str] = None, - queryid: Optional[str] = None + after: str | None = None, + queryid: str | None = None ) -> str: jid = self._con.get_own_jid().bare diff --git a/gajim/common/modules/message.py b/gajim/common/modules/message.py index 636520af1..6e1a4c0e2 100644 --- a/gajim/common/modules/message.py +++ b/gajim/common/modules/message.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import time @@ -248,7 +247,7 @@ class Message(BaseModule): message_id=properties.id, error=properties.error)) - def _log_muc_message(self, event: GcMessageReceived) -> Optional[int]: + def _log_muc_message(self, event: GcMessageReceived) -> int | None: self._check_for_mam_compliance(event.room_jid, event.stanza_id) if event.msgtxt and event.properties.muc_nickname: @@ -273,7 +272,7 @@ class Message(BaseModule): def _get_unique_id(self, properties: MessageProperties - ) -> tuple[Optional[str], Optional[str]]: + ) -> tuple[str | None, str | None]: if properties.is_self_message: # Deduplicate self message with message-id return None, properties.id @@ -376,7 +375,7 @@ class Message(BaseModule): return stanza - def log_message(self, message: OutgoingMessage) -> Optional[int]: + def log_message(self, message: OutgoingMessage) -> int | None: if not message.is_loggable: return None diff --git a/gajim/common/modules/misc.py b/gajim/common/modules/misc.py index 1f72e8e5f..5993bbeb8 100644 --- a/gajim/common/modules/misc.py +++ b/gajim/common/modules/misc.py @@ -14,7 +14,6 @@ # All XEPs that don’t need their own module -from typing import Optional import logging @@ -41,7 +40,7 @@ def parse_oob(properties: MessageProperties, # XEP-0308: Last Message Correction -def parse_correction(properties: MessageProperties) -> Optional[str]: +def parse_correction(properties: MessageProperties) -> str | None: if not properties.is_correction: return None assert properties.correction is not None diff --git a/gajim/common/modules/muc.py b/gajim/common/modules/muc.py index e46f67bfc..c29a632ce 100644 --- a/gajim/common/modules/muc.py +++ b/gajim/common/modules/muc.py @@ -18,7 +18,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import time @@ -187,7 +186,7 @@ class MUC(BaseModule): self._muc_service_jid = info.jid raise nbxmpp.NodeProcessed - def get_muc_data(self, room_jid: str) -> Optional[MUCData]: + def get_muc_data(self, room_jid: str) -> MUCData | None: return self._mucs.get(room_jid) def set_password(self, room_jid: str, password: str) -> None: @@ -226,9 +225,9 @@ class MUC(BaseModule): def _create_muc_data(self, room_jid: str, - nick: Optional[str], - password: Optional[str], - config: Optional[dict[str, Any]] + nick: str | None, + password: str | None, + config: dict[str, Any] | None ) -> MUCData: if not nick: nick = get_group_chat_nick(self._account, room_jid) @@ -243,9 +242,9 @@ class MUC(BaseModule): def join(self, jid: str, - nick: Optional[str] = None, - password: Optional[str] = None, - config: Optional[dict[str, Any]] = None + nick: str | None = None, + password: str | None = None, + config: dict[str, Any] | None = None ) -> None: if not app.account_is_available(self._account): return @@ -353,7 +352,7 @@ class MUC(BaseModule): def leave(self, room_jid: str, - reason: Optional[str] = None + reason: str | None = None ) -> None: self._log.info('Leave MUC: %s', room_jid) @@ -415,7 +414,7 @@ class MUC(BaseModule): @staticmethod def _apply_config(form: SimpleDataForm, - config: Optional[dict[str, Any]] = None + config: dict[str, Any] | None = None ) -> None: default_config = get_default_muc_config() if config is not None: @@ -768,7 +767,7 @@ class MUC(BaseModule): self._joined_users[jid.bare][jid.resource] = muc_presence return muc_presence - def _is_user_joined(self, jid: Optional[JID]) -> bool: + def _is_user_joined(self, jid: JID | None) -> bool: try: self._joined_users[jid.bare][jid.resource] except KeyError: @@ -1060,7 +1059,7 @@ class MUC(BaseModule): def invite(self, room: JID, jid: JID, - reason: Optional[str] = None, + reason: str | None = None, continue_: bool = False ) -> str: diff --git a/gajim/common/modules/omemo.py b/gajim/common/modules/omemo.py index fb4b3802b..8b1c8d4fe 100644 --- a/gajim/common/modules/omemo.py +++ b/gajim/common/modules/omemo.py @@ -20,7 +20,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional import binascii import threading @@ -408,7 +407,7 @@ class OMEMO(BaseModule): def _process_muc_message(self, properties: MessageProperties - ) -> Optional[str]: + ) -> str | None: resource = properties.jid.resource if properties.muc_ofrom is not None: @@ -426,7 +425,7 @@ class OMEMO(BaseModule): def _process_mam_message(self, properties: MessageProperties - ) -> Optional[str]: + ) -> str | None: self._log.info('Message received, archive: %s', properties.mam.archive) if properties.from_muc: @@ -567,7 +566,7 @@ class OMEMO(BaseModule): jid=JID.from_string(jid), message=EncryptionInfoMsg.UNDECIDED_FINGERPRINTS)) - def set_devicelist(self, devicelist: Optional[list[int]] = None) -> None: + def set_devicelist(self, devicelist: list[int] | None = None) -> None: devicelist_: set[int] = {self.backend.get_our_device()} if devicelist is not None: devicelist_.update(devicelist) @@ -584,7 +583,7 @@ class OMEMO(BaseModule): self.request_devicelist(jid) @as_task - def request_devicelist(self, jid: Optional[str] = None): + def request_devicelist(self, jid: str | None = None): _task = yield # noqa: F841 if jid is None: diff --git a/gajim/common/modules/presence.py b/gajim/common/modules/presence.py index 79e31a1ee..01cc8c2b5 100644 --- a/gajim/common/modules/presence.py +++ b/gajim/common/modules/presence.py @@ -17,8 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional -from typing import Union import time @@ -225,21 +223,21 @@ class Presence(BaseModule): jid=properties.jid.bare)) raise nbxmpp.NodeProcessed - def unsubscribed(self, jid: Union[JID, str]) -> None: + def unsubscribed(self, jid: JID | str) -> None: self._log.info('Unsubscribed: %s', jid) self._jids_for_auto_auth.discard(str(jid)) self._nbxmpp('BasePresence').unsubscribed(jid) - def unsubscribe(self, jid: Union[JID, str]) -> None: + def unsubscribe(self, jid: JID | str) -> None: self._log.info('Unsubscribe from %s', jid) self._jids_for_auto_auth.discard(str(jid)) self._nbxmpp('BasePresence').unsubscribe(jid) def subscribe(self, - jid: Union[JID, str], - msg: Optional[str] = None, - name: Optional[str] = None, - groups: Optional[list[str]] = None, + jid: JID | str, + msg: str | None = None, + name: str | None = None, + groups: list[str] | None = None, auto_auth: bool = False ) -> None: self._log.info('Request Subscription to %s', jid) @@ -253,12 +251,12 @@ class Presence(BaseModule): nick=app.nicks[self._account]) def get_presence(self, - to: Optional[str] = None, - typ: Optional[str] = None, - priority: Optional[int] = None, - show: Optional[str] = None, - status: Optional[str] = None, - nick: Optional[str] = None, + to: str | None = None, + typ: str | None = None, + priority: int | None = None, + show: str | None = None, + status: str | None = None, + nick: str | None = None, caps: bool = True, idle_time: bool = False ) -> nbxmpp.Presence: diff --git a/gajim/common/modules/roster.py b/gajim/common/modules/roster.py index 2d6220833..775dbf82f 100644 --- a/gajim/common/modules/roster.py +++ b/gajim/common/modules/roster.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import cast from typing import Iterable from typing import Iterator -from typing import Optional import nbxmpp from nbxmpp.namespaces import Namespace @@ -158,10 +157,10 @@ class Roster(BaseModule): raise nbxmpp.NodeProcessed - def get_item(self, jid: JID) -> Optional[RosterItem]: + def get_item(self, jid: JID) -> RosterItem | None: return self._roster.get(jid) - def set_groups(self, jid: JID, groups: Optional[Iterable[str]]) -> None: + def set_groups(self, jid: JID, groups: Iterable[str] | None) -> None: if groups is not None: groups = set(groups) item = self.get_item(jid) diff --git a/gajim/common/modules/security_labels.py b/gajim/common/modules/security_labels.py index bdfad4206..8895925fb 100644 --- a/gajim/common/modules/security_labels.py +++ b/gajim/common/modules/security_labels.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Generator -from typing import Optional from nbxmpp.errors import is_error from nbxmpp.modules.security_labels import Catalog @@ -70,7 +69,7 @@ class SecLabels(BaseModule): jid=jid, catalog=catalog)) - def get_catalog(self, jid: str) -> Optional[Catalog]: + def get_catalog(self, jid: str) -> Catalog | None: if not self.supported: return None diff --git a/gajim/common/modules/user_avatar.py b/gajim/common/modules/user_avatar.py index 90c62438c..7a680bf0a 100644 --- a/gajim/common/modules/user_avatar.py +++ b/gajim/common/modules/user_avatar.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Generator -from typing import Optional from nbxmpp.modules.user_avatar import AvatarData from nbxmpp.modules.util import is_error @@ -91,7 +90,7 @@ class UserAvatar(BaseModule): def _request_avatar_data(self, contact: types.ChatContactT, sha: str - ) -> Generator[Optional[AvatarData], None, None]: + ) -> Generator[AvatarData | None, None, None]: self._log.info('Request: %s %s', contact.jid, sha) diff --git a/gajim/common/modules/user_location.py b/gajim/common/modules/user_location.py index e820c9f32..d9d61c972 100644 --- a/gajim/common/modules/user_location.py +++ b/gajim/common/modules/user_location.py @@ -16,8 +16,6 @@ from __future__ import annotations -from typing import Optional - from nbxmpp.namespaces import Namespace from nbxmpp.protocol import JID from nbxmpp.protocol import Message @@ -47,13 +45,13 @@ class UserLocation(BaseModule): BaseModule.__init__(self, con) self._register_pubsub_handler(self._location_received) - self._current_location: Optional[LocationData] = None - self._contact_locations: dict[JID, Optional[LocationData]] = {} + self._current_location: LocationData | None = None + self._contact_locations: dict[JID, LocationData | None] = {} - def get_current_location(self) -> Optional[LocationData]: + def get_current_location(self) -> LocationData | None: return self._current_location - def get_contact_location(self, jid: JID) -> Optional[LocationData]: + def get_contact_location(self, jid: JID) -> LocationData | None: return self._contact_locations.get(jid) @event_node(Namespace.LOCATION) @@ -78,7 +76,7 @@ class UserLocation(BaseModule): @store_publish def set_location(self, - location: Optional[LocationData], + location: LocationData | None, force: bool = False ) -> None: if not self._con.get_module('PEP').supported: diff --git a/gajim/common/modules/user_tune.py b/gajim/common/modules/user_tune.py index cc9a90b38..dd7f24edc 100644 --- a/gajim/common/modules/user_tune.py +++ b/gajim/common/modules/user_tune.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from nbxmpp.namespaces import Namespace from nbxmpp.protocol import JID @@ -46,13 +45,13 @@ class UserTune(BaseModule): def __init__(self, con: types.Client) -> None: BaseModule.__init__(self, con) self._register_pubsub_handler(self._tune_received) - self._current_tune: Optional[TuneData] = None + self._current_tune: TuneData | None = None self._contact_tunes: dict[JID, TuneData] = {} - def get_current_tune(self) -> Optional[TuneData]: + def get_current_tune(self) -> TuneData | None: return self._current_tune - def get_contact_tune(self, jid: JID) -> Optional[TuneData]: + def get_contact_tune(self, jid: JID) -> TuneData | None: return self._contact_tunes.get(jid) @event_node(Namespace.TUNE) @@ -74,7 +73,7 @@ class UserTune(BaseModule): contact.notify('tune-update', data) @store_publish - def set_tune(self, tune: Optional[TuneData], force: bool = False) -> None: + def set_tune(self, tune: TuneData | None, force: bool = False) -> None: if not self._con.get_module('PEP').supported: return diff --git a/gajim/common/modules/util.py b/gajim/common/modules/util.py index 3686d0739..a8a6582a2 100644 --- a/gajim/common/modules/util.py +++ b/gajim/common/modules/util.py @@ -17,8 +17,6 @@ from __future__ import annotations from typing import Any -from typing import Optional -from typing import Union import logging from functools import partial @@ -42,7 +40,7 @@ from gajim.common.events import MessageUpdated from gajim.common.modules.misc import parse_correction -def from_xs_boolean(value: Union[str, bool]) -> bool: +def from_xs_boolean(value: str | bool) -> bool: if isinstance(value, bool): return value @@ -55,7 +53,7 @@ def from_xs_boolean(value: Union[str, bool]) -> bool: raise ValueError(f'Cant convert {value} to python boolean') -def to_xs_boolean(value: Union[bool, None]) -> str: +def to_xs_boolean(value: bool | None) -> str: # Convert to xs:boolean ('true', 'false') # from a python boolean (True, False) or None if value is True: @@ -196,7 +194,7 @@ def prepare_stanza(stanza: Message, plaintext: str) -> None: def delete_nodes(stanza: Message, name: str, - namespace: Optional[str] = None + namespace: str | None = None ) -> None: nodes = stanza.getTags(name, namespace=namespace) diff --git a/gajim/common/modules/vcard_avatars.py b/gajim/common/modules/vcard_avatars.py index 7f21f5995..756caa4b9 100644 --- a/gajim/common/modules/vcard_avatars.py +++ b/gajim/common/modules/vcard_avatars.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import Generator -from typing import Optional import weakref @@ -65,7 +64,7 @@ class VCardAvatars(BaseModule): self.avatar_conversion_available = is_available self._log.info('Discovered Avatar Conversion') - def get_avatar_sha(self, jid: JID) -> Optional[str]: + def get_avatar_sha(self, jid: JID) -> str | None: return self._muc_avatar_cache.get(jid) @as_task diff --git a/gajim/common/multimedia_helpers.py b/gajim/common/multimedia_helpers.py index d0310369c..2fc44f802 100644 --- a/gajim/common/multimedia_helpers.py +++ b/gajim/common/multimedia_helpers.py @@ -16,8 +16,6 @@ from __future__ import annotations -from typing import Optional - import logging try: @@ -44,7 +42,7 @@ class DeviceManager: def detect_element(self, name: str, text: str, pipe: str = '%s') -> None: if Gst.ElementFactory.find(name): - element: Optional[Gst.Element] = Gst.ElementFactory.make( + element: Gst.Element | None = Gst.ElementFactory.make( name, f'{name}presencetest') if element is None: log.warning('could not create %spresencetest', name) diff --git a/gajim/common/passwords.py b/gajim/common/passwords.py index 62972a4b3..a8bad5938 100644 --- a/gajim/common/passwords.py +++ b/gajim/common/passwords.py @@ -23,7 +23,6 @@ from __future__ import annotations from typing import cast -from typing import Optional import logging @@ -88,7 +87,7 @@ class SecretPasswordStorage: return False @staticmethod - def get_password(account_name: str) -> Optional[str]: + def get_password(account_name: str) -> str | None: if not is_keyring_available(): return @@ -162,7 +161,7 @@ def is_keyring_available() -> bool: return _interface.is_keyring_available -def get_password(account_name: str) -> Optional[str]: +def get_password(account_name: str) -> str | None: if not app.settings.get_account_setting(account_name, 'savepass'): return MemoryPasswordStorage().get_password(account_name) diff --git a/gajim/common/preview.py b/gajim/common/preview.py index 72b9da7ae..2f1e72437 100644 --- a/gajim/common/preview.py +++ b/gajim/common/preview.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional import logging import os @@ -82,13 +81,13 @@ class AudioPreviewState: class Preview: def __init__(self, uri: str, - urlparts: Optional[ParseResult], - orig_path: Optional[Path], - thumb_path: Optional[Path], + urlparts: ParseResult | None, + orig_path: Path | None, + thumb_path: Path | None, size: int, widget: Any, from_us: bool = False, - context: Optional[str] = None + context: str | None = None ) -> None: self.id = str(uuid.uuid4()) @@ -104,17 +103,17 @@ class Preview: self.thumb_path = thumb_path self.size = size - self.thumbnail: Optional[bytes] = None + self.thumbnail: bytes | None = None self.mime_type: str = '' self.file_size: int = 0 self.download_in_progress = False - self.info_message: Optional[str] = None + self.info_message: str | None = None self._request = None - self.key: Optional[bytes] = None - self.iv: Optional[bytes] = None + self.key: bytes | None = None + self.iv: bytes | None = None if self.is_aes_encrypted and urlparts is not None: try: self.key, self.iv = parse_fragment(urlparts.fragment) @@ -148,7 +147,7 @@ class Preview: return self._from_us @property - def context(self) -> Optional[str]: + def context(self) -> str | None: return self._context @property @@ -160,7 +159,7 @@ class Preview: return self._request @property - def request_uri(self) -> Optional[str]: + def request_uri(self) -> str | None: if self._urlparts is None: return '' if self.is_aes_encrypted: @@ -195,7 +194,7 @@ class Preview: return False return True - def update_widget(self, data: Optional[GdkPixbufType] = None) -> None: + def update_widget(self, data: GdkPixbufType | None = None) -> None: self._widget.update(self, data) def update_progress(self, progress: float, request: HTTPRequest) -> None: @@ -228,7 +227,7 @@ class PreviewManager: log.info('Supported mime types for preview') log.info(sorted(PREVIEWABLE_MIME_TYPES)) - def get_preview(self, preview_id: str) -> Optional[Preview]: + def get_preview(self, preview_id: str) -> Preview | None: return self._previews.get(preview_id) def clear_previews(self) -> None: @@ -335,7 +334,7 @@ class PreviewManager: uri: str, widget: Any, from_us: bool, - context: Optional[str] = None + context: str | None = None ) -> None: if uri.startswith('geo:'): preview = Preview(uri, None, None, None, 96, widget) @@ -369,7 +368,7 @@ class PreviewManager: uri: str, widget: Any, from_us: bool, - context: Optional[str] = None + context: str | None = None ) -> Preview: urlparts = urlparse(uri) size = app.settings.get('preview_size') @@ -388,7 +387,7 @@ class PreviewManager: context=context) def _on_orig_load_finished(self, - data: Optional[bytes], + data: bytes | None, error: Gio.AsyncResult, preview: Preview) -> None: if preview.thumb_path is None or preview.orig_path is None: @@ -409,7 +408,7 @@ class PreviewManager: preview.update_widget() @staticmethod - def _on_thumb_load_finished(data: Optional[bytes], + def _on_thumb_load_finished(data: bytes | None, error: Gio.AsyncResult, preview: Preview) -> None: diff --git a/gajim/common/preview_helpers.py b/gajim/common/preview_helpers.py index f834eca3a..43f6050ff 100644 --- a/gajim/common/preview_helpers.py +++ b/gajim/common/preview_helpers.py @@ -14,8 +14,6 @@ from typing import Any from typing import NamedTuple -from typing import Optional -from typing import Union import binascii import hashlib @@ -146,7 +144,7 @@ def extract_and_resize_frames(image: ImageFile.ImageFile, def create_thumbnail(data: bytes, size: int, mime_type: str - ) -> Optional[bytes]: + ) -> bytes | None: try: thumbnail = create_thumbnail_with_pil(data, size) @@ -162,7 +160,7 @@ def create_thumbnail(data: bytes, def create_thumbnail_with_pixbuf(data: bytes, size: int, mime_type: str - ) -> Optional[bytes]: + ) -> bytes | None: try: # Try to create GdKPixbuf loader with fixed mime-type to @@ -204,7 +202,7 @@ def create_thumbnail_with_pixbuf(data: bytes, return bytes_ -def create_thumbnail_with_pil(data: bytes, size: int) -> Optional[bytes]: +def create_thumbnail_with_pil(data: bytes, size: int) -> bytes | None: input_file = BytesIO(data) output_file = BytesIO() try: @@ -267,7 +265,7 @@ def get_thumbnail_size(pixbuf: GdkPixbuf.Pixbuf, size: int) -> tuple[int, int]: return image_width, image_height -def pixbuf_from_data(data: bytes) -> Optional[GdkPixbuf.Pixbuf]: +def pixbuf_from_data(data: bytes) -> GdkPixbuf.Pixbuf | None: loader = GdkPixbuf.PixbufLoader() try: loader.write(data) @@ -446,8 +444,8 @@ def get_previewable_mime_types() -> set[str]: )) -def guess_mime_type(file_path: Union[Path, str], - data: Optional[bytes] = None +def guess_mime_type(file_path: Path | str, + data: bytes | None = None ) -> str: file_path = str(file_path) @@ -471,7 +469,7 @@ def guess_mime_type(file_path: Union[Path, str], def guess_simple_file_type(file_path: str, - data: Optional[bytes] = None + data: bytes | None = None ) -> tuple[Gio.Icon, str]: mime_type = guess_mime_type(file_path, data) if mime_type == 'application/octet-stream': diff --git a/gajim/common/setting_values.py b/gajim/common/setting_values.py index f0c9dfd52..d91856e3a 100644 --- a/gajim/common/setting_values.py +++ b/gajim/common/setting_values.py @@ -14,7 +14,6 @@ from typing import Literal from typing import TypedDict -from typing import Union import uuid @@ -161,7 +160,7 @@ StringSettings = Literal[ ] AllSettings = Literal[BoolSettings, IntSettings, StringSettings] -AllSettingsT = Union[str, int, bool, list[str]] +AllSettingsT = str | int | bool | list[str] APP_SETTINGS = { 'additional_uri_schemes': '', @@ -390,7 +389,7 @@ AllGroupChatSettings = Literal[BoolGroupChatSettings, IntGroupChatSettings, StringGroupChatSettings] -AllGroupChatSettingsT = Union[str, int, bool] +AllGroupChatSettingsT = str | int | bool BoolContactSettings = Literal[ @@ -407,7 +406,7 @@ StringContactSettings = Literal[ AllContactSettings = Literal[BoolContactSettings, StringContactSettings] -AllContactSettingsT = Union[str, bool] +AllContactSettingsT = str | bool ACCOUNT_SETTINGS = { @@ -519,7 +518,7 @@ class OpenChatSettingDetails(TypedDict): OpenChatsSettingT = list[OpenChatSettingDetails] -AllWorkspaceSettingsT = Union[str, OpenChatsSettingT] +AllWorkspaceSettingsT = str | OpenChatsSettingT class WorkspaceSettings(TypedDict): diff --git a/gajim/common/settings.py b/gajim/common/settings.py index c8fe7897a..a286eeda5 100644 --- a/gajim/common/settings.py +++ b/gajim/common/settings.py @@ -17,10 +17,8 @@ from typing import Callable from typing import cast from typing import Literal from typing import NamedTuple -from typing import Optional from typing import overload from typing import TypedDict -from typing import Union import inspect import json @@ -76,7 +74,7 @@ from gajim.common.setting_values import WorkspaceSettings from gajim.common.storage.base import Encoder from gajim.common.storage.base import json_decoder -SETTING_TYPE = Union[bool, int, str, object] +SETTING_TYPE = bool | int | str | object log = logging.getLogger('gajim.c.settings') @@ -108,8 +106,8 @@ CREATE_SQL = ''' CURRENT_USER_VERSION) -_SignalCallable = Callable[[Any, str, Optional[str], Optional[JID]], Any] -_CallbackDict = dict[tuple[str, Optional[str], Optional[JID]], +_SignalCallable = Callable[[Any, str, str | None, JID | None], Any] +_CallbackDict = dict[tuple[str, str | None, JID | None], list[weakref.WeakMethod[_SignalCallable]]] if app.is_flatpak(): @@ -137,15 +135,15 @@ class Settings: self._settings: SettingsDictT = {} self._app_overrides: dict[str, AllSettingsT] = {} self._account_settings: dict[ - str, Union[Any, dict[str, dict[Union[JID, str], Any]]]] = {} + str, Any | dict[str, dict[JID | str, Any]]] = {} self._callbacks: _CallbackDict = defaultdict(list) def connect_signal(self, setting: str, func: _SignalCallable, - account: Optional[str] = None, - jid: Optional[JID] = None) -> None: + account: str | None = None, + jid: JID | None = None) -> None: if not inspect.ismethod(func): # static methods are not bound to an object so we can’t easily # remove the func once it should not be called anymore @@ -167,10 +165,10 @@ class Settings: setting: str, widget: Any, func_name: str, - account: Optional[str] = None, - jid: Optional[JID] = None, + account: str | None = None, + jid: JID | None = None, inverted: bool = False, - default_text: Optional[str] = None + default_text: str | None = None ) -> None: callbacks = self._callbacks[(setting, account, jid)] @@ -185,8 +183,8 @@ class Settings: def _notify(self, value: Any, setting: str, - account: Optional[str] = None, - jid: Optional[JID] = None) -> None: + account: str | None = None, + jid: JID | None = None) -> None: log.info('Signal: %s changed', setting) @@ -504,8 +502,8 @@ class Settings: jid]['encryption'] = encryption self._commit_account_settings(account) - def _split_encryption_config_key(self, key: str) -> tuple[Optional[str], - Optional[str]]: + def _split_encryption_config_key(self, key: str) -> tuple[str | None, + str | None]: for account in self._account_settings: if not key.startswith(account): continue @@ -644,19 +642,19 @@ class Settings: @overload def set_app_setting(self, setting: BoolSettings, - value: Optional[bool]) -> None: + value: bool | None) -> None: ... @overload def set_app_setting(self, setting: StringSettings, - value: Optional[str]) -> None: + value: str | None) -> None: ... @overload def set_app_setting(self, setting: IntSettings, - value: Optional[int]) -> None: + value: int | None) -> None: ... @overload @@ -667,7 +665,7 @@ class Settings: def set_app_setting(self, setting: str, - value: Optional[AllSettingsT]) -> None: + value: AllSettingsT | None) -> None: if setting not in APP_SETTINGS: raise ValueError(f'Invalid app setting: {setting}') @@ -807,27 +805,27 @@ class Settings: def set_account_setting(self, account: str, setting: StringAccountSettings, - value: Optional[str]) -> None: + value: str | None) -> None: ... @overload def set_account_setting(self, account: str, setting: IntAccountSettings, - value: Optional[int]) -> None: + value: int | None) -> None: ... @overload def set_account_setting(self, account: str, setting: BoolAccountSettings, - value: Optional[bool]) -> None: + value: bool | None) -> None: ... def set_account_setting(self, account: str, setting: str, - value: Optional[AllSettingsT]) -> None: + value: AllSettingsT | None) -> None: if account not in self._account_settings: raise ValueError(f'Account missing: {account}') @@ -1004,7 +1002,7 @@ class Settings: def set_group_chat_settings(self, setting: str, value: SETTING_TYPE, - context: Optional[str] = None + context: str | None = None ) -> None: for account, acc_settings in self._account_settings.items(): diff --git a/gajim/common/sound.py b/gajim/common/sound.py index 80baaa3cf..e3ff70f4e 100644 --- a/gajim/common/sound.py +++ b/gajim/common/sound.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import sys @@ -97,7 +96,7 @@ class PlatformMacOS(PlaySound): class PlatformUnix(PlaySound): def __init__(self) -> None: - self._cancellable: Optional[Gio.Cancellable] = None + self._cancellable: Gio.Cancellable | None = None def play(self, path: Path, loop: bool = False) -> None: if not app.is_installed('GSOUND'): diff --git a/gajim/common/storage/archive.py b/gajim/common/storage/archive.py index 62bf66215..36a9907c8 100644 --- a/gajim/common/storage/archive.py +++ b/gajim/common/storage/archive.py @@ -26,7 +26,6 @@ from typing import Iterator from typing import KeysView from typing import Literal from typing import NamedTuple -from typing import Optional import calendar import datetime @@ -284,7 +283,7 @@ class MessageArchiveStorage(SqliteStorage): self._jid_ids[row.jid] = row self._jid_ids_reversed[row.jid_id] = row - def get_jid_from_id(self, jid_id: int) -> Optional[JidsTableRow]: + def get_jid_from_id(self, jid_id: int) -> JidsTableRow | None: # Use get as a fail-safe for cases where the JID ID table is incomplete return self._jid_ids_reversed.get(jid_id) @@ -307,8 +306,8 @@ class MessageArchiveStorage(SqliteStorage): @timeit def get_jid_id(self, jid: JID, - kind: Optional[KindConstant] = None, - type_: Optional[JIDConstant] = None + kind: KindConstant | None = None, + type_: JIDConstant | None = None ) -> int: ''' Get the jid id from a jid. @@ -541,9 +540,9 @@ class MessageArchiveStorage(SqliteStorage): account: str, jid: JID, query: str, - from_users: Optional[list[str]] = None, - before: Optional[datetime.datetime] = None, - after: Optional[datetime.datetime] = None + from_users: list[str] | None = None, + before: datetime.datetime | None = None, + after: datetime.datetime | None = None ) -> Iterator[SearchLogRow]: ''' Search the conversation log for messages containing the `query` string. @@ -627,9 +626,9 @@ class MessageArchiveStorage(SqliteStorage): @timeit def search_all_logs(self, query: str, - from_users: Optional[list[str]] = None, - before: Optional[datetime.datetime] = None, - after: Optional[datetime.datetime] = None + from_users: list[str] | None = None, + before: datetime.datetime | None = None, + after: datetime.datetime | None = None ) -> Iterator[SearchLogRow]: ''' Search all conversation logs for messages containing the `query` @@ -737,7 +736,7 @@ class MessageArchiveStorage(SqliteStorage): def get_last_history_timestamp(self, account: str, jid: str - ) -> Optional[float]: + ) -> float | None: ''' Get the timestamp of the last message we received for the jid ''' @@ -763,7 +762,7 @@ class MessageArchiveStorage(SqliteStorage): def get_first_history_timestamp(self, account: str, jid: str - ) -> Optional[float]: + ) -> float | None: ''' Get the timestamp of the first message we received for the jid ''' @@ -790,7 +789,7 @@ class MessageArchiveStorage(SqliteStorage): account: str, jid: str, date: datetime.datetime - ) -> Optional[float]: + ) -> float | None: ''' Get a single timestamp of a message for 'jid' in time range of one day @@ -819,7 +818,7 @@ class MessageArchiveStorage(SqliteStorage): account: str, jid: str, date: datetime.datetime - ) -> Optional[MessageMetaRow]: + ) -> MessageMetaRow | None: ''' Load meta data for the first message of a specific date ''' @@ -950,7 +949,7 @@ class MessageArchiveStorage(SqliteStorage): account: str, jid: JID, message_id: str - ) -> Optional[LastConversationRow]: + ) -> LastConversationRow | None: ''' Load the last correctable message of a conversation by message_id. Conditions: max 5 min old @@ -977,7 +976,7 @@ class MessageArchiveStorage(SqliteStorage): def try_message_correction(self, account: str, jid: JID, - nickname: Optional[str], + nickname: str | None, corrected_text: str, correct_id: str, kind: KindConstant, @@ -1131,7 +1130,7 @@ class MessageArchiveStorage(SqliteStorage): def insert_jid(self, jid: str, - kind: Optional[KindConstant] = None, + kind: KindConstant | None = None, type_: JIDConstant = JIDConstant.NORMAL_TYPE ) -> int: ''' @@ -1276,7 +1275,7 @@ class MessageArchiveStorage(SqliteStorage): self._delayed_commit() @timeit - def get_archive_infos(self, jid: str) -> Optional[LastArchiveMessageRow]: + def get_archive_infos(self, jid: str) -> LastArchiveMessageRow | None: ''' Get the archive infos diff --git a/gajim/common/storage/base.py b/gajim/common/storage/base.py index 5b1a7c818..87e45555a 100644 --- a/gajim/common/storage/base.py +++ b/gajim/common/storage/base.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional from typing import TypeVar import json @@ -156,7 +155,7 @@ class SqliteStorage: def __init__(self, log: logging.Logger, - path: Optional[Path], + path: Path | None, create_statement: str, commit_delay: int = 500 ) -> None: diff --git a/gajim/common/storage/cache.py b/gajim/common/storage/cache.py index 2d8244baf..0eb0e3b8c 100644 --- a/gajim/common/storage/cache.py +++ b/gajim/common/storage/cache.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import NamedTuple -from typing import Optional import json import logging @@ -204,7 +203,7 @@ class CacheStorage(SqliteStorage): def get_last_disco_info(self, jid: JID, - max_age: int = 0) -> Optional[DiscoInfo]: + max_age: int = 0) -> DiscoInfo | None: ''' Get last disco info from jid @@ -274,7 +273,7 @@ class CacheStorage(SqliteStorage): self._delayed_commit() @timeit - def load_roster(self, account: str) -> Optional[dict[JID, RosterItem]]: + def load_roster(self, account: str) -> dict[JID, RosterItem] | None: select_sql = 'SELECT roster FROM roster WHERE account = ?' result = self._con.execute(select_sql, (account,)).fetchone() if result is None: diff --git a/gajim/common/storage/draft.py b/gajim/common/storage/draft.py index 10e52e79b..d0fa2a59d 100644 --- a/gajim/common/storage/draft.py +++ b/gajim/common/storage/draft.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from gajim.common import types from gajim.common.helpers import Observable @@ -34,7 +32,7 @@ class DraftStorage(Observable): self._drafts[contact] = text self.notify('draft-update', contact, text) - def get(self, contact: types.ChatContactT) -> Optional[str]: + def get(self, contact: types.ChatContactT) -> str | None: return self._drafts.get(contact) def remove(self, contact: types.ChatContactT) -> None: diff --git a/gajim/common/storage/omemo.py b/gajim/common/storage/omemo.py index 4b76d7b8b..d165b277d 100644 --- a/gajim/common/storage/omemo.py +++ b/gajim/common/storage/omemo.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import Any from typing import NamedTuple -from typing import Optional import sqlite3 import time @@ -42,7 +41,7 @@ from gajim.common import app from gajim.common.modules.util import LogAdapter -def _convert_identity_key(key: bytes) -> Optional[IdentityKey]: +def _convert_identity_key(key: bytes) -> IdentityKey | None: if not key: return return IdentityKey(CurvePublicKey(key[1:])) @@ -423,7 +422,7 @@ class OMEMOStorage(Store): result = self._con.execute(query, (recipient_id, device_id)).fetchone() return result.record if result is not None else SessionRecord() - def get_jid_from_device(self, device_id: int) -> Optional[str]: + def get_jid_from_device(self, device_id: int) -> str | None: query = '''SELECT recipient_id FROM sessions WHERE device_id = ?''' result = self._con.execute(query, (device_id, )).fetchone() @@ -584,7 +583,7 @@ class OMEMOStorage(Store): self._con.execute(query, (pre_key_id,)) self._con.commit() - def get_current_pre_key_id(self) -> Optional[int]: + def get_current_pre_key_id(self) -> int | None: query = 'SELECT MAX(prekey_id) FROM prekeys' result = self._con.execute(query).fetchone() return result.max_prekey_id if result is not None else None @@ -678,7 +677,7 @@ class OMEMOStorage(Store): def get_trust_for_identity(self, recipient_id: str, identity_key: IdentityKey - ) -> Optional[OMEMOTrust]: + ) -> OMEMOTrust | None: query = '''SELECT trust FROM identities WHERE recipient_id = ? AND public_key = ?''' @@ -742,7 +741,7 @@ class OMEMOStorage(Store): def get_identity_last_seen(self, recipient_id: str, identity_key: IdentityKey - ) -> Optional[int]: + ) -> int | None: serialized = identity_key.get_public_key().serialize() query = '''SELECT timestamp FROM identities diff --git a/gajim/common/structs.py b/gajim/common/structs.py index 0d5e08d77..2d74d2cd7 100644 --- a/gajim/common/structs.py +++ b/gajim/common/structs.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import NamedTuple -from typing import Optional from typing import TypeVar import time @@ -55,8 +54,8 @@ class MUCData: def __init__(self, room_jid: str, nick: str, - password: Optional[str], - config: Optional[dict[str, Any]] = None + password: str | None, + config: dict[str, Any] | None = None ) -> None: self._room_jid = JID.from_string(room_jid) @@ -65,12 +64,12 @@ class MUCData: self.password = password self.state = MUCJoinedState.NOT_JOINED # Message id of the captcha challenge - self.captcha_id: Optional[str] = None - self.captcha_form: Optional[SimpleDataForm] = None - self.error: Optional[str] = None - self.error_text: Optional[str] = None - self.subject: Optional[MucSubject] = None - self.last_subject_timestamp: Optional[float] = None + self.captcha_id: str | None = None + self.captcha_form: SimpleDataForm | None = None + self.error: str | None = None + self.error_text: str | None = None + self.subject: MucSubject | None = None + self.last_subject_timestamp: float | None = None @property def jid(self) -> JID: @@ -81,7 +80,7 @@ class MUCData: return self._room_jid.new_with(resource=self.nick) @property - def config(self) -> Optional[dict[str, Any]]: + def config(self) -> dict[str, Any] | None: return self._config @@ -89,20 +88,20 @@ class OutgoingMessage: def __init__(self, account: str, contact: types.ChatContactT, - message: Optional[str], + message: str | None, type_: str, - subject: Optional[str] = None, - chatstate: Optional[Chatstate] = None, - marker: Optional[tuple[str, str]] = None, - resource: Optional[str] = None, - user_nick: Optional[str] = None, - label: Optional[SecurityLabel] = None, - control: Optional[Any] = None, - attention: Optional[bool] = None, - correct_id: Optional[str] = None, - oob_url: Optional[str] = None, - xhtml: Optional[str] = None, - nodes: Optional[Any] = None, + subject: str | None = None, + chatstate: Chatstate | None = None, + marker: tuple[str, str] | None = None, + resource: str | None = None, + user_nick: str | None = None, + label: SecurityLabel | None = None, + control: Any | None = None, + attention: bool | None = None, + correct_id: str | None = None, + oob_url: str | None = None, + xhtml: str | None = None, + nodes: Any | None = None, play_sound: bool = True ) -> None: @@ -210,7 +209,7 @@ class PresenceData: show: PresenceShow status: str priority: int - idle_time: Optional[float] + idle_time: float | None available: bool @classmethod @@ -233,11 +232,11 @@ UNKNOWN_PRESENCE = PresenceData(show=PresenceShowExt.OFFLINE, class MUCPresenceData: show: PresenceShow status: str - idle_time: Optional[float] + idle_time: float | None available: bool affiliation: Affiliation role: Role - real_jid: Optional[JID] + real_jid: JID | None @classmethod def from_presence(cls, properties: PresenceProperties) -> MUCPresenceData: diff --git a/gajim/common/styling.py b/gajim/common/styling.py index f080f68c2..1731cbb63 100644 --- a/gajim/common/styling.py +++ b/gajim/common/styling.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import Match -from typing import Optional -from typing import Union import re import string @@ -190,7 +188,7 @@ def find_byte_index(text: str, index: int): raise ValueError('index not in string: %s, %s' % (text, index)) -def process(text: Union[str, bytes], level: int = 0) -> ParsingResult: +def process(text: str | bytes, level: int = 0) -> ParsingResult: if isinstance(text, bytes): text = text.decode() @@ -213,7 +211,7 @@ def process(text: Union[str, bytes], level: int = 0) -> ParsingResult: return ParsingResult(text, blocks) -def process_uris(text: Union[str, bytes]) -> list[BaseHyperlink]: +def process_uris(text: str | bytes) -> list[BaseHyperlink]: if isinstance(text, bytes): text = text.decode() @@ -324,7 +322,7 @@ def _parse_uris(line: str, offset_bytes: int) -> list[BaseHyperlink]: uris: list[BaseHyperlink] = [] - def make(start: int, end: int, is_jid: bool) -> Optional[BaseHyperlink]: + def make(start: int, end: int, is_jid: bool) -> BaseHyperlink | None: if line[end - 1] == ',': # Trim one trailing comma end -= 1 @@ -399,7 +397,7 @@ def _make_hyperlink(line: str, end: int, offset: int, offset_bytes: int, - is_jid: bool) -> Optional[BaseHyperlink]: + is_jid: bool) -> BaseHyperlink | None: text = line[start:end + 1] diff --git a/gajim/common/task_manager.py b/gajim/common/task_manager.py index 940ab9d23..08b64bb7c 100644 --- a/gajim/common/task_manager.py +++ b/gajim/common/task_manager.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import functools import logging import queue @@ -27,7 +25,7 @@ log = logging.getLogger('gajim.c.m.task_manager') class TaskManager: def __init__(self) -> None: - self._timeout: Optional[int] = None + self._timeout: int | None = None self._queue: queue.PriorityQueue[Task] = queue.PriorityQueue() def _start_worker(self) -> None: diff --git a/gajim/common/types.py b/gajim/common/types.py index 8e8b8d037..523c950d4 100644 --- a/gajim/common/types.py +++ b/gajim/common/types.py @@ -16,7 +16,6 @@ from typing import Any from typing import Callable -from typing import Optional from typing import TYPE_CHECKING from typing import Union @@ -46,10 +45,10 @@ if TYPE_CHECKING: from gajim.gtk.css_config import CSSConfig - ContactT = Union[BareContact, - ResourceContact, - GroupchatContact, - GroupchatParticipant] + ContactT = (BareContact | + ResourceContact | + GroupchatContact | + GroupchatParticipant) InterfaceT = Union['Interface'] PluginManagerT = Union['PluginManager'] @@ -63,14 +62,14 @@ PEPNotifyCallback = Callable[[nbxmpp.JID, nbxmpp.Node], None] PEPHandlersDict = dict[str, list[PEPNotifyCallback]] # Plugins -PluginExtensionPoints = dict[str, tuple[Optional[Callable[..., None]], - Optional[Callable[..., None]]]] +PluginExtensionPoints = dict[str, tuple[Callable[..., None] | None, + Callable[..., None] | None]] SettingsT = Union['Settings'] BookmarksDict = dict[JID, BookmarkData] -GdkPixbufType = Union[GdkPixbuf.Pixbuf, GdkPixbuf.PixbufAnimation] +GdkPixbufType = GdkPixbuf.Pixbuf | GdkPixbuf.PixbufAnimation AnyCallableT = Callable[..., Any] ObservableCbDict = dict[str, list[weakref.WeakMethod[AnyCallableT]]] @@ -80,4 +79,4 @@ ChatContactT = Union['BareContact', 'GroupchatContact', 'GroupchatParticipant'] OneOnOneContactT = Union['BareContact', 'GroupchatParticipant'] GroupchatContactT = Union['GroupchatContact'] -PresenceShowT = Union[PresenceShowExt, PresenceShow] +PresenceShowT = PresenceShowExt | PresenceShow diff --git a/gajim/common/util/http.py b/gajim/common/util/http.py index 9bb93170a..04e40fbdb 100644 --- a/gajim/common/util/http.py +++ b/gajim/common/util/http.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional from nbxmpp.http import HTTPRequest from nbxmpp.http import HTTPSession @@ -23,8 +22,8 @@ from gajim.common.helpers import determine_proxy from gajim.common.helpers import get_account_proxy -def create_http_session(account: Optional[str] = None, - proxy: Optional[ProxyData] = None +def create_http_session(account: str | None = None, + proxy: ProxyData | None = None ) -> HTTPSession: session = HTTPSession(user_agent=f'Gajim {app.version}') @@ -41,6 +40,6 @@ def create_http_session(account: Optional[str] = None, return session -def create_http_request(account: Optional[str] = None) -> HTTPRequest: +def create_http_request(account: str | None = None) -> HTTPRequest: session = create_http_session(account) return session.create_request() diff --git a/gajim/common/winapi/system_style.py b/gajim/common/winapi/system_style.py index 704dc98d4..27c8f1b85 100644 --- a/gajim/common/winapi/system_style.py +++ b/gajim/common/winapi/system_style.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Callable -from typing import Optional import logging @@ -33,7 +32,7 @@ log = logging.getLogger('gajim.c.winapi.system_style') class SystemStyleListener: def __init__(self, callback: Callable[..., None]) -> None: - self._prefer_dark: Optional[bool] = None + self._prefer_dark: bool | None = None self._callback = callback self._ui_settings = UISettings() @@ -56,5 +55,5 @@ class SystemStyleListener: app.ged.raise_event(StyleChanged()) @property - def prefer_dark(self) -> Optional[bool]: + def prefer_dark(self) -> bool | None: return self._prefer_dark diff --git a/gajim/gajim.py b/gajim/gajim.py index 4a5e9a734..349092807 100644 --- a/gajim/gajim.py +++ b/gajim/gajim.py @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional import os import platform @@ -124,7 +123,7 @@ def _run_app() -> None: from gajim.gtk.application import GajimApplication application = GajimApplication() - def sigint_cb(num: int, stack: Optional[FrameType]) -> None: + def sigint_cb(num: int, stack: FrameType | None) -> None: print(' SIGINT/SIGTERM received') application.quit() diff --git a/gajim/gtk/account_side_bar.py b/gajim/gtk/account_side_bar.py index e48620423..4ed76b23a 100644 --- a/gajim/gtk/account_side_bar.py +++ b/gajim/gtk/account_side_bar.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional from gi.repository import Gtk @@ -76,7 +75,7 @@ class Account(Gtk.ListBoxRow, EventHelper): self.get_style_context().add_class('account-sidebar-item') self.account = account - self._account_class: Optional[str] = None + self._account_class: str | None = None self.register_events([ ('account-enabled', ged.GUI1, diff --git a/gajim/gtk/account_wizard.py b/gajim/gtk/account_wizard.py index f0bc97b53..588c5776e 100644 --- a/gajim/gtk/account_wizard.py +++ b/gajim/gtk/account_wizard.py @@ -17,9 +17,7 @@ from __future__ import annotations from typing import Any from typing import cast from typing import Literal -from typing import Optional from typing import overload -from typing import Union import logging @@ -108,7 +106,7 @@ class AccountWizard(Assistant): self.update_proxy_list() - self._client: Optional[Client] = None + self._client: Client | None = None self._method: str = 'login' @overload @@ -264,7 +262,7 @@ class AccountWizard(Assistant): def update_proxy_list(self) -> None: self.get_page('advanced').update_proxy_list() - def _get_proxy_data(self, advanced: bool) -> Optional[ProxyData]: + def _get_proxy_data(self, advanced: bool) -> ProxyData | None: if advanced: proxy_name = self.get_page('advanced').get_proxy() proxy_data = get_proxy(proxy_name) @@ -275,7 +273,7 @@ class AccountWizard(Assistant): def _get_base_client(self, domain: str, - username: Optional[str], + username: str | None, mode: Mode, advanced: bool, ignore_all_errors: bool @@ -569,11 +567,11 @@ class AccountWizard(Assistant): self.get_page('form').remove_form() self._disconnect() - def _set_error_text(self, - error: Union[StanzaError, - RegisterStanzaError, - MalformedStanzaError] - ) -> None: + def _set_error_text( + self, + error: StanzaError | RegisterStanzaError | MalformedStanzaError + ) -> None: + error_text = error.get_text() if not error_text: error_text = _('The server rejected the registration ' @@ -842,7 +840,7 @@ class AdvancedSettings(Page): active = self._ui.proxies_combobox.get_active() return self._ui.proxies_combobox.get_model()[active][0] - def get_custom_host(self) -> Optional[CustomHostT]: + def get_custom_host(self) -> CustomHostT | None: host = self._ui.custom_host_entry.get_text() port = self._ui.custom_port_entry.get_text() if not host or not port: @@ -941,8 +939,8 @@ class SecurityWarning(Page): def __init__(self) -> None: Page.__init__(self) self.title: str = _('Security Warning') - self._cert: Optional[Gio.TlsCertificate] = None - self._domain: Optional[str] = None + self._cert: Gio.TlsCertificate | None = None + self._domain: str | None = None self._ui = get_builder('account_wizard.ui') self.pack_start(self._ui.security_warning_box, True, True, 0) @@ -950,7 +948,7 @@ class SecurityWarning(Page): self.show_all() @property - def cert(self) -> Optional[Gio.TlsCertificate]: + def cert(self) -> Gio.TlsCertificate | None: return self._cert def set_warning(self, @@ -1007,7 +1005,7 @@ class Form(Page): self.set_valign(Gtk.Align.FILL) self.complete: bool = False self.title: str = _('Create Account') - self._current_form: Optional[Any] = None + self._current_form: Any | None = None heading = Gtk.Label(label=_('Create Account')) heading.get_style_context().add_class('large-header') @@ -1082,7 +1080,7 @@ class Redirect(Page): def __init__(self) -> None: Page.__init__(self) self.title: str = _('Redirect') - self._link: Optional[str] = None + self._link: str | None = None self._ui = get_builder('account_wizard.ui') self.pack_start(self._ui.redirect_box, True, True, 0) @@ -1109,10 +1107,10 @@ class Success(SuccessPage): self.set_title(_('Account Added')) self.set_heading(_('Account has been added successfully')) - self._account: Optional[str] = None - self._our_jid: Optional[str] = None - self._label: Optional[str] = None - self._color: Optional[str] = None + self._account: str | None = None + self._our_jid: str | None = None + self._label: str | None = None + self._color: str | None = None self._ui = get_builder('account_wizard.ui') self.pack_start(self._ui.account_label_box, True, True, 0) @@ -1136,7 +1134,7 @@ class Success(SuccessPage): self._save_config() @property - def account(self) -> Optional[str]: + def account(self) -> str | None: return self._account def _add_css_provider(self) -> Gtk.CssProvider: diff --git a/gajim/gtk/accounts.py b/gajim/gtk/accounts.py index c03b13e2d..a745071b4 100644 --- a/gajim/gtk/accounts.py +++ b/gajim/gtk/accounts.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import locale import logging @@ -169,7 +168,7 @@ class AccountsWindow(Gtk.ApplicationWindow): if not initial: self._accounts[account].show() - def select_account(self, account: str, page: Optional[str] = None) -> None: + def select_account(self, account: str, page: str | None = None) -> None: try: self._accounts[account].select(page) except KeyError: @@ -466,7 +465,7 @@ class Account: self._account_row = AccountRow(account) self._menu.add_account(self._account_row) - def select(self, page_name: Optional[str] = None) -> None: + def select(self, page_name: str | None = None) -> None: self._account_row.emit('activate') if page_name is not None: self._menu.set_page(self._account, page_name) @@ -763,7 +762,7 @@ class PrivacyPage(GenericSettingPage): def __init__(self, account: str) -> None: self._account = account - self._client: Optional[types.Client] = None + self._client: types.Client | None = None if app.account_is_connected(account): self._client = app.get_client(account) diff --git a/gajim/gtk/add_contact.py b/gajim/gtk/add_contact.py index 7c90f9f2e..dd56b24b0 100644 --- a/gajim/gtk/add_contact.py +++ b/gajim/gtk/add_contact.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import logging @@ -48,15 +46,15 @@ log = logging.getLogger('gajim.gtk.add_contact') class AddContact(Assistant): def __init__(self, - account: Optional[str] = None, - jid: Optional[JID] = None, - nick: Optional[str] = None): + account: str | None = None, + jid: JID | None = None, + nick: str | None = None): Assistant.__init__(self) self.account = account self.jid = jid self._nick = nick - self._result: Union[DiscoInfo, StanzaError, None] = None + self._result: DiscoInfo | StanzaError | None = None self.add_button('next', _('Next'), complete=True, css_class='suggested-action') @@ -221,7 +219,7 @@ class AddContact(Assistant): class Address(Page): - def __init__(self, account: Optional[str], jid: Optional[JID]) -> None: + def __init__(self, account: str | None, jid: JID | None) -> None: Page.__init__(self) self.title = _('Add Contact') @@ -349,9 +347,9 @@ class Contact(Page): Page.__init__(self) self.title = _('Add Contact') - self._result: Union[DiscoInfo, BaseError, None] = None - self._account: Optional[str] = None - self._contact: Optional[types.BareContact] = None + self._result: DiscoInfo | BaseError | None = None + self._account: str | None = None + self._contact: types.BareContact | None = None self._ui = get_builder('add_contact.ui') self.add(self._ui.contact_grid) @@ -366,7 +364,7 @@ class Contact(Page): def get_default_button(self) -> str: return 'add' - def prepare(self, account: str, result: Union[DiscoInfo, StanzaError]): + def prepare(self, account: str, result: DiscoInfo | StanzaError): self._result = result self._account = account @@ -389,7 +387,7 @@ class Contact(Page): open_window( 'ContactInfo', account=self._account, contact=self._contact) - def get_subscription_data(self) -> dict[str, Union[str, list[str], bool]]: + def get_subscription_data(self) -> dict[str, str | list[str] | bool]: group = self._ui.group_combo.get_child().get_text() groups = [group] if group else [] return { @@ -404,8 +402,8 @@ class Gateway(Page): Page.__init__(self) self.title = _('Service Gateway') - self._account: Optional[str] = None - self._result: Optional[DiscoInfo] = None + self._account: str | None = None + self._result: DiscoInfo | None = None self._ui = get_builder('add_contact.ui') self.add(self._ui.gateway_box) @@ -492,7 +490,7 @@ class GroupChat(Page): Page.__init__(self) self.title = _('Join Group Chat?') - self._result: Optional[DiscoInfo] = None + self._result: DiscoInfo | None = None heading = Gtk.Label(label=_('Join Group Chat?')) heading.get_style_context().add_class('large-header') diff --git a/gajim/gtk/adhoc.py b/gajim/gtk/adhoc.py index 57d2f5103..b8741da2c 100644 --- a/gajim/gtk/adhoc.py +++ b/gajim/gtk/adhoc.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import logging @@ -50,7 +48,7 @@ log = logging.getLogger('gajim.gtk.adhoc') class AdHocCommands(Assistant): - def __init__(self, account: str, jid: Optional[str] = None) -> None: + def __init__(self, account: str, jid: str | None = None) -> None: Assistant.__init__(self, width=600, height=500) self.account = account self.jid = jid @@ -91,7 +89,7 @@ class AdHocCommands(Assistant): @ensure_not_destroyed def _received_command_list(self, task: Task) -> None: try: - commands = cast(Optional[list[AdHocCommand]], task.finish()) + commands = cast(list[AdHocCommand] | None, task.finish()) except (StanzaError, MalformedStanzaError) as error: self._set_error(to_user_string(error), False) return @@ -116,7 +114,7 @@ class AdHocCommands(Assistant): if stage.is_completed: page_name = 'completed' - page = cast(Union[Stage, Completed], self.get_page(page_name)) + page = cast(Stage | Completed, self.get_page(page_name)) page.process_stage(stage) self.show_page(page_name) @@ -247,7 +245,7 @@ class Commands(Page): self._commands[key] = command self._store.append((command.name, key)) - def get_selected_command(self) -> Optional[AdHocCommand]: + def get_selected_command(self) -> AdHocCommand | None: model, treeiter = self._treeview.get_selection().get_selected() if treeiter is None: return None @@ -268,19 +266,19 @@ class Stage(Page): self._dataform_widget = None self._notes: list[Gtk.Label] = [] - self._last_stage_data: Optional[AdHocCommand] = None + self._last_stage_data: AdHocCommand | None = None self.default = None self.show_all() @property def stage_data(self) -> tuple[AdHocCommand, - Union[SimpleDataForm, MultipleDataForm]]: + SimpleDataForm | MultipleDataForm]: assert self._last_stage_data is not None assert self._dataform_widget is not None return self._last_stage_data, self._dataform_widget.get_submit_form() @property - def actions(self) -> Optional[set[AdHocAction]]: + def actions(self) -> set[AdHocAction] | None: assert self._last_stage_data is not None return self._last_stage_data.actions @@ -295,7 +293,7 @@ class Stage(Page): self._show_form(stage_data.data) self.default = stage_data.default - def _show_form(self, form: Optional[Node]) -> None: + def _show_form(self, form: Node | None) -> None: if self._dataform_widget is not None: self.remove(self._dataform_widget) self._dataform_widget.destroy() @@ -309,7 +307,7 @@ class Stage(Page): self._dataform_widget.show_all() self.add(self._dataform_widget) - def _show_notes(self, notes: Optional[list[AdHocCommandNote]]): + def _show_notes(self, notes: list[AdHocCommandNote] | None): for note in self._notes: self.remove(note) self._notes = [] @@ -375,7 +373,7 @@ class Completed(Page): self.set_valign(Gtk.Align.FILL) self._icon_text.hide() - def _show_form(self, form: Optional[Node]) -> None: + def _show_form(self, form: Node | None) -> None: if self._dataform_widget is not None: self.remove(self._dataform_widget) self._dataform_widget.destroy() diff --git a/gajim/gtk/advanced_config.py b/gajim/gtk/advanced_config.py index bd117769b..6559df831 100644 --- a/gajim/gtk/advanced_config.py +++ b/gajim/gtk/advanced_config.py @@ -19,7 +19,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional from enum import IntEnum from enum import unique @@ -128,7 +127,7 @@ class AdvancedConfig(Gtk.ApplicationWindow): cell: Gtk.CellRenderer, model: Gtk.TreeModel, iter_: Gtk.TreeIter, - _data: Optional[object] + _data: object | None ) -> None: opt_is_default = model[iter_][Column.IS_DEFAULT] @@ -139,7 +138,7 @@ class AdvancedConfig(Gtk.ApplicationWindow): cell: Gtk.CellRenderer, model: Gtk.TreeModel, iter_: Gtk.TreeIter, - _data: Optional[object] + _data: object | None ) -> None: opt_type = model[iter_][Column.TYPE] @@ -259,7 +258,7 @@ class AdvancedConfig(Gtk.ApplicationWindow): def _visible_func(self, model: Gtk.TreeModel, treeiter: Gtk.TreeIter, - _data: Optional[object] + _data: object | None ) -> bool: search_string = self._ui.search_entry.get_text().lower() if not search_string: diff --git a/gajim/gtk/app_page.py b/gajim/gtk/app_page.py index 9b230d86a..e965f8bde 100644 --- a/gajim/gtk/app_page.py +++ b/gajim/gtk/app_page.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import sys from datetime import datetime @@ -77,8 +76,8 @@ class AppPage(Gtk.Box): def add_app_message(self, category: str, - new_version: Optional[str] = None, - new_setup_url: Optional[str] = None + new_version: str | None = None, + new_setup_url: str | None = None ) -> None: self._app_message_listbox.add_app_message( @@ -117,8 +116,8 @@ class AppMessageListBox(Gtk.ListBox): def add_app_message(self, category: str, - new_version: Optional[str] = None, - new_setup_url: Optional[str] = None + new_version: str | None = None, + new_setup_url: str | None = None ) -> None: row = AppMessageRow(category, new_version, new_setup_url) @@ -166,9 +165,9 @@ class AppMessageListBox(Gtk.ListBox): class AppMessageRow(Gtk.ListBoxRow): def __init__(self, category: str, - new_version: Optional[str] = None, - new_setup_url: Optional[str] = None, - plugin_manifests: Optional[list[PluginManifest]] = None + new_version: str | None = None, + new_setup_url: str | None = None, + plugin_manifests: list[PluginManifest] | None = None ) -> None: Gtk.ListBoxRow.__init__(self) diff --git a/gajim/gtk/application.py b/gajim/gtk/application.py index 45289999b..8b0479370 100644 --- a/gajim/gtk/application.py +++ b/gajim/gtk/application.py @@ -38,7 +38,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional import os import sys @@ -599,12 +598,12 @@ class GajimApplication(Gtk.Application, CoreApplication): @staticmethod def _on_preferences_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('Preferences') @staticmethod def _on_plugins_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('PluginsWindow') @staticmethod @@ -623,7 +622,7 @@ class GajimApplication(Gtk.Application, CoreApplication): @staticmethod def _on_quit_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: app.window.quit() @staticmethod @@ -675,7 +674,7 @@ class GajimApplication(Gtk.Application, CoreApplication): @staticmethod def _on_add_account_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('AccountWizard') @staticmethod @@ -721,22 +720,22 @@ class GajimApplication(Gtk.Application, CoreApplication): @staticmethod def _on_xml_console_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('XMLConsoleWindow') @staticmethod def _on_manage_proxies_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('ManageProxies') @staticmethod def _on_content_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_uri(GAJIM_WIKI_URI) @staticmethod def _on_join_support_chat(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: accounts = app.settings.get_active_accounts() if len(accounts) == 1: app.window.show_add_join_groupchat( @@ -746,32 +745,32 @@ class GajimApplication(Gtk.Application, CoreApplication): @staticmethod def _on_faq_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_uri(GAJIM_FAQ_URI) @staticmethod def _on_privacy_policy_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_uri(GAJIM_PRIVACY_POLICY_URI) @staticmethod def _on_shortcuts_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: ShortcutsWindow() @staticmethod def _on_features_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: open_window('Features') @staticmethod def _on_about_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: AboutDialog() @staticmethod def _on_file_transfer_action(_action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> None: + _param: GLib.Variant | None) -> None: ft = app.interface.instances['file_transfers'] if ft.window.get_property('visible'): diff --git a/gajim/gtk/assistant.py b/gajim/gtk/assistant.py index 0d927cac0..c756fbdf4 100644 --- a/gajim/gtk/assistant.py +++ b/gajim/gtk/assistant.py @@ -18,7 +18,6 @@ from typing import Any from typing import Callable from typing import cast from typing import Literal -from typing import Optional from typing import overload from gi.repository import Gdk @@ -46,7 +45,7 @@ class Assistant(Gtk.ApplicationWindow, EventHelper): )} def __init__(self, - transient_for: Optional[Gtk.Window] = None, + transient_for: Gtk.Window | None = None, width: int = 550, height: int = 400, transition_duration: int = 200) -> None: @@ -134,7 +133,7 @@ class Assistant(Gtk.ApplicationWindow, EventHelper): def add_button(self, name: str, label: str, - css_class: Optional[str] = None, + css_class: str | None = None, complete: bool = False ) -> None: button = Gtk.Button(label=label, @@ -227,10 +226,10 @@ class Page(Gtk.Box): self.title: str = '' self.complete: bool = True - def get_visible_buttons(self) -> Optional[list[str]]: + def get_visible_buttons(self) -> list[str] | None: return None - def get_default_button(self) -> Optional[str]: + def get_default_button(self) -> str | None: return None def update_page_complete(self) -> None: diff --git a/gajim/gtk/avatar.py b/gajim/gtk/avatar.py index d3d152d26..c9b722fb1 100644 --- a/gajim/gtk/avatar.py +++ b/gajim/gtk/avatar.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import functools import hashlib import logging @@ -53,7 +50,7 @@ from gajim.gtk.util import scale_with_ratio log = logging.getLogger('gajim.gtk.avatar') -AvatarCacheT = dict[Union[JID, str], dict[tuple[int, int, Optional[str]], +AvatarCacheT = dict[JID | str, dict[tuple[int, int, str | None], cairo.ImageSurface]] @@ -186,7 +183,7 @@ def add_status_to_avatar(surface: cairo.ImageSurface, @functools.lru_cache(maxsize=128) -def get_show_circle(show: Union[str, types.PresenceShowT], +def get_show_circle(show: str | types.PresenceShowT, size: int, scale: int ) -> cairo.ImageSurface: @@ -347,19 +344,19 @@ class AvatarStorage(metaclass=Singleton): def __init__(self): self._cache: AvatarCacheT = defaultdict(dict) - def invalidate_cache(self, jid: Union[JID, str]) -> None: + def invalidate_cache(self, jid: JID | str) -> None: self._cache.pop(jid, None) def get_pixbuf(self, - contact: Union[types.BareContact, - types.GroupchatContact, - types.GroupchatParticipant], + contact: (types.BareContact | + types.GroupchatContact | + types.GroupchatParticipant), size: int, scale: int, - show: Optional[str] = None, + show: str | None = None, default: bool = False, - transport_icon: Optional[str] = None, - style: str = 'circle') -> Optional[GdkPixbuf.Pixbuf]: + transport_icon: str | None = None, + style: str = 'circle') -> GdkPixbuf.Pixbuf | None: surface = self.get_surface( contact, size, scale, show, default, transport_icon, style) @@ -370,14 +367,14 @@ class AvatarStorage(metaclass=Singleton): size * scale) def get_surface(self, - contact: Union[types.BareContact, - types.GroupchatContact, - types.GroupchatParticipant], + contact: (types.BareContact | + types.GroupchatContact | + types.GroupchatParticipant), size: int, scale: int, - show: Optional[str] = None, + show: str | None = None, default: bool = False, - transport_icon: Optional[str] = None, + transport_icon: str | None = None, style: str = 'circle') -> cairo.ImageSurface: jid = contact.jid @@ -418,8 +415,8 @@ class AvatarStorage(metaclass=Singleton): size: int, scale: int, default: bool = False, - transport_icon: Optional[str] = None, - style: str = 'circle') -> Optional[cairo.ImageSurface]: + transport_icon: str | None = None, + style: str = 'circle') -> cairo.ImageSurface | None: if transport_icon is not None: surface = load_icon_surface(transport_icon, size, scale) @@ -457,7 +454,7 @@ class AvatarStorage(metaclass=Singleton): def get_workspace_surface(self, workspace_id: str, size: int, - scale: int) -> Optional[cairo.ImageSurface]: + scale: int) -> cairo.ImageSurface | None: surface = self._cache[workspace_id].get((size, scale, None)) if surface is not None: @@ -483,7 +480,7 @@ class AvatarStorage(metaclass=Singleton): return surface @staticmethod - def _load_for_publish(path: str) -> Optional[tuple[bool, bytes]]: + def _load_for_publish(path: str) -> tuple[bool, bytes] | None: pixbuf = load_pixbuf(path) if pixbuf is None: return None @@ -501,7 +498,7 @@ class AvatarStorage(metaclass=Singleton): return pixbuf.save_to_bufferv('png', [], []) @staticmethod - def save_avatar(data: bytes) -> Optional[str]: + def save_avatar(data: bytes) -> str | None: ''' Save an avatar to the harddisk @@ -521,7 +518,7 @@ class AvatarStorage(metaclass=Singleton): return sha @staticmethod - def get_avatar_path(filename: str) -> Optional[Path]: + def get_avatar_path(filename: str) -> Path | None: path = configpaths.get('AVATAR') / filename if not path.is_file(): return None @@ -533,7 +530,7 @@ class AvatarStorage(metaclass=Singleton): def surface_from_filename(self, filename: str, size: int, - scale: int) -> Optional[cairo.ImageSurface]: + scale: int) -> cairo.ImageSurface | None: size = size * scale path = self.get_avatar_path(filename) @@ -550,7 +547,7 @@ class AvatarStorage(metaclass=Singleton): def _load_surface_from_storage(self, filename: str, size: int, - scale: int) -> Optional[cairo.ImageSurface]: + scale: int) -> cairo.ImageSurface | None: size = size * scale path = self.get_avatar_path(filename) @@ -564,12 +561,12 @@ class AvatarStorage(metaclass=Singleton): return fit(surface, size) def _get_avatar_from_storage(self, - contact: Union[types.BareContact, - types.GroupchatContact, - types.GroupchatParticipant], + contact: (types.BareContact | + types.GroupchatContact | + types.GroupchatParticipant), size: int, scale: int, - style: str) -> Optional[cairo.ImageSurface]: + style: str) -> cairo.ImageSurface | None: avatar_sha = contact.avatar_sha if avatar_sha is None: diff --git a/gajim/gtk/avatar_selector.py b/gajim/gtk/avatar_selector.py index c75a6ab9c..9e46a479c 100644 --- a/gajim/gtk/avatar_selector.py +++ b/gajim/gtk/avatar_selector.py @@ -19,7 +19,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import logging from enum import IntEnum @@ -162,7 +161,7 @@ class AvatarSelector(Gtk.Box): self.prepare_crop_area(str(path)) @staticmethod - def _get_pixbuf_from_path(path: str) -> Optional[GdkPixbuf.Pixbuf]: + def _get_pixbuf_from_path(path: str) -> GdkPixbuf.Pixbuf | None: try: pixbuf = GdkPixbuf.Pixbuf.new_from_file(path) return pixbuf @@ -187,9 +186,7 @@ class AvatarSelector(Gtk.Box): return scaled_pixbuf, width, height return pixbuf, width, height - def get_avatar_surface(self) -> Optional[tuple[cairo.ImageSurface, - int, - int]]: + def get_avatar_surface(self) -> tuple[cairo.ImageSurface, int, int] | None: pixbuf = self._crop_area.get_pixbuf() if pixbuf is None: return None @@ -198,7 +195,7 @@ class AvatarSelector(Gtk.Box): return Gdk.cairo_surface_create_from_pixbuf( scaled, self.get_scale_factor()), width, height - def get_avatar_bytes(self) -> tuple[bool, Optional[bytes], int, int]: + def get_avatar_bytes(self) -> tuple[bool, bytes | None, int, int]: pixbuf = self._crop_area.get_pixbuf() if pixbuf is None: return False, None, 0, 0 @@ -219,10 +216,10 @@ class CropArea(Gtk.DrawingArea): self._image = Gdk.Rectangle() self._crop = Gdk.Rectangle() - self._pixbuf: Optional[GdkPixbuf.Pixbuf] = None - self._browse_pixbuf: Optional[GdkPixbuf.Pixbuf] = None - self._color_shifted_pixbuf: Optional[GdkPixbuf.Pixbuf] = None - self._current_cursor: Optional[Gdk.CursorType] = None + self._pixbuf: GdkPixbuf.Pixbuf | None = None + self._browse_pixbuf: GdkPixbuf.Pixbuf | None = None + self._color_shifted_pixbuf: GdkPixbuf.Pixbuf | None = None + self._current_cursor: Gdk.CursorType | None = None self._scale = 1.0 self._image.x = 0 @@ -257,7 +254,7 @@ class CropArea(Gtk.DrawingArea): else: self._aspect = -1 - def set_pixbuf(self, pixbuf: Optional[GdkPixbuf.Pixbuf]) -> None: + def set_pixbuf(self, pixbuf: GdkPixbuf.Pixbuf | None) -> None: if pixbuf is None: self._browse_pixbuf = None avatar_selector = cast(AvatarSelector, self.get_parent()) @@ -283,7 +280,7 @@ class CropArea(Gtk.DrawingArea): self.queue_draw() - def get_pixbuf(self) -> Optional[GdkPixbuf.Pixbuf]: + def get_pixbuf(self) -> GdkPixbuf.Pixbuf | None: if self._browse_pixbuf is None: return None diff --git a/gajim/gtk/builder.py b/gajim/gtk/builder.py index 0efdfc866..7ee75951f 100644 --- a/gajim/gtk/builder.py +++ b/gajim/gtk/builder.py @@ -13,7 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional import functools import sys @@ -32,10 +31,10 @@ class Builder: filename = '' def __init__(self, - filename: Optional[str] = None, - widgets: Optional[list[str]] = None, - domain: Optional[str] = None, - gettext_: Optional[Any] = None) -> None: + filename: str | None = None, + widgets: list[str] | None = None, + domain: str | None = None, + gettext_: Any | None = None) -> None: if filename is None: filename = self.filename @@ -86,5 +85,5 @@ class Builder: return self._builder.get_object(name) -def get_builder(file_name: str, widgets: Optional[list[str]] = None) -> Builder: +def get_builder(file_name: str, widgets: list[str] | None = None) -> Builder: return Builder(file_name, widgets) diff --git a/gajim/gtk/chat_action_processor.py b/gajim/gtk/chat_action_processor.py index 07c827868..64a4b1558 100644 --- a/gajim/gtk/chat_action_processor.py +++ b/gajim/gtk/chat_action_processor.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import logging @@ -52,8 +51,8 @@ class ChatActionProcessor(Gtk.Popover): self.connect('closed', self._on_popover_closed) self.connect('destroy', self._on_destroy) - self._account: Optional[str] = None - self._contact: Optional[types.ChatContactT] = None + self._account: str | None = None + self._contact: types.ChatContactT | None = None self._message_input = message_input self._message_input.connect('key-press-event', self._on_key_press) @@ -64,8 +63,8 @@ class ChatActionProcessor(Gtk.Popover): self._nick_completion = GroupChatNickCompletion() - self._start_mark: Optional[Gtk.TextMark] = None - self._current_iter: Optional[Gtk.TextIter] = None + self._start_mark: Gtk.TextMark | None = None + self._current_iter: Gtk.TextIter | None = None self._active = False diff --git a/gajim/gtk/chat_banner.py b/gajim/gtk/chat_banner.py index 01cc03776..db719e3c3 100644 --- a/gajim/gtk/chat_banner.py +++ b/gajim/gtk/chat_banner.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import cairo from gi.repository import Gdk @@ -53,8 +52,8 @@ class ChatBanner(Gtk.Box, EventHelper): Gtk.Box.__init__(self) EventHelper.__init__(self) - self._client: Optional[types.Client] = None - self._contact: Optional[types.ChatContactT] = None + self._client: types.Client | None = None + self._contact: types.ChatContactT | None = None self._last_message_from_phone: set[BareContact] = set() diff --git a/gajim/gtk/chat_function_page.py b/gajim/gtk/chat_function_page.py index a805fd14e..1c10b4745 100644 --- a/gajim/gtk/chat_function_page.py +++ b/gajim/gtk/chat_function_page.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from enum import Enum from pathlib import Path @@ -66,13 +64,13 @@ class ChatFunctionPage(Gtk.Box): self.set_valign(Gtk.Align.CENTER) self.get_style_context().add_class('padding-18') - self._client: Optional[types.Client] = None - self._contact: Optional[types.ChatContactT] = None - self._mode: Optional[FunctionMode] = None - self._data: Optional[str] = None + self._client: types.Client | None = None + self._contact: types.ChatContactT | None = None + self._mode: FunctionMode | None = None + self._data: str | None = None self._ready_state = True - self._widget: Optional[Gtk.Widget] = None + self._widget: Gtk.Widget | None = None self._heading = Gtk.Label() self._heading.set_max_width_chars(30) @@ -136,8 +134,8 @@ class ChatFunctionPage(Gtk.Box): def set_mode(self, contact: types.ChatContactT, mode: FunctionMode, - data: Optional[str] = None, - files: Optional[list[str]] = None + data: str | None = None, + files: list[str] | None = None ) -> None: self._reset() @@ -392,7 +390,7 @@ class InputWidget(Gtk.Box): def __init__(self, contact: types.ChatContactT, mode: FunctionMode, - data: Optional[str] = None + data: str | None = None ) -> None: Gtk.Box.__init__(self, @@ -468,8 +466,8 @@ class InputWidget(Gtk.Box): class ErrorWidget(Gtk.Box): def __init__(self, - mode: Optional[FunctionMode] = None, - error_text: Optional[str] = None + mode: FunctionMode | None = None, + error_text: str | None = None ) -> None: Gtk.Box.__init__(self, diff --git a/gajim/gtk/chat_list.py b/gajim/gtk/chat_list.py index 846e17e93..815b65aa7 100644 --- a/gajim/gtk/chat_list.py +++ b/gajim/gtk/chat_list.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import logging import time @@ -43,9 +41,9 @@ from gajim.gtk.util import EventHelper log = logging.getLogger('gajim.gtk.chatlist') -MessageEventT = Union[events.MessageReceived, - events.GcMessageReceived, - events.MamMessageReceived] +MessageEventT = (events.MessageReceived | + events.GcMessageReceived | + events.MamMessageReceived) class ChatList(Gtk.ListBox, EventHelper): @@ -88,7 +86,7 @@ class ChatList(Gtk.ListBox, EventHelper): entries, Gdk.DragAction.MOVE) - self._drag_row: Optional[ChatListRow] = None + self._drag_row: ChatListRow | None = None self._chat_order: list[ChatListRow] = [] self.register_events([ @@ -115,7 +113,7 @@ class ChatList(Gtk.ListBox, EventHelper): account: str, jid: JID, include_silent: bool = False - ) -> Optional[int]: + ) -> int | None: chat = self._chats.get((account, jid)) if chat is not None: if include_silent: @@ -140,13 +138,13 @@ class ChatList(Gtk.ListBox, EventHelper): self._current_filter_text = text self.invalidate_filter() - def get_chat_type(self, account: str, jid: JID) -> Optional[str]: + def get_chat_type(self, account: str, jid: JID) -> str | None: row = self._chats.get((account, jid)) if row is not None: return row.type return None - def get_selected_chat(self) -> Optional[ChatListRow]: + def get_selected_chat(self) -> ChatListRow | None: row = cast(ChatListRow | None, self.get_selected_row()) if row is None: return None @@ -352,13 +350,13 @@ class ChatList(Gtk.ListBox, EventHelper): self._workspace_id, count) - def _get_row_before(self, row: ChatListRow) -> Optional[ChatListRow]: + def _get_row_before(self, row: ChatListRow) -> ChatListRow | None: row_before = self.get_row_at_index(row.get_index() - 1) if row_before is None: return return cast(ChatListRow, row_before) - def _get_row_after(self, row: ChatListRow) -> Optional[ChatListRow]: + def _get_row_after(self, row: ChatListRow) -> ChatListRow | None: row_after = self.get_row_at_index(row.get_index() + 1) if row_after is None: return @@ -435,7 +433,7 @@ class ChatList(Gtk.ListBox, EventHelper): self._change_pinned_order(row_before) - def _change_pinned_order(self, row_before: Optional[ChatListRow]) -> None: + def _change_pinned_order(self, row_before: ChatListRow | None) -> None: assert self._drag_row is not None self._chat_order.remove(self._drag_row) diff --git a/gajim/gtk/chat_list_row.py b/gajim/gtk/chat_list_row.py index 19f81f270..51e529ea9 100644 --- a/gajim/gtk/chat_list_row.py +++ b/gajim/gtk/chat_list_row.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import pickle from datetime import datetime @@ -96,8 +95,8 @@ class ChatListRow(Gtk.ListBoxRow): self.contact_name: str = self.contact.name self.timestamp: float = 0 - self.stanza_id: Optional[str] = None - self.message_id: Optional[str] = None + self.stanza_id: str | None = None + self.message_id: str | None = None self._unread_count: int = 0 self._needs_muc_highlight: bool = False @@ -224,14 +223,14 @@ class ChatListRow(Gtk.ListBoxRow): self._update_unread() self.emit('unread-changed') - def get_header_type(self) -> Optional[RowHeaderType]: + def get_header_type(self) -> RowHeaderType | None: header = self.get_header() if header is None: return None assert isinstance(header, RowHeader) return header.type - def set_header_type(self, header_type: Optional[RowHeaderType]) -> None: + def set_header_type(self, header_type: RowHeaderType | None) -> None: if header_type == self.get_header_type(): return @@ -256,9 +255,9 @@ class ChatListRow(Gtk.ListBoxRow): def set_message_text(self, text: str, - nickname: Optional[str] = None, - icon_name: Optional[str] = None, - additional_data: Optional[AdditionalDataDict] = None + nickname: str | None = None, + icon_name: str | None = None, + additional_data: AdditionalDataDict | None = None ) -> None: draft = app.storage.drafts.get(self.contact) diff --git a/gajim/gtk/chat_list_stack.py b/gajim/gtk/chat_list_stack.py index 388b2a2d3..72b34b1c0 100644 --- a/gajim/gtk/chat_list_stack.py +++ b/gajim/gtk/chat_list_stack.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import cast -from typing import Optional from gi.repository import Gio from gi.repository import GLib @@ -118,13 +117,13 @@ class ChatListStack(Gtk.Stack, EventHelper): def get_chatlist(self, workspace_id: str) -> ChatList: return self._chat_lists[workspace_id] - def get_selected_chat(self) -> Optional[ChatListRow]: + def get_selected_chat(self) -> ChatListRow | None: chat_list = self.get_current_chat_list() if chat_list is None: return None return chat_list.get_selected_chat() - def get_current_chat_list(self) -> Optional[ChatList]: + def get_current_chat_list(self) -> ChatList | None: workspace_id = self.get_visible_child_name() if workspace_id == 'empty' or workspace_id is None: return None @@ -167,7 +166,7 @@ class ChatListStack(Gtk.Stack, EventHelper): def _on_row_selected(self, _chat_list: ChatList, - row: Optional[ChatListRow] + row: ChatListRow | None ) -> None: if row is None: self.emit('chat-unselected') @@ -300,14 +299,14 @@ class ChatListStack(Gtk.Stack, EventHelper): chat_list.remove_chats_for_account(account) self.store_open_chats(workspace_id) - def find_chat(self, account: str, jid: JID) -> Optional[ChatList]: + def find_chat(self, account: str, jid: JID) -> ChatList | None: for chat_list in self._chat_lists.values(): if chat_list.contains_chat(account, jid): return chat_list return None def contains_chat(self, account: str, jid: JID, - workspace_id: Optional[str] = None) -> bool: + workspace_id: str | None = None) -> bool: if workspace_id is None: return any(chat_list.contains_chat(account, jid) for chat_list in self._chat_lists.values()) @@ -325,7 +324,7 @@ class ChatListStack(Gtk.Stack, EventHelper): account: str, jid: JID, include_silent: bool = False - ) -> Optional[int]: + ) -> int | None: for chat_list in self._chat_lists.values(): count = chat_list.get_chat_unread_count( account, jid, include_silent) diff --git a/gajim/gtk/chat_page.py b/gajim/gtk/chat_page.py index 87e83dd29..baf0dbb86 100644 --- a/gajim/gtk/chat_page.py +++ b/gajim/gtk/chat_page.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Literal -from typing import Optional from typing import TYPE_CHECKING import logging @@ -227,7 +226,7 @@ class ChatPage(Gtk.Box): pinned: bool = False, position: int = -1, select: bool = False, - message: Optional[str] = None) -> None: + message: str | None = None) -> None: client = app.get_client(account) diff --git a/gajim/gtk/chat_stack.py b/gajim/gtk/chat_stack.py index 9f85ff936..5b4f75875 100644 --- a/gajim/gtk/chat_stack.py +++ b/gajim/gtk/chat_stack.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import logging import sys import time @@ -67,7 +64,7 @@ class ChatStack(Gtk.Stack, EventHelper): self.set_vexpand(True) self.set_hexpand(True) - self._current_contact: Optional[ChatContactT] = None + self._current_contact: ChatContactT | None = None self.add_named(ChatPlaceholderBox(), 'empty') @@ -349,10 +346,10 @@ class ChatStack(Gtk.Stack, EventHelper): self._update_group_chat_actions(self._current_contact) - def _on_account_state(self, - event: Union[events.AccountConnected, - events.AccountDisconnected] - ) -> None: + def _on_account_state( + self, + event: events.AccountConnected | events.AccountDisconnected + ) -> None: if self._current_contact is None: return @@ -410,7 +407,7 @@ class ChatStack(Gtk.Stack, EventHelper): _icon, file_type = preview_helpers.guess_simple_file_type(text) text = f'{file_type} ({file_name})' - sound: Optional[str] = None + sound: str | None = None msg_type = 'chat-message' if isinstance(contact, BareContact): msg_type = 'chat-message' @@ -554,7 +551,7 @@ class ChatStack(Gtk.Stack, EventHelper): def _on_action(self, action: Gio.SimpleAction, - param: Optional[GLib.Variant]) -> None: + param: GLib.Variant | None) -> None: action_name = action.get_name() contact = self._current_contact @@ -697,8 +694,8 @@ class ChatStack(Gtk.Stack, EventHelper): def _show_chat_function_page(self, function_mode: FunctionMode, - data: Optional[str] = None, - files: Optional[list[str]] = None + data: str | None = None, + files: list[str] | None = None ) -> None: assert self._current_contact is not None @@ -790,7 +787,7 @@ class ChatStack(Gtk.Stack, EventHelper): self._message_action_box.msg_textview.clear() app.storage.drafts.set(contact, '') - def get_last_message_id(self, contact: ChatContactT) -> Optional[str]: + def get_last_message_id(self, contact: ChatContactT) -> str | None: return self._message_action_box.get_last_message_id(contact) def _close_control(self) -> None: diff --git a/gajim/gtk/component_search.py b/gajim/gtk/component_search.py index bfb2e46fc..8ce3493eb 100644 --- a/gajim/gtk/component_search.py +++ b/gajim/gtk/component_search.py @@ -19,9 +19,7 @@ from __future__ import annotations from typing import Any from typing import cast from typing import Literal -from typing import Optional from typing import overload -from typing import Union import itertools import logging @@ -54,7 +52,7 @@ class ComponentSearch(Assistant, EventHelper): def __init__(self, account: str, jid: str, - transient_for: Optional[Gtk.Window] = None + transient_for: Gtk.Window | None = None ) -> None: Assistant.__init__(self, transient_for=transient_for, @@ -186,7 +184,7 @@ class SearchForm(Page): def process_search_form(self, form: Node) -> None: self._show_form(form) - def _show_form(self, form: Optional[Node]) -> None: + def _show_form(self, form: Node | None) -> None: if self._dataform_widget is not None: self.remove(self._dataform_widget) self._dataform_widget.destroy() @@ -225,7 +223,7 @@ class Result(Page): Page.__init__(self) self.title = _('Search Result') - self._jid_col: Optional[int] = None + self._jid_col: int | None = None self._label = Gtk.Label(label=_('No results found')) self._label.get_style_context().add_class('bold16') @@ -240,11 +238,11 @@ class Result(Page): self.add(self._label) self.add(self._scrolled) - self._treeview: Optional[Gtk.TreeView] = None + self._treeview: Gtk.TreeView | None = None self.show_all() - def process_result(self, form: Optional[Node]) -> None: + def process_result(self, form: Node | None) -> None: if self._treeview is not None: self._scrolled.remove(self._treeview) self._treeview.destroy() @@ -258,7 +256,7 @@ class Result(Page): form = dataforms.extend_form(node=form) - fieldtypes: list[Union[type[bool], type[str]]] = [] + fieldtypes: list[type[bool] | type[str]] = [] fieldvars: list[Any] = [] index = 0 for field in form.reported.iter_fields(): diff --git a/gajim/gtk/const.py b/gajim/gtk/const.py index 9aac4d12d..d9be59561 100644 --- a/gajim/gtk/const.py +++ b/gajim/gtk/const.py @@ -20,8 +20,6 @@ from typing import Any from typing import Callable from typing import Iterator from typing import NamedTuple -from typing import Optional -from typing import Union from enum import Enum from enum import IntEnum @@ -33,7 +31,7 @@ from gajim.common.setting_values import AllSettingsT class Filter(NamedTuple): name: str - pattern: Union[str, list[str]] + pattern: str | list[str] default: bool @@ -41,15 +39,15 @@ class Setting(NamedTuple): kind: SettingKind label: str type: SettingType - value: Optional[AllSettingsT] = None - name: Optional[str] = None - callback: Optional[Callable[..., None]] = None - data: Optional[Any] = None - desc: Optional[str] = None - bind: Optional[str] = None - inverted: Optional[bool] = None - enabled_func: Optional[Callable[..., bool]] = None - props: Optional[dict[str, Any]] = None + value: AllSettingsT | None = None + name: str | None = None + callback: Callable[..., None] | None = None + data: Any | None = None + desc: str | None = None + bind: str | None = None + inverted: bool | None = None + enabled_func: Callable[..., bool] | None = None + props: dict[str, Any] | None = None DEFAULT_WORKSPACE_COLOR = 'rgb(191,15,167)' diff --git a/gajim/gtk/contact_info.py b/gajim/gtk/contact_info.py index 885a31bcf..37345acc4 100644 --- a/gajim/gtk/contact_info.py +++ b/gajim/gtk/contact_info.py @@ -15,8 +15,6 @@ from __future__ import annotations from typing import cast -from typing import Optional -from typing import Union import logging from enum import IntEnum @@ -60,7 +58,7 @@ from gajim.gtk.vcard_grid import VCardGrid log = logging.getLogger('gajim.gtk.contact_info') -ContactT = Union[BareContact, GroupchatParticipant] +ContactT = BareContact | GroupchatParticipant class Column(IntEnum): @@ -72,7 +70,7 @@ class ContactInfo(Gtk.ApplicationWindow, EventHelper): def __init__(self, account: str, contact: ContactT, - page: Optional[str] = None) -> None: + page: str | None = None) -> None: Gtk.ApplicationWindow.__init__(self) EventHelper.__init__(self) @@ -539,7 +537,7 @@ class DeviceGrid: def widget(self) -> Gtk.Grid: return self._ui.devices_grid - def set_entity_time(self, entity_time: Optional[str]) -> None: + def set_entity_time(self, entity_time: str | None) -> None: if entity_time is not None: self._ui.time_value.set_text(entity_time) self._ui.time_value.show() @@ -547,7 +545,7 @@ class DeviceGrid: self._check_complete() - def set_software(self, software: Optional[SoftwareVersionResult]) -> None: + def set_software(self, software: SoftwareVersionResult | None) -> None: if software is not None: software_string = f'{software.name} {software.version}' self._ui.software_value.set_text(software_string) diff --git a/gajim/gtk/control.py b/gajim/gtk/control.py index e704a472d..894c85b67 100644 --- a/gajim/gtk/control.py +++ b/gajim/gtk/control.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import logging import time @@ -54,7 +52,7 @@ from gajim.gtk.conversation.view import ConversationView from gajim.gtk.groupchat_roster import GroupchatRoster from gajim.gtk.groupchat_state import GroupchatState -HistoryRowT = Union[events.ApplicationEvent, ConversationRow] +HistoryRowT = events.ApplicationEvent | ConversationRow REQUEST_LINES_COUNT = 20 @@ -147,9 +145,10 @@ class ChatControl(EventHelper): self._roster.clear() self.unregister_events() - def switch_contact(self, contact: Union[BareContact, - GroupchatContact, - GroupchatParticipant]) -> None: + def switch_contact( + self, + contact: BareContact | GroupchatContact | GroupchatParticipant + ) -> None: log.info('Switch to %s (%s)', contact.jid, contact.account) if self._contact is not None: @@ -431,10 +430,10 @@ class ChatControl(EventHelper): if active_jid is None: self.add_call_message(event=event) - def _on_file_request_event(self, - event: Union[events.FileRequestReceivedEvent, - events.FileRequestSent] - ) -> None: + def _on_file_request_event( + self, + event: events.FileRequestReceivedEvent | events.FileRequestSent + ) -> None: if not self._is_event_processable(event): return @@ -522,7 +521,7 @@ class ChatControl(EventHelper): def add_info_message(self, text: str, - timestamp: Optional[float] = None + timestamp: float | None = None ) -> None: self._scrolled_view.add_info_message(text, timestamp) @@ -530,12 +529,10 @@ class ChatControl(EventHelper): def add_file_transfer(self, transfer: HTTPFileTransfer) -> None: self._scrolled_view.add_file_transfer(transfer) - def add_jingle_file_transfer(self, - event: Union[ - events.FileRequestReceivedEvent, - events.FileRequestSent, - None] - ) -> None: + def add_jingle_file_transfer( + self, + event: events.FileRequestReceivedEvent | events.FileRequestSent | None + ) -> None: if self._allow_add_message(): self._scrolled_view.add_jingle_file_transfer(event) @@ -548,11 +545,11 @@ class ChatControl(EventHelper): kind: str, name: str, tim: float, - displaymarking: Optional[Displaymarking] = None, - msg_log_id: Optional[int] = None, - message_id: Optional[str] = None, - stanza_id: Optional[str] = None, - additional_data: Optional[AdditionalDataDict] = None + displaymarking: Displaymarking | None = None, + msg_log_id: int | None = None, + message_id: str | None = None, + stanza_id: str | None = None, + additional_data: AdditionalDataDict | None = None ) -> None: if additional_data is None: @@ -777,11 +774,11 @@ class ChatControl(EventHelper): text: str, kind: str, tim: float, - displaymarking: Optional[Displaymarking] = None, - msg_log_id: Optional[int] = None, - stanza_id: Optional[str] = None, - message_id: Optional[str] = None, - additional_data: Optional[AdditionalDataDict] = None + displaymarking: Displaymarking | None = None, + msg_log_id: int | None = None, + stanza_id: str | None = None, + message_id: str | None = None, + additional_data: AdditionalDataDict | None = None ) -> None: if kind == 'incoming': @@ -1204,11 +1201,11 @@ class ChatControl(EventHelper): text: str, tim: float, contact: str = '', - displaymarking: Optional[Displaymarking] = None, - message_id: Optional[str] = None, - stanza_id: Optional[str] = None, - msg_log_id: Optional[int] = None, - additional_data: Optional[AdditionalDataDict] = None, + displaymarking: Displaymarking | None = None, + message_id: str | None = None, + stanza_id: str | None = None, + msg_log_id: int | None = None, + additional_data: AdditionalDataDict | None = None, ) -> None: assert isinstance(self._contact, GroupchatContact) diff --git a/gajim/gtk/conversation/code_widget.py b/gajim/gtk/conversation/code_widget.py index c32e85ab2..35ca4d6be 100644 --- a/gajim/gtk/conversation/code_widget.py +++ b/gajim/gtk/conversation/code_widget.py @@ -13,7 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional import logging @@ -81,7 +80,7 @@ class CodeWidget(Gtk.Box): self._textview.print_code(code) @staticmethod - def _prepare_code(text: str) -> tuple[str, Optional[str]]: + def _prepare_code(text: str) -> tuple[str, str | None]: text = text.strip() code_start = text.partition('\n')[0] lang = None diff --git a/gajim/gtk/conversation/jump_to_end_button.py b/gajim/gtk/conversation/jump_to_end_button.py index 123b53741..a59b784e0 100644 --- a/gajim/gtk/conversation/jump_to_end_button.py +++ b/gajim/gtk/conversation/jump_to_end_button.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Union - from gi.repository import GObject from gi.repository import Gtk @@ -23,7 +21,7 @@ from gajim.common.modules.contacts import BareContact from gajim.common.modules.contacts import GroupchatContact from gajim.common.modules.contacts import GroupchatParticipant -ContactT = Union[BareContact, GroupchatContact, GroupchatParticipant] +ContactT = BareContact | GroupchatContact | GroupchatParticipant class JumpToEndButton(Gtk.Overlay): diff --git a/gajim/gtk/conversation/message_widget.py b/gajim/gtk/conversation/message_widget.py index b376c555b..bdac08e3a 100644 --- a/gajim/gtk/conversation/message_widget.py +++ b/gajim/gtk/conversation/message_widget.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - from gi.repository import Gdk from gi.repository import Gtk @@ -32,7 +29,7 @@ from gajim.gtk.conversation.code_widget import CodeWidget from gajim.gtk.conversation.plain_widget import PlainWidget from gajim.gtk.conversation.quote_widget import QuoteWidget -ContentT = Union[ParsingResult, QuoteBlock] +ContentT = ParsingResult | QuoteBlock class MessageWidget(Gtk.Box): @@ -60,7 +57,7 @@ class MessageWidget(Gtk.Box): def add_with_styling(self, text: str, - nickname: Optional[str] = None) -> None: + nickname: str | None = None) -> None: self._original_text = text if len(text) > MAX_MESSAGE_LENGTH: diff --git a/gajim/gtk/conversation/rows/base.py b/gajim/gtk/conversation/rows/base.py index 711828a44..b7a3f26dc 100644 --- a/gajim/gtk/conversation/rows/base.py +++ b/gajim/gtk/conversation/rows/base.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from datetime import datetime from gi.repository import Gtk @@ -25,7 +23,7 @@ from gajim.common import app class BaseRow(Gtk.ListBoxRow): - def __init__(self, account: str, widget: Optional[str] = None) -> None: + def __init__(self, account: str, widget: str | None = None) -> None: Gtk.ListBoxRow.__init__(self) self._account = account self._client = app.get_client(account) @@ -33,9 +31,9 @@ class BaseRow(Gtk.ListBoxRow): self.timestamp: datetime = datetime.fromtimestamp(0) self.kind: str = '' self.name: str = '' - self.message_id: Optional[str] = None - self.log_line_id: Optional[int] = None - self.stanza_id: Optional[str] = None + self.message_id: str | None = None + self.log_line_id: int | None = None + self.stanza_id: str | None = None self.text: str = '' self._merged: bool = False diff --git a/gajim/gtk/conversation/rows/call.py b/gajim/gtk/conversation/rows/call.py index 8e899cabc..feb06a601 100644 --- a/gajim/gtk/conversation/rows/call.py +++ b/gajim/gtk/conversation/rows/call.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import time from datetime import datetime @@ -41,8 +39,8 @@ class CallRow(BaseRow): def __init__(self, account: str, contact: types.BareContact, - event: Optional[JingleRequestReceived] = None, - db_message: Optional[ConversationRow] = None + event: JingleRequestReceived | None = None, + db_message: ConversationRow | None = None ) -> None: BaseRow.__init__(self, account) @@ -61,7 +59,7 @@ class CallRow(BaseRow): self._event = event self._db_message = db_message - self._session: Optional[JingleSession] = None + self._session: JingleSession | None = None if db_message is not None: assert db_message.additional_data is not None diff --git a/gajim/gtk/conversation/rows/file_transfer_jingle.py b/gajim/gtk/conversation/rows/file_transfer_jingle.py index 9835d902f..23f16dd0a 100644 --- a/gajim/gtk/conversation/rows/file_transfer_jingle.py +++ b/gajim/gtk/conversation/rows/file_transfer_jingle.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import logging import time from datetime import datetime @@ -54,7 +51,7 @@ from gajim.gtk.conversation.rows.widgets import DateTimeLabel from gajim.gtk.conversation.rows.widgets import NicknameLabel from gajim.gtk.util import format_eta -TransferEventT = Union[FileRequestReceivedEvent, FileRequestSent] +TransferEventT = FileRequestReceivedEvent | FileRequestSent log = logging.getLogger('gajim.gtk.conversation.rows.file_transfer_jingle') @@ -63,8 +60,8 @@ class FileTransferJingleRow(BaseRow): def __init__(self, account: str, contact: BareContact, - event: Optional[TransferEventT] = None, - db_message: Optional[ConversationRow] = None + event: TransferEventT | None = None, + db_message: ConversationRow | None = None ) -> None: BaseRow.__init__(self, account) diff --git a/gajim/gtk/conversation/rows/info.py b/gajim/gtk/conversation/rows/info.py index 67c7aee9b..339e9623d 100644 --- a/gajim/gtk/conversation/rows/info.py +++ b/gajim/gtk/conversation/rows/info.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import time from datetime import datetime @@ -32,7 +30,7 @@ class InfoMessage(BaseRow): def __init__(self, account: str, text: str, - timestamp: Optional[float] + timestamp: float | None ) -> None: BaseRow.__init__(self, account) diff --git a/gajim/gtk/conversation/rows/message.py b/gajim/gtk/conversation/rows/message.py index 0e5ec9954..7da97009a 100644 --- a/gajim/gtk/conversation/rows/message.py +++ b/gajim/gtk/conversation/rows/message.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import textwrap from datetime import datetime from datetime import timedelta @@ -63,17 +60,17 @@ class MessageRow(BaseRow): def __init__(self, account: str, contact: ChatContactT, - message_id: Optional[str], - stanza_id: Optional[str], + message_id: str | None, + stanza_id: str | None, timestamp: float, kind: str, name: str, text: str, - additional_data: Optional[AdditionalDataDict] = None, - display_marking: Optional[Displaymarking] = None, - marker: Optional[str] = None, - error: Union[CommonError, StanzaError, None] = None, - log_line_id: Optional[int] = None) -> None: + additional_data: AdditionalDataDict | None = None, + display_marking: Displaymarking | None = None, + marker: str | None = None, + error: CommonError | StanzaError | None = None, + log_line_id: int | None = None) -> None: BaseRow.__init__(self, account) self.type = 'chat' @@ -219,7 +216,7 @@ class MessageRow(BaseRow): self._message_widget.set_selectable(True) def _add_security_label(self, - display_marking: Optional[Displaymarking] + display_marking: Displaymarking | None ) -> None: if display_marking is None: @@ -256,7 +253,7 @@ class MessageRow(BaseRow): self.get_style_context().add_class( 'gajim-mention-highlight') - def _get_avatar(self, kind: str, name: str) -> Optional[cairo.ImageSurface]: + def _get_avatar(self, kind: str, name: str) -> cairo.ImageSurface | None: scale = self.get_scale_factor() if isinstance(self._contact, GroupchatContact): contact = self._contact.get_resource(name) @@ -321,7 +318,7 @@ class MessageRow(BaseRow): def _get_encryption_image(self, additional_data: AdditionalDataDict, - ) -> Optional[Gtk.Image]: + ) -> Gtk.Image | None: details = self._get_encryption_details(additional_data) if details is None: @@ -352,9 +349,10 @@ class MessageRow(BaseRow): return image @staticmethod - def _get_encryption_details(additional_data: AdditionalDataDict - ) -> Optional[tuple[ - str, Optional[str], Optional[Trust]]]: + def _get_encryption_details( + additional_data: AdditionalDataDict + ) -> tuple[str, str | None, Trust | None] | None: + name = additional_data.get_value('encrypted', 'name') if name is None: return None @@ -396,7 +394,7 @@ class MessageRow(BaseRow): self._message_widget.add_with_styling(text) self.get_style_context().add_class('retracted-message') - def set_correction(self, text: str, nickname: Optional[str]) -> None: + def set_correction(self, text: str, nickname: str | None) -> None: if not isinstance(self._message_widget, PreviewWidget): self._message_widget.add_with_styling(text, nickname) diff --git a/gajim/gtk/conversation/rows/muc_join_left.py b/gajim/gtk/conversation/rows/muc_join_left.py index b03a4ac2d..fc689e275 100644 --- a/gajim/gtk/conversation/rows/muc_join_left.py +++ b/gajim/gtk/conversation/rows/muc_join_left.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional import time from datetime import datetime @@ -32,9 +31,9 @@ class MUCJoinLeft(BaseRow): type_: str, account: str, nick: str, - reason: Optional[str] = None, + reason: str | None = None, error: bool = False, - timestamp: Optional[float] = None + timestamp: float | None = None ) -> None: BaseRow.__init__(self, account) @@ -74,7 +73,7 @@ class MUCJoinLeft(BaseRow): self.show_all() @staticmethod - def _make_left_message(nick: str, reason: Optional[str], + def _make_left_message(nick: str, reason: str | None, error: bool) -> str: reason = '' if reason is None else f': {reason}' diff --git a/gajim/gtk/conversation/rows/muc_subject.py b/gajim/gtk/conversation/rows/muc_subject.py index 584b12665..abeb17f19 100644 --- a/gajim/gtk/conversation/rows/muc_subject.py +++ b/gajim/gtk/conversation/rows/muc_subject.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import time from datetime import datetime @@ -37,7 +35,7 @@ class MUCSubject(BaseRow): def __init__(self, account: str, subject: MucSubject, - timestamp: Optional[float] = None + timestamp: float | None = None ) -> None: BaseRow.__init__(self, account) diff --git a/gajim/gtk/conversation/rows/user_status.py b/gajim/gtk/conversation/rows/user_status.py index af8d1a0fe..cf6169f0f 100644 --- a/gajim/gtk/conversation/rows/user_status.py +++ b/gajim/gtk/conversation/rows/user_status.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import time from datetime import datetime @@ -37,7 +35,7 @@ class UserStatus(BaseRow): account: str, name: str, show: str, - status: Optional[str]) -> None: + status: str | None) -> None: BaseRow.__init__(self, account) diff --git a/gajim/gtk/conversation/rows/widgets.py b/gajim/gtk/conversation/rows/widgets.py index b37af3d4b..ad48534aa 100644 --- a/gajim/gtk/conversation/rows/widgets.py +++ b/gajim/gtk/conversation/rows/widgets.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional from datetime import datetime @@ -150,7 +149,7 @@ class AvatarBox(Gtk.EventBox): def __init__(self, contact: ChatContactT, name: str, - avatar: Optional[cairo.ImageSurface], + avatar: cairo.ImageSurface | None, ) -> None: Gtk.EventBox.__init__(self) @@ -169,7 +168,7 @@ class AvatarBox(Gtk.EventBox): self.connect('button-press-event', self._on_avatar_clicked, name) - def set_from_surface(self, surface: Optional[cairo.ImageSurface]) -> None: + def set_from_surface(self, surface: cairo.ImageSurface | None) -> None: self._image.set_from_surface(surface) def set_merged(self, merged: bool) -> None: diff --git a/gajim/gtk/conversation/view.py b/gajim/gtk/conversation/view.py index e65566a97..6662a5a73 100644 --- a/gajim/gtk/conversation/view.py +++ b/gajim/gtk/conversation/view.py @@ -18,8 +18,6 @@ from typing import Any from typing import cast from typing import Generator from typing import Literal -from typing import Optional -from typing import Union import logging import time @@ -107,7 +105,7 @@ class ConversationView(Gtk.ScrolledWindow): self._list_box.set_selection_mode(Gtk.SelectionMode.NONE) self._list_box.set_sort_func(self._sort_func) - self._contact: Optional[ChatContactT] = None + self._contact: ChatContactT | None = None self._client = None # Keeps track of the number of rows shown in ConversationView @@ -125,10 +123,10 @@ class ConversationView(Gtk.ScrolledWindow): self._current_upper: float = 0 self._autoscroll: bool = True - self._request_history_at_upper: Optional[float] = None + self._request_history_at_upper: float | None = None self._upper_complete: bool = False self._lower_complete: bool = True - self._requesting: Optional[str] = None + self._requesting: str | None = None self._block_signals = False self._signal_handlers_enabled = False @@ -157,7 +155,7 @@ class ConversationView(Gtk.ScrolledWindow): self.disable_row_selection() def enable_row_selection(self, - log_line_id: Optional[int] + log_line_id: int | None ) -> None: self._list_box.set_selection_mode(Gtk.SelectionMode.MULTIPLE) @@ -376,13 +374,13 @@ class ConversationView(Gtk.ScrolledWindow): assert row is not None return cast(BaseRow, row) - def get_first_message_row(self) -> Optional[MessageRow]: + def get_first_message_row(self) -> MessageRow | None: for row in self._list_box.get_children(): if isinstance(row, MessageRow): return row return None - def get_last_message_row(self) -> Optional[MessageRow]: + def get_last_message_row(self) -> MessageRow | None: children = self._list_box.get_children() children.reverse() for row in children: @@ -390,13 +388,13 @@ class ConversationView(Gtk.ScrolledWindow): return row return None - def get_first_event_row(self) -> Optional[Union[InfoMessage, MUCJoinLeft]]: + def get_first_event_row(self) -> InfoMessage | MUCJoinLeft | None: for row in self._list_box.get_children(): if isinstance(row, (InfoMessage, MUCJoinLeft)): return row return None - def get_last_event_row(self) -> Optional[Union[InfoMessage, MUCJoinLeft]]: + def get_last_event_row(self) -> InfoMessage | MUCJoinLeft | None: children = self._list_box.get_children() children.reverse() for row in children: @@ -412,7 +410,7 @@ class ConversationView(Gtk.ScrolledWindow): def add_muc_subject(self, subject: MucSubject, - timestamp: Optional[float] = None + timestamp: float | None = None ) -> None: muc_subject = MUCSubject(self.contact.account, subject, timestamp) @@ -450,7 +448,7 @@ class ConversationView(Gtk.ScrolledWindow): def add_info_message(self, text: str, - timestamp: Optional[float] = None + timestamp: float | None = None ) -> None: message = InfoMessage(self.contact.account, text, timestamp) @@ -460,13 +458,13 @@ class ConversationView(Gtk.ScrolledWindow): transfer_row = FileTransferRow(self.contact.account, transfer) self._insert_message(transfer_row) - def add_jingle_file_transfer(self, - event: Union[ - events.FileRequestReceivedEvent, - events.FileRequestSent, - None] = None, - db_message: Optional[ConversationRow] = None - ) -> None: + def add_jingle_file_transfer( + self, + event: (events.FileRequestReceivedEvent | + events.FileRequestSent | + None) = None, + db_message: ConversationRow | None = None + ) -> None: assert isinstance(self._contact, BareContact) jingle_transfer_row = FileTransferJingleRow( @@ -481,8 +479,8 @@ class ConversationView(Gtk.ScrolledWindow): self._insert_message(EncryptionInfoRow(event)) def add_call_message(self, - event: Optional[events.JingleRequestReceived] = None, - db_message: Optional[ConversationRow] = None + event: events.JingleRequestReceived | None = None, + db_message: ConversationRow | None = None ) -> None: assert isinstance(self._contact, BareContact) call_row = CallRow( @@ -502,13 +500,13 @@ class ConversationView(Gtk.ScrolledWindow): kind: str, name: str, timestamp: float, - log_line_id: Optional[int] = None, - message_id: Optional[str] = None, - stanza_id: Optional[str] = None, - display_marking: Optional[Displaymarking] = None, - additional_data: Optional[AdditionalDataDict] = None, - marker: Optional[str] = None, - error: Union[CommonError, StanzaError, None] = None + log_line_id: int | None = None, + message_id: str | None = None, + stanza_id: str | None = None, + display_marking: Displaymarking | None = None, + additional_data: AdditionalDataDict | None = None, + marker: str | None = None, + error: CommonError | StanzaError | None = None ) -> None: if not timestamp: @@ -584,7 +582,7 @@ class ConversationView(Gtk.ScrolledWindow): if message.is_mergeable(ancestor): message.set_merged(True) - def _find_ancestor(self, message: MessageRow) -> Optional[MessageRow]: + def _find_ancestor(self, message: MessageRow) -> MessageRow | None: index = message.get_index() while index != 0: index -= 1 @@ -700,10 +698,10 @@ class ConversationView(Gtk.ScrolledWindow): adj = self.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size()) - def _get_row_by_message_id(self, id_: str) -> Optional[MessageRow]: + def _get_row_by_message_id(self, id_: str) -> MessageRow | None: return self._message_id_row_map.get(id_) - def get_row_by_log_line_id(self, log_line_id: int) -> Optional[MessageRow]: + def get_row_by_log_line_id(self, log_line_id: int) -> MessageRow | None: for row in cast(list[BaseRow], self._list_box.get_children()): if not isinstance(row, MessageRow): continue @@ -711,7 +709,7 @@ class ConversationView(Gtk.ScrolledWindow): return row return None - def get_row_by_stanza_id(self, stanza_id: str) -> Optional[MessageRow]: + def get_row_by_stanza_id(self, stanza_id: str) -> MessageRow | None: for row in cast(list[BaseRow], self._list_box.get_children()): if not isinstance(row, MessageRow): continue @@ -753,7 +751,7 @@ class ConversationView(Gtk.ScrolledWindow): def correct_message(self, correct_id: str, text: str, - nickname: Optional[str] + nickname: str | None ) -> None: message_row = self._get_row_by_message_id(correct_id) @@ -780,8 +778,8 @@ class ConversationView(Gtk.ScrolledWindow): def _on_contact_setting_changed(self, value: Any, setting: str, - _account: Optional[str], - _jid: Optional[JID]) -> None: + _account: str | None, + _jid: JID | None) -> None: if setting == 'print_join_left': if value: diff --git a/gajim/gtk/css_config.py b/gajim/gtk/css_config.py index a83b9d273..b7f78a89a 100644 --- a/gajim/gtk/css_config.py +++ b/gajim/gtk/css_config.py @@ -17,9 +17,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - import logging import math import sys @@ -84,17 +81,17 @@ class CSSConfig: css_parser.ser.prefs.keepEmptyRules = False # Holds the currently selected theme in the Theme Editor - self._pre_css: Optional[CSSStyleSheet] = None - self._pre_css_path: Optional[Path] = None + self._pre_css: CSSStyleSheet | None = None + self._pre_css_path: Path | None = None # Holds the default theme, its used if values are not found # in the selected theme - self._default_css: Optional[CSSStyleSheet] = None - self._default_css_path: Optional[Path] = None + self._default_css: CSSStyleSheet | None = None + self._default_css_path: Path | None = None # Holds the currently selected theme - self._css: Optional[CSSStyleSheet] = None - self._css_path: Optional[Path] = None + self._css: CSSStyleSheet | None = None + self._css_path: Path | None = None # User Theme CSS Provider self._provider = Gtk.CssProvider() @@ -112,7 +109,7 @@ class CSSConfig: CSSPriority.APPLICATION) # Cache of recently requested values - self._cache: dict[str, Union[str, Pango.FontDescription, None]] = {} + self._cache: dict[str, str | Pango.FontDescription | None] = {} # Holds all currently available themes self.themes: list[str] = [] @@ -145,7 +142,7 @@ class CSSConfig: return settings.get_property('gtk-application-prefer-dark-theme') return setting == Theme.DARK - def set_dark_theme(self, value: Optional[int] = None) -> None: + def set_dark_theme(self, value: int | None = None) -> None: if value is None: value = app.settings.get('dark_theme') else: @@ -256,7 +253,7 @@ class CSSConfig: log.info('Use Theme: %s', theme) return theme_path - def _load_selected(self, new_path: Optional[Path] = None) -> None: + def _load_selected(self, new_path: Path | None = None) -> None: if new_path is None: self._css_path = self._determine_theme_path() else: @@ -291,8 +288,8 @@ class CSSConfig: def set_value(self, selector: str, - attr: Union[str, StyleAttr], - value: Union[str, Pango.FontDescription], + attr: str | StyleAttr, + value: str | Pango.FontDescription, pre: bool = False ) -> None: @@ -369,7 +366,7 @@ class CSSConfig: def _get_attr_from_description(self, description: Pango.FontDescription - ) -> tuple[Optional[str], float, str, int]: + ) -> tuple[str | None, float, str, int]: size = description.get_size() / Pango.SCALE style = self._get_string_from_pango_style(description.get_style()) @@ -380,7 +377,7 @@ class CSSConfig: def _get_default_rule(self, selector: str, _attr: str - ) -> Optional[CSSStyleRule]: + ) -> CSSStyleRule | None: assert self._default_css is not None for rule in self._default_css: @@ -394,7 +391,7 @@ class CSSConfig: def get_font(self, selector: str, pre: bool = False - ) -> Optional[Pango.FontDescription]: + ) -> Pango.FontDescription | None: if pre: css = self._pre_css else: @@ -429,11 +426,11 @@ class CSSConfig: return None def _get_description_from_css(self, - family: Optional[str], - size: Optional[str], - style: Optional[str], - weight: Optional[str] - ) -> Optional[Pango.FontDescription]: + family: str | None, + size: str | None, + style: str | None, + weight: str | None + ) -> Pango.FontDescription | None: if family is None: return None @@ -467,9 +464,9 @@ class CSSConfig: def get_value(self, selector: str, - attr: Union[str, StyleAttr], + attr: str | StyleAttr, pre: bool = False - ) -> Union[str, Pango.FontDescription, None]: + ) -> str | Pango.FontDescription | None: if attr == StyleAttr.FONT: # forward to get_font() for convenience @@ -510,7 +507,7 @@ class CSSConfig: def remove_value(self, selector: str, - attr: Union[str, StyleAttr], + attr: str | StyleAttr, pre: bool = False ) -> None: @@ -622,7 +619,7 @@ class CSSConfig: def _add_to_cache(self, selector: str, attr: str, - value: Union[str, Pango.FontDescription, None] + value: str | Pango.FontDescription | None ) -> None: self._cache[selector + attr] = value @@ -630,7 +627,7 @@ class CSSConfig: def _get_from_cache(self, selector: str, attr: str - ) -> Union[str, Pango.FontDescription, None]: + ) -> str | Pango.FontDescription | None: return self._cache[selector + attr] diff --git a/gajim/gtk/dataform.py b/gajim/gtk/dataform.py index 348877ca1..f5b950ed0 100644 --- a/gajim/gtk/dataform.py +++ b/gajim/gtk/dataform.py @@ -17,8 +17,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional -from typing import Union from gi.repository import GLib from gi.repository import GObject @@ -57,8 +55,8 @@ class DataFormWidget(Gtk.ScrolledWindow): __gsignals__ = {'is-valid': (GObject.SignalFlags.RUN_LAST, None, (bool,))} def __init__(self, - form_node: Union[SimpleDataForm, MultipleDataForm], - options: Optional[dict[str, Any]] = None + form_node: SimpleDataForm | MultipleDataForm, + options: dict[str, Any] | None = None ) -> None: Gtk.ScrolledWindow.__init__(self) @@ -80,20 +78,20 @@ class DataFormWidget(Gtk.ScrolledWindow): self.add(self._form_grid) @property - def title(self) -> Optional[str]: + def title(self) -> str | None: return self._form_grid.title @property - def instructions(self) -> Optional[str]: + def instructions(self) -> str | None: return self._form_grid.instructions def validate(self) -> None: return self._form_grid.validate(True) - def get_form(self) -> Union[SimpleDataForm, MultipleDataForm]: + def get_form(self) -> SimpleDataForm | MultipleDataForm: return self._form_node - def get_submit_form(self) -> Union[SimpleDataForm, MultipleDataForm]: + def get_submit_form(self) -> SimpleDataForm | MultipleDataForm: self._form_node.type_ = 'submit' return self._form_node @@ -116,7 +114,7 @@ class DataFormWidget(Gtk.ScrolledWindow): class FormGrid(Gtk.Grid): def __init__(self, - form_node: Union[SimpleDataForm, MultipleDataForm], + form_node: SimpleDataForm | MultipleDataForm, options: dict[str, Any] ) -> None: @@ -126,19 +124,19 @@ class FormGrid(Gtk.Grid): self.set_halign(Gtk.Align.CENTER) self.row_count = 0 - self.rows: list[Union[SizeAdjustment, - Title, - Instructions, - Field, - ImageMediaField]] = [] + self.rows: list[(SizeAdjustment | + Title | + Instructions | + Field | + ImageMediaField)] = [] form_width = options.get('form-width', 435) self.set_size_request(form_width, -1) self._data_form = form_node - self.title: Optional[str] = None - self.instructions: Optional[str] = None + self.title: str | None = None + self.instructions: str | None = None self._fields = { 'boolean': BooleanField, @@ -164,20 +162,17 @@ class FormGrid(Gtk.Grid): self._analyse_fields(form_node, options) self._parse_form(form_node, options) - def _add_row(self, - field: Union[SizeAdjustment, - Title, - Instructions, - Field, - ImageMediaField] - ) -> None: + def _add_row( + self, + field: SizeAdjustment | Title | Instructions | Field | ImageMediaField + ) -> None: field.add(self, self.row_count) self.row_count += 1 self.rows.append(field) @staticmethod - def _analyse_fields(form_node: Union[SimpleDataForm, MultipleDataForm], + def _analyse_fields(form_node: SimpleDataForm | MultipleDataForm, options: dict[str, Any] ) -> None: @@ -198,7 +193,7 @@ class FormGrid(Gtk.Grid): options['right-align'] = max(label_lengths) < 30 def _parse_form(self, - form_node: Union[SimpleDataForm, MultipleDataForm], + form_node: SimpleDataForm | MultipleDataForm, options: dict[str, Any] ) -> None: @@ -292,10 +287,10 @@ class Field: options: dict[str, Any] ) -> None: - self._widget: Optional[Gtk.Widget] = None + self._widget: Gtk.Widget | None = None self._field = field self._form_grid = form_grid - self._validate_source_id: Optional[int] = None + self._validate_source_id: int | None = None self._read_only = options.get('read-only', False) self._label = Gtk.Label(label=field.label) @@ -345,7 +340,7 @@ class Field: def _set_warning(self, is_valid: bool, - error: Union[str, InvalidJid] + error: str | InvalidJid ) -> None: if not self._field.required and not is_valid and not error: diff --git a/gajim/gtk/dialogs.py b/gajim/gtk/dialogs.py index e6efa1cd5..014ade070 100644 --- a/gajim/gtk/dialogs.py +++ b/gajim/gtk/dialogs.py @@ -17,7 +17,6 @@ from __future__ import annotations from typing import Any from typing import cast from typing import NamedTuple -from typing import Optional from gi.repository import GdkPixbuf from gi.repository import Gtk @@ -41,7 +40,7 @@ class DialogButton(NamedTuple): is_default: bool @classmethod - def make(cls, type_: Optional[str] = None, **kwargs: Any) -> DialogButton: + def make(cls, type_: str | None = None, **kwargs: Any) -> DialogButton: # Defaults default_kwargs: dict[str, Any] = { 'response': None, @@ -149,7 +148,7 @@ class ConfirmationDialog(Gtk.MessageDialog): sec_text: str, buttons: list[DialogButton], modal: bool = True, - transient_for: Optional[Gtk.Window] = None + transient_for: Gtk.Window | None = None ) -> None: if transient_for is None: transient_for = app.app.get_active_window() @@ -215,7 +214,7 @@ class ConfirmationCheckDialog(ConfirmationDialog): check_text: str, buttons: list[DialogButton], modal: bool = True, - transient_for: Optional[Gtk.Window] = None + transient_for: Gtk.Window | None = None ) -> None: ConfirmationDialog.__init__(self, title, @@ -258,7 +257,7 @@ class PastePreviewDialog(ConfirmationDialog): image: GdkPixbuf.Pixbuf, buttons: list[DialogButton], modal: bool = True, - transient_for: Optional[Gtk.Window] = None + transient_for: Gtk.Window | None = None ) -> None: ConfirmationDialog.__init__(self, title, @@ -294,9 +293,9 @@ class InputDialog(ConfirmationDialog): text: str, sec_text: str, buttons: list[DialogButton], - input_str: Optional[str] = None, + input_str: str | None = None, modal: bool = True, - transient_for: Optional[Gtk.Window] = None, + transient_for: Gtk.Window | None = None, ) -> None: ConfirmationDialog.__init__(self, title, diff --git a/gajim/gtk/emoji_data_gtk.py b/gajim/gtk/emoji_data_gtk.py index 39ef9004b..2b9d7f9e4 100644 --- a/gajim/gtk/emoji_data_gtk.py +++ b/gajim/gtk/emoji_data_gtk.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import logging from collections import defaultdict @@ -91,7 +89,7 @@ def get_emoji_data() -> dict[str, dict[str, str]]: return emoji_data -def try_load_raw_emoji_data(locale: str) -> Optional[GLib.Bytes]: +def try_load_raw_emoji_data(locale: str) -> GLib.Bytes | None: # Sources of emoji data can be found at: # https://gitlab.gnome.org/GNOME/gtk/-/tree/main/gtk/emoji emoji_data_resource = f'/org/gtk/libgtk/emoji/{locale}.data' @@ -211,7 +209,7 @@ short_locale = get_short_lang_code(app_locale) locales = get_locale_fallbacks(short_locale) try: log.debug('Trying locales %s', locales) - raw_emoji_data: Optional[GLib.Bytes] = None + raw_emoji_data: GLib.Bytes | None = None for loc in locales: raw_emoji_data = try_load_raw_emoji_data(loc) if raw_emoji_data: diff --git a/gajim/gtk/features.py b/gajim/gtk/features.py index dc1dfb5d5..23b203384 100644 --- a/gajim/gtk/features.py +++ b/gajim/gtk/features.py @@ -20,7 +20,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import NamedTuple -from typing import Optional import os import sys @@ -39,7 +38,7 @@ class Feature(NamedTuple): tooltip: str dependency_u: str dependency_w: str - enabled: Optional[bool] + enabled: bool | None class Features(Gtk.ApplicationWindow): @@ -199,7 +198,7 @@ class FeatureItem(Gtk.Grid): self.add(self._icon) self.add(self._box) - def _set_feature(self, available: bool, enabled: Optional[bool]) -> None: + def _set_feature(self, available: bool, enabled: bool | None) -> None: self._icon.get_style_context().remove_class('error-color') self._icon.get_style_context().remove_class('warning-color') self._icon.get_style_context().remove_class('success-color') diff --git a/gajim/gtk/file_transfer_selector.py b/gajim/gtk/file_transfer_selector.py index bdbdc64de..a6d5801b2 100644 --- a/gajim/gtk/file_transfer_selector.py +++ b/gajim/gtk/file_transfer_selector.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import logging from pathlib import Path @@ -58,7 +57,7 @@ class FileTransferSelector(Gtk.Box): def __init__(self, contact: types.ChatContactT, - method: Optional[str] = None + method: str | None = None ) -> None: Gtk.Box.__init__(self) @@ -288,8 +287,8 @@ class FileRow(Gtk.ListBoxRow): load_file_async(self.file_path, self._on_load_finished, mime_type) def _on_load_finished(self, - data: Optional[bytes], - _error: Optional[GLib.Error], + data: bytes | None, + _error: GLib.Error | None, mime_type: Any ) -> None: diff --git a/gajim/gtk/filechoosers.py b/gajim/gtk/filechoosers.py index f1411e123..b3e914c6f 100644 --- a/gajim/gtk/filechoosers.py +++ b/gajim/gtk/filechoosers.py @@ -20,8 +20,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional -from typing import Union import os import sys @@ -60,10 +58,10 @@ class BaseFileChooser: pass def _on_response(self, - dialog: Union[Gtk.FileChooser, Gtk.FileChooserNative], + dialog: Gtk.FileChooser | Gtk.FileChooserNative, response: Gtk.ResponseType, accept_cb: AcceptCallbackT, - cancel_cb: Optional[Callable[..., Any]] + cancel_cb: Callable[..., Any] | None ) -> None: if response == Gtk.ResponseType.ACCEPT: accept_cb(dialog.get_filenames()) @@ -129,10 +127,10 @@ class NativeFileChooserDialog(Gtk.FileChooserNative, BaseFileChooser): def __init__(self, accept_cb: AcceptCallbackT, - cancel_cb: Optional[Callable[..., Any]] = None, - transient_for: Optional[Gtk.Window] = None, - path: Optional[str] = None, - file_name: Optional[str] = None, + cancel_cb: Callable[..., Any] | None = None, + transient_for: Gtk.Window | None = None, + path: str | None = None, + file_name: str | None = None, select_multiple: bool = False, modal: bool = False ) -> None: @@ -189,10 +187,10 @@ class GtkFileChooserDialog(Gtk.FileChooserDialog, BaseFileChooser): def __init__(self, accept_cb: AcceptCallbackT, - cancel_cb: Optional[Callable[..., Any]] = None, - transient_for: Optional[Gtk.Window] = None, - path: Optional[str] = None, - file_name: Optional[str] = None, + cancel_cb: Callable[..., Any] | None = None, + transient_for: Gtk.Window | None = None, + path: str | None = None, + file_name: str | None = None, select_multiple: bool = False, preview: bool = True, modal: bool = False diff --git a/gajim/gtk/filetransfer.py b/gajim/gtk/filetransfer.py index 4c352e834..6b1a9533c 100644 --- a/gajim/gtk/filetransfer.py +++ b/gajim/gtk/filetransfer.py @@ -19,8 +19,6 @@ from __future__ import annotations -from typing import Optional - import logging import os import time @@ -714,7 +712,7 @@ class FileTransfersWindow: file_path: str, file_name: str, file_desc: str = '' - ) -> Optional[FileProp]: + ) -> FileProp | None: ''' Create new file_props object and set initial file transfer properties in it diff --git a/gajim/gtk/groupchat_affiliation.py b/gajim/gtk/groupchat_affiliation.py index 4db2fd8ef..8e54607c7 100644 --- a/gajim/gtk/groupchat_affiliation.py +++ b/gajim/gtk/groupchat_affiliation.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import cast from typing import NamedTuple -from typing import Optional import logging from enum import IntEnum @@ -39,7 +38,7 @@ log = logging.getLogger('gajim.gtk.groupchat_affiliation') class AffiliationRow(NamedTuple): jid: str - nick: Optional[str] + nick: str | None affiliation: str diff --git a/gajim/gtk/groupchat_creation.py b/gajim/gtk/groupchat_creation.py index 6c4615513..1fa837006 100644 --- a/gajim/gtk/groupchat_creation.py +++ b/gajim/gtk/groupchat_creation.py @@ -13,8 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional -from typing import Union import logging import random @@ -45,7 +43,7 @@ log = logging.getLogger('gajim.gtk.groupchat_creation') class CreateGroupchatWindow(Gtk.ApplicationWindow, EventHelper): - def __init__(self, account: Optional[str]) -> None: + def __init__(self, account: str | None) -> None: Gtk.ApplicationWindow.__init__(self) EventHelper.__init__(self) self.set_name('CreateGroupchat') @@ -86,7 +84,7 @@ class CreateGroupchatWindow(Gtk.ApplicationWindow, EventHelper): self.set_focus(self._ui.address_entry) def _on_account_state(self, - _event: Union[AccountConnected, AccountDisconnected] + _event: AccountConnected | AccountDisconnected ) -> None: any_account_connected = app.get_number_of_connected_accounts() > 0 if any_account_connected: @@ -95,7 +93,7 @@ class CreateGroupchatWindow(Gtk.ApplicationWindow, EventHelper): else: self._ui.stack.set_visible_child_name('no-connection') - def _update_accounts(self, account: Optional[str] = None) -> None: + def _update_accounts(self, account: str | None = None) -> None: accounts = app.get_enabled_accounts_with_labels(connected_only=True) account_liststore = self._ui.account_combo.get_model() assert isinstance(account_liststore, Gtk.ListStore) diff --git a/gajim/gtk/groupchat_details.py b/gajim/gtk/groupchat_details.py index 5c72d2e87..01a7e0589 100644 --- a/gajim/gtk/groupchat_details.py +++ b/gajim/gtk/groupchat_details.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from gi.repository import Gdk from gi.repository import GObject from gi.repository import Gtk @@ -44,7 +42,7 @@ from gajim.gtk.structs import RemoveHistoryActionParams class GroupchatDetails(Gtk.ApplicationWindow): def __init__(self, contact: GroupchatContact, - page: Optional[str] = None + page: str | None = None ) -> None: Gtk.ApplicationWindow.__init__(self) self.set_application(app.app) @@ -73,7 +71,7 @@ class GroupchatDetails(Gtk.ApplicationWindow): self._on_stack_child_changed) self.add(self._ui.main_grid) - self._groupchat_manage: Optional[GroupchatManage] = None + self._groupchat_manage: GroupchatManage | None = None self._add_groupchat_info() self._add_groupchat_settings() diff --git a/gajim/gtk/groupchat_info.py b/gajim/gtk/groupchat_info.py index 76c4c0432..48db2e5ab 100644 --- a/gajim/gtk/groupchat_info.py +++ b/gajim/gtk/groupchat_info.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional import logging import time @@ -105,7 +104,7 @@ MUC_FEATURES = { class GroupChatInfoScrolled(Gtk.ScrolledWindow): def __init__(self, - account: Optional[str] = None, + account: str | None = None, width: int = 300, minimal: bool = False ) -> None: @@ -126,23 +125,23 @@ class GroupChatInfoScrolled(Gtk.ScrolledWindow): Gtk.PolicyType.AUTOMATIC) self._account = account - self._info: Optional[DiscoInfo] = None + self._info: DiscoInfo | None = None self._ui = get_builder('groupchat_info_scrolled.ui') self.add(self._ui.info_grid) self._ui.connect_signals(self) self.show_all() - def get_account(self) -> Optional[str]: + def get_account(self) -> str | None: return self._account def set_account(self, account: str) -> None: self._account = account - def get_jid(self) -> Optional[JID]: + def get_jid(self) -> JID | None: return self._info.jid - def set_subject(self, muc_subject: Optional[MucSubject]) -> None: + def set_subject(self, muc_subject: MucSubject | None) -> None: if muc_subject is None: return diff --git a/gajim/gtk/groupchat_inviter.py b/gajim/gtk/groupchat_inviter.py index 668bd6fe1..b65e21690 100644 --- a/gajim/gtk/groupchat_inviter.py +++ b/gajim/gtk/groupchat_inviter.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import locale @@ -41,7 +40,7 @@ from gajim.gtk.util import AccountBadge class ContactRow(Gtk.ListBoxRow): def __init__(self, account: str, - contact: Optional[types.BareContact], + contact: types.BareContact | None, jid: str, name: str, show_account: bool @@ -101,7 +100,7 @@ class ContactRow(Gtk.ListBoxRow): self.show_all() def _get_avatar_image(self, - contact: Optional[types.BareContact] + contact: types.BareContact | None ) -> Gtk.Image: if contact is None: icon_name = 'avatar-default' @@ -145,7 +144,7 @@ class GroupChatInviter(Gtk.Box): self._room_jid = room_jid self._new_contact_row_visible = False - self._new_contact_rows: dict[str, Optional[ContactRow]] = {} + self._new_contact_rows: dict[str, ContactRow | None] = {} self._accounts: list[list[str]] = [] self._ui.search_entry.connect( @@ -338,7 +337,7 @@ class GroupChatInviter(Gtk.Box): def _filter_func(self, row: ContactRow, - _user_data: Optional[Any] + _user_data: Any | None ) -> bool: search_text = self._ui.search_entry.get_text().lower() search_text_list = search_text.split() @@ -353,7 +352,7 @@ class GroupChatInviter(Gtk.Box): @staticmethod def _sort_func(row1: ContactRow, row2: ContactRow, - _user_data: Optional[Any] + _user_data: Any | None ) -> int: name1 = row1.get_search_text() name2 = row2.get_search_text() diff --git a/gajim/gtk/groupchat_nick_completion.py b/gajim/gtk/groupchat_nick_completion.py index c377c661d..33672f14c 100644 --- a/gajim/gtk/groupchat_nick_completion.py +++ b/gajim/gtk/groupchat_nick_completion.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - import logging from gi.repository import Gdk @@ -35,7 +33,7 @@ class GroupChatNickCompletion(EventHelper): def __init__(self) -> None: EventHelper.__init__(self) - self._contact: Optional[GroupchatContact] = None + self._contact: GroupchatContact | None = None self._suggestions: list[str] = [] self._last_key_tab = False diff --git a/gajim/gtk/groupchat_outcasts.py b/gajim/gtk/groupchat_outcasts.py index 725ea3fe1..26a043a92 100644 --- a/gajim/gtk/groupchat_outcasts.py +++ b/gajim/gtk/groupchat_outcasts.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import cast from typing import NamedTuple -from typing import Optional import logging from enum import IntEnum @@ -39,7 +38,7 @@ log = logging.getLogger('gajim.gtk.groupchat_outcasts') class OutcastRow(NamedTuple): jid: str - reason: Optional[str] + reason: str | None class Column(IntEnum): diff --git a/gajim/gtk/groupchat_roster.py b/gajim/gtk/groupchat_roster.py index ad2075021..94bc1c30a 100644 --- a/gajim/gtk/groupchat_roster.py +++ b/gajim/gtk/groupchat_roster.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import locale import logging @@ -229,7 +228,7 @@ class GroupchatRoster(Gtk.Revealer, EventHelper): return self._filter_string in model[iter_][Column.TEXT].lower() - def _get_group_iter(self, group_name: str) -> Optional[Gtk.TreeIter]: + def _get_group_iter(self, group_name: str) -> Gtk.TreeIter | None: try: ref = self._group_refs[group_name] except KeyError: @@ -240,7 +239,7 @@ class GroupchatRoster(Gtk.Revealer, EventHelper): return None return self._store.get_iter(path) - def _get_contact_iter(self, nick: str) -> Optional[Gtk.TreeIter]: + def _get_contact_iter(self, nick: str) -> Gtk.TreeIter | None: try: ref = self._contact_refs[nick] except KeyError: @@ -359,7 +358,7 @@ class GroupchatRoster(Gtk.Revealer, EventHelper): renderer: Gtk.CellRenderer, model: Gtk.TreeModel, iter_: Gtk.TreeIter, - _user_data: Optional[object] + _user_data: object | None ) -> None: has_parent = bool(model.iter_parent(iter_)) @@ -481,7 +480,7 @@ class GroupchatRoster(Gtk.Revealer, EventHelper): model: Gtk.TreeModel, iter1: Gtk.TreeIter, iter2: Gtk.TreeIter, - _user_data: Optional[object] + _user_data: object | None ) -> int: ''' Compare two iterators to sort them diff --git a/gajim/gtk/gstreamer.py b/gajim/gtk/gstreamer.py index 3dd9240d9..50bf722ef 100644 --- a/gajim/gtk/gstreamer.py +++ b/gajim/gtk/gstreamer.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from gi.repository import Gtk try: @@ -24,9 +22,7 @@ except Exception: pass -def create_gtk_widget() -> Optional[tuple[Gst.Element, - Gtk.Widget, - str]]: +def create_gtk_widget() -> tuple[Gst.Element, Gtk.Widget, str] | None: gtkglsink = Gst.ElementFactory.make('gtkglsink', None) if gtkglsink is not None: glsinkbin = Gst.ElementFactory.make('glsinkbin', None) diff --git a/gajim/gtk/history_export.py b/gajim/gtk/history_export.py index ce615dcd4..434b2c52e 100644 --- a/gajim/gtk/history_export.py +++ b/gajim/gtk/history_export.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import cast from typing import Literal -from typing import Optional from typing import overload import logging @@ -43,7 +42,7 @@ log = logging.getLogger('gajim.gtk.history_export') class HistoryExport(Assistant): - def __init__(self, account: Optional[str] = None) -> None: + def __init__(self, account: str | None = None) -> None: Assistant.__init__(self) self.account = account @@ -170,7 +169,7 @@ class HistoryExport(Assistant): class SelectAccountDir(Page): - def __init__(self, account: Optional[str]) -> None: + def __init__(self, account: str | None) -> None: Page.__init__(self) self._account = account self._export_directory = str(configpaths.get('MY_DATA')) diff --git a/gajim/gtk/history_sync.py b/gajim/gtk/history_sync.py index 32f6f410f..58961cdaa 100644 --- a/gajim/gtk/history_sync.py +++ b/gajim/gtk/history_sync.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import cast from typing import Literal -from typing import Optional from typing import overload import logging @@ -56,11 +55,11 @@ class HistorySyncAssistant(Assistant, EventHelper): self.account = account self._client = app.get_client(account) - self._timedelta: Optional[timedelta] = None + self._timedelta: timedelta | None = None self._now = datetime.now(timezone.utc) - self._query_id: Optional[str] = None - self._start: Optional[datetime] = None - self._end: Optional[datetime] = None + self._query_id: str | None = None + self._start: datetime | None = None + self._end: datetime | None = None mam_start = ArchiveState.NEVER archive = app.storage.archive.get_archive_infos( @@ -210,7 +209,7 @@ class SelectTime(Page): self.title = _('Synchronize Chat History') self.complete = False - self._timedelta: Optional[timedelta] = None + self._timedelta: timedelta | None = None heading = Gtk.Label() heading.get_style_context().add_class('large-header') @@ -254,7 +253,7 @@ class SelectTime(Page): self.complete = True self.update_page_complete() - def get_timedelta(self) -> Optional[timedelta]: + def get_timedelta(self) -> timedelta | None: return self._timedelta def get_default_button(self) -> str: @@ -307,12 +306,12 @@ class Progress(Page): class TimeOption(Gtk.ListBoxRow): - def __init__(self, text: str, months: Optional[timedelta] = None) -> None: + def __init__(self, text: str, months: timedelta | None = None) -> None: Gtk.ListBoxRow.__init__(self) label = Gtk.Label(label=text) self.add(label) self._timedelta = months - def get_timedelta(self) -> Optional[timedelta]: + def get_timedelta(self) -> timedelta | None: return self._timedelta diff --git a/gajim/gtk/main.py b/gajim/gtk/main.py index 101b1e347..8d0095281 100644 --- a/gajim/gtk/main.py +++ b/gajim/gtk/main.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from typing import TYPE_CHECKING import logging @@ -441,7 +440,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): def _on_action(self, action: Gio.SimpleAction, - _param: Optional[GLib.Variant]) -> Optional[int]: + _param: GLib.Variant | None) -> int | None: action_name = action.get_name() log.info('Activate action: %s', action_name) @@ -755,7 +754,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): self._account_side_bar.activate_account_page(account) self._main_stack.show_account(account) - def get_active_workspace(self) -> Optional[str]: + def get_active_workspace(self) -> str | None: return self._workspace_side_bar.get_active_workspace() def is_chat_active(self, account: str, jid: JID) -> bool: @@ -801,7 +800,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): self.add_workspace(workspace_id) def add_workspace(self, - workspace_id: Optional[str] = None, + workspace_id: str | None = None, switch: bool = True) -> str: if workspace_id is None: @@ -967,7 +966,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): jid: JID, type_: str, select: bool = False, - message: Optional[str] = None + message: str | None = None ) -> None: workspace_id = self._get_suitable_workspace(account, jid) @@ -1032,8 +1031,8 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): def add_app_message(self, category: str, - new_version: Optional[str] = None, - new_setup_url: Optional[str] = None + new_version: str | None = None, + new_setup_url: str | None = None ) -> None: self._app_page.add_app_message(category, new_version, new_setup_url) @@ -1126,7 +1125,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): def get_preferred_ft_method(self, contact: types.ChatContactT - ) -> Optional[str]: + ) -> str | None: ft_pref = app.settings.get_account_setting( contact.account, @@ -1154,8 +1153,8 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): def show_add_join_groupchat(self, account: str, jid: str, - nickname: Optional[str] = None, - password: Optional[str] = None + nickname: str | None = None, + password: str | None = None ) -> None: if not self.chat_exists(account, JID.from_string(jid)): @@ -1168,7 +1167,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): def start_chat_from_jid(self, account: str, jid: str, - message: Optional[str] = None + message: str | None = None ) -> None: jid_ = JID.from_string(jid) @@ -1202,7 +1201,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): return # TODO: Keep "confirm_block" setting? - def _block_contact(report: Optional[str] = None) -> None: + def _block_contact(report: str | None = None) -> None: client.get_module('Blocking').block([contact.jid], report) self._chat_page.remove_chat(account, contact.jid) @@ -1314,7 +1313,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): app.settings.set('mainwin_height', window_height) app.settings.save() - def on_continue2(message: Optional[str]) -> None: + def on_continue2(message: str | None) -> None: if 'file_transfers' not in app.interface.instances: app.app.start_shutdown(message=message) return @@ -1342,7 +1341,7 @@ class MainWindow(Gtk.ApplicationWindow, EventHelper): return app.app.start_shutdown(message=message) - def on_continue(message: Optional[str]) -> None: + def on_continue(message: str | None) -> None: if message is None: # user pressed Cancel to change status message dialog return diff --git a/gajim/gtk/main_stack.py b/gajim/gtk/main_stack.py index 16e1791a6..1d61085a1 100644 --- a/gajim/gtk/main_stack.py +++ b/gajim/gtk/main_stack.py @@ -14,9 +14,6 @@ from __future__ import annotations -from typing import Optional -from typing import Union - from gi.repository import Gtk from nbxmpp.protocol import JID @@ -27,7 +24,7 @@ from gajim.gtk.app_page import AppPage from gajim.gtk.chat_list import ChatList from gajim.gtk.chat_page import ChatPage -PageT = Union[ChatPage, AccountPage, AppPage] +PageT = ChatPage | AccountPage | AppPage class MainStack(Gtk.Stack): @@ -58,7 +55,7 @@ class MainStack(Gtk.Stack): def remove_chats_for_account(self, account: str) -> None: self._chat_page.remove_chats_for_account(account) - def get_visible_page_name(self) -> Optional[str]: + def get_visible_page_name(self) -> str | None: return self.get_visible_child_name() def show_app_page(self) -> None: diff --git a/gajim/gtk/menus.py b/gajim/gtk/menus.py index cbc6821a4..b2c6e9da7 100644 --- a/gajim/gtk/menus.py +++ b/gajim/gtk/menus.py @@ -20,7 +20,6 @@ from __future__ import annotations from typing import Callable from typing import cast from typing import Iterator -from typing import Optional import textwrap from datetime import datetime @@ -655,7 +654,7 @@ def get_groupchat_participant_menu(account: str, return menu -def get_component_search_menu(jid: Optional[str], copy_text: str) -> GajimMenu: +def get_component_search_menu(jid: str | None, copy_text: str) -> GajimMenu: menuitems: MenuItemListT = [ (_('Copy'), 'app.copy-text', copy_text), ] @@ -672,9 +671,9 @@ def get_chat_row_menu(contact: types.ChatContactT, name: str, text: str, timestamp: datetime, - message_id: Optional[str], - stanza_id: Optional[str], - log_line_id: Optional[int] + message_id: str | None, + stanza_id: str | None, + log_line_id: int | None ) -> GajimMenu: menu_items: MenuItemListT = [] @@ -806,7 +805,7 @@ def get_workspace_menu(workspace_id: str) -> GajimMenu: return GajimMenu.from_list(menuitems) -def escape_mnemonic(label: Optional[str]) -> Optional[str]: +def escape_mnemonic(label: str | None) -> str | None: if label is None: return None # Underscore inside a label means the next letter is a keyboard diff --git a/gajim/gtk/message_actions_box.py b/gajim/gtk/message_actions_box.py index facf92a49..e5876b7e8 100644 --- a/gajim/gtk/message_actions_box.py +++ b/gajim/gtk/message_actions_box.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging import tempfile @@ -56,8 +55,8 @@ class MessageActionsBox(Gtk.Grid): def __init__(self) -> None: Gtk.Grid.__init__(self) - self._client: Optional[Client] = None - self._contact: Optional[ChatContactT] = None + self._client: Client | None = None + self._contact: ChatContactT | None = None self._ui = get_builder('message_actions_box.ui') self.get_style_context().add_class('message-actions-box') @@ -103,7 +102,7 @@ class MessageActionsBox(Gtk.Grid): assert self._contact is not None return self._contact - def get_seclabel(self) -> Optional[SecurityLabel]: + def get_seclabel(self) -> SecurityLabel | None: return self._security_label_selector.get_seclabel() def _connect_actions(self) -> None: @@ -133,7 +132,7 @@ class MessageActionsBox(Gtk.Grid): def _on_action(self, action: Gio.SimpleAction, - param: Optional[GLib.Variant]) -> Optional[int]: + param: GLib.Variant | None) -> int | None: if self._contact is None: return @@ -218,10 +217,10 @@ class MessageActionsBox(Gtk.Grid): def toggle_message_correction(self) -> None: self.msg_textview.toggle_message_correction() - def try_message_correction(self, message: str) -> Optional[str]: + def try_message_correction(self, message: str) -> str | None: return self.msg_textview.try_message_correction(message) - def get_last_message_id(self, contact: ChatContactT) -> Optional[str]: + def get_last_message_id(self, contact: ChatContactT) -> str | None: return self.msg_textview.get_last_message_id(contact) def _on_client_state_changed(self, diff --git a/gajim/gtk/message_input.py b/gajim/gtk/message_input.py index afdaf8af1..7c850d2f5 100644 --- a/gajim/gtk/message_input.py +++ b/gajim/gtk/message_input.py @@ -20,7 +20,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging from collections import defaultdict @@ -83,11 +82,11 @@ class MessageInputTextView(Gtk.TextView, EventHelper): self._undo_list: list[str] = [] self.undo_pressed: bool = False - self._contact: Optional[ChatContactT] = None + self._contact: ChatContactT | None = None # XEP-0308 Message Correction self._correcting: dict[ChatContactT, bool] = defaultdict(lambda: False) - self._last_message_id: dict[ChatContactT, Optional[str]] = {} + self._last_message_id: dict[ChatContactT, str | None] = {} self._chat_action_processor = ChatActionProcessor(self) @@ -119,7 +118,7 @@ class MessageInputTextView(Gtk.TextView, EventHelper): return self._correcting[self._contact] - def get_last_message_id(self, contact: ChatContactT) -> Optional[str]: + def get_last_message_id(self, contact: ChatContactT) -> str | None: return self._last_message_id.get(contact) def toggle_message_correction(self) -> None: @@ -145,7 +144,7 @@ class MessageInputTextView(Gtk.TextView, EventHelper): self.get_style_context().add_class('gajim-msg-correcting') self.insert_text(message_row.message) - def try_message_correction(self, message: str) -> Optional[str]: + def try_message_correction(self, message: str) -> str | None: assert self._contact is not None if not self.is_correcting: return None @@ -213,7 +212,7 @@ class MessageInputTextView(Gtk.TextView, EventHelper): def _get_spell_checker_language(self, contact: ChatContactT - ) -> Optional[Gspell.Language]: + ) -> Gspell.Language | None: lang = contact.settings.get('speller_language') if not lang: diff --git a/gajim/gtk/notification.py b/gajim/gtk/notification.py index 092420f52..8b06cedb8 100644 --- a/gajim/gtk/notification.py +++ b/gajim/gtk/notification.py @@ -27,8 +27,6 @@ from __future__ import annotations from typing import Any -from typing import Optional -from typing import Union import logging import sys @@ -183,7 +181,7 @@ class PopupNotification(Gtk.Window): self.set_decorated(False) self.set_keep_above(True) - self._timeout_id: Optional[int] = None + self._timeout_id: int | None = None self._event = event self._ui = get_builder('popup_notification_window.ui') @@ -384,7 +382,7 @@ class Linux(NotificationBackend): _('Mark as Read'), action, params.to_variant()) def _make_notification_id(self, - event: events.Notification) -> Optional[str]: + event: events.Notification) -> str | None: if event.type in ('connection-failed', 'server-shutdown'): return self._make_id([event.type, event.account]) @@ -419,7 +417,7 @@ class Linux(NotificationBackend): def _get_avatar_for_notification(account: str, - jid: Union[JID, str]) -> GdkPixbuf.Pixbuf: + jid: JID | str) -> GdkPixbuf.Pixbuf: scale = get_monitor_scale_factor() size = AvatarSize.NOTIFICATION client = app.get_client(account) diff --git a/gajim/gtk/notification_manager.py b/gajim/gtk/notification_manager.py index 23b4d9af8..d8517a85e 100644 --- a/gajim/gtk/notification_manager.py +++ b/gajim/gtk/notification_manager.py @@ -17,8 +17,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional -from typing import Union from gi.repository import Gio from gi.repository import GLib @@ -42,7 +40,7 @@ from gajim.gtk.util import open_window NotificationActionListT = list[ tuple[str, Callable[[Gio.SimpleAction, GLib.Variant], Any], - Optional[str]]] + str | None]] class NotificationManager(Gtk.ListBox): @@ -189,7 +187,7 @@ class NotificationManager(Gtk.ListBox): def _deny_request(self, jid: str) -> None: self._client.get_module('Presence').unsubscribed(jid) - def _get_notification_row(self, jid: str) -> Optional[NotificationRow]: + def _get_notification_row(self, jid: str) -> NotificationRow | None: rows = cast(list[NotificationRow], self.get_children()) for row in rows: if row.jid == jid: @@ -310,7 +308,7 @@ class NotificationRow(Gtk.ListBoxRow): label.set_max_width_chars(30) return label - def _generate_avatar_image(self, jid: Union[str, JID]) -> Gtk.Image: + def _generate_avatar_image(self, jid: str | JID) -> Gtk.Image: contact = self._client.get_module('Contacts').get_contact(jid) surface = contact.get_avatar( AvatarSize.ROSTER, self.get_scale_factor(), add_show=False) @@ -324,7 +322,7 @@ class SubscriptionRequestRow(NotificationRow): account: str, jid: str, text: str, - user_nick: Optional[str] = None + user_nick: str | None = None ) -> None: NotificationRow.__init__(self, account, jid) self.type = 'subscribe' diff --git a/gajim/gtk/omemo_trust_manager.py b/gajim/gtk/omemo_trust_manager.py index b73d10b47..465d9ca02 100644 --- a/gajim/gtk/omemo_trust_manager.py +++ b/gajim/gtk/omemo_trust_manager.py @@ -18,8 +18,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import locale import logging @@ -67,7 +65,7 @@ TRUST_DATA = { class OMEMOTrustManager(Gtk.Box, EventHelper): def __init__(self, account: str, - contact: Optional[types.ChatContactT] = None + contact: types.ChatContactT | None = None ) -> None: Gtk.Box.__init__(self) @@ -153,7 +151,7 @@ class OMEMOTrustManager(Gtk.Box, EventHelper): app.check_finalize(self) def _on_account_state(self, - event: Union[AccountConnected, AccountDisconnected] + event: AccountConnected | AccountDisconnected ) -> None: if not app.account_is_connected(self._account): @@ -402,7 +400,7 @@ class MenuOption(Gtk.ListBoxRow): icon: str, label_text: str, color: str, - type_: Optional[OMEMOTrust] = None + type_: OMEMOTrust | None = None ) -> None: Gtk.ListBoxRow.__init__(self) diff --git a/gajim/gtk/pep_config.py b/gajim/gtk/pep_config.py index 16a133c31..1591ac473 100644 --- a/gajim/gtk/pep_config.py +++ b/gajim/gtk/pep_config.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import logging @@ -63,8 +62,8 @@ class PEPConfig(Gtk.ApplicationWindow, EventHelper): self.set_title(_('PEP Service Configuration (%s)') % self.account) self._client = app.get_client(account) - self._result_node: Optional[Node] = None - self._dataform_widget: Optional[DataFormWidget] = None + self._result_node: Node | None = None + self._dataform_widget: DataFormWidget | None = None source_manager = GtkSource.LanguageManager.get_default() lang = source_manager.get_language('xml') diff --git a/gajim/gtk/plugins.py b/gajim/gtk/plugins.py index 762bb7696..bdd895804 100644 --- a/gajim/gtk/plugins.py +++ b/gajim/gtk/plugins.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Literal -from typing import Optional import logging from enum import IntEnum @@ -259,7 +258,7 @@ class PluginsWindow(Gtk.ApplicationWindow, EventHelper): return True, plugin.available_text return False, '' - def _get_plugin_row(self, short_name: str) -> Optional[Gtk.TreeModelRow]: + def _get_plugin_row(self, short_name: str) -> Gtk.TreeModelRow | None: iter_ = self._manifests.get(short_name) if iter_ is None: return None @@ -268,7 +267,7 @@ class PluginsWindow(Gtk.ApplicationWindow, EventHelper): def _add_manifest(self, manifest: PluginManifest, installed: bool, - icon: Optional[GdkPixbuf.Pixbuf] = None) -> None: + icon: GdkPixbuf.Pixbuf | None = None) -> None: restart = self._get_restart(manifest) has_error, error = self._get_error(manifest, installed) @@ -298,7 +297,7 @@ class PluginsWindow(Gtk.ApplicationWindow, EventHelper): def _get_plugin_icon(self, manifest: PluginManifest - ) -> Optional[GdkPixbuf.Pixbuf]: + ) -> GdkPixbuf.Pixbuf | None: image_name = f'{manifest.short_name}.png' path = configpaths.get('PLUGINS_IMAGES') / image_name diff --git a/gajim/gtk/preferences.py b/gajim/gtk/preferences.py index 88481ad18..bfd9aeab6 100644 --- a/gajim/gtk/preferences.py +++ b/gajim/gtk/preferences.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import logging import sys @@ -71,7 +70,7 @@ class Preferences(Gtk.ApplicationWindow): self._ui = get_builder('preferences.ui') - self._video_preview: Optional[VideoPreview] = None + self._video_preview: VideoPreview | None = None self._prefs: dict[str, PreferenceBox] = {} side_bar_switcher = SideBarSwitcher() @@ -132,7 +131,7 @@ class Preferences(Gtk.ApplicationWindow): if event.keyval == Gdk.KEY_Escape: self.destroy() - def get_video_preview(self) -> Optional[VideoPreview]: + def get_video_preview(self) -> VideoPreview | None: return self._video_preview @staticmethod diff --git a/gajim/gtk/preview.py b/gajim/gtk/preview.py index 3286db20c..27e39da81 100644 --- a/gajim/gtk/preview.py +++ b/gajim/gtk/preview.py @@ -14,7 +14,6 @@ from typing import Any from typing import cast -from typing import Optional import logging @@ -57,7 +56,7 @@ class PreviewWidget(Gtk.Box): def __init__(self, account: str) -> None: Gtk.Box.__init__(self) self.account = account - self._preview: Optional[Preview] = None + self._preview: Preview | None = None self._destroyed = False @@ -103,7 +102,7 @@ class PreviewWidget(Gtk.Box): self._ui.info_message.set_tooltip_text('') @ensure_not_destroyed - def update(self, preview: Preview, data: Optional[GdkPixbufType]) -> None: + def update(self, preview: Preview, data: GdkPixbufType | None) -> None: self._preview = preview self._ui.progress_box.hide() diff --git a/gajim/gtk/preview_audio_analyzer.py b/gajim/gtk/preview_audio_analyzer.py index 20095eabf..f8c4c028b 100644 --- a/gajim/gtk/preview_audio_analyzer.py +++ b/gajim/gtk/preview_audio_analyzer.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Callable from typing import cast -from typing import Optional import logging import math @@ -53,7 +52,7 @@ class AudioAnalyzer: self._duration = Gst.CLOCK_TIME_NONE # in ns self._num_channels = 1 self._samples: list[tuple[float, float]] = [] - self._level: Optional[Gst.Element] = None + self._level: Gst.Element | None = None self._bus_watch_id: int = 0 self._setup_audio_analyzer(filepath) diff --git a/gajim/gtk/profile.py b/gajim/gtk/profile.py index 9f360873c..a8dc14a9b 100644 --- a/gajim/gtk/profile.py +++ b/gajim/gtk/profile.py @@ -15,8 +15,6 @@ from typing import Any from typing import cast -from typing import Optional -from typing import Union import logging @@ -96,15 +94,15 @@ class ProfileWindow(Gtk.ApplicationWindow): self._ui.add_entry_button.set_menu_model(menu) self._add_actions() - self._avatar_selector: Optional[AvatarSelector] = None - self._current_avatar: Optional[cairo.ImageSurface] = None - self._current_vcard: Optional[VCard] = None - self._avatar_nick_public: Optional[bool] = None + self._avatar_selector: AvatarSelector | None = None + self._current_avatar: cairo.ImageSurface | None = None + self._current_vcard: VCard | None = None + self._avatar_nick_public: bool | None = None # False - no change to avatar # None - we want to delete the avatar # Avatar - upload new avatar - self._new_avatar: Union[None, bool, Avatar] = False + self._new_avatar: None | bool | Avatar = False self._ui.nickname_entry.set_text(app.nicks[account]) @@ -219,7 +217,7 @@ class ProfileWindow(Gtk.ApplicationWindow): def _on_action(self, action: Gio.SimpleAction, - _param: Optional[GLib.Variant] + _param: GLib.Variant | None ) -> None: name = action.get_name() key = name.split('-')[1] diff --git a/gajim/gtk/resource_selector.py b/gajim/gtk/resource_selector.py index d46501521..322ca36c4 100644 --- a/gajim/gtk/resource_selector.py +++ b/gajim/gtk/resource_selector.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import cast -from typing import Optional import locale import logging @@ -45,7 +44,7 @@ class ResourceSelector(Gtk.ScrolledWindow): def __init__(self, contact: BareContact, - constraints: Optional[list[str]] = None) -> None: + constraints: list[str] | None = None) -> None: Gtk.ScrolledWindow.__init__(self) self.set_shadow_type(Gtk.ShadowType.IN) self.set_size_request(-1, 200) @@ -154,7 +153,7 @@ class ResourceRow(Gtk.ListBoxRow): @staticmethod def _get_client_identity(disco_info: DiscoInfo - ) -> tuple[Optional[str], Optional[str]]: + ) -> tuple[str | None, str | None]: for identity in disco_info.identities: if identity.category == 'client': return identity.name, identity.type diff --git a/gajim/gtk/roster.py b/gajim/gtk/roster.py index 9d8fee5a8..a6865b3fb 100644 --- a/gajim/gtk/roster.py +++ b/gajim/gtk/roster.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Literal -from typing import Optional import locale import logging @@ -639,7 +638,7 @@ class Roster(Gtk.ScrolledWindow, EventHelper): assert path is not None return self._store.get_iter(path) - def _get_group_iter(self, group_name: str) -> Optional[Gtk.TreeIter]: + def _get_group_iter(self, group_name: str) -> Gtk.TreeIter | None: try: ref = self._group_refs[group_name] except KeyError: diff --git a/gajim/gtk/roster_item_exchange.py b/gajim/gtk/roster_item_exchange.py index 4cb1fd53c..818da4281 100644 --- a/gajim/gtk/roster_item_exchange.py +++ b/gajim/gtk/roster_item_exchange.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional from gi.repository import Gtk from nbxmpp.protocol import JID @@ -34,7 +33,7 @@ class RosterItemExchange(Gtk.ApplicationWindow): action: str, exchange_list: dict[str, list[str]], jid_from: JID, - message_body: Optional[str] = None + message_body: str | None = None ) -> None: Gtk.ApplicationWindow.__init__(self) self.set_application(app.app) diff --git a/gajim/gtk/search_view.py b/gajim/gtk/search_view.py index 9c595e445..387b5592e 100644 --- a/gajim/gtk/search_view.py +++ b/gajim/gtk/search_view.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Iterator -from typing import Optional import itertools import logging @@ -57,12 +56,12 @@ class SearchView(Gtk.Box): Gtk.Box.__init__(self) self.set_size_request(300, -1) - self._account: Optional[str] = None - self._jid: Optional[JID] = None - self._results_iterator: Optional[Iterator[SearchLogRow]] = None + self._account: str | None = None + self._jid: JID | None = None + self._results_iterator: Iterator[SearchLogRow] | None = None - self._first_date: Optional[datetime] = None - self._last_date: Optional[datetime] = None + self._first_date: datetime | None = None + self._last_date: datetime | None = None self._ui = get_builder('search_view.ui') self._ui.results_listbox.set_header_func(self._header_func) @@ -177,7 +176,7 @@ class SearchView(Gtk.Box): @staticmethod def _strip_filters(text: str, - filter_name: str) -> tuple[str, Optional[list[str]]]: + filter_name: str) -> tuple[str, list[str] | None]: filters: list[str] = [] start = 0 new_text = '' @@ -353,7 +352,7 @@ class SearchView(Gtk.Box): self._clear() self._update_calendar() - def set_context(self, account: Optional[str], jid: Optional[JID]) -> None: + def set_context(self, account: str | None, jid: JID | None) -> None: self._account = account self._jid = jid self._update_calendar() @@ -433,7 +432,7 @@ class ResultRow(Gtk.ListBoxRow): def _get_avatar(self, kind: str, - name: str) -> Optional[cairo.ImageSurface]: + name: str) -> cairo.ImageSurface | None: scale = self.get_scale_factor() if self.contact.is_groupchat: diff --git a/gajim/gtk/security_label_selector.py b/gajim/gtk/security_label_selector.py index 7514842f4..70b158eac 100644 --- a/gajim/gtk/security_label_selector.py +++ b/gajim/gtk/security_label_selector.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import cast -from typing import Optional from gi.repository import Gtk from gi.repository import Pango @@ -34,9 +33,9 @@ from gajim.common.types import ChatContactT class SecurityLabelSelector(Gtk.ComboBox): def __init__(self) -> None: Gtk.ComboBox.__init__(self, no_show_all=True) - self._account: Optional[str] = None - self._client: Optional[Client] = None - self._contact: Optional[ChatContactT] = None + self._account: str | None = None + self._client: Client | None = None + self._contact: ChatContactT | None = None self.set_valign(Gtk.Align.CENTER) self.set_tooltip_text(_('Select a security label for your message…')) @@ -98,8 +97,8 @@ class SecurityLabelSelector(Gtk.ComboBox): def _on_setting_changed(self, state: bool, _name: str, - _account: Optional[str], - _jid: Optional[JID] + _account: str | None, + _jid: JID | None ) -> None: self.set_no_show_all(not state) if state: @@ -137,7 +136,7 @@ class SecurityLabelSelector(Gtk.ComboBox): self.set_no_show_all(False) self.show_all() - def get_seclabel(self) -> Optional[SecurityLabel]: + def get_seclabel(self) -> SecurityLabel | None: index = self.get_active() if index == -1: return None diff --git a/gajim/gtk/server_info.py b/gajim/gtk/server_info.py index 2205d10d2..19f0de7e3 100644 --- a/gajim/gtk/server_info.py +++ b/gajim/gtk/server_info.py @@ -15,7 +15,6 @@ from typing import Any from typing import cast from typing import NamedTuple -from typing import Optional import logging from datetime import timedelta @@ -49,7 +48,7 @@ log = logging.getLogger('gajim.gtk.server_info') class Feature(NamedTuple): name: str available: bool - additional: Optional[str] = None + additional: str | None = None class ServerInfo(Gtk.ApplicationWindow, EventHelper): @@ -183,7 +182,7 @@ class ServerInfo(Gtk.ApplicationWindow, EventHelper): @staticmethod def _get_addresses(fields: dict[str, str], dataforms: list[SimpleDataForm] - ) -> Optional[dict[str, list[str]]]: + ) -> dict[str, list[str]] | None: addresses: dict[str, list[str]] = {} for form in dataforms: field = form.vars.get('FORM_TYPE') diff --git a/gajim/gtk/service_registration.py b/gajim/gtk/service_registration.py index 717009a2e..b9be9df01 100644 --- a/gajim/gtk/service_registration.py +++ b/gajim/gtk/service_registration.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Literal -from typing import Optional from typing import overload import logging @@ -172,7 +171,7 @@ class Form(Page): self.title = _('Register') self.complete = False - self._dataform_widget: Optional[DataFormWidget] = None + self._dataform_widget: DataFormWidget | None = None self.show_all() def add_form(self, form: Any) -> None: diff --git a/gajim/gtk/settings.py b/gajim/gtk/settings.py index 1ea77baae..94d48ee95 100644 --- a/gajim/gtk/settings.py +++ b/gajim/gtk/settings.py @@ -19,8 +19,6 @@ from __future__ import annotations from typing import Any from typing import Callable from typing import cast -from typing import Optional -from typing import Union import logging @@ -53,7 +51,7 @@ class SettingsDialog(Gtk.ApplicationWindow): flags: Gtk.DialogFlags, settings: list[Setting], account: str, - extend: Optional[dict[SettingKind, GenericSetting]] = None + extend: dict[SettingKind, GenericSetting] | None = None ) -> None: Gtk.ApplicationWindow.__init__(self) self.set_application(app.app) @@ -97,9 +95,9 @@ class SettingsDialog(Gtk.ApplicationWindow): class SettingsBox(Gtk.ListBox): def __init__(self, - account: Optional[str] = None, - jid: Optional[str] = None, - extend: Optional[dict[SettingKind, GenericSetting]] = None + account: str | None = None, + jid: str | None = None, + extend: dict[SettingKind, GenericSetting] | None = None ) -> None: Gtk.ListBox.__init__(self) self.get_style_context().add_class('settings-box') @@ -176,13 +174,13 @@ class GenericSetting(Gtk.ListBoxRow): label: str, type_: SettingType, value: AllSettingsT, - name: Optional[str], - callback: Optional[Callable[..., None]] = None, - data: Optional[Any] = None, - desc: Optional[str] = None, - bind: Optional[str] = None, + name: str | None, + callback: Callable[..., None] | None = None, + data: Any | None = None, + desc: str | None = None, + bind: str | None = None, inverted: bool = False, - enabled_func: Optional[Callable[..., bool]] = None + enabled_func: Callable[..., bool] | None = None ) -> None: Gtk.ListBoxRow.__init__(self) @@ -278,8 +276,8 @@ class GenericSetting(Gtk.ListBoxRow): def _parse_bind(self) -> tuple[SettingType, str, - Optional[str], - Optional[JID]]: + str | None, + JID | None]: assert self.bind is not None if '::' not in self.bind: return SettingType.CONFIG, self.bind, None, None @@ -306,7 +304,7 @@ class GenericSetting(Gtk.ListBoxRow): value: AllSettingsT, account: str, jid: JID - ) -> Optional[AllSettingsT]: + ) -> AllSettingsT | None: if value is None: return None if type_ == SettingType.VALUE: @@ -378,9 +376,7 @@ class GenericSetting(Gtk.ListBoxRow): self.set_sensitive(enabled_func_value) def _add_action_button(self, - kwargs: dict[str, Union[str, - Callable[..., None], - None]] + kwargs: dict[str, str | Callable[..., None] | None] ) -> None: icon_name = cast(str, kwargs.get('button-icon-name')) button_text = cast(str, kwargs.get('button-text')) @@ -699,7 +695,7 @@ class LoginSetting(DialogSetting): class PopoverSetting(GenericSetting): def __init__(self, *args: Any, - entries: Union[list[str], dict[str, str]], + entries: list[str] | dict[str, str], **kwargs: Any ) -> None: GenericSetting.__init__(self, *args) @@ -761,7 +757,7 @@ class PopoverSetting(GenericSetting): self.show_all() @staticmethod - def _convert_to_dict(entries: Union[list[Any], dict[Any, Any]] + def _convert_to_dict(entries: list[Any] | dict[Any, Any] ) -> dict[Any, Any]: if isinstance(entries, list): entries = {key: key for key in entries} @@ -795,7 +791,7 @@ class PopoverSetting(GenericSetting): def on_row_activated(self) -> None: self._popover.popup() - def update_entries(self, entries: Union[list[str], dict[str, str]]) -> None: + def update_entries(self, entries: list[str] | dict[str, str]) -> None: self._entries = self._convert_to_dict(entries) self._menu_listbox.foreach(self._menu_listbox.remove) self._add_menu_entries() @@ -819,7 +815,7 @@ class PopoverRow(Gtk.ListBoxRow): class ComboSetting(GenericSetting): def __init__(self, *args: Any, - combo_items: list[Union[str, tuple[str, str]]] + combo_items: list[str | tuple[str, str]] ) -> None: GenericSetting.__init__(self, *args) diff --git a/gajim/gtk/sidebar_switcher.py b/gajim/gtk/sidebar_switcher.py index ab5203dbf..974f61b0a 100644 --- a/gajim/gtk/sidebar_switcher.py +++ b/gajim/gtk/sidebar_switcher.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import cast -from typing import Optional from gi.repository import Gtk @@ -23,7 +22,7 @@ from gajim.common import app class SideBarSwitcher(Gtk.ListBox): - def __init__(self, width: Optional[int] = None) -> None: + def __init__(self, width: int | None = None) -> None: Gtk.ListBox.__init__(self) self.set_vexpand(True) self.get_style_context().add_class('settings-menu') @@ -84,7 +83,7 @@ class Row(Gtk.ListBoxRow): def __init__(self, name: str, title: str, - icon_name: Optional[str], + icon_name: str | None, visible: bool) -> None: Gtk.ListBoxRow.__init__(self) diff --git a/gajim/gtk/start_chat.py b/gajim/gtk/start_chat.py index 96e80a998..360ce5e09 100644 --- a/gajim/gtk/start_chat.py +++ b/gajim/gtk/start_chat.py @@ -16,8 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional -from typing import Union import locale from enum import IntEnum @@ -61,7 +59,7 @@ from gajim.gtk.util import AccountBadge from gajim.gtk.util import GajimPopover from gajim.gtk.util import get_icon_name -ContactT = Union[BareContact, GroupchatContact] +ContactT = BareContact | GroupchatContact class Search(IntEnum): @@ -71,8 +69,8 @@ class Search(IntEnum): class StartChatDialog(Gtk.ApplicationWindow): def __init__(self, - initial_jid: Optional[str] = None, - initial_message: Optional[str] = None + initial_jid: str | None = None, + initial_message: str | None = None ) -> None: Gtk.ApplicationWindow.__init__(self) @@ -84,7 +82,7 @@ class StartChatDialog(Gtk.ApplicationWindow): self.set_type_hint(Gdk.WindowTypeHint.DIALOG) self.set_default_size(-1, 600) self.ready_to_destroy = False - self._parameter_form: Optional[MuclumbusResult] = None + self._parameter_form: MuclumbusResult | None = None self._keywords: list[str] = [] self._destroyed = False self._search_stopped = False @@ -97,10 +95,10 @@ class StartChatDialog(Gtk.ApplicationWindow): self._ui.join_box.pack_start(self._nick_chooser, True, False, 0) # Helper for the case where we don't receive a disco info - self._new_chat_row: Optional[ContactRow] = None + self._new_chat_row: ContactRow | None = None self._search_is_valid_jid = False - self.new_contact_rows: dict[str, Optional[ContactRow]] = {} + self.new_contact_rows: dict[str, ContactRow | None] = {} self._accounts = app.get_enabled_accounts_with_labels() rows: list[ContactRow] = [] @@ -144,7 +142,7 @@ class StartChatDialog(Gtk.ApplicationWindow): if rows: self._load_contacts(rows) - self._initial_message: dict[str, Optional[str]] = {} + self._initial_message: dict[str, str | None] = {} if initial_jid is not None: self._initial_message[initial_jid] = initial_message self._ui.search_entry.set_text(initial_jid) @@ -459,7 +457,7 @@ class StartChatDialog(Gtk.ApplicationWindow): else: self._set_error_from_code('not-muc-service') - def _set_error(self, error: Union[StanzaError, TimeoutStanzaError]) -> None: + def _set_error(self, error: StanzaError | TimeoutStanzaError) -> None: if isinstance(error, TimeoutStanzaError): text = _('This address is not reachable.') else: @@ -761,9 +759,9 @@ class StartChatDialog(Gtk.ApplicationWindow): class ContactRow(Gtk.ListBoxRow): def __init__(self, account: str, - contact: Optional[ContactT], - jid: Optional[JID], - name: Optional[str], + contact: ContactT | None, + jid: JID | None, + name: str | None, show_account: bool, groupchat: bool = False ) -> None: @@ -872,7 +870,7 @@ class GlobalSearch(Gtk.ListBox): Gtk.ListBox.__init__(self) self.set_has_tooltip(True) self.set_activate_on_single_click(False) - self._progress: Optional[ProgressRow] = None + self._progress: ProgressRow | None = None self._add_placeholder() self.show_all() diff --git a/gajim/gtk/status_icon.py b/gajim/gtk/status_icon.py index b7499ef16..ab48d77e4 100644 --- a/gajim/gtk/status_icon.py +++ b/gajim/gtk/status_icon.py @@ -20,7 +20,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Union import logging import sys @@ -170,10 +169,10 @@ class GtkMenuBackend(EventHelper): def _on_our_show(self, _event: events.ShowChanged) -> None: self.update_state() - def _on_account_state(self, - _event: Union[events.AccountConnected, - events.AccountDisconnected] - ) -> None: + def _on_account_state( + self, + _event: events.AccountConnected | events.AccountDisconnected + ) -> None: account_connected = bool(app.get_number_of_connected_accounts() > 0) self._ui.start_chat_menuitem.set_sensitive(account_connected) diff --git a/gajim/gtk/status_message_selector.py b/gajim/gtk/status_message_selector.py index 82415dcc0..ea03bcb7d 100644 --- a/gajim/gtk/status_message_selector.py +++ b/gajim/gtk/status_message_selector.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional from gi.repository import Gtk @@ -32,7 +31,7 @@ from gajim.gtk.util import EventHelper class StatusMessageSelector(Gtk.Box, EventHelper): - def __init__(self, account: Optional[str] = None) -> None: + def __init__(self, account: str | None = None) -> None: Gtk.Box.__init__(self) EventHelper.__init__(self) self.get_style_context().add_class('linked') diff --git a/gajim/gtk/status_selector.py b/gajim/gtk/status_selector.py index 281bdbe6d..bc6d58cf9 100644 --- a/gajim/gtk/status_selector.py +++ b/gajim/gtk/status_selector.py @@ -14,8 +14,6 @@ from __future__ import annotations -from typing import Optional - from gi.repository import Gtk from gi.repository import Pango @@ -36,7 +34,7 @@ from gajim.gtk.util import EventHelper class StatusSelector(Gtk.MenuButton, EventHelper): - def __init__(self, account: Optional[str] = None, compact: bool = False): + def __init__(self, account: str | None = None, compact: bool = False): Gtk.MenuButton.__init__(self) EventHelper.__init__(self) self.set_direction(Gtk.ArrowType.UP) diff --git a/gajim/gtk/themes.py b/gajim/gtk/themes.py index 4360baafa..11efc6bb5 100644 --- a/gajim/gtk/themes.py +++ b/gajim/gtk/themes.py @@ -19,8 +19,6 @@ from __future__ import annotations from typing import Any from typing import cast from typing import NamedTuple -from typing import Optional -from typing import Union from enum import IntEnum @@ -301,7 +299,7 @@ class Themes(Gtk.ApplicationWindow): @staticmethod def _update_preferences_window() -> None: - window = cast(Optional[Preferences], get_app_window('Preferences')) + window = cast(Preferences | None, get_app_window('Preferences')) if window is not None: window.update_theme_list() @@ -353,7 +351,7 @@ class Themes(Gtk.ApplicationWindow): class Option(Gtk.ListBoxRow): def __init__(self, option: StyleOption, - value: Union[str, Pango.FontDescription, None] + value: str | Pango.FontDescription | None ) -> None: Gtk.ListBoxRow.__init__(self) self.option = option @@ -382,7 +380,7 @@ class Option(Gtk.ListBoxRow): self.add(self._box) self.show_all() - def _init_color(self, color: Optional[str]) -> None: + def _init_color(self, color: str | None) -> None: color_button = Gtk.ColorButton() if color is not None: rgba = Gdk.RGBA() @@ -392,7 +390,7 @@ class Option(Gtk.ListBoxRow): color_button.connect('color-set', self._on_color_set) self._box.add(color_button) - def _init_font(self, desc: Optional[Pango.FontDescription]) -> None: + def _init_font(self, desc: Pango.FontDescription | None) -> None: font_button = Gtk.FontButton() if desc is not None: font_button.set_font_desc(desc) diff --git a/gajim/gtk/util.py b/gajim/gtk/util.py index 44b674ac7..aa1783514 100644 --- a/gajim/gtk/util.py +++ b/gajim/gtk/util.py @@ -18,8 +18,6 @@ from __future__ import annotations from typing import Any -from typing import Optional -from typing import Union import logging import math @@ -64,7 +62,7 @@ from gajim.gtk.const import WINDOW_MODULES log = logging.getLogger('gajim.gtk.util') -MenuValueT = Union[None, str, GLib.Variant, VariantMixin] +MenuValueT = None | str | GLib.Variant | VariantMixin MenuItemListT = list[tuple[str, str, MenuValueT]] @@ -79,8 +77,8 @@ def icon_exists(name: str) -> bool: def load_icon_info(icon_name: str, size: int, - scale: Optional[int], - flags: Gtk.IconLookupFlags) -> Optional[Gtk.IconInfo]: + scale: int | None, + flags: Gtk.IconLookupFlags) -> Gtk.IconInfo | None: if scale is None: scale = app.window.get_scale_factor() @@ -106,9 +104,9 @@ def load_icon_info(icon_name: str, def load_icon_surface( icon_name: str, size: int = 16, - scale: Optional[int] = None, + scale: int | None = None, flags: Gtk.IconLookupFlags = Gtk.IconLookupFlags.FORCE_SIZE -) -> Optional[cairo.ImageSurface]: +) -> cairo.ImageSurface | None: icon_info = load_icon_info(icon_name, size, scale, flags) if icon_info is None: @@ -118,9 +116,9 @@ def load_icon_surface( def load_icon_pixbuf(icon_name: str, size: int = 16, - scale: Optional[int] = None, + scale: int | None = None, flags: Gtk.IconLookupFlags = Gtk.IconLookupFlags.FORCE_SIZE - ) -> Optional[GdkPixbuf.Pixbuf]: + ) -> GdkPixbuf.Pixbuf | None: icon_info = load_icon_info(icon_name, size, scale, flags) if icon_info is None: @@ -139,7 +137,7 @@ def get_app_icon_list(scale_widget: Gtk.Widget) -> list[GdkPixbuf.Pixbuf]: def get_icon_name(name: str, - transport: Optional[str] = None) -> str: + transport: str | None = None) -> str: if transport is not None: return f'{transport}-{name}' @@ -226,7 +224,7 @@ def restore_main_window_position() -> None: app.settings.get('mainwin_y_position')) -def get_source_view_style_scheme() -> Optional[GtkSource.StyleScheme]: +def get_source_view_style_scheme() -> GtkSource.StyleScheme | None: style_scheme_manager = GtkSource.StyleSchemeManager.get_default() if app.css_config.prefer_dark: return style_scheme_manager.get_scheme('solarized-dark') @@ -362,7 +360,7 @@ def get_monitor_scale_factor() -> int: return monitor.get_scale_factor() -def get_primary_accel_mod() -> Optional[Gdk.ModifierType]: +def get_primary_accel_mod() -> Gdk.ModifierType | None: ''' Returns the primary Gdk.ModifierType modifier. cmd on osx, ctrl everywhere else. @@ -413,7 +411,7 @@ def format_tune(data: TuneData) -> str: 'source': source} -def get_account_tune_icon_name(account: str) -> Optional[str]: +def get_account_tune_icon_name(account: str) -> str | None: client = app.get_client(account) tune = client.get_module('UserTune').get_current_tune() return None if tune is None else 'audio-x-generic' @@ -436,13 +434,13 @@ def format_location(location: LocationData) -> str: return location_string.strip() -def get_account_location_icon_name(account: str) -> Optional[str]: +def get_account_location_icon_name(account: str) -> str | None: client = app.get_client(account) location = client.get_module('UserLocation').get_current_location() return None if location is None else 'applications-internet' -def format_eta(time_: Union[int, float]) -> str: +def format_eta(time_: int | float) -> str: times = {'minutes': 0, 'seconds': 0} time_ = int(time_) times['seconds'] = time_ % 60 @@ -463,7 +461,7 @@ def format_fingerprint(fingerprint: str) -> str: return buf.rstrip().upper() -def find_widget(name: str, container: Gtk.Container) -> Optional[Gtk.Widget]: +def find_widget(name: str, container: Gtk.Container) -> Gtk.Widget | None: for child in container.get_children(): if Gtk.Buildable.get_name(child) == name: return child @@ -550,7 +548,7 @@ def add_css_to_widget(widget: Any, css: str) -> None: Gtk.STYLE_PROVIDER_PRIORITY_USER) -def get_pixbuf_from_data(file_data: bytes) -> Optional[GdkPixbuf.Pixbuf]: +def get_pixbuf_from_data(file_data: bytes) -> GdkPixbuf.Pixbuf | None: # TODO: This already exists in preview_helpery pixbuf_from_data ''' Get image data and returns GdkPixbuf.Pixbuf @@ -592,7 +590,7 @@ def scale_with_ratio(size: int, width: int, height: int) -> tuple[int, int]: def scale_pixbuf(pixbuf: GdkPixbuf.Pixbuf, - size: int) -> Optional[GdkPixbuf.Pixbuf]: + size: int) -> GdkPixbuf.Pixbuf | None: width, height = scale_with_ratio(size, pixbuf.get_width(), pixbuf.get_height()) @@ -602,15 +600,15 @@ def scale_pixbuf(pixbuf: GdkPixbuf.Pixbuf, def scale_pixbuf_from_data(data: bytes, size: int - ) -> Optional[GdkPixbuf.Pixbuf]: + ) -> GdkPixbuf.Pixbuf | None: pixbuf = get_pixbuf_from_data(data) assert pixbuf is not None return scale_pixbuf(pixbuf, size) -def load_pixbuf(path: Union[str, Path], - size: Optional[int] = None - ) -> Optional[GdkPixbuf.Pixbuf]: +def load_pixbuf(path: str | Path, + size: int | None = None + ) -> GdkPixbuf.Pixbuf | None: try: if size is None: return GdkPixbuf.Pixbuf.new_from_file(str(path)) @@ -688,9 +686,9 @@ def get_app_windows(account: str) -> list[Gtk.Window]: def get_app_window(name: str, - account: Optional[str] = None, - jid: Optional[Union[str, JID]] = None - ) -> Optional[Gtk.Window]: + account: str | None = None, + jid: str | JID | None = None + ) -> Gtk.Window | None: for win in app.app.get_windows(): if type(win).__name__ != name: continue @@ -797,7 +795,7 @@ def wrap_with_event_box(klass: Any) -> Any: class AccountBadge(Gtk.Label): - def __init__(self, account: Optional[str] = None) -> None: + def __init__(self, account: str | None = None) -> None: Gtk.Label.__init__(self) self.set_ellipsize(Pango.EllipsizeMode.END) self.set_max_width_chars(12) @@ -831,7 +829,7 @@ class AccountBadge(Gtk.Label): def _on_account_label_changed(self, _value: str, _setting: str, - account: Optional[str], + account: str | None, *args: Any ) -> None: @@ -883,7 +881,7 @@ def get_style_attribute_with_name(name: str) -> Pango.Attribute: raise ValueError('unknown attribute %s' % name) -def get_key_theme() -> Optional[str]: +def get_key_theme() -> str | None: settings = Gtk.Settings.get_default() if settings is None: return None @@ -891,7 +889,7 @@ def get_key_theme() -> Optional[str]: def make_menu_item(label: str, - action: Optional[str] = None, + action: str | None = None, value: MenuValueT = None) -> Gio.MenuItem: item = Gio.MenuItem.new(label) @@ -925,7 +923,7 @@ class GajimMenu(Gio.Menu): def add_item(self, label: str, action: str, - value: Optional[MenuValueT] = None) -> None: + value: MenuValueT | None = None) -> None: item = make_menu_item(label, action, value) self.append_item(item) @@ -953,9 +951,9 @@ class GdkRectangle(Gdk.Rectangle): class GajimPopover(Gtk.Popover): def __init__(self, menu: Gio.MenuModel, - relative_to: Optional[Gtk.Widget] = None, + relative_to: Gtk.Widget | None = None, position: Gtk.PositionType = Gtk.PositionType.RIGHT, - event: Optional[Gdk.EventButton] = None) -> None: + event: Gdk.EventButton | None = None) -> None: Gtk.Popover.__init__(self) diff --git a/gajim/gtk/vcard_grid.py b/gajim/gtk/vcard_grid.py index d84812015..3e122fa55 100644 --- a/gajim/gtk/vcard_grid.py +++ b/gajim/gtk/vcard_grid.py @@ -13,7 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional import datetime @@ -159,7 +158,7 @@ class VCardGrid(Gtk.Grid): self._account = account self._row_count: int = 0 - self._vcard: Optional[VCard] = None + self._vcard: VCard | None = None self._props = [] def set_editable(self, enabled: bool) -> None: @@ -177,7 +176,7 @@ class VCardGrid(Gtk.Grid): self.add_property(prop) - def get_vcard(self) -> Optional[VCard]: + def get_vcard(self) -> VCard | None: return self._vcard def validate(self) -> None: @@ -237,7 +236,7 @@ class ValueLabel(Gtk.Label): def __init__(self, prop, account): Gtk.Label.__init__(self) self._prop = prop - self._uri: Optional[URI] = None + self._uri: URI | None = None self._account = account self.set_selectable(True) self.set_xalign(0) @@ -559,7 +558,7 @@ class VCardProperty: self._second_column.extend([self._type_combobox, self._type_image]) @staticmethod - def _get_icon_name(type_: str) -> Optional[str]: + def _get_icon_name(type_: str) -> str | None: if type_ == 'home': return 'feather-home' if type_ == 'work': diff --git a/gajim/gtk/video_preview.py b/gajim/gtk/video_preview.py index 6840bd9f5..6a5fdfd65 100644 --- a/gajim/gtk/video_preview.py +++ b/gajim/gtk/video_preview.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional import logging @@ -41,10 +40,10 @@ class VideoPreview: self._active = False - self._av_pipeline: Optional[Gst.Pipeline] = None - self._av_src: Optional[Gst.Bin] = None - self._av_sink: Optional[Gst.Element] = None - self._av_widget: Optional[Gtk.Widget] = None + self._av_pipeline: Gst.Pipeline | None = None + self._av_src: Gst.Bin | None = None + self._av_sink: Gst.Element | None = None + self._av_widget: Gtk.Widget | None = None @property def widget(self) -> Gtk.Box: diff --git a/gajim/gtk/workspace_dialog.py b/gajim/gtk/workspace_dialog.py index b03b028fa..61b00e5d2 100644 --- a/gajim/gtk/workspace_dialog.py +++ b/gajim/gtk/workspace_dialog.py @@ -13,7 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional from gi.repository import Gdk from gi.repository import Gtk @@ -31,7 +30,7 @@ from gajim.gtk.util import rgba_to_float class WorkspaceDialog(Gtk.ApplicationWindow): - def __init__(self, workspace_id: Optional[str] = None) -> None: + def __init__(self, workspace_id: str | None = None) -> None: Gtk.ApplicationWindow.__init__(self) self.set_name('WorkspaceDialog') self.set_application(app.app) @@ -51,8 +50,8 @@ class WorkspaceDialog(Gtk.ApplicationWindow): self._ui.image_box.add(self._avatar_selector) name: str = _('My Workspace') - color: Optional[str] = None - self._avatar_sha: Optional[str] = None + color: str | None = None + self._avatar_sha: str | None = None if app.settings.get_workspace_count() == 1: # Don't allow to remove last workspace @@ -137,7 +136,7 @@ class WorkspaceDialog(Gtk.ApplicationWindow): scale) self._ui.preview.set_from_surface(surface) - def _get_avatar_data(self) -> Optional[bytes]: + def _get_avatar_data(self) -> bytes | None: if not self._avatar_selector.get_prepared(): return None diff --git a/gajim/gtk/workspace_side_bar.py b/gajim/gtk/workspace_side_bar.py index 5a060a143..d5f0c78ad 100644 --- a/gajim/gtk/workspace_side_bar.py +++ b/gajim/gtk/workspace_side_bar.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import cast -from typing import Optional import logging import pickle @@ -62,9 +61,9 @@ class WorkspaceSideBar(Gtk.ListBox): entries, Gdk.DragAction.MOVE) - self.drag_row: Optional[Workspace] = None - self.row_before: Optional[CommonWorkspace] = None - self.row_after: Optional[CommonWorkspace] = None + self.drag_row: Workspace | None = None + self.row_before: CommonWorkspace | None = None + self.row_after: CommonWorkspace | None = None self.connect('drag-motion', self._on_drag_motion) self.connect('drag-data-received', self._on_drag_data_received) @@ -169,14 +168,14 @@ class WorkspaceSideBar(Gtk.ListBox): def _get_row_before(self, row: CommonWorkspace - ) -> Optional[CommonWorkspace]: + ) -> CommonWorkspace | None: workspace = cast( CommonWorkspace, self.get_row_at_index(row.get_index() - 1)) return workspace def _get_row_after(self, row: CommonWorkspace - ) -> Optional[CommonWorkspace]: + ) -> CommonWorkspace | None: workspace = cast( CommonWorkspace, self.get_row_at_index(row.get_index() + 1)) return workspace @@ -231,7 +230,7 @@ class WorkspaceSideBar(Gtk.ListBox): def get_other_workspace(self, exclude_workspace_id: str - ) -> Optional[str]: + ) -> str | None: for workspace in self._workspaces.values(): if workspace.workspace_id != exclude_workspace_id: @@ -251,7 +250,7 @@ class WorkspaceSideBar(Gtk.ListBox): if row is not None and row.workspace_id != 'add': app.window.activate_workspace(row.workspace_id) - def get_active_workspace(self) -> Optional[str]: + def get_active_workspace(self) -> str | None: row = cast(CommonWorkspace | None, self.get_selected_row()) if row is None: return None @@ -265,7 +264,7 @@ class WorkspaceSideBar(Gtk.ListBox): def get_workspace_by_id(self, workspace_id: str - ) -> Optional[CommonWorkspace]: + ) -> CommonWorkspace | None: workspaces = cast(list[CommonWorkspace], self.get_children()) for row in workspaces: if row.workspace_id == workspace_id: diff --git a/gajim/gtk/xml_console.py b/gajim/gtk/xml_console.py index 8f5ccfd4a..cb7443385 100644 --- a/gajim/gtk/xml_console.py +++ b/gajim/gtk/xml_console.py @@ -13,8 +13,6 @@ # along with Gajim. If not, see <http://www.gnu.org/licenses/>. from typing import Any -from typing import Optional -from typing import Union import time @@ -59,9 +57,9 @@ class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper): self.set_name('XMLConsoleWindow') self._selected_account = 'AllAccounts' - self._selected_send_account: Optional[str] = None - self._filter_dialog: Optional[SettingsDialog] = None - self._last_stanza: Optional[str] = None + self._selected_send_account: str | None = None + self._filter_dialog: SettingsDialog | None = None + self._last_stanza: str | None = None self._last_search: str = '' self._presence = True @@ -148,7 +146,7 @@ class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper): self._ui.headerbar.set_subtitle(title) def _on_account_changed(self, - event: Union[AccountEnabled, AccountDisabled] + event: AccountEnabled | AccountDisabled ) -> None: buf = self._ui.protocol_view.get_buffer() @@ -356,9 +354,9 @@ class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper): self._last_search = search_str @staticmethod - def _get_accounts() -> list[tuple[Optional[str], str]]: + def _get_accounts() -> list[tuple[str | None, str]]: accounts = app.get_accounts_sorted() - combo_accounts: list[tuple[Optional[str], str]] = [] + combo_accounts: list[tuple[str | None, str]] = [] for account in accounts: label = app.get_account_label(account) combo_accounts.append((account, label)) @@ -481,7 +479,7 @@ class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper): self._print_stanza(event, 'outgoing') def _print_stanza(self, - event: Union[StanzaReceived, StanzaSent], + event: StanzaReceived | StanzaSent, kind: str ) -> None: if event.account == 'AccountWizard': diff --git a/gajim/plugins/helpers.py b/gajim/plugins/helpers.py index 7993e7909..8de689a62 100644 --- a/gajim/plugins/helpers.py +++ b/gajim/plugins/helpers.py @@ -12,7 +12,6 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <http://www.gnu.org/licenses/>. -from typing import Optional from pathlib import Path @@ -30,7 +29,7 @@ class GajimPluginActivateException(Exception): ''' -def get_builder(file_name: str, widgets: Optional[list[str]] = None) -> Builder: +def get_builder(file_name: str, widgets: list[str] | None = None) -> Builder: return Builder(file_name, widgets, # pyright: ignore domain=DOMAIN, diff --git a/gajim/plugins/manifest.py b/gajim/plugins/manifest.py index b6846ab82..e0b672e1d 100644 --- a/gajim/plugins/manifest.py +++ b/gajim/plugins/manifest.py @@ -15,7 +15,6 @@ from __future__ import annotations from typing import Any -from typing import Optional import json import sys @@ -52,7 +51,7 @@ class PluginManifest: version: V requirements: list[Requirement] platforms: list[str] - path: Optional[Path] = None + path: Path | None = None def __hash__(self): return hash(f'{self.short_name}_{self.version}') @@ -105,7 +104,7 @@ class PluginManifest: @classmethod def from_manifest_json(cls, manifest: dict[str, Any], - path: Optional[Path] = None) -> PluginManifest: + path: Path | None = None) -> PluginManifest: return cls( name=manifest['name'], short_name=manifest['short_name'], diff --git a/gajim/plugins/pluginmanager.py b/gajim/plugins/pluginmanager.py index 59036230a..b1f660456 100644 --- a/gajim/plugins/pluginmanager.py +++ b/gajim/plugins/pluginmanager.py @@ -16,7 +16,6 @@ from __future__ import annotations from typing import Any from typing import Callable -from typing import Optional import logging import os @@ -97,7 +96,7 @@ class PluginManager(metaclass=Singleton): def update_plugins(self, replace: bool = True, activate: bool = False, - plugin_name: Optional[str] = None + plugin_name: str | None = None ) -> list[str]: ''' Move plugins from the downloaded folder to the user plugin folder @@ -151,7 +150,7 @@ class PluginManager(metaclass=Singleton): def _load_plugin_module(self, manifest: PluginManifest - ) -> Optional[type[GajimPlugin]]: + ) -> type[GajimPlugin] | None: assert manifest.path is not None module_path = manifest.path / '__init__.py' @@ -184,7 +183,7 @@ class PluginManager(metaclass=Singleton): def add_plugin(self, manifest: PluginManifest, activate: bool = False - ) -> Optional[GajimPlugin]: + ) -> GajimPlugin | None: plugin_class = self._load_plugin_module(manifest) if plugin_class is None: @@ -242,13 +241,13 @@ class PluginManager(metaclass=Singleton): for module_to_remove in modules_to_remove: del sys.modules[module_to_remove] - def get_active_plugin(self, plugin_name: str) -> Optional[GajimPlugin]: + def get_active_plugin(self, plugin_name: str) -> GajimPlugin | None: for plugin in self.active_plugins: if plugin.manifest.short_name == plugin_name: return plugin return None - def get_plugin(self, short_name: str) -> Optional[GajimPlugin]: + def get_plugin(self, short_name: str) -> GajimPlugin | None: for plugin in self.plugins: if plugin.manifest.short_name == short_name: return plugin @@ -527,7 +526,7 @@ class PluginManager(metaclass=Singleton): client.connection.register_handler(handler) @staticmethod - def _load_manifest(plugin_path: Path) -> Optional[PluginManifest]: + def _load_manifest(plugin_path: Path) -> PluginManifest | None: try: return PluginManifest.from_path(plugin_path) except Exception as error: @@ -564,7 +563,7 @@ class PluginManager(metaclass=Singleton): def install_from_zip(self, zip_filename: str, overwrite: bool = False - ) -> Optional[GajimPlugin]: + ) -> GajimPlugin | None: ''' Install plugin from zip and return plugin ''' @@ -656,7 +655,7 @@ class PluginManager(metaclass=Singleton): app.ged.raise_event(PluginRemoved(manifest=plugin.manifest)) - def get_plugin_by_path(self, plugin_dir: str) -> Optional[GajimPlugin]: + def get_plugin_by_path(self, plugin_dir: str) -> GajimPlugin | None: for plugin in self.plugins: if plugin.__path__ in plugin_dir: return plugin diff --git a/gajim/plugins/repository.py b/gajim/plugins/repository.py index bc431ca52..f0cd0a74d 100644 --- a/gajim/plugins/repository.py +++ b/gajim/plugins/repository.py @@ -15,7 +15,6 @@ from typing import Any from typing import cast from typing import Iterable -from typing import Optional import json import logging @@ -146,7 +145,7 @@ class PluginRepository(Observable): return suitable_plugins - def _refresh_plugin_index(self, callback: Optional[Any] = None) -> None: + def _refresh_plugin_index(self, callback: Any | None = None) -> None: log.info('Refresh index') request = create_http_request() request.set_user_data(callback) diff --git a/pyproject.toml b/pyproject.toml index b77d0b231..fae748650 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -233,7 +233,6 @@ ignore = [ "SIM201", # Use x instead of not x "SIM212", # Use `value if value else ''` instead of `'' if not value else value` "SIM300", # Yoda conditions are discouraged use x instead - "UP007", # Use X | Y for type annotations "UP030", # Use implicit references for positional format fields "UP031", # Use format specifiers instead of percent format "UP032", # Use f-string instead of `format` call diff --git a/scripts/update_flatpak_manifest.py b/scripts/update_flatpak_manifest.py index 875ec009e..881f21283 100755 --- a/scripts/update_flatpak_manifest.py +++ b/scripts/update_flatpak_manifest.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -from typing import Optional import json import logging @@ -24,7 +23,7 @@ def get_package_type(module: ruamel.yaml.comments.CommentedMap) -> str: return 'sdist' def get_current_version(module: ruamel.yaml.comments.CommentedMap - ) -> tuple[Optional[str], Optional[str]]: + ) -> tuple[str | None, str | None]: name = module['name'].replace('python3-','') url = module['sources'][0]['url'] if url.endswith('.git'): @@ -38,8 +37,8 @@ def get_current_version(module: ruamel.yaml.comments.CommentedMap def get_latest_version(package_name: str, package_type: str, - py_version: Optional[str] - ) -> tuple[str, Optional[str]]: + py_version: str | None + ) -> tuple[str, str | None]: with urlopen(f'{PYPI_INDEX}/{package_name}/json') as f: data = f.read() d = json.loads(data) diff --git a/win/misc/depcheck.py b/win/misc/depcheck.py index 2f965d539..6bebe3349 100644 --- a/win/misc/depcheck.py +++ b/win/misc/depcheck.py @@ -9,7 +9,6 @@ # Deletes unneeded DLLs and checks DLL dependencies. -from typing import Optional import logging import os @@ -76,7 +75,7 @@ def get_dependencies(filename: str) -> list[str]: return deps -def find_lib(root: str, name: str) -> Optional[str]: +def find_lib(root: str, name: str) -> str | None: search_path = os.path.join(root, 'bin') if os.path.exists(os.path.join(search_path, name)): return os.path.join(search_path, name) |