Source code for iskg.base
"""Base Widget class with layout engines (pack/grid/place), event bindings,
style rendering, and widget tree management."""
from __future__ import annotations
import contextlib
import difflib
import json
import warnings
from collections.abc import Callable, Sequence
from typing import Any
_counter: list[int] = [0]
# Stack of active layout containers (Box/HBox/VBox entered via ``with``). When a
# widget is created without an explicit ``parent``, it is automatically parented
# to the top of this stack. This enables a declarative, indentation-based layout
# style without passing ``parent=`` everywhere.
_LAYOUT_STACK: list = []
def _new_id() -> str:
_counter[0] += 1
return f"iw{_counter[0]}"
def _dump_value(value: Any) -> Any:
"""Sanitise a config value for :meth:`Widget.dump`.
Keeps JSON-friendly primitives as-is (truncating long strings),
caps lists/tuples, and falls back to ``repr()`` for callables or any
other non-serialisable object so ``json.dumps(widget.dump())`` never
raises.
"""
if value is None or isinstance(value, (bool, int, float)):
return value
if isinstance(value, str):
return value if len(value) <= 160 else f"{value[:160]}…"
if isinstance(value, (list, tuple)):
items = [_dump_value(v) for v in list(value)[:12]]
if len(value) > 12:
items.append(f"…({len(value) - 12} more)")
return items
return repr(value)
#: Padding accepted by :meth:`Widget.pack` / :meth:`Widget.grid`: either one
#: value applied to both sides, or a tkinter-style ``(before, after)`` sequence.
PadValue = int | Sequence[int]
def _pad_pair(value: Any) -> tuple[int, int]:
"""Normalise padding to ``(left/top, right/bottom)`` pixels.
``5`` → ``(5, 5)`` (the historical behaviour), ``(8, 4)`` → ``(8, 4)``,
``0`` / ``None`` / malformed → ``(0, 0)``. Accepts lists as well as
tuples so values coming from JSON-ish config round-trip.
"""
if isinstance(value, (tuple, list)):
if not value:
return (0, 0)
first = int(value[0])
second = int(value[1]) if len(value) > 1 else first
return (first, second)
if value is None:
return (0, 0)
try:
number = int(value)
except (TypeError, ValueError):
return (0, 0)
return (number, number)
def _pad_css(axis: str, value: Any) -> str:
"""Render ``margin-*`` declarations for a ``padx``/``pady`` value.
``axis`` is ``"x"`` (left/right) or ``"y"`` (top/bottom). Returns ``""``
for zero padding so widgets without explicit padding keep inheriting any
class-level padding (an inline ``padding:0`` would otherwise clobber it).
Emitted as ``margin`` — tkinter semantics: space *around* the widget.
Emitted as ``padding`` it would land *inside* the border-box of
fixed-size widgets (buttons have a fixed height) and create no visual
spacing at all.
"""
first, second = _pad_pair(value)
if not first and not second:
return ""
if axis == "x":
return f"margin-left:{first}px;margin-right:{second}px;"
return f"margin-top:{first}px;margin-bottom:{second}px;"
_CONFIG_TO_CSS: list[tuple[str, str, bool]] = [
("padding", "padding", True),
("bg", "background", False),
("background", "background", False),
("fg", "color", False),
("foreground", "color", False),
("font-size", "font-size", True),
("font-family", "font-family", False),
("font-weight", "font-weight", False),
("border-color", "border-color", False),
("border-width", "border-width", True),
("border-radius", "border-radius", True),
("opacity", "opacity", False),
("text-align", "text-align", False),
("margin", "margin", True),
("cursor", "cursor", False),
("width", "width", True),
("height", "height", True),
("min-width", "min-width", True),
("min-height", "min-height", True),
("max-width", "max-width", True),
("max-height", "max-height", True),
("flex", "flex", False),
("overflow", "overflow", False),
("overflow-x", "overflow-x", False),
("overflow-y", "overflow-y", False),
("gap", "gap", True),
("order", "order", False),
("align-self", "align-self", False),
("justify-self", "justify-self", False),
("align-items", "align-items", False),
("justify-content", "justify-content", False),
("inset", "inset", True),
("top", "top", True),
("right", "right", True),
("bottom", "bottom", True),
("left", "left", True),
("object-fit", "object-fit", False),
("aspect-ratio", "aspect-ratio", False),
("z-index", "z-index", False),
("transform", "transform", False),
("transition", "transition", False),
("white-space", "white-space", False),
("text-overflow", "text-overflow", False),
("line-height", "line-height", False),
]
_PX_KEYS: set[str] = {k for k, _, px in _CONFIG_TO_CSS if px}
# Expected Python types for well-known config keys. Keys not listed here are
# accepted as-is. `None` is always allowed (means "unset"/inherit).
# Note: width/height are intentionally NOT type-checked strictly because they
# accept CSS strings too ("95%", "10px"), which the widgets rely on.
_CONFIG_TYPE_SPECS: dict[str, type | tuple[type, ...]] = {
"visible": bool,
"text": str,
"disabled": bool,
"hidden": bool,
}
def _validate_config_type(key: str, val: Any) -> None:
"""Raise ``TypeError`` if ``val`` has an unexpected type for ``key``."""
spec = _CONFIG_TYPE_SPECS.get(key)
if spec is None or val is None:
return
if not isinstance(val, spec):
expected = spec if isinstance(spec, tuple) else (spec,)
names = " or ".join(t.__name__ for t in expected)
raise TypeError(f"{key!r} expects {names}, got {type(val).__name__}")
def _validate_css_value(key: str, val: Any) -> None:
if key in _PX_KEYS and val is not None and val != "" and isinstance(val, str):
cleaned = val.strip()
if cleaned and not any(c.isdigit() for c in cleaned):
warnings.warn(
f"Numeric CSS key '{key}' received non-numeric string {val!r}. "
f"Expected a number (e.g. 10) or mixed string (e.g. '10px 5px').",
stacklevel=3,
)
# Canonical config keys used across widgets, for typo detection in
# ``__init__`` / ``config()`` (see ``_warn_unknown_config_key``).
_WIDGET_CONFIG_KEYS = frozenset(
{
"active",
"anchor",
"autoscroll",
"checked",
"class",
"color",
"columns",
"command",
"current",
"cursor",
"date",
"delay",
"digits",
"disabled",
"editable",
"expand",
"fit",
"flex",
"font",
"font-family",
"font-size",
"font-weight",
"format",
"foreground",
"from",
"gridlines",
"group",
"height",
"hidden",
"icon",
"icon_size",
"id",
"items",
"justify",
"label",
"max",
"maxlength",
"max_lines",
"max_pts",
"menu",
"military",
"min",
"name",
"orient",
"padding",
"placeholder",
"propagate",
"readonly",
"rows",
"seconds",
"sections",
"selected",
"show_timestamp",
"show_toolbar",
"show_value",
"size",
"smooth",
"src",
"state",
"step",
"style",
"takefocus",
"text",
"textvariable",
"to",
"tooltip",
"units",
"value",
"values",
"variable",
"visible",
"width",
"wrap",
"wraplength",
"y_max",
"y_min",
}
)
_KNOWN_CONFIG_KEYS = frozenset({css_k for css_k, _, _ in _CONFIG_TO_CSS} | _WIDGET_CONFIG_KEYS)
def _warn_unknown_config_key(k: str, key: str) -> None:
"""Warn when a config key looks like a typo of a known widget property.
ISKG intentionally accepts any key (for flexible inline CSS), so we only
warn for *unknown* keys that are very close to a known property (e.g.
``textt`` -> ``text``, ``widht`` -> ``width``), never for arbitrary CSS.
"""
if key.startswith("--"):
return
candidate = key[:-1] if key.endswith("-") else key
if candidate in _KNOWN_CONFIG_KEYS:
return
if "-" in key:
return
matches = difflib.get_close_matches(candidate, _KNOWN_CONFIG_KEYS, n=1, cutoff=0.8)
if matches:
warnings.warn(
f"Unknown widget config key {k!r}; did you mean {matches[0]!r}?",
stacklevel=3,
)
[docs]
class Widget:
"""Base class for all ISKG widgets.
Manages widget identity, parent-child tree, layout configuration,
style rendering, event bindings, and bridge communication with the
JavaScript frontend.
Every concrete widget (Button, Label, Frame, etc.) inherits from this class.
Configuration kwargs and ``.config()`` accept any key. Underscores in keys
are converted to hyphens. Common CSS keys (``fg``, ``bg``, ``font_size``,
``padding``, ``margin``, ``flex``, ``overflow``, etc.) from
``_CONFIG_TO_CSS`` are automatically mapped to inline styles. Keys starting
with ``--`` are treated as CSS custom properties.
Subclasses that take a ``text`` (or comparable) parameter as the
second positional argument may set the class attribute
``_FIRST_POSITIONAL_AS_TEXT = True`` to opt into the
``Label("text")``-style call: any first positional string is moved
into ``text="..."`` automatically. Subclasses that genuinely need a
different first-positional contract (e.g. ``Container`` widgets with
``text`` as a frame title) should leave it as ``False``.
"""
_FIRST_POSITIONAL_AS_TEXT = False
def __init__(self, parent: Widget | None = None, **kwargs: Any) -> None:
# Inherit / set up state before normal param processing so
# ``__init_subclass__`` hooks (if any) can override behaviour.
self._id: str = _new_id()
self._parent: Widget | None = None
self._children: list[Widget] = []
self._config_dict: dict[str, Any] = {}
self._layout_mode: str | None = None
self._layout_info: dict[str, Any] = {}
self._bindings: dict[str, Callable] = {}
self._key_bindings: list[dict[str, Any]] = []
self._destroyed: bool = False
self._app: Any = None
self._textvariable: Any = None
self._variable: Any = None
self._last_sync_js: str = ""
self._last_style_css: str | None = None
self._context_menu: Any = None
self._context_show: bool = False
self._dnd_target: bool = False
for k, v in kwargs.items():
key = k.replace("_", "-")
if key == "state":
self._config_dict["state"] = v
self._config_dict["disabled"] = v == "disabled"
elif key == "font":
self._set_font(v)
elif key in ("textvariable", "text-variable"):
self._textvariable = v
self._config_dict["textvariable"] = v
if v is not None:
v._widgets.append(self)
elif key in ("variable",):
self._variable = v
self._config_dict["variable"] = v
if v is not None:
v._widgets.append(self)
elif key == "tooltip":
self._config_dict["tooltip"] = str(v) if v else ""
else:
_warn_unknown_config_key(k, key)
_validate_config_type(k, v)
self._config_dict[key] = v
if parent is None and _LAYOUT_STACK:
parent = _LAYOUT_STACK[-1]
if parent is not None:
parent.add(self)
@classmethod
def _swap_first_positional_str(
cls, args: tuple[Any, ...], kwargs: dict[str, Any]
) -> tuple[tuple[Any, ...], dict[str, Any]]:
"""Detect the common tkinter/Qt ``Label("text")`` / ``Button("text")``
call style and reorder the first positional string into
``text="..."``.
Subclasses with a different first-positional contract should
override ``__init__`` and avoid invoking this helper.
"""
if args and isinstance(args[0], str) and "text" not in kwargs:
kwargs = {**kwargs, "text": args[0]}
args = args[1:]
return args, kwargs
@property
def widget_id(self) -> str:
"""Unique identifier for this widget instance."""
return self._id
@property
def parent(self) -> Widget | None:
"""Parent widget, or None if this is a root widget."""
return self._parent
@property
def app(self) -> Any:
"""The Application instance this widget belongs to, or None."""
if self._app:
return self._app
if self._parent:
return self._parent.app
return None
[docs]
def add(self, child: Widget) -> None:
"""Add a child widget to this widget's children list.
If the child is already present, this is a no-op.
"""
if child in self._children:
return
child._parent = self
self._children.append(child)
app = self.app
if app is not None:
from .app import _HANDLERS
child._app = app
for _, w in child._collect_widgets():
w._app = app
if isinstance(w, Widget):
_HANDLERS[w._id] = w._handle_bridge_event
[docs]
def remove(self, child: Widget) -> None:
"""Remove a child widget from this widget's children list."""
if child in self._children:
self._children.remove(child)
child._parent = None
[docs]
def pack(
self,
side: str = "top",
fill: str = "none",
expand: bool = False,
padx: PadValue = 0,
pady: PadValue = 0,
anchor: str = "nw",
in_: Widget | None = None,
) -> Widget:
"""Arrange this widget using pack layout.
Args:
side: ``"top"``, ``"left"``, ``"bottom"``, or ``"right"``.
fill: ``"none"``, ``"x"``, ``"y"``, or ``"both"``.
expand: whether to take extra space.
padx: horizontal padding in pixels — one value for both sides, or
a tkinter-style ``(left, right)`` tuple.
pady: vertical padding in pixels — one value for both sides, or
a tkinter-style ``(top, bottom)`` tuple.
anchor: ``"nw"``, ``"n"``, ``"ne"``, ``"w"``, ``"e"``, ``"sw"``, ``"s"``, ``"se"``.
in_: parent widget to pack into. If different from current parent,
the widget is reparented automatically.
"""
if in_ is not None and in_ is not self._parent:
if self._parent is not None:
self._parent.remove(self)
in_.add(self)
if self._layout_mode and self._layout_mode != "pack":
warnings.warn(
f"Widget {self._id}: pack() called after {self._layout_mode}(). "
f"Previous layout will be overwritten.",
stacklevel=2,
)
self._layout_mode = "pack"
self._config_dict.pop("hidden", None)
self._layout_info = {
"side": side,
"fill": fill,
"expand": expand,
"padx": padx,
"pady": pady,
"anchor": anchor,
}
return self
[docs]
def grid(
self,
row: int = 0,
column: int = 0,
rowspan: int = 1,
columnspan: int = 1,
sticky: str = "",
padx: PadValue = 0,
pady: PadValue = 0,
) -> Widget:
"""Arrange this widget using grid layout.
Args:
row: row index (0-based).
column: column index (0-based).
rowspan: number of rows to span.
columnspan: number of columns to span.
sticky: combination of ``"n"``, ``"s"``, ``"e"``, ``"w"``,
or ``"c"`` for center.
padx: horizontal padding — one value for both sides, or a
tkinter-style ``(left, right)`` tuple.
pady: vertical padding — one value for both sides, or a
tkinter-style ``(top, bottom)`` tuple.
To control row/column weights and minimum sizes, use
:meth:`~iskg.widgets._containers.Frame.grid_columnconfigure`
and :meth:`~iskg.widgets._containers.Frame.grid_rowconfigure`
on the parent *Frame*.
"""
if self._layout_mode and self._layout_mode != "grid":
warnings.warn(
f"Widget {self._id}: grid() called after {self._layout_mode}(). "
f"Previous layout will be overwritten.",
stacklevel=2,
)
self._layout_mode = "grid"
self._config_dict.pop("hidden", None)
self._config_dict.pop("_grid_saved", None)
self._layout_info = {
"row": row,
"column": column,
"rowspan": rowspan,
"columnspan": columnspan,
"sticky": sticky,
"padx": padx,
"pady": pady,
}
return self
[docs]
def place(
self,
x: int = 0,
y: int = 0,
width: int | None = None,
height: int | None = None,
anchor: str = "nw",
) -> Widget:
"""Position this widget at absolute coordinates.
Args:
x: left offset in pixels.
y: top offset in pixels.
width: explicit width in pixels, or None for auto.
height: explicit height in pixels, or None for auto.
anchor: ``"nw"``, ``"n"``, ``"ne"``, ``"w"``, ``"e"``, ``"sw"``, ``"s"``, ``"se"``.
"""
if self._layout_mode and self._layout_mode != "place":
warnings.warn(
f"Widget {self._id}: place() called after {self._layout_mode}(). "
f"Previous layout will be overwritten.",
stacklevel=2,
)
self._layout_mode = "place"
self._config_dict.pop("hidden", None)
self._layout_info = {
"x": x,
"y": y,
"width": width,
"height": height,
"anchor": anchor,
}
return self
[docs]
def grid_remove(self) -> None:
"""Remove from grid layout, remembering position.
Call :meth:`grid` with the same parameters to restore.
"""
self._config_dict["_grid_saved"] = dict(self._layout_info)
self._config_dict["hidden"] = True
self._sync()
[docs]
def grid_forget(self) -> None:
"""Remove from grid layout (position lost).
Call :meth:`grid` with new parameters to re-display.
"""
self._config_dict["hidden"] = True
self._sync()
pack_forget = grid_forget
@property
def tooltip(self) -> str:
"""Get/set the hover tooltip text for this widget."""
return self._config_dict.get("tooltip", "")
@tooltip.setter
def tooltip(self, value: str) -> None:
self._config_dict["tooltip"] = str(value)
self._sync()
def _render_tooltip_js(self) -> str:
text = self._config_dict.get("tooltip", "")
if not text:
return ""
escaped = text.replace("\\", "\\\\").replace("'", "\\'").replace('"', """)
return f'''(function(){{
var el=document.getElementById("{self._id}");
if(!el)return;
var tip=document.createElement("div");
tip.className="iskg-tooltip";
tip.setAttribute("data-tipfor","{self._id}");
tip.innerHTML="{escaped}";
tip.style.display="none";
document.body.appendChild(tip);
var timer=null;
el.onmouseenter=function(e){{
timer=setTimeout(function(){{
var r=el.getBoundingClientRect();
tip.style.display="block";
tip.style.left=Math.min(e.clientX,document.documentElement.clientWidth-tip.offsetWidth)+"px";
tip.style.top=(r.bottom+4)+"px";
}},400);
}};
el.onmouseleave=function(){{clearTimeout(timer);tip.style.display="none";}};
}})();'''
[docs]
def config(self, **kwargs: Any) -> Widget:
"""Configure widget properties.
Accepts any keyword argument; underscores in keys are converted to
hyphens for CSS. Common keys: ``fg``, ``bg``, ``font_size``,
``padding``, ``border_color``, ``opacity``, etc.
Also accepts ``state`` (``"normal"``, ``"disabled"``, ``"readonly"``),
``visible`` (bool), ``textvariable``, and ``variable`` which are
handled specially.
"""
for k, v in kwargs.items():
key = k.replace("_", "-")
if key == "state":
self._set_state(v)
elif key == "visible":
_validate_config_type("visible", v)
if v:
self._eval_js(f'iskg_set_visible("{self._id}",true);')
else:
self._eval_js(f'iskg_set_visible("{self._id}",false);')
elif key == "font":
self._set_font(v)
elif key in ("textvariable", "text-variable"):
if v is not None:
v._widgets.append(self)
self._textvariable = v
self._config_dict["textvariable"] = v
elif key in ("variable",):
if v is not None:
v._widgets.append(self)
self._variable = v
self._config_dict["variable"] = v
elif key == "flex":
self._config_dict["flex"] = bool(v)
elif key == "tooltip":
self._config_dict["tooltip"] = str(v) if v else ""
self._eval_js(self._render_tooltip_js())
else:
_warn_unknown_config_key(k, key)
if "-" in key and not key.startswith("--"):
known = {css_k for css_k, _, _ in _CONFIG_TO_CSS}
if key not in known:
warnings.warn(
f"Unknown config key '{key}' on {type(self).__name__} "
f"(set via config({k}=...)). If this is a custom CSS property, "
f"prefix it with '--'.",
stacklevel=2,
)
else:
_validate_css_value(key, v)
_validate_config_type(k, v)
self._config_dict[key] = v
self._sync()
return self
def _get_cfg(self, key: str, default: Any = None) -> Any:
"""Read config key, trying hyphen first, then underscore."""
if key in self._config_dict:
return self._config_dict[key]
alt = key.replace("-", "_")
return self._config_dict.get(alt, default)
def _own_min_size(self) -> tuple[int, int]:
"""Class-specific natural minimum ``(width, height)`` in pixels.
Leaf widgets override this using :mod:`iskg.metrics`; the base
implementation returns ``(0, 0)`` (no opinion).
"""
return (0, 0)
def _children_min_size(self) -> tuple[int, int]:
"""Minimum imposed by this widget's children, per its layout mode.
Containers (Frame and friends) override this; leaves return ``(0, 0)``.
"""
return (0, 0)
@staticmethod
def _cfg_px(value: Any) -> int:
"""Coerce a config pixel value (``int``/digit-string) to ``int``."""
if isinstance(value, bool):
return 0
if isinstance(value, int):
return max(0, value)
if isinstance(value, str) and value.isdigit():
return int(value)
return 0
def _content_min_size(self) -> tuple[int, int]:
"""Natural minimum ``(width, height)`` so this widget is never squeezed
below its content (frames covering their widgets).
Systemic by default: explicit ``width``/``height``/``min_width``/
``min_height`` always count, then the class default
(:meth:`_own_min_size`), then the children's contribution
(:meth:`_children_min_size`). Pass ``fit=False`` to opt out and keep
the old shrink-to-zero behaviour (``ImageBox`` reuses the name
``fit`` for its image scaling mode — only the boolean ``False`` is
treated as opt-out).
"""
if self._get_cfg("fit", True) is False:
return (0, 0)
if self._config_dict.get("hidden"):
return (0, 0)
own_w, own_h = self._own_min_size()
kids_w, kids_h = self._children_min_size()
w = max(
self._cfg_px(self._config_dict.get("width")),
self._cfg_px(self._config_dict.get("min_width")),
own_w,
kids_w,
)
h = max(
self._cfg_px(self._config_dict.get("height")),
self._cfg_px(self._config_dict.get("min_height")),
own_h,
kids_h,
)
return (w, h)
def _var_updated(self, var: Any) -> None:
"""Called when a bound variable changes value.
Override in subclasses to update the widget display.
"""
pass
[docs]
def cget(self, key: str) -> Any:
"""Get a widget configuration value by key."""
return self._config_dict.get(key.replace("_", "-"))
def _eval_js(self, js: str) -> None:
app = self.app
if app and app._running:
app._eval_js(js)
def _set_font(self, v: Any) -> None:
if isinstance(v, str):
self._config_dict["font"] = v
return
if isinstance(v, (list, tuple)):
if len(v) > 0:
self._config_dict["font-family"] = v[0]
if len(v) > 1:
self._config_dict["font-size"] = v[1]
if len(v) > 2:
self._config_dict["font-weight"] = v[2]
def _set_state(self, state: str) -> None:
self._config_dict["state"] = state
self._config_dict["disabled"] = state == "disabled"
if state == "disabled":
self._eval_js(f'iskg_set_enabled("{self._id}",false);')
elif state == "readonly":
self._eval_js(f'iskg_set_attr("{self._id}","readonly","true");')
else:
self._eval_js(f'iskg_set_enabled("{self._id}",true);')
self._eval_js(f'iskg_set_attr("{self._id}","readonly","");')
@property
def state(self) -> str:
"""Get the widget state (``"normal"``, ``"disabled"``, ``"readonly"``)."""
return self._config_dict.get("state", "normal")
@state.setter
def state(self, value: str) -> None:
self._set_state(value)
@property
def visible(self) -> bool:
"""Whether the widget is visible."""
return not self._config_dict.get("hidden", False)
@visible.setter
def visible(self, value: bool) -> None:
self._config_dict["hidden"] = not value
self._eval_js(f'iskg_set_visible("{self._id}",{str(value).lower()});')
@property
def width(self) -> int | None:
return self._config_dict.get("width")
@width.setter
def width(self, value: int | None) -> None:
if value is None:
self._config_dict.pop("width", None)
else:
self._config_dict["width"] = int(value)
self._sync()
@property
def height(self) -> int | None:
return self._config_dict.get("height")
@height.setter
def height(self, value: int | None) -> None:
if value is None:
self._config_dict.pop("height", None)
else:
self._config_dict["height"] = int(value)
self._sync()
@property
def cursor(self) -> str:
return self._config_dict.get("cursor", "default")
@cursor.setter
def cursor(self, value: str) -> None:
self._config_dict["cursor"] = value
self._sync()
[docs]
def focus(self) -> None:
"""Move keyboard focus to this widget."""
self._eval_js(f'iskg_focus("{self._id}");')
focus_set = focus
@property
def takefocus(self) -> bool:
"""Whether this widget can receive keyboard focus. Default ``True`` for
interactive widgets (Button, Entry, etc.), ``False`` for containers."""
return self._config_dict.get("takefocus", self._default_takefocus())
@takefocus.setter
def takefocus(self, value: bool) -> None:
self._config_dict["takefocus"] = bool(value)
def _default_takefocus(self) -> bool:
return False
@staticmethod
def _tabindex_attr(takefocus: bool) -> str:
return ' tabindex="0"' if takefocus else ""
def _collect_focusable(self) -> list[Widget]:
result: list[Widget] = []
self._collect_focusable_into(result)
return result
def _collect_focusable_into(self, result: list[Widget]) -> None:
if self._destroyed:
return
if self.takefocus:
result.append(self)
for child in self._children:
if not child._destroyed:
child._collect_focusable_into(result)
[docs]
def focus_next(self) -> None:
"""Move focus to the next widget in tab order."""
chain = self._collect_focusable()
if not chain:
return
try:
idx = chain.index(self)
nxt = chain[(idx + 1) % len(chain)]
except ValueError:
nxt = chain[0]
nxt.focus()
[docs]
def focus_prev(self) -> None:
"""Move focus to the previous widget in tab order."""
chain = self._collect_focusable()
if not chain:
return
try:
idx = chain.index(self)
nxt = chain[(idx - 1) % len(chain)]
except ValueError:
nxt = chain[-1]
nxt.focus()
class _Timer:
"""A cancelable timer returned by :meth:`after`.
Attributes:
running: ``True`` while the timer is pending.
"""
def __init__(self, timer_id: str, timer: Any) -> None:
self._id = timer_id
self._timer = timer
self.running = True
def cancel(self) -> None:
"""Cancel this timer. No-op if already fired or cancelled."""
if self.running:
self.running = False
if self._timer is not None:
self._timer.cancel()
self.cancelled = True
[docs]
def after(self, ms: int, callback: Callable) -> _Timer:
"""Schedule a function to run after *ms* milliseconds.
Delegates to :meth:`Application.after` so callbacks are serialized
on the same worker thread. If the widget isn't attached to an
app yet, falls back to a one-shot :class:`threading.Timer`.
Args:
ms: delay in milliseconds.
callback: function to call (no arguments).
Returns:
A :class:`_Timer` with ``.cancel()`` and ``.running``.
"""
import threading
timer_id = f"wt{id(callback)}_{id(self)}"
app = self.app
if app is not None:
return app.after(ms, callback)
# Standalone widget (no app yet): use a one-shot timer.
handle = self._Timer(timer_id, None)
handle.cancelled = False # type: ignore[attr-defined]
def _fire() -> None:
if getattr(handle, "cancelled", False):
return
try:
callback()
except Exception:
if app and app._debug:
import traceback
traceback.print_exc()
t = threading.Timer(ms / 1000, _fire)
t.daemon = True
handle._timer = t # type: ignore[attr-defined]
self._config_dict.setdefault("_timers", {})[timer_id] = handle
t.start()
return handle
[docs]
def after_cancel(self, timer_id: str) -> None:
"""Cancel a timer by its string ID (legacy)."""
timers = self._config_dict.get("_timers", {})
t = timers.pop(timer_id, None)
if t:
t.cancel()
def _build_rerender_js(self) -> str:
import json as _json
html = self._render()
js = f'iskg_replace_widget("{self._id}", {_json.dumps(html)});'
init_js = self._render_js()
if init_js:
js += init_js
return js
[docs]
def rerender(self) -> None:
"""Replace the widget's rendered DOM with a fresh :meth:`_render`.
Useful for properties that have no incremental update path
(e.g. a dropdown's option list). After swapping the element, the
widget's init JS is re-run so event bindings are restored.
No-op when the app is not running or the widget is destroyed.
"""
if self._destroyed or not (self._app and self._app._running):
return
js = self._build_rerender_js()
self._last_sync_js = js
self._app._defer_sync(js)
@staticmethod
def _parse_key_event(spec: str) -> dict[str, Any] | None:
"""Parse a tkinter-style key event spec like ``"<KeyPress-a>"``.
Returns a dict with keys: ``event_type`` (``"keypress"``/``"keyrelease"``),
``key`` (str or None), ``ctrl``, ``alt``, ``shift`` (bool).
Returns ``None`` if the spec is not a key event.
"""
s = spec.strip()
if not (s.startswith("<") and s.endswith(">")):
return None
if s.startswith("<<"):
return None # virtual event like <<Custom>>, not a key event
s = s[1:-1]
parts = s.split("-")
result: dict[str, Any] = {
"event_type": "keypress",
"key": None,
"ctrl": False,
"alt": False,
"shift": False,
}
for p in parts:
pl = p.lower()
if pl in ("keypress", "key"):
result["event_type"] = "keypress"
elif pl == "keyrelease":
result["event_type"] = "keyrelease"
elif pl in ("control", "ctrl"):
result["ctrl"] = True
elif pl == "alt":
result["alt"] = True
elif pl == "shift":
result["shift"] = True
else:
result["key"] = p
return result
def _install_key_binding(self, parsed: dict[str, Any], callback: Callable) -> None:
entry = dict(parsed)
entry["cb"] = callback
self._key_bindings.append(entry)
self._bindings[parsed["event_type"]] = callback
if self._app and self._app._running:
self._eval_js(self._render_key_binding_js(parsed))
def _render_key_binding_js(self, parsed: dict[str, Any]) -> str:
mods = {}
if parsed["ctrl"]:
mods["ctrl"] = True
if parsed["alt"]:
mods["alt"] = True
if parsed["shift"]:
mods["shift"] = True
mods_json = json.dumps(mods) if mods else "null"
key_json = json.dumps(parsed["key"]) if parsed["key"] else "null"
evt = json.dumps(parsed["event_type"])
return f'iskg_bind_key("{self._id}",{evt},{key_json},{mods_json});'
def _render_key_bindings_js(self) -> str:
parts = [self._render_key_binding_js(e) for e in self._key_bindings]
return "".join(parts)
def _render_contextmenu_js(self) -> str:
"""Return JS installing the right-click listener, if needed."""
if "contextmenu" in self._bindings or self._config_dict.get("menu") is not None:
return f'iskg_bind_contextmenu("{self._id}");'
return ""
def _render_dnd_js(self) -> str:
"""Return JS marking this widget as a drag/drop target, if bound."""
if self._drop_enabled():
return (
f'iskg_register_dnd("{self._id}","target");'
f'(function(){{var el=document.getElementById("{self._id}");'
f'if(el)el.classList.add("iskg-drop-target");}})();'
)
return ""
def _drop_enabled(self) -> bool:
return bool(
self._dnd_target
or self._bindings.get("<<Drop>>")
or self._config_dict.get("drop")
or "drop" in self._bindings
)
[docs]
def bind(self, event: str, callback: Callable) -> None:
"""Bind a callback to an event.
Supports standard bridge events (``"click"``, ``"change"``, etc.),
tkinter-style key events (``"<KeyPress-a>"``, ``"<KeyRelease-Return>"``,
``"<Control-c>"``, ``"<Key>"``), and virtual events
(``"<<CustomEvent>>"``).
events. Right-click is available as ``"contextmenu"``; its callback
receives a dict with ``x`` and ``y``.
Key event callbacks receive a dict with ``key``, ``code``, ``ctrl``,
``alt``, ``shift``.
"""
parsed = self._parse_key_event(event)
if parsed is not None:
self._install_key_binding(parsed, callback)
else:
self._bindings[event] = callback
if event == "contextmenu" and self._app and self._app._running:
self._eval_js(f'iskg_bind_contextmenu("{self._id}");')
if event == "<<Drop>>":
self._dnd_target = True
self._eval_js(f'iskg_register_dnd("{self._id}","target");')
[docs]
def unbind(self, event: str) -> None:
"""Remove a previously bound event callback."""
parsed = self._parse_key_event(event)
if parsed is not None:
et = parsed["event_type"]
self._key_bindings[:] = [
e
for e in self._key_bindings
if not (
e["event_type"] == et
and e["key"] == parsed["key"]
and e["ctrl"] == parsed["ctrl"]
and e["alt"] == parsed["alt"]
and e["shift"] == parsed["shift"]
)
]
self._bindings.pop(et, None)
if self._app and self._app._running:
self._eval_js(f'iskg_unbind_key("{self._id}",{json.dumps(et)});')
else:
self._bindings.pop(event, None)
[docs]
def event_generate(self, event: str, data: Any = None) -> bool:
"""Generate a virtual event that bubbles up the parent chain.
Args:
event: event name (e.g. ``"<<Custom>>"``, ``"click"``, ``"change"``).
data: optional data passed to the callback.
Returns:
``True`` if propagation should stop (callback returned ``"break"``).
"""
if self._handle_bridge_event(event, data) == "break":
return True
if self._parent and not self._parent._destroyed:
return self._parent.event_generate(event, data)
return False
def _handle_bridge_event(self, event_name: str, event_data: Any) -> str | None:
if event_name == "drop" and "<<Drop>>" in self._bindings:
cb = self._bindings["<<Drop>>"]
result = cb(event_data)
if result == "break":
return "break"
return None
if event_name == "contextcmd" and self._context_menu is not None:
from .widgets._menus import resolve_context_command
cmd = resolve_context_command(self._context_menu, str(event_data or ""))
if cmd:
cmd()
return None
if event_name == "contextmenu" and self._context_menu is not None and self._context_show:
from .widgets._menus import render_context_items
html = render_context_items(self._context_menu.items)
if self._app and self._app._running:
self._eval_js(f'iskg_open_contextmenu("{self._id}", {json.dumps(html)});')
if event_name in ("change", "input"):
if self._textvariable is not None and not getattr(self, "_variable_handled", False):
self._textvariable.set(str(event_data), _from_widget=self)
if self._variable is not None and not getattr(self, "_variable_handled", False):
self._variable.set(event_data, _from_widget=self)
cb = self._bindings.get(event_name)
if cb:
result = cb(event_data)
if result == "break":
return "break"
cmd = self._config_dict.get("command")
if cmd and event_name in ("click", "change", "drop"):
self._invoke_command(cmd, event_data)
return None
def _invoke_command(self, cmd: Callable, event_data: Any) -> None:
"""Invoke a user ``command`` callback.
Callbacks that take no arguments (e.g. ``lambda: ...``) are called with
no args for backward compatibility. Callbacks that accept one argument
receive the event payload (e.g. the selected index for a ``ListBox``
``change`` or the file list for a ``DropTarget`` ``drop``).
The arity is resolved by trying the data-carrying call first and falling
back to a no-arg call, instead of inspecting the signature.
"""
try:
cmd(event_data)
except TypeError:
try:
cmd()
except TypeError:
raise
[docs]
def destroy(self) -> None:
"""Destroy this widget and all its children."""
self._destroyed = True
app = self._app
for child in list(self._children):
child.destroy()
if self._parent:
self._parent.remove(self)
if app and app._running:
with contextlib.suppress(Exception):
app._eval_js(f'iskg_cleanup("{self._id}");')
if app:
app._widget_destroyed(self._id)
def _sync(self) -> None:
if self._destroyed or not (self._app and self._app._running):
return
# Each helper tracks its own dedup; an empty string means "no JS
# to send for this slot". The combined JS is the concatenation of
# the *non-empty* parts, and the dedup compares against the
# concatenation emitted last time. Because individual helpers
# skip when their slice hasn't changed, a no-op _sync() produces
# exactly the same combined JS and is short-circuited.
update_js = self._render_update_js()
style_js = self._render_style_update_js()
attr_js = self._render_attr_update_js()
combined = ";".join(p for p in (update_js, style_js, attr_js) if p)
if combined and combined != self._last_sync_js:
self._last_sync_js = combined
self._app._defer_sync(combined)
def _render(self) -> str:
"""Return the HTML string for this widget. Override in subclasses."""
if self._layout_mode == "grid" or self._layout_mode == "pack":
return f'<div id="{self._id}" style="{self._render_style()}"></div>'
return ""
def _render_js(self) -> str:
"""Return JavaScript to initialise this widget. Override in subclasses."""
return self._render_key_bindings_js() + self._render_tooltip_js()
def _render_update_js(self) -> str:
"""Return JavaScript to update this widget's DOM. Override in subclasses."""
return ""
@staticmethod
def _css_value(val: Any, is_px: bool) -> str:
if isinstance(val, (int, float)):
return f"{val}px" if is_px else str(val)
s = str(val).strip()
if is_px and s:
from re import split as _re_split
parts = _re_split(r"\s+", s)
parts = [f"{p}px" if p and p[-1].isdigit() else p for p in parts]
return " ".join(parts)
return s
def _render_style_css(self) -> str:
css = ""
for cfg_key, css_prop, is_px in _CONFIG_TO_CSS:
val = self._config_dict.get(cfg_key)
if val is not None and val != "":
css += f"{css_prop}:{self._css_value(val, is_px)};"
for k, v in self._config_dict.items():
if k.startswith("--"):
css += f"{k}:{v};"
return css
def _render_style_update_js(self) -> str:
css = self._render_style_css()
# _last_style_css is primed by Application.add() (called once when
# the widget is mounted). If a widget is mutated before being added
# to an app, the first sync after mount will emit the style as a
# one-shot reconciliation.
if css and css != self._last_style_css:
self._last_style_css = css
return f'iskg_set_style("{self._id}",{json.dumps(css)});'
return ""
def _prime_style_cache(self) -> None:
"""Snapshot the initial CSS so the first post-mount _sync() does
not re-emit bytes that are already in the initial HTML."""
if self._last_style_css is None:
self._last_style_css = self._render_style_css()
_ARIA_ROLE: str = ""
def _render_aria_attrs(self) -> str:
parts = []
role = self._ARIA_ROLE
if role:
parts.append(f'role="{role}"')
if self._config_dict.get("disabled"):
parts.append('aria-disabled="true"')
if parts:
return " " + " ".join(parts)
return ""
def _render_attr_update_js(self) -> str:
parts = []
disabled = self._config_dict.get("disabled")
if disabled is not None:
parts.append(f'iskg_set_enabled("{self._id}",{"false" if disabled else "true"});')
return "".join(parts) if parts else ""
def _render_attrs(self) -> str:
"""Return common HTML attributes (tabindex, disabled, ARIA)."""
attrs = ""
if self._config_dict.get("disabled"):
attrs += " disabled"
if self._config_dict.get("draggable"):
attrs += ' draggable="true"'
if self._config_dict.get("takefocus", self._default_takefocus()):
attrs += ' tabindex="0"'
# Validation state → CSS class so invalid/intermediate styling applies.
vstate = self._config_dict.get("validation_state")
if vstate == "invalid":
attrs += ' class="iskg-invalid"'
attrs += ' aria-invalid="true"'
elif vstate == "intermediate":
attrs += ' aria-invalid="false"'
attrs += self._render_aria_attrs()
return attrs
def _render_style(self) -> str:
li = self._layout_info
style = ""
if self._config_dict.get("hidden"):
style += "display:none;"
if self._layout_mode == "pack":
side = li.get("side", "top")
expand = li.get("expand", False)
fill = li.get("fill", "none")
if side in ("left", "right"):
# row: main-axis = horizontal, cross-axis = vertical
if expand:
emw, emh = self._content_min_size()
style += f"flex:1;min-width:{emw}px;min-height:{emh}px;"
else:
style += "flex-shrink:0;"
if fill in ("y", "both"):
style += "align-self:stretch;"
if fill in ("x", "both") and expand:
style += "width:100%;"
if side == "right" and not expand:
style += "margin-left:auto;"
else:
# column: main-axis = vertical, cross-axis = horizontal
if expand:
emw, emh = self._content_min_size()
style += f"flex:1;min-width:{emw}px;min-height:{emh}px;"
if fill in ("x", "both"):
style += "align-self:stretch;"
if fill in ("y", "both") and not expand:
style += "height:100%;"
if side == "bottom":
style += "margin-top:auto;"
style += _pad_css("x", li.get("padx"))
style += _pad_css("y", li.get("pady"))
elif self._layout_mode == "grid":
g = li
s = f"grid-row:{g.get('row', 0) + 1}/span {max(1, g.get('rowspan', 1))};"
s += f"grid-column:{g.get('column', 0) + 1}/span {max(1, g.get('columnspan', 1))};"
s += _pad_css("x", g.get("padx"))
s += _pad_css("y", g.get("pady"))
sticky = g.get("sticky", "")
sticky_set = set(sticky)
if "we" in sticky or "ew" in sticky:
s += "justify-self:stretch;"
elif "w" in sticky_set:
s += "justify-self:start;"
elif "e" in sticky_set:
s += "justify-self:end;"
elif "c" in sticky_set:
s += "justify-self:center;"
if "ns" in sticky:
s += "align-self:stretch;"
elif "n" in sticky_set:
s += "align-self:start;"
elif "s" in sticky_set:
s += "align-self:end;"
elif "c" in sticky_set:
s += "align-self:center;"
style += s
elif self._layout_mode == "place":
p = li
style += f"position:absolute;left:{p.get('x', 0)}px;top:{p.get('y', 0)}px;"
if p.get("width") is not None:
style += f"width:{p['width']}px;"
if p.get("height") is not None:
style += f"height:{p['height']}px;"
style += self._render_style_css()
return style
def _render_children(self) -> str:
parts: list[str] = []
for child in self._children:
if child._destroyed:
continue
parts.append(child._render())
return "".join(parts)
def _render_children_js(self) -> str:
parts: list[str] = []
for child in self._children:
if child._destroyed:
continue
js = child._render_js()
if js:
parts.append(js)
base_js = child._render_key_bindings_js() + child._render_tooltip_js()
if base_js:
parts.append(base_js)
parts.append(child._render_children_js())
return "".join(parts)
def _collect_widgets(self, depth: int = 0) -> list[tuple[int, Widget]]:
result: list[tuple[int, Widget]] = [(depth, self)]
for child in self._children:
if child._destroyed:
continue
result.extend(child._collect_widgets(depth + 1))
return result
[docs]
def dump(self) -> dict[str, Any]:
"""JSON-friendly snapshot of this widget and its subtree.
Returns a nested dict::
{"type": "Button", "id": "iw3", "destroyed": False,
"config": {...}, "children": [...]}
``config`` mirrors ``_config_dict`` with every value sanitised by
:func:`_dump_value`, so the result can always be serialised with
``json.dumps``. Useful from a REPL or a debug panel::
print(json.dumps(app.dump_tree(), indent=2))
"""
node: dict[str, Any] = {
"type": type(self).__name__,
"id": self._id,
"destroyed": self._destroyed,
"config": {k: _dump_value(v) for k, v in self._config_dict.items()},
}
if self._children:
node["children"] = [child.dump() for child in self._children]
return node