More typing work

This commit is contained in:
Kovid Goyal 2020-03-06 08:35:23 +05:30
parent 686b5f297e
commit 8a34fede55
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
8 changed files with 56 additions and 34 deletions

View File

@ -13,13 +13,13 @@ def icat(args):
def list_fonts(args): def list_fonts(args):
from kitty.fonts.list import main from kitty.fonts.list import main as list_main
main(args) list_main(args)
def remote_control(args): def remote_control(args):
from kitty.remote_control import main from kitty.remote_control import main as rc_main
main(args) rc_main(args)
def runpy(args): def runpy(args):
@ -35,8 +35,8 @@ def hold(args):
def complete(args): def complete(args):
from kitty.complete import main from kitty.complete import main as complete_main
main(args[1:], entry_points, namespaced_entry_points) complete_main(args[1:], entry_points, namespaced_entry_points)
def launch(args): def launch(args):
@ -92,10 +92,10 @@ def setup_openssl_environment():
if 'SSL_CERT_FILE' not in os.environ and 'SSL_CERT_DIR' not in os.environ: if 'SSL_CERT_FILE' not in os.environ and 'SSL_CERT_DIR' not in os.environ:
if os.access('/etc/pki/tls/certs/ca-bundle.crt', os.R_OK): if os.access('/etc/pki/tls/certs/ca-bundle.crt', os.R_OK):
os.environ['SSL_CERT_FILE'] = '/etc/pki/tls/certs/ca-bundle.crt' os.environ['SSL_CERT_FILE'] = '/etc/pki/tls/certs/ca-bundle.crt'
sys.kitty_ssl_env_var = 'SSL_CERT_FILE' setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_FILE')
elif os.path.isdir('/etc/ssl/certs'): elif os.path.isdir('/etc/ssl/certs'):
os.environ['SSL_CERT_DIR'] = '/etc/ssl/certs' os.environ['SSL_CERT_DIR'] = '/etc/ssl/certs'
sys.kitty_ssl_env_var = 'SSL_CERT_DIR' setattr(sys, 'kitty_ssl_env_var', 'SSL_CERT_DIR')
def main(): def main():
@ -109,8 +109,8 @@ def main():
elif first_arg.startswith('+'): elif first_arg.startswith('+'):
namespaced(['+', first_arg[1:]] + sys.argv[2:]) namespaced(['+', first_arg[1:]] + sys.argv[2:])
else: else:
from kitty.main import main from kitty.main import main as kitty_main
main() kitty_main()
else: else:
func(sys.argv[1:]) func(sys.argv[1:])

View File

@ -12,7 +12,9 @@ from functools import partial
from html.entities import html5 from html.entities import html5
from itertools import groupby from itertools import groupby
from operator import itemgetter from operator import itemgetter
from typing import DefaultDict, Dict, Set from typing import (
DefaultDict, Dict, Generator, Iterable, List, Optional, Set, Tuple, Union
)
from urllib.request import urlopen from urllib.request import urlopen
os.chdir(os.path.dirname(os.path.abspath(__file__))) os.chdir(os.path.dirname(os.path.abspath(__file__)))
@ -44,8 +46,8 @@ def get_data(fname, folder='UCD'):
# Map of class names to set of codepoints in class # Map of class names to set of codepoints in class
class_maps: Dict[str, Set[int]] = {} class_maps: Dict[str, Set[int]] = {}
all_symbols = set() all_symbols: Set[int] = set()
name_map = {} name_map: Dict[int, str] = {}
word_search_map: DefaultDict[str, Set[int]] = defaultdict(set) word_search_map: DefaultDict[str, Set[int]] = defaultdict(set)
zwj = 0x200d zwj = 0x200d
marks = set(emoji_skin_tone_modifiers) | {zwj} marks = set(emoji_skin_tone_modifiers) | {zwj}
@ -60,7 +62,7 @@ def parse_ucd():
if len(w) > 1: if len(w) > 1:
word_search_map[w.lower()].add(c) word_search_map[w.lower()].add(c)
first = None first: Optional[int] = None
for word, c in html5.items(): for word, c in html5.items():
if len(c) == 1: if len(c) == 1:
add_word(word.rstrip(';'), ord(c)) add_word(word.rstrip(';'), ord(c))
@ -78,7 +80,7 @@ def parse_ucd():
category = parts[2] category = parts[2]
s = class_maps.setdefault(category, set()) s = class_maps.setdefault(category, set())
desc = parts[1] desc = parts[1]
codepoints = (codepoint,) codepoints: Union[Tuple[int, ...], Iterable[int]] = (codepoint,)
if first is None: if first is None:
if desc.endswith(', First>'): if desc.endswith(', First>'):
first = codepoint first = codepoint
@ -104,8 +106,8 @@ def split_two(line):
spec, rest = line.split(';', 1) spec, rest = line.split(';', 1)
spec, rest = spec.strip(), rest.strip().split(' ', 1)[0].strip() spec, rest = spec.strip(), rest.strip().split(' ', 1)[0].strip()
if '..' in spec: if '..' in spec:
chars = tuple(map(lambda x: int(x, 16), filter(None, spec.split('.')))) chars_ = tuple(map(lambda x: int(x, 16), filter(None, spec.split('.'))))
chars = set(range(chars[0], chars[1] + 1)) chars = set(range(chars_[0], chars_[1] + 1))
else: else:
chars = {int(spec, 16)} chars = {int(spec, 16)}
return chars, rest return chars, rest
@ -137,7 +139,7 @@ ambiguous: Set[int] = set()
def parse_eaw(): def parse_eaw():
global doublewidth, ambiguous global doublewidth, ambiguous
seen = set() seen: Set[int] = set()
for line in get_data('ucd/EastAsianWidth.txt'): for line in get_data('ucd/EastAsianWidth.txt'):
chars, eaw = split_two(line) chars, eaw = split_two(line)
if eaw == 'A': if eaw == 'A':
@ -153,7 +155,7 @@ def parse_eaw():
doublewidth |= set(range(0x30000, 0x3FFFD + 1)) - seen doublewidth |= set(range(0x30000, 0x3FFFD + 1)) - seen
def get_ranges(items): def get_ranges(items: List[int]) -> Generator[Union[int, Tuple[int, int]], None, None]:
items.sort() items.sort()
for k, g in groupby(enumerate(items), lambda m: m[0]-m[1]): for k, g in groupby(enumerate(items), lambda m: m[0]-m[1]):
group = tuple(map(itemgetter(1), g)) group = tuple(map(itemgetter(1), g))
@ -221,7 +223,7 @@ def gen_emoji():
def category_test(name, p, classes, comment, static=False, extra_chars=frozenset(), exclude=frozenset()): def category_test(name, p, classes, comment, static=False, extra_chars=frozenset(), exclude=frozenset()):
static = 'static inline ' if static else '' static = 'static inline ' if static else ''
chars = set() chars: Set[int] = set()
for c in classes: for c in classes:
chars |= class_maps[c] chars |= class_maps[c]
chars |= extra_chars chars |= extra_chars
@ -252,7 +254,7 @@ def codepoint_to_mark_map(p, mark_map):
def classes_to_regex(classes, exclude=''): def classes_to_regex(classes, exclude=''):
chars = set() chars: Set[int] = set()
for c in classes: for c in classes:
chars |= class_maps[c] chars |= class_maps[c]
for c in map(ord, exclude): for c in map(ord, exclude):
@ -300,7 +302,9 @@ def gen_ucd():
p('}\n') p('}\n')
with open('kitty/unicode-data.h') as f: with open('kitty/unicode-data.h') as f:
unicode_data = f.read() unicode_data = f.read()
expected = int(re.search(r'^#define VS15 (\d+)', unicode_data, re.M).group(1)) m = re.search(r'^#define VS15 (\d+)', unicode_data, re.M)
if m is not None:
expected = int(m.group(1))
if rmap[0xfe0e] != expected: if rmap[0xfe0e] != expected:
raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format( raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format(
rmap[0xfe0e], rmap[0xfe0f] rmap[0xfe0e], rmap[0xfe0f]
@ -364,7 +368,7 @@ def gen_names():
# The trie # The trie
p(f'typedef struct {{ uint32_t children_offset; uint32_t match_offset; }} word_trie;\n') p(f'typedef struct {{ uint32_t children_offset; uint32_t match_offset; }} word_trie;\n')
all_trie_nodes = [] all_trie_nodes: List['TrieNode'] = []
class TrieNode: class TrieNode:
@ -411,7 +415,7 @@ def gen_names():
def gen_wcwidth(): def gen_wcwidth():
seen = set() seen: Set[int] = set()
def add(p, comment, chars_, ret): def add(p, comment, chars_, ret):
chars = chars_ - seen chars = chars_ - seen

View File

@ -46,8 +46,8 @@ def init_env(env, pkg_config, at_least_version, test_compile, module='x11'):
elif module == 'cocoa': elif module == 'cocoa':
ans.cppflags.append('-DGL_SILENCE_DEPRECATION') ans.cppflags.append('-DGL_SILENCE_DEPRECATION')
for f in 'Cocoa IOKit CoreFoundation CoreVideo'.split(): for f_ in 'Cocoa IOKit CoreFoundation CoreVideo'.split():
ans.ldpaths.extend(('-framework', f)) ans.ldpaths.extend(('-framework', f_))
elif module == 'wayland': elif module == 'wayland':
at_least_version('wayland-protocols', *sinfo['wayland_protocols']) at_least_version('wayland-protocols', *sinfo['wayland_protocols'])

View File

@ -127,16 +127,16 @@ def screen_manipulate_title_stack(op, which):
write(CSI + '%d;%dt' % (op, which)) write(CSI + '%d;%dt' % (op, which))
def report_device_attributes(mode, char): def report_device_attributes(mode: int, char: int) -> None:
x = CSI x = CSI
if char: if char:
x += ord(char) x += chr(char)
if mode: if mode:
x += str(mode) x += str(mode)
write(CSI + x + 'c') write(CSI + x + 'c')
def write_osc(code, string=''): def write_osc(code: int, string='') -> None:
if string: if string:
string = ';' + string string = ';' + string
write(OSC + str(code) + string + '\x07') write(OSC + str(code) + string + '\x07')

View File

@ -0,0 +1,11 @@
try:
from typing import TypedDict
except ImportError:
TypedDict = dict
class ListedFont(TypedDict):
family: str
full_name: str
postscript_name: str
is_monospace: bool

View File

@ -3,10 +3,13 @@
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import re import re
from typing import Generator
from kitty.fast_data_types import coretext_all_fonts from kitty.fast_data_types import coretext_all_fonts
from kitty.utils import log_error from kitty.utils import log_error
from . import ListedFont
attr_map = {(False, False): 'font_family', attr_map = {(False, False): 'font_family',
(True, False): 'bold_font', (True, False): 'bold_font',
(False, True): 'italic_font', (False, True): 'italic_font',
@ -32,7 +35,7 @@ def all_fonts_map():
return ans return ans
def list_fonts(): def list_fonts() -> Generator[ListedFont, None, None]:
for fd in coretext_all_fonts(): for fd in coretext_all_fonts():
f = fd['family'] f = fd['family']
if f: if f:

View File

@ -4,12 +4,15 @@
import re import re
from functools import lru_cache from functools import lru_cache
from typing import Generator
from kitty.fast_data_types import ( from kitty.fast_data_types import (
FC_SLANT_ITALIC, FC_SLANT_ROMAN, FC_WEIGHT_BOLD, FC_WEIGHT_REGULAR, FC_DUAL, FC_MONO, FC_SLANT_ITALIC, FC_SLANT_ROMAN, FC_WEIGHT_BOLD,
fc_list, fc_match as fc_match_impl, FC_DUAL, FC_MONO FC_WEIGHT_REGULAR, fc_list, fc_match as fc_match_impl
) )
from . import ListedFont
attr_map = {(False, False): 'font_family', attr_map = {(False, False): 'font_family',
(True, False): 'bold_font', (True, False): 'bold_font',
(False, True): 'italic_font', (False, True): 'italic_font',
@ -39,7 +42,7 @@ def all_fonts_map(monospaced=True):
return create_font_map(ans) return create_font_map(ans)
def list_fonts(): def list_fonts() -> Generator[ListedFont, None, None]:
for fd in fc_list(): for fd in fc_list():
f = fd.get('family') f = fd.get('family')
if f: if f:

View File

@ -4,6 +4,7 @@
import sys import sys
from kitty.constants import is_macos from kitty.constants import is_macos
from typing import Sequence
if is_macos: if is_macos:
from .core_text import list_fonts from .core_text import list_fonts
@ -19,7 +20,7 @@ def create_family_groups(monospaced=True):
return g return g
def main(argv): def main(argv: Sequence[str]) -> None:
psnames = '--psnames' in argv psnames = '--psnames' in argv
isatty = sys.stdout.isatty() isatty = sys.stdout.isatty()
groups = create_family_groups() groups = create_family_groups()