Skip to content

Commit

Permalink
some typing fixes in ui
Browse files Browse the repository at this point in the history
  • Loading branch information
ilius committed Nov 24, 2024
1 parent ef40464 commit ae8e072
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 18 deletions.
3 changes: 2 additions & 1 deletion pyglossary/ui/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def getEntryFilterConfigPair(name: str) -> tuple[str, Option]:


class UIBase:
configDefDict = OrderedDict(
configDefDict: dict[str, Option] = OrderedDict(
[
(
"log_time",
Expand Down Expand Up @@ -228,6 +228,7 @@ def loadConfig(
from pyglossary.json_utils import jsonToData

data = jsonToData(fread(rootConfJsonFile))
assert isinstance(data, dict)
if user and isfile(confJsonFile):
try:
userData = jsonToData(fread(confJsonFile))
Expand Down
8 changes: 5 additions & 3 deletions pyglossary/ui/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import logging
import sys
from dataclasses import dataclass
from typing import Any
from typing import Any, cast

from pyglossary import core, logger # essential
from pyglossary.langs import langDict
Expand Down Expand Up @@ -72,7 +72,7 @@
# -v (verbose or version?)
# -r (reverse or read-options)

log = None
log: logger.Logger | None = None


def validateLangStr(st: str) -> str | None:
Expand All @@ -82,6 +82,7 @@ def validateLangStr(st: str) -> str | None:
lang = langDict[st.lower()]
if lang:
return lang.name
assert log
log.error(f"unknown language {st!r}")
return None

Expand Down Expand Up @@ -145,7 +146,7 @@ def mainPrepare() -> tuple[bool, MainPrepareResult | None]:
print(f"PyGlossary {getVersion()}")
return True, None

log = logging.getLogger("pyglossary")
log = cast(logger.Logger, logging.getLogger("pyglossary"))

if args.ui_type == "none":
args.noColor = True
Expand Down Expand Up @@ -273,6 +274,7 @@ def main() -> None: # noqa: PLR0912

from pyglossary.ui.runner import getRunner

assert log
run = getRunner(res.args, res.uiType, log)
if run is None:
sys.exit(1)
Expand Down
31 changes: 17 additions & 14 deletions pyglossary/ui/ui_cmd_interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,15 @@

if TYPE_CHECKING:
from collections.abc import Iterable
from typing import Literal

from prompt_toolkit.completion import CompleteEvent
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text import StyleAndTextTuples
from prompt_toolkit.key_binding.key_processor import KeyPressEvent

from pyglossary.option import Option
from pyglossary.plugin_prop import PluginProp

import prompt_toolkit
from prompt_toolkit import ANSI
from prompt_toolkit import prompt as promptLow
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
Expand Down Expand Up @@ -109,29 +112,29 @@ def formatMessage(self):
# msg = ANSI(msg) # NOT SUPPORTED
return msg # noqa: RET504

def __pt_formatted_text__(self): # noqa: PLW3201
def __pt_formatted_text__(self) -> StyleAndTextTuples: # noqa: PLW3201
return [("", self.formatMessage())]


def checkbox_prompt(
message: str,
default: bool,
) -> PromptSession[bool]:
) -> bool:
"""Create a `PromptSession` object for the 'confirm' function."""
bindings = KeyBindings()

check = MiniCheckBoxPrompt(message=message, value=default)

@bindings.add(" ")
def space(_event: "prompt_toolkit.E") -> None:
def space(_event: KeyPressEvent) -> None:
check.value = not check.value
# cursor_pos = check.formatMessage().find("[") + 1
# cur_cursor_pos = session.default_buffer.cursor_position
# print(f"{cur_cursor_pos=}, {cursor_pos=}")
# session.default_buffer.cursor_position = cursor_pos

@bindings.add(Keys.Any)
def _(_event: "prompt_toolkit.E") -> None:
def _(_event: KeyPressEvent) -> None:
"""Disallow inserting other text."""

complete_message = check
Expand Down Expand Up @@ -186,7 +189,7 @@ def dataToPrettyJson(data, ensure_ascii=False, sort_keys=False):


def prompt(
message: str,
message: ANSI | str,
multiline: bool = False,
**kwargs,
):
Expand Down Expand Up @@ -232,8 +235,8 @@ def file_filter(_filename: str) -> bool:

def get_completions(
self,
document: "prompt_toolkit.Document",
complete_event: "prompt_toolkit.CompleteEvent",
document: Document,
complete_event: CompleteEvent,
) -> Iterable[Completion]:
text = document.text_before_cursor

Expand Down Expand Up @@ -271,10 +274,10 @@ def __init__(
self._outputFilename = ""
self._inputFormat = ""
self._outputFormat = ""
self.config = None
self._readOptions = None
self._writeOptions = None
self._convertOptions = None
self.config = {}
self._readOptions = {}
self._writeOptions = {}
self._convertOptions = {}
ui_cmd.UI.__init__(
self,
progressbar=progressbar,
Expand Down Expand Up @@ -913,7 +916,7 @@ def askFinalAction(self) -> str | None:
continue
return action

def askFinalOptions(self) -> bool | Literal["back"]:
def askFinalOptions(self) -> bool | str:
while True:
try:
action = self.askFinalAction()
Expand Down

0 comments on commit ae8e072

Please sign in to comment.