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): snap the area picker to the parts of a window, not only the window (#785)

Ruben Lütked5f1d67644cf
diff --git a/docs/appshots.md b/docs/appshots.md
index 4d8cef0406..1517b6857a 100644
--- a/docs/appshots.md
+++ b/docs/appshots.md
@@ -61,7 +61,12 @@ blur previews, markings and windows while keeping Qt loaded. The picker provides
beside it show the position — while dragging, the width and height in real
pixels. No lens, no boxed labels, no banner;
- hovering lifts the window under the pointer out of the dim, and a click
- without a drag takes exactly that window;
+ without a drag takes exactly that window. On Windows it offers the parts
+ inside the window too (a sidebar, a list, a field, a panel, a button):
+ the smallest part under the pointer lights up as soon as the window has
+ been read (typically 10-200 ms), the mouse wheel steps out to the larger
+ parts around it and the whole window (and back in), and a click takes
+ what is lit;
- a drag clears the dim and tints the selected area a translucent grey
with one thin border.
@@ -153,7 +158,13 @@ the app maps that back to capture pixels (`dodaios/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 fifteen minutes
+(Wayland) only dragging works. The parts of a window come from UI Automation
+(`dodaios/appshot/picker/elements.py`): one cached query per window on a
+worker thread, the window under the pointer first, each window read once per
+pick; text runs, links, scroll bars and parts under 16 px are left out, and
+nested parts that are nearly the same box count as one wheel step. Off
+Windows, and for windows that expose no parts, hovering snaps to whole
+windows as before. The picker gives up after fifteen minutes
without a result.
A selected area is about pixels, not about the window in front: unlike a window
diff --git a/dodaios/appshot/picker/__init__.py b/dodaios/appshot/picker/__init__.py
index 4d0c5a84b1..4d2b50e74e 100644
--- a/dodaios/appshot/picker/__init__.py
+++ b/dodaios/appshot/picker/__init__.py
@@ -32,10 +32,11 @@ stdout::
stdin::
{"cmd": "start", "language": "en", "monitors": [], # resident: fresh capture
- "windows": [], "keep_area": false} # (keep the released area)
+ "windows": [], "handles": [], # (handles: hwnds beside the
+ "keep_area": false} # window rects; keep the area)
{"cmd": "quit"} # release the runtime
{"cmd": "layout", "monitors": [...], # mss monitors and the
- "windows": [[l, t, w, h], ...]} # snap targets, top first
+ "windows": [[l, t, w, h], ...], "handles": [...]} # snap targets, top first
{"cmd": "cancel"} # e.g. a global Esc
Stdin EOF (the parent died) cancels as well.
diff --git a/dodaios/appshot/picker/elements.py b/dodaios/appshot/picker/elements.py
new file mode 100644
index 0000000000..99318d1497
--- /dev/null
+++ b/dodaios/appshot/picker/elements.py
@@ -0,0 +1,184 @@
+"""Read the parts of a window — panels, lists, fields, buttons — for snapping.
+
+Runs ONLY inside ``python -m dodaios.appshot.picker`` (PySide6, AP-26).
+
+Hovering a window lifts the whole window out of the dim. To offer the parts
+inside it too, the picker asks the OS accessibility tree which elements the
+window holds and where they are: on Windows UI Automation
+(``FindAllBuildCache`` with the bounding rectangle cached, one cross-process
+call per window, typically 10-200 ms). Other platforms report nothing, so
+the picker keeps snapping to whole windows there.
+
+The walk runs on a worker thread so the overlay never waits for it; the
+window under the pointer is read first, each window at most once per pick,
+and results arrive as a Qt signal. Rects are in capture space (physical
+pixels on Windows), the same space as the window rects from the main
+process, so the picker maps both the same way.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+from collections.abc import Callable
+
+from PySide6.QtCore import QObject, Signal
+
+#: Elements read per window at most: enough for any real layout, and a hard
+#: stop for pages with tens of thousands of nodes.
+MAX_PARTS = 3000
+#: How long one window may keep UI Automation busy (ms) before it gives up.
+UIA_TIMEOUT_MS = 1000
+
+Scan = Callable[[int], list[list[int]]]
+
+
+class ElementScanner(QObject):
+ """Reads windows' parts on a worker thread; ``found(handle, rects)`` reports them."""
+
+ found = Signal(object, object)
+
+ def __init__(self, scan: Callable[[], Scan | None] | None = None) -> None:
+ super().__init__()
+ #: Builds the scan function ON the worker thread (COM lives there).
+ self._make_scan = scan or uia_scan
+ self._lock = threading.Condition()
+ self._queue: list[int] = []
+ self._results: dict[int, list[list[int]]] = {}
+ self._session = 0
+ self._thread: threading.Thread | None = None
+ self._stopped = False
+ #: The platform cannot read parts: requests are dropped at once.
+ self._unavailable = False
+
+ def reset(self) -> None:
+ """A new pick: forget what was read, the windows may have changed."""
+ with self._lock:
+ self._queue.clear()
+ self._results.clear()
+ self._session += 1
+
+ def request(self, handle: int) -> None:
+ """Read ``handle``'s parts next (a pointer moved onto it)."""
+ if not handle:
+ return
+ with self._lock:
+ if self._unavailable:
+ return
+ cached = self._results.get(handle)
+ if cached is None:
+ if handle in self._queue:
+ self._queue.remove(handle)
+ self._queue.insert(0, handle)
+ self._start()
+ self._lock.notify()
+ if cached is not None:
+ self.found.emit(handle, cached)
+
+ def stop(self) -> None:
+ with self._lock:
+ self._stopped = True
+ self._queue.clear()
+ self._lock.notify()
+
+ def _start(self) -> None:
+ if self._thread is None:
+ self._thread = threading.Thread(
+ target=self._run, name="appshot-picker-parts", daemon=True
+ )
+ self._thread.start()
+
+ def _run(self) -> None:
+ try:
+ scan = self._make_scan()
+ except Exception: # noqa: BLE001 - no reader: the picker snaps to whole windows
+ scan = None
+ if scan is None:
+ with self._lock:
+ self._unavailable = True
+ self._queue.clear()
+ return
+ while True:
+ with self._lock:
+ while not self._queue and not self._stopped:
+ self._lock.wait()
+ if self._stopped:
+ return
+ handle = self._queue.pop(0)
+ session = self._session
+ try:
+ rects = scan(handle)
+ except Exception: # noqa: BLE001 - an unreadable window keeps whole-window snapping
+ rects = []
+ with self._lock:
+ if session != self._session or self._stopped:
+ continue
+ self._results[handle] = rects
+ self.found.emit(handle, rects)
+
+
+def uia_scan() -> Scan | None:
+ """A UI Automation reader for this thread; ``None`` off Windows or without it."""
+ if sys.platform != "win32":
+ return None
+ try:
+ import comtypes # noqa: PLC0415
+
+ try:
+ comtypes.CoInitializeEx(comtypes.COINIT_MULTITHREADED)
+ except OSError: # this thread already has COM: synchronous calls work in either
+ pass
+ try:
+ from comtypes.gen import UIAutomationClient as uia_api # noqa: PLC0415
+ except ImportError: # first use on this machine: generate the UIA wrappers
+ import comtypes.client # noqa: PLC0415
+
+ comtypes.client.GetModule("UIAutomationCore.dll")
+ from comtypes.gen import UIAutomationClient as uia_api # noqa: PLC0415
+ uia = comtypes.CoCreateInstance(
+ uia_api.CUIAutomation8._reg_clsid_,
+ interface=uia_api.IUIAutomation2,
+ clsctx=comtypes.CLSCTX_INPROC_SERVER,
+ )
+ uia.TransactionTimeout = UIA_TIMEOUT_MS
+ uia.ConnectionTimeout = UIA_TIMEOUT_MS
+ kinds = [
+ getattr(uia_api, f"UIA_{name}ControlTypeId")
+ for name in (
+ "Button", "ComboBox", "Custom", "DataGrid", "DataItem", "Document",
+ "Edit", "Group", "Header", "Image", "List", "ListItem", "Menu",
+ "MenuBar", "MenuItem", "Pane", "SplitButton", "StatusBar", "Tab",
+ "TabItem", "Table", "ToolBar", "Tree", "TreeItem", "Window",
+ )
+ ]
+ # Text runs, links, scroll bars and separators are left out: too
+ # small or too many to be a part anyone means to take.
+ wanted = uia.CreateAndCondition(
+ uia.CreateOrConditionFromArray(
+ [uia.CreatePropertyCondition(uia_api.UIA_ControlTypePropertyId, k) for k in kinds]
+ ),
+ uia.CreatePropertyCondition(uia_api.UIA_IsOffscreenPropertyId, False),
+ )
+ cache = uia.CreateCacheRequest()
+ cache.AddProperty(uia_api.UIA_BoundingRectanglePropertyId)
+ cache.AutomationElementMode = uia_api.AutomationElementMode_None
+ descendants = uia_api.TreeScope_Descendants
+ except Exception as exc: # noqa: BLE001 - no UI Automation: whole windows only
+ sys.stderr.write(f"appshot-picker: window parts unavailable ({exc!r}).\n")
+ return None
+
+ def scan(handle: int) -> list[list[int]]:
+ root = uia.ElementFromHandle(handle)
+ found = root.FindAllBuildCache(descendants, wanted, cache)
+ rects: list[list[int]] = []
+ for index in range(min(int(found.Length), MAX_PARTS)):
+ box = found.GetElement(index).CachedBoundingRectangle
+ width, height = box.right - box.left, box.bottom - box.top
+ if width > 0 and height > 0:
+ rects.append([int(box.left), int(box.top), int(width), int(height)])
+ return rects
+
+ return scan
+
+
+__all__ = ["MAX_PARTS", "ElementScanner", "uia_scan"]
diff --git a/dodaios/appshot/picker/markup_model.py b/dodaios/appshot/picker/markup_model.py
index fc8ff7d843..2962550bd0 100644
--- a/dodaios/appshot/picker/markup_model.py
+++ b/dodaios/appshot/picker/markup_model.py
@@ -580,6 +580,71 @@ def clip_to(box: Box, sel: Box) -> Box | None:
return (x0, y0, x1 - x0, y1 - y0)
+# --------------------------------------------------------------------------
+# Snapping to the parts of a window
+# --------------------------------------------------------------------------
+
+#: Parts of a window smaller than this (logical px, either side) are no
+#: snap targets: icons and single words would make the pointer jumpy.
+MIN_PART_PX = 16.0
+
+
+def window_parts(window: Box, boxes: list[Box], min_px: float = MIN_PART_PX) -> list[Box]:
+ """A window's parts (panels, lists, fields, buttons), cut to the window.
+
+ Slivers, copies and parts that are the window itself are dropped; what is
+ left is what hovering may lift out of the dim instead of the whole window.
+ """
+ out: list[Box] = []
+ seen: set[tuple[int, int, int, int]] = set()
+ whole = tuple(round(v) for v in window)
+ for box in boxes:
+ clipped = clip_to(box, window)
+ if clipped is None or clipped[2] < min_px or clipped[3] < min_px:
+ continue
+ key = (round(clipped[0]), round(clipped[1]), round(clipped[2]), round(clipped[3]))
+ if key in seen or key == whole:
+ continue
+ seen.add(key)
+ out.append(clipped)
+ return out
+
+
+#: Two nested parts this close on every edge (logical px, or this share of
+#: the larger side) count as one: a wheel step must visibly change the area.
+NEAR_PX = 12.0
+NEAR_SHARE = 0.05
+
+
+def _nearly_same(a: Box, b: Box) -> bool:
+ reach = max(NEAR_PX, NEAR_SHARE * max(a[2], a[3], b[2], b[3]))
+ edges = (
+ (a[0], b[0]),
+ (a[1], b[1]),
+ (a[0] + a[2], b[0] + b[2]),
+ (a[1] + a[3], b[1] + b[3]),
+ )
+ return all(abs(x - y) <= reach for x, y in edges)
+
+
+def snap_candidates(point: Point, window: Box, parts: list[Box]) -> list[Box]:
+ """What a click at ``point`` may take: the parts under it, smallest first,
+ then the whole window. The mouse wheel steps along this list.
+
+ Nested parts that are nearly the same box (a pane and its content area,
+ a field and its frame) collapse into the larger one.
+ """
+ under = [box for box in parts if _inside(point, box, 0.0)]
+ under.sort(key=lambda box: box[2] * box[3])
+ out: list[Box] = []
+ for box in [*under, window]:
+ if out and _nearly_same(out[-1], box):
+ out[-1] = box
+ else:
+ out.append(box)
+ return out
+
+
def hide_fractions(shapes: list[Shape], sel: Box) -> list[dict[str, object]]:
"""Pixelate/blur patches as fractions of the selection, for the main process."""
out: list[dict[str, object]] = []
@@ -660,6 +725,7 @@ __all__ = [
"HANDLES",
"HIGHLIGHT",
"LINE",
+ "MIN_PART_PX",
"MOVE",
"PALETTE",
"PEN",
@@ -699,9 +765,11 @@ __all__ = [
"segment_middle",
"segment_path",
"shape_at",
+ "snap_candidates",
"text_size",
"toolbar_home",
"toolbar_origin",
"toolbar_spot",
"translated",
+ "window_parts",
]
diff --git a/dodaios/appshot/picker/markup_window.py b/dodaios/appshot/picker/markup_window.py
index 2a7213ddb8..76b1f6aa8f 100644
--- a/dodaios/appshot/picker/markup_window.py
+++ b/dodaios/appshot/picker/markup_window.py
@@ -6,6 +6,11 @@ Runs ONLY inside ``python -m dodaios.appshot.picker`` (PySide6, AP-26).
screen under the pointer, and the **area** tool chosen. Dragging an area,
or clicking a window, takes the appshot the moment the mouse is released:
there is no second step to confirm it.
+- Hovering offers the parts of the window under the pointer too: a panel,
+ a list, a field, a button (:mod:`dodaios.appshot.picker.elements`). The
+ smallest part under the pointer lights up; the mouse wheel steps out to
+ the larger parts around it and the whole window, and back in. A click
+ takes what is lit.
- Any drawing tool can be picked first (its button, its letter, Tab or the
middle mouse button) and used anywhere on the frozen screen. Back on the
area tool, the area drag then takes the appshot with every marking in it.
@@ -25,12 +30,13 @@ painting and the toolbar in :mod:`dodaios.appshot.picker.annotate`.
from __future__ import annotations
from PySide6.QtCore import QPointF, QRectF, Qt
-from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPainterPath, QPen
+from PySide6.QtGui import QColor, QCursor, QGuiApplication, QPainter, QPainterPath, QPen
from dodaios.appshot import picker as wire
from dodaios.appshot.picker import annotate
from dodaios.appshot.picker import markup_model as mm
-from dodaios.appshot.picker.renderer import EDGE_GAP, HALO, INK, _SelectWindow
+from dodaios.appshot.picker.renderer import EDGE_GAP, HALO, INK, _screen_info, _SelectWindow
+from dodaios.appshot.region import snap_targets_on_screen
#: Cursor per kept-area resize handle.
_HANDLE_CURSORS = {
@@ -156,6 +162,12 @@ class MarkupWindow(_SelectWindow):
self._toolbar: annotate.Toolbar | None = None
#: Where the marking being drawn or dragged was painted last.
self._painted_live: QRectF | None = None
+ #: The parts of each snap window (by handle), in logical pixels.
+ self._parts: dict[int, list[QRectF]] = {}
+ #: How far the mouse wheel stepped out from the smallest part under
+ #: the pointer, and which part that was (a new one starts at 0 again).
+ self._depth = 0
+ self._depth_base: QRectF | None = None
def release_capture(self) -> None:
"""Drop pixels explicitly, including the preview's bound-method cycle."""
@@ -183,6 +195,70 @@ class MarkupWindow(_SelectWindow):
value = getattr(state, name)
setattr(self._markup, name, dict(value) if isinstance(value, dict) else value)
+ # -- the parts of the window under the pointer ----------------------------
+ def ask_parts_under_cursor(self) -> None:
+ point = QPointF(self.mapFromGlobal(QCursor.pos()))
+ if self.rect().contains(point.toPoint()):
+ self._ask_parts(point)
+
+ def _ask_parts(self, point: QPointF) -> None:
+ index = self._window_at(point)
+ if index is not None:
+ self._owner.want_parts(self._snap_handles[index])
+
+ def add_parts(self, handle: int, rects: list) -> None:
+ """Window ``handle``'s parts (capture space) arrived: keep the ones on this screen."""
+ indices = [i for i, h in enumerate(self._snap_handles) if h == handle]
+ if not indices:
+ return
+ boxes = [
+ box
+ for _i, box in snap_targets_on_screen(
+ _screen_info(self.screen_ref),
+ (self.width(), self.height()),
+ self._monitors,
+ rects,
+ min_px=mm.MIN_PART_PX,
+ )
+ ]
+ window = self._snaps[indices[0]]
+ parts = mm.window_parts(_box(window), boxes)
+ self._parts[handle] = [QRectF(*box) for box in parts]
+ if self._pointer is not None and self._choosing():
+ self._follow_parts(self._pointer)
+ self._repaint_changes()
+
+ def _window_at(self, point: QPointF) -> int | None:
+ """The top-most snap window under ``point``."""
+ for index, rect in enumerate(self._snaps):
+ if rect.contains(point):
+ return index
+ return None
+
+ def _candidates(self, point: QPointF) -> list[QRectF]:
+ """What a click at ``point`` may take: parts smallest first, then the window."""
+ index = self._window_at(point)
+ if index is None:
+ return []
+ window = self._snaps[index]
+ parts = self._parts.get(self._snap_handles[index], [])
+ boxes = mm.snap_candidates((point.x(), point.y()), _box(window), [_box(p) for p in parts])
+ return [QRectF(*box) for box in boxes]
+
+ def _follow_parts(self, point: QPointF) -> None:
+ """A new part under the pointer starts the wheel over at the smallest one."""
+ candidates = self._candidates(point)
+ smallest = candidates[0] if candidates else None
+ if smallest != self._depth_base:
+ self._depth_base = smallest
+ self._depth = 0
+
+ def _snap_at(self, point: QPointF) -> QRectF | None:
+ candidates = self._candidates(point)
+ if not candidates:
+ return None
+ return candidates[min(self._depth, len(candidates) - 1)]
+
def _ensure_toolbar(self) -> annotate.Toolbar:
if self._toolbar is None:
bar = annotate.Toolbar(
@@ -758,6 +834,9 @@ class MarkupWindow(_SelectWindow):
self._touch_live()
return
self._pointer = p
+ if self._choosing():
+ self._ask_parts(p)
+ self._follow_parts(p)
self._repaint_changes()
self._update_cursor(point)
@@ -814,8 +893,17 @@ class MarkupWindow(_SelectWindow):
if self._inert():
return
steps = event.angleDelta().y()
- if steps:
- self._step_width(1 if steps > 0 else -1)
+ if not steps:
+ return
+ if self._choosing() and self._start is None and self._pointer is not None:
+ # Choosing: the wheel steps out to the larger parts and back in.
+ candidates = self._candidates(self._pointer)
+ if candidates:
+ step = 1 if steps > 0 else -1
+ self._depth = max(0, min(len(candidates) - 1, self._depth + step))
+ self._repaint_changes()
+ return
+ self._step_width(1 if steps > 0 else -1)
def _pointer_point(self) -> mm.Point | None:
p = self._pointer
diff --git a/dodaios/appshot/picker/renderer.py b/dodaios/appshot/picker/renderer.py
index cfa59584b9..43c4b17917 100644
--- a/dodaios/appshot/picker/renderer.py
+++ b/dodaios/appshot/picker/renderer.py
@@ -35,6 +35,7 @@ from __future__ import annotations
import sys
import threading
from contextlib import suppress
+from typing import TYPE_CHECKING
from PySide6.QtCore import QObject, QPointF, QRectF, Qt, Signal, Slot
from PySide6.QtGui import (
@@ -51,11 +52,14 @@ from PySide6.QtGui import (
from PySide6.QtWidgets import QApplication, QWidget
from dodaios.appshot import picker as wire
+
+if TYPE_CHECKING:
+ from dodaios.appshot.picker.elements import ElementScanner
from dodaios.appshot.region import (
grab_preview,
match_monitor,
selection_fractions,
- snap_rects_on_screen,
+ snap_targets_on_screen,
)
#: A light veil before the drag (the picker is armed). While dragging the
@@ -198,8 +202,11 @@ class _SelectWindow(QWidget):
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.
+ #: Snap targets in this window's logical coordinates, top-most first,
+ #: and the window handle behind each (``0`` = unknown).
self._snaps: list[QRectF] = []
+ self._snap_handles: list[int] = []
+ self._monitors: list[dict] = []
self._monitor: dict | None = None
self._font = number_font()
self._metrics = QFontMetricsF(self._font)
@@ -222,15 +229,29 @@ class _SelectWindow(QWidget):
def adopt(self, other: _SelectWindow) -> None:
"""Carry over choices made on ``other`` (the screen the pointer left)."""
+ def ask_parts_under_cursor(self) -> None:
+ """Snapping to the parts of a window belongs to the appshot window."""
+
+ def add_parts(self, handle: int, rects: list) -> None:
+ """The parts of window ``handle`` arrived; this window takes whole windows."""
+
# -- data from the main process ------------------------------------------
- def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:
+ def set_layout(
+ self, monitors: list[dict], windows: list[list[int]], handles: list | None = None
+ ) -> None:
"""Map capture-space window rects onto this screen's logical pixels."""
info = _screen_info(self.screen_ref)
+ self._monitors = monitors
self._monitor = match_monitor(info, monitors)
- rects = snap_rects_on_screen(
+ targets = snap_targets_on_screen(
info, (self.width(), self.height()), monitors, windows, min_px=_MIN_SNAP_PX
)
- self._snaps = [QRectF(*rect) for rect in rects]
+ handles = handles if isinstance(handles, list) else []
+ self._snaps = [QRectF(*rect) for _index, rect in targets]
+ self._snap_handles = [
+ handles[index] if index < len(handles) and isinstance(handles[index], int) else 0
+ for index, _rect in targets
+ ]
self.update()
# -- input ---------------------------------------------------------------
@@ -462,6 +483,10 @@ class Picker(QObject):
self.keep_area = False
self._marking_sent = False
self._done = False
+ #: Reads the parts of the window under the pointer (Windows); made on
+ #: the first pick, then kept warm with the rest of the runtime.
+ self._parts: ElementScanner | None = None
+ self._parts_asked: set[int] = set()
def start(self) -> None:
if self._started:
@@ -469,6 +494,9 @@ class Picker(QObject):
self._started = True
self._done = False
self._marking_sent = False
+ self._parts_asked = set()
+ if self._parts is not None:
+ self._parts.reset()
screens = QGuiApplication.screens()
# Freeze every screen BEFORE any overlay window exists.
frozen = {id(s): self._grab(s) for s in screens}
@@ -499,9 +527,35 @@ class Picker(QObject):
def _grab(screen) -> QPixmap | None:
return grab_preview(screen)
- def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:
+ def set_layout(
+ self, monitors: list[dict], windows: list[list[int]], handles: list | None = None
+ ) -> None:
for win in self._windows:
- win.set_layout(monitors, windows)
+ win.set_layout(monitors, windows, handles)
+ if self._focused is not None:
+ # The window under the pointer is the likeliest target: read it now.
+ self._focused.ask_parts_under_cursor()
+
+ def want_parts(self, handle: int) -> None:
+ """The pointer is over window ``handle``: read its parts, once per pick."""
+ if not handle or handle in self._parts_asked or not self._started:
+ return
+ self._parts_asked.add(handle)
+ if self._parts is None:
+ if sys.platform != "win32":
+ return
+ from dodaios.appshot.picker.elements import ElementScanner # noqa: PLC0415
+
+ self._parts = ElementScanner()
+ self._parts.found.connect(self._parts_found)
+ self._parts.request(handle)
+
+ @Slot(object, object)
+ def _parts_found(self, handle: object, rects: object) -> None:
+ if not self._started or not isinstance(handle, int) or not isinstance(rects, list):
+ return
+ for win in self._windows:
+ win.add_parts(handle, rects)
def focus_on(self, window: _SelectWindow) -> None:
"""The pointer moved onto ``window``: only that screen shows the numbers."""
@@ -571,6 +625,8 @@ class Picker(QObject):
self._focused = None
self.marking = None
self._started = False
+ if self._parts is not None:
+ self._parts.reset()
if info is None or frac is None:
_emit({"event": wire.EVENT_SELECTION, "cancelled": True})
else:
@@ -596,7 +652,9 @@ class Picker(QObject):
self.language = str(payload.get("language") or "en")
self.keep_area = payload.get("keep_area") is True
self.start()
- self.set_layout(payload.get("monitors", []), payload.get("windows", []))
+ self.set_layout(
+ payload.get("monitors", []), payload.get("windows", []), payload.get("handles")
+ )
elif cmd == wire.CMD_QUIT:
self.on_eof()
elif cmd == wire.CMD_CANCEL and self._started:
@@ -605,12 +663,16 @@ class Picker(QObject):
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)
+ self.set_layout(
+ [m for m in monitors if isinstance(m, dict)], windows, payload.get("handles")
+ )
@Slot()
def on_eof(self) -> None:
if self._started:
self.finish(None, None)
+ if self._parts is not None:
+ self._parts.stop()
self._app.quit()
diff --git a/dodaios/appshot/region.py b/dodaios/appshot/region.py
index 67efc3920b..0744c686c1 100644
--- a/dodaios/appshot/region.py
+++ b/dodaios/appshot/region.py
@@ -183,6 +183,25 @@ def snap_rects_on_screen(
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.
"""
+ return [
+ rect
+ for _index, rect in snap_targets_on_screen(screen, size, monitors, windows, min_px=min_px)
+ ]
+
+
+def snap_targets_on_screen(
+ screen: dict,
+ size: tuple[float, float],
+ monitors: list[dict],
+ windows: list[list[int]],
+ *,
+ min_px: float,
+) -> list[tuple[int, FRect]]:
+ """:func:`snap_rects_on_screen`, each rect with its index in ``windows``.
+
+ The index ties a rect that survived the clipping back to what came with
+ it (the window handle its elements are read from).
+ """
monitor = match_monitor(screen, monitors)
if monitor is None:
return []
@@ -191,16 +210,19 @@ def snap_rects_on_screen(
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:
+ out: list[tuple[int, FRect]] = []
+ for index, rect in enumerate(windows):
if not isinstance(rect, (list, tuple)) or len(rect) != 4:
continue
- left, top, w, h = (float(v) for v in rect)
+ try:
+ left, top, w, h = (float(v) for v in rect)
+ except (TypeError, ValueError): # a garbled rect is no snap target
+ continue
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))
+ out.append((index, (x0, y0, x1 - x0, y1 - y0)))
return out
@@ -279,11 +301,15 @@ def snap_layout() -> dict[str, Any]:
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.
+ ``handles`` runs alongside ``windows`` (``0`` = unknown): the picker reads
+ the parts of the window under the pointer through them, to snap to a
+ panel, list or button instead of the whole window.
"""
from dodaios.screen_context.ports import make_display_enumerator # noqa: PLC0415
monitors = make_display_enumerator().monitors()
windows: list[list[int]] = []
+ handles: list[int] = []
try:
from dodaios.platform import window_state as ws # noqa: PLC0415
from dodaios.screen_context.ports import _input_space # noqa: PLC0415
@@ -294,10 +320,12 @@ def snap_layout() -> dict[str, Any]:
continue
rect = ws.window_frame_rect(win) or ws.window_rect(win)
if rect and rect[2] > 0 and rect[3] > 0:
+ handle = getattr(win, "handle", None)
windows.append([int(v) for v in rect])
+ handles.append(handle if isinstance(handle, int) else 0)
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}
+ return {"monitors": [dict(m) for m in monitors], "windows": windows, "handles": handles}
def _spawn(language: str = "en", *, resident: bool = False) -> subprocess.Popen[str]:
@@ -514,4 +542,5 @@ __all__ = [
"selection_to_bbox",
"snap_layout",
"snap_rects_on_screen",
+ "snap_targets_on_screen",
]
diff --git a/tests/unit/appshot/test_picker_standby.py b/tests/unit/appshot/test_picker_standby.py
index 1411767322..09e3a9e8b0 100644
--- a/tests/unit/appshot/test_picker_standby.py
+++ b/tests/unit/appshot/test_picker_standby.py
@@ -33,7 +33,7 @@ def test_resident_finish_releases_every_screen_without_quitting(monkeypatch):
processEvents=lambda: calls.append("flush"), quit=lambda: calls.append("quit")
),
_windows=[window], _done=False, _resident=True, _started=True,
- _focused=window, marking=window,
+ _focused=window, marking=window, _parts=None,
)
monkeypatch.setattr(renderer, "_emit", lambda payload: calls.append(payload))
renderer.Picker.finish(owner, None, None)
diff --git a/tests/unit/appshot/test_picker_window_parts.py b/tests/unit/appshot/test_picker_window_parts.py
new file mode 100644
index 0000000000..a629b7d331
--- /dev/null
+++ b/tests/unit/appshot/test_picker_window_parts.py
@@ -0,0 +1,284 @@
+"""Hovering in the area picker offers the parts of a window, not only the window.
+
+The geometry is plain data; the scanner runs on its worker thread with a
+fake reader (no UI Automation needed); the window is the real Qt window on
+the offscreen platform. Qt parts auto-skip without PySide6.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import threading
+
+import pytest
+
+from dodaios.appshot import region
+from dodaios.appshot.picker import markup_model as mm
+
+needs_qt = pytest.mark.skipif(
+ importlib.util.find_spec("PySide6") is None,
+ reason="PySide6 not installed (the area picker is a [desktop] extra)",
+)
+
+W, H = 1600, 900
+WINDOW = [100, 100, 1000, 700]
+#: A sidebar, a list item in it, a content pane and a pane's inner area that
+#: is nearly the pane itself.
+PARTS = [
+ [100, 100, 250, 700],
+ [110, 200, 230, 40],
+ [350, 100, 750, 700],
+ [356, 104, 740, 690],
+ [0, 0, 5, 5],
+]
+MONITORS = [
+ {"left": 0, "top": 0, "width": W, "height": H},
+ {"left": 0, "top": 0, "width": W, "height": H},
+]
+
+
+# ----------------------------------------------------------------- geometry
+
+
+def test_window_parts_are_cut_to_the_window_without_copies_or_slivers() -> None:
+ window = (100.0, 100.0, 1000.0, 700.0)
+ parts = mm.window_parts(
+ window,
+ [
+ (50.0, 150.0, 200.0, 100.0), # sticks out on the left
+ (50.0, 150.0, 200.0, 100.0), # the same again
+ (100.0, 100.0, 1000.0, 700.0), # the window itself
+ (300.0, 300.0, 10.0, 10.0), # too small
+ (2000.0, 0.0, 100.0, 100.0), # outside
+ ],
+ )
+ assert parts == [(100.0, 150.0, 150.0, 100.0)]
+
+
+def test_candidates_run_from_the_smallest_part_out_to_the_window() -> None:
+ window = (100.0, 100.0, 1000.0, 700.0)
+ parts = [tuple(float(v) for v in p) for p in PARTS[:4]]
+ assert mm.snap_candidates((120, 210), window, parts) == [
+ (110.0, 200.0, 230.0, 40.0),
+ (100.0, 100.0, 250.0, 700.0),
+ window,
+ ]
+ # The pane's inner area is nearly the pane: one step, the larger one.
+ assert mm.snap_candidates((600, 400), window, parts) == [(350.0, 100.0, 750.0, 700.0), window]
+ assert mm.snap_candidates((5, 5), window, parts) == [window]
+
+
+def test_the_layout_carries_a_handle_beside_each_window(monkeypatch) -> None:
+ from dodaios.platform import window_state as ws
+ from dodaios.screen_context import ports
+
+ class Win:
+ def __init__(self, handle, minimized=False):
+ self.handle = handle
+ self.minimized = minimized
+
+ class Displays:
+ def monitors(self):
+ return MONITORS
+
+ monkeypatch.setattr(ports, "make_display_enumerator", lambda: Displays())
+ monkeypatch.setattr(ws, "list_windows", lambda: [Win(11), Win(22, minimized=True), Win(None)])
+ monkeypatch.setattr(
+ ws, "window_frame_rect", lambda win: (0, 0, 100 + 10 * bool(win.handle), 50)
+ )
+ monkeypatch.setattr(region, "_is_cloaked", lambda _h: False)
+ layout = region.snap_layout()
+ assert layout["windows"] == [[0, 0, 110, 50], [0, 0, 100, 50]]
+ assert layout["handles"] == [11, 0]
+
+
+def test_snap_targets_keep_their_index_when_others_drop_out() -> None:
+ screen = {"x": 0.0, "y": 0.0, "w": float(W), "h": float(H), "dpr": 1.0}
+ targets = region.snap_targets_on_screen(
+ screen, (W, H), MONITORS, [[0, 0, 5, 5], WINDOW, "junk"], min_px=24
+ )
+ assert targets == [(1, (100.0, 100.0, 1000.0, 700.0))]
+
+
+# ------------------------------------------------------------------ scanner
+
+
[email protected](scope="module")
+def qt():
+ if importlib.util.find_spec("PySide6") is None:
+ pytest.skip("PySide6 not installed")
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtWidgets import QApplication
+
+ return QApplication.instance() or QApplication([])
+
+
+def _wait_for(qt, condition, timeout_s: float = 3.0) -> None:
+ import time
+
+ deadline = time.monotonic() + timeout_s
+ while not condition() and time.monotonic() < deadline:
+ qt.processEvents()
+ time.sleep(0.01)
+ assert condition()
+
+
+@needs_qt
+def test_the_scanner_reads_each_window_once_per_pick_on_its_own_thread(qt) -> None:
+ from dodaios.appshot.picker.elements import ElementScanner
+
+ calls: list[tuple[int, str]] = []
+
+ def make_scan():
+ def scan(handle: int) -> list[list[int]]:
+ calls.append((handle, threading.current_thread().name))
+ return [[handle, 0, 10, 10]]
+
+ return scan
+
+ scanner = ElementScanner(make_scan)
+ found: list[tuple] = []
+ scanner.found.connect(lambda handle, rects: found.append((handle, rects)))
+ scanner.request(7)
+ _wait_for(qt, lambda: found)
+ assert found == [(7, [[7, 0, 10, 10]])]
+ assert calls[0][1] == "appshot-picker-parts", "never on the Qt thread"
+ scanner.request(7)
+ _wait_for(qt, lambda: len(found) == 2)
+ assert len(calls) == 1, "a window is read once per pick"
+ scanner.reset()
+ scanner.request(7)
+ _wait_for(qt, lambda: len(found) == 3)
+ assert len(calls) == 2, "a new pick reads it again"
+ scanner.stop()
+
+
+@needs_qt
+def test_without_a_reader_the_scanner_stays_quiet(qt) -> None:
+ from dodaios.appshot.picker.elements import ElementScanner
+
+ scanner = ElementScanner(lambda: None)
+ found: list = []
+ scanner.found.connect(lambda *args: found.append(args))
+ scanner.request(5)
+ _wait_for(qt, lambda: scanner._unavailable)
+ scanner.request(6)
+ qt.processEvents()
+ assert found == [] and scanner._queue == []
+
+
+# ------------------------------------------------------------------- window
+
+
+def picker(qt, monkeypatch):
+ from PySide6.QtGui import QColor, QGuiApplication, QPixmap
+
+ from dodaios.appshot.picker import markup_window, renderer
+
+ events: list[dict] = []
+ asked: list[int] = []
+ monkeypatch.setattr(renderer, "_emit", events.append)
+ info = {"x": 0.0, "y": 0.0, "w": float(W), "h": float(H), "dpr": 1.0}
+ monkeypatch.setattr(renderer, "_screen_info", lambda _s: info)
+ monkeypatch.setattr(markup_window, "_screen_info", lambda _s: info)
+ owner = renderer.Picker(qt, language="en", resident=True)
+ monkeypatch.setattr(owner, "want_parts", asked.append)
+ frozen = QPixmap(W, H)
+ frozen.fill(QColor(40, 90, 160))
+ win = markup_window.MarkupWindow(QGuiApplication.primaryScreen(), frozen, owner)
+ win.setGeometry(0, 0, W, H)
+ owner._windows.append(win)
+ owner._focused = win
+ owner._started = True
+ win.show()
+ win.arm()
+ win.set_layout(MONITORS, [WINDOW], [4242])
+ yield owner, win, events, asked
+ if not owner._done:
+ owner.finish(None, None)
+
+
+def _move(win, x: float, y: float) -> None:
+ from PySide6.QtCore import QEvent, QPointF, Qt
+ from PySide6.QtGui import QMouseEvent
+
+ win.mouseMoveEvent(
+ QMouseEvent(
+ QEvent.Type.MouseMove, QPointF(x, y), QPointF(x, y), Qt.MouseButton.NoButton,
+ Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier,
+ )
+ )
+
+
+def _click(win, x: float, y: float) -> None:
+ from PySide6.QtCore import QEvent, QPointF, Qt
+ from PySide6.QtGui import QMouseEvent
+
+ left = Qt.MouseButton.LeftButton
+ for kind, held, handler in (
+ (QEvent.Type.MouseButtonPress, left, win.mousePressEvent),
+ (QEvent.Type.MouseButtonRelease, Qt.MouseButton.NoButton, win.mouseReleaseEvent),
+ ):
+ handler(QMouseEvent(kind, QPointF(x, y), QPointF(x, y), left, held,
+ Qt.KeyboardModifier.NoModifier))
+
+
+def _wheel(win, x: float, y: float, up: bool) -> None:
+ from PySide6.QtCore import QPoint, QPointF, Qt
+ from PySide6.QtGui import QWheelEvent
+
+ win.wheelEvent(
+ QWheelEvent(
+ QPointF(x, y), QPointF(x, y), QPoint(0, 0), QPoint(0, 120 if up else -120),
+ Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier,
+ Qt.ScrollPhase.NoScrollPhase, False,
+ )
+ )
+
+
+@needs_qt
+def test_hovering_asks_for_the_parts_and_lights_the_smallest_one(picker) -> None:
+ owner, win, events, asked = picker
+ _move(win, 120, 210)
+ assert asked and asked[-1] == 4242, "the window under the pointer is read"
+ assert win._hole() == win._snaps[0], "until its parts arrive, the whole window lights up"
+ win.add_parts(4242, PARTS)
+ assert (win._hole().x(), win._hole().y(), win._hole().width(), win._hole().height()) == (
+ 110, 200, 230, 40,
+ )
+
+
+@needs_qt
+def test_the_wheel_steps_out_and_a_click_takes_what_is_lit(picker) -> None:
+ owner, win, events, asked = picker
+ win.add_parts(4242, PARTS)
+ _move(win, 120, 210)
+ _wheel(win, 120, 210, up=True)
+ assert win._hole().width() == 250, "one step out: the sidebar"
+ _wheel(win, 120, 210, up=True)
+ _wheel(win, 120, 210, up=True)
+ assert win._hole().width() == 1000, "it stops at the whole window"
+ _wheel(win, 120, 210, up=False)
+ _click(win, 120, 210)
+ selection = next(e for e in events if e.get("event") == "selection")
+ assert selection["rect"] == pytest.approx([100 / W, 100 / H, 250 / W, 700 / H])
+
+
+@needs_qt
+def test_a_new_part_under_the_pointer_starts_at_the_smallest_again(picker) -> None:
+ owner, win, events, asked = picker
+ win.add_parts(4242, PARTS)
+ _move(win, 120, 210)
+ _wheel(win, 120, 210, up=True)
+ _move(win, 600, 400)
+ assert win._hole().width() == 750
+
+
+@needs_qt
+def test_parts_of_another_window_are_ignored(picker) -> None:
+ owner, win, events, asked = picker
+ win.add_parts(9999, PARTS)
+ _move(win, 120, 210)
+ assert win._hole() == win._snaps[0]