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(appshot): mark up the chosen area in place before the shot, ShareX-style

rubenluetke10-beepbe4762e08b0e
diff --git a/jarvis/appshot/effect.py b/jarvis/appshot/effect.py
index 66ecd78b2e..ea35e8a346 100644
--- a/jarvis/appshot/effect.py
+++ b/jarvis/appshot/effect.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import asyncio
import base64
+import contextvars
import io
import logging
from typing import Any
@@ -31,6 +32,12 @@ _THUMB_EDGE = 560
_tasks: set[asyncio.Task[None]] = set()
+#: Markings the user drew in the area picker for the capture now running
+#: (:mod:`jarvis.appshot.markup`); the thumbnail shows them like the appshot.
+shutter_markup: contextvars.ContextVar[Any] = contextvars.ContextVar(
+ "appshot_shutter_markup", default=None
+)
+
# The card's hover line — app chrome, so it follows [ui].language; a phrase
# table always carries every supported locale.
_CARD_HINTS: dict[str, str] = {
@@ -56,7 +63,7 @@ def on_shutter(target: Any, size: tuple[int, int], rgb: bytes, monitors: list[di
controller.hold_for_snap()
loop = asyncio.get_running_loop()
task = loop.create_task(
- _play(controller, tuple(target.bbox), size, rgb, monitors),
+ _play(controller, tuple(target.bbox), size, rgb, monitors, shutter_markup.get()),
name="appshot-effect",
)
_tasks.add(task)
@@ -75,6 +82,7 @@ async def _play(
size: tuple[int, int],
rgb: bytes,
monitors: list[dict],
+ markup: Any = None,
) -> None:
try:
from jarvis.core.config import load_config # noqa: PLC0415
@@ -84,6 +92,10 @@ async def _play(
return
from jarvis.appshot.card_actions import card_labels, card_rest_ms # noqa: PLC0415
+ if markup is not None:
+ from jarvis.appshot.markup import apply_to_rgb # noqa: PLC0415
+
+ size, rgb = await asyncio.to_thread(apply_to_rgb, size, rgb, markup)
thumb = await asyncio.to_thread(thumbnail_jpeg, size, rgb)
monitor, rect = placement(bbox, monitors)
shown = await controller.snap(
@@ -179,4 +191,11 @@ def placement(
]
-__all__ = ["attach_card_image", "card_hint", "on_shutter", "placement", "thumbnail_jpeg"]
+__all__ = [
+ "attach_card_image",
+ "card_hint",
+ "on_shutter",
+ "placement",
+ "shutter_markup",
+ "thumbnail_jpeg",
+]
diff --git a/jarvis/appshot/markup.py b/jarvis/appshot/markup.py
new file mode 100644
index 0000000000..7cb0639f52
--- /dev/null
+++ b/jarvis/appshot/markup.py
@@ -0,0 +1,163 @@
+"""Burn the picker's markings into the real appshot.
+
+The area picker lets the user mark the chosen area up before the shot is
+taken (:mod:`jarvis.appshot.picker.annotate`). Its markings arrive here as a
+transparent PNG overlay of the area plus a list of blur/pixelate rectangles.
+The capture itself still runs through Screen Context — denylist, redaction
+and all — and only the finished, privacy-filtered picture gets the markings:
+
+1. blur and pixelate patches, on the capture's own pixels;
+2. the overlay on top, stretched to the capture's size (the overlay is drawn
+ at the overlay screen's pixel density, the capture may be downscaled).
+
+So the assistant sees exactly what the user pointed at. Pure Pillow, no GUI —
+works on every OS and on a headless box.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import io
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+HIDE_KINDS = ("blur", "pixelate")
+#: Blur radius and pixelate block as a share of the capture's longer side —
+#: strong enough that text under them cannot be read back.
+_BLUR_SHARE = 0.008
+_PIXEL_SHARE = 0.009
+#: An overlay larger than this (decoded bytes) is refused as garbage.
+_MAX_OVERLAY_BYTES = 64 * 1024 * 1024
+
+FRect = tuple[float, float, float, float]
+
+
+@dataclass(frozen=True, slots=True)
+class Hide:
+ kind: str
+ rect: FRect
+
+
+@dataclass(frozen=True, slots=True)
+class Markup:
+ """The user's markings on an area appshot."""
+
+ overlay_png: bytes = b""
+ hides: tuple[Hide, ...] = ()
+
+ @property
+ def empty(self) -> bool:
+ return not self.overlay_png and not self.hides
+
+
+def parse_markup(payload: Any) -> Markup | None:
+ """The picker's ``markup`` object → :class:`Markup`; ``None`` when absent or empty."""
+ if not isinstance(payload, dict):
+ return None
+ overlay = b""
+ raw = payload.get("overlay")
+ if isinstance(raw, str) and raw:
+ try:
+ overlay = base64.b64decode(raw, validate=True)
+ except (binascii.Error, ValueError):
+ log.warning("appshot: the picker sent an unreadable markings overlay; ignored")
+ overlay = b""
+ if len(overlay) > _MAX_OVERLAY_BYTES or not overlay.startswith(b"\x89PNG\r\n\x1a\n"):
+ overlay = b""
+ hides: list[Hide] = []
+ for item in payload.get("hides") or ():
+ if not isinstance(item, dict) or item.get("kind") not in HIDE_KINDS:
+ continue
+ rect = item.get("rect")
+ if not isinstance(rect, (list, tuple)) or len(rect) != 4:
+ continue
+ try:
+ fx, fy, fw, fh = (max(0.0, min(1.0, float(v))) for v in rect)
+ except (TypeError, ValueError):
+ continue
+ if fw > 0 and fh > 0:
+ hides.append(Hide(kind=str(item["kind"]), rect=(fx, fy, fw, fh)))
+ markup = Markup(overlay_png=overlay, hides=tuple(hides))
+ return None if markup.empty else markup
+
+
+def apply_to_image(image: Any, markup: Markup) -> Any:
+ """Return a new RGB Pillow image with ``markup`` burnt in."""
+ from PIL import Image, ImageFilter # noqa: PLC0415
+
+ out = image.convert("RGB")
+ width, height = out.size
+ longer = max(width, height)
+ for hide in markup.hides:
+ fx, fy, fw, fh = hide.rect
+ box = (
+ round(fx * width),
+ round(fy * height),
+ min(width, round((fx + fw) * width)),
+ min(height, round((fy + fh) * height)),
+ )
+ if box[2] - box[0] < 1 or box[3] - box[1] < 1:
+ continue
+ patch = out.crop(box)
+ if hide.kind == "pixelate":
+ block = max(4, round(longer * _PIXEL_SHARE))
+ small = patch.resize(
+ (max(1, patch.width // block), max(1, patch.height // block)),
+ Image.Resampling.BOX,
+ )
+ patch = small.resize(patch.size, Image.Resampling.NEAREST)
+ else:
+ radius = max(4.0, longer * _BLUR_SHARE)
+ # Blur twice: one pass leaves large text guessable.
+ patch = patch.filter(ImageFilter.GaussianBlur(radius)).filter(
+ ImageFilter.GaussianBlur(radius)
+ )
+ out.paste(patch, box[:2])
+ if markup.overlay_png:
+ with Image.open(io.BytesIO(markup.overlay_png)) as overlay:
+ layer = overlay.convert("RGBA")
+ if layer.size != out.size:
+ layer = layer.resize(out.size, Image.Resampling.LANCZOS)
+ base = out.convert("RGBA")
+ base.alpha_composite(layer)
+ out = base.convert("RGB")
+ return out
+
+
+def apply_to_bytes(image: bytes, mime: str, markup: Markup) -> bytes:
+ """``image`` (JPEG or PNG bytes) with the markings, in the same format."""
+ from PIL import Image # noqa: PLC0415
+
+ with Image.open(io.BytesIO(image)) as picture:
+ marked = apply_to_image(picture, markup)
+ buffer = io.BytesIO()
+ if mime == "image/png":
+ marked.save(buffer, format="PNG", optimize=True)
+ else:
+ marked.save(buffer, format="JPEG", quality=90, optimize=True)
+ return buffer.getvalue()
+
+
+def apply_to_rgb(
+ size: tuple[int, int], rgb: bytes, markup: Markup
+) -> tuple[tuple[int, int], bytes]:
+ """The raw frame with the markings — for the shutter thumbnail only."""
+ from PIL import Image # noqa: PLC0415
+
+ marked = apply_to_image(Image.frombytes("RGB", size, rgb), markup)
+ return marked.size, marked.tobytes()
+
+
+__all__ = [
+ "HIDE_KINDS",
+ "Hide",
+ "Markup",
+ "apply_to_bytes",
+ "apply_to_image",
+ "apply_to_rgb",
+ "parse_markup",
+]
diff --git a/jarvis/appshot/picker/__init__.py b/jarvis/appshot/picker/__init__.py
index 74813e9697..c327720d77 100644
--- a/jarvis/appshot/picker/__init__.py
+++ b/jarvis/appshot/picker/__init__.py
@@ -1,17 +1,23 @@
"""The area picker for region appshots — a one-shot PySide6 sidecar.
-``python -m jarvis.appshot.picker --hint "<text>"`` dims every screen, lets
-the user drag one rectangle and prints the result as one JSON line on stdout,
-then exits. The main process never imports PySide6 (AP-26); it talks to this
-process through :mod:`jarvis.appshot.region`.
+``python -m jarvis.appshot.picker --lang de`` dims every screen, lets the
+user drag one rectangle, mark it up in place with a toolbar and prints
+the result as one JSON line on stdout, then exits. The main process never
+imports PySide6 (AP-26); it talks to this process through
+:mod:`jarvis.appshot.region`.
Wire format (one JSON object per line):
stdout::
{"event": "ready"} # overlay is up
+ {"event": "marking"} # area chosen, toolbar up
{"event": "selection", "screen": {"x":…, "y":…, # the Qt screen,
- "w":…, "h":…, "dpr":…}, "rect": [fx, fy, fw, fh]} # fractions of it
+ "w":…, "h":…, "dpr":…}, "rect": [fx, fy, fw, fh], # fractions of it,
+ "action": "done" | "copy" | "save" | "edit", # what the user pressed,
+ "markup": {"overlay": "<b64 PNG>", # markings (optional):
+ "hides": [{"kind": "blur" | "pixelate", # transparent overlay of
+ "rect": [fx, fy, fw, fh]}]}} # the area + hide patches
{"event": "selection", "cancelled": true} # Esc / right-click
stdin::
@@ -32,7 +38,14 @@ from typing import Any
EXIT_NO_GUI = 3
EVENT_READY = "ready"
+EVENT_MARKING = "marking"
EVENT_SELECTION = "selection"
+#: What finishing the selection asks for besides taking the appshot.
+ACTION_DONE = "done"
+ACTION_COPY = "copy"
+ACTION_SAVE = "save"
+ACTION_EDIT = "edit"
+ACTIONS = (ACTION_DONE, ACTION_COPY, ACTION_SAVE, ACTION_EDIT)
CMD_CANCEL = "cancel"
CMD_LAYOUT = "layout"
@@ -51,8 +64,14 @@ def decode(line: str) -> dict[str, Any] | None:
__all__ = [
+ "ACTIONS",
+ "ACTION_COPY",
+ "ACTION_DONE",
+ "ACTION_EDIT",
+ "ACTION_SAVE",
"CMD_CANCEL",
"CMD_LAYOUT",
+ "EVENT_MARKING",
"EVENT_READY",
"EVENT_SELECTION",
"EXIT_NO_GUI",
diff --git a/jarvis/appshot/picker/__main__.py b/jarvis/appshot/picker/__main__.py
index af9311b351..82aa136770 100644
--- a/jarvis/appshot/picker/__main__.py
+++ b/jarvis/appshot/picker/__main__.py
@@ -17,7 +17,9 @@ def main(argv: list[str] | None = None) -> int:
# Accepted and ignored: a main process started before the picker lost its
# banner still passes it until the app restarts.
parser.add_argument("--hint", default="")
- parser.parse_args(argv)
+ # The toolbar's tooltip language ([ui].language); English when absent.
+ parser.add_argument("--lang", default="en")
+ args = parser.parse_args(argv)
try:
from jarvis.appshot.picker.renderer import run # noqa: PLC0415
except ImportError as exc:
@@ -26,7 +28,7 @@ def main(argv: list[str] | None = None) -> int:
"extra to select an area for an appshot.\n"
)
return EXIT_NO_GUI
- return run()
+ return run(args.lang)
if __name__ == "__main__":
diff --git a/jarvis/appshot/picker/annotate.py b/jarvis/appshot/picker/annotate.py
new file mode 100644
index 0000000000..67425abd2f
--- /dev/null
+++ b/jarvis/appshot/picker/annotate.py
@@ -0,0 +1,784 @@
+"""Mark up a chosen area in place with the picker's annotation tools.
+
+Runs ONLY inside ``python -m jarvis.appshot.picker`` (PySide6, AP-26). Once
+an area is chosen the overlay stays up: a toolbar docks under the selection
+and the user draws on the frozen frame right there — boxes, circles, arrows,
+lines, pen and highlighter strokes, text, numbered steps, blur and pixelate.
+Enter (or the check button) takes the appshot WITH the markings, so the
+assistant sees exactly what was pointed at.
+
+The rules live in :mod:`jarvis.appshot.picker.markup_model` (plain data);
+this module paints them, draws the toolbar and turns input into model calls.
+The markings leave the process as a transparent PNG overlay plus the
+blur/pixelate rectangles; the main process applies both to the real,
+privacy-filtered capture (:mod:`jarvis.appshot.markup`).
+"""
+
+from __future__ import annotations
+
+import base64
+import math
+from collections.abc import Callable
+
+from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QPointF, QRectF, QSize, Qt, Signal
+from PySide6.QtGui import (
+ QColor,
+ QFont,
+ QFontMetricsF,
+ QGuiApplication,
+ QIcon,
+ QImage,
+ QPainter,
+ QPainterPath,
+ QPen,
+ QPixmap,
+ QPolygonF,
+)
+from PySide6.QtWidgets import (
+ QButtonGroup,
+ QFrame,
+ QGraphicsDropShadowEffect,
+ QHBoxLayout,
+ QToolButton,
+ QWidget,
+)
+
+from jarvis.appshot.picker import markup_model as mm
+
+#: The world outside the selection while marking up: darker than the idle
+#: veil, so the eye stays on the area being marked.
+DIM_OUTSIDE = QColor(0, 0, 0, 120)
+_HANDLE_FILL = QColor(255, 255, 255)
+_HANDLE_EDGE = QColor(0, 0, 0, 110)
+_HANDLE_R = 4.0
+#: Logical px per pixelate block, and the blur's downscale factor.
+_PIXEL_BLOCK = 9.0
+_BLUR_FACTOR = 12.0
+_HIGHLIGHT_ALPHA = 105
+
+# Toolbar wording — app chrome, so it follows [ui].language like the card.
+_LABELS: dict[str, dict[str, str]] = {
+ "en": {
+ mm.MOVE: "Select and move",
+ mm.RECT: "Rectangle",
+ mm.ELLIPSE: "Ellipse",
+ mm.ARROW: "Arrow",
+ mm.LINE: "Line",
+ mm.PEN: "Pen",
+ mm.HIGHLIGHT: "Highlighter",
+ mm.TEXT: "Text",
+ mm.COUNTER: "Numbered step",
+ mm.BLUR: "Blur",
+ mm.PIXELATE: "Pixelate",
+ "color": "Colour",
+ "width": "Line width (mouse wheel)",
+ "undo": "Undo",
+ "redo": "Redo",
+ "copy": "Copy",
+ "save": "Save to Downloads",
+ "edit": "Open in the editor",
+ "cancel": "Cancel",
+ "done": "Done — send to the assistant",
+ },
+ "de": {
+ mm.MOVE: "Auswählen und verschieben", # i18n-allow: product UI string
+ mm.RECT: "Rechteck", # i18n-allow: product UI string
+ mm.ELLIPSE: "Ellipse", # i18n-allow: product UI string
+ mm.ARROW: "Pfeil", # i18n-allow: product UI string
+ mm.LINE: "Linie", # i18n-allow: product UI string
+ mm.PEN: "Stift", # i18n-allow: product UI string
+ mm.HIGHLIGHT: "Textmarker", # i18n-allow: product UI string
+ mm.TEXT: "Text", # i18n-allow: product UI string
+ mm.COUNTER: "Nummerierter Schritt", # i18n-allow: product UI string
+ mm.BLUR: "Weichzeichnen", # i18n-allow: product UI string
+ mm.PIXELATE: "Verpixeln", # i18n-allow: product UI string
+ "color": "Farbe", # i18n-allow: product UI string
+ "width": "Linienstärke (Mausrad)", # i18n-allow: product UI string
+ "undo": "Rückgängig", # i18n-allow: product UI string
+ "redo": "Wiederholen", # i18n-allow: product UI string
+ "copy": "Kopieren", # i18n-allow: product UI string
+ "save": "In Downloads speichern", # i18n-allow: product UI string
+ "edit": "Im Editor öffnen", # i18n-allow: product UI string
+ "cancel": "Abbrechen", # i18n-allow: product UI string
+ "done": "Fertig — an den Assistenten", # i18n-allow: product UI string
+ },
+ "es": {
+ mm.MOVE: "Seleccionar y mover", # i18n-allow: product UI string
+ mm.RECT: "Rectángulo", # i18n-allow: product UI string
+ mm.ELLIPSE: "Elipse", # i18n-allow: product UI string
+ mm.ARROW: "Flecha", # i18n-allow: product UI string
+ mm.LINE: "Línea", # i18n-allow: product UI string
+ mm.PEN: "Lápiz", # i18n-allow: product UI string
+ mm.HIGHLIGHT: "Resaltador", # i18n-allow: product UI string
+ mm.TEXT: "Texto", # i18n-allow: product UI string
+ mm.COUNTER: "Paso numerado", # i18n-allow: product UI string
+ mm.BLUR: "Desenfocar", # i18n-allow: product UI string
+ mm.PIXELATE: "Pixelar", # i18n-allow: product UI string
+ "color": "Color", # i18n-allow: product UI string
+ "width": "Grosor (rueda del ratón)", # i18n-allow: product UI string
+ "undo": "Deshacer", # i18n-allow: product UI string
+ "redo": "Rehacer", # i18n-allow: product UI string
+ "copy": "Copiar", # i18n-allow: product UI string
+ "save": "Guardar en Descargas", # i18n-allow: product UI string
+ "edit": "Abrir en el editor", # i18n-allow: product UI string
+ "cancel": "Cancelar", # i18n-allow: product UI string
+ "done": "Listo — enviar al asistente", # i18n-allow: product UI string
+ },
+}
+
+#: Shortcut shown in each tooltip.
+_ACTION_KEYS = {
+ "undo": "Ctrl+Z",
+ "redo": "Ctrl+Y",
+ "copy": "Ctrl+C",
+ "save": "Ctrl+S",
+ "edit": "Ctrl+E",
+ "cancel": "Esc",
+ "done": "Enter",
+}
+
+
+def labels_for(language: str) -> dict[str, str]:
+ return dict(_LABELS.get((language or "").lower()[:2], _LABELS["en"]))
+
+
+def _qcolor(hex_color: str, alpha: int = 255) -> QColor:
+ colour = QColor(hex_color)
+ colour.setAlpha(alpha)
+ return colour
+
+
+def _is_light(hex_color: str) -> bool:
+ c = QColor(hex_color)
+ return (0.299 * c.red() + 0.587 * c.green() + 0.114 * c.blue()) > 160
+
+
+def _qrect(box: mm.Box) -> QRectF:
+ return QRectF(box[0], box[1], box[2], box[3])
+
+
+def _text_font(shape: mm.Shape) -> QFont:
+ font = QFont()
+ font.setPixelSize(max(8, round(mm.text_size(shape.width))))
+ font.setWeight(QFont.Weight.Bold)
+ font.setStyleHint(QFont.StyleHint.SansSerif)
+ return font
+
+
+def text_rect(shape: mm.Shape) -> QRectF:
+ """A text marking's exact bounds, measured with its own font."""
+ metrics = QFontMetricsF(_text_font(shape))
+ lines = shape.text.split("\n") or [""]
+ width = max(metrics.horizontalAdvance(line) for line in lines)
+ x, y = shape.points[0]
+ return QRectF(x, y, max(width, metrics.averageCharWidth()), metrics.lineSpacing() * len(lines))
+
+
+# --------------------------------------------------------------------------
+# Painting the markings
+# --------------------------------------------------------------------------
+
+
+def _arrow_polygon(start: mm.Point, end: mm.Point, width: float) -> QPolygonF | None:
+ """A tapered arrow: thin tail, wide shaft, sharp head."""
+ dx, dy = end[0] - start[0], end[1] - start[1]
+ length = math.hypot(dx, dy)
+ if length < 1.0:
+ return None
+ ux, uy = dx / length, dy / length
+ nx, ny = -uy, ux
+ head = min(length * 0.6, max(12.0, width * 3.4 + 8.0))
+ head_half = head * 0.62
+ tail_half = max(0.6, width * 0.3)
+ shaft_half = max(1.2, width * 0.75)
+ bx, by = end[0] - ux * head, end[1] - uy * head
+ points = [
+ (start[0] + nx * tail_half, start[1] + ny * tail_half),
+ (bx + nx * shaft_half, by + ny * shaft_half),
+ (bx + nx * head_half, by + ny * head_half),
+ end,
+ (bx - nx * head_half, by - ny * head_half),
+ (bx - nx * shaft_half, by - ny * shaft_half),
+ (start[0] - nx * tail_half, start[1] - ny * tail_half),
+ ]
+ return QPolygonF([QPointF(x, y) for x, y in points])
+
+
+def _stroke_path(points: list[mm.Point]) -> QPainterPath:
+ path = QPainterPath(QPointF(*points[0]))
+ if len(points) == 1:
+ path.lineTo(QPointF(points[0][0] + 0.01, points[0][1]))
+ for point in points[1:]:
+ path.lineTo(QPointF(*point))
+ return path
+
+
+def paint_shape(
+ painter: QPainter,
+ shape: mm.Shape,
+ *,
+ hide_source: Callable[[mm.Shape], QPixmap | None] | None = None,
+ caret: bool = False,
+) -> None:
+ """Paint one marking in the painter's current (logical) coordinates."""
+ if not shape.points:
+ return
+ painter.save()
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ colour = _qcolor(shape.color)
+ kind = shape.kind
+ if kind in mm.HIDE_KINDS:
+ box = _qrect(mm.normalized(shape.points[0], shape.points[-1]))
+ patch = hide_source(shape) if hide_source is not None else None
+ if patch is not None:
+ painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, kind == mm.BLUR)
+ painter.drawPixmap(box, patch, QRectF(patch.rect()))
+ else:
+ painter.fillRect(box, QColor(128, 128, 132, 220))
+ elif kind in (mm.RECT, mm.ELLIPSE):
+ pen = QPen(colour, shape.width)
+ pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ box = _qrect(mm.normalized(shape.points[0], shape.points[-1]))
+ if kind == mm.RECT:
+ painter.drawRect(box)
+ else:
+ painter.drawEllipse(box)
+ elif kind == mm.LINE:
+ pen = QPen(colour, shape.width)
+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)
+ painter.setPen(pen)
+ painter.drawLine(QPointF(*shape.points[0]), QPointF(*shape.points[-1]))
+ elif kind == mm.ARROW:
+ polygon = _arrow_polygon(shape.points[0], shape.points[-1], shape.width)
+ if polygon is not None:
+ edge = QPen(colour, 1.0)
+ edge.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ painter.setPen(edge)
+ painter.setBrush(colour)
+ painter.drawPolygon(polygon)
+ elif kind in mm.STROKE_KINDS:
+ highlight = kind == mm.HIGHLIGHT
+ width = shape.width * 4.0 + 8.0 if highlight else shape.width
+ pen = QPen(_qcolor(shape.color, _HIGHLIGHT_ALPHA) if highlight else colour, width)
+ pen.setCapStyle(Qt.PenCapStyle.FlatCap if highlight else Qt.PenCapStyle.RoundCap)
+ pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawPath(_stroke_path(shape.points))
+ elif kind == mm.TEXT:
+ _paint_text(painter, shape, caret=caret)
+ elif kind == mm.COUNTER:
+ r = mm.counter_radius(shape.width)
+ centre = QPointF(*shape.points[0])
+ painter.setPen(QPen(QColor(255, 255, 255, 235), 2.0))
+ painter.setBrush(colour)
+ painter.drawEllipse(centre, r, r)
+ font = QFont()
+ font.setPixelSize(max(8, round(r * 1.15)))
+ font.setWeight(QFont.Weight.Bold)
+ painter.setFont(font)
+ painter.setPen(QColor(17, 17, 17) if _is_light(shape.color) else QColor(255, 255, 255))
+ painter.drawText(
+ QRectF(centre.x() - r, centre.y() - r, 2 * r, 2 * r),
+ Qt.AlignmentFlag.AlignCenter,
+ str(shape.number),
+ )
+ painter.restore()
+
+
+def _paint_text(painter: QPainter, shape: mm.Shape, *, caret: bool) -> None:
+ font = _text_font(shape)
+ metrics = QFontMetricsF(font)
+ x, y = shape.points[0]
+ path = QPainterPath()
+ lines = shape.text.split("\n")
+ for i, line in enumerate(lines):
+ path.addText(QPointF(x, y + metrics.ascent() + i * metrics.lineSpacing()), font, line)
+ halo = QColor(17, 17, 17, 220) if _is_light(shape.color) else QColor(255, 255, 255, 235)
+ outline = QPen(halo, max(2.0, font.pixelSize() / 7.0))
+ outline.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ painter.strokePath(path, outline)
+ painter.fillPath(path, _qcolor(shape.color))
+ if caret:
+ last = lines[-1] if lines else ""
+ cx = x + metrics.horizontalAdvance(last) + 1.5
+ cy = y + (len(lines) - 1) * metrics.lineSpacing()
+ painter.setPen(QPen(_qcolor(shape.color), 1.5))
+ painter.drawLine(QPointF(cx, cy + 2), QPointF(cx, cy + metrics.height() - 2))
+
+
+def paint_selection_frame(painter: QPainter, sel: QRectF) -> None:
+ """The selection's border and its eight resize handles."""
+ painter.save()
+ r = sel.adjusted(0.5, 0.5, -0.5, -0.5)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.setPen(QPen(QColor(0, 0, 0, 70), 1.0))
+ painter.drawRect(r.adjusted(-1.0, -1.0, 1.0, 1.0))
+ painter.setPen(QPen(QColor(255, 255, 255, 235), 1.0))
+ painter.drawRect(r)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.setPen(QPen(_HANDLE_EDGE, 1.0))
+ painter.setBrush(_HANDLE_FILL)
+ for hx, hy in mm.handle_points((sel.x(), sel.y(), sel.width(), sel.height())).values():
+ painter.drawEllipse(QPointF(hx, hy), _HANDLE_R, _HANDLE_R)
+ painter.restore()
+
+
+def paint_picked(painter: QPainter, shape: mm.Shape) -> None:
+ """A dashed frame around the marking the move tool holds."""
+ box = text_rect(shape) if shape.kind == mm.TEXT else _qrect(mm.bounds(shape))
+ pad = shape.width / 2.0 + 4.0
+ painter.save()
+ pen = QPen(QColor(255, 255, 255, 230), 1.0, Qt.PenStyle.DashLine)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRect(box.adjusted(-pad, -pad, pad, pad))
+ painter.restore()
+
+
+# --------------------------------------------------------------------------
+# Hide patches from the frozen frame
+# --------------------------------------------------------------------------
+
+
+class HidePatches:
+ """Blur/pixelate previews cut from the frozen frame, cached per rectangle."""
+
+ def __init__(self, frozen: QPixmap | None, scale: Callable[[], float]) -> None:
+ self._frozen = frozen
+ self._scale = scale
+ self._cache: dict[tuple, QPixmap] = {}
+
+ def __call__(self, shape: mm.Shape) -> QPixmap | None:
+ if self._frozen is None or len(shape.points) < 2:
+ return None
+ x, y, w, h = mm.normalized(shape.points[0], shape.points[-1])
+ if w < 1 or h < 1:
+ return None
+ scale = self._scale()
+ key = (shape.kind, round(x), round(y), round(w), round(h))
+ cached = self._cache.get(key)
+ if cached is not None:
+ return cached
+ source = self._frozen.copy(
+ round(x * scale), round(y * scale), max(1, round(w * scale)), max(1, round(h * scale))
+ )
+ if source.isNull():
+ return None
+ if shape.kind == mm.PIXELATE:
+ block = max(2.0, _PIXEL_BLOCK * scale)
+ small = source.scaled(
+ max(1, round(source.width() / block)),
+ max(1, round(source.height() / block)),
+ Qt.AspectRatioMode.IgnoreAspectRatio,
+ Qt.TransformationMode.SmoothTransformation,
+ )
+ else:
+ small = source.scaled(
+ max(1, round(source.width() / _BLUR_FACTOR)),
+ max(1, round(source.height() / _BLUR_FACTOR)),
+ Qt.AspectRatioMode.IgnoreAspectRatio,
+ Qt.TransformationMode.SmoothTransformation,
+ )
+ if len(self._cache) > 64:
+ self._cache.clear()
+ self._cache[key] = small
+ return small
+
+
+# --------------------------------------------------------------------------
+# Rendering the result
+# --------------------------------------------------------------------------
+
+
+def render_overlay(shapes: list[mm.Shape], sel: QRectF, scale: float) -> str:
+ """Every non-hide marking on a transparent PNG of the selection, as base64.
+
+ ``scale`` is device pixels per logical pixel, so the overlay is as sharp
+ as the screen. The main process resizes it onto the real capture.
+ """
+ width = max(1, round(sel.width() * scale))
+ height = max(1, round(sel.height() * scale))
+ image = QImage(width, height, QImage.Format.Format_ARGB32_Premultiplied)
+ image.fill(Qt.GlobalColor.transparent)
+ painter = QPainter(image)
+ painter.scale(width / sel.width(), height / sel.height())
+ painter.translate(-sel.x(), -sel.y())
+ painter.setClipRect(sel)
+ for shape in shapes:
+ if shape.kind not in mm.HIDE_KINDS:
+ paint_shape(painter, shape)
+ painter.end()
+ data = QByteArray()
+ buffer = QBuffer(data)
+ buffer.open(QIODevice.OpenModeFlag.WriteOnly)
+ image.save(buffer, "PNG")
+ buffer.close()
+ return base64.b64encode(bytes(data.data())).decode("ascii")
+
+
+# --------------------------------------------------------------------------
+# The toolbar
+# --------------------------------------------------------------------------
+
+
+def _dark_hud() -> bool:
+ """Follow the system appearance where Qt can read it; dark otherwise."""
+ try:
+ scheme = QGuiApplication.styleHints().colorScheme()
+ return scheme != Qt.ColorScheme.Light
+ except AttributeError: # Qt < 6.5 cannot tell
+ return True
+
+
+def _icon_pixmap(draw: Callable[[QPainter, QColor], None], colour: QColor, dpr: float) -> QPixmap:
+ size = 18
+ pixmap = QPixmap(round(size * dpr), round(size * dpr))
+ pixmap.setDevicePixelRatio(dpr)
+ pixmap.fill(Qt.GlobalColor.transparent)
+ painter = QPainter(pixmap)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ pen = QPen(colour, 1.6)
+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)
+ pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ painter.setPen(pen)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ draw(painter, colour)
+ painter.end()
+ return pixmap
+
+
+def _glyph(name: str) -> Callable[[QPainter, QColor], None]: # noqa: C901 - one table of glyphs
+ def move(p: QPainter, c: QColor) -> None:
+ path = QPainterPath(QPointF(4, 3))
+ for x, y in ((4, 15), (7.5, 11.5), (10, 16.5), (12, 15.5), (9.6, 10.6), (14.5, 10.6)):
+ path.lineTo(QPointF(x, y))
+ path.closeSubpath()
+ p.drawPath(path)
+
+ def rect(p: QPainter, c: QColor) -> None:
+ p.drawRoundedRect(QRectF(3, 4.5, 12, 9), 1.5, 1.5)
+
+ def ellipse(p: QPainter, c: QColor) -> None:
+ p.drawEllipse(QRectF(2.5, 4, 13, 10))
+
+ def arrow(p: QPainter, c: QColor) -> None:
+ p.drawLine(QPointF(4, 14), QPointF(14, 4))
+ p.drawLine(QPointF(14, 4), QPointF(8, 4))
+ p.drawLine(QPointF(14, 4), QPointF(14, 10))
+
+ def line(p: QPainter, c: QColor) -> None:
+ p.drawLine(QPointF(4, 14), QPointF(14, 4))
+
+ def pen(p: QPainter, c: QColor) -> None:
+ path = QPainterPath(QPointF(3, 15))
+ path.lineTo(QPointF(4, 11.5))
+ path.lineTo(QPointF(12, 3.5))
+ path.lineTo(QPointF(14.5, 6))
+ path.lineTo(QPointF(6.5, 14))
+ path.closeSubpath()
+ p.drawPath(path)
+
+ def highlight(p: QPainter, c: QColor) -> None:
+ p.drawRoundedRect(QRectF(5, 3, 8, 8), 1.5, 1.5)
+ p.drawLine(QPointF(7, 11), QPointF(7, 13.5))
+ p.drawLine(QPointF(11, 11), QPointF(11, 13.5))
+ p.drawLine(QPointF(3, 15.5), QPointF(15, 15.5))
+
+ def text(p: QPainter, c: QColor) -> None:
+ p.drawLine(QPointF(4, 4.5), QPointF(14, 4.5))
+ p.drawLine(QPointF(9, 4.5), QPointF(9, 14.5))
+
+ def counter(p: QPainter, c: QColor) -> None:
+ p.drawEllipse(QRectF(2.5, 2.5, 13, 13))
+ font = QFont()
+ font.setPixelSize(9)
+ font.setWeight(QFont.Weight.Bold)
+ p.setFont(font)
+ p.drawText(QRectF(2.5, 2.5, 13, 13), Qt.AlignmentFlag.AlignCenter, "1")
+
+ def blur(p: QPainter, c: QColor) -> None:
+ path = QPainterPath(QPointF(9, 2.5))
+ path.cubicTo(QPointF(9, 2.5), QPointF(3.5, 9), QPointF(3.5, 11.5))
+ path.cubicTo(QPointF(3.5, 14.5), QPointF(6, 16), QPointF(9, 16))
+ path.cubicTo(QPointF(12, 16), QPointF(14.5, 14.5), QPointF(14.5, 11.5))
+ path.cubicTo(QPointF(14.5, 9), QPointF(9, 2.5), QPointF(9, 2.5))
+ p.drawPath(path)
+
+ def pixelate(p: QPainter, c: QColor) -> None:
+ p.setPen(Qt.PenStyle.NoPen)
+ for i in range(3):
+ for j in range(3):
+ shade = QColor(c)
+ shade.setAlpha(255 if (i + j) % 2 == 0 else 110)
+ p.fillRect(QRectF(3 + i * 4.2, 3 + j * 4.2, 3.6, 3.6), shade)
+
+ def undo(p: QPainter, c: QColor) -> None:
+ path = QPainterPath(QPointF(5, 7))
+ path.lineTo(QPointF(11, 7))
+ path.cubicTo(QPointF(16, 7), QPointF(16, 15), QPointF(11, 15))
+ path.lineTo(QPointF(7, 15))
+ p.drawPath(path)
+ p.drawLine(QPointF(5, 7), QPointF(8, 4))
+ p.drawLine(QPointF(5, 7), QPointF(8, 10))
+
+ def redo(p: QPainter, c: QColor) -> None:
+ p.translate(18, 0)
+ p.scale(-1, 1)
+ undo(p, c)
+
+ def copy(p: QPainter, c: QColor) -> None:
+ p.drawRoundedRect(QRectF(6, 6, 9, 9.5), 1.5, 1.5)
+ path = QPainterPath(QPointF(4, 12))
+ path.lineTo(QPointF(3, 12))
+ path.lineTo(QPointF(3, 2.5))
+ path.lineTo(QPointF(11, 2.5))
+ path.lineTo(QPointF(11, 4))
+ p.drawPath(path)
+
+ def save(p: QPainter, c: QColor) -> None:
+ p.drawLine(QPointF(9, 2.5), QPointF(9, 11.5))
+ p.drawLine(QPointF(5.5, 8), QPointF(9, 11.5))
+ p.drawLine(QPointF(12.5, 8), QPointF(9, 11.5))
+ p.drawLine(QPointF(3, 15), QPointF(15, 15))
+
+ def edit(p: QPainter, c: QColor) -> None:
+ p.drawRoundedRect(QRectF(2.5, 3.5, 13, 11), 2, 2)
+ p.drawLine(QPointF(6, 11), QPointF(12, 7))
+
+ def cancel(p: QPainter, c: QColor) -> None:
+ p.drawLine(QPointF(5, 5), QPointF(13, 13))
+ p.drawLine(QPointF(13, 5), QPointF(5, 13))
+
+ def done(p: QPainter, c: QColor) -> None:
+ pen_ = QPen(c, 2.0)
+ pen_.setCapStyle(Qt.PenCapStyle.RoundCap)
+ pen_.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ p.setPen(pen_)
+ path = QPainterPath(QPointF(4, 9.5))
+ path.lineTo(QPointF(7.5, 13))
+ path.lineTo(QPointF(14, 5.5))
+ p.drawPath(path)
+
+ table = {
+ mm.MOVE: move,
+ mm.RECT: rect,
+ mm.ELLIPSE: ellipse,
+ mm.ARROW: arrow,
+ mm.LINE: line,
+ mm.PEN: pen,
+ mm.HIGHLIGHT: highlight,
+ mm.TEXT: text,
+ mm.COUNTER: counter,
+ mm.BLUR: blur,
+ mm.PIXELATE: pixelate,
+ "undo": undo,
+ "redo": redo,
+ "copy": copy,
+ "save": save,
+ "edit": edit,
+ "cancel": cancel,
+ "done": done,
+ }
+ return table[name]
+
+
+class Toolbar(QFrame):
+ """The floating marking toolbar, docked to the selection by its window."""
+
+ tool_chosen = Signal(str)
+ color_chosen = Signal(str)
+ width_cycled = Signal()
+ action = Signal(str)
+
+ _BTN = 30
+ _SWATCH = 18
+
+ def __init__(self, parent: QWidget, *, language: str, dpr: float) -> None:
+ super().__init__(parent)
+ self.setObjectName("hud")
+ self.setCursor(Qt.CursorShape.ArrowCursor)
+ self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
+ self._labels = labels_for(language)
+ self._dpr = max(1.0, dpr)
+ dark = _dark_hud()
+ self._fg = QColor(236, 236, 240) if dark else QColor(28, 28, 32)
+ bg = "rgba(28, 28, 31, 242)" if dark else "rgba(250, 250, 252, 245)"
+ edge = "rgba(255, 255, 255, 34)" if dark else "rgba(0, 0, 0, 34)"
+ hover = "rgba(255, 255, 255, 26)" if dark else "rgba(0, 0, 0, 18)"
+ sep = "rgba(255, 255, 255, 40)" if dark else "rgba(0, 0, 0, 30)"
+ self.setStyleSheet(
+ f"""
+ QFrame#hud {{ background: {bg}; border: 1px solid {edge}; border-radius: 11px; }}
+ QFrame#sep {{ background: {sep}; border: none; }}
+ QToolButton {{ border: none; border-radius: 7px; background: transparent; }}
+ QToolButton:hover {{ background: {hover}; }}
+ QToolButton:checked {{ background: #0A84FF; }}
+ QToolButton#done {{ background: #0A84FF; }}
+ QToolButton#done:hover {{ background: #3B9BFF; }}
+ QToolButton:disabled {{ background: transparent; }}
+ """
+ )
+ shadow = QGraphicsDropShadowEffect(self)
+ shadow.setBlurRadius(24)
+ shadow.setOffset(0, 4)
+ shadow.setColor(QColor(0, 0, 0, 110))
+ self.setGraphicsEffect(shadow)
+
+ layout = QHBoxLayout(self)
+ layout.setContentsMargins(6, 5, 6, 5)
+ layout.setSpacing(2)
+ self._tools = QButtonGroup(self)
+ self._tools.setExclusive(True)
+ self._tool_buttons: dict[str, QToolButton] = {}
+ for kind, key in mm.TOOL_KEYS.items():
+ button = self._button(kind, f"{self._labels[kind]} ({key})", checkable=True)
+ self._tools.addButton(button)
+ self._tool_buttons[kind] = button
+ button.clicked.connect(lambda _c=False, k=kind: self.tool_chosen.emit(k))
+ layout.addWidget(button)
+ layout.addWidget(self._separator())
+ self._swatches: dict[str, QToolButton] = {}
+ for index, colour in enumerate(mm.PALETTE):
+ swatch = QToolButton(self)
+ swatch.setFocusPolicy(Qt.FocusPolicy.NoFocus)
+ swatch.setCheckable(True)
+ swatch.setFixedSize(QSize(self._SWATCH + 4, self._BTN))
+ swatch.setToolTip(f"{self._labels['color']} ({index + 1})")
+ swatch.clicked.connect(lambda _c=False, col=colour: self.color_chosen.emit(col))
+ self._swatches[colour] = swatch
+ layout.addWidget(swatch)
+ self._width = self._button("width", self._labels["width"], glyph=False)
+ self._width.clicked.connect(lambda _c=False: self.width_cycled.emit())
+ layout.addWidget(self._width)
+ layout.addWidget(self._separator())
+ self._undo = self._action_button("undo", layout)
+ self._redo = self._action_button("redo", layout)
+ layout.addWidget(self._separator())
+ for name in ("copy", "save", "edit"):
+ self._action_button(name, layout)
+ layout.addWidget(self._separator())
+ self._action_button("cancel", layout)
+ done = self._action_button("done", layout, colour=QColor(255, 255, 255))
+ done.setObjectName("done")
+ self._colour = mm.PALETTE[0]
+ self._width_value = mm.WIDTHS[mm.DEFAULT_WIDTH_INDEX]
+ self.adjustSize()
+
+ # -- building ------------------------------------------------------------
+ def _button(
+ self,
+ name: str,
+ tip: str,
+ *,
+ checkable: bool = False,
+ glyph: bool = True,
+ colour: QColor | None = None,
+ ) -> QToolButton:
+ button = QToolButton(self)
+ button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
+ button.setFixedSize(QSize(self._BTN, self._BTN))
+ button.setIconSize(QSize(18, 18))
+ button.setToolTip(tip)
+ button.setCheckable(checkable)
+ if glyph:
+ icon = QIcon()
+ draw = _glyph(name)
+ normal = colour or self._fg
+ disabled = QColor(normal)
+ disabled.setAlpha(80)
+ for tint, mode, state in (
+ (normal, QIcon.Mode.Normal, QIcon.State.Off),
+ (QColor(255, 255, 255), QIcon.Mode.Normal, QIcon.State.On),
+ (disabled, QIcon.Mode.Disabled, QIcon.State.Off),
+ ):
+ icon.addPixmap(_icon_pixmap(draw, tint, self._dpr), mode, state)
+ button.setIcon(icon)
+ return button
+
+ def _action_button(
+ self, name: str, layout: QHBoxLayout, colour: QColor | None = None
+ ) -> QToolButton:
+ tip = f"{self._labels[name]} ({_ACTION_KEYS[name]})"
+ button = self._button(name, tip, colour=colour)
+ button.clicked.connect(lambda _c=False, n=name: self.action.emit(n))
+ layout.addWidget(button)
+ return button
+
+ def _separator(self) -> QFrame:
+ line = QFrame(self)
+ line.setObjectName("sep")
+ line.setFixedSize(QSize(1, 18))
+ return line
+
+ # -- state ---------------------------------------------------------------
+ def set_tool(self, kind: str) -> None:
+ button = self._tool_buttons.get(kind)
+ if button is not None:
+ button.setChecked(True)
+
+ def set_color(self, colour: str) -> None:
+ self._colour = colour
+ for value, swatch in self._swatches.items():
+ chosen = value == colour
+ swatch.setChecked(chosen)
+ # The ring in the icon marks the choice; no blue checked fill.
+ swatch.setStyleSheet("QToolButton:checked { background: transparent; }")
+ swatch.setIcon(self._swatch_icon(value, chosen))
+ swatch.setIconSize(QSize(self._SWATCH, self._SWATCH))
+ self._refresh_width()
+
+ def _swatch_icon(self, colour: str, chosen: bool) -> QIcon:
+ size = self._SWATCH
+ pixmap = QPixmap(round(size * self._dpr), round(size * self._dpr))
+ pixmap.setDevicePixelRatio(self._dpr)
+ pixmap.fill(Qt.GlobalColor.transparent)
+ painter = QPainter(pixmap)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ if chosen:
+ painter.setPen(QPen(self._fg, 1.6))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawEllipse(QRectF(0.8, 0.8, size - 1.6, size - 1.6))
+ painter.setPen(QPen(QColor(128, 128, 128, 150), 1.0))
+ painter.setBrush(QColor(colour))
+ inset = 3.6 if chosen else 2.4
+ painter.drawEllipse(QRectF(inset, inset, size - 2 * inset, size - 2 * inset))
+ painter.end()
+ return QIcon(pixmap)
+
+ def set_width(self, width: float) -> None:
+ self._width_value = width
+ self._refresh_width()
+
+ def _refresh_width(self) -> None:
+ size = 18
+ pixmap = QPixmap(round(size * self._dpr), round(size * self._dpr))
+ pixmap.setDevicePixelRatio(self._dpr)
+ pixmap.fill(Qt.GlobalColor.transparent)
+ painter = QPainter(pixmap)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ pen = QPen(self._fg, min(9.0, self._width_value))
+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)
+ painter.setPen(pen)
+ painter.drawLine(QPointF(4.5, 9), QPointF(13.5, 9))
+ painter.end()
+ self._width.setIcon(QIcon(pixmap))
+
+ def set_history(self, can_undo: bool, can_redo: bool) -> None:
+ self._undo.setEnabled(can_undo)
+ self._redo.setEnabled(can_redo)
+
+
+__all__ = [
+ "DIM_OUTSIDE",
+ "HidePatches",
+ "Toolbar",
+ "labels_for",
+ "paint_picked",
+ "paint_selection_frame",
+ "paint_shape",
+ "render_overlay",
+ "text_rect",
+]
diff --git a/jarvis/appshot/picker/markup_model.py b/jarvis/appshot/picker/markup_model.py
new file mode 100644
index 0000000000..12acfd9a74
--- /dev/null
+++ b/jarvis/appshot/picker/markup_model.py
@@ -0,0 +1,415 @@
+"""The picker's markings as plain data — no Qt, so the rules are testable anywhere.
+
+After an area is chosen the picker stays open and the user
+marks it up in place: boxes, circles, arrows, lines, pen and highlighter
+strokes, text, numbered steps, and blur or pixelate patches. Every marking is
+a :class:`Shape` in the overlay window's logical pixels; the Qt side
+(:mod:`jarvis.appshot.picker.annotate`) only paints them and turns mouse and
+keys into calls here.
+
+Geometry is floats and tuples, never Qt types, so the undo history can copy
+the whole list cheaply and these rules run on a headless CI box.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field, replace
+
+Point = tuple[float, float]
+#: ``(left, top, width, height)``.
+Box = tuple[float, float, float, float]
+
+RECT = "rect"
+ELLIPSE = "ellipse"
+ARROW = "arrow"
+LINE = "line"
+PEN = "pen"
+HIGHLIGHT = "highlight"
+TEXT = "text"
+COUNTER = "counter"
+BLUR = "blur"
+PIXELATE = "pixelate"
+#: Not a marking: picks, moves and deletes existing ones.
+MOVE = "move"
+
+#: Drawn by dragging a box.
+BOX_KINDS = frozenset({RECT, ELLIPSE, BLUR, PIXELATE})
+#: Drawn by dragging from a start to an end point.
+SEGMENT_KINDS = frozenset({ARROW, LINE})
+#: Drawn by dragging a free path.
+STROKE_KINDS = frozenset({PEN, HIGHLIGHT})
+#: Hide what is under them. They are applied to the real capture first, under
+#: every other marking, so the picker paints them first as well.
+HIDE_KINDS = frozenset({BLUR, PIXELATE})
+
+#: Tool order in the toolbar, with the key that selects each one.
+TOOL_KEYS: dict[str, str] = {
+ MOVE: "V",
+ RECT: "R",
+ ELLIPSE: "E",
+ ARROW: "A",
+ LINE: "L",
+ PEN: "P",
+ HIGHLIGHT: "H",
+ TEXT: "T",
+ COUNTER: "N",
+ BLUR: "B",
+ PIXELATE: "X",
+}
+
+#: Marking colours; red is the default.
+PALETTE: tuple[str, ...] = (
+ "#FF3B30",
+ "#FF9500",
+ "#FFCC00",
+ "#34C759",
+ "#0A84FF",
+ "#AF52DE",
+ "#FFFFFF",
+ "#111111",
+)
+#: Stroke widths the mouse wheel and the width button step through (logical px).
+WIDTHS: tuple[float, ...] = (2.0, 3.0, 4.0, 6.0, 9.0)
+DEFAULT_WIDTH_INDEX = 1
+
+#: A drag shorter than this (logical px) draws nothing, except where a click
+#: is the whole gesture (text, counter).
+MIN_DRAG_PX = 3.0
+#: Grab distance for the selection's resize handles.
+HANDLE_GRAB_PX = 8.0
+#: The selection never shrinks below this while it is resized.
+MIN_SELECTION_PX = 8.0
+
+
+@dataclass(slots=True)
+class Shape:
+ """One marking. What ``points`` holds depends on ``kind``:
+
+ box kinds and segments: ``[start, end]``; strokes: the whole path; text:
+ ``[anchor]`` (top-left of the first line); counter: ``[centre]``.
+ """
+
+ kind: str
+ color: str = PALETTE[0]
+ width: float = WIDTHS[DEFAULT_WIDTH_INDEX]
+ points: list[Point] = field(default_factory=list)
+ text: str = ""
+ number: int = 0
+
+ def copy(self) -> Shape:
+ return replace(self, points=list(self.points))
+
+
+# --------------------------------------------------------------------------
+# Geometry
+# --------------------------------------------------------------------------
+
+
+def normalized(a: Point, b: Point) -> Box:
+ left, top = min(a[0], b[0]), min(a[1], b[1])
+ return (left, top, abs(b[0] - a[0]), abs(b[1] - a[1]))
+
+
+def constrain(kind: str, start: Point, end: Point) -> Point:
+ """Shift held: boxes become squares/circles, lines snap to 45 degrees."""
+ dx, dy = end[0] - start[0], end[1] - start[1]
+ if kind in BOX_KINDS:
+ side = max(abs(dx), abs(dy))
+ return (
+ start[0] + math.copysign(side, dx or 1.0),
+ start[1] + math.copysign(side, dy or 1.0),
+ )
+ if kind in SEGMENT_KINDS:
+ length = math.hypot(dx, dy)
+ if length == 0:
+ return end
+ angle = round(math.atan2(dy, dx) / (math.pi / 4)) * (math.pi / 4)
+ return (start[0] + length * math.cos(angle), start[1] + length * math.sin(angle))
+ return end
+
+
+def counter_radius(width: float) -> float:
+ return 9.0 + width * 1.6
+
+
+def text_size(width: float) -> float:
+ """Text height in logical px for a stroke width — the width step scales text too."""
+ return 12.0 + width * 2.5
+
+
+def text_box(shape: Shape, char_w: float = 0.6) -> Box:
+ """A text marking's rough bounds (the Qt side measures exactly when painting)."""
+ size = text_size(shape.width)
+ lines = shape.text.split("\n") or [""]
+ width = max(len(line) for line in lines) * size * char_w
+ height = len(lines) * size * 1.25
+ x, y = shape.points[0]
+ return (x, y, max(width, size * 0.5), height)
+
+
+def bounds(shape: Shape) -> Box:
+ """The area a marking covers, before its stroke width."""
+ if not shape.points:
+ return (0.0, 0.0, 0.0, 0.0)
+ if shape.kind == TEXT:
+ return text_box(shape)
+ if shape.kind == COUNTER:
+ r = counter_radius(shape.width)
+ x, y = shape.points[0]
+ return (x - r, y - r, 2 * r, 2 * r)
+ xs = [p[0] for p in shape.points]
+ ys = [p[1] for p in shape.points]
+ return (min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys))
+
+
+def _distance_to_segment(p: Point, a: Point, b: Point) -> float:
+ ax, ay = a
+ bx, by = b
+ dx, dy = bx - ax, by - ay
+ span = dx * dx + dy * dy
+ if span == 0:
+ return math.hypot(p[0] - ax, p[1] - ay)
+ t = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / span))
+ return math.hypot(p[0] - (ax + t * dx), p[1] - (ay + t * dy))
+
+
+def hit(shape: Shape, p: Point, tolerance: float = 6.0) -> bool:
+ """Whether a click at ``p`` lands on ``shape`` (outlines, not empty insides)."""
+ tol = tolerance + shape.width / 2.0
+ if shape.kind in (TEXT, COUNTER, BLUR, PIXELATE):
+ x, y, w, h = bounds(shape)
+ return x - tol <= p[0] <= x + w + tol and y - tol <= p[1] <= y + h + tol
+ if shape.kind in SEGMENT_KINDS or shape.kind in STROKE_KINDS:
+ pts = shape.points
+ if len(pts) == 1:
+ return math.hypot(p[0] - pts[0][0], p[1] - pts[0][1]) <= tol
+ return any(_distance_to_segment(p, a, b) <= tol for a, b in zip(pts, pts[1:], strict=False))
+ x, y, w, h = normalized(shape.points[0], shape.points[-1])
+ if shape.kind == RECT:
+ inside_outer = x - tol <= p[0] <= x + w + tol and y - tol <= p[1] <= y + h + tol
+ inside_inner = x + tol < p[0] < x + w - tol and y + tol < p[1] < y + h - tol
+ return inside_outer and not inside_inner
+ if shape.kind == ELLIPSE:
+ rx, ry = w / 2.0, h / 2.0
+ if rx <= 0 or ry <= 0:
+ return False
+ cx, cy = x + rx, y + ry
+ # Normalised radial distance; 1.0 is the outline.
+ d = math.hypot((p[0] - cx) / rx, (p[1] - cy) / ry)
+ return abs(d - 1.0) * min(rx, ry) <= tol
+ return False
+
+
+def shape_at(shapes: list[Shape], p: Point) -> int | None:
+ """Index of the top-most marking under ``p``."""
+ for index in range(len(shapes) - 1, -1, -1):
+ if hit(shapes[index], p):
+ return index
+ return None
+
+
+def translated(shape: Shape, dx: float, dy: float) -> Shape:
+ moved = shape.copy()
+ moved.points = [(x + dx, y + dy) for x, y in shape.points]
+ return moved
+
+
+def is_meaningful(shape: Shape) -> bool:
+ """A finished drag that actually draws something."""
+ if shape.kind == TEXT:
+ return bool(shape.text.strip())
+ if shape.kind == COUNTER:
+ return bool(shape.points)
+ if len(shape.points) < 2:
+ return False
+ if shape.kind in STROKE_KINDS:
+ return True
+ x, y, w, h = normalized(shape.points[0], shape.points[-1])
+ if shape.kind in SEGMENT_KINDS:
+ return math.hypot(w, h) >= MIN_DRAG_PX
+ return w >= MIN_DRAG_PX and h >= MIN_DRAG_PX
+
+
+def next_counter(shapes: list[Shape]) -> int:
+ """The number the next step marker shows: one past the highest so far."""
+ return max((s.number for s in shapes if s.kind == COUNTER), default=0) + 1
+
+
+# --------------------------------------------------------------------------
+# The selection frame
+# --------------------------------------------------------------------------
+
+#: Handle names: corners and edge midpoints.
+HANDLES = ("nw", "n", "ne", "e", "se", "s", "sw", "w")
+
+
+def handle_points(sel: Box) -> dict[str, Point]:
+ x, y, w, h = sel
+ return {
+ "nw": (x, y),
+ "n": (x + w / 2, y),
+ "ne": (x + w, y),
+ "e": (x + w, y + h / 2),
+ "se": (x + w, y + h),
+ "s": (x + w / 2, y + h),
+ "sw": (x, y + h),
+ "w": (x, y + h / 2),
+ }
+
+
+def handle_at(sel: Box, p: Point, grab: float = HANDLE_GRAB_PX) -> str | None:
+ for name, (hx, hy) in handle_points(sel).items():
+ if abs(p[0] - hx) <= grab and abs(p[1] - hy) <= grab:
+ return name
+ return None
+
+
+def resize(sel: Box, handle: str, p: Point, limit: tuple[float, float]) -> Box:
+ """Drag ``handle`` of ``sel`` to ``p``; clamped to the screen ``limit``."""
+ x0, y0, w, h = sel
+ x1, y1 = x0 + w, y0 + h
+ px = max(0.0, min(limit[0], p[0]))
+ py = max(0.0, min(limit[1], p[1]))
+ if "w" in handle:
+ x0 = min(px, x1 - MIN_SELECTION_PX)
+ if "e" in handle:
+ x1 = max(px, x0 + MIN_SELECTION_PX)
+ if "n" in handle:
+ y0 = min(py, y1 - MIN_SELECTION_PX)
+ if "s" in handle:
+ y1 = max(py, y0 + MIN_SELECTION_PX)
+ return (x0, y0, x1 - x0, y1 - y0)
+
+
+def toolbar_origin(
+ sel: Box, bar: tuple[float, float], screen: tuple[float, float], gap: float = 10.0
+) -> Point:
+ """Where the toolbar goes: centred under the selection, else above, else inside.
+
+ Always kept fully on the screen.
+ """
+ x, y, w, h = sel
+ bw, bh = bar
+ sw, sh = screen
+ left = x + (w - bw) / 2.0
+ if y + h + gap + bh <= sh:
+ top = y + h + gap
+ elif y - gap - bh >= 0:
+ top = y - gap - bh
+ else:
+ top = y + h - gap - bh
+ left = max(gap, min(sw - bw - gap, left))
+ top = max(gap, min(sh - bh - gap, top))
+ return (left, top)
+
+
+def clip_to(box: Box, sel: Box) -> Box | None:
+ """``box`` cut to the selection; ``None`` when nothing of it is inside."""
+ x0 = max(box[0], sel[0])
+ y0 = max(box[1], sel[1])
+ x1 = min(box[0] + box[2], sel[0] + sel[2])
+ y1 = min(box[1] + box[3], sel[1] + sel[3])
+ if x1 - x0 <= 0 or y1 - y0 <= 0:
+ return None
+ return (x0, y0, x1 - x0, y1 - y0)
+
+
+def hide_fractions(shapes: list[Shape], sel: Box) -> list[dict[str, object]]:
+ """Blur/pixelate patches as fractions of the selection, for the main process."""
+ out: list[dict[str, object]] = []
+ sx, sy, sw, sh = sel
+ if sw <= 0 or sh <= 0:
+ return out
+ for shape in shapes:
+ if shape.kind not in HIDE_KINDS or len(shape.points) < 2:
+ continue
+ clipped = clip_to(normalized(shape.points[0], shape.points[-1]), sel)
+ if clipped is None:
+ continue
+ x, y, w, h = clipped
+ out.append({"kind": shape.kind, "rect": [(x - sx) / sw, (y - sy) / sh, w / sw, h / sh]})
+ return out
+
+
+# --------------------------------------------------------------------------
+# Undo
+# --------------------------------------------------------------------------
+
+
+class History:
+ """Snapshots of the marking list; every finished action pushes one."""
+
+ def __init__(self) -> None:
+ self._undo: list[list[Shape]] = [[]]
+ self._redo: list[list[Shape]] = []
+
+ @staticmethod
+ def _copy(shapes: list[Shape]) -> list[Shape]:
+ return [s.copy() for s in shapes]
+
+ def push(self, shapes: list[Shape]) -> None:
+ self._undo.append(self._copy(shapes))
+ self._redo.clear()
+
+ def undo(self) -> list[Shape] | None:
+ if len(self._undo) <= 1:
+ return None
+ self._redo.append(self._undo.pop())
+ return self._copy(self._undo[-1])
+
+ def redo(self) -> list[Shape] | None:
+ if not self._redo:
+ return None
+ state = self._redo.pop()
+ self._undo.append(state)
+ return self._copy(state)
+
+ @property
+ def can_undo(self) -> bool:
+ return len(self._undo) > 1
+
+ @property
+ def can_redo(self) -> bool:
+ return bool(self._redo)
+
+
+__all__ = [
+ "ARROW",
+ "BLUR",
+ "BOX_KINDS",
+ "COUNTER",
+ "ELLIPSE",
+ "HANDLES",
+ "HIDE_KINDS",
+ "HIGHLIGHT",
+ "LINE",
+ "MOVE",
+ "PALETTE",
+ "PEN",
+ "PIXELATE",
+ "RECT",
+ "SEGMENT_KINDS",
+ "STROKE_KINDS",
+ "TEXT",
+ "TOOL_KEYS",
+ "WIDTHS",
+ "History",
+ "Shape",
+ "bounds",
+ "clip_to",
+ "constrain",
+ "counter_radius",
+ "handle_at",
+ "handle_points",
+ "hide_fractions",
+ "hit",
+ "is_meaningful",
+ "next_counter",
+ "normalized",
+ "resize",
+ "shape_at",
+ "text_size",
+ "toolbar_origin",
+ "translated",
+]
diff --git a/jarvis/appshot/picker/renderer.py b/jarvis/appshot/picker/renderer.py
index e30a9fd684..7e9aab276d 100644
--- a/jarvis/appshot/picker/renderer.py
+++ b/jarvis/appshot/picker/renderer.py
@@ -1,4 +1,4 @@
-"""PySide6 area picker for region appshots, as quiet as macOS's Cmd+Shift+4.
+"""PySide6 area picker for region appshots.
Runs ONLY inside ``python -m jarvis.appshot.picker``; the main process never
imports this module (AP-26). One frameless, always-on-top window per screen:
@@ -13,10 +13,17 @@ imports this module (AP-26). One frameless, always-on-top window per screen:
- **Window snapping.** Hovering lifts the window under the pointer out of the
dim (rectangles from the main process, top-most first); a click without a
drag takes exactly that window.
-- **Drag to select.** Like CleanShot X, the screen around the selection
+- **Drag to select.** The screen around the selection
clears and the selected area itself turns a translucent grey, with one thin
border.
+- **Mark up in place.** Releasing the drag does not take the
+ shot yet: the selection keeps resize handles and a toolbar docks under it
+ (:mod:`jarvis.appshot.picker.annotate`). The user draws boxes, arrows, text,
+ steps, blur and so on right on the frozen frame; Enter or the check button
+ takes the appshot with the markings, Ctrl+C / Ctrl+S / Ctrl+E also copy,
+ save or open it in the full editor.
+
Only the parts that change are repainted, so the numbers follow the pointer
without dragging a full 4K repaint behind them. Esc or a right-click cancels.
The result is reported as fractions of its screen, so mixed-DPI layouts map
@@ -44,6 +51,8 @@ from PySide6.QtGui import (
from PySide6.QtWidgets import QApplication, QWidget
from jarvis.appshot import picker as wire
+from jarvis.appshot.picker import annotate
+from jarvis.appshot.picker import markup_model as mm
from jarvis.appshot.region import match_monitor, selection_fractions, snap_rects_on_screen
#: A light veil before the drag (the picker is armed). While dragging the
@@ -56,7 +65,7 @@ _SELECTION_TINT = QColor(128, 128, 132, 105)
_BORDER = QColor(255, 255, 255, 235)
_BORDER_EDGE = QColor(0, 0, 0, 70)
-#: The numbers beside the crosshair: dark ink with a white halo, like macOS.
+#: The numbers beside the crosshair: dark ink with a white halo.
_INK = QColor(20, 20, 22)
_HALO = QColor(255, 255, 255, 235)
_NUMBER_PT = 8.5
@@ -71,6 +80,24 @@ _CROSS_RING = 3.5
#: Windows smaller than this (logical px, either side) are not snap targets.
_MIN_SNAP_PX = 24
+#: Cursor per selection resize handle.
+_HANDLE_CURSORS = {
+ "nw": Qt.CursorShape.SizeFDiagCursor,
+ "se": Qt.CursorShape.SizeFDiagCursor,
+ "ne": Qt.CursorShape.SizeBDiagCursor,
+ "sw": Qt.CursorShape.SizeBDiagCursor,
+ "n": Qt.CursorShape.SizeVerCursor,
+ "s": Qt.CursorShape.SizeVerCursor,
+ "e": Qt.CursorShape.SizeHorCursor,
+ "w": Qt.CursorShape.SizeHorCursor,
+}
+#: Keyboard shortcuts for the toolbar's actions (with Ctrl / Cmd).
+_ACTION_KEYS = {
+ Qt.Key.Key_C: wire.ACTION_COPY,
+ Qt.Key.Key_S: wire.ACTION_SAVE,
+ Qt.Key.Key_E: wire.ACTION_EDIT,
+}
+
def _screen_info(screen) -> dict[str, float]:
g = screen.geometry()
@@ -99,7 +126,7 @@ def _number_font() -> QFont:
def crosshair_cursor(dpr: float) -> QCursor:
- """The macOS-style crosshair: two thin arms with a ring at the centre.
+ """The crosshair: two thin arms with a ring at the centre.
Drawn by the OS as the real cursor (no lag behind the mouse), at the
screen's pixel density, black on a white halo so it reads everywhere.
@@ -133,6 +160,38 @@ def crosshair_cursor(dpr: float) -> QCursor:
return QCursor(pixmap, hot, hot)
+class _MarkupState:
+ """Everything the annotation mode of one screen window holds."""
+
+ def __init__(self) -> None:
+ #: The chosen area (logical px); ``None`` while still choosing.
+ self.sel: QRectF | None = None
+ self.shapes: list[mm.Shape] = []
+ self.history = mm.History()
+ self.tool = mm.ARROW
+ self.color = mm.PALETTE[0]
+ self.width_index = mm.DEFAULT_WIDTH_INDEX
+ #: The marking being dragged out right now.
+ self.drawing: mm.Shape | None = None
+ #: The text marking being typed (not yet in ``shapes``).
+ self.typing: mm.Shape | None = None
+ #: Index into ``shapes`` the move tool holds.
+ self.picked: int | None = None
+ #: ``("resize", handle)`` / ``("move", None)`` while a drag runs.
+ self.drag: tuple[str, str | None] | None = None
+ self.last: QPointF | None = None
+ self.moved = False
+
+ @property
+ def width(self) -> float:
+ return mm.WIDTHS[self.width_index]
+
+ def box(self) -> mm.Box:
+ sel = self.sel
+ assert sel is not None
+ return (sel.x(), sel.y(), sel.width(), sel.height())
+
+
class _SelectWindow(QWidget):
"""One screen's selection canvas."""
@@ -171,6 +230,10 @@ class _SelectWindow(QWidget):
#: What was painted last, so the next move repaints only what changed.
self._painted_numbers: QRectF | None = None
self._painted_hole: QRectF | None = None
+ self._cross = crosshair_cursor(screen.devicePixelRatio() or 1.0)
+ self._markup = _MarkupState()
+ self._patches = annotate.HidePatches(frozen, self._scale)
+ self._toolbar: annotate.Toolbar | None = None
# -- data from the main process ------------------------------------------
def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:
@@ -185,12 +248,24 @@ class _SelectWindow(QWidget):
# -- input ---------------------------------------------------------------
def keyPressEvent(self, event) -> None: # noqa: N802 (Qt override)
+ marking = self._owner.marking
+ if marking is not None and marking is not self:
+ marking.keyPressEvent(event)
+ return
+ if self._markup.sel is not None:
+ self._markup_key(event)
+ return
if event.key() == Qt.Key.Key_Escape:
self._owner.finish(None, None)
return
super().keyPressEvent(event)
def mousePressEvent(self, event) -> None: # noqa: N802
+ if self._owner.marking is not None and self._owner.marking is not self:
+ return
+ if self._markup.sel is not None:
+ self._markup_press(event)
+ return
if event.button() == Qt.MouseButton.RightButton:
self._owner.finish(None, None)
return
@@ -202,6 +277,10 @@ class _SelectWindow(QWidget):
self.update()
def mouseMoveEvent(self, event) -> None: # noqa: N802
+ if self._owner.marking is not None:
+ if self._owner.marking is self:
+ self._markup_move(event)
+ return
self._pointer = event.position()
if self._start is not None:
self._end = event.position()
@@ -209,6 +288,10 @@ class _SelectWindow(QWidget):
self._repaint_changes()
def mouseReleaseEvent(self, event) -> None: # noqa: N802
+ if self._owner.marking is not None:
+ if self._owner.marking is self:
+ self._markup_release(event)
+ return
if event.button() != Qt.MouseButton.LeftButton or self._start is None:
return
end = event.position()
@@ -230,7 +313,10 @@ class _SelectWindow(QWidget):
if frac is None:
self.update()
return
- self._owner.finish(self, frac)
+ fx, fy, fw, fh = frac
+ self._begin_markup(
+ QRectF(fx * self.width(), fy * self.height(), fw * self.width(), fh * self.height())
+ )
def clear_pointer(self) -> None:
if self._pointer is not None or self._start is not None:
@@ -330,6 +416,10 @@ class _SelectWindow(QWidget):
full = QRectF(0, 0, self.width(), self.height())
if self._frozen is not None:
painter.drawPixmap(full, self._frozen, QRectF(self._frozen.rect()))
+ if self._markup.sel is not None:
+ self._paint_markup(painter, full)
+ painter.end()
+ return
hole = self._hole()
if self._selection() is not None and hole is not None:
# Dragging: the surroundings stay clear, the selection turns grey.
@@ -365,7 +455,7 @@ class _SelectWindow(QWidget):
ascent = self._metrics.ascent()
path = QPainterPath()
for i, text in enumerate(numbers):
- # Right-aligned in their column, the way macOS stacks them.
+ # Right-aligned in their column.
x = box.right() - 2.0 - self._metrics.horizontalAdvance(text)
path.addText(QPointF(x, box.top() + 1.0 + ascent + i * line), self._font, text)
painter.save()
@@ -376,15 +466,396 @@ class _SelectWindow(QWidget):
painter.fillPath(path, _INK)
painter.restore()
+ # -- marking up the chosen area ------------------------------------------
+ def _begin_markup(self, sel: QRectF) -> None:
+ """The area is chosen: keep the overlay and dock the toolbar under it."""
+ m = self._markup
+ m.sel = sel
+ self._pointer = None
+ self._painted_numbers = None
+ self._painted_hole = None
+ if self._toolbar is None:
+ bar = annotate.Toolbar(
+ self, language=self._owner.language, dpr=self.screen_ref.devicePixelRatio() or 1.0
+ )
+ bar.tool_chosen.connect(self._set_tool)
+ bar.color_chosen.connect(self._set_color)
+ bar.width_cycled.connect(lambda: self._step_width(1, wrap=True))
+ bar.action.connect(self._toolbar_action)
+ self._toolbar = bar
+ self._toolbar.set_tool(m.tool)
+ self._toolbar.set_color(m.color)
+ self._toolbar.set_width(m.width)
+ self._sync_history()
+ self._place_toolbar()
+ self._toolbar.show()
+ self._toolbar.raise_()
+ self._owner.begin_markup(self)
+ self._update_cursor(None)
+ self.update()
+
+ def _end_markup(self) -> None:
+ """Back to choosing an area (right-click on an unmarked selection)."""
+ self._markup = _MarkupState()
+ if self._toolbar is not None:
+ self._toolbar.hide()
+ self._owner.end_markup(self)
+ self.setCursor(self._cross)
+ self.update()
+
+ def _place_toolbar(self) -> None:
+ bar = self._toolbar
+ if bar is None or self._markup.sel is None:
+ return
+ bar.adjustSize()
+ x, y = mm.toolbar_origin(
+ self._markup.box(), (bar.width(), bar.height()), (self.width(), self.height())
+ )
+ bar.move(round(x), round(y))
+
+ def _sync_history(self) -> None:
+ if self._toolbar is not None:
+ h = self._markup.history
+ self._toolbar.set_history(h.can_undo, h.can_redo)
+
+ def _commit(self) -> None:
+ self._markup.history.push(self._markup.shapes)
+ self._sync_history()
+
+ def _set_tool(self, kind: str) -> None:
+ self._commit_typing()
+ self._markup.tool = kind
+ self._markup.picked = None
+ if self._toolbar is not None:
+ self._toolbar.set_tool(kind)
+ self._update_cursor(None)
+ self.update()
+
+ def _set_color(self, colour: str) -> None:
+ m = self._markup
+ m.color = colour
+ target = m.typing or (m.shapes[m.picked] if m.picked is not None else None)
+ if target is not None:
+ target.color = colour
+ if target is not m.typing:
+ self._commit()
+ if self._toolbar is not None:
+ self._toolbar.set_color(colour)
+ self.update()
+
+ def _step_width(self, step: int, *, wrap: bool = False) -> None:
+ m = self._markup
+ count = len(mm.WIDTHS)
+ index = m.width_index + step
+ m.width_index = index % count if wrap else max(0, min(count - 1, index))
+ target = m.typing or (m.shapes[m.picked] if m.picked is not None else None)
+ if target is not None:
+ target.width = m.width
+ if target is not m.typing:
+ self._commit()
+ if self._toolbar is not None:
+ self._toolbar.set_width(m.width)
+ self.update()
+
+ def _toolbar_action(self, name: str) -> None:
+ if name == "undo":
+ self._undo(redo=False)
+ elif name == "redo":
+ self._undo(redo=True)
+ elif name == "cancel":
+ self._owner.finish(None, None)
+ elif name in wire.ACTIONS:
+ self._deliver(name)
+
+ def _undo(self, *, redo: bool) -> None:
+ m = self._markup
+ m.typing = None
+ state = m.history.redo() if redo else m.history.undo()
+ if state is not None:
+ m.shapes = state
+ m.picked = None
+ self._sync_history()
+ self.update()
+
+ def _deliver(self, action: str) -> None:
+ """Take the appshot: the area plus the markings, then close."""
+ self._commit_typing()
+ m = self._markup
+ sel = m.sel
+ if sel is None:
+ return
+ frac = (
+ sel.x() / self.width(),
+ sel.y() / self.height(),
+ sel.width() / self.width(),
+ sel.height() / self.height(),
+ )
+ markup = None
+ if m.shapes:
+ markup = {
+ "overlay": annotate.render_overlay(m.shapes, sel, self._scale()),
+ "hides": mm.hide_fractions(m.shapes, m.box()),
+ }
+ self._owner.finish(self, frac, action=action, markup=markup)
+
+ def _commit_typing(self) -> None:
+ m = self._markup
+ shape = m.typing
+ if shape is None:
+ return
+ m.typing = None
+ if mm.is_meaningful(shape):
+ m.shapes.append(shape)
+ self._commit()
+ self.update()
+
+ def _markup_key(self, event) -> None: # noqa: C901 - one key table
+ m = self._markup
+ key = event.key()
+ mods = event.modifiers()
+ ctrl = bool(mods & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.MetaModifier))
+ if m.typing is not None:
+ self._typing_key(event, key, mods, ctrl)
+ return
+ if key == Qt.Key.Key_Escape:
+ if m.picked is not None:
+ m.picked = None
+ self.update()
+ else:
+ self._owner.finish(None, None)
+ elif key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
+ self._deliver(wire.ACTION_DONE)
+ elif ctrl and key == Qt.Key.Key_Z:
+ self._undo(redo=bool(mods & Qt.KeyboardModifier.ShiftModifier))
+ elif ctrl and key == Qt.Key.Key_Y:
+ self._undo(redo=True)
+ elif ctrl and key in _ACTION_KEYS:
+ self._deliver(_ACTION_KEYS[key])
+ elif key in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace) and m.picked is not None:
+ del m.shapes[m.picked]
+ m.picked = None
+ self._commit()
+ self.update()
+ elif not ctrl and Qt.Key.Key_1 <= key <= Qt.Key.Key_9:
+ index = int(key) - int(Qt.Key.Key_1)
+ if index < len(mm.PALETTE):
+ self._set_color(mm.PALETTE[index])
+ elif not ctrl and event.text():
+ letter = event.text().upper()
+ for kind, shortcut in mm.TOOL_KEYS.items():
+ if shortcut == letter:
+ self._set_tool(kind)
+ break
+
+ def _typing_key(self, event, key, mods, ctrl: bool) -> None:
+ shape = self._markup.typing
+ assert shape is not None
+ if key == Qt.Key.Key_Escape:
+ self._markup.typing = None
+ elif key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
+ if mods & Qt.KeyboardModifier.ShiftModifier:
+ shape.text += "\n"
+ else:
+ self._commit_typing()
+ elif key == Qt.Key.Key_Backspace:
+ shape.text = shape.text[:-1]
+ elif ctrl and key == Qt.Key.Key_V:
+ shape.text += QGuiApplication.clipboard().text()
+ elif not ctrl and event.text() and event.text().isprintable():
+ shape.text += event.text()
+ self.update()
+
+ def _markup_press(self, event) -> None: # noqa: C901 - one press table
+ m = self._markup
+ p = event.position()
+ point = (p.x(), p.y())
+ if event.button() == Qt.MouseButton.RightButton:
+ if m.drawing is not None:
+ m.drawing = None
+ elif m.typing is not None:
+ m.typing = None
+ elif not m.shapes:
+ self._end_markup()
+ return
+ self.update()
+ return
+ if event.button() != Qt.MouseButton.LeftButton:
+ return
+ self._commit_typing()
+ handle = mm.handle_at(m.box(), point)
+ if handle is not None:
+ m.drag = ("resize", handle)
+ return
+ inside = m.sel is not None and m.sel.contains(p)
+ if m.tool == mm.MOVE:
+ m.picked = mm.shape_at(m.shapes, point)
+ if m.picked is not None:
+ m.drag, m.last, m.moved = ("move", None), p, False
+ self.update()
+ return
+ if not inside:
+ if not m.shapes:
+ # A press outside an unmarked area starts choosing again.
+ self._end_markup()
+ self.mousePressEvent(event)
+ return
+ m.picked = None
+ if m.tool == mm.TEXT:
+ m.typing = mm.Shape(
+ mm.TEXT,
+ color=m.color,
+ width=m.width,
+ points=[(point[0], point[1] - mm.text_size(m.width) / 2.0)],
+ )
+ elif m.tool == mm.COUNTER:
+ m.shapes.append(
+ mm.Shape(
+ mm.COUNTER,
+ color=m.color,
+ width=m.width,
+ points=[point],
+ number=mm.next_counter(m.shapes),
+ )
+ )
+ self._commit()
+ elif m.tool in mm.STROKE_KINDS:
+ m.drawing = mm.Shape(m.tool, color=m.color, width=m.width, points=[point])
+ else:
+ m.drawing = mm.Shape(m.tool, color=m.color, width=m.width, points=[point, point])
+ self._update_markup_area()
+
+ def _markup_move(self, event) -> None:
+ m = self._markup
+ p = event.position()
+ point = (p.x(), p.y())
+ if m.drag is not None and m.drag[0] == "resize":
+ sel = mm.resize(m.box(), m.drag[1] or "se", point, (self.width(), self.height()))
+ m.sel = QRectF(*sel)
+ self._place_toolbar()
+ self.update()
+ return
+ if m.drag is not None and m.drag[0] == "move" and m.picked is not None and m.last:
+ delta = p - m.last
+ m.shapes[m.picked] = mm.translated(m.shapes[m.picked], delta.x(), delta.y())
+ m.last, m.moved = p, True
+ self._update_markup_area()
+ return
+ shape = m.drawing
+ if shape is not None:
+ if shape.kind in mm.STROKE_KINDS:
+ lx, ly = shape.points[-1]
+ if abs(point[0] - lx) + abs(point[1] - ly) >= 1.5:
+ shape.points.append(point)
+ else:
+ end = point
+ if event.modifiers() & Qt.KeyboardModifier.ShiftModifier:
+ end = mm.constrain(shape.kind, shape.points[0], point)
+ shape.points[-1] = end
+ self._update_markup_area()
+ return
+ self._update_cursor(point)
+
+ def _markup_release(self, event) -> None:
+ if event.button() != Qt.MouseButton.LeftButton:
+ return
+ m = self._markup
+ drag, m.drag = m.drag, None
+ if drag is not None and drag[0] == "move" and m.moved:
+ self._commit()
+ shape, m.drawing = m.drawing, None
+ if shape is not None and mm.is_meaningful(shape):
+ m.shapes.append(shape)
+ self._commit()
+ self._update_markup_area()
+
+ def wheelEvent(self, event) -> None: # noqa: N802
+ if self._markup.sel is None:
+ return
+ steps = event.angleDelta().y()
+ if steps:
+ self._step_width(1 if steps > 0 else -1)
+
+ def _update_cursor(self, point: mm.Point | None) -> None:
+ m = self._markup
+ if point is not None:
+ handle = mm.handle_at(m.box(), point)
+ if handle is not None:
+ self.setCursor(_HANDLE_CURSORS[handle])
+ return
+ if m.tool == mm.MOVE:
+ over = mm.shape_at(m.shapes, point) is not None
+ self.setCursor(Qt.CursorShape.SizeAllCursor if over else Qt.CursorShape.ArrowCursor)
+ return
+ if m.tool == mm.TEXT:
+ self.setCursor(Qt.CursorShape.IBeamCursor)
+ elif m.tool == mm.MOVE:
+ self.setCursor(Qt.CursorShape.ArrowCursor)
+ else:
+ self.setCursor(self._cross)
+
+ def _update_markup_area(self) -> None:
+ """Repaint the selection (markings are clipped to it) and its frame."""
+ if self._markup.sel is None:
+ self.update()
+ return
+ self.update(self._markup.sel.adjusted(-40, -40, 40, 40).toAlignedRect())
+
+ def _paint_markup(self, painter: QPainter, full: QRectF) -> None:
+ m = self._markup
+ sel = m.sel
+ assert sel is not None
+ dim = QPainterPath()
+ dim.addRect(full)
+ cut = QPainterPath()
+ cut.addRect(sel)
+ painter.fillPath(dim.subtracted(cut), annotate.DIM_OUTSIDE)
+ if self._frozen is None:
+ # Live overlay: a fully clear pixel lets clicks fall through to the
+ # window below, so the area keeps an invisible film to draw on.
+ painter.fillRect(sel, QColor(0, 0, 0, 1))
+ live =[*m.shapes, *(s for s in (m.drawing, m.typing) if s is not None)]
+ painter.save()
+ painter.setClipRect(sel, Qt.ClipOperation.IntersectClip)
+ for shape in (s for s in live if s.kind in mm.HIDE_KINDS):
+ annotate.paint_shape(painter, shape, hide_source=self._patches)
+ for shape in (s for s in live if s.kind not in mm.HIDE_KINDS):
+ annotate.paint_shape(painter, shape, caret=shape is m.typing)
+ painter.restore()
+ if m.picked is not None and m.picked < len(m.shapes):
+ annotate.paint_picked(painter, m.shapes[m.picked])
+ annotate.paint_selection_frame(painter, sel)
+ self._paint_size(painter, sel)
+
+ def _paint_size(self, painter: QPainter, sel: QRectF) -> None:
+ """``W x H`` in capture pixels, just above the area's top-left corner."""
+ scale = self._scale()
+ text = f"{round(sel.width() * scale)} × {round(sel.height() * scale)}"
+ ascent = self._metrics.ascent()
+ y = sel.top() - 6.0
+ if y - ascent < _EDGE_GAP:
+ y = sel.top() + ascent + 6.0
+ path = QPainterPath()
+ path.addText(QPointF(sel.left() + 1.0, y), self._font, text)
+ painter.save()
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ halo = QPen(_HALO, 2.6)
+ halo.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
+ painter.strokePath(path, halo)
+ painter.fillPath(path, _INK)
+ painter.restore()
+
class Picker(QObject):
"""Owns the per-screen windows and reports exactly one result."""
- def __init__(self, app: QApplication) -> None:
+ def __init__(self, app: QApplication, *, language: str = "en") -> None:
super().__init__()
self._app = app
+ self.language = language
self._windows: list[_SelectWindow] = []
self._focused: _SelectWindow | None = None
+ #: The window whose area is being marked up; the others stay inert.
+ self.marking: _SelectWindow | None = None
self._done = False
def start(self) -> None:
@@ -421,14 +892,38 @@ class Picker(QObject):
def focus_on(self, window: _SelectWindow) -> None:
"""The pointer moved onto ``window``: only that screen shows the numbers."""
- if self._focused is window:
+ if self._focused is window or self.marking is not None:
return
for other in self._windows:
if other is not window:
other.clear_pointer()
self._focused = window
- def finish(self, window: _SelectWindow | None, frac) -> None:
+ def begin_markup(self, window: _SelectWindow) -> None:
+ """An area is chosen on ``window``: the toolbar is up, keys go there."""
+ self.marking = window
+ self._focused = window
+ for other in self._windows:
+ if other is not window:
+ other.clear_pointer()
+ window.raise_()
+ window.activateWindow()
+ window.setFocus()
+ # The parent drops its global Esc now: Esc may end a text box here.
+ _emit({"event": wire.EVENT_MARKING})
+
+ def end_markup(self, window: _SelectWindow) -> None:
+ if self.marking is window:
+ self.marking = None
+
+ def finish(
+ self,
+ window: _SelectWindow | None,
+ frac,
+ *,
+ action: str = "done",
+ markup: dict | None = None,
+ ) -> None:
if self._done:
return
self._done = True
@@ -440,7 +935,15 @@ class Picker(QObject):
if info is None or frac is None:
_emit({"event": wire.EVENT_SELECTION, "cancelled": True})
else:
- _emit({"event": wire.EVENT_SELECTION, "screen": info, "rect": list(frac)})
+ payload: dict = {
+ "event": wire.EVENT_SELECTION,
+ "screen": info,
+ "rect": list(frac),
+ "action": action,
+ }
+ if markup is not None:
+ payload["markup"] = markup
+ _emit(payload)
self._app.quit()
@Slot(str)
@@ -479,7 +982,7 @@ class _StdinPump(QObject):
self.eof.emit()
-def run() -> int:
+def run(language: str = "en") -> int:
"""Picker main loop. Returns the process exit code."""
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
@@ -490,7 +993,7 @@ def run() -> int:
sys.stderr.write(f"appshot-picker: no usable display ({exc!r}).\n")
return wire.EXIT_NO_GUI
app.setQuitOnLastWindowClosed(False)
- picker = Picker(app)
+ picker = Picker(app, language=language)
pump = _StdinPump()
pump.line.connect(picker.on_line, Qt.ConnectionType.QueuedConnection)
pump.eof.connect(picker.on_eof, Qt.ConnectionType.QueuedConnection)
diff --git a/jarvis/appshot/region.py b/jarvis/appshot/region.py
index ac8988d407..a65a07b859 100644
--- a/jarvis/appshot/region.py
+++ b/jarvis/appshot/region.py
@@ -27,21 +27,26 @@ from __future__ import annotations
import asyncio
import contextlib
+import contextvars
import importlib.util
import logging
import os
import subprocess
import sys
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
+from jarvis.appshot.markup import Markup, parse_markup
+
log = logging.getLogger(__name__)
#: A drag smaller than this (logical px, either side) is a click, not a pick.
MIN_SELECTION_PX = 4
-#: The picker gives up on its own after this long without a selection.
-PICK_TIMEOUT_S = 120.0
+#: The picker gives up on its own after this long without a result. Long
+#: enough to mark an area up in peace; Esc still ends it at once.
+PICK_TIMEOUT_S = 900.0
#: Grace for the picker to exit (and its overlay to leave the glass).
_EXIT_GRACE_S = 2.0
#: Extra settle time so the compositor has repainted without the dim layer.
@@ -50,18 +55,31 @@ _SETTLE_S = 0.08
Rect = tuple[int, int, int, int]
FRect = tuple[float, float, float, float]
+
@dataclass(frozen=True, slots=True)
class Selection:
- """A finished selection: which Qt screen, which part of it."""
+ """A finished selection: which Qt screen, which part of it, and how it ended.
+
+ ``action`` is the button the user finished with (``done``, ``copy``,
+ ``save`` or ``edit``); ``markup`` holds what they drew on the area, if
+ anything (:mod:`jarvis.appshot.markup`).
+ """
screen: dict[str, float]
rect: FRect
+ action: str = "done"
+ markup: Markup | None = None
class RegionUnavailable(RuntimeError):
"""No area can be selected on this host; the message says why."""
+#: The toolbar's tooltip language for the picker being started.
+_language: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "appshot_picker_language", default="en"
+)
+
#: One picker at a time: a second shortcut press, the page button and the
#: voice tool must not stack overlays (one Esc would cancel all of them).
_picking = False
@@ -195,7 +213,15 @@ def parse_selection(payload: dict[str, Any]) -> Selection | None:
return None
if frac[2] <= 0.0 or frac[3] <= 0.0:
return None
- return Selection(screen=info, rect=frac) # type: ignore[arg-type]
+ from jarvis.appshot.picker import ACTION_DONE, ACTIONS # noqa: PLC0415
+
+ action = payload.get("action")
+ return Selection(
+ screen=info,
+ rect=frac, # type: ignore[arg-type]
+ action=action if action in ACTIONS else ACTION_DONE,
+ markup=parse_markup(payload.get("markup")),
+ )
# --------------------------------------------------------------------------
@@ -264,11 +290,11 @@ def snap_layout() -> dict[str, Any]:
return {"monitors": [dict(m) for m in monitors], "windows": windows}
-def _spawn() -> subprocess.Popen[str]:
+def _spawn(language: str = "en") -> subprocess.Popen[str]:
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415
return subprocess.Popen(
- [sys.executable, "-m", "jarvis.appshot.picker"],
+ [sys.executable, "-m", "jarvis.appshot.picker", "--lang", language or "en"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
@@ -279,15 +305,27 @@ def _spawn() -> subprocess.Popen[str]:
)
-def _read_result(proc: subprocess.Popen[str]) -> dict[str, Any] | None:
- """Block until the picker reports its selection; ``None`` on EOF."""
+def _read_result(
+ proc: subprocess.Popen[str], on_marking: Callable[[], None] | None = None
+) -> dict[str, Any] | None:
+ """Block until the picker reports its selection; ``None`` on EOF.
+
+ ``on_marking`` runs (on this reader thread) once the user has chosen an
+ area and the marking toolbar is up.
+ """
from jarvis.appshot import picker as wire # noqa: PLC0415
assert proc.stdout is not None
for line in proc.stdout:
payload = wire.decode(line)
- if payload is not None and payload.get("event") == wire.EVENT_SELECTION:
+ if payload is None:
+ continue
+ event = payload.get("event")
+ if event == wire.EVENT_SELECTION:
return payload
+ if event == wire.EVENT_MARKING and on_marking is not None:
+ with contextlib.suppress(Exception): # a lost hint only keeps the global Esc
+ on_marking()
return None
@@ -351,9 +389,12 @@ async def _escape_cancels(proc: subprocess.Popen[str]) -> None:
log.debug("appshot: global Escape for the area picker unavailable", exc_info=True)
-async def pick_region(*, timeout_s: float = PICK_TIMEOUT_S) -> Selection | None:
- """Let the user drag a rectangle. ``None`` = cancelled or timed out.
+async def pick_region(
+ *, timeout_s: float = PICK_TIMEOUT_S, language: str = "en"
+) -> Selection | None:
+ """Let the user drag a rectangle and mark it up. ``None`` = cancelled or timed out.
+ ``language`` is the toolbar's tooltip language (``[ui].language``).
Raises :class:`RegionUnavailable` when no picker can run on this host.
"""
global _picking
@@ -364,7 +405,11 @@ async def pick_region(*, timeout_s: float = PICK_TIMEOUT_S) -> Selection | None:
raise RegionUnavailable("An area is already being selected. Finish or press Esc first.")
_picking = True
try:
- payload, code, timed_out = await _run_picker(timeout_s)
+ token = _language.set(language or "en")
+ try:
+ payload, code, timed_out = await _run_picker(timeout_s)
+ finally:
+ _language.reset(token)
finally:
_picking = False
if payload is None and not timed_out and code not in (0, None):
@@ -393,7 +438,7 @@ async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | No
layout = None
# Shielded: a caller cancelled mid-spawn must still get the process reaped,
# or its overlay would cover the screens until the stdin timeout.
- spawn = asyncio.ensure_future(asyncio.to_thread(_spawn))
+ spawn = asyncio.ensure_future(asyncio.to_thread(_spawn, _language.get()))
try:
proc = await asyncio.shield(spawn)
except asyncio.CancelledError:
@@ -407,10 +452,15 @@ async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | No
raise RegionUnavailable("The selection overlay could not be started.") from exc
if layout is not None:
await asyncio.to_thread(_send_layout, proc, layout)
- escape = asyncio.get_running_loop().create_task(
- _escape_cancels(proc), name="appshot-region-esc"
- )
- reader = asyncio.ensure_future(asyncio.to_thread(_read_result, proc))
+ loop = asyncio.get_running_loop()
+ escape = loop.create_task(_escape_cancels(proc), name="appshot-region-esc")
+
+ def marking() -> None:
+ # The picker has keyboard focus now, and Esc there may only end a
+ # text box: the global Esc must stop cancelling the whole picker.
+ loop.call_soon_threadsafe(escape.cancel)
+
+ reader = asyncio.ensure_future(asyncio.to_thread(_read_result, proc, marking))
timed_out = False
payload: dict[str, Any] | None = None
try:
diff --git a/jarvis/appshot/service.py b/jarvis/appshot/service.py
index ec0bb69706..b961122c50 100644
--- a/jarvis/appshot/service.py
+++ b/jarvis/appshot/service.py
@@ -88,14 +88,18 @@ async def take_appshot(
"""Capture once and deliver it per ``[appshot].target``.
``scope="window"`` takes the front window; ``scope="region"`` first lets
- the user drag out an area (:mod:`jarvis.appshot.region`) and takes exactly
- that — a cancelled selection is a refusal with ``reason_code="cancelled"``.
+ the user drag out an area and mark it up in place
+ (:mod:`jarvis.appshot.region`) and takes exactly that, with the markings
+ burnt in — a cancelled selection is a refusal with
+ ``reason_code="cancelled"``. Finishing the area with Copy, Save or Edit
+ also copies, saves or opens the finished appshot.
``deliver=False`` is for a caller that consumes the picture itself (the
live model's tool). Never raises; a refusal carries the user-facing reason.
"""
from jarvis.screen_context.models import IntentVerdict, VisualIntent # noqa: PLC0415
from jarvis.screen_context.turn import get_service # noqa: PLC0415
+ selection = None
try:
config = await asyncio.to_thread(_load_config)
if not config.screen_context.enabled:
@@ -106,14 +110,23 @@ async def take_appshot(
)
service = get_service(bus=bus)
if scope == "region":
- picked = await _pick_area(service)
+ picked = await _pick_area(service, _language(config))
if isinstance(picked, AppshotResult):
return picked
- outcome = await service.capture(
- verdict=IntentVerdict(intent=VisualIntent.SCREEN, evidence=("appshot-region",)),
- trace_id=trace_id or uuid.uuid4(),
- region=picked,
- )
+ bbox, selection = picked
+ from jarvis.appshot.effect import shutter_markup # noqa: PLC0415
+
+ # The corner card's thumbnail is cut at the shutter: give it the
+ # markings too, so it shows what the assistant gets.
+ token = shutter_markup.set(selection.markup)
+ try:
+ outcome = await service.capture(
+ verdict=IntentVerdict(intent=VisualIntent.SCREEN, evidence=("appshot-region",)),
+ trace_id=trace_id or uuid.uuid4(),
+ region=bbox,
+ )
+ finally:
+ shutter_markup.reset(token)
else:
outcome = await service.capture(
verdict=IntentVerdict(intent=VisualIntent.WINDOW, evidence=("appshot",)),
@@ -128,6 +141,8 @@ async def take_appshot(
if outcome.handle_id:
service.consume(outcome.handle_id)
shot = shot_from_context(outcome.context, trigger=trigger)
+ if selection is not None and selection.markup is not None:
+ shot = await _with_markup(shot, selection.markup)
except Exception: # noqa: BLE001 - a shortcut press must never crash the app
log.error("appshot: capture failed", exc_info=True)
return AppshotResult(
@@ -157,11 +172,60 @@ async def take_appshot(
trigger,
delivered_to,
)
+ if selection is not None and selection.action != "done":
+ await _finish_action(selection.action, shot, bus)
return AppshotResult(status="captured", shot=replace(shot, delivered_to=delivered_to))
-async def _pick_area(service: Any) -> tuple[int, int, int, int] | AppshotResult:
- """Run the area picker; the chosen rectangle, or the refusal to return."""
+def _language(config: Any) -> str:
+ return str(getattr(getattr(config, "ui", None), "language", "") or "en").lower()[:2]
+
+
+async def _with_markup(shot: Appshot, markup: Any) -> Appshot:
+ """Burn the markings the user drew in the picker into the finished appshot."""
+ from jarvis.appshot.markup import apply_to_bytes # noqa: PLC0415
+
+ try:
+ image = await asyncio.to_thread(apply_to_bytes, shot.image, shot.mime, markup)
+ except Exception: # noqa: BLE001 - the plain appshot is still worth sending
+ log.warning("appshot: markings could not be applied; sent unmarked", exc_info=True)
+ return shot
+ return replace(shot, image=image, note=f"{shot.note}\n\n{EDIT_NOTE}")
+
+
+async def _finish_action(action: str, shot: Appshot, bus: Any | None) -> None:
+ """Copy, save or open the appshot, as the picker's toolbar asked."""
+ try:
+ if action in ("copy", "save"):
+ from jarvis.appshot.card_actions import as_png, save_to_downloads # noqa: PLC0415
+
+ png = await asyncio.to_thread(as_png, shot.image)
+ if action == "copy":
+ from jarvis.platform.clipboard_image import write_png # noqa: PLC0415
+
+ if not await asyncio.to_thread(write_png, png):
+ log.warning("appshot: the area could not be copied to the clipboard")
+ else:
+ path = await asyncio.to_thread(save_to_downloads, png)
+ log.info("appshot: area saved as %s", path.name)
+ elif action == "edit":
+ from jarvis.appshot.editor_window import open_editor_window # noqa: PLC0415
+
+ if await open_editor_window(shot.id) or bus is None:
+ return
+ from jarvis.core.events import ( # noqa: PLC0415
+ AppshotEditRequested,
+ ShowWindowRequested,
+ )
+
+ await bus.publish(AppshotEditRequested(source_layer="appshot", appshot_id=shot.id))
+ await bus.publish(ShowWindowRequested(source_layer="appshot", source="appshot_picker"))
+ except Exception: # noqa: BLE001 - the appshot itself is taken and delivered
+ log.warning("appshot: the picker's %r action failed", action, exc_info=True)
+
+
+async def _pick_area(service: Any, language: str = "en") -> tuple[Any, Any] | AppshotResult:
+ """Run the area picker; ``(rectangle, selection)``, or the refusal to return."""
from jarvis.appshot.region import ( # noqa: PLC0415
RegionUnavailable,
pick_region,
@@ -169,7 +233,7 @@ async def _pick_area(service: Any) -> tuple[int, int, int, int] | AppshotResult:
)
try:
- selection = await pick_region()
+ selection = await pick_region(language=language)
except RegionUnavailable as exc:
return AppshotResult(status="refused", reason_code="region_unavailable", message=str(exc))
if selection is None:
@@ -184,7 +248,7 @@ async def _pick_area(service: Any) -> tuple[int, int, int, int] | AppshotResult:
reason_code="no_display",
message="No screen could be found for the selected area.",
)
- return bbox
+ return bbox, selection
async def record_turn_capture(context: Any, *, bus: Any | None, trigger: Trigger) -> None:
diff --git a/tests/unit/appshot/test_appshot_markup.py b/tests/unit/appshot/test_appshot_markup.py
new file mode 100644
index 0000000000..42111b49e8
--- /dev/null
+++ b/tests/unit/appshot/test_appshot_markup.py
@@ -0,0 +1,388 @@
+"""Marking up an area in the picker — the rules, the wire, and the burnt-in result.
+
+No display needed: the marking model is plain data, the burn-in is Pillow, and
+the region flow runs against a fake picker and a recording capture service.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+
+import pytest
+from PIL import Image
+
+from jarvis.appshot import region
+from jarvis.appshot import service as appshot_service
+from jarvis.appshot.markup import Hide, Markup, apply_to_bytes, apply_to_rgb, parse_markup
+from jarvis.appshot.picker import ACTION_DONE, EVENT_MARKING, encode
+from jarvis.appshot.picker import markup_model as mm
+from jarvis.screen_context.models import CaptureTarget, ScreenContext, TargetKind, TargetReason
+from jarvis.screen_context.service import CaptureOutcome
+
+SCREEN = {"x": 0.0, "y": 0.0, "w": 1920.0, "h": 1080.0, "dpr": 1.0}
+
+
+def _png(size: tuple[int, int], colour: tuple[int, int, int, int]) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGBA", size, colour).save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def _jpeg(size: tuple[int, int], colour: tuple[int, int, int]) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", size, colour).save(buffer, format="JPEG", quality=95)
+ return buffer.getvalue()
+
+
+# ------------------------------------------------------------------ the model
+
+
+def test_shift_turns_a_box_into_a_square_and_a_line_into_45_degrees() -> None:
+ assert mm.constrain(mm.RECT, (10, 10), (50, 30)) == (50, 50)
+ assert mm.constrain(mm.ELLIPSE, (10, 10), (-20, 15)) == (-20, 40)
+ x, y = mm.constrain(mm.ARROW, (0, 0), (100, 10))
+ assert round(y, 6) == 0 and round(x, 3) == round((100**2 + 10**2) ** 0.5, 3)
+
+
+def test_a_click_without_a_drag_draws_nothing_but_text_and_steps_count() -> None:
+ assert not mm.is_meaningful(mm.Shape(mm.RECT, points=[(5, 5), (6, 6)]))
+ assert not mm.is_meaningful(mm.Shape(mm.ARROW, points=[(5, 5), (6, 5)]))
+ assert mm.is_meaningful(mm.Shape(mm.RECT, points=[(5, 5), (40, 30)]))
+ assert not mm.is_meaningful(mm.Shape(mm.TEXT, points=[(5, 5)], text=" "))
+ assert mm.is_meaningful(mm.Shape(mm.TEXT, points=[(5, 5)], text="here"))
+ assert mm.is_meaningful(mm.Shape(mm.COUNTER, points=[(5, 5)], number=1))
+
+
+def test_steps_number_on_from_the_highest_one() -> None:
+ shapes = [mm.Shape(mm.COUNTER, points=[(0, 0)], number=n) for n in (1, 4, 2)]
+ assert mm.next_counter(shapes) == 5
+ assert mm.next_counter([]) == 1
+
+
+def test_a_rectangle_is_picked_on_its_outline_not_its_empty_inside() -> None:
+ box = mm.Shape(mm.RECT, width=2, points=[(100, 100), (300, 200)])
+ assert mm.hit(box, (100, 150))
+ assert mm.hit(box, (200, 201))
+ assert not mm.hit(box, (200, 150))
+ arrow = mm.Shape(mm.ARROW, width=3, points=[(0, 0), (100, 100)])
+ assert mm.hit(arrow, (50, 52))
+ assert not mm.hit(arrow, (50, 80))
+
+
+def test_the_top_most_marking_wins_and_moving_keeps_the_original() -> None:
+ lower = mm.Shape(mm.BLUR, points=[(0, 0), (100, 100)])
+ upper = mm.Shape(mm.COUNTER, points=[(50, 50)], number=1)
+ assert mm.shape_at([lower, upper], (50, 50)) == 1
+ moved = mm.translated(upper, 10, -5)
+ assert moved.points == [(60, 45)] and upper.points == [(50, 50)]
+
+
+def test_undo_and_redo_walk_the_snapshots() -> None:
+ history = mm.History()
+ shapes = [mm.Shape(mm.RECT, points=[(0, 0), (10, 10)])]
+ history.push(shapes)
+ shapes.append(mm.Shape(mm.LINE, points=[(0, 0), (10, 10)]))
+ history.push(shapes)
+ assert [s.kind for s in history.undo() or []] == [mm.RECT]
+ assert history.undo() == []
+ assert history.undo() is None
+ assert [s.kind for s in history.redo() or []] == [mm.RECT]
+ assert history.can_redo
+ history.push([])
+ assert not history.can_redo
+
+
+def test_snapshots_do_not_share_points_with_the_live_list() -> None:
+ history = mm.History()
+ shape = mm.Shape(mm.PEN, points=[(0, 0), (1, 1)])
+ history.push([shape])
+ history.push([])
+ shape.points.append((9, 9))
+ restored = history.undo()
+ assert restored is not None and restored[0].points == [(0, 0), (1, 1)]
+
+
+def test_the_selection_resizes_by_its_handles_and_never_flips() -> None:
+ sel = (100.0, 100.0, 200.0, 100.0)
+ assert mm.handle_at(sel, (300, 200)) == "se"
+ assert mm.handle_at(sel, (200, 100)) == "n"
+ assert mm.handle_at(sel, (200, 150)) is None
+ assert mm.resize(sel, "se", (400, 260), (1920, 1080)) == (100.0, 100.0, 300.0, 160.0)
+ x, y, w, h = mm.resize(sel, "w", (500, 150), (1920, 1080))
+ assert w == mm.MIN_SELECTION_PX and x == 300.0 - mm.MIN_SELECTION_PX
+ assert mm.resize(sel, "nw", (-50, -50), (1920, 1080))[:2] == (0.0, 0.0)
+
+
+def test_the_toolbar_docks_below_then_above_then_inside_and_stays_on_screen() -> None:
+ screen = (1920.0, 1080.0)
+ bar = (800.0, 40.0)
+ assert mm.toolbar_origin((560, 100, 800, 300), bar, screen) == (560.0, 410.0)
+ assert mm.toolbar_origin((560, 700, 800, 370), bar, screen) == (560.0, 650.0)
+ x, y = mm.toolbar_origin((0, 0, 1920, 1080), bar, screen)
+ assert (x, y) == (560.0, 1080 - 10 - 40)
+ x, _y = mm.toolbar_origin((1800, 100, 100, 100), bar, screen)
+ assert x == 1920 - 800 - 10
+
+
+def test_hide_patches_leave_as_fractions_of_the_area_clipped_to_it() -> None:
+ sel = (100.0, 100.0, 200.0, 100.0)
+ shapes = [
+ mm.Shape(mm.BLUR, points=[(150, 120), (250, 170)]),
+ mm.Shape(mm.PIXELATE, points=[(50, 50), (150, 150)]),
+ mm.Shape(mm.RECT, points=[(150, 120), (250, 170)]),
+ mm.Shape(mm.BLUR, points=[(0, 0), (20, 20)]),
+ ]
+ hides = mm.hide_fractions(shapes, sel)
+ assert hides == [
+ {"kind": "blur", "rect": [0.25, 0.2, 0.5, 0.5]},
+ {"kind": "pixelate", "rect": [0.0, 0.0, 0.25, 0.5]},
+ ]
+
+
+# ---------------------------------------------------------------- the wire
+
+
+def test_markup_parses_and_drops_garbage() -> None:
+ overlay = _png((4, 4), (255, 0, 0, 255))
+ markup = parse_markup(
+ {
+ "overlay": base64.b64encode(overlay).decode(),
+ "hides": [
+ {"kind": "blur", "rect": [0.1, 0.1, 0.2, 0.2]},
+ {"kind": "erase", "rect": [0, 0, 1, 1]},
+ {"kind": "pixelate", "rect": [0, 0, 0, 1]},
+ {"kind": "pixelate", "rect": ["x", 0, 1, 1]},
+ "nope",
+ ],
+ }
+ )
+ assert markup is not None
+ assert markup.overlay_png == overlay
+ assert markup.hides == (Hide("blur", (0.1, 0.1, 0.2, 0.2)),)
+
+
+ "payload",
+ [
+ None,
+ "x",
+ {},
+ {"overlay": "!!!not base64"},
+ {"overlay": base64.b64encode(b"GIF89a").decode()},
+ ],
+)
+def test_no_usable_markup_is_none(payload) -> None:
+ assert parse_markup(payload) is None
+
+
+def test_a_selection_carries_its_action_and_markings() -> None:
+ overlay = base64.b64encode(_png((2, 2), (0, 0, 0, 0))).decode()
+ selection = region.parse_selection(
+ {
+ "event": "selection",
+ "screen": SCREEN,
+ "rect": [0.1, 0.1, 0.5, 0.5],
+ "action": "copy",
+ "markup": {"overlay": overlay, "hides": []},
+ }
+ )
+ assert selection is not None and selection.action == "copy"
+ assert selection.markup is not None and selection.markup.overlay_png
+ plain = region.parse_selection(
+ {"screen": SCREEN, "rect": [0.1, 0.1, 0.5, 0.5], "action": "format-disk"}
+ )
+ assert plain is not None and plain.action == ACTION_DONE and plain.markup is None
+
+
+def test_the_marking_event_reaches_the_reader_before_the_selection() -> None:
+ lines = [
+ encode({"event": "ready"}),
+ encode({"event": EVENT_MARKING}),
+ encode({"event": "selection", "cancelled": True}),
+ ]
+
+ class Proc:
+ stdout = iter(lines)
+
+ seen: list[str] = []
+ payload = region._read_result(Proc(), lambda: seen.append("marking")) # type: ignore[arg-type]
+ assert seen == ["marking"]
+ assert payload == {"event": "selection", "cancelled": True}
+
+
+# ------------------------------------------------------------- the burn-in
+
+
+def test_the_overlay_lands_on_the_capture_at_its_size() -> None:
+ # Overlay drawn at 2x; the capture came out at 1x: it is stretched to fit.
+ overlay = Image.new("RGBA", (200, 100), (0, 0, 0, 0))
+ overlay.paste((255, 0, 0, 255), (0, 0, 100, 100))
+ buffer = io.BytesIO()
+ overlay.save(buffer, format="PNG")
+ marked = apply_to_bytes(
+ _jpeg((100, 50), (0, 0, 255)), "image/jpeg", Markup(overlay_png=buffer.getvalue())
+ )
+ with Image.open(io.BytesIO(marked)) as image:
+ assert image.size == (100, 50)
+ assert image.format == "JPEG"
+ left = image.getpixel((20, 25))
+ right = image.getpixel((80, 25))
+ assert left[0] > 200 and left[2] < 60
+ assert right[2] > 200 and right[0] < 60
+
+
+def test_blur_and_pixelate_hide_what_was_under_them() -> None:
+ picture = Image.new("RGB", (200, 100), (255, 255, 255))
+ for x in range(0, 200, 2):
+ for y in range(100):
+ picture.putpixel((x, y), (0, 0, 0))
+ buffer = io.BytesIO()
+ picture.save(buffer, format="PNG")
+ markup = Markup(hides=(Hide("blur", (0.0, 0.0, 0.5, 1.0)), Hide("pixelate", (0.5, 0, 0.5, 1))))
+ marked = apply_to_bytes(buffer.getvalue(), "image/png", markup)
+ with Image.open(io.BytesIO(marked)) as image:
+ assert image.format == "PNG"
+ row = [image.getpixel((x, 50))[0] for x in range(20, 80)]
+ # The 1-px stripes are gone: a flat grey instead of 0/255 alternating.
+ assert max(row) - min(row) < 60
+
+
+def test_the_thumbnail_gets_the_markings_too() -> None:
+ overlay = _png((10, 10), (0, 255, 0, 255))
+ size, rgb = apply_to_rgb((10, 10), bytes(300), Markup(overlay_png=overlay))
+ assert size == (10, 10)
+ assert rgb[:3] == bytes((0, 255, 0))
+
+
+# ---------------------------------------------------------------- the flow
+
+
+class Config:
+ class screen_context: # noqa: N801 - mirrors the config attribute
+ enabled = True
+ ttl_s = 120.0
+ deck_preview_s = 0.0
+
+ class appshot: # noqa: N801
+ target = "message"
+
+ class ui: # noqa: N801
+ language = "de"
+
+
+class Displays:
+ def monitors(self):
+ return [
+ {"left": 0, "top": 0, "width": 1920, "height": 1080},
+ {"left": 0, "top": 0, "width": 1920, "height": 1080},
+ ]
+
+
+class Capture:
+ def __init__(self) -> None:
+ self.displays = Displays()
+ self.markup_at_shutter: list = []
+
+ async def capture(self, *, verdict=None, trace_id=None, region=None):
+ from jarvis.appshot.effect import shutter_markup
+
+ self.markup_at_shutter.append(shutter_markup.get())
+ context = ScreenContext(
+ image=_jpeg((region[2], region[3]), (0, 0, 255)),
+ mime="image/jpeg",
+ size=(region[2], region[3]),
+ target=CaptureTarget(
+ kind=TargetKind.REGION, bbox=region, reason=TargetReason.USER_REGION
+ ),
+ )
+ return CaptureOutcome(status="captured", verdict=verdict, context=context, handle_id="")
+
+ def consume(self, handle_id):
+ return None
+
+
+def flow(monkeypatch):
+ import jarvis.screen_context.turn as turn
+ from jarvis.appshot.store import get_store
+
+ capture = Capture()
+ picks: list = []
+ asked: list = []
+
+ async def pick_region(**kwargs):
+ asked.append(kwargs)
+ return picks.pop(0) if picks else None
+
+ monkeypatch.setattr(turn, "get_service", lambda bus=None: capture)
+ monkeypatch.setattr(appshot_service, "_load_config", lambda: Config())
+ monkeypatch.setattr(region, "pick_region", pick_region)
+ get_store().clear()
+ yield capture, picks, asked
+ get_store().clear()
+
+
+async def test_a_marked_area_reaches_the_assistant_with_its_markings(flow) -> None:
+ capture, picks, asked = flow
+ red = Image.new("RGBA", (960, 540), (0, 0, 0, 0))
+ red.paste((255, 0, 0, 255), (0, 0, 480, 540))
+ buffer = io.BytesIO()
+ red.save(buffer, format="PNG")
+ markup = Markup(overlay_png=buffer.getvalue())
+ picks.append(region.Selection(screen=SCREEN, rect=(0.25, 0.25, 0.5, 0.5), markup=markup))
+
+ result = await appshot_service.take_appshot(trigger="hotkey", scope="region")
+
+ assert result.ok
+ assert asked == [{"language": "de"}]
+ assert capture.markup_at_shutter == [markup]
+ assert appshot_service.EDIT_NOTE in result.shot.note
+ with Image.open(io.BytesIO(result.shot.image)) as image:
+ assert image.size == (960, 540)
+ assert image.getpixel((100, 270))[0] > 200
+ assert image.getpixel((800, 270))[2] > 200
+ pending = appshot_service.take_pending_for_turn()
+ assert pending is not None and pending.image == result.shot.image
+
+
+async def test_an_unmarked_area_stays_untouched(flow) -> None:
+ _capture, picks, _asked = flow
+ picks.append(region.Selection(screen=SCREEN, rect=(0.0, 0.0, 0.5, 0.5)))
+
+ result = await appshot_service.take_appshot(trigger="hotkey", scope="region")
+
+ assert result.ok
+ assert appshot_service.EDIT_NOTE not in result.shot.note
+
+
+async def test_copy_save_and_edit_run_after_delivery(flow, monkeypatch, tmp_path) -> None:
+ _capture, picks, _asked = flow
+ from jarvis.appshot import card_actions, editor_window
+ from jarvis.platform import clipboard_image
+
+ copied: list[bytes] = []
+ opened: list[str] = []
+ monkeypatch.setattr(clipboard_image, "write_png", lambda png: copied.append(png) or True)
+ monkeypatch.setattr(
+ card_actions,
+ "save_to_downloads",
+ lambda png: (tmp_path / "shot.png").write_bytes(png) and tmp_path / "shot.png",
+ )
+
+ async def open_window(shot_id: str) -> bool:
+ opened.append(shot_id)
+ return True
+
+ monkeypatch.setattr(editor_window, "open_editor_window", open_window)
+ for action in ("copy", "save", "edit"):
+ picks.append(region.Selection(screen=SCREEN, rect=(0.0, 0.0, 0.5, 0.5), action=action))
+
+ copy = await appshot_service.take_appshot(trigger="hotkey", scope="region")
+ await appshot_service.take_appshot(trigger="hotkey", scope="region")
+ edit = await appshot_service.take_appshot(trigger="hotkey", scope="region")
+
+ assert copy.ok and edit.ok
+ assert len(copied) == 1 and copied[0].startswith(b"\x89PNG")
+ assert (tmp_path / "shot.png").read_bytes().startswith(b"\x89PNG")
+ assert opened == [edit.shot.id]