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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(appshot): open the area picker with its toolbar up and take the area on release (#765)
Ruben Lütkebbcde05f176e
diff --git a/docs/appshots.md b/docs/appshots.mdindex fda912fb97..4d8cef0406 100644--- a/docs/appshots.md+++ b/docs/appshots.md@@ -10,7 +10,7 @@ text — and hands it to the conversation as context. Settings live under| Trigger | What happens ||---|---|| **Window shortcut** — both Alt keys at once by default (both Option keys on a Mac) | The front window is captured and delivered per **Appshot destination**. |-| **Area shortcut** — both Shift keys at once by default | Every screen dims; drag a rectangle, mark it up right there with the toolbar that docks under it, and Enter captures exactly that part with your markings and delivers it the same way. Esc or a right-click cancels and sends nothing. |+| **Area shortcut** — both Shift keys at once by default | Every screen dims with the marking toolbar already at the top. Drag a rectangle (or click a window) and letting go captures exactly that part at once, with whatever you marked on the screen before, and delivers it the same way. Esc or a right-click cancels and sends nothing. || **Voice or chat** — "take an appshot", "mach einen Appshot", "haz un appshot" | The turn that asked captures the front window and answers with it. Only an explicit request for the whole screen ("an appshot of my full screen") captures the monitor the cursor is on instead — the live model's `take_appshot` passes `scope: "screen"` for it. || **Try it** buttons on the Appshots page | "Take appshot in 3 s" waits three seconds so you can switch windows; "Select area" opens the area picker at once. Both then behave like the shortcuts. |@@ -65,23 +65,40 @@ blur previews, markings and windows while keeping Qt loaded. The picker provides- a drag clears the dim and tints the selected area a translucent greywith one thin border.-### Marking up before the shot+### Marking up, before or after choosing the area-Letting go of the drag (or clicking a window) does not take the shot yet. The-area stays on screen with eight resize handles (they are the crop), its size-in pixels above its corner, and a toolbar docked under it (above it, or-inside it, when there is no room). Everything drawn here is what the-assistant sees, so it can be pointed at directly. The tools, keys and looks-are the same as in the full editor below:+The marking toolbar is up the moment the screens dim, centred at the top of+the screen under the pointer (it follows the pointer to another screen until+something is marked there). The **area** tool is in hand: drag a rectangle,+or click a window, and letting go takes the appshot at once. There is no+second step to confirm it.++To point at something, pick a drawing tool first (its button, its letter,+Tab or the middle mouse button), draw anywhere on the frozen screen, then go+back to the area tool (K, Tab or the middle button) and drag the area: the+appshot carries every marking inside it. Space takes the whole screen with+its markings. With the area tool, a press on a marking moves that marking;+hold Ctrl to start the area right on top of it.++**Adjust before taking** (the frame button next to Copy) switches to the+older flow and is remembered (`[appshot].region_keep_area`): a released area+stays on screen with eight resize handles (they are the crop) and its size+in pixels above its corner; drag inside it with the area tool to move it,+mark it up, then Enter, a double-click in it or the check button takes it.+The toolbar moves under the area when the area would sit under it.++Everything drawn is what the assistant sees, so it can be pointed at+directly. The tools, keys and looks are the same as in the full editor below:| Key | Tool | ||---|---|---|+| K | Area (default) | Drag or click a window; letting go takes the appshot (the editor's crop key) || V | Select and move | Click a marking to pick it, drag to move it, Delete removes it, arrow keys nudge it || R | Rectangle | Shift = square || F | Filled rectangle | Shift = square || E | Ellipse | Shift = circle || L | Line | Shift snaps to 45 degrees |-| A | Arrow (default) | Tapered, classic or two heads; Shift snaps to 45 degrees |+| A | Arrow | Tapered, classic or two heads; Shift snaps to 45 degrees. The first tool Tab goes to || T | Text | Click, type; Enter finishes, Shift+Enter is a new line, Ctrl+V pastes; plain, label or outline look || P | Pixelate / blur | Hides what is under the box || H | Spotlight | Dims everything outside the box |@@ -90,8 +107,8 @@ are the same as in the full editor below:| M | Highlighter | Wide translucent stroke || B | Background | Puts the area on a gradient or solid frame |-Tools with looks (arrow, text, pixelate/blur, background) show them in a-second row under the toolbar. Colours: eight presets. Size: keys 1-5, the+Tools with looks (arrow, text, pixelate/blur, background) show them right+after the tools, in the same row. Colours: eight presets. Size: keys 1-5, thesize button or the mouse wheel (new text and step markers follow it). Ctrl+Z/ Ctrl+Y undo and redo. Every marking shows its points right after it isdrawn (the previous one loses them), and any drawing tool takes a drawn@@ -101,18 +118,22 @@ and one in the middle that bends them into a curve, boxes and strokes one ateach corner, a step marker one on its rim, and text one at each corner —dragging that scales the text, font size and all, from the opposite corner. A colour, size orlook chosen then changes that marking. Double-clicking a text (with V or T)-edits it. Dragging an area handle resizes the area at any time; a press-outside an unmarked area, or a right-click on it, starts a new selection.+edits it. A right-click on a marking removes it. With a kept area, its+handles resize it at any time, and a right-click on nothing drops it so a new+one can be drawn.Finishing:| Key / button | Result ||---|---|-| Enter / check button | Take the appshot with the markings and deliver it |+| Letting go of the area drag, or clicking a window | Take that area with the markings and deliver it |+| Space | Take the whole screen with the markings |+| Enter / check button | Take the kept area (or the whole screen, when none is kept) with the markings |+| Double-click in a kept area | The same as Enter || Ctrl+C / Copy | The same, and the finished picture goes to the clipboard || Ctrl+S / Save | The same, and a PNG goes to `~/Downloads` || Ctrl+E / Editor | The same, and the full appshot editor opens on it |-| Esc / cross | Cancel; nothing is captured |+| Esc / cross / right-click on nothing | Cancel; nothing is captured |The capture itself is unchanged: after the overlay closes, Screen Contextgrabs the area (denylist, redaction and all), and only that finished picture@@ -122,8 +143,10 @@ stretched to the capture's size, then the background frame if one waschosen. The markings never show anything theprivacy filter removed. A marked appshot carries the same note as an editoredit (the markings are the user's), and the corner card's thumbnail shows-them too. While the toolbar is up the global Esc stops cancelling, so Esc can-end a text box without throwing the selection away.+them too. Once something is marked the global Esc stops cancelling, so Esc+can end a text box without throwing the markings away. On Windows the picker+takes the keyboard when it opens, so Space, Tab and the tool letters work+before the first click.The picker reports the rectangle as fractions of the screen it was drawn on;the app maps that back to capture pixels (`dodaios/appshot/region.py`), so@@ -434,6 +457,7 @@ and served with `Cache-Control: no-store`.|---|---|---|| `hotkey` | `"alt+alt"` | Window appshot. `alt+alt` / `shift+shift` / `ctrl+ctrl` = both keys of that pair; any other combo in the shared hotkey syntax; `""` = off || `region_hotkey` | `"shift+shift"` | Area appshot, same syntax. Must differ from `hotkey` (the app refuses one key for both) |+| `region_keep_area` | `false` | `false`: letting go of the area drag takes the appshot at once. `true`: the area stays to be adjusted and marked; Enter or a double-click takes it. The picker's "Adjust before taking" button flips it |Both shortcuts are changed on the Appshots page: **Change** records the nextkey gesture (hold the keys, then let go; Esc cancels), the X turns the@@ -455,7 +479,7 @@ original any-order behaviour.|---|---|---|---|---|| Both-Alt shortcut | `GetAsyncKeyState` (AltGr counts as right Alt) | `CGEventSourceKeyState`, needs the Input Monitoring grant; a silent check (never a prompt) reports the shortcut unavailable and names the grant when it is missing | `XQueryKeymap` via python-xlib | Unavailable, reason shown on the page; voice and the button still work where capture works || Other shortcuts (incl. the area shortcut) | Shared hotkey backends (`dodaios/trigger/backends`) | same | same | same as above |-| Area picker and its marking toolbar | PySide6 overlay; a global Esc also cancels until an area is chosen, because Windows may not hand it keyboard focus until the first click | PySide6 overlay | PySide6 overlay | Unavailable, reason shown on the page; the window appshot still works |+| Area picker and its marking toolbar | PySide6 overlay; it takes the keyboard when it opens, and a global Esc also cancels until something is marked, in case Windows still keeps the keyboard from it | PySide6 overlay | PySide6 overlay | Unavailable, reason shown on the page; the window appshot still works || Burning the markings into the appshot | Pillow, in the main process (`dodaios/appshot/markup.py`) | same | same | same (no display needed) || Flash + thumbnail | PySide6 overlay, excluded from capture | PySide6 overlay | PySide6 overlay | No overlay; the appshot is still taken where capture works || Capture | Screen Context engine | Needs Screen Recording; macOS asks for it at the first appshot you take | X11 | Honest refusal |diff --git a/dodaios/appshot/picker/__init__.py b/dodaios/appshot/picker/__init__.pyindex 6834efe03d..4d0c5a84b1 100644--- a/dodaios/appshot/picker/__init__.py+++ b/dodaios/appshot/picker/__init__.py@@ -1,8 +1,9 @@"""The area picker for region appshots — an isolated PySide6 sidecar.-``python -m dodaios.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+``python -m dodaios.appshot.picker --lang de`` dims every screen with the+marking toolbar already up, lets the user mark the screen and drag one+rectangle (in either order) and prints the result as one JSON line on+stdout, then exits. The main process neverimports PySide6 (AP-26); it talks to this process through:mod:`dodaios.appshot.region`.@@ -16,7 +17,10 @@ stdout::{"event": "standby"} # resident runtime loaded{"event": "ready"} # overlay is up- {"event": "marking"} # area chosen, toolbar up+ {"event": "marking"} # something is marked; the+ # parent drops its global Esc+ {"event": "option", "keep_area": true} # "adjust before taking"+ # flipped; the parent saves it{"event": "selection", "screen": {"x":…, "y":…, # the Qt screen,"w":…, "h":…, "dpr":…}, "rect": [fx, fy, fw, fh], # fractions of it,"action": "done" | "copy" | "save" | "edit", # what the user pressed,@@ -28,7 +32,7 @@ stdout::stdin::{"cmd": "start", "language": "en", "monitors": [], # resident: fresh capture- "windows": []}+ "windows": [], "keep_area": false} # (keep the released area){"cmd": "quit"} # release the runtime{"cmd": "layout", "monitors": [...], # mss monitors and the"windows": [[l, t, w, h], ...]} # snap targets, top first@@ -49,6 +53,7 @@ EVENT_READY = "ready"EVENT_STANDBY = "standby"EVENT_MARKING = "marking"EVENT_SELECTION = "selection"+EVENT_OPTION = "option"#: What finishing the selection asks for besides taking the appshot.ACTION_DONE = "done"ACTION_COPY = "copy"@@ -85,6 +90,7 @@ __all__ = ["CMD_START","CMD_QUIT","EVENT_MARKING",+ "EVENT_OPTION","EVENT_READY","EVENT_STANDBY","EVENT_SELECTION",diff --git a/dodaios/appshot/picker/annotate.py b/dodaios/appshot/picker/annotate.pyindex 2718c09b5e..6d41b6f249 100644--- a/dodaios/appshot/picker/annotate.py+++ b/dodaios/appshot/picker/annotate.py@@ -1,11 +1,11 @@-"""Mark up a chosen area in place with the picker's annotation tools.+"""The picker's annotation tools: painting, the toolbar, the result overlay.-Runs ONLY inside ``python -m dodaios.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, with the same tools,-looks and keys as the full appshot editor. Enter (or the check button) takes-the appshot WITH the markings, so the assistant sees exactly what was pointed-at.+Runs ONLY inside ``python -m dodaios.appshot.picker`` (PySide6, AP-26). The+toolbar is up from the moment the overlay appears, centred at the top of the+screen: the user draws on the frozen frame with the same tools, looks and+keys as the full appshot editor, then drags the area (or the area first, with+"adjust before taking" on). The appshot carries the markings, so the+assistant sees exactly what was pointed at.The rules live in :mod:`dodaios.appshot.picker.markup_model` (plain data);this module paints them like the full editor does, draws the toolbar and its@@ -63,6 +63,8 @@ _SPOTLIGHT_DIM = QColor(0, 0, 0, 140)# Toolbar wording — app chrome, so it follows [ui].language like the card._LABELS: dict[str, dict[str, str]] = {"en": {+ mm.AREA: "Area: drag, or click a window. Space takes the whole screen",+ "keep": "Adjust the area before taking it (Enter takes it)",mm.MOVE: "Select and move",mm.RECT: "Rectangle",mm.FILLED: "Filled rectangle",@@ -97,6 +99,14 @@ _LABELS: dict[str, dict[str, str]] = {"placeholder": "Type text",},"de": {+ mm.AREA: (+ "Bereich: ziehen oder ein Fenster anklicken. " # i18n-allow: product UI string+ "Leertaste nimmt den ganzen Bildschirm" # i18n-allow: product UI string+ ),+ "keep": (+ "Bereich vor der Aufnahme anpassen " # i18n-allow: product UI string+ "(Enter nimmt ihn auf)" # i18n-allow: product UI string+ ),mm.MOVE: "Auswählen und verschieben", # i18n-allow: product UI stringmm.RECT: "Rechteck", # i18n-allow: product UI stringmm.FILLED: "Gefülltes Rechteck", # i18n-allow: product UI string@@ -131,6 +141,14 @@ _LABELS: dict[str, dict[str, str]] = {"placeholder": "Text eingeben", # i18n-allow: product UI string},"es": {+ mm.AREA: (+ "Área: arrastra o haz clic en una ventana. " # i18n-allow: product UI string+ "Espacio captura toda la pantalla" # i18n-allow: product UI string+ ),+ "keep": (+ "Ajustar el área antes de capturarla " # i18n-allow: product UI string+ "(Intro la captura)" # i18n-allow: product UI string+ ),mm.MOVE: "Seleccionar y mover", # i18n-allow: product UI stringmm.RECT: "Rectángulo", # i18n-allow: product UI stringmm.FILLED: "Rectángulo relleno", # i18n-allow: product UI string@@ -165,6 +183,8 @@ _LABELS: dict[str, dict[str, str]] = {"placeholder": "Escribe un texto", # i18n-allow: product UI string},"zh": {+ mm.AREA: "区域:拖动或点击一个窗口。空格键截取整个屏幕", # i18n-allow: product UI string+ "keep": "截取前先调整区域(回车截取)", # i18n-allow: product UI stringmm.MOVE: "选择并移动", # i18n-allow: product UI stringmm.RECT: "矩形", # i18n-allow: product UI stringmm.FILLED: "实心矩形", # i18n-allow: product UI string@@ -199,6 +219,14 @@ _LABELS: dict[str, dict[str, str]] = {"placeholder": "输入文字", # i18n-allow: product UI string},"pt": {+ mm.AREA: (+ "Área: arrasta ou clica numa janela. Espaço " # i18n-allow: product UI string+ "captura o ecrã inteiro" # i18n-allow: product UI string+ ),+ "keep": (+ "Ajustar a área antes de a capturar " # i18n-allow: product UI string+ "(Enter captura)" # i18n-allow: product UI string+ ),mm.MOVE: "Selecionar e mover", # i18n-allow: product UI stringmm.RECT: "Retângulo", # i18n-allow: product UI stringmm.FILLED: "Retângulo preenchido", # i18n-allow: product UI string@@ -245,8 +273,10 @@ _ACTION_KEYS = {"done": "Enter",}-#: Toolbar order — the full editor's: selection, shapes, text, effects, ink.+#: Toolbar order — the area first, then the full editor's: selection,+#: shapes, text, effects, ink.TOOL_ORDER = (+ mm.AREA,mm.MOVE,mm.RECT,mm.FILLED,@@ -850,6 +880,23 @@ def _icon_pixmap(draw: Callable[[QPainter, QColor], None], colour: QColor, dpr:def _glyphs() -> dict[str, Callable[[QPainter, QColor], None]]: # noqa: C901 - one glyph table+ def area(p: QPainter, c: QColor) -> None:+ # Four corner marks around a dashed frame: "choose this part".+ for x, y, dx, dy in ((2, 2, 1, 1), (16, 2, -1, 1), (2, 16, 1, -1), (16, 16, -1, -1)):+ p.drawLine(QPointF(x, y), QPointF(x + 4.5 * dx, y))+ p.drawLine(QPointF(x, y), QPointF(x, y + 4.5 * dy))+ faint = QColor(c)+ faint.setAlpha(140)+ p.setPen(QPen(faint, 1.1, Qt.PenStyle.DashLine))+ p.drawRect(QRectF(5.5, 5.5, 7, 7))++ def keep(p: QPainter, c: QColor) -> None:+ # A frame with handles on its corners: the area stays to be adjusted.+ p.drawRect(QRectF(4, 4, 10, 10))+ p.setBrush(c)+ for x, y in ((4, 4), (14, 4), (4, 14), (14, 14)):+ p.drawRect(QRectF(x - 1.6, y - 1.6, 3.2, 3.2))+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)):@@ -1027,6 +1074,8 @@ def _glyphs() -> dict[str, Callable[[QPainter, QColor], None]]: # noqa: C901 -p.drawLine(QPointF(5, 13), QPointF(13, 5))return {+ mm.AREA: area,+ "keep": keep,mm.MOVE: move,mm.RECT: rect,mm.FILLED: filled,@@ -1060,14 +1109,17 @@ def _glyphs() -> dict[str, Callable[[QPainter, QColor], None]]: # noqa: C901 -class Toolbar(QFrame):- """The floating marking toolbar, docked to the selection by its window.+ """The floating marking toolbar, centred at the top of its screen.- One row: the tools, then — for a tool with looks to choose from (arrow,- text, pixelate/blur, background) — those looks, then colours, size,- history and the finishing actions.+ One row: the area tool, the drawing tools, then — for a tool with looks+ to choose from (arrow, text, pixelate/blur, background) — those looks,+ then colours, size, history, the "adjust before taking" switch and the+ finishing actions."""tool_chosen = Signal(str)+ #: "Adjust the area before taking it" switched on or off.+ keep_toggled = Signal(bool)color_chosen = Signal(str)width_cycled = Signal()action = Signal(str)@@ -1128,7 +1180,7 @@ class Toolbar(QFrame):self._tools.addButton(button)self._tool_buttons[kind] = buttonbutton.clicked.connect(lambda _c=False, k=kind: self.tool_chosen.emit(k))- if kind == mm.BACKGROUND:+ if kind in (mm.MOVE, mm.BACKGROUND):main.addWidget(self._separator())main.addWidget(button)# The current tool's looks sit right after the tools, in the same row.@@ -1155,6 +1207,10 @@ class Toolbar(QFrame):self._undo = self._action_button("undo", main)self._redo = self._action_button("redo", main)main.addWidget(self._separator())+ self._keep = self._button("keep", self._labels["keep"], checkable=True)+ self._keep.setObjectName("option")+ self._keep.toggled.connect(self.keep_toggled.emit)+ main.addWidget(self._keep)for name in ("copy", "save", "edit"):self._action_button(name, main)main.addWidget(self._separator())@@ -1274,6 +1330,12 @@ class Toolbar(QFrame):painter.end()self._width.setIcon(QIcon(pixmap))+ def set_keep(self, keep: bool) -> None:+ """Show the switch's state without reporting it back as a toggle."""+ self._keep.blockSignals(True)+ self._keep.setChecked(keep)+ self._keep.blockSignals(False)+def set_history(self, can_undo: bool, can_redo: bool) -> None:self._undo.setEnabled(can_undo)self._redo.setEnabled(can_redo)diff --git a/dodaios/appshot/picker/markup_model.py b/dodaios/appshot/picker/markup_model.pyindex 552378d686..fc8ff7d843 100644--- a/dodaios/appshot/picker/markup_model.py+++ b/dodaios/appshot/picker/markup_model.py@@ -1,7 +1,8 @@"""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 with the same tools as the full appshot editor+The picker opens with its toolbar already up: the user can mark the frozen+screen first and choose the area after, or the other way round, with the+same tools as the full appshot editor(``frontend/src/lib/appshotEditorModel.ts``): select and move, rectangle,filled rectangle, ellipse, line, arrow (three looks), text (three looks),pixelate/blur, spotlight, numbered steps, pen, highlighter and a background@@ -40,6 +41,9 @@ REDACT = "redact"#: Not markings: the select tool, and the background frame switch.MOVE = "move"BACKGROUND = "background"+#: Not a marking either: choosing the area to take. Releasing its drag takes+#: the appshot at once, unless the user keeps the area to adjust it first.+AREA = "area"#: Drawn by dragging a box.BOX_KINDS = frozenset({RECT, FILLED, ELLIPSE, SPOTLIGHT, REDACT})@@ -52,7 +56,9 @@ STROKE_KINDS = frozenset({PEN, HIGHLIGHT})AREA_KINDS = frozenset({SPOTLIGHT, REDACT})#: Tool → key, in the full editor's toolbar order; the same keys as there.+#: The area tool takes the full editor's crop key: the area is the crop.TOOL_KEYS: dict[str, str] = {+ AREA: "K",MOVE: "V",RECT: "R",FILLED: "F",@@ -168,6 +174,9 @@ def grab_scope(tool: str) -> str:drawn can be moved and reshaped again at once; ``grips``: pen andhighlighter only take the selected marking's points, so writing overearlier ink never drags it along; ``none``: the background switch.+ The area tool takes hold of markings like a drawing tool, so a marking+ drawn first can still be moved before the area is chosen; Ctrl skips+ that and starts the area right on top of it."""if tool == MOVE:return "any"@@ -516,6 +525,28 @@ def resize(sel: Box, handle: str, p: Point, limit: tuple[float, float]) -> Box:return (x0, y0, x1 - x0, y1 - y0)+def other_tool(tool: str, last_drawing: str) -> str:+ """Tab / middle-click: from the area tool to the last drawing tool and back."""+ return last_drawing if tool == AREA else AREA+++def toolbar_home(bar: tuple[float, float], screen: tuple[float, float], gap: float = 12.0) -> Point:+ """The toolbar's place before any area is kept: centred at the top of the screen."""+ bw, _bh = bar+ sw, _sh = screen+ return (max(gap, (sw - bw) / 2.0), gap)+++def toolbar_spot(+ sel: Box | None, bar: tuple[float, float], screen: tuple[float, float], gap: float = 12.0+) -> Point:+ """Top centre; docked to a kept area only when the area would sit under it."""+ home = toolbar_home(bar, screen, gap)+ if sel is None or clip_to((home[0], home[1], bar[0], bar[1]), sel) is None:+ return home+ return toolbar_origin(sel, bar, screen, gap=10.0)++def toolbar_origin(sel: Box, bar: tuple[float, float], screen: tuple[float, float], gap: float = 10.0) -> Point:@@ -615,6 +646,7 @@ class History:__all__ = [+ "AREA","AREA_KINDS","ARROW","ARROW_STYLES",@@ -660,6 +692,7 @@ __all__ = ["is_meaningful","next_counter","normalized",+ "other_tool","reshape","resize","rough_measure",@@ -667,6 +700,8 @@ __all__ = ["segment_path","shape_at","text_size",+ "toolbar_home","toolbar_origin",+ "toolbar_spot","translated",]diff --git a/dodaios/appshot/picker/markup_window.py b/dodaios/appshot/picker/markup_window.pynew file mode 100644index 0000000000..2a7213ddb8--- /dev/null+++ b/dodaios/appshot/picker/markup_window.py@@ -0,0 +1,984 @@+"""The appshot picker's screen window: toolbar up front, mark first, take on release.++Runs ONLY inside ``python -m dodaios.appshot.picker`` (PySide6, AP-26).++- The overlay opens with the marking toolbar centred at the top of the+ 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.+- 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.+- Space takes the whole screen with its markings; so do Enter, Ctrl+C / S / E+ and the finishing buttons while no area is kept.+- With "adjust before taking" switched on, a released area stays with its+ resize handles instead: it is marked up, resized and moved, and Enter, a+ double-click in it or the check button takes it. The parent remembers the+ switch (``[appshot].region_keep_area``).+- Esc, or a right-click on nothing, closes the overlay; a right-click on a+ marking removes it.++The marking rules live in :mod:`dodaios.appshot.picker.markup_model`, the+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 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++#: Cursor per kept-area 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,+}+#: Cursor per marking grip kind (:func:`markup_model.grip_cursor`).+_GRIP_CURSORS = {+ "fdiag": Qt.CursorShape.SizeFDiagCursor,+ "bdiag": Qt.CursorShape.SizeBDiagCursor,+ "hor": Qt.CursorShape.SizeHorCursor,+ "grab": Qt.CursorShape.OpenHandCursor,+}+#: Arrow keys nudge the selected marking.+_NUDGE = {+ Qt.Key.Key_Left: (-1.0, 0.0),+ Qt.Key.Key_Right: (1.0, 0.0),+ Qt.Key.Key_Up: (0.0, -1.0),+ Qt.Key.Key_Down: (0.0, 1.0),+}+#: 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,+}+#: Extra room around a marking being drawn or dragged, so its arrow head,+#: shadow, grips and dashed frame repaint with it (logical px, plus widths).+_LIVE_PAD = 24.0+_LIVE_PAD_PER_WIDTH = 6.0+++class _MarkupState:+ """Everything one screen window holds: the markings, the kept area, the tool."""++ def __init__(self) -> None:+ #: The kept area (logical px), with "adjust before taking" on; ``None``+ #: while no area is chosen.+ self.sel: QRectF | None = None+ self.shapes: list[mm.Shape] = []+ self.history = mm.History()+ self.tool = mm.AREA+ #: Where Tab and the middle button go from the area tool.+ self.last_drawing = mm.ARROW+ self.color = mm.PALETTE[0]+ self.width_index = mm.DEFAULT_WIDTH_INDEX+ self.arrow_style = mm.ARROW_STYLES[0]+ self.text_style = mm.TEXT_STYLES[0]+ self.redact_mode = mm.REDACT_MODES[0]+ #: The background frame (preset, padding, radius, shadow), or ``None``.+ self.background: dict | None = None+ #: The marking being dragged out right now.+ self.drawing: mm.Shape | None = None+ #: The text being typed (not in ``shapes`` while open); where an edited+ #: text came from, and how it was, so Esc can put it back.+ self.typing: mm.Shape | None = None+ self.typing_index: int | None = None+ self.typing_original: mm.Shape | None = None+ #: Index into ``shapes`` of the selected marking (grips shown).+ self.selected: int | None = None+ #: ``("area", handle)`` / ``("area-move", None)`` / ``("grip", grip)``+ #: / ``("move", None)``.+ self.drag: tuple[str, str | None] | None = None+ #: The selected marking as it was when a grip drag began.+ self.original: mm.Shape | None = None+ self.last: QPointF | None = None+ self.moved = False++ #: The choices that follow the pointer from one screen to the next.+ STYLE = (+ "tool",+ "last_drawing",+ "color",+ "width_index",+ "arrow_style",+ "text_style",+ "redact_mode",+ "background",+ )++ @property+ def width(self) -> float:+ return mm.WIDTHS[self.width_index]++ @property+ def engaged(self) -> bool:+ """Anything on this screen that moving to another one would lose."""+ return bool(+ self.shapes+ or self.sel is not None+ or self.typing is not None+ or self.drawing is not None+ )++ def box(self) -> mm.Box:+ sel = self.sel+ assert sel is not None+ return (sel.x(), sel.y(), sel.width(), sel.height())++ def selected_shape(self) -> mm.Shape | None:+ if self.selected is None or not 0 <= self.selected < len(self.shapes):+ return None+ return self.shapes[self.selected]+++def _box(rect: QRectF) -> mm.Box:+ return (rect.x(), rect.y(), rect.width(), rect.height())+++class MarkupWindow(_SelectWindow):+ """One screen of the appshot picker: choose an area and mark it, in any order."""++ def __init__(self, screen, frozen, owner) -> None:+ super().__init__(screen, frozen, owner)+ self._markup = _MarkupState()+ self._patches = annotate.HidePatches(frozen, self._scale)+ self._toolbar: annotate.Toolbar | None = None+ #: Where the marking being drawn or dragged was painted last.+ self._painted_live: QRectF | None = None++ def release_capture(self) -> None:+ """Drop pixels explicitly, including the preview's bound-method cycle."""+ self._frozen = None+ self._patches = annotate.HidePatches(None, self._scale)+ self._markup = _MarkupState()++ # -- the toolbar ---------------------------------------------------------+ def arm(self) -> None:+ bar = self._ensure_toolbar()+ self._sync_toolbar()+ bar.show()+ bar.raise_()+ self._update_cursor(self._pointer_point())++ def disarm(self) -> None:+ if self._toolbar is not None:+ self._toolbar.hide()++ def adopt(self, other) -> None:+ state = getattr(other, "_markup", None)+ if not isinstance(state, _MarkupState):+ return+ for name in _MarkupState.STYLE:+ value = getattr(state, name)+ setattr(self._markup, name, dict(value) if isinstance(value, dict) else value)++ def _ensure_toolbar(self) -> annotate.Toolbar:+ 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)+ bar.option_chosen.connect(self._set_option)+ bar.keep_toggled.connect(self._set_keep)+ self._toolbar = bar+ return self._toolbar++ def _sync_toolbar(self) -> None:+ bar = self._toolbar+ if bar is None:+ return+ m = self._markup+ bar.set_tool(m.tool)+ bar.set_color(m.color)+ bar.set_width(m.width)+ bar.set_keep(self._owner.keep_area)+ self._sync_options()+ self._sync_history()++ def _show_toolbar(self) -> None:+ if self._toolbar is not None and self._owner.marking in (None, self):+ self._place_toolbar()+ self._toolbar.show()+ self._toolbar.raise_()++ def _place_toolbar(self) -> None:+ bar = self._toolbar+ if bar is None:+ return+ bar.adjustSize()+ sel = self._markup.box() if self._markup.sel is not None else None+ x, y = mm.toolbar_spot(sel, (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 _sync_options(self) -> None:+ """The looks shown for the current tool (or the selected marking's kind)."""+ bar = self._toolbar+ if bar is None:+ return+ m = self._markup+ kind = m.tool+ selected = m.selected_shape()+ if kind in (mm.MOVE, mm.AREA) and selected is not None:+ kind = selected.kind+ if kind == mm.ARROW:+ style = selected.style if selected is not None and selected.kind == mm.ARROW else ""+ options = [(s, f"arrow_{s}") for s in mm.ARROW_STYLES]+ bar.set_options(options, style or m.arrow_style, "arrow")+ elif kind == mm.TEXT:+ style = selected.style if selected is not None and selected.kind == mm.TEXT else ""+ options = [(s, f"text_{s}") for s in mm.TEXT_STYLES]+ bar.set_options(options, style or m.text_style, "text")+ elif kind == mm.REDACT:+ mode = selected.mode if selected is not None and selected.kind == mm.REDACT else ""+ options = [(s, f"redact_{s}") for s in mm.REDACT_MODES]+ bar.set_options(options, mode or m.redact_mode, "redact")+ elif kind == mm.BACKGROUND:+ options = [("off", "background_off")]+ options += [(preset, "preset") for preset, _stops in mm.BACKGROUND_PRESETS]+ chosen = m.background["preset"] if m.background else "off"+ bar.set_options(options, chosen, "background")+ else:+ bar.set_options([], "")+ self._place_toolbar()++ def _sync_lock(self) -> None:+ """Markings keep the toolbar on this screen; without them it may follow the pointer."""+ if self._markup.engaged:+ self._owner.lock(self)+ else:+ self._owner.unlock(self)++ # -- choices -------------------------------------------------------------+ def _commit(self) -> None:+ self._markup.history.push(self._markup.shapes)+ self._sync_history()++ def _set_tool(self, kind: str) -> None:+ self._commit_typing()+ m = self._markup+ if kind != mm.AREA:+ m.last_drawing = kind+ m.tool = kind+ if mm.grab_scope(kind) == "none":+ m.selected = None+ if kind == mm.BACKGROUND and m.background is None:+ m.background = dict(mm.DEFAULT_BACKGROUND)+ if self._toolbar is not None:+ self._toolbar.set_tool(kind)+ self._painted_numbers = None+ self._painted_hole = None+ self._sync_options()+ self._update_cursor(self._pointer_point())+ self.update()++ def _set_keep(self, keep: bool) -> None:+ self._owner.set_keep_area(keep)++ def _set_color(self, colour: str) -> None:+ m = self._markup+ m.color = colour+ target = m.typing or m.selected_shape()+ 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, to: int | None = None) -> None:+ m = self._markup+ count = len(mm.WIDTHS)+ if to is not None:+ m.width_index = max(0, min(count - 1, to))+ else:+ index = m.width_index + step+ m.width_index = index % count if wrap else max(0, min(count - 1, index))+ target = m.typing or m.selected_shape()+ if target is not None:+ target.width = m.width+ if target.kind == mm.TEXT:+ target.size = mm.text_size(m.width)+ elif target.kind == mm.COUNTER:+ target.size = mm.counter_size(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 _set_option(self, group: str, value: str) -> None:+ m = self._markup+ selected = m.selected_shape()+ changed = False+ if group == "arrow":+ m.arrow_style = value+ if selected is not None and selected.kind == mm.ARROW:+ selected.style, changed = value, True+ elif group == "text":+ m.text_style = value+ target = m.typing or (selected if selected and selected.kind == mm.TEXT else None)+ if target is not None:+ target.style = value+ changed = target is not m.typing+ elif group == "redact":+ m.redact_mode = value+ if selected is not None and selected.kind == mm.REDACT:+ selected.mode, changed = value, True+ elif group == "background":+ if value == "off":+ m.background = None+ else:+ m.background = {**(m.background or mm.DEFAULT_BACKGROUND), "preset": value}+ if changed:+ self._commit()+ self._sync_options()+ 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+ m.typing_index = None+ state = m.history.redo() if redo else m.history.undo()+ if state is not None:+ m.shapes = state+ m.selected = None+ self._sync_history()+ self._sync_options()+ self._sync_lock()+ self.update()++ # -- taking the appshot --------------------------------------------------+ def area_chosen(self, frac: tuple[float, float, float, float]) -> None:+ """The area drag ended: take it at once, or keep it to adjust it first."""+ fx, fy, fw, fh = frac+ rect = QRectF(fx * self.width(), fy * self.height(), fw * self.width(), fh * self.height())+ if not self._owner.keep_area:+ self._deliver(wire.ACTION_DONE, area=rect)+ return+ m = self._markup+ m.sel = rect+ self._pointer = None+ self._painted_numbers = None+ self._painted_hole = None+ self._sync_options()+ self._show_toolbar()+ self._sync_lock()+ self._update_cursor(None)+ self.update()++ def _deliver(self, action: str, *, area: QRectF | None = None, whole: bool = False) -> None:+ """Take the appshot: the area (kept, given, or the whole screen) plus the markings."""+ self._commit_typing()+ m = self._markup+ full = QRectF(0, 0, self.width(), self.height())+ sel = full if whole else (area or m.sel or full)+ frac = (+ sel.x() / self.width(),+ sel.y() / self.height(),+ sel.width() / self.width(),+ sel.height() / self.height(),+ )+ markup: dict | None = None+ if m.shapes or m.background:+ markup = {+ "overlay": annotate.render_overlay(m.shapes, sel, self._scale())+ if m.shapes+ else "",+ "hides": mm.hide_fractions(m.shapes, _box(sel)),+ }+ if m.background:+ markup["background"] = dict(m.background)+ self._owner.finish(self, frac, action=action, markup=markup)++ # -- text ----------------------------------------------------------------+ def _start_typing(self, at: mm.Point, *, index: int | None = None) -> None:+ """Open the text box: a new one at ``at``, or the text at ``index``."""+ m = self._markup+ if index is not None:+ m.typing = m.shapes.pop(index)+ m.typing_index = index+ m.typing_original = m.typing.copy()+ else:+ size = mm.text_size(m.width)+ m.typing = mm.Shape(+ mm.TEXT,+ color=m.color,+ width=m.width,+ size=size,+ style=m.text_style,+ points=[(at[0], at[1] - size * 0.62)],+ )+ m.typing_index = None+ m.selected = None+ self._sync_options()+ self._sync_lock()+ self.update()++ def _commit_typing(self, *, cancel: bool = False) -> None:+ m = self._markup+ shape, index = m.typing, m.typing_index+ if shape is None:+ return+ m.typing, m.typing_index = None, None+ original, m.typing_original = m.typing_original, None+ if cancel:+ if index is not None and original is not None:+ # Esc on an edited text keeps it as it was.+ m.shapes.insert(min(index, len(m.shapes)), original)+ self._sync_lock()+ self.update()+ return+ shape.text = shape.text.rstrip()+ if mm.is_meaningful(shape):+ at = min(index, len(m.shapes)) if index is not None else len(m.shapes)+ m.shapes.insert(at, shape)+ # A finished text shows its points, like every fresh marking.+ m.selected = at+ self._commit()+ self._sync_options()+ elif index is not None:+ self._commit() # emptied: the text is gone+ self._sync_lock()+ self.update()++ def _text_at(self, point: mm.Point) -> int | None:+ index = mm.shape_at(self._markup.shapes, point, annotate.qt_measure, areas=False)+ if index is not None and self._markup.shapes[index].kind == mm.TEXT:+ return index+ return None++ def _grabbable(self, point: mm.Point) -> int | None:+ """The marking a press at ``point`` would move with the current tool."""+ m = self._markup+ scope = mm.grab_scope(m.tool)+ if scope in ("none", "grips"):+ return None+ index = mm.shape_at(m.shapes, point, annotate.qt_measure, areas=scope == "any")+ if index is None or (m.tool == mm.TEXT and m.shapes[index].kind == mm.TEXT):+ return None+ return index++ # -- keys ----------------------------------------------------------------+ def focusNextPrevChild(self, next_child: bool) -> bool: # noqa: N802 (Qt override)+ # Tab switches between the area and the last drawing tool, not focus.+ return False++ def keyPressEvent(self, event) -> None: # noqa: N802, C901 - one key table+ marking = self._owner.marking+ if marking is not None and marking is not self:+ marking.keyPressEvent(event)+ return+ 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 self._start is not None:+ self._cancel_area_drag()+ elif m.selected is not None:+ m.selected = None+ self._sync_options()+ 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 key == Qt.Key.Key_Space and not ctrl:+ self._deliver(wire.ACTION_DONE, whole=True)+ elif key in (Qt.Key.Key_Tab, Qt.Key.Key_Backtab):+ self._set_tool(mm.other_tool(m.tool, m.last_drawing))+ 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.selected is not None:+ del m.shapes[m.selected]+ m.selected = None+ self._commit()+ self._sync_options()+ self._sync_lock()+ self.update()+ elif key in _NUDGE and m.selected is not None:+ dx, dy = _NUDGE[key]+ step = 10.0 if mods & Qt.KeyboardModifier.ShiftModifier else 1.0+ m.shapes[m.selected] = mm.translated(m.shapes[m.selected], dx * step, dy * step)+ self._commit()+ self.update()+ elif not ctrl and Qt.Key.Key_1 <= key <= Qt.Key.Key_5:+ self._step_width(0, to=int(key) - int(Qt.Key.Key_1))+ 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._commit_typing(cancel=True)+ return+ if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):+ if mods & Qt.KeyboardModifier.ShiftModifier:+ shape.text += "\n"+ else:+ self._commit_typing()+ return+ 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()++ # -- the mouse -----------------------------------------------------------+ def _inert(self) -> bool:+ """Another screen holds the markings: this one waits."""+ return self._owner.marking is not None and self._owner.marking is not self++ def mousePressEvent(self, event) -> None: # noqa: N802, C901 - one press table+ if self._inert():+ return+ self._owner.focus_on(self)+ m = self._markup+ p = event.position()+ point = (p.x(), p.y())+ button = event.button()+ if button == Qt.MouseButton.RightButton:+ self._right_click(point)+ return+ if button == Qt.MouseButton.MiddleButton:+ self._set_tool(mm.other_tool(m.tool, m.last_drawing))+ return+ if button != Qt.MouseButton.LeftButton:+ return+ self._commit_typing()+ # Ctrl skips taking hold of markings: draw (or choose) right over them.+ free = not bool(+ event.modifiers()+ & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.MetaModifier)+ )+ selected = m.selected_shape()+ if free and selected is not None and mm.grab_scope(m.tool) != "none":+ grip = mm.grip_at(selected, point, mm.HANDLE_GRAB_PX + 1, annotate.qt_measure)+ if grip is not None:+ m.drag, m.original, m.moved = ("grip", grip), selected.copy(), False+ return+ if m.sel is not None:+ handle = mm.handle_at(m.box(), point)+ if handle is not None:+ m.drag = ("area", handle)+ return+ grabbed = self._grabbable(point) if free else None+ if grabbed is not None:+ m.selected = grabbed+ m.drag, m.last, m.moved = ("move", None), p, False+ self._sync_options()+ self.update()+ return+ if m.selected is not None:+ m.selected = None+ self._sync_options()+ self.update()+ if m.tool == mm.AREA:+ if m.sel is not None and m.sel.contains(p):+ m.drag, m.last = ("area-move", None), p+ return+ self._start = p+ self._end = p+ self._pointer = p+ # The toolbar steps aside while the area is drawn, so nothing+ # covers what is being chosen.+ if self._toolbar is not None:+ self._toolbar.hide()+ self.update()+ return+ if m.tool in (mm.MOVE, mm.BACKGROUND):+ return+ if m.tool == mm.TEXT:+ self._start_typing(point, index=self._text_at(point))+ return+ if m.tool == mm.COUNTER:+ m.shapes.append(+ mm.Shape(+ mm.COUNTER,+ color=m.color,+ width=m.width,+ size=mm.counter_size(m.width),+ points=[point],+ number=mm.next_counter(m.shapes),+ )+ )+ m.selected = len(m.shapes) - 1+ self._commit()+ self._sync_options()+ 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],+ style=m.arrow_style if m.tool == mm.ARROW else "",+ mode=m.redact_mode if m.tool == mm.REDACT else "",+ )+ self._sync_lock()+ self._touch_live()++ def _right_click(self, point: mm.Point) -> None:+ """Undo the gesture in progress, remove a marking, or close."""+ m = self._markup+ if self._start is not None:+ self._cancel_area_drag()+ return+ if m.drawing is not None:+ m.drawing = None+ self._sync_lock()+ self._touch_live()+ return+ if m.typing is not None:+ self._commit_typing(cancel=True)+ return+ index = mm.shape_at(m.shapes, point, annotate.qt_measure)+ if index is not None:+ del m.shapes[index]+ m.selected = None+ self._commit()+ self._sync_options()+ self._sync_lock()+ self.update()+ return+ if m.sel is not None:+ m.sel = None+ m.drag = None+ self._sync_options()+ self._sync_lock()+ self._update_cursor(point)+ self.update()+ return+ self._owner.finish(None, None)++ def _cancel_area_drag(self) -> None:+ self._start = None+ self._end = None+ self._show_toolbar()+ self.update()++ def mouseMoveEvent(self, event) -> None: # noqa: N802+ if self._inert():+ return+ self._owner.focus_on(self)+ m = self._markup+ p = event.position()+ point = (p.x(), p.y())+ if self._start is not None:+ self._end = p+ self._pointer = p+ self._repaint_changes()+ return+ drag = m.drag+ if drag is not None and drag[0] == "area" and m.sel is not None:+ sel = mm.resize(m.box(), drag[1] or "se", point, (self.width(), self.height()))+ m.sel = QRectF(*sel)+ self._place_toolbar()+ self.update()+ return+ if drag is not None and drag[0] == "area-move" and m.sel is not None and m.last:+ delta = p - m.last+ sel = m.sel+ x = max(0.0, min(self.width() - sel.width(), sel.x() + delta.x()))+ y = max(0.0, min(self.height() - sel.height(), sel.y() + delta.y()))+ m.sel = QRectF(x, y, sel.width(), sel.height())+ m.last = p+ self._place_toolbar()+ self.update()+ return+ if drag is not None and drag[0] == "grip" and m.selected is not None and m.original:+ m.shapes[m.selected] = mm.reshape(+ m.original, drag[1] or "se", point, annotate.qt_measure+ )+ m.moved = True+ self._touch_live()+ return+ if drag is not None and drag[0] == "move" and m.selected is not None and m.last:+ delta = p - m.last+ m.shapes[m.selected] = mm.translated(m.shapes[m.selected], delta.x(), delta.y())+ m.last, m.moved = p, True+ self._touch_live()+ 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._touch_live()+ return+ self._pointer = p+ self._repaint_changes()+ self._update_cursor(point)++ def mouseReleaseEvent(self, event) -> None: # noqa: N802+ if self._inert() or event.button() != Qt.MouseButton.LeftButton:+ return+ if self._start is not None:+ frac = self._take_drag(event.position())+ if frac is None:+ self._show_toolbar()+ self.update()+ return+ self.area_chosen(frac)+ return+ m = self._markup+ drag, m.drag = m.drag, None+ m.original = None+ if drag is not None and drag[0] in ("area", "area-move"):+ self._sync_options()+ self.update()+ return+ if drag is not None and drag[0] in ("move", "grip") 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()+ # Every fresh marking shows its points at once (the previous one+ # loses them), so it can be moved and reshaped right away.+ m.selected = len(m.shapes) - 1+ self._sync_options()+ self._sync_lock()+ self._touch_live()++ def mouseDoubleClickEvent(self, event) -> None: # noqa: N802+ """Double-click a text to change it; double-click in a kept area to take it."""+ if self._inert():+ return+ m = self._markup+ if m.typing is not None:+ return+ p = event.position()+ if m.tool in (mm.MOVE, mm.TEXT):+ index = self._text_at((p.x(), p.y()))+ if index is not None:+ m.drag = None+ self._start_typing((p.x(), p.y()), index=index)+ return+ if m.sel is not None and m.sel.contains(p) and m.tool in (mm.AREA, mm.MOVE):+ m.drag = None+ self._deliver(wire.ACTION_DONE)++ def wheelEvent(self, event) -> None: # noqa: N802+ if self._inert():+ return+ steps = event.angleDelta().y()+ if steps:+ self._step_width(1 if steps > 0 else -1)++ def _pointer_point(self) -> mm.Point | None:+ p = self._pointer+ return (p.x(), p.y()) if p is not None else None++ def _update_cursor(self, point: mm.Point | None) -> None: # noqa: C901 - one cursor table+ m = self._markup+ if point is not None:+ selected = m.selected_shape()+ if selected is not None and mm.grab_scope(m.tool) != "none":+ grip = mm.grip_at(selected, point, mm.HANDLE_GRAB_PX + 1, annotate.qt_measure)+ if grip is not None:+ self.setCursor(_GRIP_CURSORS[mm.grip_cursor(grip)])+ return+ if m.sel is not None:+ handle = mm.handle_at(m.box(), point)+ if handle is not None:+ self.setCursor(_HANDLE_CURSORS[handle])+ return+ if self._grabbable(point) is not None:+ self.setCursor(Qt.CursorShape.SizeAllCursor)+ return+ if m.tool == mm.AREA and m.sel is not None and m.sel.contains(QPointF(*point)):+ self.setCursor(Qt.CursorShape.SizeAllCursor)+ return+ if m.tool == mm.TEXT:+ self.setCursor(Qt.CursorShape.IBeamCursor)+ elif m.tool in (mm.MOVE, mm.BACKGROUND):+ self.setCursor(Qt.CursorShape.ArrowCursor)+ else:+ self.setCursor(self._cross)++ # -- what the crosshair shows --------------------------------------------+ def _choosing(self) -> bool:+ """The area tool is out and no area is kept: snapping and numbers show."""+ return self._markup.tool == mm.AREA and self._markup.sel is None++ def _hole(self) -> QRectF | None:+ if self._markup.sel is not None:+ return None+ sel = self._selection()+ if sel is not None:+ return sel+ if self._choosing() and self._pointer is not None:+ return self._snap_at(self._pointer)+ return None++ def _numbers(self) -> tuple[str, str] | None:+ if self._selection() is None and not self._choosing():+ return None+ return super()._numbers()++ # -- painting ------------------------------------------------------------+ def _live_rect(self) -> QRectF | None:+ """What the marking being drawn or dragged covers, with room for its frills."""+ m = self._markup+ shape = m.drawing or m.selected_shape()+ if shape is None or not shape.points:+ return None+ if shape.kind == mm.SPOTLIGHT:+ # A spotlight dims everything around it.+ return QRectF(0, 0, self.width(), self.height())+ x, y, w, h = mm.bounds(shape, annotate.qt_measure)+ pad = _LIVE_PAD + shape.width * _LIVE_PAD_PER_WIDTH+ return QRectF(x, y, w, h).adjusted(-pad, -pad, pad, pad)++ def _touch_live(self) -> None:+ """Repaint where the live marking is now and where it was."""+ rect = self._live_rect()+ dirty = rect+ if self._painted_live is not None:+ dirty = self._painted_live if dirty is None else dirty.united(self._painted_live)+ self._painted_live = rect+ if self._markup.sel is not None or dirty is None:+ self.update()+ else:+ self.update(dirty.toAlignedRect())++ def paintEvent(self, event) -> None: # noqa: N802+ painter = QPainter(self)+ painter.setClipRect(event.rect())+ 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_kept(painter, full)+ painter.end()+ return+ hole = self._hole()+ self._paint_veil(painter, full, hole)+ self._paint_markings(painter, full)+ if hole is not None:+ self._paint_border(painter, hole)+ self._paint_numbers(painter)+ painter.end()++ def _paint_markings(self, painter: QPainter, area: QRectF) -> None:+ m = self._markup+ live = [*m.shapes, *(s for s in (m.drawing,) if s is not None)]+ if live:+ for shape in (s for s in live if s.kind == mm.REDACT):+ annotate.paint_shape(painter, shape, hide_source=self._patches)+ for shape in (s for s in live if s.kind != mm.REDACT):+ annotate.paint_shape(painter, shape)+ annotate.paint_spotlights(painter, live, area)+ if m.typing is not None:+ labels = annotate.labels_for(self._owner.language)+ annotate.paint_typing(painter, m.typing, labels["placeholder"], caret=True)+ selected = m.selected_shape()+ if selected is not None:+ annotate.paint_picked(painter, selected)++ def _paint_kept(self, painter: QPainter, full: QRectF) -> None:+ """A kept area: the world around it darker, markings cut to it, handles."""+ 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))+ if m.background:+ annotate.paint_background_frame(painter, sel, m.background)+ painter.save()+ painter.setClipRect(sel, Qt.ClipOperation.IntersectClip)+ live = [*m.shapes, *(s for s in (m.drawing,) if s is not None)]+ for shape in (s for s in live if s.kind == mm.REDACT):+ annotate.paint_shape(painter, shape, hide_source=self._patches)+ for shape in (s for s in live if s.kind != mm.REDACT):+ annotate.paint_shape(painter, shape)+ annotate.paint_spotlights(painter, live, sel)+ painter.restore()+ if m.typing is not None:+ labels = annotate.labels_for(self._owner.language)+ annotate.paint_typing(painter, m.typing, labels["placeholder"], caret=True)+ selected = m.selected_shape()+ if selected is not None:+ annotate.paint_picked(painter, selected)+ 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()+++__all__ = ["MarkupWindow"]diff --git a/dodaios/appshot/picker/renderer.py b/dodaios/appshot/picker/renderer.pyindex 37a28f4524..cfa59584b9 100644--- a/dodaios/appshot/picker/renderer.py+++ b/dodaios/appshot/picker/renderer.py@@ -17,12 +17,12 @@ imports this module (AP-26). One frameless, always-on-top window per screen:clears and the selected area itself turns a translucent grey, with one thinborder.-- **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:`dodaios.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.+This module holds that plain area chooser (:class:`_SelectWindow`, which the+screen recorder uses as it is) and the process around the windows+(:class:`Picker`). The appshot's windows add the marking toolbar on top+(:mod:`dodaios.appshot.picker.markup_window`): it is up from the start, the+screen can be marked before the area is chosen, and releasing the area drag+takes the appshot at once.Only the parts that change are repainted, so the numbers follow the pointerwithout dragging a full 4K repaint behind them. Esc or a right-click cancels.@@ -51,27 +51,30 @@ from PySide6.QtGui import (from PySide6.QtWidgets import QApplication, QWidgetfrom dodaios.appshot import picker as wire-from dodaios.appshot.picker import annotate-from dodaios.appshot.picker import markup_model as mm-from dodaios.appshot.region import grab_preview, match_monitor, selection_fractions, snap_rects_on_screen+from dodaios.appshot.region import (+ grab_preview,+ match_monitor,+ selection_fractions,+ snap_rects_on_screen,+)#: A light veil before the drag (the picker is armed). While dragging the#: veil lifts and the selection itself takes a neutral grey tint instead, so#: the chosen area reads as "marked" on light and dark content alike.-_DIM_IDLE = QColor(0, 0, 0, 55)-_SELECTION_TINT = QColor(128, 128, 132, 105)+DIM_IDLE = QColor(0, 0, 0, 55)+SELECTION_TINT = QColor(128, 128, 132, 105)#: The selection border: a white hairline with a faint dark edge outside it,#: so it reads on light and dark content alike._BORDER = QColor(255, 255, 255, 235)_BORDER_EDGE = QColor(0, 0, 0, 70)#: The numbers beside the crosshair: dark ink with a white halo.-_INK = QColor(20, 20, 22)-_HALO = QColor(255, 255, 255, 235)+INK = QColor(20, 20, 22)+HALO = QColor(255, 255, 255, 235)_NUMBER_PT = 8.5#: Offset of the numbers from the crosshair centre, and the screen-edge gap._NUMBER_OFFSET = QPointF(12.0, 10.0)-_EDGE_GAP = 4.0+EDGE_GAP = 4.0#: Crosshair cursor geometry (logical px): arm length, ring radius._CROSS_ARM = 11@@ -80,38 +83,6 @@ _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,-}-#: Cursor per marking grip kind (:func:`markup_model.grip_cursor`).-_GRIP_CURSORS = {- "fdiag": Qt.CursorShape.SizeFDiagCursor,- "bdiag": Qt.CursorShape.SizeBDiagCursor,- "hor": Qt.CursorShape.SizeHorCursor,- "grab": Qt.CursorShape.OpenHandCursor,-}-#: Arrow keys nudge the selected marking.-_NUDGE = {- Qt.Key.Key_Left: (-1.0, 0.0),- Qt.Key.Key_Right: (1.0, 0.0),- Qt.Key.Key_Up: (0.0, -1.0),- Qt.Key.Key_Down: (0.0, 1.0),-}-#: 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()@@ -131,7 +102,30 @@ def _emit(payload: dict) -> None:sys.stdout.flush()-def _number_font() -> QFont:+def _claim_keyboard(window: QWidget) -> None:+ """Windows: take the keyboard, so the toolbar's keys work before the first click.++ Windows keeps the foreground with the app the user was in when a+ background process asks for it; the overlay would then stay deaf to+ Space, Tab and the tool letters until it is clicked once. The shared,+ hardened foreground path (:mod:`dodaios.platform.window_state`) takes it.+ """+ if sys.platform != "win32":+ return+ try:+ import ctypes # noqa: PLC0415++ hwnd = int(window.winId())+ if int(ctypes.windll.user32.GetForegroundWindow() or 0) == hwnd:+ return+ from dodaios.platform.window_state import _force_foreground_windows # noqa: PLC0415++ _force_foreground_windows(hwnd)+ except Exception as exc: # noqa: BLE001 - a click still hands the keyboard over+ sys.stderr.write(f"appshot-picker: could not take the keyboard ({exc!r}).\n")+++def number_font() -> QFont:font = QFont()font.setPointSizeF(_NUMBER_PT)font.setWeight(QFont.Weight.DemiBold)@@ -161,7 +155,7 @@ def crosshair_cursor(dpr: float) -> QCursor:(QPointF(c, c - arm), QPointF(c, c - gap)),(QPointF(c, c + gap), QPointF(c, c + arm)),)- for colour, width in ((_HALO, 3.0), (_INK, 1.1)):+ for colour, width in ((HALO, 3.0), (INK, 1.1)):pen = QPen(colour, width)pen.setCapStyle(Qt.PenCapStyle.FlatCap)painter.setPen(pen)@@ -174,55 +168,8 @@ 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- self.arrow_style = mm.ARROW_STYLES[0]- self.text_style = mm.TEXT_STYLES[0]- self.redact_mode = mm.REDACT_MODES[0]- #: The background frame (preset, padding, radius, shadow), or ``None``.- self.background: dict | None = None- #: The marking being dragged out right now.- self.drawing: mm.Shape | None = None- #: The text being typed (not in ``shapes`` while open); where an edited- #: text came from, and how it was, so Esc can put it back.- self.typing: mm.Shape | None = None- self.typing_index: int | None = None- self.typing_original: mm.Shape | None = None- #: Index into ``shapes`` of the selected marking (grips shown).- self.selected: int | None = None- #: ``("area", handle)`` / ``("grip", grip)`` / ``("move", None)``.- self.drag: tuple[str, str | None] | None = None- #: The selected marking as it was when a grip drag began.- self.original: mm.Shape | 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())-- def selected_shape(self) -> mm.Shape | None:- if self.selected is None or not 0 <= self.selected < len(self.shapes):- return None- return self.shapes[self.selected]--class _SelectWindow(QWidget):- """One screen's selection canvas."""+ """One screen's selection canvas: drag an area or click a window."""def __init__(self, screen, frozen: QPixmap | None, owner: Picker) -> None:super().__init__(None)@@ -254,21 +201,26 @@ class _SelectWindow(QWidget):#: Snap targets in this window's logical coordinates, top-most first.self._snaps: list[QRectF] = []self._monitor: dict | None = None- self._font = _number_font()+ self._font = number_font()self._metrics = QFontMetricsF(self._font)#: What was painted last, so the next move repaints only what changed.self._painted_numbers: QRectF | None = Noneself._painted_hole: QRectF | None = Noneself._cross = crosshair_cursor(screen.devicePixelRatio() or 1.0)- self._markup = _MarkupState()- self._patches = annotate.HidePatches(frozen, self._scale)- self._toolbar: annotate.Toolbar | None = Nonedef release_capture(self) -> None:- """Drop pixels explicitly, including the preview's bound-method cycle."""+ """Drop the frozen frame's pixels explicitly."""self._frozen = None- self._patches = annotate.HidePatches(None, self._scale)- self._markup = _MarkupState()++ # -- the toolbar hooks (the appshot window has a toolbar; this one not) --+ def arm(self) -> None:+ """The pointer is on this screen: show what belongs to it."""++ def disarm(self) -> None:+ """The pointer left for another screen."""++ def adopt(self, other: _SelectWindow) -> None:+ """Carry over choices made on ``other`` (the screen the pointer left)."""# -- data from the main process ------------------------------------------def set_layout(self, monitors: list[dict], windows: list[list[int]]) -> None:@@ -283,24 +235,12 @@ 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)- returnif event.key() == Qt.Key.Key_Escape:self._owner.finish(None, None)returnsuper().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)- returnif event.button() == Qt.MouseButton.RightButton:self._owner.finish(None, None)return@@ -312,10 +252,6 @@ 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)- returnself._pointer = event.position()if self._start is not None:self._end = event.position()@@ -323,18 +259,24 @@ 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)- returnif event.button() != Qt.MouseButton.LeftButton or self._start is None:return- end = event.position()- frac = selection_fractions(- self._start.x(), self._start.y(), end.x(), end.y(), self.width(), self.height()- )+ frac = self._take_drag(event.position())+ if frac is None:+ self.update()+ return+ self.area_chosen(frac)++ def _take_drag(self, end: QPointF) -> tuple[float, float, float, float] | None:+ """End the drag at ``end``: its area, or the window under a plain click."""+ start = self._startself._start = Noneself._end = None+ if start is None:+ return None+ frac = selection_fractions(+ start.x(), start.y(), end.x(), end.y(), self.width(), self.height()+ )if frac is None:# A click, not a drag: take the window under the pointer, if any.snap = self._snap_at(end)@@ -345,13 +287,11 @@ class _SelectWindow(QWidget):snap.width() / self.width(),snap.height() / self.height(),)- if frac is None:- self.update()- return- fx, fy, fw, fh = frac- self._begin_markup(- QRectF(fx * self.width(), fy * self.height(), fw * self.width(), fh * self.height())- )+ return frac++ def area_chosen(self, frac: tuple[float, float, float, float]) -> None:+ """An area is chosen: report it."""+ self._owner.finish(self, frac)def clear_pointer(self) -> None:if self._pointer is not None or self._start is not None:@@ -421,9 +361,9 @@ class _SelectWindow(QWidget):h = line * 2 + 2.0x = point.x() + _NUMBER_OFFSET.x()y = point.y() + _NUMBER_OFFSET.y()- if x + w > self.width() - _EDGE_GAP:+ if x + w > self.width() - EDGE_GAP:x = point.x() - _NUMBER_OFFSET.x() - w- if y + h > self.height() - _EDGE_GAP:+ if y + h > self.height() - EDGE_GAP:y = point.y() - _NUMBER_OFFSET.y() - hreturn QRectF(round(x), round(y), round(w), round(h))@@ -451,27 +391,27 @@ 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()- returnhole = self._hole()- if self._selection() is not None and hole is not None:- # Dragging: the surroundings stay clear, the selection turns grey.- painter.fillRect(hole, _SELECTION_TINT)- else:- dim = QPainterPath()- dim.addRect(full)- if hole is not None:- cut = QPainterPath()- cut.addRect(hole)- dim = dim.subtracted(cut)- painter.fillPath(dim, _DIM_IDLE)+ self._paint_veil(painter, full, hole)if hole is not None:self._paint_border(painter, hole)self._paint_numbers(painter)painter.end()+ def _paint_veil(self, painter: QPainter, full: QRectF, hole: QRectF | None) -> None:+ """Dim the screen around the hole; while dragging, tint the hole instead."""+ if self._selection() is not None and hole is not None:+ # Dragging: the surroundings stay clear, the selection turns grey.+ painter.fillRect(hole, SELECTION_TINT)+ return+ dim = QPainterPath()+ dim.addRect(full)+ if hole is not None:+ cut = QPainterPath()+ cut.addRect(hole)+ dim = dim.subtracted(cut)+ painter.fillPath(dim, DIM_IDLE)+def _paint_border(self, painter: QPainter, rect: QRectF) -> None:# Drawn without antialiasing so both hairlines land on whole pixels.r = rect.adjusted(0.5, 0.5, -0.5, -0.5)@@ -495,586 +435,10 @@ class _SelectWindow(QWidget):path.addText(QPointF(x, box.top() + 1.0 + ascent + i * line), self._font, text)painter.save()painter.setRenderHint(QPainter.RenderHint.Antialiasing)- halo = QPen(_HALO, 2.6)+ halo = QPen(HALO, 2.6)halo.setJoinStyle(Qt.PenJoinStyle.RoundJoin)painter.strokePath(path, halo)- 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)- bar.option_chosen.connect(self._set_option)- self._toolbar = bar- self._toolbar.set_tool(m.tool)- self._toolbar.set_color(m.color)- self._toolbar.set_width(m.width)- self._sync_options()- 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 _sync_options(self) -> None:- """The looks shown for the current tool (or the selected marking's kind)."""- bar = self._toolbar- if bar is None:- return- m = self._markup- kind = m.tool- selected = m.selected_shape()- if kind == mm.MOVE and selected is not None:- kind = selected.kind- if kind == mm.ARROW:- style = selected.style if selected is not None and selected.kind == mm.ARROW else ""- options = [(s, f"arrow_{s}") for s in mm.ARROW_STYLES]- bar.set_options(options, style or m.arrow_style, "arrow")- elif kind == mm.TEXT:- style = selected.style if selected is not None and selected.kind == mm.TEXT else ""- options = [(s, f"text_{s}") for s in mm.TEXT_STYLES]- bar.set_options(options, style or m.text_style, "text")- elif kind == mm.REDACT:- mode = selected.mode if selected is not None and selected.kind == mm.REDACT else ""- options = [(s, f"redact_{s}") for s in mm.REDACT_MODES]- bar.set_options(options, mode or m.redact_mode, "redact")- elif kind == mm.BACKGROUND:- options = [("off", "background_off")]- options += [(preset, "preset") for preset, _stops in mm.BACKGROUND_PRESETS]- chosen = m.background["preset"] if m.background else "off"- bar.set_options(options, chosen, "background")- else:- bar.set_options([], "")- self._place_toolbar()-- def _commit(self) -> None:- self._markup.history.push(self._markup.shapes)- self._sync_history()-- def _set_tool(self, kind: str) -> None:- self._commit_typing()- m = self._markup- m.tool = kind- if mm.grab_scope(kind) == "none":- m.selected = None- if kind == mm.BACKGROUND and m.background is None:- m.background = dict(mm.DEFAULT_BACKGROUND)- if self._toolbar is not None:- self._toolbar.set_tool(kind)- self._sync_options()- self._update_cursor(None)- self.update()-- def _set_color(self, colour: str) -> None:- m = self._markup- m.color = colour- target = m.typing or m.selected_shape()- 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, to: int | None = None) -> None:- m = self._markup- count = len(mm.WIDTHS)- if to is not None:- m.width_index = max(0, min(count - 1, to))- else:- index = m.width_index + step- m.width_index = index % count if wrap else max(0, min(count - 1, index))- target = m.typing or m.selected_shape()- if target is not None:- target.width = m.width- if target.kind == mm.TEXT:- target.size = mm.text_size(m.width)- elif target.kind == mm.COUNTER:- target.size = mm.counter_size(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 _set_option(self, group: str, value: str) -> None:- m = self._markup- selected = m.selected_shape()- changed = False- if group == "arrow":- m.arrow_style = value- if selected is not None and selected.kind == mm.ARROW:- selected.style, changed = value, True- elif group == "text":- m.text_style = value- target = m.typing or (selected if selected and selected.kind == mm.TEXT else None)- if target is not None:- target.style = value- changed = target is not m.typing- elif group == "redact":- m.redact_mode = value- if selected is not None and selected.kind == mm.REDACT:- selected.mode, changed = value, True- elif group == "background":- if value == "off":- m.background = None- else:- m.background = {**(m.background or mm.DEFAULT_BACKGROUND), "preset": value}- if changed:- self._commit()- self._sync_options()- 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- m.typing_index = None- state = m.history.redo() if redo else m.history.undo()- if state is not None:- m.shapes = state- m.selected = None- self._sync_history()- self._sync_options()- 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: dict | None = None- if m.shapes or m.background:- markup = {- "overlay": annotate.render_overlay(m.shapes, sel, self._scale())- if m.shapes- else "",- "hides": mm.hide_fractions(m.shapes, m.box()),- }- if m.background:- markup["background"] = dict(m.background)- self._owner.finish(self, frac, action=action, markup=markup)-- def _start_typing(self, at: mm.Point, *, index: int | None = None) -> None:- """Open the text box: a new one at ``at``, or the text at ``index``."""- m = self._markup- if index is not None:- m.typing = m.shapes.pop(index)- m.typing_index = index- m.typing_original = m.typing.copy()- else:- size = mm.text_size(m.width)- m.typing = mm.Shape(- mm.TEXT,- color=m.color,- width=m.width,- size=size,- style=m.text_style,- points=[(at[0], at[1] - size * 0.62)],- )- m.typing_index = None- m.selected = None- self._sync_options()- self.update()-- def _commit_typing(self, *, cancel: bool = False) -> None:- m = self._markup- shape, index = m.typing, m.typing_index- if shape is None:- return- m.typing, m.typing_index = None, None- original, m.typing_original = m.typing_original, None- if cancel:- if index is not None and original is not None:- # Esc on an edited text keeps it as it was.- m.shapes.insert(min(index, len(m.shapes)), original)- self.update()- return- shape.text = shape.text.rstrip()- if mm.is_meaningful(shape):- at = min(index, len(m.shapes)) if index is not None else len(m.shapes)- m.shapes.insert(at, shape)- # A finished text shows its points, like every fresh marking.- m.selected = at- self._commit()- self._sync_options()- elif index is not None:- self._commit() # emptied: the text is gone- self.update()-- def _text_at(self, point: mm.Point) -> int | None:- index = mm.shape_at(self._markup.shapes, point, annotate.qt_measure, areas=False)- if index is not None and self._markup.shapes[index].kind == mm.TEXT:- return index- return None-- def _grabbable(self, point: mm.Point) -> int | None:- """The marking a press at ``point`` would move with the current tool."""- m = self._markup- scope = mm.grab_scope(m.tool)- if scope in ("none", "grips"):- return None- index = mm.shape_at(m.shapes, point, annotate.qt_measure, areas=scope == "any")- if index is None or (m.tool == mm.TEXT and m.shapes[index].kind == mm.TEXT):- return None- return index-- 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.selected is not None:- m.selected = None- self._sync_options()- 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.selected is not None:- del m.shapes[m.selected]- m.selected = None- self._commit()- self._sync_options()- self.update()- elif key in _NUDGE and m.selected is not None:- dx, dy = _NUDGE[key]- step = 10.0 if mods & Qt.KeyboardModifier.ShiftModifier else 1.0- m.shapes[m.selected] = mm.translated(m.shapes[m.selected], dx * step, dy * step)- self._commit()- self.update()- elif not ctrl and Qt.Key.Key_1 <= key <= Qt.Key.Key_5:- self._step_width(0, to=int(key) - int(Qt.Key.Key_1))- 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._commit_typing(cancel=True)- return- if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):- if mods & Qt.KeyboardModifier.ShiftModifier:- shape.text += "\n"- else:- self._commit_typing()- return- 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:- self._commit_typing(cancel=True)- elif not m.shapes:- self._end_markup()- return- self.update()- return- if event.button() != Qt.MouseButton.LeftButton:- return- self._commit_typing()- selected = m.selected_shape()- if selected is not None and mm.grab_scope(m.tool) != "none":- grip = mm.grip_at(selected, point, mm.HANDLE_GRAB_PX + 1, annotate.qt_measure)- if grip is not None:- m.drag, m.original, m.moved = ("grip", grip), selected.copy(), False- return- handle = mm.handle_at(m.box(), point)- if handle is not None:- m.drag = ("area", handle)- return- grabbed = self._grabbable(point)- if grabbed is not None:- m.selected = grabbed- m.drag, m.last, m.moved = ("move", None), p, False- self._sync_options()- self.update()- return- if m.selected is not None:- m.selected = None- self._sync_options()- inside = m.sel is not None and m.sel.contains(p)- if m.tool in (mm.MOVE, mm.BACKGROUND):- if not inside and not m.shapes:- self._end_markup()- self.mousePressEvent(event)- return- 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- if m.tool == mm.TEXT:- index = self._text_at(point)- self._start_typing(point, index=index)- return- if m.tool == mm.COUNTER:- m.shapes.append(- mm.Shape(- mm.COUNTER,- color=m.color,- width=m.width,- size=mm.counter_size(m.width),- points=[point],- number=mm.next_counter(m.shapes),- )- )- m.selected = len(m.shapes) - 1- 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],- style=m.arrow_style if m.tool == mm.ARROW else "",- mode=m.redact_mode if m.tool == mm.REDACT else "",- )- self._update_markup_area()-- def _markup_move(self, event) -> None:- m = self._markup- p = event.position()- point = (p.x(), p.y())- drag = m.drag- if drag is not None and drag[0] == "area":- sel = mm.resize(m.box(), drag[1] or "se", point, (self.width(), self.height()))- m.sel = QRectF(*sel)- self._place_toolbar()- self.update()- return- if drag is not None and drag[0] == "grip" and m.selected is not None and m.original:- m.shapes[m.selected] = mm.reshape(- m.original, drag[1] or "se", point, annotate.qt_measure- )- m.moved = True- self._update_markup_area()- return- if drag is not None and drag[0] == "move" and m.selected is not None and m.last:- delta = p - m.last- m.shapes[m.selected] = mm.translated(m.shapes[m.selected], 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- m.original = None- if drag is not None and drag[0] in ("move", "grip") 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()- # Every fresh marking shows its points at once (the previous one- # loses them), so it can be moved and reshaped right away.- m.selected = len(m.shapes) - 1- self._sync_options()- self._update_markup_area()-- def mouseDoubleClickEvent(self, event) -> None: # noqa: N802- """Double-click a text with the select or text tool to change it."""- m = self._markup- if m.sel is None or m.typing is not None or m.tool not in (mm.MOVE, mm.TEXT):- return- p = event.position()- index = self._text_at((p.x(), p.y()))- if index is not None:- m.drag = None- self._start_typing((p.x(), p.y()), index=index)-- 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:- selected = m.selected_shape()- if selected is not None and mm.grab_scope(m.tool) != "none":- grip = mm.grip_at(selected, point, mm.HANDLE_GRAB_PX + 1, annotate.qt_measure)- if grip is not None:- self.setCursor(_GRIP_CURSORS[mm.grip_cursor(grip)])- return- handle = mm.handle_at(m.box(), point)- if handle is not None:- self.setCursor(_HANDLE_CURSORS[handle])- return- if self._grabbable(point) is not None:- self.setCursor(Qt.CursorShape.SizeAllCursor)- return- if m.tool == mm.TEXT:- self.setCursor(Qt.CursorShape.IBeamCursor)- elif m.tool in (mm.MOVE, mm.BACKGROUND):- 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))- if m.background:- annotate.paint_background_frame(painter, sel, m.background)- live = [*m.shapes, *(s for s in (m.drawing,) if s is not None)]- painter.save()- painter.setClipRect(sel, Qt.ClipOperation.IntersectClip)- for shape in (s for s in live if s.kind == mm.REDACT):- annotate.paint_shape(painter, shape, hide_source=self._patches)- for shape in (s for s in live if s.kind != mm.REDACT):- annotate.paint_shape(painter, shape)- annotate.paint_spotlights(painter, live, sel)- painter.restore()- if m.typing is not None:- labels = annotate.labels_for(self._owner.language)- annotate.paint_typing(painter, m.typing, labels["placeholder"], caret=True)- selected = m.selected_shape()- if selected is not None:- annotate.paint_picked(painter, selected)- 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.fillPath(path, INK)painter.restore()@@ -1091,8 +455,12 @@ class Picker(QObject):self._started = Falseself._windows: list[_SelectWindow] = []self._focused: _SelectWindow | None = None- #: The window whose area is being marked up; the others stay inert.+ #: The window being marked up; the others stay inert until it is clear.self.marking: _SelectWindow | None = None+ #: "Adjust the area before taking it": a released area stays to be+ #: resized and marked, instead of being taken at once.+ self.keep_area = False+ self._marking_sent = Falseself._done = Falsedef start(self) -> None:@@ -1100,6 +468,7 @@ class Picker(QObject):returnself._started = Trueself._done = False+ self._marking_sent = Falsescreens = QGuiApplication.screens()# Freeze every screen BEFORE any overlay window exists.frozen = {id(s): self._grab(s) for s in screens}@@ -1112,15 +481,19 @@ class Picker(QObject):for win in self._windows:win.show()if self._focused is not None:+ self._focused.arm()self._focused.raise_()self._focused.activateWindow()self._focused.setFocus()+ _claim_keyboard(self._focused)self._app.processEvents()_emit({"event": wire.EVENT_READY})def make_window(self, screen, frozen: QPixmap | None) -> _SelectWindow:- """Allow capture modes to provide their own selection completion behavior."""- return _SelectWindow(screen, frozen, self)+ """The appshot's window; capture modes provide their own."""+ from dodaios.appshot.picker.markup_window import MarkupWindow # noqa: PLC0415++ return MarkupWindow(screen, frozen, self)@staticmethoddef _grab(screen) -> QPixmap | None:@@ -1134,28 +507,44 @@ class Picker(QObject):"""The pointer moved onto ``window``: only that screen shows the numbers."""if self._focused is window or self.marking is not None:return+ previous = self._focusedfor other in self._windows:if other is not window:other.clear_pointer()self._focused = window+ if previous is not None:+ previous.disarm()+ window.adopt(previous)+ window.arm()- def begin_markup(self, window: _SelectWindow) -> None:- """An area is chosen on ``window``: the toolbar is up, keys go there."""+ def lock(self, window: _SelectWindow) -> None:+ """``window`` holds markings: the toolbar stays there, keys go there."""+ if self.marking is window:+ returnself.marking = windowself._focused = windowfor other in self._windows:if other is not window:other.clear_pointer()+ other.disarm()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})+ if not self._marking_sent:+ self._marking_sent = True+ # 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:+ def unlock(self, window: _SelectWindow) -> None:+ """``window`` holds nothing any more: the toolbar may follow the pointer."""if self.marking is window:self.marking = None+ def set_keep_area(self, keep: bool) -> None:+ """The user flipped "adjust before taking"; the parent remembers it."""+ self.keep_area = bool(keep)+ _emit({"event": wire.EVENT_OPTION, "keep_area": self.keep_area})+def finish(self,window: _SelectWindow | None,@@ -1205,6 +594,7 @@ class Picker(QObject):cmd = payload.get("cmd")if cmd == wire.CMD_START and self._resident and not self._started:self.language = str(payload.get("language") or "en")+ self.keep_area = payload.get("keep_area") is Trueself.start()self.set_layout(payload.get("monitors", []), payload.get("windows", []))elif cmd == wire.CMD_QUIT:@@ -1271,4 +661,4 @@ def run(language: str = "en", *, resident: bool = False) -> int:return app.exec()-__all__ = ["Picker", "crosshair_cursor", "run"]+__all__ = ["Picker", "crosshair_cursor", "number_font", "run"]diff --git a/dodaios/appshot/picker_host.py b/dodaios/appshot/picker_host.pyindex ad9679cf9a..5cc8bb43f6 100644--- a/dodaios/appshot/picker_host.py+++ b/dodaios/appshot/picker_host.py@@ -85,15 +85,19 @@ class PickerHost:await reader # reap closes stdout, including a stuck startupraise- async def pick(self, timeout_s: float, language: str) -> tuple[Any, int | None, bool]:+ async def pick(+ self, timeout_s: float, language: str, *, keep_area: bool = False+ ) -> tuple[Any, int | None, bool]:async with self._lock:self._active = asyncio.current_task()try:- return await self._pick(timeout_s, language)+ return await self._pick(timeout_s, language, keep_area)finally:self._active = None- async def _pick(self, timeout_s: float, language: str) -> tuple[Any, int | None, bool]:+ async def _pick(+ self, timeout_s: float, language: str, keep_area: bool+ ) -> tuple[Any, int | None, bool]:started = time.perf_counter()proc = await self._ensure()try:@@ -107,7 +111,9 @@ class PickerHost:timed_out = Falsetry:await asyncio.to_thread(- self._send, proc, {"cmd": wire.CMD_START, "language": language, **layout}+ self._send,+ proc,+ {"cmd": wire.CMD_START, "language": language, "keep_area": keep_area, **layout},)loop = asyncio.get_running_loop()escape = loop.create_task(region._escape_cancels(proc), name="appshot-region-esc")@@ -120,8 +126,12 @@ class PickerHost:"appshot: picker visible in %.1f ms", (time.perf_counter() - started) * 1000)+ def option(payload: dict[str, Any]) -> None:+ if isinstance(payload.get("keep_area"), bool):+ loop.call_soon_threadsafe(_remember_keep_area, payload["keep_area"])+reader = asyncio.create_task(- asyncio.to_thread(region._read_result, proc, marking, ready)+ asyncio.to_thread(region._read_result, proc, marking, ready, option))try:payload = await asyncio.wait_for(asyncio.shield(reader), timeout_s)@@ -149,6 +159,29 @@ class PickerHost:await self._dispose()+#: Saves of the "adjust before taking" switch still being written.+_saving: set[asyncio.Task] = set()+++def _remember_keep_area(keep: bool) -> None:+ """Write the switch into ``[appshot].region_keep_area`` off the event loop."""++ def write() -> None:+ from dodaios.core.config_writer import set_appshot_settings # noqa: PLC0415++ set_appshot_settings({"region_keep_area": keep})++ async def save() -> None:+ try:+ await asyncio.to_thread(write)+ except Exception: # noqa: BLE001 - the switch still holds for this selection+ log.warning("appshot: could not remember the area switch", exc_info=True)++ task = asyncio.get_running_loop().create_task(save(), name="appshot-keep-area")+ _saving.add(task)+ task.add_done_callback(_saving.discard)++_host: PickerHost | None = Nonediff --git a/dodaios/appshot/region.py b/dodaios/appshot/region.pyindex baa3b74f8e..67efc3920b 100644--- a/dodaios/appshot/region.py+++ b/dodaios/appshot/region.py@@ -80,6 +80,10 @@ class RegionUnavailable(RuntimeError):_language: contextvars.ContextVar[str] = contextvars.ContextVar("appshot_picker_language", default="en")+#: "Adjust the area before taking it" for the picker being started.+_keep_area: contextvars.ContextVar[bool] = contextvars.ContextVar(+ "appshot_picker_keep_area", default=False+)#: 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).@@ -316,11 +320,13 @@ def _spawn(language: str = "en", *, resident: bool = False) -> subprocess.Popen[def _read_result(proc: subprocess.Popen[str], on_marking: Callable[[], None] | None = None,on_ready: Callable[[], None] | None = None,+ on_option: Callable[[dict[str, Any]], 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.+ ``on_marking`` runs (on this reader thread) once the user has marked+ something, so the picker's own Esc may close a text box from then on;+ ``on_option`` with each switch the user flips in the toolbar."""from dodaios.appshot import picker as wire # noqa: PLC0415@@ -337,6 +343,9 @@ def _read_result(if event == wire.EVENT_MARKING and on_marking is not None:with contextlib.suppress(Exception): # a lost hint only keeps the global Escon_marking()+ if event == wire.EVENT_OPTION and on_option is not None:+ with contextlib.suppress(Exception): # a lost switch is only not remembered+ on_option(payload)return None@@ -420,11 +429,17 @@ def grab_preview(screen: Any) -> Any | None:async def pick_region(- *, timeout_s: float = PICK_TIMEOUT_S, language: str = "en", trace_id: UUID | None = None,+ *,+ timeout_s: float = PICK_TIMEOUT_S,+ language: str = "en",+ keep_area: bool = False,+ trace_id: UUID | None = None,) -> 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``).+ ``language`` is the toolbar's tooltip language (``[ui].language``);+ ``keep_area`` keeps a released area to adjust it before it is taken+ (``[appshot].region_keep_area``), instead of taking it at once.Raises :class:`RegionUnavailable` when no picker can run on this host."""global _picking@@ -441,9 +456,11 @@ async def pick_region(await require_screen_recording_async("appshot", trace_id=trace_id)token = _language.set(language or "en")+ keep_token = _keep_area.set(bool(keep_area))try:payload, code, timed_out = await _run_picker(timeout_s)finally:+ _keep_area.reset(keep_token)_language.reset(token)finally:_picking = False@@ -474,7 +491,9 @@ async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | Nofrom dodaios.appshot.picker_host import get_picker_hosttry:- return await get_picker_host().pick(timeout_s, _language.get())+ return await get_picker_host().pick(+ timeout_s, _language.get(), keep_area=_keep_area.get()+ )except (OSError, TimeoutError) as exc:log.warning("appshot: area picker could not be started", exc_info=True)raise RegionUnavailable("The selection overlay could not be started.") from excdiff --git a/dodaios/appshot/service.py b/dodaios/appshot/service.pyindex 0a2512ee76..2f2228969e 100644--- a/dodaios/appshot/service.py+++ b/dodaios/appshot/service.py@@ -128,7 +128,12 @@ async def take_appshot(# be wallpaper only, so the area is then grabbed live after the# picker has asked macOS just in time.frozen = None if issue is not None else await service.freeze_screens()- picked = await _pick_area(service, _language(config), trace_id=capture_trace_id)+ picked = await _pick_area(+ service,+ _language(config),+ keep_area=bool(getattr(config.appshot, "region_keep_area", False)),+ trace_id=capture_trace_id,+ )if isinstance(picked, AppshotResult):return pickedbbox, selection = picked@@ -353,7 +358,11 @@ async def _finish_action(action: str, shot: Appshot, bus: Any | None) -> None:async def _pick_area(- service: Any, language: str = "en", *, trace_id: uuid.UUID | None = None,+ service: Any,+ language: str = "en",+ *,+ keep_area: bool = False,+ trace_id: uuid.UUID | None = None,) -> tuple[Any, Any] | AppshotResult:"""Run the area picker; ``(rectangle, selection)``, or the refusal to return."""from dodaios.appshot.region import ( # noqa: PLC0415@@ -364,7 +373,7 @@ async def _pick_area(from dodaios.platform.screen_access import ScreenCaptureRefusedtry:- selection = await pick_region(language=language, trace_id=trace_id)+ selection = await pick_region(language=language, keep_area=keep_area, trace_id=trace_id)except ScreenCaptureRefused as exc:log.info("appshot: area selection refused (%s)", exc.reason or "capture_permission")return AppshotResult(diff --git a/dodaios/core/config.py b/dodaios/core/config.pyindex dc2b8bfb04..2a8159af2a 100644--- a/dodaios/core/config.py+++ b/dodaios/core/config.py@@ -2718,6 +2718,12 @@ class AppshotConfig(BaseModel):#: collides with no app or OS shortcut.region_hotkey: str = "shift+shift"+ #: Off: releasing the area drag takes the appshot at once, with whatever+ #: was marked on the screen before it. On: the area stays with resize+ #: handles to adjust and mark it, and Enter or a double-click takes it.+ #: The picker's toolbar flips it (read by ``dodaios.appshot.service``).+ region_keep_area: bool = False+#: One shortcut selects a recording area; pressing it again stops and saves.recording_hotkey: str = "ctrl+shift+9"diff --git a/dodaios/core/config_writer.py b/dodaios/core/config_writer.pyindex 06f29ea750..366fbecd8d 100644--- a/dodaios/core/config_writer.py+++ b/dodaios/core/config_writer.py@@ -1006,9 +1006,9 @@ def set_screen_context_settings(#: The master switch is ``[screen_context].enabled``, written by the setter above.APPSHOT_SETTING_KEYS: frozenset[str] = frozenset({"keep_newest",- "hotkey", "region_hotkey", "recording_hotkey", "target", "sound", "effect", "card_seconds",- "library", "copy_to_clipboard", "recording_resolution", "recording_fps", "recording_bitrate_mbps",- "recording_system_audio"}+ "hotkey", "region_hotkey", "region_keep_area", "recording_hotkey", "target", "sound",+ "effect", "card_seconds", "library", "copy_to_clipboard", "recording_resolution",+ "recording_fps", "recording_bitrate_mbps", "recording_system_audio"})diff --git a/dodaios/ui/web/appshot_routes.py b/dodaios/ui/web/appshot_routes.pyindex ccdfbd6266..fd0396b470 100644--- a/dodaios/ui/web/appshot_routes.py+++ b/dodaios/ui/web/appshot_routes.py@@ -54,6 +54,7 @@ class SettingsPatch(BaseModel):enabled: bool | None = Nonehotkey: str | None = Field(default=None, max_length=64)region_hotkey: str | None = Field(default=None, max_length=64)+ region_keep_area: bool | None = Nonerecording_hotkey: str | None = Field(default=None, max_length=64)recording_resolution: Literal["720p", "1080p", "1440p", "2160p", "native"] | None = Nonerecording_fps: Literal[30, 60, 120] | None = None@@ -148,6 +149,7 @@ def _settings_payload() -> dict[str, Any]:"enabled": bool(config.screen_context.enabled),"hotkey": hotkeys["window"],"region_hotkey": hotkeys["region"],+ "region_keep_area": bool(getattr(block, "region_keep_area", False)),"recording_hotkey": hotkeys["recording"],**{f"recording_{key}": valuefor key, value in RecordingOptions.from_config(block).model_dump().items()},diff --git a/tests/unit/appshot/test_appshot_markup.py b/tests/unit/appshot/test_appshot_markup.pyindex ca62ae7864..0bd24d671f 100644--- a/tests/unit/appshot/test_appshot_markup.py+++ b/tests/unit/appshot/test_appshot_markup.py@@ -125,6 +125,26 @@ def test_the_toolbar_docks_below_then_above_then_inside_and_stays_on_screen() ->assert x == 1920 - 800 - 10+def test_the_toolbar_waits_at_the_top_and_steps_aside_for_a_kept_area() -> None:+ screen = (1920.0, 1080.0)+ bar = (800.0, 40.0)+ assert mm.toolbar_home(bar, screen) == (560.0, 12.0)+ assert mm.toolbar_home((2000.0, 40.0), screen)[0] == 12.0, "too wide: from the left edge"+ assert mm.toolbar_spot(None, bar, screen) == (560.0, 12.0)+ # An area clear of the top keeps the toolbar where it was ...+ assert mm.toolbar_spot((100, 300, 400, 300), bar, screen) == (560.0, 12.0)+ # ... one under it moves the toolbar out of the way.+ assert mm.toolbar_spot((500, 0, 900, 400), bar, screen) == (550.0, 410.0)+++def test_tab_swaps_the_area_and_the_last_drawing_tool() -> None:+ assert mm.other_tool(mm.AREA, mm.PEN) == mm.PEN+ assert mm.other_tool(mm.PEN, mm.PEN) == mm.AREA+ assert mm.other_tool(mm.TEXT, mm.PEN) == mm.AREA+ # The area tool takes hold of markings like a drawing tool does.+ assert mm.grab_scope(mm.AREA) == "shapes"++def test_hide_patches_leave_as_fractions_of_the_area_clipped_to_it() -> None:sel = (100.0, 100.0, 200.0, 100.0)shapes = [@@ -206,7 +226,7 @@ def test_the_picker_offers_the_full_editors_tools_keys_and_presets() -> None:Path(__file__).resolve().parents[3] / "dodaios/ui/web/frontend/src/lib/appshotEditorModel.ts").read_text(encoding="utf-8")keys = dict(re.findall(r'\{ tool: "(\w+)", key: "(\w)" \}', model))- keys.pop("crop") # the picker's area handles are its crop+ keys[mm.AREA] = keys.pop("crop") # the picker's area is its crop, on the same keyassert {tool: key.upper() for tool, key in keys.items()} == mm.TOOL_KEYSpresets = re.findall(r'\{ id: "(\w+)", stops: \[([^\]]+)\] \}', model)parsed = tuple((pid, tuple(re.findall(r'"(#[0-9a-f]{6})"', stops))) for pid, stops in presets)@@ -289,6 +309,21 @@ def test_the_marking_event_reaches_the_reader_before_the_selection() -> None:assert payload == {"event": "selection", "cancelled": True}+def test_a_flipped_switch_reaches_the_reader() -> None:+ lines = [+ encode({"event": "option", "keep_area": True}),+ encode({"event": "selection", "cancelled": True}),+ ]++ class Proc:+ stdout = iter(lines)++ seen: list[dict] = []+ payload = region._read_result(Proc(), None, None, seen.append) # type: ignore[arg-type]+ assert seen == [{"event": "option", "keep_area": True}]+ assert payload == {"event": "selection", "cancelled": True}++# ------------------------------------------------------------- the burn-indiff --git a/tests/unit/appshot/test_picker_host.py b/tests/unit/appshot/test_picker_host.pyindex 69318a41a8..cb0e0b19aa 100644--- a/tests/unit/appshot/test_picker_host.py+++ b/tests/unit/appshot/test_picker_host.py@@ -94,6 +94,32 @@ def host(monkeypatch):return picker_host.PickerHost(), children+async def test_the_area_switch_goes_out_with_start_and_comes_back_saved(host, monkeypatch):+ owner, children = host+ saved: list[dict] = []+ from dodaios.core import config_writer++ monkeypatch.setattr(config_writer, "set_appshot_settings", saved.append)+ await owner.prewarm()+ proc = children[0]+ proc.finish = False+ try:+ task = asyncio.create_task(owner.pick(5, "en", keep_area=True))+ await asyncio.to_thread(proc.started.wait, 2)+ assert proc.commands[-1]["keep_area"] is True+ proc.stdout.emit({"event": wire.EVENT_OPTION, "keep_area": False})+ proc.stdout.emit({"event": wire.EVENT_SELECTION, "cancelled": True})+ payload, _code, _timed_out = await task+ assert payload["cancelled"]+ for _ in range(50):+ if saved:+ break+ await asyncio.sleep(0.02)+ assert saved == [{"region_keep_area": False}]+ finally:+ await owner.close()++async def test_standby_never_requests_pixels_and_repeated_picks_reuse_process(host):owner, children = hosttry:diff --git a/tests/unit/appshot/test_picker_standby.py b/tests/unit/appshot/test_picker_standby.pyindex 7abdeec72c..1411767322 100644--- a/tests/unit/appshot/test_picker_standby.py+++ b/tests/unit/appshot/test_picker_standby.py@@ -6,14 +6,14 @@ import pytestpytest.importorskip("PySide6.QtWidgets")-from dodaios.appshot.picker import renderer # noqa: E402+from dodaios.appshot.picker import markup_window, renderer # noqa: E402def test_release_capture_drops_frozen_pixels_and_blur_cache():window = SimpleNamespace(_frozen=object(), _patches=object(), _markup=object(), _scale=lambda: 1)- renderer._SelectWindow.release_capture(window)+ markup_window.MarkupWindow.release_capture(window)assert window._frozen is Noneassert window._patches._frozen is Noneassert window._patches._cache == {}diff --git a/tests/unit/appshot/test_picker_upfront_toolbar.py b/tests/unit/appshot/test_picker_upfront_toolbar.pynew file mode 100644index 0000000000..91c7a34b7c--- /dev/null+++ b/tests/unit/appshot/test_picker_upfront_toolbar.py@@ -0,0 +1,293 @@+"""The area picker opens with its marking toolbar up and takes the area on release.++Drives the real picker window on Qt's offscreen platform: the toolbar is+there before anything is chosen, markings drawn first ride along with the+area, releasing the drag takes the appshot without a confirm step, and+"adjust before taking" keeps the old adjust-then-Enter flow. Auto-skips+without PySide6 (a [desktop] extra).+"""++from __future__ import annotations++import importlib.util+import os++import pytest++pytestmark = 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++[email protected](scope="module")+def qt():+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ from PySide6.QtWidgets import QApplication # noqa: PLC0415++ app = QApplication.instance() or QApplication([])+ yield app+++def picker(qt, monkeypatch):+ from PySide6.QtGui import QColor, QGuiApplication, QPixmap # noqa: PLC0415++ from dodaios.appshot.picker import renderer # noqa: PLC0415+ from dodaios.appshot.picker.markup_window import MarkupWindow # noqa: PLC0415++ events: list[dict] = []+ monkeypatch.setattr(renderer, "_emit", events.append)+ owner = renderer.Picker(qt, language="en", resident=True)+ screen = QGuiApplication.primaryScreen()++ def window() -> MarkupWindow:+ frozen = QPixmap(W, H)+ frozen.fill(QColor(40, 90, 160))+ win = MarkupWindow(screen, frozen, owner)+ win.setGeometry(0, 0, W, H)+ owner._windows.append(win)+ return win++ first = window()+ owner._started = True+ owner._focused = first+ first.show()+ first.arm()+ yield owner, first, window, events+ if not owner._done:+ owner.finish(None, None)+++def _mouse(win, kind: str, x: float, y: float, button=None, modifiers=None) -> None:+ from PySide6.QtCore import QEvent, QPointF, Qt # noqa: PLC0415+ from PySide6.QtGui import QMouseEvent # noqa: PLC0415++ button = button or Qt.MouseButton.LeftButton+ modifiers = modifiers or Qt.KeyboardModifier.NoModifier+ types = {+ "press": QEvent.Type.MouseButtonPress,+ "move": QEvent.Type.MouseMove,+ "release": QEvent.Type.MouseButtonRelease,+ "double": QEvent.Type.MouseButtonDblClick,+ }+ if kind == "move":+ changed, held = Qt.MouseButton.NoButton, button+ elif kind == "release":+ changed, held = button, Qt.MouseButton.NoButton+ else:+ changed, held = button, button+ event = QMouseEvent(types[kind], QPointF(x, y), QPointF(x, y), changed, held, modifiers)+ {+ "press": win.mousePressEvent,+ "move": win.mouseMoveEvent,+ "release": win.mouseReleaseEvent,+ "double": win.mouseDoubleClickEvent,+ }[kind](event)+++def _drag(win, a: tuple[float, float], b: tuple[float, float], **kw) -> None:+ _mouse(win, "press", *a, **kw)+ _mouse(win, "move", (a[0] + b[0]) / 2, (a[1] + b[1]) / 2, **kw)+ _mouse(win, "move", *b, **kw)+ _mouse(win, "release", *b, **kw)+++def _key(win, key, text: str = "", modifiers=None) -> None:+ from PySide6.QtCore import QEvent, Qt # noqa: PLC0415+ from PySide6.QtGui import QKeyEvent # noqa: PLC0415++ win.keyPressEvent(+ QKeyEvent(QEvent.Type.KeyPress, key, modifiers or Qt.KeyboardModifier.NoModifier, text)+ )+++def _selection(events: list[dict]) -> dict | None:+ return next((e for e in events if e.get("event") == "selection"), None)+++def test_the_toolbar_is_up_before_any_area_is_chosen(picker) -> None:+ from dodaios.appshot.picker import markup_model as mm # noqa: PLC0415++ owner, win, _window, events = picker+ bar = win._toolbar+ assert bar is not None and bar.isVisible(), "the toolbar shows the moment the overlay opens"+ assert win._markup.tool == mm.AREA, "the area tool is the one in hand"+ assert bar._tool_buttons[mm.AREA].isChecked()+ assert bar.y() == 12, "it sits at the top of the screen, not under a selection"+ assert abs((bar.x() + bar.width() / 2) - W / 2) <= 1, "centred"+ assert _selection(events) is None+++def test_releasing_the_area_drag_takes_the_appshot_at_once(picker) -> None:+ owner, win, _window, events = picker+ _drag(win, (100, 120), (300, 270))+ selection = _selection(events)+ assert selection is not None, "no confirm step: the release takes it"+ assert selection["action"] == "done"+ assert selection["rect"] == pytest.approx([100 / W, 120 / H, 200 / W, 150 / H])+ assert "markup" not in selection+++def test_markings_drawn_first_ride_along_with_the_area(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ from dodaios.appshot.picker import markup_model as mm # noqa: PLC0415++ owner, win, _window, events = picker+ _key(win, Qt.Key.Key_A, "a")+ assert win._markup.tool == mm.ARROW+ _drag(win, (150, 150), (260, 210))+ assert len(win._markup.shapes) == 1+ # The parent drops its global Esc once something is marked.+ assert {"event": "marking"} in events+ assert _selection(events) is None, "drawing never takes the appshot"+ _key(win, Qt.Key.Key_Tab)+ assert win._markup.tool == mm.AREA, "Tab goes back to the area tool"+ _drag(win, (100, 100), (400, 300))+ selection = _selection(events)+ assert selection is not None+ assert selection["markup"]["overlay"], "the arrow is burnt into the appshot"+++def test_ctrl_starts_the_area_right_over_a_marking(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ owner, win, _window, events = picker+ _key(win, Qt.Key.Key_F, "f")+ _drag(win, (100, 100), (300, 300))+ _key(win, Qt.Key.Key_K, "k")+ # A plain press on the filled box would take hold of it ...+ _drag(win, (200, 200), (220, 220))+ assert _selection(events) is None+ assert win._markup.shapes[0].points[0] == pytest.approx((120, 120))+ # ... with Ctrl it starts the area there instead.+ _drag(win, (150, 150), (350, 330), modifiers=Qt.KeyboardModifier.ControlModifier)+ assert _selection(events) is not None+++def test_space_takes_the_whole_screen(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ owner, win, _window, events = picker+ _key(win, Qt.Key.Key_Space, " ")+ selection = _selection(events)+ assert selection is not None and selection["rect"] == pytest.approx([0, 0, 1, 1])+++def test_keep_area_leaves_the_area_to_adjust_then_enter_takes_it(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ owner, win, _window, events = picker+ owner.keep_area = True+ _drag(win, (100, 100), (300, 250))+ assert _selection(events) is None, "the area stays"+ assert win._markup.sel is not None+ assert win._toolbar is not None and win._toolbar.isVisible()+ # Its handles still resize it.+ _drag(win, (300, 250), (400, 300))+ _key(win, Qt.Key.Key_Return)+ selection = _selection(events)+ assert selection is not None+ assert selection["rect"] == pytest.approx([100 / W, 100 / H, 300 / W, 200 / H])+++def test_keep_area_double_click_in_the_area_takes_it(picker) -> None:+ owner, win, _window, events = picker+ owner.keep_area = True+ _drag(win, (100, 100), (300, 250))+ _mouse(win, "double", 200, 180)+ assert _selection(events) is not None+++def test_flipping_the_switch_reports_it_to_the_parent(picker) -> None:+ owner, win, _window, events = picker+ assert win._toolbar is not None+ win._toolbar._keep.click()+ assert owner.keep_area is True+ assert {"event": "option", "keep_area": True} in events+ win._toolbar._keep.click()+ assert {"event": "option", "keep_area": False} in events+++def test_right_click_removes_a_marking_then_closes(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ owner, win, _window, events = picker+ _key(win, Qt.Key.Key_R, "r")+ _drag(win, (100, 100), (300, 300))+ assert len(win._markup.shapes) == 1+ right = Qt.MouseButton.RightButton+ _mouse(win, "press", 100, 200, button=right)+ assert win._markup.shapes == [], "a right-click on a marking removes it"+ assert _selection(events) is None+ _mouse(win, "press", 500, 500, button=right)+ assert _selection(events) == {"event": "selection", "cancelled": True}+++def test_esc_closes_a_text_box_before_it_closes_the_overlay(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ owner, win, _window, events = picker+ _key(win, Qt.Key.Key_T, "t")+ _mouse(win, "press", 200, 200)+ assert win._markup.typing is not None+ _key(win, Qt.Key.Key_H, "H")+ _key(win, Qt.Key.Key_I, "i")+ _key(win, Qt.Key.Key_Return)+ assert [s.text for s in win._markup.shapes] == ["Hi"]+ _mouse(win, "press", 400, 400)+ _key(win, Qt.Key.Key_Escape)+ assert win._markup.typing is None and _selection(events) is None+ _key(win, Qt.Key.Key_Escape) # deselects the text+ _key(win, Qt.Key.Key_Escape)+ assert _selection(events) == {"event": "selection", "cancelled": True}+++def test_the_toolbar_follows_the_pointer_until_something_is_marked(picker) -> None:+ from PySide6.QtCore import Qt # noqa: PLC0415++ from dodaios.appshot.picker import markup_model as mm # noqa: PLC0415++ owner, first, window, events = picker+ second = window()+ second.show()+ _key(first, Qt.Key.Key_D, "d")+ owner.focus_on(second)+ assert first._toolbar is not None and not first._toolbar.isVisible()+ assert second._toolbar is not None and second._toolbar.isVisible()+ assert second._markup.tool == mm.PEN, "the chosen tool comes along"+ _drag(second, (50, 50), (120, 90))+ assert owner.marking is second+ owner.focus_on(first)+ assert second._toolbar.isVisible(), "markings keep the toolbar on their screen"+ _mouse(first, "press", 10, 10)+ assert first._markup.drawing is None, "the other screen waits"+++def test_the_plain_chooser_still_finishes_on_release(qt, monkeypatch) -> None:+ """The screen recorder's window has no toolbar and still ends on release."""+ from PySide6.QtGui import QGuiApplication, QPixmap # noqa: PLC0415++ from dodaios.appshot.picker import renderer # noqa: PLC0415++ finished: list[tuple] = []++ class Owner:+ marking = None+ language = "en"++ def focus_on(self, _window) -> None:+ return None++ def finish(self, window, frac) -> None:+ finished.append((window, frac))++ win = renderer._SelectWindow(QGuiApplication.primaryScreen(), QPixmap(W, H), Owner())+ win.setGeometry(0, 0, W, H)+ win.arm()+ _drag(win, (0, 0), (W / 2, H / 2))+ assert finished and finished[0][1] == pytest.approx((0, 0, 0.5, 0.5))+ win.close()