API Reference

Application

Application and window management, JS bridge, and file dialogs.

class iskg.app.Application(title: str = 'ISKG App', width: int = 800, height: int = 600, scanlines: bool = True, vignette: bool = True, theme: str = 'ifaz', debug: bool = False, extra_css: str = '', stderr_log: str | None = None, font_ids: list[str] | None = None, icon: str | None = None, on_top: bool = False, frameless: bool = False, easy_drag: bool = True, x: int | None = None, y: int | None = None, min_size: bool = True)[source]

Bases: object

Main application entry point.

Creates a native window via pywebview, renders all widgets as HTML/CSS/JS, and manages the JS bridge for event handling.

Usage:

app = Application("My App", 800, 600)
label = Label(text="Hello")
app.add(label)
app.run()

Pass debug=True to log JavaScript errors — and every bridge traffic line (Python→JS evals and JS→Python events) — to stderr, mirrored in trace():

app = Application(debug=True)
add(widget: Widget) → Widget[source]

Register a root-level widget with the application.

Widgets must be added to the app before run() is called.

after(ms: int, callback: Callable) → Any[source]

Schedule callback to run after ms milliseconds.

All timer callbacks share a single daemon worker thread fed by a priority queue, so callbacks from different timers are serialized and never run concurrently. This avoids races when two timers both call _sync() and both append to _deferred_sync at the same instant. Returns a handle with .cancel() / .running.

Parameters:
  • ms – delay in milliseconds.

  • callback – zero-argument callable.

Returns:

A timer handle (Widget._Timer-compatible) with .cancel().

after_cancel(timer_id: str) → None[source]

Cancel a timer previously created with after().

alert(message: str) → None[source]

Show a browser-style alert dialog.

bind(event: str, callback: Callable | None = None) → Callable[source]

Bind a window-wide (global) keyboard shortcut.

Unlike Widget.bind, these shortcuts fire regardless of which widget has focus. Uses the same tkinter-style syntax: "<Control-s>", "<Alt-F4>", "<KeyRelease-a>", etc.

The callback receives a dict with key, code, ctrl, alt, shift. May be used as a decorator:

@app.bind("<Control-s>")
def on_save(data):
    ...
color_dialog(title: str = 'Choose Color', initial_color: str = '#000000') → str | None[source]

Open a color picker dialog.

Uses GTK on Linux, falls back to a browser <input type="color"> on Windows/macOS.

Returns a hex string (e.g. "#ff8800") or None.

confirm(message: str) → bool[source]

Show a browser-style confirm dialog. Returns True if OK was clicked.

current_theme() → str[source]

Return the name of the currently active theme.

property debug: bool
dump_tree() → list[dict[str, Any]][source]

Snapshot of every root widget and its subtree.

Returns a list of nested dicts (see Widget.dump()), always JSON-serialisable:

app.dump_tree()
app.dump_tree_text()   # same data, indented plain text
dump_tree_text() → str[source]

Plain-text rendering of dump_tree(), indented per level.

emit(event: str, *args: Any) → Application[source]

Fire a global application event synchronously.

Parameters:
  • event – event name.

  • *args – payload forwarded to every subscribed handler.

execute_js(js_code: str) → Application[source]

Execute arbitrary JavaScript in the webview window.

file_dialog(dialog_type: str = 'open', directory: str = '', file_types: list[str] | None = None, allow_multiple: bool = False, title: str = '') → Any | None[source]

Open a native OS file dialog.

Uses GTK directly (same toolkit as pywebview underneath) with explicit dialog sizing.

_gtk_file_dialog returns _GTK_UNAVAILABLE when GTK is not importable, so a user Cancel (None) is not mistaken for a missing toolkit and does not trigger a second dialog via pywebview.

font_dialog(title: str = 'Choose Font', initial_font: str = '') → dict[str, Any] | None[source]

Open a font picker dialog.

Uses GTK on Linux, falls back to a browser prompt on Windows/macOS.

Returns a dict with keys family, size, weight, style, or None.

geometry(x: int | None = None, y: int | None = None, w: int | None = None, h: int | None = None) → tuple[int, int, int, int][source]

Get or set the window position and size.

While the window is running, the getter reports the live position reported by the window manager.

get_clipboard() → str[source]

Read text from the system clipboard (requires pyperclip).

get_widget(widget_id: str) → Widget | None[source]

Look up a widget by its id anywhere in the tree (or None).

inject_css(css: str) → Application[source]

Inject a CSS string at runtime (after the app has started).

The CSS is appended inside a <style id="iskg-user-css"> tag so the user can call this multiple times without losing the previous injection. Useful for theme overrides and app-specific styling.

Parameters:

css – a raw CSS string (e.g. "body { background: #000; }").

inject_js(js_code: str) → Application[source]

Inject JavaScript at runtime (queue-safe alias of execute_js()).

Symmetric counterpart of inject_css(). Called before run() (the natural place for WidgetInspector.enable(), SystemTray, toasts…) the code is queued and executed once the DOM reports loaded — previously these call sites raised AttributeError: 'Application' object has no attribute 'inject_js' the first time they ran, and an equivalent silent drop would have swallowed pre-run injections.

off(event: str, callback: Callable | None = None) → Application[source]

Unsubscribe one (or all) handler(s) from an event.

Parameters:
  • event – event name.

  • callback – handler to remove; when None all handlers for the event are removed.

on(event: str, callback: Callable | None = None) → Callable[source]

Subscribe to a global application event.

Built-in events:

  • "theme-changed" — fired with the new theme name after set_theme().

  • "closing" — fired with None when the window is about to close (in addition to on_close()).

  • "widget-created" — fired with the widget id when a widget is added to the tree (root widgets registered via add()).

Arbitrary user events are also supported.

Parameters:
  • event – event name.

  • callback –

    callable invoked as callback(*args) where args are whatever was passed to emit(). May be omitted to use as a decorator:

    @app.on("my-event")
    def handler(value):
        ...
    

Returns:

The registered callback (handy as a decorator).

on_close(callback: Callable) → None[source]

Register a callback to call when the window is closed.

on_top(value: bool | None = None) → bool[source]

Get or set the always-on-top flag.

When the window is running, the setter applies it live (the window manager keeps the window above others immediately).

quit() → None[source]

Close the application window, fire on_close and exit the main loop.

The on_close callbacks run exactly once (idempotent with the invocation done in run() when the loop ends naturally).

register_theme(name: str, overrides: dict[str, str]) → Application[source]

Register a new theme for runtime use.

Parameters:
  • name – unique theme name (e.g. "mytheme").

  • overrides – dict of CSS custom properties, e.g. {"--bg-primary": "#000", "--text": "#fff"}.

remove(widget: Widget) → None[source]

Unregister a root-level widget.

run(extra_js: str = '') → None[source]

Open the window and start the application main loop.

Blocks until the window is closed. Redirects GTK stderr warnings to stderr_log (or /dev/null when no log path is given) during execution. The original descriptor is always restored via finally, so application prints and tracebacks are never silently swallowed.

Parameters:

extra_js – additional JavaScript to execute on startup (e.g. tooltip init code).

run_async(coro: Any, then: Callable | None = None) → Any[source]

Run a coroutine in a background thread with its own event loop.

Useful for long-running tasks (e.g. network/HTTP calls) without blocking the UI. When the coroutine finishes, then(result) is scheduled on the app via after() (result is the return value, or the raised exception if it failed).

Parameters:
  • coro – a coroutine (e.g. some_async_fn()).

  • then – optional callback then(result) invoked on completion.

Returns:

The background threading.Thread (daemon).

set_clipboard(text: str) → None[source]

Copy text to the system clipboard (requires pyperclip).

set_theme(name: str) → Application[source]

Switch the UI theme at runtime.

Parameters:

name – one of "ifaz", "cold", "warm", "night", or a custom name previously registered via register_theme().

sync_batch() → SyncBatch[source]

Context manager that batches _sync JS until the block exits.

test_loop() → TestLoop[source]

Build the widget tree without a native window (headless).

Returns a TestLoop recorder that captures the JS emitted by _sync()/_eval_js() instead of calling pywebview, so widgets can be exercised in CI/without a display (no GTK/WebKit involved).

Example:

app = Application("t")
label = Label(text="hi")
app.add(label)
loop = app.test_loop()
assert "hi" in loop.html
label.text = "bye"
assert "bye" in "".join(loop.js_calls)
loop.stop()
title(text: str | None = None) → str[source]

Get or set the window title.

trace(limit: int | None = None) → list[dict[str, Any]][source]

Snapshot of the JS bridge traffic, oldest first.

Every entry is a dict with at least t (unix time) and one of these kind values:

  • "js-out" — Python evaluated JS in the webview (bytes, js truncated to ~400 chars).

  • "event-in" — bridge event arrived from JS (widget, event, data).

  • "event-dropped" — a debounced duplicate was discarded.

  • "event-unhandled" — no handler was registered for the widget id (classic “my click does nothing” cause).

  • "js-error" — evaluate_js raised (error).

The buffer holds the last 500 entries and is always recording.

Parameters:

limit – if given, return only the last limit entries.

Example:

app = Application(debug=True)   # also echoes to stderr
...
for e in app.trace(limit=20):
    print(e["kind"], e.get("event") or e.get("bytes"))
trace_clear() → None[source]

Empty the bridge trace ring buffer.

property window_min_size: tuple[int, int] | None

Last computed OS-window minimum (width, height), or None when disabled (min_size=False) or the tree imposes no minimum.

winfo_screendpi() → int[source]

Return the screen DPI (approximate, requires a running window).

winfo_screenheight() → int[source]

Return the screen height in pixels (requires a running window).

winfo_screenwidth() → int[source]

Return the screen width in pixels (requires a running window).

class iskg.app.SyncBatch(app: Application)[source]

Bases: object

Context manager returned by Application.sync_batch().

Accumulates _sync JS emitted inside the with block and flushes it as a single evaluate_js call when the block exits.

class iskg.app.TestLoop(app: Application)[source]

Bases: object

Headless controller returned by Application.test_loop().

Exposes the rendered HTML, the JS emitted so far, and helpers to push bridge events into the widget tree (same path pywebview would use).

fire(widget_id: str, event_name: str, data: Any = None) → None[source]

Deliver a bridge event as if it came from JS.

property html: str

The full HTML document built for the current widget tree.

property js_calls: list[str]

Every evaluate_js string sent to the (fake) window.

stop() → None[source]

Tear down the loop: stop the app and fire on_close callbacks.

iskg.app.Window

alias of Application

Base Widget

Base Widget class with layout engines (pack/grid/place), event bindings, style rendering, and widget tree management.

iskg.base.PadValue = int | collections.abc.Sequence[int]

either one value applied to both sides, or a tkinter-style (before, after) sequence.

Type:

Padding accepted by Widget.pack() / Widget.grid()

class iskg.base.Widget(parent: Widget | None = None, **kwargs: Any)[source]

Bases: object

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.

add(child: Widget) → None[source]

Add a child widget to this widget’s children list.

If the child is already present, this is a no-op.

after(ms: int, callback: Callable) → _Timer[source]

Schedule a function to run after ms milliseconds.

Delegates to 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 threading.Timer.

Parameters:
  • ms – delay in milliseconds.

  • callback – function to call (no arguments).

Returns:

A _Timer with .cancel() and .running.

after_cancel(timer_id: str) → None[source]

Cancel a timer by its string ID (legacy).

property app: Any

The Application instance this widget belongs to, or None.

bind(event: str, callback: Callable) → None[source]

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.

cget(key: str) → Any[source]

Get a widget configuration value by key.

config(**kwargs: Any) → Widget[source]

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.

property cursor: str
destroy() → None[source]

Destroy this widget and all its children.

dump() → dict[str, Any][source]

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 _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))
event_generate(event: str, data: Any = None) → bool[source]

Generate a virtual event that bubbles up the parent chain.

Parameters:
  • event – event name (e.g. "<<Custom>>", "click", "change").

  • data – optional data passed to the callback.

Returns:

True if propagation should stop (callback returned "break").

focus() → None[source]

Move keyboard focus to this widget.

focus_next() → None[source]

Move focus to the next widget in tab order.

focus_prev() → None[source]

Move focus to the previous widget in tab order.

focus_set() → None

Move keyboard focus to this widget.

grid(row: int = 0, column: int = 0, rowspan: int = 1, columnspan: int = 1, sticky: str = '', padx: int | Sequence[int] = 0, pady: int | Sequence[int] = 0) → Widget[source]

Arrange this widget using grid layout.

Parameters:
  • 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 grid_columnconfigure() and grid_rowconfigure() on the parent Frame.

grid_forget() → None[source]

Remove from grid layout (position lost). Call grid() with new parameters to re-display.

grid_remove() → None[source]

Remove from grid layout, remembering position. Call grid() with the same parameters to restore.

property height: int | None
hide() → None[source]

Hide this widget.

pack(side: str = 'top', fill: str = 'none', expand: bool = False, padx: int | Sequence[int] = 0, pady: int | Sequence[int] = 0, anchor: str = 'nw', in_: Widget | None = None) → Widget[source]

Arrange this widget using pack layout.

Parameters:
  • 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.

pack_forget() → None

Remove from grid layout (position lost). Call grid() with new parameters to re-display.

property parent: Widget | None

Parent widget, or None if this is a root widget.

place(x: int = 0, y: int = 0, width: int | None = None, height: int | None = None, anchor: str = 'nw') → Widget[source]

Position this widget at absolute coordinates.

Parameters:
  • 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".

popup_menu(menu: Any, x: int | None = None, y: int | None = None) → None[source]

Show a context menu at the given position or the last right-click.

Parameters:
  • menu – a Menu or a list of MenuItem (or None for a separator).

  • x – absolute X coordinate; defaults to the last right-click.

  • y – absolute Y coordinate; defaults to the last right-click.

remove(child: Widget) → None[source]

Remove a child widget from this widget’s children list.

rerender() → None[source]

Replace the widget’s rendered DOM with a fresh _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.

set_menu(menu: Any = None, *, show: bool = True) → None[source]

Attach a context (right-click) menu to this widget.

Parameters:
  • menu – a Menu, a list of MenuItem/None (None renders a separator), or None to remove the menu (keep the "contextmenu" event notification).

  • show – when True (default on attach), the menu is shown at the right-click position and its item command fires on selection. When False, the menu is only announced via the "contextmenu" binding and no popup is shown.

show() → None[source]

Show this widget.

property state: str

Get the widget state ("normal", "disabled", "readonly").

property takefocus: bool

Whether this widget can receive keyboard focus. Default True for interactive widgets (Button, Entry, etc.), False for containers.

property tooltip: str

Get/set the hover tooltip text for this widget.

unbind(event: str) → None[source]

Remove a previously bound event callback.

update() → None[source]

Force a sync update of this widget’s rendering.

property visible: bool

Whether the widget is visible.

property widget_id: str

Unique identifier for this widget instance.

property width: int | None
iskg.base.current_layout() → Any | None[source]

Widget Controls

class iskg.widgets._controls.Button(*args: Any, parent: Widget | None = None, text: str = '', command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A clickable push button with IFAZ tactical styling.

Config options: text, command, variant ("primary", "success", "danger", "warning", "info"), size ("sm", "lg"), plus all CSS properties from _CONFIG_TO_CSS.

property command: Callable | None
property enabled: bool
property text: str
class iskg.widgets._controls.CheckBox(*args: Any, parent: Widget | None = None, text: str = '', checked: bool = False, command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A toggleable check box with label.

property checked: bool
property enabled: bool
property text: str
class iskg.widgets._controls.ComboBox(parent: Widget | None = None, values: list[str] | None = None, current: int = 0, command: Callable | None = None, editable: bool = False, **kwargs: Any)[source]

Bases: Widget

A dropdown select menu.

property current: int
property editable: bool
property enabled: bool
property value: str
property values: list[str]

The list of selectable options (read-only snapshot).

class iskg.widgets._controls.Entry(*args: Any, parent: Widget | None = None, text: str = '', justify: str = '', maxlength: int | None = None, **kwargs: Any)[source]

Bases: Widget

A single-line text input field.

Config options: text, placeholder, justify, width, password (bool), maxlength, plus all CSS properties from _CONFIG_TO_CSS.

property enabled: bool
property justify: str
property maxlength: int | None
property password: bool
property placeholder: str
property readonly: bool
property text: str
class iskg.widgets._controls.RadioButton(*args: Any, parent: Widget | None = None, text: str = '', group: str = 'default', command: Callable | None = None, value: str = '', variable: Any = None, selected: bool = False, **kwargs: Any)[source]

Bases: Widget

A radio button for single-selection within a group.

property enabled: bool
property group: str
property selected: bool
property text: str
property value: Any
class iskg.widgets._controls.Scale(parent: Widget | None = None, value: float = 0.5, command: Callable | None = None, from_: float = 0.0, to: float = 1.0, orient: str = 'horizontal', **kwargs: Any)[source]

Bases: Slider

A range slider with min/max labels.

property from_: float
property orient: str
property to: float
class iskg.widgets._controls.Slider(parent: Widget | None = None, value: float = 50, min_value: float | None = None, max_value: float | None = None, command: Callable | None = None, from_: float = 0, to: float = 100, orient: str = 'horizontal', **kwargs: Any)[source]

Bases: Widget

A horizontal range slider.

Config options: from, to, value, step, orient ("horizontal" / "vertical"), show_value (bool), plus all CSS properties.

property enabled: bool
property from_: float
property orient: str
property show_value: bool
property step: float | None
property to: float
property value: float
class iskg.widgets._controls.SpinBox(parent: Widget | None = None, value: int = 0, min_value: int | None = None, max_value: int | None = None, step: int = 1, command: Callable | None = None, from_: int = 0, to: int = 100, **kwargs: Any)[source]

Bases: Widget

A numeric stepper with up/down buttons.

property enabled: bool
property from_: int
property max_value: int
property min_value: int
property step: int
property to: int
property value: int
class iskg.widgets._controls.ToggleSwitch(*args: Any, parent: Widget | None = None, text: str = '', active: bool | None = None, command: Callable | None = None, checked: bool = False, **kwargs: Any)[source]

Bases: Widget

A toggle switch akin to a checkbox with slider appearance.

property checked: bool
property enabled: bool
property text: str

Widget Display

class iskg.widgets._display.IconLabel(*args: Any, parent: Widget | None = None, text: str = '', icon: str = '', icon_size: int = 14, **kwargs: Any)[source]

Bases: Widget

A label with an inline icon.

property icon: str
property icon_size: int
property text: str
class iskg.widgets._display.ImageBox(parent: Widget | None = None, src: str = '', width: int | str = 100, height: int | str = 100, fit: str = 'contain', command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A widget that displays an image.

property fit: str
property src: str
class iskg.widgets._display.IndicatorLED(parent: Widget | None = None, color: str = 'green', size: int = 8, active: bool = True, label: str = '', **kwargs: Any)[source]

Bases: Widget

A small colored indicator light.

property active: bool
property color: str
property label: str
property size: int
class iskg.widgets._display.LEDDisplay(parent: Widget | None = None, value: Any = 0, digits: int = 4, color: str = 'green', label: str = '', height: int = 32, **kwargs: Any)[source]

Bases: Widget

A seven-segment LED-style digital display.

property color: str
property digits: int
property label: str
property value: Any
class iskg.widgets._display.Label(*args: Any, parent: Widget | None = None, text: str = '', wraplength: int | None = None, anchor: str = '', justify: str = '', **kwargs: Any)[source]

Bases: Widget

A static text label.

Config options: text, wraplength, anchor, justify, plus all CSS properties from _CONFIG_TO_CSS (fg, bg, font_size, padding, etc.).

property anchor: str
property justify: str
property text: str
property wraplength: int | None
class iskg.widgets._display.ProgressBar(parent: Widget | None = None, value: float = 0, max_: int = 100, **kwargs: Any)[source]

Bases: Widget

A clickable progress bar widget.

Supports click-to-set-value, command callbacks, bind("change", cb), and variable binding.

Config options: value, max, show_text (bool, show percentage), width, plus all CSS properties.

property enabled: bool
property max_: float
property show_text: bool
property value: float
class iskg.widgets._display.RadialGauge(parent: Widget | None = None, from_: int = 0, to: int = 100, value: float = 50, size: int = 100, label: str = '', units: str = '', **kwargs: Any)[source]

Bases: Widget

A radial gauge dial for displaying values.

property from_: int
property label: str
property to: int
property units: str
property value: float
class iskg.widgets._display.StatusBar(parent: Widget | None = None, sections: list | None = None, **kwargs: Any)[source]

Bases: Widget

A status bar with multiple sections.

property sections: list
property text: str

Widget Containers

class iskg.widgets._containers.Frame(*args: Any, parent: Widget | None = None, text: str = '', flex: bool = True, **kwargs: Any)[source]

Bases: Widget

A rectangular container widget for grouping children.

Config options (via kwargs or .config()):

  • text (str): Header text shown above children.

  • container (bool): If True the outer div becomes display:flex;flex-direction:column so the inner wrapper can fill it via flex:1. Default True.

  • direction (str): "auto" (detect from children’s side), "row", or "column". Default "auto".

  • gap (int): Gap between children in pixels. Default 3.

  • skip_hidden (bool): If True, hidden children are omitted from the HTML. If False, they are rendered with display:none. Default True.

  • height_mode (str): "flex" (wrapper uses flex:1, needs container=True), "percent" (wrapper uses height:100%), or "auto". Default "flex".

grid_columnconfigure(column: int, weight: float = 0, minsize: int = 0) → None[source]
grid_rowconfigure(row: int, weight: float = 0, minsize: int = 0) → None[source]
pack_propagate(flag: bool) → None[source]
property text: str
class iskg.widgets._containers.Notebook(parent: Widget | None = None, **kwargs: Any)[source]

Bases: Widget

A tabbed container widget.

add_tab(title: str, widget: Widget) → Widget[source]
property current_tab: int
remove_tab(idx: int) → bool[source]

Remove a tab by index. Returns True if removed.

set_active(idx: int) → bool[source]

Set the active tab by index. Returns True if changed.

property tab_count: int
class iskg.widgets._containers.PanedWindow(parent: Widget | None = None, orient: str = 'horizontal', sash_pos: float = 0.5, minsize: int = 30, sash_width: int = 5, **kwargs: Any)[source]

Bases: Widget

A container with resizable panes separated by draggable dividers.

Supports any number of child panes. Each pane gets equal space initially; drag the sashes to resize adjacent panes.

Parameters:
  • parent – parent widget.

  • orient – "horizontal" (left/right panes) or "vertical" (top/bottom).

  • sash_pos – initial divider position as fraction (0.0–1.0, default 0.5). Only used when there are exactly 2 panes.

  • minsize – minimum pane size in pixels (default 30).

  • sash_width – sash thickness in pixels (default 5).

property sash_pos: float
class iskg.widgets._containers.ScrollBar(parent: Widget | None = None, orient: str = 'vertical', value: float = 0, **kwargs: Any)[source]

Bases: Widget

A scrollbar widget for scrolling content.

Config options (via kwargs or .config()):

orient (str): "vertical" or "horizontal". value (float): Scroll position as percentage (0-100). thumb_size (int): Thumb size in pixels. Default 20. step (int): Scroll step in percentage points. Default 5.

class iskg.widgets._containers.ScrolledFrame(parent: Widget | None = None, width: int | None = None, height: int | None = None, scroll: str = 'vertical', autoscroll: bool = False, scrollbar_overflow: str | None = None, **kwargs: Any)[source]

Bases: Frame

A frame with scrollbars when content overflows.

Parameters:
  • parent – parent widget.

  • width – viewport width in pixels (auto if omitted).

  • height – viewport height in pixels (auto if omitted).

  • scroll – "vertical" (default), "horizontal", or "both".

  • autoscroll – if True, auto-scrolls to bottom on content change (useful for log viewers).

  • scrollbar_overflow – custom overflow CSS override (e.g. "overflow-y:auto;scrollbar-gutter:stable;").

class iskg.widgets._containers.Separator(parent: Widget | None = None, orient: str = 'horizontal', **kwargs: Any)[source]

Bases: Widget

A horizontal or vertical visual separator line.

class iskg.widgets._containers.Spacer(parent: Widget | None = None, width: int = 0, height: int = 0, expand: bool = False, **kwargs: Any)[source]

Bases: Widget

An invisible spacer widget for layout.

Widget Text

class iskg.widgets._text.RichText(*args: Any, parent: Widget | None = None, text: str = '', height: int = 150, show_toolbar: bool = True, **kwargs: Any)[source]

Bases: Widget

A rich text editor with formatting toolbar.

property enabled: bool
property text: str
class iskg.widgets._text.Text(*args: Any, parent: Widget | None = None, text: str = '', **kwargs: Any)[source]

Bases: Widget

A multi-line text input area.

append(text: str) → None[source]
clear() → None[source]
property enabled: bool
property readonly: bool
property text: str

Widget Data

class iskg.widgets._data.DataGrid(parent: Widget | None = None, columns: list[str] | None = None, rows: list[list[str]] | None = None, column_types: list[str] | None = None, choices: dict[int, list[str]] | None = None, editable: bool = False, width: int = 300, height: int = 200, command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A sortable data table with typed cells.

Each column can be typed via column_types (a list of "text", "number", "bool", "check", "choice", "date"). When types are set, cells render with appropriate input/format and emit richer events.

Parameters:
  • parent – parent widget.

  • columns – list of column header labels.

  • column_types – list of cell types (one per column). Default: all text.

  • rows – list of rows, each row is a list of cell values.

  • choices – dict {col_index: [values]} for "choice" columns.

  • editable – if True, all cells become inline-editable. Default: False.

  • width – viewport width in px.

  • height – viewport height in px.

  • command – optional (row_idx, col_idx, value) callback.

append_row(row: list[str]) → None[source]
property choices: dict[int, list[str]]
clear() → None[source]
property column_types: list[str]
property columns: list[str]
property editable: bool
property enabled: bool
get_cell(row: int, col: int) → str[source]
remove_row(idx: int) → None[source]
property rows: list[list[str]]
property selected_col: int
property selected_row: int
set_cell(row: int, col: int, value: str) → None[source]
class iskg.widgets._data.DropTarget(parent: Widget | None = None, text: str = 'Drop files here', width: int = 200, height: int = 100, **kwargs: Any)[source]

Bases: Widget

A drag-and-drop target area.

class iskg.widgets._data.ListBox(parent: Widget | None = None, items: list[str] | None = None, command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A selectable list of items.

append(item: str) → None[source]
clear() → None[source]
delete(idx: int) → None[source]
property enabled: bool
insert(idx: int, item: str) → None[source]
property items: list[str]
property selected_index: int
class iskg.widgets._data.TreeView(parent: Widget | None = None, items: list | None = None, width: int = 200, height: int = 200, command: Callable | None = None, **kwargs: Any)[source]

Bases: Widget

A hierarchical tree view widget.

add(*args, **kwargs)[source]

Add a child widget to this widget’s children list.

If the child is already present, this is a no-op.

add_node(item, parent_path=None) → None[source]
clear() → None[source]
property enabled: bool
property items: list
remove_node(path: str) → bool[source]
property selected_path: str

Widget Canvas

class iskg.widgets._canvas.Canvas(parent: Widget | None = None, width: int = 300, height: int = 200, **kwargs: Any)[source]

Bases: Widget

A drawing surface for shapes and text.

clear() → None[source]
create_arc(x1: int, y1: int, x2: int, y2: int, start: int = 0, extent: int = 90, **kwargs: Any) → None[source]
create_image(x: int, y: int, data: bytes, **kwargs: Any) → None[source]
create_line(x1: int, y1: int, x2: int, y2: int, **kwargs: Any) → None[source]
create_oval(x1: int, y1: int, x2: int, y2: int, **kwargs: Any) → None[source]
create_polygon(*points: int, **kwargs: Any) → None[source]
create_rectangle(x1: int, y1: int, x2: int, y2: int, **kwargs: Any) → None[source]
create_text(x: int, y: int, text: str = '', **kwargs: Any) → None[source]
class iskg.widgets._canvas.Knob(parent: Widget | None = None, from_: int = 0, to: int = 100, value: float = 0, size: int = 60, color: str = 'cyan', show_value: bool = True, **kwargs: Any)[source]

Bases: Widget

A rotary knob control for adjusting values.

Config options: from, to, value, size (pixels), color, show_value (bool), plus all CSS properties.

property color: str
destroy() → None[source]

Destroy this widget and all its children.

property enabled: bool
property from_: float
property to: float
property value: float

Widget Menus

class iskg.widgets._menus.Menu(text: str = '')[source]

Bases: object

A dropdown menu for the main menu bar.

add_item(text: str, command: Callable | None = None, shortcut: str = '', icon: str = '') → MenuItem[source]
add_menu(text: str) → Menu[source]
add_separator() → None[source]
class iskg.widgets._menus.MenuBar(parent: Widget | None = None, **kwargs: Any)[source]

Bases: Widget

A main menu bar with dropdown menus.

add_menu(text: str) → Menu[source]
class iskg.widgets._menus.MenuItem(text: str, command: Callable | None = None, shortcut: str = '', icon: str = '')[source]

Bases: object

An item within a Menu.

iskg.widgets._menus.render_context_items(items: list[MenuItem | None], prefix: str = '') → str[source]

Render MenuItems as the inner HTML of a context-menu popup.

Each leaf item carries a data-cmd attribute with its slash-joined path (prefix/text); submenus are nested .iskg-menu-dd blocks.

iskg.widgets._menus.resolve_context_command(menu: Any, path: str) → Callable | None[source]

Resolve a slash-joined context-menu path to its item command.

Widget Charts

Y-axis chart widgets: time-series graph and sparkline.

class iskg.widgets._charts.Sparkline(parent: Widget | None = None, **kwargs: Any)[source]

Bases: TimeSeriesGraph

A compact single-series mini-graph.

Identical API to TimeSeriesGraph (append/replace/ update/clear); defaults to a smaller, borderless chart.

class iskg.widgets._charts.TimeSeriesGraph(parent: Widget | None = None, width: int = 300, height: int = 80, series: dict[str, str] | None = None, max_pts: int = 200, y_min: float | None = None, y_max: float | None = None, gridlines: bool = True, smooth: bool = True, **kwargs: Any)[source]

Bases: Widget

A lightweight real-time SVG chart (one or more series).

Use append() to stream values in (the graph keeps only the last max_pts points), or replace() to draw a fixed dataset.

Parameters:
  • parent – parent widget (optional).

  • height – SVG height in px.

  • series – dict mapping a series name to its colour keyword ("green"/"red"/"amber"/"cyan") or hex. A graph needs at least one series.

  • max_pts – how many trailing points to keep per series.

  • y_max (y_min /) – optional fixed Y bounds; None auto-scales.

  • gridlines – draw horizontal gridlines (default True).

  • smooth – render the series as smoothed Bézier curves instead of straight polylines (default True).

  • kwargs – forwarded to Widget.

append(series: str, value: float | None = None) → None[source]

Append one value to a series, dropping old points.

With a single-series chart you may call just append(value).

clear() → None[source]

Clear all series data.

replace(series: str | list[float], values: list[float] | None = None) → None[source]

Replace a series with a fixed dataset.

With a single-series chart you may call replace(values).

property series: list[str]

Names of the chart series.

update(value: float | None = None) → None[source]

Append to the first series (convenience for single-series graphs).

With no argument, behaves like the base update() (re-sync the widget).

property values: dict[str, list[float]]

A copy of the current data per series.

Widget Log

Scrollable, colour-coded log output widget.

class iskg.widgets._logview.LogViewer(parent: Widget | None = None, height: int = 150, max_lines: int = 500, show_timestamp: bool = False, autoscroll: bool = True, **kwargs: Any)[source]

Bases: Widget

A read-only, auto-scrolling log output area.

Lines are colour-coded by severity level and the most recent lines are shown at the bottom. Old lines beyond max_lines are dropped.

Parameters:
  • parent – parent widget (optional).

  • height – visible height in px.

  • max_lines – max lines kept before trimming.

  • show_timestamp – prefix each line with an ISO timestamp captured at append time (default False). The timestamp is frozen per line so that the rendered HTML is stable across re-renders, allowing the per-widget JS-update dedup to short-circuit no-op syncs.

  • autoscroll – always keep the view scrolled to the newest line (default True).

  • kwargs – forwarded to Widget.

append(text: str, level: str = 'INFO') → LogViewer[source]

Append a line to the log.

Parameters:
  • text – message (may contain multiple lines separated by \n).

  • level – one of "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL".

Returns:

self (for chaining).

clear() → LogViewer[source]

Clear all lines.

property lines: list[tuple[str, str]]

(severity, text) pairs currently shown.

Widget Datetime

Clock and DatePicker widgets for HUD-style displays.

class iskg.widgets._datetime.Clock(parent: Widget | None = None, seconds: bool = True, military: bool = True, command: Any = None, **kwargs: Any)[source]

Bases: Widget

A live ticking digital clock (HH:MM:SS or HH:MM).

The clock updates itself in the browser. Optional command fires on every tick.

Parameters:
  • parent – parent widget (optional).

  • seconds – show seconds (default True).

  • military – 24-hour format (default True). False renders a 12-hour clock with an AM/PM suffix.

  • command – optional callback invoked on every tick.

  • kwargs – forwarded to Widget.

destroy() → None[source]

Destroy this widget and all its children.

property military: bool
property seconds: bool
start() → None[source]

Restart the clock after a previous stop().

stop() → None[source]

Stop the clock from ticking. The widget can be re-started with start().

class iskg.widgets._datetime.DatePicker(parent: Widget | None = None, width: int = 120, date: date | None = None, command: Any = None, format_: str = '%Y-%m-%d', **kwargs: Any)[source]

Bases: Widget

A compact calendar popup for selecting a date.

Clicking the field opens a month grid with previous/next navigation; clicking a day updates the field and fires a "change" event with the ISO date string (YYYY-MM-DD) plus optional command.

Parameters:
  • parent – parent widget (optional).

  • width – field width in px.

  • date – initial date; defaults to today.

  • command – optional callback invoked on selection.

  • format – strftime-style format for the field label.

  • kwargs – forwarded to Widget.

property date: date
property date_format: str

strftime-style format for the field label.

property iso: str

The selected date as an ISO string (YYYY-MM-DD).

property value: date

The currently selected date.

Widget Dialogs

class iskg.widgets._dialogs.FileDialog[source]

Bases: object

Static methods for native file open/save dialogs.

static open_file(app: Any, title: str = 'Open', directory: str = '', file_types: list[str] | None = None, multiple: bool = False) → Any[source]
static open_folder(app: Any, title: str = 'Select Folder', directory: str = '') → Any[source]
static save_file(app: Any, title: str = 'Save As', directory: str = '', file_types: list[str] | None = None) → Any[source]
class iskg.widgets._dialogs.MessageDialog(parent: Widget | None = None, title: str = '', text: str = '', buttons: list[str] | None = None, callback: Callable[[str], None] | None = None, **kwargs: Any)[source]

Bases: Widget

A message box overlay (info/warning/error/question).

Shows an HTML overlay within the app window. Pass callback to receive the clicked button label.

show(app: Any = None) → None[source]

Show this widget.

iskg.widgets._dialogs.showerror(title: str = '', text: str = '', parent: Widget | None = None, callback: Callable[[str], None] | None = None) → MessageDialog[source]

Show an error message box (HTML overlay).

iskg.widgets._dialogs.showinfo(title: str = '', text: str = '', parent: Widget | None = None, callback: Callable[[str], None] | None = None) → MessageDialog[source]

Show an info message box (HTML overlay).

iskg.widgets._dialogs.showquestion(title: str = '', text: str = '', parent: Widget | None = None, callback: Callable[[str], None] | None = None) → MessageDialog[source]

Show a question dialog with Yes/No buttons (HTML overlay).

iskg.widgets._dialogs.showwarning(title: str = '', text: str = '', parent: Widget | None = None, callback: Callable[[str], None] | None = None) → MessageDialog[source]

Show a warning message box (HTML overlay).

Widget Misc

class iskg.widgets._misc.Tooltip(parent: Widget | None = None, text: str = '', delay: int = 500, **kwargs: Any)[source]

Bases: Widget

A tooltip that appears on hover.

attach(target_id: str) → str[source]

Template & Bridge

HTML page builder and JS bridge for ISKG widgets.

iskg.template.build_html(root_widgets: list[Any], ifaz_css: str, extra_js: str = '', extra_css: str = '', theme_name: str = 'ifaz', font_ids: list[str] | None = None) → str[source]

Theme

Base IFAZ style sheet for ISKG.

The CSS lives in iskg/themes/ifaz.css (loaded at import time) so it can be edited as a real stylesheet instead of a giant Python string. Named-theme overrides (CSS custom properties) are defined in iskg.themes.

Themes

Named theme definitions for ISKG.

Each theme is a dict of CSS custom property overrides applied on top of the default IFAZ style sheet (iskg.theme.IFAZ_CSS).

Available themes: ifaz, night, warm, cold, desert, infinity, cyberdusk, light, dracula, nord, gruvbox, monokai, catppuccin.

Usage:

from iskg.themes import THEMES, available_themes, theme_js

# List available themes
available_themes()  # -> ["ifaz", "desert", ...]

# Apply theme at runtime
app.set_theme("dracula")

# Or get JS to apply manually
js = theme_js("nord")
app.execute_js(js)
iskg.themes.available_themes() → list[str][source]

Return the list of registered theme names.

iskg.themes.resolve_theme(name: str) → dict[str, str][source]

Return the theme dict for name, falling back to "ifaz".

iskg.themes.theme_css(name: str) → str[source]

Return a CSS :root block for the named theme (for initial render).

iskg.themes.theme_js(name: str) → str[source]

Return a JavaScript snippet that applies the named theme in the browser.

Call execute_js() on the application window to apply:

app.execute_js(theme_js("cold"))

Fonts

Embedded fonts (SIL OFL) as base64 woff2 data.

No external CDN required — all fonts are compiled directly into the package as base64-encoded @font-face CSS.

Available fonts:

  • Inter (--font-sans, --font-display) — UI sans-serif

  • JetBrains Mono (--font-mono) — Monospace

  • Nunito (--font-rounded) — Rounded sans

  • Manrope (--font-geometric) — Geometric sans

  • Space Grotesk (--font-display-alt) — Display sans

  • Fira Sans (--font-humanist) — Humanist sans

  • Playfair Display (--font-serif) — Serif

Usage:

# Font CSS is automatically included in the page. Use CSS variables:
# var(--font-sans), var(--font-mono), var(--font-rounded), etc.
# Or fall back to system fonts by not setting a custom font:

widget.config(font="bold 14px var(--font-display)")

To use system fonts instead, override the CSS variable:

app._eval_js("document.documentElement.style.setProperty('--font-sans', 'Arial, sans-serif')")
iskg.fonts.font_css(ids: list[str] | None = None) → str[source]

Return @font-face CSS rules for embedded fonts.

Parameters:

ids – subset of font ids to embed ("inter", "jetbrains-mono", "nunito", "manrope", "space-grotesk", "fira-sans", "playfair-display"). None embeds all fonts.

Reactivity (hot updates)

ISKG refleja los cambios de propiedades en el DOM sin recrear el widget, por capas:

  1. Estilos (capa base _render_style_update_js): cualquier prop en _CONFIG_TO_CSS se aplica en caliente para todos los widgets vía iskg_set_style — fg/color, bg/background, font_size/font_family/font_weight, width, height, margin, padding, border_*, opacity, text_align, flex, gap, etc.

  2. Atributos (_render_attr_update_js): disabled se refleja para todos los widgets (iskg_set_enabled).

  3. Visibilidad: el setter visible usa iskg_set_visible.

  4. Por widget (_render_update_js): props semánticas — text (Button/Entry/Label/Text/RichText/IconLabel/StatusBar), value (Slider/SpinBox/ProgressBar/LEDDisplay/RadialGauge), checked (CheckBox/RadioButton/ToggleSwitch), values/current (ComboBox), color/active/size/label (IndicatorLED), src (ImageBox), etc.

Si una prop no tiene camino incremental, el escape hatch es Widget.rerender(), que reemplaza el DOM y re-engancha el JS de inicialización. Ver docs/PLAN_MEJORAS.md (roadmap, punto 3) para el contrato completo y los tests correspondientes.

Debugging

Debugging and introspection tools for ISKG apps.

class iskg.debug.Logger(name: str = 'iskg', level: str = 'info')[source]

Bases: object

Levelled logger matching the qDebug / qInfo / qWarning / qCritical Qt API.

Usage:

log = Logger()
log.debug("loading file", path=path)
log.set_level("warning")
LEVELS = {'critical': 40, 'debug': 10, 'info': 20, 'warning': 30}
critical(msg: str, **kw: Any) → None[source]
debug(msg: str, **kw: Any) → None[source]
property history: list[tuple[float, str, str]]
info(msg: str, **kw: Any) → None[source]
set_level(level: str) → None[source]
warning(msg: str, **kw: Any) → None[source]
class iskg.debug.WidgetInspector(app: Any)[source]

Bases: object

Click-to-inspect overlay: click any widget to see its class, id and full config in a floating panel.

On pick, the panel is populated from Application.get_widget() / Widget.dump() and the app event "widget-picked" is emitted with the same dict, so other tools can subscribe:

inspector = WidgetInspector(app)
inspector.enable()          # Alt+I toggles the panel
app.on("widget-picked", lambda info: print(info["type"]))

The bridge handler iskg-inspector is registered on enable() and removed on disable() (before this fix the pick event had no handler, so clicks were silently swallowed).

disable() → None[source]
enable() → None[source]
iskg.debug.disable_hot_reload() → None[source]

Cancel the most recently-started hot-reload poller.

(Hot-reload is global; this flips a sentinel checked by the next poll tick. Re-call enable_hot_reload to restart with a new file.)

iskg.debug.enable_hot_reload(app: Any, css_path: str, on_change: Callable[[str], None] | None = None, poll_interval: float = 0.5) → None[source]

Poll css_path for modifications and re-inject it when it changes.

The poller runs on the daemon after-callback worker (single thread, no race conditions). Call disable_hot_reload() to stop.

iskg.debug.fps_meter(app: Any, duration_s: float = 1.0) → float[source]

Measure the average frame rate by counting requestAnimationFrame callbacks over duration_s seconds.

iskg.debug.qCritical(msg: str) → None[source]
iskg.debug.qDebug(msg: str) → None[source]

Qt-style qDebug: print to stderr with [ISKG:debug] prefix.

iskg.debug.qInfo(msg: str) → None[source]
iskg.debug.qWarning(msg: str) → None[source]

Layout & metrics

Default visual metrics for ISKG widgets.

Single source of truth for the comfortable UI scale. The CSS theme (iskg/themes/ifaz.css) and the content-minimum propagation (iskg.base.Widget._content_min_size()) both follow these values, so a widget is never rendered — or squeezed — below them unless the code opts out explicitly (fit=False, or explicit width/height/min_width/min_height).

Note: ImageBox(fit=...) uses the name fit for its own image scaling mode (a string like "contain"); the content-minimum fit flag is a boolean and only interpreted as opt-out when strictly False.

iskg.metrics.char_width(font_size: float) → float[source]

Approximate advance width of one character in the mono UI font.

iskg.metrics.estimate_text_width(text: object, font_size: float = 11, pad_x: int = 0, letter_spacing: float = 0, extra: int = 0) → int[source]

Estimate the pixel width of text in the mono UI font.

Uses the longest line (labels/buttons do not wrap their minimum). Crude by design — it only feeds minimum-size propagation, and any explicit width/min_width set in code wins over the estimate.