Skip to content

Commit

Permalink
More type fixes (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickMassot authored Feb 4, 2024
1 parent 4f67b98 commit e2b21ca
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 73 deletions.
19 changes: 8 additions & 11 deletions kalamine/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from contextlib import contextmanager
from importlib import metadata
from pathlib import Path
from typing import List, Literal, Union
from typing import List, Literal, Union, Iterator

import click

Expand Down Expand Up @@ -47,7 +47,7 @@ def make_all(layout: KeyboardLayout, output_dir_path: Path) -> None:
"""

@contextmanager
def file_creation_context(ext: str = "") -> Path:
def file_creation_context(ext: str = "") -> Iterator[Path]:
"""Generate an output file path for extension EXT, return it and finally echo info."""
path = output_dir_path / (layout.meta["fileName"] + ext)
yield path
Expand Down Expand Up @@ -103,7 +103,7 @@ def file_creation_context(ext: str = "") -> Path:
type=click.Path(),
help="Keyboard drivers to generate.",
)
def make(layout_descriptors: List[Path], out: Union[Path, Literal["all"]]):
def make(layout_descriptors: List[Path], out: Union[Path, Literal["all"]]) -> None:
"""Convert TOML/YAML descriptions into OS-specific keyboard drivers."""

for input_file in layout_descriptors:
Expand All @@ -114,14 +114,11 @@ def make(layout_descriptors: List[Path], out: Union[Path, Literal["all"]]):
make_all(layout, Path("dist"))
continue

# Transform out into Path.
out = Path(out)

# quick output: reuse the input name and change the file extension
if out in ["keylayout", "klc", "xkb", "xkb_custom", "svg"]:
output_file = input_file.with_suffix("." + out)
output_file = input_file.with_suffix(f".{out}")
else:
output_file = out
output_file = Path(out)

# detailed output
if output_file.suffix == ".ahk":
Expand Down Expand Up @@ -186,7 +183,7 @@ def make(layout_descriptors: List[Path], out: Union[Path, Literal["all"]]):
@click.option("--geometry", default="ISO", help="Specify keyboard geometry.")
@click.option("--altgr/--no-altgr", default=False, help="Set an AltGr layer.")
@click.option("--1dk/--no-1dk", "odk", default=False, help="Set a custom dead key.")
def create(output_file: Path, geometry: str, altgr: bool, odk: bool):
def create(output_file: Path, geometry: str, altgr: bool, odk: bool) -> None:
"""Create a new TOML layout description."""
base_dir_path = Path(__file__).resolve(strict=True).parent.parent

Expand Down Expand Up @@ -226,8 +223,8 @@ def keymap(layout_name: str, layout_layer: str, layer_name: str = "") -> str:
content += "\n\n"
content += "\n# "
content += "\n# ".join(topic.rstrip().split("\n"))

output_file.write_text(content, "w", encoding="utf-8", newline="\n")
with open(output_file, "w", encoding="utf-8", newline="\n") as file:
file.write(content)
click.echo(f"... {output_file}")


Expand Down
24 changes: 12 additions & 12 deletions kalamine/cli_xkb.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
import sys
import tempfile
from pathlib import Path
from typing import List
from typing import List, Dict, Union, Optional

import click

from .layout import KeyboardLayout
from .xkb_manager import WAYLAND, XKBManager
from .xkb_manager import WAYLAND, XKBManager, Index


@click.group()
def cli():
def cli() -> None:
if platform.system() != "Linux":
sys.exit("This command is only compatible with GNU/Linux, sorry.")

Expand All @@ -22,7 +22,7 @@ def cli():
@click.argument(
"filepath", type=click.Path(exists=True, dir_okay=False, path_type=Path)
)
def apply(filepath: Path):
def apply(filepath: Path) -> None:
"""Apply a Kalamine layout."""

if WAYLAND:
Expand All @@ -42,7 +42,7 @@ def apply(filepath: Path):
@click.argument(
"layouts", nargs=-1, type=click.Path(exists=True, dir_okay=False, path_type=Path)
)
def install(layouts: List[Path]):
def install(layouts: List[Path]) -> None:
"""Install a list of Kalamine layouts."""

if not layouts:
Expand All @@ -55,22 +55,22 @@ def install(layouts: List[Path]):
kb_layouts.append(layout)
kb_locales.add(layout.meta["locale"])

def xkb_install(xkb):
def xkb_install(xkb: XKBManager) -> Index:
for layout in kb_layouts:
xkb.add(layout)
index = xkb.index # gets erased with xkb.update()
xkb.clean()
xkb.update()
print()
print("Successfully installed.")
return index
return dict(index)

# EAFP (Easier to Ask Forgiveness than Permission)
try:
xkb_root = XKBManager(root=True)
xkb_index = xkb_install(xkb_root)
print(f"On XOrg, you can try the layout{'s' if len(layouts) > 1 else ''} with:")
for locale, variants in xkb_index:
for locale, variants in xkb_index.items():
for name in variants.keys():
print(f" setxkbmap {locale} -variant {name}")
print()
Expand All @@ -87,10 +87,10 @@ def xkb_install(xkb):

@cli.command()
@click.argument("mask") # [locale]/[name]
def remove(mask: str):
def remove(mask: str) -> None:
"""Remove a list of Kalamine layouts."""

def xkb_remove(root=False):
def xkb_remove(root:bool = False) -> None:
xkb = XKBManager(root=root)
xkb.clean()
for locale, variants in xkb.list(mask).items():
Expand All @@ -108,11 +108,11 @@ def xkb_remove(root=False):
@cli.command(name="list")
@click.option("-a", "--all", "all_flag", is_flag=True)
@click.argument("mask", default="*")
def list_command(mask, all_flag):
def list_command(mask: str, all_flag: bool) -> None:
"""List installed Kalamine layouts."""

for root in [True, False]:
filtered = {}
filtered: Dict[str, Union[Optional[KeyboardLayout], str]] = {} # Very weird type...

xkb = XKBManager(root=root)
layouts = xkb.list_all(mask) if all_flag else xkb.list(mask)
Expand Down
14 changes: 7 additions & 7 deletions kalamine/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import click
import tomli
import yaml
from lxml import etree
from lxml import etree # type: ignore

from .template import (
ahk_keymap,
Expand Down Expand Up @@ -227,7 +227,7 @@ def __init__(self, filepath: Path) -> None:

self._parse_dead_keys(spc)

def _parse_dead_keys(self, spc):
def _parse_dead_keys(self, spc: Dict[str, str]) -> None:
"""Build a deadkey dict."""

def layout_has_char(char: str) -> bool:
Expand All @@ -241,7 +241,7 @@ def layout_has_char(char: str) -> bool:
return True
return False

all_spaces = []
all_spaces: List[str] = []
for space in ["\u0020", "\u00a0", "\u202f"]:
if layout_has_char(space):
all_spaces.append(space)
Expand All @@ -261,10 +261,10 @@ def layout_has_char(char: str) -> bool:
for key_name in LAYER_KEYS:
if key_name.startswith("-"):
continue
for i in [Layer.ODK_SHIFT, Layer.ODK]:
if key_name in self.layers[i]:
deadkey[self.layers[i.necromance()][key_name]] = self.layers[
i
for layer in [Layer.ODK_SHIFT, Layer.ODK]:
if key_name in self.layers[layer]:
deadkey[self.layers[layer.necromance()][key_name]] = self.layers[
layer
][key_name]
for space in all_spaces:
deadkey[space] = spc["1dk"]
Expand Down
16 changes: 7 additions & 9 deletions kalamine/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
from pathlib import Path

import click
from livereload import Server
from livereload import Server # type: ignore

from .layout import KeyboardLayout


def keyboard_server(file_path: Path) -> None:
kb_layout = KeyboardLayout(file_path)

Expand Down Expand Up @@ -60,22 +59,21 @@ def main_page(layout: KeyboardLayout) -> str:
"""

class LayoutHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
dir_path = os.path.dirname(os.path.realpath(__file__))
www_path = os.path.join(dir_path, "www")
super().__init__(*args, directory=www_path, **kwargs)
def __init__(self, *args, **kwargs) -> None: # type: ignore
kwargs['directory'] = str(Path(__file__).parent / "www")
super().__init__(*args, **kwargs)

def do_GET(self):
def do_GET(self) -> None:
self.send_response(200)

def send(page, content="text/plain", charset="utf-8"):
def send(page: str, content:str = "text/plain", charset:str = "utf-8") -> None:
self.send_header("Content-type", f"{content}; charset={charset}")
self.end_headers()
self.wfile.write(bytes(page, charset))
# self.wfile.write(page.encode(charset))

# XXX always reloads the layout on the root page, never in sub pages
global kb_layout
nonlocal kb_layout
if self.path == "/json":
send(json.dumps(kb_layout.json), content="application/json")
elif self.path == "/keylayout":
Expand Down
14 changes: 7 additions & 7 deletions kalamine/template.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
import json
from typing import TYPE_CHECKING, Dict, List
from typing import TYPE_CHECKING, Dict, List, Tuple

from .utils import DEAD_KEYS, LAYER_KEYS, ODK_ID, Layer, load_data

Expand Down Expand Up @@ -119,12 +119,12 @@ def ahk_keymap(layout: "KeyboardLayout", altgr: bool = False) -> List[str]:
specials = " \u00a0\u202f‘’'\"^`~"
esc_all = True # set to False to ease the debug (more readable AHK script)

def ahk_escape(key):
def ahk_escape(key: str) -> str:
if len(key) == 1:
return f"U+{ord(key):04x}" if esc_all or key in specials else key
return f"{key}`" if key.endswith("`") else key # deadkey identifier

def ahk_actions(symbol):
def ahk_actions(symbol: str) -> Dict[str, str]:
actions = {}
for key, dk in layout.dead_keys.items():
dk_id = ahk_escape(key)
Expand Down Expand Up @@ -348,7 +348,7 @@ def osx_keymap(layout: "KeyboardLayout") -> List[List[str]]:
]
caps = index == 2

def has_dead_keys(letter):
def has_dead_keys(letter: str) -> bool:
if letter in "\u0020\u00a0\u202f": # space
return True
for k in layout.dead_keys:
Expand Down Expand Up @@ -395,7 +395,7 @@ def osx_actions(layout: "KeyboardLayout") -> List[str]:

ret_actions = []

def when(state, action):
def when(state: str, action: str) -> str:
state_attr = f'state="{state}"'.ljust(18)
if action in layout.dead_keys:
action_attr = f"next=\"{DK_INDEX[action].name}\""
Expand All @@ -405,7 +405,7 @@ def when(state, action):
action_attr = f'output="{xml_proof(action)}"'
return f" <when {state_attr} {action_attr} />"

def append_actions(symbol, actions):
def append_actions(symbol: str, actions: List[Tuple[str, str]]) -> None:
ret_actions.append(f'<action id="{xml_proof_id(symbol)}">')
ret_actions.append(when("none", symbol))
for state, out in actions:
Expand Down Expand Up @@ -441,7 +441,7 @@ def append_actions(symbol, actions):
if key in layout.dead_keys:
continue

actions = []
actions: List[Tuple[str, str]] = []
for k in DK_INDEX:
if k in layout.dead_keys:
if key in layout.dead_keys[k]:
Expand Down
Loading

0 comments on commit e2b21ca

Please sign in to comment.