Skip to content

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

12.4 KB
Raw Blame
"""What the corner card can do besides opening the editor.

The card (a PySide6 window in the indicator sidecar) shows Copy, Save and
Copy text on hover. The sidecar only reports the press; the work happens here
in the main process, on the card's own appshot (every card in the corner
stack names its appshot id; the last appshot when none is named):

* **Copy** goes through :mod:`dodaios.platform.clipboard_image`, which owns the
  clipboard natively on every OS. A Qt clipboard in the sidecar would lose the
  picture on Linux the moment the sidecar quits.
* **Save** writes a PNG into ``~/Downloads``, like every other save in the app.
* **Copy text** puts the appshot's scrubbed on-screen text (``ui_text``) on
  the clipboard for reuse in other apps.

And when the editor closes, :func:`return_to_corner` brings the (edited)
appshot back to the bottom of the corner stack, so it stays at hand.
Every function here returns a result and never raises.
"""

from __future__ import annotations

import asyncio
import base64
import io
import logging
import sys
import time
from pathlib import Path
from typing import Any

log = logging.getLogger(__name__)

#: Card wording — app chrome, so it follows ``[ui].language`` like the hint.
_LABELS: dict[str, dict[str, str]] = {
    "en": {
        "edit": "Edit",
        "copy": "Copy",
        "save": "Save",
        "close": "Close",
        "pin": "Keep on screen",
        "unpin": "Unpin",
        "copy_text": "Copy text",
        "copied": "Copied",
        "saved": "Saved to Downloads",
        "failed": "That did not work",
        "no_access": "No permission to save in Downloads",
        "no_access_mac": "Allow Downloads in Privacy & Security > Files and Folders",
        "gone": "No longer kept",
        "text_copied": "Text copied",
        "no_text": "No text found",
    },
    "de": {
        "edit": "Bearbeiten",  # i18n-allow: product UI string
        "copy": "Kopieren",  # i18n-allow: product UI string
        "save": "Speichern",  # i18n-allow: product UI string
        "close": "Schließen",  # i18n-allow: product UI string
        "pin": "Am Bildschirm halten",  # i18n-allow: product UI string
        "unpin": "Nicht mehr halten",  # i18n-allow: product UI string
        "copy_text": "Text kopieren",  # i18n-allow: product UI string
        "copied": "Kopiert",  # i18n-allow: product UI string
        "saved": "In Downloads gespeichert",  # i18n-allow: product UI string
        "failed": "Das hat nicht geklappt",  # i18n-allow: product UI string
        "no_access": "Keine Berechtigung für Downloads",  # i18n-allow: product UI string
        "no_access_mac": "Downloads in Dateien und Ordner erlauben",  # i18n-allow: UI
        "gone": "Nicht mehr aufbewahrt",  # i18n-allow: product UI string
        "text_copied": "Text kopiert",  # i18n-allow: product UI string
        "no_text": "Kein Text gefunden",  # i18n-allow: product UI string
    },
    "es": {
        "edit": "Editar",  # i18n-allow: product UI string
        "copy": "Copiar",  # i18n-allow: product UI string
        "save": "Guardar",  # i18n-allow: product UI string
        "close": "Cerrar",  # i18n-allow: product UI string
        "pin": "Mantener en pantalla",  # i18n-allow: product UI string
        "unpin": "Dejar de fijar",  # i18n-allow: product UI string
        "copy_text": "Copiar texto",  # i18n-allow: product UI string
        "copied": "Copiado",  # i18n-allow: product UI string
        "saved": "Guardado en Descargas",  # i18n-allow: product UI string
        "failed": "No ha funcionado",  # i18n-allow: product UI string
        "no_access": "Sin permiso para guardar en Descargas",  # i18n-allow: product UI string
        "no_access_mac": "Permite Descargas en Archivos y carpetas",  # i18n-allow: UI
        "gone": "Ya no se conserva",  # i18n-allow: product UI string
        "text_copied": "Texto copiado",  # i18n-allow: product UI string
        "no_text": "No se encontró texto",  # i18n-allow: product UI string
    },
    "zh": {
        "edit": "编辑",  # i18n-allow: UI
        "copy": "复制",  # i18n-allow: UI
        "save": "保存",  # i18n-allow: UI
        "close": "关闭",  # i18n-allow: UI
        "pin": "固定在屏幕上",  # i18n-allow: UI
        "unpin": "取消固定",  # i18n-allow: UI
        "copy_text": "复制文字",  # i18n-allow: UI
        "copied": "已复制",  # i18n-allow: UI
        "saved": "已保存到“下载”",  # i18n-allow: UI
        "failed": "操作未成功",  # i18n-allow: UI
        "no_access": "没有保存到“下载”文件夹的权限",  # i18n-allow: UI
        "no_access_mac": "请在“隐私与安全性 > 文件和文件夹”中允许访问“下载”",  # i18n-allow: UI
        "gone": "已不再保留",  # i18n-allow: UI
        "text_copied": "文字已复制",  # i18n-allow: UI
        "no_text": "未找到文字",  # i18n-allow: UI
    },
    "pt": {
        "edit": "Editar",  # i18n-allow: product UI string
        "copy": "Copiar",  # i18n-allow: product UI string
        "save": "Guardar",  # i18n-allow: product UI string
        "close": "Fechar",  # i18n-allow: product UI string
        "pin": "Manter no ecrã",  # i18n-allow: product UI string
        "unpin": "Deixar de fixar",  # i18n-allow: product UI string
        "copy_text": "Copiar texto",  # i18n-allow: product UI string
        "copied": "Copiado",  # i18n-allow: product UI string
        "saved": "Guardado em Transferências",  # i18n-allow: product UI string
        "failed": "Não funcionou",  # i18n-allow: product UI string
        "no_access": "Sem permissão para guardar em Transferências",  # i18n-allow: UI
        "no_access_mac": "Permite Transferências em Ficheiros e pastas",  # i18n-allow: UI
        "gone": "Já não está guardado",  # i18n-allow: product UI string
        "text_copied": "Texto copiado",  # i18n-allow: product UI string
        "no_text": "Nenhum texto encontrado",  # i18n-allow: product UI string
    },
}


def card_labels(config: Any) -> dict[str, str]:
    language = str(getattr(getattr(config, "ui", None), "language", "") or "").lower()[:2]
    return dict(_LABELS.get(language, _LABELS["en"]))


def card_rest_ms(config: Any) -> int:
    """How long the card stays untouched; ``0`` = until the user closes it."""
    seconds = getattr(getattr(config, "appshot", None), "card_seconds", 6)
    try:
        value = int(seconds)
    except (TypeError, ValueError):  # Invalid optional timing falls back to the standard card duration.
        value = 6
    return max(0, value) * 1000


def as_png(image: bytes) -> bytes:
    """The held picture (JPEG or PNG) as PNG bytes."""
    if image.startswith(b"\x89PNG\r\n\x1a\n"):
        return image
    from PIL import Image  # noqa: PLC0415

    with Image.open(io.BytesIO(image)) as picture:
        out = io.BytesIO()
        picture.convert("RGB").save(out, format="PNG")
    return out.getvalue()


def save_to_downloads(png: bytes, *, folder: Path | None = None, now: float | None = None) -> Path:
    """Write ``png`` into Downloads under a fresh name and return the path."""
    from dodaios.platform import user_dirs  # noqa: PLC0415

    target = folder or user_dirs.downloads_dir()
    target.mkdir(parents=True, exist_ok=True)
    moment = time.time() if now is None else now
    stem = time.strftime("appshot-%Y%m%d-%H%M%S", time.localtime(moment))
    path = target / f"{stem}.png"
    counter = 1
    while path.exists():
        counter += 1
        path = target / f"{stem}-{counter}.png"
    path.write_bytes(png)
    return path


def save_shot_to_downloads(
    shot: Any, *, folder: Path | None = None, now: float | None = None
) -> Path:
    """Save an appshot's lossless copy; beside it the HDR one, when there is one.

    ``appshot-….png`` is the 8-bit picture every viewer shows the same way;
    ``appshot-…-hdr.png`` keeps the HDR monitor's full range for viewers that
    read PNG colour tags (cICP). Returns the 8-bit file's path.
    """
    png = shot.original_png or as_png(shot.image)
    where = {k: v for k, v in (("folder", folder), ("now", now)) if v is not None}
    path = save_to_downloads(png, **where)
    if shot.hdr_png:
        hdr = path.with_name(f"{path.stem}-hdr.png")
        if not hdr.exists():
            hdr.write_bytes(shot.hdr_png)
    return path


def _held(shot_id: str):
    """The card's appshot: by id when the card names one, else the last one."""
    from dodaios.appshot.store import get_store  # noqa: PLC0415

    store = get_store()
    return store.get(shot_id) if shot_id else store.latest()


async def _with_originals(shot: Any) -> Any:
    """Wait for a lossless copy that is still encoding (a second at most)."""
    from dodaios.appshot.service import finished  # noqa: PLC0415

    return await finished(shot)


async def run_card_action(action: str, shot_id: str = "") -> str:
    """Do ``copy``, ``save`` or ``copy_text`` on a card's appshot; the card's status line."""
    from dodaios.core.config import load_config  # noqa: PLC0415

    config = await asyncio.to_thread(load_config)
    labels = card_labels(config)
    shot = _held(shot_id)
    if shot is None:
        return labels["gone"]
    try:
        if action == "copy_text":
            text = (shot.ui_text or "").strip()
            if not text:
                return labels["no_text"]
            from dodaios.platform.clipboard import write_text  # noqa: PLC0415

            ok = await asyncio.to_thread(write_text, text)
            return labels["text_copied"] if ok else labels["failed"]
        shot = await _with_originals(shot)
        if action == "copy":
            from dodaios.platform.clipboard_image import write_png  # noqa: PLC0415

            png = shot.original_png or await asyncio.to_thread(as_png, shot.image)
            ok = await asyncio.to_thread(write_png, png)
            return labels["copied"] if ok else labels["failed"]
        if action == "save":
            path = await asyncio.to_thread(save_shot_to_downloads, shot)
            log.info("appshot: card saved %s", path.name)
            return labels["saved"]
    except PermissionError:
        # macOS asks once for Downloads (Files and Folders); a "Don't Allow"
        # lands here, and the card says where to change it.
        log.warning("appshot: no permission to write into Downloads", exc_info=True)
        return labels["no_access_mac" if sys.platform == "darwin" else "no_access"]
    except Exception:  # noqa: BLE001 - the card says so; nothing else depends on it
        log.warning("appshot: card action %r failed", action, exc_info=True)
        return labels["failed"]
    return labels["failed"]


async def return_to_corner(fly_from: list[float] | None = None, *, shot_id: str = "") -> bool:
    """Bring an appshot back into the corner card stack. ``False`` = not shown.

    ``shot_id`` is the appshot the editor had open (the last one when empty).
    ``fly_from`` (``[x, y, w, h]``, global logical pixels) is where the
    editor showed the picture: it then flies from there to the bottom of the
    stack, like after the shutter. Without it the card slides in from the edge.
    """
    try:
        from dodaios.appshot.effect import card_hint, thumbnail_from_image  # noqa: PLC0415
        from dodaios.core.config import load_config  # noqa: PLC0415
        from dodaios.cu.indicator.controller import get_indicator_controller  # noqa: PLC0415

        controller = get_indicator_controller()
        shot = _held(shot_id)
        if controller is None or shot is None:
            return False
        config = await asyncio.to_thread(load_config)
        if not bool(getattr(getattr(config, "appshot", None), "effect", True)):
            return False
        thumb = await asyncio.to_thread(thumbnail_from_image, shot.image)
        keep = float(config.screen_context.deck_preview_s) > 0
        return bool(
            await controller.show_card(
                thumb_b64=base64.b64encode(thumb).decode("ascii"),
                image_b64=base64.b64encode(shot.image).decode("ascii") if keep else "",
                hint=card_hint(config),
                rest_ms=card_rest_ms(config),
                labels=card_labels(config),
                fly_from=fly_from,
                shot_id=shot.id,
            )
        )
    except Exception:  # noqa: BLE001 - the card is a convenience, never a failure
        log.warning("appshot: could not return the appshot to the corner", exc_info=True)
        return False


__all__ = [
    "as_png",
    "card_labels",
    "card_rest_ms",
    "return_to_corner",
    "run_card_action",
    "save_to_downloads",
]