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): give the area picker ShareX's region-capture look

rubenluetke10-beep17926ed1be9d
diff --git a/docs/appshots.md b/docs/appshots.md
index f5eb85dfae..ce5c503bd4 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -23,12 +23,26 @@ window there, it takes the whole screen instead.
The area picker is a short-lived PySide6 process (`python -m
jarvis.appshot.picker`) that starts on the shortcut and exits after one
-selection, so nothing stays resident. It covers every screen with a dimmed
-layer and a crosshair, shows the size in real pixels while you drag, and
-reports the rectangle as fractions of the screen it was drawn on; the app maps
-that back to capture pixels (`jarvis/appshot/region.py`), so mixed-DPI setups
-capture exactly what was outlined. A selection stays on one screen. The picker
-gives up after two minutes without a selection.
+selection, so nothing stays resident. Its look follows ShareX's region
+capture:
+
+- every screen is frozen and dimmed the moment the picker opens, so nothing
+ moves under the selection (where a frozen frame cannot be grabbed, a dim
+ layer over the live desktop is used instead, without the magnifier);
+- hovering highlights the window under the pointer, and a click without a
+ drag takes exactly that window;
+- a drag cuts the area out of the dim layer with a marching-ants border and
+ its size in real pixels;
+- a magnifier beside the pointer shows a zoomed pixel grid with the centre
+ pixel marked, plus the position (or the selection size while dragging).
+
+The picker reports the rectangle as fractions of the screen it was drawn on;
+the app maps that back to capture pixels (`jarvis/appshot/region.py`), so
+mixed-DPI setups capture exactly what was outlined. A selection stays on one
+screen. The window list for snapping is read before the overlay appears and
+skips minimized and (on Windows) cloaked windows; where no list is available
+(Wayland) only dragging works. The picker gives up after two minutes without
+a selection.
A selected area is about pixels, not about the window in front: unlike a window
appshot it is not voided when focus moves while the picker closes. Its privacy
diff --git a/jarvis/appshot/picker/__init__.py b/jarvis/appshot/picker/__init__.py
index feeaff3b7e..74813e9697 100644
--- a/jarvis/appshot/picker/__init__.py
+++ b/jarvis/appshot/picker/__init__.py
@@ -16,6 +16,8 @@ stdout::
stdin::
+ {"cmd": "layout", "monitors": [...], # mss monitors and the
+ "windows": [[l, t, w, h], ...]} # snap targets, top first
{"cmd": "cancel"} # e.g. a global Esc
Stdin EOF (the parent died) cancels as well.
@@ -32,6 +34,7 @@ EXIT_NO_GUI = 3
EVENT_READY = "ready"
EVENT_SELECTION = "selection"
CMD_CANCEL = "cancel"
+CMD_LAYOUT = "layout"
def encode(payload: dict[str, Any]) -> str:
@@ -47,4 +50,12 @@ def decode(line: str) -> dict[str, Any] | None:
return payload if isinstance(payload, dict) else None
-__all__ = ["CMD_CANCEL", "EVENT_READY", "EVENT_SELECTION", "EXIT_NO_GUI", "decode", "encode"]
+__all__ = [
+ "CMD_CANCEL",
+ "CMD_LAYOUT",
+ "EVENT_READY",
+ "EVENT_SELECTION",
+ "EXIT_NO_GUI",
+ "decode",
+ "encode",
+]
diff --git a/jarvis/appshot/picker/renderer.py b/jarvis/appshot/picker/renderer.py
index 9556d6acbb..e457e90706 100644
--- a/jarvis/appshot/picker/renderer.py
+++ b/jarvis/appshot/picker/renderer.py
@@ -1,11 +1,23 @@
-"""PySide6 area picker for region appshots.
+"""PySide6 area picker for region appshots, modelled on ShareX's region capture.
Runs ONLY inside ``python -m jarvis.appshot.picker``; the main process never
-imports this module (AP-26). One dimmed, frameless, always-on-top window per
-screen with a crosshair: drag a rectangle (live size readout in real pixels),
-release to confirm, Esc or right-click to cancel. The selection is reported as
-fractions of its screen, so mixed-DPI layouts map back to capture pixels
-exactly (see :mod:`jarvis.appshot.region`).
+imports this module (AP-26). One frameless, always-on-top window per screen:
+
+- **Frozen screen.** Each screen is grabbed once before the overlay appears
+ and shown dimmed, so nothing moves under the selection. Where the grab
+ fails (no permission, odd platform) the overlay falls back to a translucent
+ dim layer over the live desktop and simply has no magnifier.
+- **Window snapping.** Hovering highlights the window under the pointer
+ (rectangles from the main process, top-most first); a click without a drag
+ selects exactly that window.
+- **Drag to select.** The selection is cut out of the dim layer with a
+ marching-ants border and its size in real pixels.
+- **Magnifier.** A zoomed pixel grid beside the pointer with the centre pixel
+ marked and the position (or the selection size) underneath.
+
+Esc or a right-click cancels. The result is reported as fractions of its
+screen, so mixed-DPI layouts map back to capture pixels exactly (see
+:mod:`jarvis.appshot.region`).
"""
from __future__ import annotations
@@ -14,7 +26,7 @@ import sys
import threading
from contextlib import suppress
-from PySide6.QtCore import QObject, QPointF, QRectF, Qt, Signal, Slot
+from PySide6.QtCore import QObject, QPointF, QRect, QRectF, Qt, QTimer, Signal, Slot
from PySide6.QtGui import (
QColor,
QCursor,
@@ -24,16 +36,35 @@ from PySide6.QtGui import (
QPainter,
QPainterPath,
QPen,
+ QPixmap,
)
from PySide6.QtWidgets import QApplication, QWidget
from jarvis.appshot import picker as wire
-from jarvis.appshot.region import selection_fractions
+from jarvis.appshot.region import (
+ match_monitor,
+ selection_fractions,
+ snap_rects_on_screen,
+)
+
+_DIM = QColor(0, 0, 0, 115)
+_LABEL_BG = QColor(18, 18, 20, 225)
+_LABEL_FG = QColor(255, 255, 255, 240)
+_LABEL_MUTED = QColor(255, 255, 255, 150)
+
+#: Magnifier: this many source pixels per side, each drawn this many px wide.
+_MAG_PIXELS = 15
+_MAG_CELL = 10
+_MAG_SIZE = _MAG_PIXELS * _MAG_CELL
+_MAG_OFFSET = 22
+_MAG_RADIUS = 6.0
-# Jarvis gold, the same edge colour as the capture border and the shutter.
-_GOLD = (255, 229, 0)
-_SOFT_GOLD = (231, 196, 110)
-_DIM_ALPHA = 105
+#: Marching ants: dash length and the tick that moves them.
+_DASH = 4.0
+_ANTS_MS = 90
+
+#: Windows smaller than this (logical px, either side) are not snap targets.
+_MIN_SNAP_PX = 24
def _screen_info(screen) -> dict[str, float]:
@@ -54,10 +85,26 @@ def _emit(payload: dict) -> None:
sys.stdout.flush()
+def _font(size: float, *, bold: bool = False) -> QFont:
+ font = QFont()
+ font.setPointSizeF(size)
+ font.setWeight(QFont.Weight.DemiBold if bold else QFont.Weight.Normal)
+ return font
+
+
+def _draw_label(painter: QPainter, box: QRectF, text: str, font: QFont) -> None:
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(_LABEL_BG)
+ painter.drawRoundedRect(box, 4.0, 4.0)
+ painter.setFont(font)
+ painter.setPen(_LABEL_FG)
+ painter.drawText(box, Qt.AlignmentFlag.AlignCenter, text)
+
+
class _SelectWindow(QWidget):
- """One screen's dimmed selection canvas."""
+ """One screen's selection canvas."""
- def __init__(self, screen, owner: Picker) -> None:
+ def __init__(self, screen, frozen: QPixmap | None, owner: Picker) -> None:
super().__init__(None)
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint
@@ -65,7 +112,8 @@ class _SelectWindow(QWidget):
| Qt.WindowType.Tool
| Qt.WindowType.NoDropShadowWindowHint
)
- self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ if frozen is None:
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
if sys.platform == "darwin":
# Qt::Tool is an NSPanel on macOS; without this it stays invisible
# while this never-activated process is in the background.
@@ -78,11 +126,27 @@ class _SelectWindow(QWidget):
self.setMouseTracking(True)
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.screen_ref = screen
+ self._frozen = frozen
self._owner = owner
self._start: QPointF | None = None
self._end: QPointF | None = None
self._pointer: QPointF | None = None
+ #: Snap targets in this window's logical coordinates, top-most first.
+ self._snaps: list[QRectF] = []
+ self._monitor: dict | None = None
+
+ # -- data from the main process ------------------------------------------
+ def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:
+ """Map capture-space window rects onto this screen's logical pixels."""
+ info = _screen_info(self.screen_ref)
+ self._monitor = match_monitor(info, monitors)
+ rects = snap_rects_on_screen(
+ info, (self.width(), self.height()), monitors, windows, min_px=_MIN_SNAP_PX
+ )
+ self._snaps = [QRectF(*rect) for rect in rects]
+ self.update()
+ # -- input ---------------------------------------------------------------
def keyPressEvent(self, event) -> None: # noqa: N802 (Qt override)
if event.key() == Qt.Key.Key_Escape:
self._owner.finish(None, None)
@@ -114,8 +178,18 @@ class _SelectWindow(QWidget):
self._start.x(), self._start.y(), end.x(), end.y(), self.width(), self.height()
)
self._start = None
+ self._end = None
+ if frac is None:
+ # A click, not a drag: take the window under the pointer, if any.
+ snap = self._snap_at(end)
+ if snap is not None:
+ frac = (
+ snap.x() / self.width(),
+ snap.y() / self.height(),
+ snap.width() / self.width(),
+ snap.height() / self.height(),
+ )
if frac is None:
- # A click without a drag: keep the overlay up for a real selection.
self.update()
return
self._owner.finish(self, frac)
@@ -124,79 +198,187 @@ class _SelectWindow(QWidget):
if self._pointer is not None or self._start is not None:
self._pointer = None
self._start = None
+ self._end = None
self.update()
+ def has_hole(self) -> bool:
+ return self._hole() is not None
+
+ # -- geometry ------------------------------------------------------------
def _selection(self) -> QRectF | None:
if self._start is None or self._end is None:
return None
return QRectF(self._start, self._end).normalized()
+ def _snap_at(self, point: QPointF) -> QRectF | None:
+ for rect in self._snaps:
+ if rect.contains(point):
+ return rect
+ return None
+
+ def _hole(self) -> QRectF | None:
+ sel = self._selection()
+ if sel is not None:
+ return sel
+ if self._pointer is not None:
+ return self._snap_at(self._pointer)
+ return None
+
+ def _scale(self) -> float:
+ """Device pixels per logical pixel — from the frozen frame when present."""
+ if self._frozen is not None and self.width() > 0:
+ return self._frozen.width() / self.width()
+ return float(self.screen_ref.devicePixelRatio() or 1.0)
+
+ def _capture_point(self, point: QPointF) -> tuple[int, int]:
+ """``point`` in capture coordinates (what the screenshot will use)."""
+ mon = self._monitor
+ if mon is None:
+ scale = self._scale()
+ return round(point.x() * scale), round(point.y() * scale)
+ fx = point.x() / max(1.0, self.width())
+ fy = point.y() / max(1.0, self.height())
+ return (
+ round(float(mon.get("left", 0)) + fx * float(mon.get("width", 0))),
+ round(float(mon.get("top", 0)) + fy * float(mon.get("height", 0))),
+ )
+
+ # -- painting ------------------------------------------------------------
def paintEvent(self, event) -> None: # noqa: N802
del event
painter = QPainter(self)
- painter.setRenderHint(QPainter.RenderHint.Antialiasing)
full = QRectF(0, 0, self.width(), self.height())
- sel = self._selection()
+ if self._frozen is not None:
+ painter.drawPixmap(full, self._frozen, QRectF(self._frozen.rect()))
+ hole = self._hole()
dim = QPainterPath()
dim.addRect(full)
- if sel is not None:
- hole = QPainterPath()
- hole.addRect(sel)
- dim = dim.subtracted(hole)
- painter.fillPath(dim, QColor(0, 0, 0, _DIM_ALPHA))
- if sel is not None:
- pen = QPen(QColor(*_GOLD, 235))
- pen.setWidthF(1.5)
- painter.setPen(pen)
- painter.setBrush(Qt.BrushStyle.NoBrush)
- painter.drawRect(sel)
- self._paint_size(painter, sel)
- elif self._pointer is not None:
- pen = QPen(QColor(255, 255, 255, 120))
- pen.setWidthF(1.0)
- painter.setPen(pen)
- p = self._pointer
- painter.drawLine(QPointF(0, p.y()), QPointF(self.width(), p.y()))
- painter.drawLine(QPointF(p.x(), 0), QPointF(p.x(), self.height()))
+ if hole is not None:
+ cut = QPainterPath()
+ cut.addRect(hole)
+ dim = dim.subtracted(cut)
+ painter.fillPath(dim, _DIM)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ if hole is not None:
+ self._paint_border(painter, hole)
+ self._paint_size(painter, hole)
+ if self._pointer is not None and self._frozen is not None:
+ self._paint_magnifier(painter, self._pointer)
if self._owner.hint and self._owner.hint_window is self:
self._paint_hint(painter, self._owner.hint)
painter.end()
- def _paint_size(self, painter: QPainter, sel: QRectF) -> None:
- dpr = float(self.screen_ref.devicePixelRatio() or 1.0)
- text = f"{round(sel.width() * dpr)} × {round(sel.height() * dpr)}"
- font = QFont()
- font.setPointSizeF(9.5)
- font.setWeight(QFont.Weight.DemiBold)
- painter.setFont(font)
+ def _paint_border(self, painter: QPainter, rect: QRectF) -> None:
+ r = rect.adjusted(0.5, 0.5, -0.5, -0.5)
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.setPen(QPen(QColor(0, 0, 0, 220), 1.0))
+ painter.drawRect(r)
+ ants = QPen(QColor(255, 255, 255, 250), 1.0)
+ ants.setDashPattern([_DASH, _DASH])
+ ants.setDashOffset(self._owner.ants_offset)
+ painter.setPen(ants)
+ painter.drawRect(r)
+
+ def _paint_size(self, painter: QPainter, rect: QRectF) -> None:
+ scale = self._scale()
+ text = f"{round(rect.width() * scale)} × {round(rect.height() * scale)}"
+ font = _font(9.0, bold=True)
metrics = QFontMetricsF(font)
- w = metrics.horizontalAdvance(text) + 16.0
- h = metrics.height() + 8.0
- x = sel.right() - w
- y = sel.bottom() + 6.0
- if y + h > self.height():
- y = sel.bottom() - h - 6.0
+ w = metrics.horizontalAdvance(text) + 14.0
+ h = metrics.height() + 6.0
+ x = rect.left()
+ y = rect.top() - h - 5.0
+ if y < 4.0:
+ x, y = rect.left() + 5.0, rect.top() + 5.0
x = max(4.0, min(x, self.width() - w - 4.0))
- box = QRectF(x, y, w, h)
+ _draw_label(painter, QRectF(x, y, w, h), text, font)
+
+ def _paint_magnifier(self, painter: QPainter, point: QPointF) -> None:
+ frozen = self._frozen
+ assert frozen is not None
+ scale = self._scale()
+ cx, cy = int(point.x() * scale), int(point.y() * scale)
+ half = _MAG_PIXELS // 2
+ source = QRect(cx - half, cy - half, _MAG_PIXELS, _MAG_PIXELS)
+
+ sel = self._selection()
+ if sel is not None:
+ info = f"{round(sel.width() * scale)} × {round(sel.height() * scale)}"
+ else:
+ px, py = self._capture_point(point)
+ info = f"X: {px} Y: {py}"
+ font = _font(8.5)
+ metrics = QFontMetricsF(font)
+ info_h = metrics.height() + 8.0
+ total_h = _MAG_SIZE + 4.0 + info_h
+
+ x = point.x() + _MAG_OFFSET
+ y = point.y() + _MAG_OFFSET
+ if x + _MAG_SIZE > self.width() - 4:
+ x = point.x() - _MAG_OFFSET - _MAG_SIZE
+ if y + total_h > self.height() - 4:
+ y = point.y() - _MAG_OFFSET - total_h
+ box = QRectF(x, y, _MAG_SIZE, _MAG_SIZE)
+
+ # Soft shadow, then the zoomed pixels clipped to a rounded square.
painter.setPen(Qt.PenStyle.NoPen)
- painter.setBrush(QColor(18, 18, 18, 210))
- painter.drawRoundedRect(box, h / 2.0, h / 2.0)
- painter.setPen(QColor(255, 244, 205, 240))
- painter.drawText(box, Qt.AlignmentFlag.AlignCenter, text)
+ for spread, alpha in ((6.0, 20), (3.0, 35), (1.0, 60)):
+ painter.setBrush(QColor(0, 0, 0, alpha))
+ painter.drawRoundedRect(
+ box.adjusted(-spread, -spread + 2, spread, spread + 2),
+ _MAG_RADIUS + spread,
+ _MAG_RADIUS + spread,
+ )
+ clip = QPainterPath()
+ clip.addRoundedRect(box, _MAG_RADIUS, _MAG_RADIUS)
+ painter.save()
+ painter.setClipPath(clip)
+ painter.fillRect(box, QColor(0, 0, 0))
+ painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, False)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)
+ visible = source.intersected(frozen.rect())
+ if not visible.isEmpty():
+ target = QRectF(
+ box.x() + (visible.x() - source.x()) * _MAG_CELL,
+ box.y() + (visible.y() - source.y()) * _MAG_CELL,
+ visible.width() * _MAG_CELL,
+ visible.height() * _MAG_CELL,
+ )
+ painter.drawPixmap(target, frozen, QRectF(visible))
+ # Pixel grid and a tinted crosshair row/column through the centre.
+ painter.setPen(QPen(QColor(0, 0, 0, 45), 1.0))
+ for i in range(1, _MAG_PIXELS):
+ off = i * _MAG_CELL
+ painter.drawLine(QPointF(box.x() + off, box.y()), QPointF(box.x() + off, box.bottom()))
+ painter.drawLine(QPointF(box.x(), box.y() + off), QPointF(box.right(), box.y() + off))
+ offset = half * _MAG_CELL
+ centre = QRectF(box.x() + offset, box.y() + offset, _MAG_CELL, _MAG_CELL)
+ tint = QColor(90, 160, 255, 55)
+ painter.fillRect(QRectF(box.x(), centre.y(), box.width(), _MAG_CELL), tint)
+ painter.fillRect(QRectF(centre.x(), box.y(), _MAG_CELL, box.height()), tint)
+ painter.setPen(QPen(QColor(0, 0, 0, 230), 1.0))
+ painter.drawRect(centre.adjusted(-1, -1, 0, 0))
+ painter.setPen(QPen(QColor(255, 255, 255, 240), 1.0))
+ painter.drawRect(centre)
+ painter.restore()
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.setPen(QPen(QColor(255, 255, 255, 200), 1.0))
+ painter.drawRoundedRect(box.adjusted(0.5, 0.5, -0.5, -0.5), _MAG_RADIUS, _MAG_RADIUS)
+
+ info_box = QRectF(box.x(), box.bottom() + 4.0, _MAG_SIZE, info_h)
+ _draw_label(painter, info_box, info, font)
def _paint_hint(self, painter: QPainter, hint: str) -> None:
- font = QFont()
- font.setPointSizeF(10.5)
- font.setWeight(QFont.Weight.Medium)
- painter.setFont(font)
+ font = _font(9.0)
metrics = QFontMetricsF(font)
- w = metrics.horizontalAdvance(hint) + 32.0
- h = metrics.height() + 14.0
- box = QRectF((self.width() - w) / 2.0, 24.0, w, h)
- painter.setPen(QPen(QColor(*_SOFT_GOLD, 200), 1.0))
- painter.setBrush(QColor(18, 18, 18, 190))
- painter.drawRoundedRect(box, h / 2.0, h / 2.0)
- painter.setPen(QColor(255, 240, 200, 240))
+ w = metrics.horizontalAdvance(hint) + 24.0
+ h = metrics.height() + 10.0
+ box = QRectF((self.width() - w) / 2.0, 16.0, w, h)
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(_LABEL_BG)
+ painter.drawRoundedRect(box, 5.0, 5.0)
+ painter.setFont(font)
+ painter.setPen(_LABEL_MUTED)
painter.drawText(box, Qt.AlignmentFlag.AlignCenter, hint)
@@ -210,9 +392,16 @@ class Picker(QObject):
self._windows: list[_SelectWindow] = []
self.hint_window: _SelectWindow | None = None
self._done = False
+ self.ants_offset = 0.0
+ self._ants = QTimer(self)
+ self._ants.setInterval(_ANTS_MS)
+ self._ants.timeout.connect(self._march)
def start(self) -> None:
- self._windows = [_SelectWindow(s, self) for s in QGuiApplication.screens()]
+ screens = QGuiApplication.screens()
+ # Freeze every screen BEFORE any overlay window exists.
+ frozen = {id(s): self._grab(s) for s in screens}
+ self._windows = [_SelectWindow(s, frozen[id(s)], self) for s in screens]
cursor_screen = QGuiApplication.screenAt(QCursor.pos()) or QGuiApplication.primaryScreen()
self.hint_window = next(
(w for w in self._windows if w.screen_ref is cursor_screen),
@@ -224,9 +413,29 @@ class Picker(QObject):
self.hint_window.raise_()
self.hint_window.activateWindow()
self.hint_window.setFocus()
+ self._ants.start()
self._app.processEvents()
_emit({"event": wire.EVENT_READY})
+ @staticmethod
+ def _grab(screen) -> QPixmap | None:
+ try:
+ pixmap = screen.grabWindow(0)
+ except Exception: # noqa: BLE001 - no frozen frame: fall back to a live dim layer
+ sys.stderr.write("appshot-picker: screen grab failed; using a live overlay\n")
+ return None
+ return None if pixmap.isNull() or pixmap.width() <= 0 else pixmap
+
+ def _march(self) -> None:
+ self.ants_offset = (self.ants_offset + 1.0) % (2 * _DASH)
+ for win in self._windows:
+ if win.has_hole():
+ win.update()
+
+ def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:
+ for win in self._windows:
+ win.set_layout(monitors, windows)
+
def focus_on(self, window: _SelectWindow) -> None:
"""The pointer moved onto ``window``: only that screen shows a guide."""
for other in self._windows:
@@ -241,10 +450,11 @@ class Picker(QObject):
if self._done:
return
self._done = True
+ self._ants.stop()
info = _screen_info(window.screen_ref) if window is not None else None
for win in self._windows:
win.hide()
- # The dimmed overlay must be off the glass before the parent grabs.
+ # The overlay must be off the glass before the parent grabs.
self._app.processEvents()
if info is None or frac is None:
_emit({"event": wire.EVENT_SELECTION, "cancelled": True})
@@ -255,8 +465,16 @@ class Picker(QObject):
@Slot(str)
def on_line(self, raw: str) -> None:
payload = wire.decode(raw)
- if payload is not None and payload.get("cmd") == wire.CMD_CANCEL:
+ if payload is None:
+ return
+ cmd = payload.get("cmd")
+ if cmd == wire.CMD_CANCEL:
self.finish(None, None)
+ elif cmd == wire.CMD_LAYOUT:
+ monitors = payload.get("monitors")
+ windows = payload.get("windows")
+ if isinstance(monitors, list) and isinstance(windows, list):
+ self.set_layout([m for m in monitors if isinstance(m, dict)], windows)
@Slot()
def on_eof(self) -> None:
@@ -295,8 +513,8 @@ def run(*, hint: str = "") -> int:
pump = _StdinPump()
pump.line.connect(picker.on_line, Qt.ConnectionType.QueuedConnection)
pump.eof.connect(picker.on_eof, Qt.ConnectionType.QueuedConnection)
- pump.start()
picker.start()
+ pump.start()
return app.exec()
diff --git a/jarvis/appshot/region.py b/jarvis/appshot/region.py
index a87239916a..24976070db 100644
--- a/jarvis/appshot/region.py
+++ b/jarvis/appshot/region.py
@@ -50,12 +50,12 @@ _SETTLE_S = 0.08
Rect = tuple[int, int, int, int]
FRect = tuple[float, float, float, float]
-# Hint pill over the screens — ALL supported output locales, resolved through
-# the one turn-language resolver (a phrase table always carries every locale).
+# Hint pill over the screens — app chrome, so it follows the app's display
+# language ([ui].language); a phrase table always carries every locale.
_HINTS: dict[str, str] = {
- "de": "Ziehe über den Bereich, den du zeigen willst · Esc bricht ab", # i18n-allow
- "en": "Drag over the area you want to show · Esc to cancel",
- "es": "Arrastra sobre la zona que quieres mostrar · Esc para cancelar", # i18n-allow
+ "de": "Bereich ziehen · Fenster anklicken · Esc bricht ab", # i18n-allow
+ "en": "Drag to select an area · Click a window · Esc to cancel",
+ "es": "Arrastra para elegir una zona · Clic en una ventana · Esc cancela", # i18n-allow
}
@@ -155,6 +155,41 @@ def selection_to_bbox(selection: Selection, monitors: list[dict]) -> Rect | None
return fraction_to_bbox(monitor, selection.rect)
+def snap_rects_on_screen(
+ screen: dict,
+ size: tuple[float, float],
+ monitors: list[dict],
+ windows: list[list[int]],
+ *,
+ min_px: float,
+) -> list[FRect]:
+ """Capture-space window rects → the picker screen's logical pixels.
+
+ ``size`` is the picker window's logical size. Rects are clipped to the
+ screen; slivers under ``min_px`` and rects on other screens are dropped.
+ Order (top-most first) is kept, so the first hit is the visible window.
+ """
+ monitor = match_monitor(screen, monitors)
+ if monitor is None:
+ return []
+ ml, mt = float(monitor.get("left", 0)), float(monitor.get("top", 0))
+ mw = max(1.0, float(monitor.get("width", 1)))
+ mh = max(1.0, float(monitor.get("height", 1)))
+ width, height = float(size[0]), float(size[1])
+ sx, sy = width / mw, height / mh
+ out: list[FRect] = []
+ for rect in windows:
+ if not isinstance(rect, (list, tuple)) or len(rect) != 4:
+ continue
+ left, top, w, h = (float(v) for v in rect)
+ x0, y0 = max(0.0, (left - ml) * sx), max(0.0, (top - mt) * sy)
+ x1 = min(width, (left + w - ml) * sx)
+ y1 = min(height, (top + h - mt) * sy)
+ if x1 - x0 >= min_px and y1 - y0 >= min_px:
+ out.append((x0, y0, x1 - x0, y1 - y0))
+ return out
+
+
def parse_selection(payload: dict[str, Any]) -> Selection | None:
"""A picker ``selection`` event → :class:`Selection` (``None`` = cancelled)."""
if payload.get("cancelled"):
@@ -196,19 +231,59 @@ def picker_capability() -> tuple[bool, str]:
def _hint() -> str:
try:
from jarvis.core.config import load_config # noqa: PLC0415
- from jarvis.core.turn_language import ( # noqa: PLC0415
- DEFAULT_LOCALE,
- resolve_output_language,
- )
- pin = str(getattr(load_config().brain, "reply_language", "") or "")
- language = resolve_output_language(pin, "", "", default=DEFAULT_LOCALE)
+ language = str(getattr(load_config().ui, "language", "") or "").lower()[:2]
return _HINTS.get(language, _HINTS["en"])
except Exception: # noqa: BLE001 - the hint is decoration; English is honest
log.debug("appshot: picker hint language unresolved", exc_info=True)
return _HINTS["en"]
+def _is_cloaked(handle: int | None) -> bool:
+ """Windows only: a DWM-cloaked window (hidden UWP shells) is no target."""
+ if os.name != "nt" or not handle:
+ return False
+ try:
+ import ctypes # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ dwmapi = ctypes.WinDLL("dwmapi")
+ cloaked = wintypes.DWORD(0)
+ result = dwmapi.DwmGetWindowAttribute(
+ wintypes.HWND(handle), 14, ctypes.byref(cloaked), ctypes.sizeof(cloaked)
+ )
+ return result == 0 and bool(cloaked.value)
+ except Exception: # noqa: BLE001 - unknown cloak state keeps the window
+ return False
+
+
+def snap_layout() -> dict[str, Any]:
+ """Monitors and window rectangles for the picker's window snapping.
+
+ Read BEFORE the picker exists, so its own overlay never becomes a target.
+ Rects are in capture coordinates, top-most window first; an empty window
+ list (Wayland, an unreadable desktop) only switches snapping off.
+ """
+ from jarvis.screen_context.ports import make_display_enumerator # noqa: PLC0415
+
+ monitors = make_display_enumerator().monitors()
+ windows: list[list[int]] = []
+ try:
+ from jarvis.platform import window_state as ws # noqa: PLC0415
+ from jarvis.screen_context.ports import _input_space # noqa: PLC0415
+
+ with _input_space():
+ for win in ws.list_windows():
+ if getattr(win, "minimized", False) or _is_cloaked(getattr(win, "handle", None)):
+ continue
+ rect = ws.window_frame_rect(win) or ws.window_rect(win)
+ if rect and rect[2] > 0 and rect[3] > 0:
+ windows.append([int(v) for v in rect])
+ except Exception: # noqa: BLE001 - snapping is a convenience; dragging still works
+ log.debug("appshot: window list for snapping unavailable", exc_info=True)
+ return {"monitors": [dict(m) for m in monitors], "windows": windows}
+
+
def _spawn(hint: str) -> subprocess.Popen[str]:
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS # noqa: PLC0415
@@ -236,6 +311,15 @@ def _read_result(proc: subprocess.Popen[str]) -> dict[str, Any] | None:
return None
+def _send_layout(proc: subprocess.Popen[str], layout: dict[str, Any]) -> None:
+ from jarvis.appshot import picker as wire # noqa: PLC0415
+
+ with contextlib.suppress(Exception): # a closed pipe means it already ended
+ if proc.stdin is not None and proc.poll() is None:
+ proc.stdin.write(wire.encode({"cmd": wire.CMD_LAYOUT, **layout}))
+ proc.stdin.flush()
+
+
def _cancel(proc: subprocess.Popen[str]) -> None:
from jarvis.appshot import picker as wire # noqa: PLC0415
@@ -323,6 +407,11 @@ def _exit_message(code: int) -> str:
async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | None, bool]:
"""Spawn, wait for one selection, always reap. ``(payload, exit code, timed out)``."""
hint = await asyncio.to_thread(_hint)
+ try:
+ layout = await asyncio.to_thread(snap_layout)
+ except Exception: # noqa: BLE001 - no snapping; dragging still works
+ log.debug("appshot: snap layout unavailable", exc_info=True)
+ 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, hint))
@@ -337,6 +426,8 @@ async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | No
except Exception as exc: # noqa: BLE001 - surfaced to the user as unavailable
log.warning("appshot: area picker could not be started", exc_info=True)
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"
)
@@ -373,4 +464,6 @@ __all__ = [
"screen_monitor_score",
"selection_fractions",
"selection_to_bbox",
+ "snap_layout",
+ "snap_rects_on_screen",
]
diff --git a/tests/unit/appshot/test_appshot_region.py b/tests/unit/appshot/test_appshot_region.py
index fec5271a40..5c8ac42af8 100644
--- a/tests/unit/appshot/test_appshot_region.py
+++ b/tests/unit/appshot/test_appshot_region.py
@@ -480,3 +480,25 @@ async def test_overlapping_reloads_leave_exactly_one_listener(monkeypatch) -> No
await shortcut.stop()
await asyncio.sleep(0)
assert running == []
+
+
+# ------------------------------------------------------------ window snapping
+
+
+def test_window_rects_land_on_the_picker_screen_in_logical_pixels() -> None:
+ laptop = {"x": -3840.0, "y": 0.0, "w": 2560.0, "h": 1440.0, "dpr": 1.5}
+ windows = [
+ [-3840, 0, 1920, 1080], # top-left quarter of the 4K laptop
+ [-300, 100, 900, 600], # straddles both screens: clipped to the laptop
+ [100, 100, 800, 600], # entirely on the other monitor
+ [-3840, 0, 20, 20], # a sliver
+ ]
+
+ rects = region.snap_rects_on_screen(laptop, (2560, 1440), MONITORS, windows, min_px=24)
+
+ assert rects == [(0.0, 0.0, 1280.0, 720.0), (2360.0, 66.66666666666666, 200.0, 400.0)]
+
+
+def test_no_monitors_means_no_snap_targets() -> None:
+ screen = {"x": 0, "y": 0, "w": 100, "h": 100, "dpr": 1}
+ assert region.snap_rects_on_screen(screen, (100, 100), [], [[0, 0, 50, 50]], min_px=1) == []