OTPRunner 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
otprunner/cli.py ADDED
@@ -0,0 +1,259 @@
1
+ """CLI de OTPRunner. Mismos comandos que el runner de KRunner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+ import time
9
+
10
+ from . import APP_NAME, __version__, config, exporting, i18n, importer, migration
11
+ from .camera import CameraError
12
+ from .capture import CaptureError
13
+ from .i18n import _
14
+ from .otpauth import OtpError
15
+ from .store import StoreError, open_store
16
+
17
+
18
+ def _match(names, pattern: str | None) -> list[str]:
19
+ if not pattern:
20
+ return list(names)
21
+ p = pattern.casefold()
22
+ return [n for n in names if p in n.casefold()]
23
+
24
+
25
+ def _resolve(names, pattern: str) -> str:
26
+ """Nombre exacto, o el único que contiene ``pattern``."""
27
+ if pattern in names:
28
+ return pattern
29
+ hits = _match(names, pattern)
30
+ if len(hits) == 1:
31
+ return hits[0]
32
+ if not hits:
33
+ raise StoreError(_("no account matches “{filter}”").format(filter=pattern))
34
+ raise StoreError(_("“{filter}” is ambiguous: {matches}").format(filter=pattern, matches=", ".join(hits)))
35
+
36
+
37
+ def _read_source(src: str) -> str:
38
+ if src == "-":
39
+ return sys.stdin.read()
40
+ if src.lower().startswith(("otpauth://", "otpauth-migration://")):
41
+ return src
42
+ with open(src, encoding="utf-8") as f:
43
+ return f.read()
44
+
45
+
46
+ def _report(res: importer.ImportResult, errors: list[str]) -> int:
47
+ for n in res.added:
48
+ print(_("added: {name}").format(name=n))
49
+ for wanted, final in res.renamed:
50
+ print(" " + _("(“{wanted}” already existed, saved as “{final}”)").format(wanted=wanted, final=final))
51
+ for n in res.updated:
52
+ print(_("updated (same secret, name kept): {name}").format(name=n))
53
+ for n in res.skipped:
54
+ print(_("skipped (already present with the same secret): {name}").format(name=n))
55
+ for e in errors:
56
+ print(_("error: {message}").format(message=e), file=sys.stderr)
57
+ return 1 if errors and not (res.added or res.updated) else 0
58
+
59
+
60
+ async def _cmd(args, cfg) -> int:
61
+ if args.cmd == "doctor":
62
+ from . import doctor
63
+
64
+ return await doctor.run()
65
+
66
+ if args.cmd == "serve":
67
+ from . import runner
68
+
69
+ return await runner.serve(idle_timeout=args.idle, demo=args.demo)
70
+
71
+ async with await open_store(args.backend or cfg.backend) as store:
72
+ if args.cmd == "list":
73
+ accounts = await store.all()
74
+ names = _match(accounts, args.filter)
75
+ if args.names:
76
+ print("\n".join(names))
77
+ return 0
78
+ now = time.time()
79
+ width = max((len(n) for n in names), default=0)
80
+ for n in names:
81
+ a = accounts[n]
82
+ extra = f"{a.remaining(now):>3}s" if a.type == "totp" else "hotp"
83
+ print(f"{n:<{width}} {a.code(now)} {extra}")
84
+ return 0
85
+
86
+ if args.cmd == "code":
87
+ accounts = await store.all()
88
+ name = _resolve(accounts, args.name)
89
+ acc = accounts[name]
90
+ code = acc.code()
91
+ if acc.type == "hotp":
92
+ await store.put(name, acc.with_counter(acc.counter + 1), replace=True)
93
+ print(code)
94
+ if args.copy:
95
+ from . import clipboard
96
+ from .dbusutil import session_bus
97
+
98
+ bus = await session_bus()
99
+ try:
100
+ provider = await clipboard.copy(code, bus)
101
+ finally:
102
+ bus.disconnect()
103
+ print(_("copied to the clipboard ({provider})").format(provider=provider), file=sys.stderr)
104
+ return 0
105
+
106
+ if args.cmd == "add":
107
+ from . import adding, capture
108
+ from .dbusutil import session_bus
109
+
110
+ source = "uri" if args.uri else "clipboard" if args.clipboard else "camera" if args.camera else "screen"
111
+ if source == "screen":
112
+ print(_("Select the area of the screen with the QR code…"), file=sys.stderr)
113
+ elif source == "camera":
114
+ print(_("Show the QR code to the camera (close the window to cancel)…"), file=sys.stderr)
115
+ bus = await session_bus()
116
+ try:
117
+ outcome = await adding.add(store, source, bus, name=args.name, uri=args.uri, device=cfg.camera,
118
+ progress=lambda msg: print(msg, file=sys.stderr))
119
+ except capture.CaptureCancelled:
120
+ print(_("cancelled"), file=sys.stderr)
121
+ return 1
122
+ finally:
123
+ bus.disconnect()
124
+ title, body = outcome.summary()
125
+ print(title)
126
+ if body:
127
+ print(body)
128
+ return 0 if outcome.ok else 1
129
+
130
+ if args.cmd == "import":
131
+ parsed = importer.parse_text(_read_source(args.source))
132
+ if not parsed.accounts and not parsed.errors:
133
+ print(_("error: no otpauth URI found"), file=sys.stderr)
134
+ return 1
135
+ res = await importer.import_accounts(store, parsed.accounts)
136
+ return _report(res, parsed.errors)
137
+
138
+ if args.cmd == "export":
139
+ accounts = await store.all()
140
+ names = _match(accounts, args.filter)
141
+ if not names:
142
+ print(_("no accounts to export"), file=sys.stderr)
143
+ return 1
144
+ if args.format == "otpauth" or (args.format == "auto" and len(names) == 1):
145
+ for n in names:
146
+ if args.qr:
147
+ print(n)
148
+ exporting.terminal(accounts[n].to_uri())
149
+ else:
150
+ print(accounts[n].to_uri())
151
+ return 0
152
+ exp = exporting.build({n: accounts[n] for n in names}, batch_size=args.batch,
153
+ single_otpauth=args.format == "auto")
154
+ for n, reason in exp.skipped:
155
+ print(_("skipped {name}: {reason} (use --format otpauth)").format(name=n, reason=reason), file=sys.stderr)
156
+ for i, uri in enumerate(exp.uris, 1):
157
+ if args.qr:
158
+ print(_("QR {i} of {n}").format(i=i, n=len(exp.uris)))
159
+ exporting.terminal(uri)
160
+ else:
161
+ print(uri)
162
+ return 0 if exp.uris else 1
163
+
164
+ if args.cmd in ("remove", "rm"):
165
+ name = _resolve(await store.names(), args.name)
166
+ if not args.yes:
167
+ ans = input(_("Remove “{name}”? [y/N] ").format(name=name)).strip().lower()
168
+ if ans not in ("y", "yes", _("y"), _("yes")):
169
+ print(_("cancelled"))
170
+ return 1
171
+ await store.delete(name)
172
+ print(_("removed: {name}").format(name=name))
173
+ return 0
174
+
175
+ if args.cmd == "rename":
176
+ old = _resolve(await store.names(), args.old)
177
+ await store.rename(old, args.new)
178
+ print(_("renamed: {old} → {new}").format(old=old, new=args.new))
179
+ return 0
180
+ return 2
181
+
182
+
183
+ def build_parser() -> argparse.ArgumentParser:
184
+ p = argparse.ArgumentParser(prog="otprunner", description=_("{app}: TOTP codes with the secrets in the system keystore.").format(app=APP_NAME))
185
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
186
+ p.add_argument("--backend", help=_("keystore: auto, kwallet, secretservice (default: from the config)"))
187
+ sub = p.add_subparsers(dest="cmd", required=True, metavar=_("COMMAND"))
188
+
189
+ s = sub.add_parser("list", help=_("list accounts and codes"))
190
+ s.add_argument("filter", nargs="?")
191
+ s.add_argument("--names", action="store_true", help=_("names only"))
192
+
193
+ s = sub.add_parser("code", help=_("show the code of an account"))
194
+ s.add_argument("name")
195
+ s.add_argument("-c", "--copy", action="store_true", help=_("also copy it to the clipboard"))
196
+
197
+ s = sub.add_parser("add", help=_("add an account"))
198
+ s.add_argument("name", nargs="?", help=_("name (default: issuer:account from the QR code)"))
199
+ g = s.add_mutually_exclusive_group()
200
+ g.add_argument("--screen", action="store_true", help=_("QR code in an area of the screen (default)"))
201
+ g.add_argument("--clipboard", action="store_true", help=_("URI or QR image from the clipboard"))
202
+ g.add_argument("--camera", action="store_true", help=_("QR code shown to the camera"))
203
+ g.add_argument("--uri", help=_("otpauth:// or otpauth-migration:// URI"))
204
+
205
+ s = sub.add_parser("import", help=_("import otpauth/otpauth-migration URIs from a file, '-' or the URI itself"))
206
+ s.add_argument("source")
207
+
208
+ s = sub.add_parser("export", help=_("export accounts"))
209
+ s.add_argument("filter", nargs="?")
210
+ s.add_argument("--format", choices=("auto", "migration", "otpauth"), default="auto",
211
+ help=_("auto: otpauth for a single account, migration for several"))
212
+ s.add_argument("--batch", type=int, default=migration.DEFAULT_BATCH, help=_("accounts per migration URI"))
213
+ s.add_argument("--qr", action="store_true", help=_("show as QR codes in the terminal"))
214
+
215
+ s = sub.add_parser("remove", aliases=["rm"], help=_("remove an account"))
216
+ s.add_argument("name")
217
+ s.add_argument("-y", "--yes", action="store_true", help=_("do not ask for confirmation"))
218
+
219
+ s = sub.add_parser("rename", help=_("rename an account"))
220
+ s.add_argument("old")
221
+ s.add_argument("new")
222
+
223
+ sub.add_parser("doctor", help=_("diagnose the environment"))
224
+ sub.add_parser("install", help=_("register the runner in KRunner (and the systemd user unit)"))
225
+ sub.add_parser("uninstall", help=_("undo install (the secrets are kept)"))
226
+
227
+ s = sub.add_parser("serve", help=_("run the runner DBus service (started by DBus/systemd)"))
228
+ s.add_argument("-v", "--verbose", action="store_true", help=_("debug logging"))
229
+ s.add_argument("--idle", type=float, help=_("idle seconds before exiting (0 = never)"))
230
+ s.add_argument("--demo", action="store_true", help=_("serve made-up accounts instead of the keystore (for screenshots)"))
231
+ return p
232
+
233
+
234
+ def main(argv: list[str] | None = None) -> int:
235
+ cfg = config.load()
236
+ i18n.setup(cfg.language)
237
+ args = build_parser().parse_args(argv)
238
+ if args.cmd in ("install", "uninstall"):
239
+ from . import install
240
+
241
+ return install.install() if args.cmd == "install" else install.uninstall()
242
+ if args.cmd == "serve":
243
+ import logging
244
+
245
+ logging.basicConfig(
246
+ level=logging.DEBUG if args.verbose else logging.INFO,
247
+ format="%(levelname)s %(name)s: %(message)s",
248
+ )
249
+ try:
250
+ return asyncio.run(_cmd(args, cfg))
251
+ except (StoreError, OtpError, CaptureError, CameraError, OSError) as e:
252
+ print(_("error: {message}").format(message=e), file=sys.stderr)
253
+ return 1
254
+ except KeyboardInterrupt:
255
+ return 130
256
+
257
+
258
+ if __name__ == "__main__":
259
+ sys.exit(main())
otprunner/clipboard.py ADDED
@@ -0,0 +1,66 @@
1
+ """Copia al portapapeles con el primer proveedor disponible: Klipper → wl-copy → xclip → xsel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ import shutil
9
+
10
+ from .dbusutil import DBusCallError, call, name_available
11
+ from .i18n import _
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+
16
+ class ClipboardError(RuntimeError):
17
+ pass
18
+
19
+
20
+ def _commands() -> list[tuple[str, list[str]]]:
21
+ cmds = []
22
+ if os.environ.get("WAYLAND_DISPLAY"):
23
+ cmds.append(("wl-copy", ["wl-copy"]))
24
+ if os.environ.get("DISPLAY"):
25
+ cmds.append(("xclip", ["xclip", "-selection", "clipboard", "-in"]))
26
+ cmds.append(("xsel", ["xsel", "--clipboard", "--input"]))
27
+ return [(n, c) for n, c in cmds if shutil.which(c[0])]
28
+
29
+
30
+ async def providers(bus) -> list[str]:
31
+ out = ["klipper"] if bus is not None and await name_available(bus, "org.kde.klipper") else []
32
+ return out + [n for n, _ in _commands()]
33
+
34
+
35
+ async def copy(text: str, bus=None) -> str:
36
+ """Copia ``text`` y devuelve el nombre del proveedor usado."""
37
+ errors = []
38
+ if bus is not None:
39
+ try:
40
+ if await name_available(bus, "org.kde.klipper"):
41
+ await call(bus, "org.kde.klipper", "/klipper", "org.kde.klipper.klipper",
42
+ "setClipboardContents", "s", [text])
43
+ return "klipper"
44
+ except DBusCallError as e:
45
+ errors.append(f"klipper: {e}")
46
+ for name, cmd in _commands():
47
+ try:
48
+ # xclip/xsel/wl-copy se quedan en segundo plano sirviendo la selección:
49
+ # no capturamos su salida para no esperar a que terminen.
50
+ proc = await asyncio.create_subprocess_exec(
51
+ *cmd, stdin=asyncio.subprocess.PIPE,
52
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
53
+ start_new_session=True,
54
+ )
55
+ proc.stdin.write(text.encode())
56
+ await proc.stdin.drain()
57
+ proc.stdin.close()
58
+ rc = await asyncio.wait_for(proc.wait(), timeout=5)
59
+ if rc == 0:
60
+ return name
61
+ errors.append(_("{tool}: exit code {rc}").format(tool=name, rc=rc))
62
+ except (OSError, asyncio.TimeoutError) as e:
63
+ errors.append(f"{name}: {e}")
64
+ if errors:
65
+ raise ClipboardError(_("no clipboard available: {errors}").format(errors="; ".join(errors)))
66
+ raise ClipboardError(_("no clipboard available (install wl-clipboard or xclip)"))
otprunner/config.py ADDED
@@ -0,0 +1,78 @@
1
+ """Configuración opcional en ``$XDG_CONFIG_HOME/otprunner/config.toml``.
2
+
3
+ Ejemplo::
4
+
5
+ backend = "auto" # auto | secretservice | kwallet
6
+ keywords = ["otp", "otpr"] # palabras clave en KRunner
7
+ idle_timeout = 600 # segundos sin uso antes de cerrar el servicio (0 = nunca)
8
+ show_codes = "selected" # selected: solo en la línea seleccionada | always | never
9
+ max_results = 7 # resultados devueltos: KRunner reparte 15 entre los runners que respondan
10
+ language = "es" # idioma de la interfaz (por defecto, el del escritorio)
11
+ camera = "/dev/video0" # dispositivo de la cámara (por defecto, el del lector)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import sys
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from .i18n import _
21
+
22
+ if sys.version_info >= (3, 11):
23
+ import tomllib
24
+ else: # pragma: no cover
25
+ import tomli as tomllib
26
+
27
+
28
+ SHOW_CODES = ("selected", "always", "never")
29
+
30
+
31
+ def config_path() -> Path:
32
+ base = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
33
+ return Path(base) / "otprunner" / "config.toml"
34
+
35
+
36
+ @dataclass
37
+ class Config:
38
+ backend: str = "auto"
39
+ keywords: list[str] = field(default_factory=lambda: ["otp", "otpr"])
40
+ idle_timeout: float = 600
41
+ show_codes: str = "selected"
42
+ max_results: int = 7
43
+ camera: str | None = None
44
+ language: str | None = None
45
+
46
+
47
+ def load(path: Path | None = None) -> Config:
48
+ path = path or config_path()
49
+ cfg = Config()
50
+ try:
51
+ data = tomllib.loads(path.read_text())
52
+ except FileNotFoundError:
53
+ return cfg
54
+ except (OSError, tomllib.TOMLDecodeError) as e:
55
+ print("otprunner: " + _("ignoring {path}: {error}").format(path=path, error=e), file=sys.stderr)
56
+ return cfg
57
+ if isinstance(data.get("backend"), str):
58
+ cfg.backend = data["backend"]
59
+ kw = data.get("keywords")
60
+ if isinstance(kw, list) and kw and all(isinstance(k, str) and k for k in kw):
61
+ cfg.keywords = kw
62
+ idle = data.get("idle_timeout")
63
+ if isinstance(idle, (int, float)) and not isinstance(idle, bool) and idle >= 0:
64
+ cfg.idle_timeout = idle
65
+ show = data.get("show_codes")
66
+ if show in SHOW_CODES:
67
+ cfg.show_codes = show
68
+ elif show is not None:
69
+ print("otprunner: " + _("invalid show_codes={value} (use {valid})").format(
70
+ value=repr(show), valid=", ".join(SHOW_CODES)), file=sys.stderr)
71
+ limit = data.get("max_results")
72
+ if isinstance(limit, int) and not isinstance(limit, bool) and limit >= 3:
73
+ cfg.max_results = limit
74
+ if isinstance(data.get("camera"), str) and data["camera"]:
75
+ cfg.camera = data["camera"]
76
+ if isinstance(data.get("language"), str) and data["language"]:
77
+ cfg.language = data["language"]
78
+ return cfg
@@ -0,0 +1,8 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
2
+ <defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1">
3
+ <stop offset="0" stop-color="#3daee9"/><stop offset="1" stop-color="#1a6fa8"/></linearGradient></defs>
4
+ <rect x="0.5" y="0.5" width="15" height="15" rx="3.5" fill="url(#g)"/>
5
+ <path d="M8 3 A5 5 0 1 1 3.67 5.5" fill="none" stroke="#fff" stroke-width="1.9" stroke-linecap="round"/>
6
+ <circle cx="8" cy="7.3" r="1.7" fill="#fff"/>
7
+ <path d="M7.1 8 L6.7 10.9 H9.3 L8.9 8 Z" fill="#fff"/>
8
+ </svg>
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
2
+ <defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1">
3
+ <stop offset="0" stop-color="#3daee9"/><stop offset="1" stop-color="#1a6fa8"/></linearGradient></defs>
4
+ <rect x="8" y="8" width="112" height="112" rx="24" fill="url(#g)"/>
5
+ <circle cx="64" cy="64" r="38" fill="none" stroke="#ffffff" stroke-opacity=".25" stroke-width="10"/>
6
+ <path d="M64 26 A38 38 0 1 1 31.1 45" fill="none" stroke="#fff" stroke-width="10" stroke-linecap="round"/>
7
+ <circle cx="64" cy="57" r="11" fill="#fff"/>
8
+ <path d="M58 62 L55 82 H73 L70 62 Z" fill="#fff"/>
9
+ </svg>
otprunner/dbusutil.py ADDED
@@ -0,0 +1,51 @@
1
+ """Utilidades mínimas sobre dbus-fast (llamadas directas, sin introspección)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dbus_fast import BusType, Message, MessageType
6
+ from dbus_fast.aio import MessageBus
7
+
8
+ from .i18n import _
9
+
10
+ DBUS = ("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus")
11
+
12
+
13
+ class DBusCallError(RuntimeError):
14
+ def __init__(self, name: str, text: str) -> None:
15
+ super().__init__(f"{name}: {text}")
16
+ self.name = name
17
+
18
+
19
+ class NoSessionBus(OSError):
20
+ """No hay bus de sesión (fuera de una sesión gráfica, en un contenedor…)."""
21
+
22
+
23
+ async def session_bus() -> MessageBus:
24
+ try:
25
+ return await MessageBus(bus_type=BusType.SESSION).connect()
26
+ except Exception as e: # noqa: BLE001 — dbus-fast lanza varios tipos según la causa
27
+ raise NoSessionBus(_("cannot connect to the DBus session bus (run it inside your desktop session): {error}")
28
+ .format(error=e)) from None
29
+
30
+
31
+ async def call(bus: MessageBus, dest: str, path: str, iface: str, member: str, sig: str = "", body=None):
32
+ reply = await bus.call(
33
+ Message(destination=dest, path=path, interface=iface, member=member, signature=sig, body=body or [])
34
+ )
35
+ if reply.message_type == MessageType.ERROR:
36
+ raise DBusCallError(reply.error_name or "error", " ".join(map(str, reply.body)))
37
+ return reply.body
38
+
39
+
40
+ async def get_prop(bus: MessageBus, dest: str, path: str, iface: str, prop: str):
41
+ (v,) = await call(bus, dest, path, "org.freedesktop.DBus.Properties", "Get", "ss", [iface, prop])
42
+ return v.value
43
+
44
+
45
+ async def name_available(bus: MessageBus, name: str) -> bool:
46
+ """True si el nombre tiene dueño o es activable por DBus."""
47
+ (has,) = await call(bus, *DBUS, "NameHasOwner", "s", [name])
48
+ if has:
49
+ return True
50
+ (names,) = await call(bus, *DBUS, "ListActivatableNames")
51
+ return name in names
otprunner/demo.py ADDED
@@ -0,0 +1,34 @@
1
+ """Cuentas ficticias para demostraciones y capturas (``otprunner serve --demo``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+
7
+ from .otpauth import Account
8
+ from .store import MemoryStore
9
+
10
+ ACCOUNTS = (
11
+ ("GitHub", "alice"),
12
+ ("GitLab", "alice"),
13
+ ("Google", "alice@example.com"),
14
+ ("Proton", "alice@proton.me"),
15
+ ("Amazon", "alice@example.com"),
16
+ ("AWS", "alice (root)"),
17
+ ("Cloudflare", "alice@example.com"),
18
+ ("Dropbox", "alice@example.com"),
19
+ ("Mastodon", "@alice@fosstodon.org"),
20
+ ("Nextcloud", "alice"),
21
+ ("PayPal", "alice@example.com"),
22
+ ("Bitwarden", "alice@example.com"),
23
+ ("Discord", "alice#4242"),
24
+ ("DigitalOcean", "alice@example.com"),
25
+ )
26
+
27
+
28
+ def store() -> MemoryStore:
29
+ """Almacén en memoria con secretos aleatorios: nada de esto existe fuera del proceso."""
30
+ s = MemoryStore()
31
+ for issuer, name in ACCOUNTS:
32
+ acc = Account(secret=secrets.token_bytes(20), name=name, issuer=issuer)
33
+ s.data[acc.label] = acc.to_uri()
34
+ return s
otprunner/dialogs.py ADDED
@@ -0,0 +1,110 @@
1
+ """Diálogos mínimos para el runner: kdialog → zenity. Sin herramienta, devuelven None."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from pathlib import Path
10
+ from .i18n import _
11
+
12
+
13
+ class NoDialogTool(RuntimeError):
14
+ def __init__(self) -> None:
15
+ super().__init__(_("no dialog tool available: install kdialog or zenity"))
16
+
17
+
18
+ def tool() -> str | None:
19
+ for t in ("kdialog", "zenity"):
20
+ if shutil.which(t):
21
+ return t
22
+ return None
23
+
24
+
25
+ async def _run(cmd: list[str]) -> tuple[int, str]:
26
+ proc = await asyncio.create_subprocess_exec(
27
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL)
28
+ out, _err = await proc.communicate()
29
+ return proc.returncode, out.decode(errors="replace").rstrip("\n")
30
+
31
+
32
+ _MONITOR_RE = re.compile(r"(\d+)/\d+x(\d+)/\d+\+(-?\d+)\+(-?\d+)")
33
+ # Espacio que se quedan la barra de título, los botones del visor y el panel del escritorio.
34
+ _CHROME_W, _CHROME_H = 80, 160
35
+
36
+
37
+ def _out(cmd: list[str]) -> str:
38
+ if not shutil.which(cmd[0]):
39
+ return ""
40
+ try:
41
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=2).stdout
42
+ except (OSError, subprocess.SubprocessError):
43
+ return ""
44
+
45
+
46
+ def monitors(listing: str | None = None) -> list[tuple[int, int, int, int]]:
47
+ """(ancho, alto, x, y) de cada monitor, según ``xrandr --listmonitors`` (X11 y XWayland)."""
48
+ text = _out(["xrandr", "--listmonitors"]) if listing is None else listing
49
+ return [tuple(map(int, m.groups())) for m in _MONITOR_RE.finditer(text)] # type: ignore[misc]
50
+
51
+
52
+ def pointer(text: str | None = None) -> tuple[int, int] | None:
53
+ text = _out(["xdotool", "getmouselocation", "--shell"]) if text is None else text
54
+ xy = dict(re.findall(r"^([XY])=(-?\d+)$", text, re.M))
55
+ return (int(xy["X"]), int(xy["Y"])) if len(xy) == 2 else None
56
+
57
+
58
+ def image_area(default: tuple[int, int] = (1280, 760), mons=None, ptr=None) -> tuple[int, int]:
59
+ """Tamaño máximo de una imagen para que su ventana quepa en pantalla.
60
+
61
+ Usa el monitor donde está el puntero (donde KDE abre las ventanas nuevas); si no se
62
+ sabe, el más pequeño, para que quepa en cualquiera.
63
+ """
64
+ mons = monitors() if mons is None else mons
65
+ if not mons:
66
+ return default
67
+ ptr = pointer() if ptr is None else ptr
68
+ here = [m for m in mons if ptr and m[2] <= ptr[0] < m[2] + m[0] and m[3] <= ptr[1] < m[3] + m[1]]
69
+ w, h, _x, _y = here[0] if here else min(mons, key=lambda m: m[0] * m[1])
70
+ return max(min(w - _CHROME_W, default[0]), 200), max(min(h - _CHROME_H, default[1]), 200)
71
+
72
+
73
+ async def confirm(title: str, text: str, ok_label: str | None = None) -> bool:
74
+ ok_label = ok_label or _("Continue")
75
+ t = tool()
76
+ if t == "kdialog":
77
+ rc, _out = await _run(["kdialog", "--title", title, "--warningcontinuecancel", text,
78
+ "--continue-label", ok_label])
79
+ elif t == "zenity":
80
+ rc, _out = await _run(["zenity", "--question", "--title", title, "--text", text,
81
+ "--ok-label", ok_label, "--cancel-label", _("Cancel"), "--icon-name", "dialog-warning"])
82
+ else:
83
+ raise NoDialogTool()
84
+ return rc == 0
85
+
86
+
87
+ async def ask_text(title: str, label: str, default: str = "") -> str | None:
88
+ t = tool()
89
+ if t == "kdialog":
90
+ rc, out = await _run(["kdialog", "--title", title, "--inputbox", label, default])
91
+ elif t == "zenity":
92
+ rc, out = await _run(["zenity", "--entry", "--title", title, "--text", label, "--entry-text", default])
93
+ else:
94
+ raise NoDialogTool()
95
+ return out.strip() if rc == 0 and out.strip() else None
96
+
97
+
98
+ async def show_image(path: Path, title: str) -> None:
99
+ """Muestra la imagen y espera a que el usuario cierre la ventana."""
100
+ t = tool()
101
+ if t == "kdialog":
102
+ await _run(["kdialog", "--title", title, "--imgbox", str(path)])
103
+ elif t == "zenity" and shutil.which("xdg-open"):
104
+ # zenity no muestra imágenes: abrimos el visor del sistema y esperamos a que el
105
+ # usuario confirme para poder borrar el fichero.
106
+ await _run(["xdg-open", str(path)])
107
+ await _run(["zenity", "--info", "--title", title,
108
+ "--text", _("Press OK when you have scanned the QR code, and close the viewer.")])
109
+ else:
110
+ raise NoDialogTool()