Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(pets): Jarvis thinks in a pixel-art thought bubble above the pet

rubenluetke10-beep60b31952c6c6
diff --git a/docs/pets.md b/docs/pets.md
index 5fe9546d11..dd82ac6fe9 100644
--- a/docs/pets.md
+++ b/docs/pets.md
@@ -36,14 +36,16 @@ one click.
thinking or transcribing;
- speaker: silence the assistant's voice for this session (TTS volume 0,
mirrored from `VoiceSpeakerMuteChanged`).
-- **The card column** under the strip (above the pet when there is no room
- below), in the Codex companion's material — a dark, slightly see-through
- surface with a hairline rim, soft corners and a soft shadow (see *Cards*):
- - the **thinking line** while Jarvis thinks: one muted line, the current
- step, with a light sweeping across it. Never the live transcript, never
- the reply. It can be switched off (`[ui] pet_bubble`);
- - **done cards** when Jarvis answered a typed chat or a job Jarvis started
- came back: a check, what was asked, the start of the answer.
+- **The thought bubble** above the pet's head while Jarvis thinks, drawn in
+ the pets' pixel art: a white pixel cloud with a dark outline and two small
+ puffs trailing down to the head. Bobbing dots while Jarvis just thinks, the
+ current step ("Search the web") while it works. Never the live transcript,
+ never the reply. It can be switched off (`[ui] pet_bubble`). See *The
+ thought bubble*.
+- **Done cards** under the strip (above the pet when there is no room below):
+ a dark, slightly see-through surface with a hairline rim, soft corners and a
+ soft shadow, when Jarvis answered a typed chat or a job Jarvis started came
+ back — a check, what was asked, the start of the answer (see *Cards*).
- **The pet "None"** (`pet_id = "none"`) shows the control strip and the
cards without a figure.
@@ -55,12 +57,13 @@ Wayland, global shortcuts are a no-op, as for every other shortcut.
## Cards
-One window (`ui/orb/notice_stack.py`) holds the thinking line on top and the
-done cards below it; `ui/orb/pet_cards.py` draws them. On Windows the window
-carries real per-pixel alpha (`jarvis/platform/layered_window.py`,
-`UpdateLayeredWindow`): the desktop shows faintly through the cards, shadows
-and fades are soft. Elsewhere, or when Windows refuses a frame, the same frame
-is flattened onto the colour key: opaque cards with hard edges, no shadow.
+One window (`ui/orb/notice_stack.py`) holds the done cards;
+`ui/orb/pet_cards.py` draws them. Both it and the thought bubble show their
+frames through `ui/orb/layered_surface.py`: on Windows with real per-pixel
+alpha (`jarvis/platform/layered_window.py`, `UpdateLayeredWindow`) — the
+desktop shows faintly through the cards, shadows and fades are soft —
+elsewhere, or when Windows refuses a frame, flattened onto the colour key:
+opaque with hard edges, no shadow.
Done cards are about Jarvis and nothing else (`jarvis/ui/pets/notices.py`):
@@ -77,20 +80,29 @@ Done cards are always the column's width, so they stack edge to edge: the
newest in front, up to two older ones peeking out behind it, each a step
smaller and fainter and showing its surface only; at most three are kept.
Hovering fans them into a column; leaving folds them back. A click sends the
-card under the pointer away. A card leaves on its own after 9 s (`error`
-14 s), never while the pointer rests on the stack; the same card twice within
-3 s refreshes instead of stacking. Cards drift in and fade on springs, and the
+card under the pointer away. A card leaves on its own after 9 s (`error` 14
+s), never while the pointer rests on the stack; the same card twice within 3 s
+refreshes instead of stacking. Cards drift in and fade on springs, and the
check ticks itself in. The column repaints at ~60 fps only while something
-moves, at 20 fps while only the thinking line's sweep moves, and not at all at
-rest. Done cards are dropped while the bell is off, the pet is hidden, or the
-look is not the pet; the strip stays in sight while they show.
-
-## The thinking line
-
-The line mirrors Jarvis's real thinking, fed by bus events in
+moves and not at all at rest. Done cards are dropped while the bell is off,
+the pet is hidden, or the look is not the pet; the strip stays in sight while
+they show.
+
+## The thought bubble
+
+`ui/orb/thought_bubble.py` draws it at the pet sprite's own pixel size
+(`PetRenderer.factor`), nearest-neighbour like the sprites: a white cloud with
+the pets' dark outline (`#1B1622`), a shaded bottom row and a corner highlight,
+and two puffs whose smallest ends just above the pet's head. It pops in puff by
+puff, then the cloud, floats up and down by one art pixel, and pops out in
+reverse. The bare "Thinking …" label shows as three dots bobbing in turn; any
+other line is the cloud's text (ellipsized at 230 px). It repaints at ~16 fps
+while up and not at all otherwise.
+
+What it says mirrors Jarvis's real thinking, fed by bus events in
`ui/orb/bus_bridge.py` and condensed by `jarvis/ui/pets/status_line.py`:
-The surface shows ONE line: the detail when there is one, else the title.
+The bubble shows ONE line: the detail when there is one, else the title.
| Source | Title | Detail |
|---|---|---|
@@ -269,7 +281,7 @@ name.
| `set_pet_outcome(kind)` | Play the one-shot `success` or `error` |
| `set_pet_action(kind)` | `working` / `searching` for the running tool step, `None` when it ended |
| `set_pet_busy(busy)` | An agent task is running in the background |
-| `show_status(title, detail="")` | Show or update the thinking line (already condensed) |
+| `show_status(title, detail="")` | Show or update the thought bubble (already condensed) |
| `clear_status(linger_s=1.5)` | Take the card down after `linger_s` |
| `wants_status_lines` (attribute) | True only for the pet: the bridge feeds the card to nothing else |
| `set_muted(muted)` | Mirror the microphone mute on the strip |
@@ -302,7 +314,7 @@ Control-strip actions: `bell` (handled in the surface, reported through
| `[ui] orb_style` | `jarvis_bar` | `pet` selects the pet |
| `[ui] pet_id` | `gigi` | Active pet (built-in id, `u…` id or `none`) |
| `[ui] pet_scale` | `1.0` | Size multiplier, 0.5–2.0 |
-| `[ui] pet_bubble` | `true` | Show the thinking line |
+| `[ui] pet_bubble` | `true` | Show the thought bubble |
| `[ui] pet_strip_always` | `false` | Keep the control strip up even at rest |
| `[trigger] hotkey_pet_toggle` | `alt+win+p` | Hide / show the pet; empty disables it |
diff --git a/jarvis/ui/pets/notices.py b/jarvis/ui/pets/notices.py
index ef686c240a..0db8085a0e 100644
--- a/jarvis/ui/pets/notices.py
+++ b/jarvis/ui/pets/notices.py
@@ -3,8 +3,7 @@
The pet's done cards are about Jarvis and nothing else. A card appears when:
* a typed chat with Jarvis finished a turn (``JarvisChatTurnFinished``) — the
- card is what was asked over the start of Jarvis's answer, like the Codex
- companion's confirmation;
+ card is what was asked over the start of Jarvis's answer;
* a task Jarvis itself started finished: a background Jarvis-Agent task
(``JarvisAgentBackgroundCompleted``) or a coding job Jarvis delegated to an
agent (``DelegationResultReady``).
diff --git a/tests/unit/ui/test_pet_notices.py b/tests/unit/ui/test_pet_notices.py
index c559f5770b..9e8a173804 100644
--- a/tests/unit/ui/test_pet_notices.py
+++ b/tests/unit/ui/test_pet_notices.py
@@ -1,11 +1,12 @@
-"""The desktop pet's card column and bell (docs/pets.md "Cards").
+"""The desktop pet's thought bubble, done cards and bell (docs/pets.md).
Pins, without a real window: which events become done cards (Jarvis only) and
-how they read, the column's model and geometry (thinking line on top, newest
-card in front, two peeking, fanned out on hover, mirrored upward), the springs,
-the card renderer (see-through surface, soft shadow, hard edges on a colour
-key), the bell glyph and toggle, the overlay's thinking-line routing, the
-bridge, the chat service's announcement, and the macOS proxy / host round trip.
+how they read, the column's model and geometry (newest card in front, two
+peeking, fanned out on hover), the springs, the card renderer (see-through
+surface, soft shadow, hard edges on a colour key), the pixel-art thought
+bubble (dots or words, puffs that end at the head, the pop-in order), the
+bell glyph and toggle, the overlay's routing, the bridge, the chat service's
+announcement, and the macOS proxy / host round trip.
"""
from __future__ import annotations
@@ -26,9 +27,10 @@ from jarvis.core.events import (
)
from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlay
from jarvis.ui.pets import notices
-from ui.orb import controls, pet_cards
+from ui.orb import controls, pet_cards, thought_bubble
from ui.orb import notice_stack as ns
from ui.orb.bus_bridge import OrbBusBridge
+from ui.orb.layered_surface import flatten_for_key
from ui.orb.overlay import OrbOverlay
KEY = (255, 0, 255)
@@ -91,11 +93,10 @@ def test_a_twin_refreshes_and_cards_expire_unless_paused() -> None:
assert notice.kind == "done"
-def test_the_thinking_line_sits_on_top_and_cards_peek_below() -> None:
- status, slots = ns.column_layout(40, [60, 60, 60, 60], expanded=False, scale=1.0)
- assert status == ns.Slot(0.0, 1.0, 1.0)
+def test_the_newest_card_is_in_front_and_older_ones_peek_below() -> None:
+ slots = ns.column_layout([60, 60, 60, 60], expanded=False, scale=1.0)
front = slots[0]
- assert front.y == 40 + ns.CARD_GAP and front.size == 1.0 and front.opacity == 1.0
+ assert front.y == 0 and front.size == 1.0 and front.opacity == 1.0
# Each card behind is smaller and fainter, its bottom a step lower.
assert slots[1].size < 1.0 and slots[1].opacity < 1.0
bottoms = [s.y + 60 * s.size for s in slots[:3]]
@@ -104,8 +105,7 @@ def test_the_thinking_line_sits_on_top_and_cards_peek_below() -> None:
def test_fanned_out_cards_form_a_column() -> None:
- status, slots = ns.column_layout(None, [60, 80], expanded=True, scale=1.0)
- assert status is None
+ slots = ns.column_layout([60, 80], expanded=True, scale=1.0)
assert [s.y for s in slots] == [0, 60 + ns.CARD_GAP]
assert all(s.size == 1.0 and s.opacity == 1.0 for s in slots)
@@ -133,12 +133,11 @@ def test_a_done_card_is_see_through_with_a_soft_shadow() -> None:
assert card.getpixel((0, 0))[3] == 0
-def test_cards_fit_their_text_and_never_outgrow_the_limit() -> None:
- short = pet_cards.render_card("status", "Thinking …", "", scale=1.0, max_width=360)
+def test_done_cards_share_one_width_and_wrap_the_answer() -> None:
+ short = pet_cards.render_card("done", "Hi", "Hello", scale=1.0, max_width=300)
long = pet_cards.render_card("done", "word " * 40, "word " * 80, scale=1.0, max_width=300)
pad = 2 * pet_cards.SHADOW_PAD
- assert short.width - pad < 200
- assert long.width - pad <= 300
+ assert short.width == long.width == 300 + pad
assert long.height - pad < 120 # title on one line, the answer on two
@@ -151,22 +150,57 @@ def test_text_helpers_ellipsize_and_wrap() -> None:
def test_a_keyed_frame_has_hard_edges_only() -> None:
card = pet_cards.render_card("done", "Hi", "Hello", scale=1.0, max_width=360)
- flat = pet_cards.flatten_for_key(card, KEY)
+ flat = flatten_for_key(card, KEY, pet_cards.FILL_SOLID)
colours = {c for _n, c in flat.getcolors(flat.width * flat.height)}
pinkish = {c for c in colours if c != KEY and c[0] > 200 and c[2] > 200 and c[1] < 80}
assert KEY in colours and not pinkish
-def test_the_icon_ticks_itself_and_the_sweep_moves() -> None:
+def test_the_icon_ticks_itself() -> None:
empty = pet_cards.render_icon("done", 0, 20)
full = pet_cards.render_icon("done", pet_cards.ICON_FRAMES, 20)
assert empty.getchannel("A").getextrema()[1] == 0
assert full.getchannel("A").getextrema()[1] == 255
- line = pet_cards.render_card("status", "Thinking …", "", scale=1.0, max_width=360)
- a = pet_cards.shimmer(line, 4, 1.0)
- b = pet_cards.shimmer(line, 12, 1.0)
+
+
+# --- the thought bubble ------------------------------------------------------------
+
+
+def test_the_bubble_is_pixel_art_in_the_pets_palette() -> None:
+ image, layout = thought_bubble.render_bubble("", art_px=4, scale=1.0, now=0.0)
+ alpha = image.getchannel("A")
+ assert set(alpha.getdata()) <= {0, 255} # hard sprite edges, no soft alpha
+ colours = {c[:3] for _n, c in image.getcolors(image.width * image.height) if c[3]}
+ palette = {
+ thought_bubble.OUTLINE,
+ thought_bubble.FILL,
+ thought_bubble.SHADE,
+ thought_bubble.HIGHLIGHT,
+ thought_bubble.INK,
+ }
+ assert colours <= palette
+ # Every art pixel is a whole block of screen pixels.
+ assert image.width % 4 == 0 and image.height % 4 == 0
+ # The smallest puff ends near the bottom left, where the head is.
+ tip_x, tip_y = layout.tip
+ assert tip_x < image.width / 2 and tip_y > layout.body[3]
+
+
+def test_dots_bob_and_words_widen_the_cloud() -> None:
+ a, _ = thought_bubble.render_bubble("", art_px=3, scale=1.0, now=0.0)
+ b, _ = thought_bubble.render_bubble("", art_px=3, scale=1.0, now=thought_bubble.DOT_STEP_S)
assert a.tobytes() != b.tobytes()
- assert a.getchannel("A").tobytes() == line.getchannel("A").tobytes()
+ words, _ = thought_bubble.render_bubble("Search the web", art_px=3, scale=1.0, now=0.0)
+ assert words.width > a.width
+ long, _ = thought_bubble.render_bubble("word " * 80, art_px=3, scale=1.0, now=0.0)
+ assert long.width < thought_bubble.MAX_TEXT_W + 30 * 3
+
+
+def test_the_puffs_pop_in_before_the_cloud_and_leave_after_it() -> None:
+ steps = [thought_bubble.entrance(t, leaving=False) for t in (0.0, 0.13, 0.25, 0.4)]
+ assert steps == [(0, False), (1, False), (2, False), (2, True)]
+ assert thought_bubble.entrance(0.0, leaving=True) == (2, True)
+ assert thought_bubble.entrance(thought_bubble.LEAVE_S, leaving=True) == (0, False)
# --- the bell ----------------------------------------------------------------------
@@ -199,18 +233,17 @@ class _Strip:
class _Column:
+ """Records what the overlay asks of its card column and thought bubble."""
+
def __init__(self) -> None:
self.calls: list[tuple] = []
self.count = 0
- def set_status(self, line: str) -> None:
+ def set_text(self, line: str) -> None:
self.calls.append(("status", line))
- def clear_status(self, linger: float) -> None:
- self.calls.append(("clear", linger))
-
- def clear(self) -> None:
- self.calls.append(("clear_cards",))
+ def clear(self, linger: float | None = None) -> None:
+ self.calls.append(("clear", linger) if linger is not None else ("clear_cards",))
def _pet() -> tuple[OrbOverlay, _Strip, _Column]:
@@ -218,7 +251,9 @@ def _pet() -> tuple[OrbOverlay, _Strip, _Column]:
strip, column = _Strip(), _Column()
pet._controls = strip # type: ignore[assignment]
pet._notices = column # type: ignore[assignment]
+ pet._thought = column # type: ignore[assignment]
pet._card_column = lambda: column # type: ignore[method-assign]
+ pet._thought_bubble = lambda: column # type: ignore[method-assign]
pet._enqueue_ui = lambda fn: fn() # type: ignore[method-assign]
return pet, strip, column
@@ -248,15 +283,21 @@ def test_the_phone_calls_when_idle_and_hangs_up_in_a_call() -> None:
assert calls == ["talk", "hangup"]
-def test_the_thinking_line_shows_the_current_step_else_the_heading() -> None:
+def test_the_bubble_says_the_step_else_the_heading_else_dots() -> None:
pet, _strip, column = _pet()
pet.show_status("Planning", "Search the web")
- pet.show_status("Thinking …", "")
+ pet.show_status("Planning", "")
+ pet.show_status("Denkt nach …", "") # the bare label: the dots say it
pet.clear_status(2.0)
- assert column.calls == [("status", "Search the web"), ("status", "Thinking …"), ("clear", 2.0)]
+ assert column.calls == [
+ ("status", "Search the web"),
+ ("status", "Planning"),
+ ("status", ""),
+ ("clear", 2.0),
+ ]
-def test_no_thinking_line_when_the_card_is_switched_off() -> None:
+def test_no_bubble_when_it_is_switched_off() -> None:
pet, _strip, column = _pet()
pet._pet_bubble = False
pet.show_status("Thinking …", "")
diff --git a/ui/orb/controls.py b/ui/orb/controls.py
index fa6cca7b6a..7a458e3b06 100644
--- a/ui/orb/controls.py
+++ b/ui/orb/controls.py
@@ -366,8 +366,8 @@ def render_row(
# --- The pet's control strip ------------------------------------------------
-# The desktop pet (``docs/pets.md``) carries its controls in the shape the
-# Codex companion made familiar: a bell in its own filled disc, then ONE filled
+# The desktop pet (``docs/pets.md``) carries its controls in a compact row:
+# a bell in its own filled disc, then ONE filled
# pill holding microphone mute, the talk orb and the speaker, with thin
# low-contrast dividers, then the phone in its own disc — green to call Jarvis,
# red to hang up, the colours every phone app uses for exactly those two. Same
@@ -384,7 +384,7 @@ PET_PILL_ACTIONS: tuple[str, ...] = ("mic_mute", "orb", "speaker")
#: Unscaled geometry, in logical pixels at 100 % display scaling and
#: ``pet_scale`` 1.0 — sized against the companion figure (about 180 px), so the
-#: strip is roughly 0.3 x the figure's width tall, as in the Codex app.
+#: strip is roughly 0.3 x the figure's width tall.
#: ``PET_SLOT`` is the pill's height and the bell and phone discs' diameter.
PET_SLOT = 50
PET_ICON_SLOT = 46
diff --git a/ui/orb/layered_surface.py b/ui/orb/layered_surface.py
new file mode 100644
index 0000000000..acfce34146
--- /dev/null
+++ b/ui/orb/layered_surface.py
@@ -0,0 +1,221 @@
+"""A frameless always-on-top Tk window that shows one RGBA frame at a time.
+
+The pet's cards and its thought bubble are drawn in PIL with real alpha. This
+window puts such a frame on the desktop the best way the platform allows:
+
+* **Windows** — ``UpdateLayeredWindow`` (:mod:`jarvis.platform.layered_window`):
+ real per-pixel alpha, so soft shadows, see-through surfaces and fades work,
+ and fully transparent pixels let clicks through.
+* **macOS** — a transparent Tk window; the frame is flattened to hard edges
+ first (Aqua composites RGBA images without clearing the previous frame).
+* **Elsewhere**, or when Windows refuses a frame — the overlay's colour key:
+ the frame is flattened onto opaque colour with hard edges, so no blended
+ pixel survives as a pink fringe.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import tkinter as tk
+from collections.abc import Callable
+
+from PIL import Image, ImageTk
+
+from jarvis.platform import layered_window
+
+log = logging.getLogger("jarvis.orb")
+
+#: A frame's pixels at least this opaque survive flattening; the rest are keyed.
+FLATTEN_ALPHA_CUTOFF = 200
+
+
+def flatten_for_key(
+ image: Image.Image, key: tuple[int, int, int], backdrop: tuple[int, int, int]
+) -> Image.Image:
+ """``image`` for a colour-keyed window: opaque where it is mostly covered.
+
+ Pixels at least :data:`FLATTEN_ALPHA_CUTOFF` covered become the frame over
+ ``backdrop``; the rest become the key — a hard edge, never a fringe.
+ """
+ alpha = image.getchannel("A")
+ solid = Image.new("RGBA", image.size, (*backdrop, 255))
+ solid.alpha_composite(image)
+ hard = alpha.point(lambda v: 255 if v >= FLATTEN_ALPHA_CUTOFF else 0)
+ out = Image.new("RGB", image.size, key)
+ out.paste(solid.convert("RGB"), (0, 0), hard)
+ return out
+
+
+class AlphaWindow:
+ """One frameless window showing RGBA frames. Every method runs on the Tk thread."""
+
+ def __init__(
+ self,
+ parent: tk.Misc,
+ size: tuple[int, int],
+ *,
+ backdrop: tuple[int, int, int],
+ name: str = "pet surface",
+ ) -> None:
+ from ui.orb import overlay as _ov # noqa: PLC0415 — overlay imports this module
+
+ self._ov = _ov
+ self._name = name
+ self._backdrop = backdrop
+ self._size = (max(1, int(size[0])), max(1, int(size[1])))
+ self._alpha_hwnd = 0
+ self._mac_transparent = False
+ self._shown = False
+ self._photo: ImageTk.PhotoImage | None = None
+ self._image_id: int | None = None
+ top = tk.Toplevel(parent)
+ top.overrideredirect(True)
+ top.wm_attributes("-topmost", True)
+ if sys.platform == "darwin":
+ try:
+ top.wm_attributes("-transparent", True)
+ top.configure(bg="systemTransparent")
+ self._mac_transparent = True
+ except tk.TclError:
+ log.warning("macOS -transparent unsupported — the %s renders opaque", name)
+ top.configure(bg=_ov.COLOR_KEY_HEX)
+ else:
+ if layered_window.per_pixel_alpha_supported():
+ top.update_idletasks()
+ hwnd = layered_window.tk_toplevel_hwnd(top)
+ # The first frame goes in now: Windows refuses the very first
+ # UpdateLayeredWindow on a window that was already withdrawn.
+ if layered_window.enable_per_pixel_alpha(hwnd) and layered_window.update_layered(
+ hwnd, self.blank()
+ ):
+ self._alpha_hwnd = hwnd
+ if not self._alpha_hwnd:
+ try:
+ top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)
+ except tk.TclError:
+ log.debug("no colour key on this window system", exc_info=True)
+ top.configure(bg=_ov.COLOR_KEY_HEX)
+ _ov._hide_tk_window_from_task_switcher(top) # noqa: SLF001 — shared overlay helper
+ _ov._exclude_tk_window_from_capture(top) # noqa: SLF001 — shared overlay helper
+ top.withdraw()
+ canvas = tk.Canvas(
+ top,
+ width=self._size[0],
+ height=self._size[1],
+ bg="systemTransparent" if self._mac_transparent else _ov.COLOR_KEY_HEX,
+ highlightthickness=0,
+ borderwidth=0,
+ )
+ canvas.pack(fill="both", expand=True)
+ if self._mac_transparent:
+ top.update_idletasks()
+ _ov.apply_macos_clear_backing()
+ self.top: tk.Toplevel | None = top
+ self.canvas: tk.Canvas | None = canvas
+
+ @property
+ def size(self) -> tuple[int, int]:
+ return self._size
+
+ @property
+ def shown(self) -> bool:
+ return self._shown
+
+ def blank(self) -> Image.Image:
+ return Image.new("RGBA", self._size, (0, 0, 0, 0))
+
+ def bind(self, sequence: str, handler: Callable[[tk.Event], object]) -> None:
+ if self.canvas is not None:
+ self.canvas.bind(sequence, handler)
+
+ def set_cursor(self, cursor: str) -> None:
+ if self.canvas is None:
+ return
+ try:
+ self.canvas.configure(cursor=cursor)
+ except tk.TclError:
+ log.debug("%s cursor change failed", self._name, exc_info=True)
+
+ def resize(self, size: tuple[int, int]) -> None:
+ size = (max(1, int(size[0])), max(1, int(size[1])))
+ if size == self._size:
+ return
+ self._size = size
+ if self.canvas is not None:
+ try:
+ self.canvas.configure(width=size[0], height=size[1])
+ except tk.TclError:
+ log.debug("%s resize failed", self._name, exc_info=True)
+
+ def move(self, x: int, y: int) -> None:
+ if self.top is None:
+ return
+ w, h = self._size
+ try:
+ self.top.geometry(f"{w}x{h}+{int(x)}+{int(y)}")
+ except tk.TclError:
+ log.debug("%s placement failed", self._name, exc_info=True)
+
+ def present(self, frame: Image.Image) -> None:
+ """Put ``frame`` (RGBA, the window's size) on screen."""
+ _ov = self._ov
+ if self._alpha_hwnd:
+ if layered_window.update_layered(self._alpha_hwnd, frame):
+ return
+ log.warning("per-pixel alpha refused; the %s falls back to the colour key", self._name)
+ self._alpha_hwnd = 0
+ if self.top is not None:
+ try:
+ self.top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)
+ except tk.TclError:
+ log.debug("colour-key fallback failed", exc_info=True)
+ canvas = self.canvas
+ if canvas is None:
+ return
+ key = (int(_ov.COLOR_KEY_RGB[0]), int(_ov.COLOR_KEY_RGB[1]), int(_ov.COLOR_KEY_RGB[2]))
+ flat = flatten_for_key(frame, key, self._backdrop)
+ image = _ov.key_to_alpha(flat) if self._mac_transparent else flat
+ try:
+ self._photo = ImageTk.PhotoImage(image, master=canvas)
+ if self._image_id is None:
+ self._image_id = canvas.create_image(0, 0, anchor="nw", image=self._photo)
+ else:
+ canvas.itemconfigure(self._image_id, image=self._photo)
+ except tk.TclError:
+ log.debug("%s frame paint failed", self._name, exc_info=True)
+
+ def show(self) -> None:
+ if self.top is None or self._shown:
+ return
+ try:
+ self.top.deiconify()
+ self.top.lift()
+ except tk.TclError:
+ log.debug("%s show failed", self._name, exc_info=True)
+ return
+ self._shown = True
+
+ def withdraw(self) -> None:
+ if self._alpha_hwnd:
+ # A layered window keeps its last bitmap; leave nothing behind.
+ layered_window.update_layered(self._alpha_hwnd, self.blank())
+ if self.top is not None and self._shown:
+ try:
+ self.top.withdraw()
+ except tk.TclError:
+ log.debug("%s withdraw failed", self._name, exc_info=True)
+ self._shown = False
+
+ def destroy(self) -> None:
+ top, self.top, self.canvas = self.top, None, None
+ self._photo = None
+ self._shown = False
+ if top is not None:
+ try:
+ top.destroy()
+ except tk.TclError:
+ log.debug("%s destroy failed", self._name, exc_info=True)
+
+
+__all__ = ["FLATTEN_ALPHA_CUTOFF", "AlphaWindow", "flatten_for_key"]
diff --git a/ui/orb/notice_stack.py b/ui/orb/notice_stack.py
index 0d08ba116f..7ba435626e 100644
--- a/ui/orb/notice_stack.py
+++ b/ui/orb/notice_stack.py
@@ -1,44 +1,39 @@
-"""The desktop pet's card column: what Jarvis is thinking, and what it finished.
+"""The desktop pet's card column: what Jarvis finished.
-Under the control strip hangs one quiet column (the look is
-:mod:`ui.orb.pet_cards`):
-
-* **The thinking line** at the top while Jarvis thinks — one muted line with a
- light sweeping across it. It changes in place as the thought moves on and
- fades out after Jarvis stops.
-* **Done cards** below it when a Jarvis turn, or a task Jarvis started,
- finished: a check, what was asked, the start of the answer. Several stack:
- the newest in front, up to two older ones peeking out behind it, smaller
- and fainter. Hovering fans them into a column; a click sends one away; each
- leaves on its own after a while, never while the pointer rests on them.
+Under the control strip hangs one quiet column of done cards (the look is
+:mod:`ui.orb.pet_cards`; what Jarvis is thinking shows in the thought bubble
+above the pet, :mod:`ui.orb.thought_bubble`). A card appears when a Jarvis
+turn, or a task Jarvis started, finished: a check, what was asked, the start
+of the answer. Several stack: the newest in front, up to two older ones
+peeking out behind it, smaller and fainter. Hovering fans them into a column;
+a click sends one away; each leaves on its own after a while, never while the
+pointer rests on them.
Split like :mod:`ui.orb.controls`: a pure model and geometry
(:class:`NoticeModel`, :func:`column_layout`, :class:`Spring`), and one Tk
window (:class:`PetNoticeStack`) that composites the cards into a single
-frame while something moves and leaves the screen alone while nothing does.
-On Windows the frame goes through ``UpdateLayeredWindow`` with real per-pixel
-alpha (see-through cards, soft shadows, true fades); elsewhere, or if Windows
-refuses it, the same frame is flattened onto a colour key.
+frame while something moves and leaves the screen alone while nothing does
+(:class:`ui.orb.layered_surface.AlphaWindow`: real per-pixel alpha on Windows,
+a colour key elsewhere).
"""
from __future__ import annotations
import logging
-import sys
import time
import tkinter as tk
from dataclasses import dataclass, field
from itertools import count
from typing import Any
-from PIL import Image, ImageTk
+from PIL import Image
-from jarvis.platform import layered_window
from ui.orb import pet_cards
+from ui.orb.layered_surface import AlphaWindow
log = logging.getLogger("jarvis.orb")
-#: Card kinds the stack keeps (the thinking line is separate).
+#: Card kinds the stack keeps.
NOTICE_KINDS: tuple[str, ...] = ("done", "error")
#: Seconds a card stays before it leaves on its own.
NOTICE_TTL_S: dict[str, float] = {"done": 9.0, "error": 14.0}
@@ -59,8 +54,6 @@ PEEK_FADE = 0.25
SPRING_STIFFNESS = 320.0
SPRING_DAMPING = 30.0
FRAME_MS = 16
-#: Frame interval while only the thinking line's sweep moves.
-SHIMMER_FRAME_MS = 50
EXPIRY_POLL_MS = 400
COLLAPSE_GRACE_MS = 280
#: How far a card drifts while it fades in or out.
@@ -143,14 +136,8 @@ class Slot:
opacity: float
-def column_layout(
- status_h: int | None,
- heights: list[int],
- *,
- expanded: bool,
- scale: float,
-) -> tuple[Slot | None, list[Slot]]:
- """Targets for the thinking line and the cards (newest first), top down.
+def column_layout(heights: list[int], *, expanded: bool, scale: float) -> list[Slot]:
+ """Targets for the cards (newest first), top down.
Folded, every card lines up its bottom with the front card's bottom and
peeks out below it, a step smaller and fainter per place; cards past
@@ -159,26 +146,22 @@ def column_layout(
"""
gap = CARD_GAP * scale
cursor = 0.0
- status = None
- if status_h is not None:
- status = Slot(0.0, 1.0, 1.0)
- cursor = status_h + gap
slots: list[Slot] = []
if expanded:
for h in heights:
slots.append(Slot(cursor, 1.0, 1.0))
cursor += h + gap
- return status, slots
+ return slots
if not heights:
- return status, slots
- front_bottom = cursor + heights[0]
+ return slots
+ front_bottom = heights[0]
for index, h in enumerate(heights):
level = min(index, NOTICE_PEEK)
size = 1.0 - PEEK_SHRINK * level
opacity = (1.0 - PEEK_FADE * level) if index <= NOTICE_PEEK else 0.0
bottom = front_bottom + level * PEEK_OFFSET * scale
slots.append(Slot(bottom - h * size, size, opacity))
- return status, slots
+ return slots
class Spring:
@@ -216,7 +199,7 @@ class Spring:
class _Item:
"""One card on screen: its content and its moving parts."""
- key: int # notice id; 0 is the thinking line
+ key: int # the notice id
kind: str
title: str
detail: str
@@ -233,34 +216,30 @@ class PetNoticeStack:
"""The card column's own frameless window. Every method runs on the Tk thread."""
def __init__(self, parent: tk.Misc, *, scale: float = 1.0, width: int = 360) -> None:
- self._parent = parent
self._scale = max(0.25, float(scale))
self._card_w = max(160, int(width))
self._model = NoticeModel()
self._items: dict[int, _Item] = {}
self._leaving: list[_Item] = []
- self._status: _Item | None = None
self._expanded = False
self._hovered: int | None = None
self._pointer_inside = False
self._hover_since: float | None = None
self._upward = False
self._anchor: tuple[int, int, int, int, int] | None = None
- self._top: tk.Toplevel | None = None
- self._canvas: tk.Canvas | None = None
- self._photo: ImageTk.PhotoImage | None = None
- self._image_id: int | None = None
- self._alpha_hwnd = 0
- self._mac_transparent = False
self._frame_after: str | None = None
self._expiry_after: str | None = None
self._collapse_after: str | None = None
- self._status_clear_after: str | None = None
self._last_tick = 0.0
- self._shown = False
- self._build()
+ self._window = AlphaWindow(
+ parent, self.window_size, backdrop=pet_cards.FILL_SOLID, name="pet's cards"
+ )
+ self._window.bind("<Motion>", self._on_motion)
+ self._window.bind("<Enter>", self._on_motion)
+ self._window.bind("<Leave>", self._on_leave)
+ self._window.bind("<ButtonRelease-1>", self._on_click)
- # -- setup ----------------------------------------------------------------
+ # -- geometry -------------------------------------------------------------
@property
def _pad(self) -> int:
@@ -268,98 +247,33 @@ class PetNoticeStack:
@property
def window_size(self) -> tuple[int, int]:
- """Room for the thinking line plus every kept card fanned out."""
+ """Room for every kept card fanned out."""
s = self._scale
tallest_card = _spx(
2 * pet_cards.PAD_Y + 1.45 * pet_cards.TITLE_PX + 3 + 2 * 1.45 * pet_cards.BODY_PX, s
)
gap = CARD_GAP * s
- height = _spx(pet_cards.STATUS_HEIGHT, s) + NOTICE_KEEP * (tallest_card + gap) + gap
+ height = NOTICE_KEEP * (tallest_card + gap)
return self._card_w + 2 * self._pad, int(height) + 2 * self._pad
- def _blank(self) -> Image.Image:
- return Image.new("RGBA", self.window_size, (0, 0, 0, 0))
-
- def _build(self) -> None:
- from ui.orb import overlay as _ov # noqa: PLC0415 — overlay imports this module
-
- top = tk.Toplevel(self._parent)
- top.overrideredirect(True)
- top.wm_attributes("-topmost", True)
- width, height = self.window_size
- if sys.platform == "darwin":
- try:
- top.wm_attributes("-transparent", True)
- top.configure(bg="systemTransparent")
- self._mac_transparent = True
- except tk.TclError:
- log.warning("macOS -transparent unsupported — the pet's cards render opaque")
- top.configure(bg=_ov.COLOR_KEY_HEX)
- else:
- if layered_window.per_pixel_alpha_supported():
- top.update_idletasks()
- hwnd = layered_window.tk_toplevel_hwnd(top)
- # The first frame goes in now: Windows refuses the very first
- # UpdateLayeredWindow on a window that was already withdrawn.
- if layered_window.enable_per_pixel_alpha(hwnd) and layered_window.update_layered(
- hwnd, self._blank()
- ):
- self._alpha_hwnd = hwnd
- if not self._alpha_hwnd:
- try:
- top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)
- except tk.TclError:
- log.debug("no colour key on this window system", exc_info=True)
- top.configure(bg=_ov.COLOR_KEY_HEX)
- _ov._hide_tk_window_from_task_switcher(top) # noqa: SLF001 — shared overlay helper
- _ov._exclude_tk_window_from_capture(top) # noqa: SLF001 — shared overlay helper
- top.withdraw()
- canvas = tk.Canvas(
- top,
- width=width,
- height=height,
- bg="systemTransparent" if self._mac_transparent else _ov.COLOR_KEY_HEX,
- highlightthickness=0,
- borderwidth=0,
- )
- canvas.pack(fill="both", expand=True)
- if self._mac_transparent:
- top.update_idletasks()
- _ov.apply_macos_clear_backing()
- canvas.bind("<Motion>", self._on_motion)
- canvas.bind("<Enter>", self._on_motion)
- canvas.bind("<Leave>", self._on_leave)
- canvas.bind("<ButtonRelease-1>", self._on_click)
- self._top = top
- self._canvas = canvas
-
# -- public ---------------------------------------------------------------
@property
def count(self) -> int:
- """Done cards on screen (the thinking line is not counted)."""
+ """Done cards on screen."""
return len(self._model.items)
- @property
- def status_showing(self) -> bool:
- return self._status is not None
-
@property
def window(self) -> tk.Toplevel | None:
"""The column's toplevel while it is on screen (for Z-order repair)."""
- return self._top if self._shown else None
+ return self._window.top if self._window.shown else None
def set_scale(self, scale: float, width: int) -> None:
scale, width = max(0.25, float(scale)), max(160, int(width))
if (scale, width) == (self._scale, self._card_w):
return
self._scale, self._card_w = scale, width
- if self._canvas is not None:
- w, h = self.window_size
- try:
- self._canvas.configure(width=w, height=h)
- except tk.TclError:
- log.debug("card canvas resize failed", exc_info=True)
+ self._window.resize(self.window_size)
self._retarget(snap=True)
self._place()
self._kick()
@@ -406,49 +320,10 @@ class PetNoticeStack:
else:
item.born = now
self._retarget()
- self._show()
- self._kick()
-
- def set_status(self, text: str) -> None:
- """Show or update the thinking line."""
- text = " ".join(str(text or "").split())
- if not text:
- self.clear_status(0.0)
- return
- self._cancel(("_status_clear_after",))
- item = self._status
- if item is None:
- item = _Item(
- key=0,
- kind="status",
- title=text,
- detail="",
- y=Spring(0.0),
- size=Spring(0.97),
- opacity=Spring(0.0),
- born=time.monotonic(),
- )
- self._status = item
- self._retarget(fresh=0)
- else:
- item.title = text
- self._retarget()
- self._show()
+ self._place()
+ self._window.show()
self._kick()
- def clear_status(self, linger_s: float = 1.5) -> None:
- """Fade the thinking line out after ``linger_s`` seconds (at once when 0).
-
- A pending clear keeps its earlier deadline; a new status cancels it.
- """
- if self._status is None or self._top is None or self._status_clear_after is not None:
- return
- delay = max(0, int(float(linger_s) * 1000))
- if delay == 0:
- self._drop_status()
- return
- self._status_clear_after = self._top.after(delay, self._drop_status)
-
def clear(self) -> None:
"""Send every done card away (the bell was switched off)."""
for gone in self._model.clear():
@@ -462,34 +337,14 @@ class PetNoticeStack:
self._model.clear()
self._items.clear()
self._leaving.clear()
- self._status = None
self._withdraw()
def destroy(self) -> None:
self._cancel_all()
- top, self._top, self._canvas = self._top, None, None
- self._photo = None
- if top is not None:
- try:
- top.destroy()
- except tk.TclError:
- log.debug("card window destroy failed", exc_info=True)
+ self._window.destroy()
# -- motion ---------------------------------------------------------------
- def _drop_status(self) -> None:
- self._status_clear_after = None
- item = self._status
- if item is None:
- return
- item.leaving = True
- item.opacity.target = 0.0
- item.size.target = 0.97
- self._leaving.append(item)
- self._status = None
- self._retarget()
- self._kick()
-
def _send_off(self, notice_id: int) -> None:
item = self._items.pop(notice_id, None)
if item is None:
@@ -507,16 +362,11 @@ class PetNoticeStack:
frame: int | None = None,
content: bool = True,
) -> Image.Image:
- scale = round(self._scale, 3)
- if item.kind == "status":
- return pet_cards.render_card(
- "status", item.title, "", scale=scale, max_width=self._card_w
- )
return pet_cards.render_card(
item.kind,
item.title,
item.detail,
- scale=scale,
+ scale=round(self._scale, 3),
max_width=self._card_w,
hovered=hovered,
icon_frame=pet_cards.ICON_FRAMES if frame is None else frame,
@@ -531,18 +381,11 @@ class PetNoticeStack:
return [self._items[n.id] for n in self._model.items if n.id in self._items]
def _retarget(self, *, snap: bool = False, fresh: int | None = None) -> None:
- status_h = self._card_height(self._status) if self._status is not None else None
cards = self._cards()
heights = [self._card_height(c) for c in cards]
- status_slot, slots = column_layout(
- status_h, heights, expanded=self._expanded, scale=self._scale
- )
+ slots = column_layout(heights, expanded=self._expanded, scale=self._scale)
inner_h = self.window_size[1] - 2 * self._pad
- pairs: list[tuple[_Item, Slot, int]] = []
- if self._status is not None and status_slot is not None and status_h is not None:
- pairs.append((self._status, status_slot, status_h))
- pairs += list(zip(cards, slots, heights, strict=False))
- for item, slot, h in pairs:
+ for item, slot, h in zip(cards, slots, heights, strict=False):
y = slot.y
if self._upward:
# Growing up from above the pet: mirror the column, newest
@@ -561,56 +404,50 @@ class PetNoticeStack:
spring.snap()
def _kick(self, delay: int = FRAME_MS) -> None:
- if self._top is None or self._frame_after is not None:
+ top = self._window.top
+ if top is None or self._frame_after is not None:
return
self._cancel(("_expiry_after",))
self._last_tick = time.monotonic()
- self._frame_after = self._top.after(delay, self._tick)
+ self._frame_after = top.after(delay, self._tick)
def _tick(self) -> None:
self._frame_after = None
- if self._top is None:
+ top = self._window.top
+ if top is None:
return
now = time.monotonic()
dt = min(0.05, max(0.001, now - self._last_tick))
self._last_tick = now
moving = False
- for item in [*self._all_items(), *self._leaving]:
+ for item in [*self._cards(), *self._leaving]:
for spring in (item.y, item.size, item.opacity):
if spring.settled:
spring.snap()
else:
spring.step(dt)
moving = True
- if item.kind != "status" and now - item.born < 0.6:
+ if now - item.born < 0.6:
moving = True # the check is still ticking itself
self._leaving = [i for i in self._leaving if i.opacity.value > 0.02]
self._paint(now)
if moving or self._leaving:
- self._frame_after = self._top.after(FRAME_MS, self._tick)
- return
- if self._status is not None:
- # Only the sweep moves: a calmer frame rate is plenty.
- self._frame_after = self._top.after(SHIMMER_FRAME_MS, self._tick)
- if self._items:
- self._schedule_expiry()
+ self._frame_after = top.after(FRAME_MS, self._tick)
return
if not self._items:
self._withdraw()
return
self._schedule_expiry()
- def _all_items(self) -> list[_Item]:
- return ([self._status] if self._status is not None else []) + self._cards()
-
def _schedule_expiry(self) -> None:
- if self._top is None or self._expiry_after is not None or not self._items:
+ top = self._window.top
+ if top is None or self._expiry_after is not None or not self._items:
return
- self._expiry_after = self._top.after(EXPIRY_POLL_MS, self._check_expiry)
+ self._expiry_after = top.after(EXPIRY_POLL_MS, self._check_expiry)
def _check_expiry(self) -> None:
self._expiry_after = None
- if self._top is None:
+ if self._window.top is None:
return
now = time.monotonic()
if self._pointer_inside:
@@ -632,31 +469,24 @@ class PetNoticeStack:
# -- painting -------------------------------------------------------------
def _paint(self, now: float) -> None:
- frame = self._blank()
+ frame = self._window.blank()
pad = self._pad
width = frame.width
- # Back to front: the deepest card first, the thinking line last.
- order = [*reversed(self._cards()), *self._leaving]
- if self._status is not None:
- order.append(self._status)
- for item in order:
+ # Back to front: the deepest card first, leaving cards on top.
+ for item in [*reversed(self._cards()), *self._leaving]:
opacity = max(0.0, min(1.0, item.opacity.value))
if opacity <= 0.01:
item.box = (0.0, 0.0, 0.0, 0.0)
continue
- if item.kind == "status":
- step = int(now / pet_cards.SHIMMER_PERIOD_S * pet_cards.SHIMMER_STEPS)
- image = pet_cards.shimmer(self._card_image(item), step, round(self._scale, 3))
- else:
- ticked = int((now - item.born) / 0.5 * pet_cards.ICON_FRAMES)
- image = self._card_image(
- item,
- hovered=item.key == self._hovered and not item.leaving,
- frame=min(pet_cards.ICON_FRAMES, ticked),
- # Behind the front card: its edge only, no text showing
- # through the see-through card in front.
- content=item.size.value > 0.985 or item.leaving,
- )
+ ticked = int((now - item.born) / 0.5 * pet_cards.ICON_FRAMES)
+ image = self._card_image(
+ item,
+ hovered=item.key == self._hovered and not item.leaving,
+ frame=min(pet_cards.ICON_FRAMES, ticked),
+ # Behind the front card: its edge only, no text showing
+ # through the see-through card in front.
+ content=item.size.value > 0.985 or item.leaving,
+ )
size = max(0.5, item.size.value)
if abs(size - 1.0) > 0.004:
image = image.resize(
@@ -671,35 +501,7 @@ class PetNoticeStack:
y = int(round(item.y.value + pad - inset))
frame.alpha_composite(image, (max(0, x), max(0, y)))
item.box = (x + inset, y + inset, x + image.width - inset, y + image.height - inset)
- self._present(frame)
-
- def _present(self, frame: Image.Image) -> None:
- from ui.orb import overlay as _ov # noqa: PLC0415 — overlay imports this module
-
- if self._alpha_hwnd:
- if layered_window.update_layered(self._alpha_hwnd, frame):
- return
- log.warning("per-pixel alpha refused; the pet's cards fall back to the colour key")
- self._alpha_hwnd = 0
- if self._top is not None:
- try:
- self._top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)
- except tk.TclError:
- log.debug("colour-key fallback failed", exc_info=True)
- canvas = self._canvas
- if canvas is None:
- return
- key = (int(_ov.COLOR_KEY_RGB[0]), int(_ov.COLOR_KEY_RGB[1]), int(_ov.COLOR_KEY_RGB[2]))
- flat = pet_cards.flatten_for_key(frame, key)
- image = _ov.key_to_alpha(flat) if self._mac_transparent else flat
- try:
- self._photo = ImageTk.PhotoImage(image, master=canvas)
- if self._image_id is None:
- self._image_id = canvas.create_image(0, 0, anchor="nw", image=self._photo)
- else:
- canvas.itemconfigure(self._image_id, image=self._photo)
- except tk.TclError:
- log.debug("card frame paint failed", exc_info=True)
+ self._window.present(frame)
# -- pointer --------------------------------------------------------------
@@ -725,11 +527,7 @@ class PetNoticeStack:
self._schedule_collapse()
if hit != self._hovered:
self._hovered = hit
- if self._canvas is not None:
- try:
- self._canvas.configure(cursor="hand2" if hit is not None else "")
- except tk.TclError:
- log.debug("card cursor change failed", exc_info=True)
+ self._window.set_cursor("hand2" if hit is not None else "")
self._kick()
def _on_leave(self, _event: tk.Event) -> None:
@@ -754,9 +552,10 @@ class PetNoticeStack:
self._kick()
def _schedule_collapse(self) -> None:
- if self._top is None or self._collapse_after is not None or not self._expanded:
+ top = self._window.top
+ if top is None or self._collapse_after is not None or not self._expanded:
return
- self._collapse_after = self._top.after(COLLAPSE_GRACE_MS, self._collapse_now)
+ self._collapse_after = top.after(COLLAPSE_GRACE_MS, self._collapse_now)
def _collapse_now(self) -> None:
self._collapse_after = None
@@ -768,47 +567,24 @@ class PetNoticeStack:
# -- window ---------------------------------------------------------------
def _place(self) -> None:
- if self._top is None or self._anchor is None:
+ if self._anchor is None:
return
center_x, below_y, above_y, _limit, screen_w = self._anchor
width, height = self.window_size
pad = self._pad
x = max(8 - pad, min(center_x - width // 2, screen_w - width + pad - 8))
y = above_y - height + pad if self._upward else below_y - pad
- try:
- self._top.geometry(f"{width}x{height}+{x}+{y}")
- except tk.TclError:
- log.debug("card window placement failed", exc_info=True)
-
- def _show(self) -> None:
- if self._top is None or self._shown:
- return
- self._place()
- try:
- self._top.deiconify()
- self._top.lift()
- except tk.TclError:
- log.debug("card window show failed", exc_info=True)
- return
- self._shown = True
+ self._window.move(x, y)
def _withdraw(self) -> None:
self._cancel_all()
self._expanded = False
self._pointer_inside = False
self._hovered = None
- if self._alpha_hwnd:
- # A layered window keeps its last bitmap; leave nothing behind.
- layered_window.update_layered(self._alpha_hwnd, self._blank())
- if self._top is not None and self._shown:
- try:
- self._top.withdraw()
- except tk.TclError:
- log.debug("card window withdraw failed", exc_info=True)
- self._shown = False
+ self._window.withdraw()
def _cancel(self, names: tuple[str, ...]) -> None:
- top = self._top
+ top = self._window.top
for attr in names:
after_id = getattr(self, attr)
if after_id is not None and top is not None:
@@ -819,7 +595,7 @@ class PetNoticeStack:
setattr(self, attr, None)
def _cancel_all(self) -> None:
- self._cancel(("_frame_after", "_expiry_after", "_collapse_after", "_status_clear_after"))
+ self._cancel(("_frame_after", "_expiry_after", "_collapse_after"))
__all__ = [
diff --git a/ui/orb/overlay.py b/ui/orb/overlay.py
index 521a187f8d..5a77b0756e 100644
--- a/ui/orb/overlay.py
+++ b/ui/orb/overlay.py
@@ -98,6 +98,7 @@ from ui.orb.taskbar import (
get_taskbar_info,
get_tray_notify_rect,
)
+from ui.orb.thought_bubble import PetThoughtBubble
from ui.orb.voice_orb import VoiceOrbRenderer
#: The looks this window can wear (ONE definition, in jarvis.ui.overlay_styles):
@@ -259,10 +260,9 @@ ORB_BUBBLE_THEME = BubbleTheme(
)
-#: The pet's status card — the agent card of the Codex companion: a dark pill
-#: with a hairline border, a bold light title and a muted detail line, no tail
-#: and no italics. It reports what Jarvis is thinking or doing; it is not the
-#: pet talking. ``header`` is the title colour, ``text`` the detail colour.
+#: The comment bubble's look while the pet is the style: a dark pill with a
+#: hairline border, a bold light title and a muted detail line, no tail and no
+#: italics. ``header`` is the title colour, ``text`` the detail colour.
PET_BUBBLE_THEME = BubbleTheme(
bg="#1E1F22",
border="#3A3B40",
@@ -285,7 +285,7 @@ def bubble_theme_for_style(style: str) -> BubbleTheme:
return MASCOT_BUBBLE_THEME
-#: The default linger of the pet's ``clear_status`` (its thinking line).
+#: The default linger of the pet's ``clear_status`` (its thought bubble).
PET_STATUS_LINGER_S = 1.5
PET_BUBBLE_GAP = 8
#: The notification cards are this many times the strip's width.
@@ -297,6 +297,16 @@ COLOR_KEY_HEX = "#FF00FF"
COLOR_KEY_RGB = np.array([255, 0, 255], dtype=np.uint8)
+def _is_bare_thinking_label(text: str) -> bool:
+ """Is ``text`` only the generic "Thinking …" label (in any interface language)?"""
+ try:
+ from ui.orb.bus_bridge import PET_CARD_LABELS # noqa: PLC0415 — lazy, optional
+ except Exception: # noqa: BLE001 — without the labels, words are shown as words
+ return False
+ word = text.rstrip(" .…")
+ return any(word == label.rstrip(" .…") for label in PET_CARD_LABELS["thinking"].values())
+
+
def key_to_alpha(img: Image.Image) -> Image.Image:
"""RGB frame → RGBA with the magenta color key mapped to full transparency.
@@ -2302,6 +2312,8 @@ class OrbOverlay:
self._on_notify_toggle: Callable[[bool], None] | None = None
#: The notification cards' window, created with the first card.
self._notices: PetNoticeStack | None = None
+ #: The thought bubble above the pet's head, created when Jarvis first thinks.
+ self._thought: PetThoughtBubble | None = None
self._ring_after_id: str | None = None
#: The phone disc's ringing timer, like the bell's.
self._call_ring_after_id: str | None = None
@@ -2806,6 +2818,9 @@ class OrbOverlay:
notices = self._notices
if notices is not None and notices.window is not None:
windows.append(notices.window)
+ thought = self._thought
+ if thought is not None and thought.window is not None:
+ windows.append(thought.window)
for window in windows:
try:
if force or is_healthy(window) is not True:
@@ -3605,6 +3620,8 @@ class OrbOverlay:
if self._notices is not None:
# The pet's cards hang off the pet; they go with it.
self._notices.hide()
+ if self._thought is not None:
+ self._thought.hide()
if self._root is not None:
try:
self._root.withdraw()
@@ -3647,6 +3664,10 @@ class OrbOverlay:
self._notices = None
if notices is not None:
notices.destroy()
+ thought = self._thought
+ self._thought = None
+ if thought is not None:
+ thought.destroy()
except Exception: # noqa: BLE001 — teardown must reach root.destroy
logging.getLogger("jarvis.orb").debug("notice stack teardown failed", exc_info=True)
try:
@@ -3833,11 +3854,54 @@ class OrbOverlay:
return center_x, below_y, above_y, limit, screen_w
def _sync_notice_anchor(self, *, refresh_limit: bool = True) -> None:
+ """Bring the cards and the thought bubble to where the pet is now."""
+ if self._style != "pet":
+ return
+ thought = self._thought
+ if thought is not None:
+ thought.set_look(art_px=self._thought_art_px(), scale=self._pet_strip_scale())
+ thought.set_anchor(*self._thought_anchor())
notices = self._notices
- if notices is None or self._style != "pet":
+ if notices is None:
return
notices.set_anchor(self._notice_anchor(refresh_limit=refresh_limit))
+ def _thought_art_px(self) -> int:
+ """Screen pixels per art pixel: the pet sprite's own, so the bubble
+ is drawn at exactly the figure's pixel size."""
+ renderer = self._renderer
+ if isinstance(renderer, PetRenderer) and renderer.has_figure:
+ return max(1, int(renderer.factor))
+ return max(2, int(round(3 * self._pet_strip_scale())))
+
+ def _thought_anchor(self) -> tuple[int, int, int]:
+ """``(head_x, head_y, screen_w)``: where the bubble's puffs end, just
+ above and right of the middle of the pet's head."""
+ head_x = self._mascot_x + int(self._win_w * 0.6)
+ head_y = self._mascot_y + int(self._win_h * 0.08)
+ try:
+ screen_w = int(self._root.winfo_screenwidth()) if self._root is not None else 1920
+ except tk.TclError:
+ screen_w = 1920
+ return head_x, head_y, screen_w
+
+ def _thought_bubble(self) -> PetThoughtBubble | None:
+ """The bubble, built on first use; ``None`` when the pet cannot show it."""
+ if self._style != "pet" or self._root is None:
+ return None
+ if self._user_hidden or not self._window_mapped():
+ return None
+ if self._thought is None:
+ try:
+ self._thought = PetThoughtBubble(
+ self._root, art_px=self._thought_art_px(), scale=self._pet_strip_scale()
+ )
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("thought bubble unavailable", exc_info=True)
+ return None
+ self._thought.set_anchor(*self._thought_anchor())
+ return self._thought
+
def set_pet(self, pet_id: str) -> None:
"""Swap the figure live; ``"none"`` keeps the strip without a figure. Thread-safe."""
pet = str(pet_id or "").strip() or NO_PET_ID
@@ -3892,10 +3956,11 @@ class OrbOverlay:
self._kick_frame()
def show_status(self, title: str = "", detail: str = "") -> None:
- """Show or update the pet's thinking line. Thread-safe.
+ """Show or update what Jarvis is thinking, in the thought bubble. Thread-safe.
- One muted line, like the Codex companion's: the current step when
- there is one (``detail``), else the heading (``title``).
+ The current step when there is one (``detail``), else the heading
+ (``title``) — except the bare "Thinking …" label, which the bubble
+ says with its bobbing dots instead of words.
"""
if self._style != "pet":
return
@@ -3903,6 +3968,8 @@ class OrbOverlay:
if not self._pet_bubble:
return
line = " ".join(str(detail or "").split()) or " ".join(str(title or "").split())
+ if not detail and _is_bare_thinking_label(line):
+ line = ""
self._enqueue_ui(lambda: self._apply_status(line))
def clear_status(self, linger_s: float = PET_STATUS_LINGER_S) -> None:
@@ -3915,8 +3982,8 @@ class OrbOverlay:
linger = PET_STATUS_LINGER_S
def _apply() -> None:
- if self._notices is not None:
- self._notices.clear_status(linger)
+ if self._thought is not None:
+ self._thought.clear(linger)
self._enqueue_ui(_apply)
@@ -3973,8 +4040,8 @@ class OrbOverlay:
def _apply_pet_look(self) -> None:
if self._style != "pet":
return
- if not self._pet_bubble and self._notices is not None:
- self._notices.clear_status(0.0)
+ if not self._pet_bubble and self._thought is not None:
+ self._thought.hide()
renderer = self._renderer
if isinstance(renderer, PetRenderer):
renderer.set_look(pet_scale=self._pet_scale)
@@ -4015,14 +4082,10 @@ class OrbOverlay:
def _apply_status(self, line: str) -> None:
if not self._pet_bubble:
return
- # No card floating over an empty desktop: it belongs to the pet.
- notices = self._card_column()
- if notices is None:
- return
- if line:
- notices.set_status(line)
- else:
- notices.clear_status(0.0)
+ # No bubble over an empty desktop: it belongs to the pet.
+ thought = self._thought_bubble()
+ if thought is not None:
+ thought.set_text(line)
def _status_anchor(self, *, refresh_limit: bool = True) -> tuple[int, int, int, int]:
"""``(center_x, below_y, above_y, limit_bottom)`` for the status card."""
@@ -4246,6 +4309,8 @@ class OrbOverlay:
if style != "pet" and self._notices is not None:
# Notifications are the pet's; the other looks have no bell.
self._notices.hide()
+ if style != "pet" and self._thought is not None:
+ self._thought.hide()
self._ensure_controls()
self._sync_controls_visibility()
self._kick_frame()
diff --git a/ui/orb/pet_cards.py b/ui/orb/pet_cards.py
index 7b47e51800..5671054ac2 100644
--- a/ui/orb/pet_cards.py
+++ b/ui/orb/pet_cards.py
@@ -1,20 +1,14 @@
-"""The pet's cards, drawn: the thinking line and the "done" card.
-
-Two looks, one material — the Codex companion's: a dark, slightly
-see-through surface with a hairline rim, soft rounded corners and a soft
-shadow.
-
-* **status** — one muted line while Jarvis thinks ("Thinking …", "Search the
- web"). A light sweeps across the words while the line is up, so a long
- thought reads as alive without a spinner.
-* **done** / **error** — a Jarvis turn or a task Jarvis started has finished:
- a small green check (red cross) and a bold title — what was asked — over
- the first line or two of the answer.
-
-Everything is pure PIL and returns RGBA with real alpha, ready for a
-per-pixel-alpha window (:mod:`jarvis.platform.layered_window`). Where only a
-colour key exists, :func:`flatten_for_key` turns the same image into hard
-edges on an opaque fill, so a card never grows a pink fringe.
+"""The pet's done cards, drawn.
+
+A Jarvis turn or a task Jarvis started has finished: a small green check (a
+red cross when it failed) and a bold title — what was asked — over the first
+line or two of the answer, on a dark, slightly see-through surface with a
+hairline rim, soft rounded corners and a soft shadow.
+
+Everything is pure PIL and returns RGBA with real alpha, ready for
+:class:`ui.orb.layered_surface.AlphaWindow`, which flattens it onto a colour
+key where a platform has no per-pixel alpha. The text helpers (:func:`font`,
+:func:`ellipsize`, :func:`wrap`) serve the thought bubble too.
"""
from __future__ import annotations
@@ -30,11 +24,10 @@ from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
_Rgb = tuple[int, int, int]
_Rgba = tuple[int, int, int, int]
-#: What a card shows. ``status`` is the live thinking line.
-CARD_KINDS: tuple[str, ...] = ("status", "done", "error")
+#: What a card shows.
+CARD_KINDS: tuple[str, ...] = ("done", "error")
#: Unscaled geometry (logical px at 100 % and ``pet_scale`` 1.0).
-STATUS_HEIGHT = 40
PAD_X = 16
PAD_Y = 11
LINE_GAP = 3
@@ -50,7 +43,6 @@ SHADOW_ALPHA = 110
#: Font sizes in px.
TITLE_PX = 14.5
BODY_PX = 14.0
-STATUS_PX = 14.0
#: Lines of the answer under a done card's title.
DETAIL_LINES = 2
@@ -63,9 +55,6 @@ FILL_SOLID: _Rgb = (30, 30, 33)
RIM_SOLID: _Rgb = (58, 58, 63)
TITLE: _Rgb = (242, 242, 245)
BODY: _Rgb = (190, 191, 198)
-STATUS: _Rgb = (150, 151, 158)
-#: The sweep's brightest point on the status line.
-STATUS_SHINE: _Rgb = (236, 237, 242)
ICON_FILL: dict[str, _Rgb] = {"done": (34, 197, 94), "error": (239, 68, 68)}
ICON_MARK: dict[str, _Rgb] = {"done": (10, 26, 16), "error": (40, 8, 8)}
#: Hover lifts a card a shade.
@@ -73,10 +62,6 @@ HOVER_LIFT = 10
#: The icon draws itself in this many steps (the check is ticked).
ICON_FRAMES = 10
-#: Sweep positions across the status line per pass.
-SHIMMER_STEPS = 24
-SHIMMER_PERIOD_S = 1.6
-
_SS = 3 # supersampling for the card silhouette
@@ -293,28 +278,14 @@ def render_card(
"""One card as RGBA, shadow included (``SHADOW_PAD`` on every side).
A done card is always ``max_width`` wide, so stacked cards line up edge
- to edge; the thinking line fits its text. ``content=False`` draws the
+ to edge. ``content=False`` draws the
surface alone — a card peeking out behind another must not show its
text through the see-through card in front.
- ``status`` cards ignore ``detail`` handling of their own: the caller
- passes the one line to show as ``title``. Pure and cached — never mutate
- the result.
+ Pure and cached — never mutate the result.
"""
pad_x, pad_y = _px(PAD_X, scale), _px(PAD_Y, scale)
max_inner = max(40, max_width - 2 * pad_x)
- if kind == "status":
- f = font("regular", _px(STATUS_PX, scale))
- text = ellipsize(" ".join(title.split()), f, max_inner)
- width = max(_px(MIN_WIDTH, scale), int(math.ceil(_text_w(f, text))) + 2 * pad_x)
- height = _px(STATUS_HEIGHT, scale)
- radius = min(height // 2, _px(RADIUS, scale))
- card = _surface(min(width, max_width), height, radius, round(scale, 3), hovered).copy()
- pad = _px(SHADOW_PAD, scale)
- ImageDraw.Draw(card).text(
- (pad + pad_x, pad + height / 2.0), text, font=f, fill=STATUS + (255,), anchor="lm"
- )
- return card
title_font = font("semibold", _px(TITLE_PX, scale))
body_font = font("regular", _px(BODY_PX, scale))
icon_d = _px(ICON, scale)
@@ -354,70 +325,18 @@ def render_card(
return card
[email protected]_cache(maxsize=64)
-def _sweep_gain(width: int, height: int, head: int, band: int) -> Image.Image:
- """The sweep's brightness across the card: a soft band centred on ``head``."""
- row = Image.new("L", (width, 1), 0)
- px = row.load()
- for x in range(width):
- d = (x - head) / max(1, band)
- px[x, 0] = int(255 * math.exp(-d * d * 2.5))
- return row.resize((width, height))
-
-
-def shimmer(card: Image.Image, step: int, scale: float) -> Image.Image:
- """A status card with the light sweep at ``step`` of ``SHIMMER_STEPS``.
-
- The text pixels (where the card is brighter than its fill) are re-tinted
- along a soft band moving left to right; nothing else changes.
- """
- pad = _px(SHADOW_PAD, scale)
- width, height = card.size
- band = max(8.0, (width - 2 * pad) * 0.28)
- head = -band + (width + 2 * band) * ((step % SHIMMER_STEPS) / SHIMMER_STEPS)
- gain = _sweep_gain(width, height, int(round(head)), int(round(band)))
- rgb = card.convert("RGB")
- lum = rgb.convert("L")
- text = lum.point(lambda v: 255 if v > STATUS[0] - 40 else 0)
- shine = Image.new("RGBA", card.size, STATUS_SHINE + (255,))
- sweep = ImageChops.multiply(gain, text)
- out = card.copy()
- shine.putalpha(ImageChops.multiply(sweep, card.getchannel("A")))
- out.alpha_composite(shine)
- out.putalpha(card.getchannel("A")) # the sweep tints; it never changes coverage
- return out
-
-
def card_box(image: Image.Image, scale: float) -> tuple[int, int, int, int]:
"""The card's own rectangle inside its shadow-padded image."""
pad = _px(SHADOW_PAD, scale)
return pad, pad, image.width - pad, image.height - pad
-def flatten_for_key(image: Image.Image, key: _Rgb) -> Image.Image:
- """``image`` for a colour-keyed window: opaque card, keyed outside.
-
- Pixels at least half covered become the card over its solid fill; the
- rest become the key — a hard edge, so no blended pixel survives as a
- fringe. The shadow and the see-through are lost on purpose.
- """
- alpha = image.getchannel("A")
- solid = Image.new("RGBA", image.size, FILL_SOLID + (255,))
- solid.alpha_composite(image)
- hard = alpha.point(lambda v: 255 if v >= 200 else 0)
- out = Image.new("RGB", image.size, key)
- out.paste(solid.convert("RGB"), (0, 0), hard)
- return out
-
-
__all__ = [
"CARD_KINDS",
"card_box",
"ellipsize",
- "flatten_for_key",
"font",
"render_card",
"render_icon",
- "shimmer",
"wrap",
]
diff --git a/ui/orb/pet_renderer.py b/ui/orb/pet_renderer.py
index d0c9100534..f8b6668a31 100644
--- a/ui/orb/pet_renderer.py
+++ b/ui/orb/pet_renderer.py
@@ -49,8 +49,8 @@ from ui.orb import controls as orb_controls
log = logging.getLogger("jarvis.orb")
#: The visible figure's larger side at 100 % display scaling and ``pet_scale``
-#: 1.0, in logical pixels — about the size of the companion in the Codex app,
-#: so the control strip under it (``controls.PET_SLOT``) reads as its own.
+#: 1.0, in logical pixels — a desk companion's size, big enough that the
+#: control strip under it (``controls.PET_SLOT``) reads as its own.
PET_TARGET_FIGURE_PX = 180
#: Nominal window edge before a pack is loaded (the real size replaces it).
diff --git a/ui/orb/thought_bubble.py b/ui/orb/thought_bubble.py
new file mode 100644
index 0000000000..d7dc6abb61
--- /dev/null
+++ b/ui/orb/thought_bubble.py
@@ -0,0 +1,343 @@
+"""The pet's thought bubble: what Jarvis is thinking, above the pet's head.
+
+Drawn in the pets' own pixel-art language (``jarvis/ui/pets/builtin``): a
+puffy white cloud with a dark one-pixel outline, a shaded bottom row and a
+highlight in the corner, plus two small puffs trailing down to the pet's head
+— a comic thought bubble at the pet's pixel size, so it reads as part of the
+figure rather than as an app panel.
+
+* While Jarvis only thinks, three pixel dots bob in turn inside the cloud.
+* While it works through a step ("Search the web"), the step is the cloud's
+ text, in the dark ink of the pets' outlines.
+* The puffs pop in one after the other, then the cloud; on the way out the
+ order reverses. The cloud floats up and down by one art pixel.
+
+Pure rendering (:func:`render_bubble`) and one window (:class:`PetThoughtBubble`).
+Pixel art is drawn at art resolution and scaled by a whole number with
+nearest-neighbour, exactly like the pet sprites, so its edges stay crisp.
+"""
+
+from __future__ import annotations
+
+import functools
+import logging
+import math
+import time
+import tkinter as tk
+from dataclasses import dataclass
+
+from PIL import Image, ImageChops, ImageDraw, ImageFilter
+
+from ui.orb import pet_cards
+from ui.orb.layered_surface import AlphaWindow
+
+log = logging.getLogger("jarvis.orb")
+
+_Rgb = tuple[int, int, int]
+
+#: The pets' palette: the dark outline every built-in sprite uses, a white
+#: cloud, its shaded underside and its highlight, and the ink of the text.
+OUTLINE: _Rgb = (27, 22, 34)
+FILL: _Rgb = (250, 249, 253)
+SHADE: _Rgb = (222, 220, 234)
+HIGHLIGHT: _Rgb = (255, 255, 255)
+INK: _Rgb = (46, 36, 58)
+
+#: Art-pixel geometry (one art pixel = ``art_px`` screen pixels).
+PAD_X = 5
+PAD_Y = 3
+MIN_BODY_H = 11
+DOT = 2
+DOT_GAP = 2
+DOTS = 3
+#: The trailing puffs: (radius, dx from the cloud's left edge, dy below it).
+PUFFS: tuple[tuple[float, float, float], ...] = ((2.6, 6.0, 3.6), (1.7, 2.5, 8.2))
+#: Room around the art for the float and the outline.
+MARGIN = 2
+
+#: Animation timing.
+DOT_STEP_S = 0.22
+BOB_PERIOD_S = 1.8
+ENTER_S = 0.36
+LEAVE_S = 0.24
+FRAME_MS = 60
+#: Text size, logical px at 100 % (times the strip scale).
+TEXT_PX = 13.0
+#: The widest the cloud's text may get, logical px at 100 %.
+MAX_TEXT_W = 230
+
+
+@dataclass(frozen=True)
+class BubbleLayout:
+ """Where things sit in a rendered bubble, in screen pixels."""
+
+ size: tuple[int, int]
+ #: The cloud body's box (x0, y0, x1, y1).
+ body: tuple[int, int, int, int]
+ #: Where the smallest puff ends: the point that touches the pet's head.
+ tip: tuple[int, int]
+
+
+def _cloud_mask(w: int, h: int) -> Image.Image:
+ """The cloud's silhouette at art resolution: a body with puffy bumps on top.
+
+ Drawn without antialiasing — every pixel is in or out, like a sprite.
+ """
+ bump = max(3, h // 3)
+ mask = Image.new("L", (w, h + bump), 0)
+ d = ImageDraw.Draw(mask)
+ d.rounded_rectangle([0, bump, w - 1, bump + h - 1], radius=min(4, h // 2), fill=255)
+ # Evenly spaced bumps along the whole top edge make it a cloud, not a box
+ # with a hat: one about every eleven art pixels, alternating in size.
+ count = max(2, round(w / 11))
+ span = w - 2 * bump
+ for i in range(count):
+ cx = bump + span * (i + 0.5) / count
+ r = bump + (0 if i % 2 else 1)
+ rx = max(r, span / count * 0.62)
+ d.ellipse([cx - rx, bump - r + 1, cx + rx, bump + r + 1], fill=255)
+ return mask
+
+
+def _outline(mask: Image.Image) -> Image.Image:
+ """The one-pixel ring around ``mask`` (4-connected, like hand-drawn sprites)."""
+ grown = mask.filter(ImageFilter.MaxFilter(3))
+ return ImageChops.subtract(grown, mask)
+
+
[email protected]_cache(maxsize=64)
+def _art(body_w: int, body_h: int, puffs_shown: int, cloud_shown: bool) -> tuple[Image.Image, int]:
+ """The bubble at art resolution (RGBA) and the cloud's top bump height."""
+ bump = max(3, body_h // 3)
+ cloud = _cloud_mask(body_w, body_h)
+ tail_h = int(max(dy + r for r, _dx, dy in PUFFS)) + 2
+ w = body_w + 2 * MARGIN
+ h = cloud.height + tail_h + 2 * MARGIN
+ shape = Image.new("L", (w, h), 0)
+ if cloud_shown:
+ shape.paste(cloud, (MARGIN, MARGIN))
+ d = ImageDraw.Draw(shape)
+ body_bottom = MARGIN + cloud.height
+ for index, (r, dx, dy) in enumerate(PUFFS):
+ if index < len(PUFFS) - puffs_shown:
+ continue # the pop-in starts with the smallest puff, nearest the head
+ cx, cy = MARGIN + dx, body_bottom + dy
+ d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=255)
+ # Fill, then the shaded underside (the bottom art row of every blob), a
+ # corner highlight, then the outline around everything.
+ art = Image.new("RGBA", (w, h), (0, 0, 0, 0))
+ art.paste((*FILL, 255), (0, 0), shape)
+ lifted = Image.new("L", (w, h), 0)
+ lifted.paste(shape, (0, -1))
+ bottom_row = ImageChops.subtract(shape, lifted)
+ art.paste((*SHADE, 255), (0, 0), bottom_row)
+ if cloud_shown:
+ hl = ImageDraw.Draw(art)
+ x0, y0 = MARGIN + 3, MARGIN + bump + 2
+ hl.point([(x0, y0), (x0 + 1, y0), (x0, y0 + 1)], fill=(*HIGHLIGHT, 255))
+ art.paste((*OUTLINE, 255), (0, 0), _outline(shape))
+ return art, bump
+
+
+def bubble_layout(
+ text_w: int, line_h: int, *, art_px: int, dots: bool
+) -> tuple[int, int, int, int]:
+ """``(body_w, body_h, content_w, content_h)`` in art pixels."""
+ u = max(1, art_px)
+ if dots:
+ content_w = DOTS * DOT + (DOTS - 1) * DOT_GAP
+ content_h = DOT + 1
+ else:
+ content_w = math.ceil(text_w / u)
+ content_h = math.ceil(line_h / u)
+ body_w = content_w + 2 * PAD_X
+ body_h = max(MIN_BODY_H, content_h + 2 * PAD_Y)
+ return body_w, body_h, content_w, content_h
+
+
+def render_bubble(
+ text: str,
+ *,
+ art_px: int,
+ scale: float,
+ now: float,
+ puffs_shown: int = len(PUFFS),
+ cloud_shown: bool = True,
+) -> tuple[Image.Image, BubbleLayout]:
+ """The bubble as RGBA at screen size, and where its parts sit.
+
+ An empty ``text`` shows the bobbing dots. ``puffs_shown`` and
+ ``cloud_shown`` drive the pop-in and pop-out.
+ """
+ u = max(1, int(art_px))
+ font = pet_cards.font("semibold", max(9, int(round(TEXT_PX * scale))))
+ dots = not text
+ shown_text = "" if dots else pet_cards.ellipsize(text, font, MAX_TEXT_W * scale)
+ text_w = int(math.ceil(font.getlength(shown_text))) if shown_text else 0
+ ascent, descent = font.getmetrics()
+ body_w, body_h, content_w, content_h = bubble_layout(
+ text_w, ascent + descent, art_px=u, dots=dots
+ )
+ art, bump = _art(body_w, body_h, puffs_shown, cloud_shown)
+ art = art.copy()
+ body_x0, body_y0 = MARGIN, MARGIN + bump
+ if cloud_shown and dots:
+ d = ImageDraw.Draw(art)
+ phase = int(now / DOT_STEP_S) % (DOTS + 1)
+ cx0 = body_x0 + (body_w - content_w) // 2
+ cy = body_y0 + (body_h - DOT) // 2
+ for i in range(DOTS):
+ lift = 1 if i == phase else 0
+ x = cx0 + i * (DOT + DOT_GAP)
+ d.rectangle([x, cy - lift, x + DOT - 1, cy - lift + DOT - 1], fill=(*INK, 255))
+ image = art.resize((art.width * u, art.height * u), Image.Resampling.NEAREST)
+ if cloud_shown and shown_text:
+ d = ImageDraw.Draw(image)
+ cx = (body_x0 + body_w / 2.0) * u
+ cy = (body_y0 + body_h / 2.0) * u
+ d.text((cx, cy), shown_text, font=font, fill=(*INK, 255), anchor="mm")
+ small_r, small_dx, small_dy = PUFFS[-1]
+ cloud_bottom = MARGIN + bump + body_h
+ tip = (int((MARGIN + small_dx) * u), int((cloud_bottom + small_dy + small_r) * u))
+ body = (body_x0 * u, (body_y0 - bump) * u, (body_x0 + body_w) * u, (body_y0 + body_h) * u)
+ return image, BubbleLayout(size=image.size, body=body, tip=tip)
+
+
+def entrance(age_s: float, leaving: bool) -> tuple[int, bool]:
+ """``(puffs_shown, cloud_shown)`` at ``age_s`` into the pop-in (or pop-out)."""
+ span = LEAVE_S if leaving else ENTER_S
+ t = max(0.0, min(1.0, age_s / span))
+ if leaving:
+ t = 1.0 - t
+ steps = len(PUFFS) + 1
+ shown = int(t * steps + 1e-9)
+ # In: smallest puff (nearest the head) first, then the bigger one, then
+ # the cloud. ``PUFFS`` is listed big to small, so count from its end.
+ puffs = min(len(PUFFS), shown)
+ return puffs, shown >= steps
+
+
+class PetThoughtBubble:
+ """The bubble's own window. Every method runs on the Tk thread."""
+
+ def __init__(self, parent: tk.Misc, *, art_px: int = 3, scale: float = 1.0) -> None:
+ self._art_px = max(1, int(art_px))
+ self._scale = max(0.25, float(scale))
+ self._text = ""
+ self._visible = False
+ self._leaving = False
+ self._since = 0.0
+ self._anchor: tuple[int, int, int] | None = None
+ self._after: str | None = None
+ self._clear_after: str | None = None
+ self._window = AlphaWindow(parent, (8, 8), backdrop=FILL, name="thought bubble")
+
+ @property
+ def window(self) -> tk.Toplevel | None:
+ return self._window.top if self._window.shown else None
+
+ @property
+ def showing(self) -> bool:
+ return self._visible and not self._leaving
+
+ def set_look(self, *, art_px: int, scale: float) -> None:
+ self._art_px = max(1, int(art_px))
+ self._scale = max(0.25, float(scale))
+ if self._visible:
+ self._paint()
+
+ def set_anchor(self, head_x: int, head_y: int, screen_w: int) -> None:
+ """Where the trailing puffs end: just above the pet's head."""
+ self._anchor = (int(head_x), int(head_y), int(screen_w))
+ if self._visible:
+ self._paint()
+
+ def set_text(self, text: str) -> None:
+ """Show the bubble with ``text`` (``""``: the thinking dots)."""
+ self._cancel("_clear_after")
+ self._text = " ".join(str(text or "").split())
+ if not self._visible or self._leaving:
+ self._visible = True
+ self._leaving = False
+ self._since = time.monotonic()
+ self._tick()
+
+ def clear(self, linger_s: float = 1.5) -> None:
+ """Pop the bubble away after ``linger_s`` seconds (at once when 0)."""
+ if not self._visible or self._leaving or self._clear_after is not None:
+ return
+ top = self._window.top
+ delay = max(0, int(float(linger_s) * 1000))
+ if delay == 0 or top is None:
+ self._start_leaving()
+ return
+ self._clear_after = top.after(delay, self._start_leaving)
+
+ def hide(self) -> None:
+ """Gone at once (the pet was hidden)."""
+ self._cancel("_clear_after")
+ self._cancel("_after")
+ self._visible = False
+ self._leaving = False
+ self._window.withdraw()
+
+ def destroy(self) -> None:
+ self.hide()
+ self._window.destroy()
+
+ def _start_leaving(self) -> None:
+ self._clear_after = None
+ if not self._visible or self._leaving:
+ return
+ self._leaving = True
+ self._since = time.monotonic()
+ self._tick()
+
+ def _tick(self) -> None:
+ self._cancel("_after")
+ top = self._window.top
+ if top is None or not self._visible:
+ return
+ age = time.monotonic() - self._since
+ if self._leaving and age >= LEAVE_S:
+ self.hide()
+ return
+ self._paint()
+ self._after = top.after(FRAME_MS, self._tick)
+
+ def _paint(self) -> None:
+ if self._anchor is None:
+ return
+ now = time.monotonic()
+ puffs, cloud = entrance(now - self._since, self._leaving)
+ image, layout = render_bubble(
+ self._text,
+ art_px=self._art_px,
+ scale=self._scale,
+ now=now,
+ puffs_shown=puffs,
+ cloud_shown=cloud,
+ )
+ head_x, head_y, screen_w = self._anchor
+ bob = self._art_px if int(now / (BOB_PERIOD_S / 2)) % 2 else 0
+ x = head_x - layout.tip[0]
+ y = head_y - layout.tip[1] - bob
+ x = max(4, min(x, screen_w - image.width - 4))
+ y = max(4, y)
+ self._window.resize(image.size)
+ self._window.move(x, y)
+ self._window.present(image)
+ self._window.show()
+
+ def _cancel(self, name: str) -> None:
+ after_id = getattr(self, name)
+ top = self._window.top
+ if after_id is not None and top is not None:
+ try:
+ top.after_cancel(after_id)
+ except tk.TclError:
+ log.debug("thought bubble timer cancel failed", exc_info=True)
+ setattr(self, name, None)
+
+
+__all__ = ["BubbleLayout", "PetThoughtBubble", "entrance", "render_bubble"]