diff --git a/kuhy_credit/kuhy_credit/demo.py b/kuhy_credit/kuhy_credit/demo.py new file mode 100644 index 0000000..011cd8e --- /dev/null +++ b/kuhy_credit/kuhy_credit/demo.py @@ -0,0 +1,40 @@ +"""Tk demo: a gatelock-sized window with the credit in the bottom-right corner. + + python -m kuhy_credit.demo [--light] + +Nothing opens until you click the logo and then the panel. +""" + +from __future__ import annotations + +import argparse +import tkinter as tk +from typing import TYPE_CHECKING + +from kuhy_credit._data import DARK, LIGHT, SPACE_MD +from kuhy_credit.tk import KuhyCredit + +if TYPE_CHECKING: + from collections.abc import Callable + + +def build( + root: tk.Tk, *, theme: str = "dark", opener: Callable[[str], object] | None = None +) -> KuhyCredit: + """Fill ``root`` with a themed demo window and return its credit.""" + root.geometry("640x400") + root.configure(bg=(DARK if theme == "dark" else LIGHT)["surface"]) + credit = KuhyCredit(root, theme=theme, opener=opener) + credit.place(relx=1.0, rely=1.0, x=-SPACE_MD, y=-SPACE_MD, anchor="se") + return credit + + +def main(argv: list[str] | None = None, *, root: tk.Tk | None = None) -> int: + """Run the demo window; returns the exit code.""" + parser = argparse.ArgumentParser(description="kuhy credit Tk demo") + parser.add_argument("--light", action="store_true", help="light theme") + args = parser.parse_args(argv) + win = root or tk.Tk() + build(win, theme="light" if args.light else "dark") + win.mainloop() + return 0 diff --git a/kuhy_credit/kuhy_credit/tk.py b/kuhy_credit/kuhy_credit/tk.py new file mode 100644 index 0000000..665440e --- /dev/null +++ b/kuhy_credit/kuhy_credit/tk.py @@ -0,0 +1,143 @@ +"""The Tkinter credit: an M1 logo button that opens a "Created by kuhy" panel. + + credit = KuhyCredit(parent) # a Canvas: pack/grid/place it + credit.place(relx=1, rely=1, anchor="se") + +A click, Enter or Space on the logo opens a small panel (logo + text) placed +in the toplevel next to the logo. A click, Enter or Space on the panel opens +the website through ``opener`` (default: a new browser tab) and closes it. +Escape, a click anywhere else in the window and a second logo click close it. + +Tk draws no rounded corners and exposes no accessibility tree, so the radius +token and the accessible name have no Tk form; keyboard focus does. +""" + +from __future__ import annotations + +import tkinter as tk +import webbrowser +from typing import TYPE_CHECKING + +from kuhy_credit._data import ( + DARK, + FOCUS, + LIGHT, + LOGO_FIELD, + LOGO_SHAPES, + LOGO_SIZE, + SPACE_MD, + SPACE_SM, + TEXT, + TEXT_BODY, + URL, +) + +if TYPE_CHECKING: + from collections.abc import Callable + +_THEMES = {"dark": DARK, "light": LIGHT} +_KEYS = ("", "") + + +def _draw_logo(canvas: tk.Canvas, size: int) -> None: + """Draw the field and every logo polygon, scaled to ``size`` px. + + Canvas coordinates start at the outer edge, so the drawing is shifted + past the focus ring; the field colour is also the canvas background. + """ + inset = int(canvas.cget("highlightthickness")) + scale = size / LOGO_SIZE + canvas.configure(bg=LOGO_FIELD) + canvas.create_rectangle(inset, inset, inset + size, inset + size, fill=LOGO_FIELD, width=0) + for fill, points in LOGO_SHAPES: + coords = [inset + p * scale for p in points] + canvas.create_polygon(coords, fill=fill, width=0) + + +def _new_tab(url: str) -> None: + webbrowser.open(url, new=2) + + +class KuhyCredit(tk.Canvas): + """The logo button; owns the panel it opens.""" + + def __init__( + self, + parent: tk.Misc, + *, + theme: str = "dark", + size: int = 48, + opener: Callable[[str], object] | None = None, + ) -> None: + """Build the logo in ``parent`` and the (hidden) panel in its toplevel.""" + if theme not in _THEMES: + msg = f"theme must be one of {sorted(_THEMES)}, got {theme!r}" + raise ValueError(msg) + pal = _THEMES[theme] + super().__init__( + parent, width=size, height=size, highlightthickness=2, takefocus=1, + highlightcolor=FOCUS, highlightbackground=pal["surface"], cursor="hand2", + ) # fmt: skip + _draw_logo(self, size) + self._open_url = opener or _new_tab + self._top = self.winfo_toplevel() + self.panel = tk.Frame( + self._top, bg=pal["surface"], padx=SPACE_MD, pady=SPACE_MD, takefocus=1, + highlightthickness=1, highlightbackground=pal["border"], highlightcolor=FOCUS, + cursor="hand2", + ) # fmt: skip + self.panel_logo = tk.Canvas(self.panel, width=size, height=size, highlightthickness=0) + _draw_logo(self.panel_logo, size) + self.panel_logo.pack(side="left") + self.label = tk.Label( + self.panel, text=TEXT, bg=pal["surface"], fg=pal["text"], font=("Arial", -TEXT_BODY) + ) + self.label.pack(side="left", padx=(SPACE_SM, 0)) + self.is_open = False + self.bind("", self._toggle) + for widget in (self.panel, self.panel_logo, self.label): + widget.bind("", self._activate) + for key in _KEYS: + self.bind(key, self._toggle) + self.panel.bind(key, self._activate) + self._top.bind("", self._escape, add="+") + self._top.bind("", self._outside, add="+") + + def open(self) -> None: + """Show the panel beside the logo, on the side with more room.""" + self._top.update_idletasks() + lx = self.winfo_rootx() - self._top.winfo_rootx() + ly = self.winfo_rooty() - self._top.winfo_rooty() + lw, lh = self.winfo_width(), self.winfo_height() + pw, ph = self.panel.winfo_reqwidth(), self.panel.winfo_reqheight() + below = ly + lh / 2 < self._top.winfo_height() / 2 + y = ly + lh + SPACE_SM if below else ly - SPACE_SM - ph + x = lx if lx + lw / 2 < self._top.winfo_width() / 2 else lx + lw - pw + self.panel.place(x=max(0, x), y=max(0, y)) + self.panel.lift() + self.panel.focus_set() + self.is_open = True + + def close(self) -> None: + """Hide the panel.""" + self.panel.place_forget() + self.is_open = False + + def _toggle(self, _event: tk.Event | None = None) -> None: + if self.is_open: + self.close() + else: + self.open() + + def _activate(self, _event: tk.Event | None = None) -> None: + self.close() + self._open_url(URL) + + def _escape(self, _event: tk.Event | None = None) -> None: + if self.is_open: + self.close() + self.focus_set() + + def _outside(self, event: tk.Event) -> None: + if self.is_open and event.widget not in (self, self.panel, self.panel_logo, self.label): + self.close() diff --git a/kuhy_credit/pyproject.toml b/kuhy_credit/pyproject.toml index 7399e12..432acab 100644 --- a/kuhy_credit/pyproject.toml +++ b/kuhy_credit/pyproject.toml @@ -21,12 +21,16 @@ target-version = "py314" line-length = 100 extend-exclude = ["web", "flutter", "godot"] +# The generated data file wraps itself; the formatter would explode it. +[tool.ruff.format] +exclude = ["kuhy_credit/_data.py"] + [tool.ruff.lint] select = ["ALL"] ignore = ["D203", "D213", "COM812", "ISC001", "S603", "S607", "CPY001"] [tool.ruff.lint.per-file-ignores] -"tests/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001", "E501"] +"tests/*.py" = ["ANN", "ARG", "D", "TC", "PLC0415", "PLR2004", "S101", "SLF001", "E501"] "kuhy_credit/_data.py" = ["E501"] # The generator and the terminal helper are CLIs: printing is their output. "generator/generate.py" = ["T201"] @@ -56,4 +60,4 @@ omit = ["*/tests/*"] [tool.coverage.report] fail_under = 100 show_missing = true -exclude_lines = ["pragma: no cover", 'if __name__ == "__main__":'] +exclude_lines = ["pragma: no cover", 'if __name__ == "__main__":', "if TYPE_CHECKING:"] diff --git a/kuhy_credit/tests/conftest.py b/kuhy_credit/tests/conftest.py new file mode 100644 index 0000000..ebb022a --- /dev/null +++ b/kuhy_credit/tests/conftest.py @@ -0,0 +1,31 @@ +"""A real Tk root per test. Run under xvfb-run, never on kuhy's display.""" + +from __future__ import annotations + +import tkinter as tk +from collections.abc import Iterator + +import pytest + + +@pytest.fixture +def root() -> Iterator[tk.Tk]: + win = tk.Tk() + win.geometry("480x320+0+0") + yield win + win.destroy() + + +class Opener: + """Stands in for the browser launch: records URLs, opens nothing.""" + + def __init__(self) -> None: + self.urls: list[str] = [] + + def __call__(self, url: str) -> None: + self.urls.append(url) + + +@pytest.fixture +def opener() -> Opener: + return Opener() diff --git a/kuhy_credit/tests/test_tk.py b/kuhy_credit/tests/test_tk.py new file mode 100644 index 0000000..04f5a4c --- /dev/null +++ b/kuhy_credit/tests/test_tk.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import tkinter as tk +import webbrowser + +import pytest + +from kuhy_credit import TEXT, URL +from kuhy_credit import tk as credit_tk +from kuhy_credit._data import DARK, LIGHT, LOGO_SHAPES + + +def _make(root: tk.Tk, opener, *, theme: str = "dark", corner: str = "se") -> credit_tk.KuhyCredit: + credit = credit_tk.KuhyCredit(root, theme=theme, opener=opener) + rel = {"se": (1.0, 1.0), "nw": (0.0, 0.0)}[corner] + credit.place(relx=rel[0], rely=rel[1], anchor=corner) + root.update() + return credit + + +def _click(widget: tk.Misc) -> None: + widget.event_generate("", x=2, y=2) + widget.update() + + +def test_logo_draws_field_and_every_shape(root, opener) -> None: + credit = _make(root, opener) + assert len(credit.find_all()) == 1 + len(LOGO_SHAPES) + assert not credit.is_open + + +def test_logo_click_opens_panel_with_logo_and_text(root, opener) -> None: + credit = _make(root, opener) + _click(credit) + assert credit.is_open + assert credit.panel.winfo_ismapped() + assert credit.label.cget("text") == TEXT + assert len(credit.panel_logo.find_all()) == 1 + len(LOGO_SHAPES) + assert opener.urls == [] + + +@pytest.mark.parametrize("target", ["panel", "label", "panel_logo"]) +def test_panel_click_opens_the_url_and_closes(root, opener, target: str) -> None: + credit = _make(root, opener) + _click(credit) + _click(getattr(credit, target)) + assert opener.urls == [URL] + assert not credit.is_open + + +def test_escape_closes_without_opening(root, opener) -> None: + credit = _make(root, opener) + _click(credit) + credit.panel.event_generate("") + root.update() + assert not credit.is_open + assert opener.urls == [] + + +def test_outside_click_closes(root, opener) -> None: + other = tk.Frame(root, width=50, height=50) + other.place(x=200, y=100) + credit = _make(root, opener) + _click(credit) + _click(other) + assert not credit.is_open + assert opener.urls == [] + + +def test_second_logo_click_closes_and_stays_closed(root, opener) -> None: + credit = _make(root, opener) + _click(credit) + _click(credit) + root.update() + assert not credit.is_open + assert opener.urls == [] + + +@pytest.mark.parametrize("key", ["", ""]) +def test_keyboard_opens_panel_then_url(root, opener, key: str) -> None: + credit = _make(root, opener) + assert int(credit.cget("takefocus")) == 1 + assert root.tk_focusNext() is credit # Tab reaches the logo + credit.focus_force() + root.update() + credit.event_generate(key) + root.update() + assert credit.is_open + assert root.focus_get() is credit.panel + credit.panel.event_generate(key) + root.update() + assert opener.urls == [URL] + + +def test_click_outside_when_closed_is_ignored(root, opener) -> None: + credit = _make(root, opener) + _click(root) + assert not credit.is_open + + +@pytest.mark.parametrize(("theme", "pal"), [("dark", DARK), ("light", LIGHT)]) +def test_theme_colours_come_from_tokens(root, opener, theme: str, pal: dict) -> None: + credit = _make(root, opener, theme=theme) + assert credit.panel.cget("bg") == pal["surface"] + assert credit.panel.cget("highlightbackground") == pal["border"] + assert credit.label.cget("fg") == pal["text"] + + +def test_unknown_theme_is_rejected(root, opener) -> None: + with pytest.raises(ValueError, match="theme"): + credit_tk.KuhyCredit(root, theme="blue", opener=opener) + + +def test_panel_sits_above_a_bottom_right_logo(root, opener) -> None: + credit = _make(root, opener, corner="se") + _click(credit) + assert credit.panel.winfo_y() < credit.winfo_y() + assert credit.panel.winfo_x() + credit.panel.winfo_width() <= root.winfo_width() + + +def test_panel_sits_below_a_top_left_logo(root, opener) -> None: + credit = _make(root, opener, corner="nw") + _click(credit) + assert credit.panel.winfo_y() > credit.winfo_y() + assert credit.panel.winfo_x() == credit.winfo_x() + + +def test_default_opener_uses_a_new_browser_tab(monkeypatch: pytest.MonkeyPatch, root) -> None: + seen = [] + monkeypatch.setattr(webbrowser, "open", lambda url, new=0: seen.append((url, new))) + credit = _make(root, None) + _click(credit) + _click(credit.panel) + assert seen == [(URL, 2)] + + +def test_escape_when_closed_keeps_focus_where_it_is(root, opener) -> None: + entry = tk.Entry(root) + entry.place(x=10, y=10) + _make(root, opener) + entry.focus_force() + root.update() + entry.event_generate("") + root.update() + assert root.focus_get() is entry diff --git a/kuhy_credit/tests/test_tk_e2e.py b/kuhy_credit/tests/test_tk_e2e.py new file mode 100644 index 0000000..fcc41a9 --- /dev/null +++ b/kuhy_credit/tests/test_tk_e2e.py @@ -0,0 +1,50 @@ +"""E2E: the demo window, two pointer clicks hit-tested at screen coordinates.""" + +from __future__ import annotations + +import tkinter as tk + +import pytest + +from kuhy_credit import URL, demo + + +def _click_at_centre_of(root: tk.Tk, widget: tk.Misc) -> None: + """Click whatever widget sits under the centre of ``widget`` on screen.""" + root.update() + x = widget.winfo_rootx() + widget.winfo_width() // 2 + y = widget.winfo_rooty() + widget.winfo_height() // 2 + hit = root.winfo_containing(x, y) + assert hit is not None + hit.event_generate("", x=x - hit.winfo_rootx(), y=y - hit.winfo_rooty()) + root.update() + + +@pytest.mark.parametrize("theme", ["dark", "light"]) +def test_two_clicks_open_the_website(root, opener, theme: str) -> None: + credit = demo.build(root, theme=theme, opener=opener) + _click_at_centre_of(root, credit) + assert credit.is_open + assert opener.urls == [] + _click_at_centre_of(root, credit.label) + assert opener.urls == [URL] + assert not credit.is_open + + +def test_main_runs_the_window(root, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(root, "mainloop", lambda: None) + assert demo.main(["--light"], root=root) == 0 + assert demo.main([], root=root) == 0 + + +def test_main_creates_its_own_root(monkeypatch: pytest.MonkeyPatch) -> None: + made = [] + + class FakeTk(tk.Tk): + def mainloop(self, n: int = 0) -> None: + made.append(self) + self.destroy() + + monkeypatch.setattr(tk, "Tk", FakeTk) + assert demo.main([]) == 0 + assert len(made) == 1