hi-puter 0.1.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.
Files changed (64) hide show
  1. hi_puter/__init__.py +1 -0
  2. hi_puter/__main__.py +4 -0
  3. hi_puter/actions/__init__.py +0 -0
  4. hi_puter/actions/base.py +18 -0
  5. hi_puter/actions/registry.py +81 -0
  6. hi_puter/adapters/__init__.py +0 -0
  7. hi_puter/adapters/base.py +20 -0
  8. hi_puter/adapters/factory.py +16 -0
  9. hi_puter/adapters/linux/__init__.py +0 -0
  10. hi_puter/adapters/linux/adapter.py +194 -0
  11. hi_puter/adapters/linux/mpris.py +100 -0
  12. hi_puter/adapters/linux/screen.py +177 -0
  13. hi_puter/adapters/processes.py +105 -0
  14. hi_puter/adapters/runner.py +35 -0
  15. hi_puter/adapters/windows/__init__.py +0 -0
  16. hi_puter/adapters/windows/adapter.py +45 -0
  17. hi_puter/audio/__init__.py +0 -0
  18. hi_puter/audio/capture.py +30 -0
  19. hi_puter/audio/cue.py +24 -0
  20. hi_puter/audio/devices.py +8 -0
  21. hi_puter/audio/listener.py +74 -0
  22. hi_puter/audio/ring_buffer.py +12 -0
  23. hi_puter/audio/segmenter.py +69 -0
  24. hi_puter/audio/vad.py +8 -0
  25. hi_puter/brain/__init__.py +0 -0
  26. hi_puter/brain/assistant.py +439 -0
  27. hi_puter/brain/llm.py +215 -0
  28. hi_puter/brain/tools.py +469 -0
  29. hi_puter/brain/writer.py +240 -0
  30. hi_puter/cli/__init__.py +0 -0
  31. hi_puter/cli/app.py +52 -0
  32. hi_puter/cli/commands/__init__.py +0 -0
  33. hi_puter/cli/commands/chat.py +80 -0
  34. hi_puter/cli/commands/doctor.py +104 -0
  35. hi_puter/cli/commands/lifecycle.py +45 -0
  36. hi_puter/cli/commands/model.py +56 -0
  37. hi_puter/cli/commands/rename.py +20 -0
  38. hi_puter/cli/commands/setup.py +18 -0
  39. hi_puter/core/__init__.py +0 -0
  40. hi_puter/core/config.py +238 -0
  41. hi_puter/core/errors.py +26 -0
  42. hi_puter/core/logging.py +15 -0
  43. hi_puter/core/paths.py +44 -0
  44. hi_puter/core/responses.py +3 -0
  45. hi_puter/nlu/__init__.py +0 -0
  46. hi_puter/nlu/catalog.py +195 -0
  47. hi_puter/nlu/matcher.py +16 -0
  48. hi_puter/nlu/normalize.py +12 -0
  49. hi_puter/runtime/__init__.py +0 -0
  50. hi_puter/runtime/assemble.py +104 -0
  51. hi_puter/runtime/daemon.py +116 -0
  52. hi_puter/runtime/lifecycle.py +69 -0
  53. hi_puter/runtime/states.py +34 -0
  54. hi_puter/runtime/voice_loop.py +198 -0
  55. hi_puter/speech/__init__.py +0 -0
  56. hi_puter/speech/models.py +21 -0
  57. hi_puter/speech/stt.py +44 -0
  58. hi_puter/speech/tts.py +88 -0
  59. hi_puter/speech/vocab.py +9 -0
  60. hi_puter/speech/wake.py +55 -0
  61. hi_puter-0.1.0.dist-info/METADATA +216 -0
  62. hi_puter-0.1.0.dist-info/RECORD +64 -0
  63. hi_puter-0.1.0.dist-info/WHEEL +4 -0
  64. hi_puter-0.1.0.dist-info/entry_points.txt +2 -0
hi_puter/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
hi_puter/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from hi_puter.cli.app import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
File without changes
@@ -0,0 +1,18 @@
1
+ from dataclasses import dataclass
2
+ from typing import Protocol
3
+
4
+ from hi_puter.adapters.base import SystemAdapter
5
+ from hi_puter.nlu.catalog import Risk
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class ActionResult:
10
+ ok: bool
11
+ spoken: str
12
+
13
+
14
+ class Action(Protocol):
15
+ id: str
16
+ risk: Risk
17
+
18
+ def run(self, slots: dict[str, str], adapter: SystemAdapter) -> ActionResult: ...
@@ -0,0 +1,81 @@
1
+ """Maps the fast regex intents onto toolbox calls, so simple commands skip the language model."""
2
+
3
+ from typing import Any
4
+
5
+ from hi_puter.actions.base import ActionResult
6
+ from hi_puter.adapters.base import SystemAdapter
7
+ from hi_puter.core.config import Config
8
+ from hi_puter.nlu.catalog import SITES, Intent
9
+ from hi_puter.nlu.normalize import normalize
10
+
11
+ HELP = (
12
+ "I can open apps and websites, search the web, change the volume, lock the screen, "
13
+ "take screenshots, check the battery and time, save notes, and handle multi-step requests."
14
+ )
15
+
16
+
17
+ def intent_call(intent: Intent, text: str = "") -> tuple[str, dict[str, Any]] | None:
18
+ """The tool name and arguments for an intent, or None for intents answered without a tool."""
19
+ slots = intent.slots
20
+ calls: dict[str, tuple[str, dict[str, Any]]] = {
21
+ "open_app": ("open_app", {"app": slots.get("app", "")}),
22
+ "close_app": ("close_app", {"app": slots.get("app", "")}),
23
+ "open_site": (
24
+ "open_website",
25
+ {"url": SITES.get(slots.get("site", ""), slots.get("site", ""))},
26
+ ),
27
+ "search": ("web_search", {"query": slots.get("query", "")}),
28
+ "volume_set": ("set_volume", {"level": int(slots.get("level", "50"))}),
29
+ "volume_up": ("change_volume", {"delta": 10}),
30
+ "volume_down": ("change_volume", {"delta": -10}),
31
+ "mute": ("set_mute", {"muted": not normalize(text).startswith("unmute")}),
32
+ "lock": ("lock_screen", {}),
33
+ "screenshot": ("take_screenshot", {}),
34
+ "battery": ("system_status", {}),
35
+ "time": ("current_time", {}),
36
+ "power": ("power", {"action": intent.id}),
37
+ }
38
+ if intent.action == "start_document":
39
+ return (
40
+ "start_document",
41
+ {"kind": slots.get("kind", "document"), "topic": slots.get("topic", "")},
42
+ )
43
+ if intent.action == "start_recording":
44
+ return ("start_recording", {"seconds": _seconds(slots.get("amount"), slots.get("unit"))})
45
+ if intent.action in {"open_document", "stop_recording"}:
46
+ return (intent.action, {})
47
+ if intent.action == "screenshot_choose":
48
+ return ("take_screenshot", {"mode": "choose"})
49
+ if intent.action == "media":
50
+ player = (slots.get("app") or slots.get("player") or "").strip() or None
51
+ return ("media_control", {"action": intent.id.removeprefix("media_"), "app": player})
52
+ return calls.get(intent.action)
53
+
54
+
55
+ NUMBER_WORDS = {
56
+ "a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
57
+ "ten": 10, "fifteen": 15, "twenty": 20, "thirty": 30,
58
+ } # fmt: skip
59
+
60
+
61
+ def _seconds(amount: str | None, unit: str | None) -> int | None:
62
+ """("30", "seconds") -> 30, ("two", "minutes") -> 120, (None, None) -> None."""
63
+ if not amount:
64
+ return None
65
+ number = int(amount) if amount.isdigit() else NUMBER_WORDS.get(amount, 0)
66
+ return number * 60 if (unit or "").startswith("minute") else number or None
67
+
68
+
69
+ def execute(
70
+ intent: Intent, adapter: SystemAdapter, config: Config | None = None, text: str = ""
71
+ ) -> ActionResult:
72
+ from hi_puter.brain.tools import build_toolbox
73
+
74
+ call = intent_call(intent, text)
75
+ if call is None:
76
+ return ActionResult(True, "Okay." if intent.action == "stop" else HELP)
77
+ toolbox = build_toolbox(adapter, config or Config())
78
+ if call[0] not in toolbox:
79
+ return ActionResult(False, "That action is not supported on this system.")
80
+ outcome = toolbox.call(*call)
81
+ return ActionResult(outcome.ok, outcome.text)
File without changes
@@ -0,0 +1,20 @@
1
+ from pathlib import Path
2
+ from typing import Protocol
3
+
4
+
5
+ class SystemAdapter(Protocol):
6
+ def capabilities(self) -> frozenset[str]: ...
7
+ def volume_get(self) -> int: ...
8
+ def volume_set(self, level: int) -> None: ...
9
+ def volume_change(self, delta: int) -> None: ...
10
+ def set_mute(self, muted: bool) -> None: ...
11
+ def lock(self) -> None: ...
12
+ def screenshot(self, interactive: bool = False) -> Path | None: ...
13
+ def start_recording(self, seconds: float | None) -> Path: ...
14
+ def stop_recording(self) -> Path | None: ...
15
+ def open_path(self, path: Path) -> None: ...
16
+ def open_app(self, name: str) -> None: ...
17
+ def close_app(self, name: str) -> int: ...
18
+ def media(self, action: str, app: str | None) -> str: ...
19
+ def open_url(self, url: str) -> None: ...
20
+ def power(self, kind: str) -> None: ...
@@ -0,0 +1,16 @@
1
+ import sys
2
+
3
+ from hi_puter.adapters.base import SystemAdapter
4
+ from hi_puter.core.errors import ActionError
5
+
6
+
7
+ def get_adapter() -> SystemAdapter:
8
+ if sys.platform == "win32":
9
+ from hi_puter.adapters.windows.adapter import WindowsAdapter
10
+
11
+ return WindowsAdapter()
12
+ if sys.platform.startswith("linux"):
13
+ from hi_puter.adapters.linux.adapter import LinuxAdapter
14
+
15
+ return LinuxAdapter()
16
+ raise ActionError(f"Unsupported platform: {sys.platform}")
File without changes
@@ -0,0 +1,194 @@
1
+ import logging
2
+ import re
3
+ import shutil
4
+ import subprocess
5
+ import webbrowser
6
+ from collections.abc import Sequence
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+
10
+ from hi_puter.adapters import processes
11
+ from hi_puter.adapters.linux import mpris, screen
12
+ from hi_puter.adapters.runner import run
13
+ from hi_puter.core.errors import ActionError
14
+
15
+ SINK = "@DEFAULT_AUDIO_SINK@"
16
+ log = logging.getLogger("hi_puter")
17
+
18
+
19
+ class LinuxAdapter:
20
+ def __init__(self) -> None:
21
+ self._recorder = screen.ScreenRecorder()
22
+
23
+ def capabilities(self) -> frozenset[str]:
24
+ return frozenset(
25
+ {"volume", "lock", "screenshot", "recording", "apps", "web", "power", "media", "files"}
26
+ )
27
+
28
+ def volume_get(self) -> int:
29
+ output = run(["wpctl", "get-volume", SINK]).stdout # "Volume: 0.40"
30
+ found = re.search(r"([\d.]+)", output)
31
+ return round(float(found.group(1)) * 100) if found else 0
32
+
33
+ def volume_set(self, level: int) -> None:
34
+ run(["wpctl", "set-volume", SINK, f"{max(0, min(100, level))}%"])
35
+
36
+ def volume_change(self, delta: int) -> None:
37
+ sign = "+" if delta >= 0 else "-"
38
+ run(["wpctl", "set-volume", "-l", "1.0", SINK, f"{abs(delta)}%{sign}"])
39
+
40
+ def set_mute(self, muted: bool) -> None:
41
+ run(["wpctl", "set-mute", SINK, "1" if muted else "0"])
42
+
43
+ def lock(self) -> None:
44
+ run(["loginctl", "lock-session"])
45
+
46
+ def screenshot(self, interactive: bool = False) -> Path | None:
47
+ """Save a full-screen capture, or open the screenshot tool (returns None)."""
48
+ if not interactive:
49
+ try:
50
+ path = screen.portal_screenshot(interactive=False, timeout=15)
51
+ except ActionError as exc:
52
+ log.info("Portal screenshot unavailable: %s", exc)
53
+ path = None
54
+ if path is not None:
55
+ return path
56
+ path = _screenshot_with_cli()
57
+ if path is not None:
58
+ return path
59
+ # Silent capture refused or unavailable: let the user pick what to capture.
60
+ screen.open_screenshot_tool()
61
+ return None
62
+
63
+ def start_recording(self, seconds: float | None) -> Path:
64
+ return self._recorder.start(seconds)
65
+
66
+ def stop_recording(self) -> Path | None:
67
+ return self._recorder.stop()
68
+
69
+ def open_path(self, path: Path) -> None:
70
+ opener = shutil.which("gio") or shutil.which("xdg-open")
71
+ if opener is None:
72
+ raise ActionError("No program to open files with (install xdg-utils).")
73
+ argv = [opener, "open", str(path)] if opener.endswith("gio") else [opener, str(path)]
74
+ subprocess.Popen(
75
+ argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True
76
+ )
77
+
78
+ def open_app(self, name: str) -> None:
79
+ for desktop_id in _desktop_ids(name):
80
+ try:
81
+ run(["gtk-launch", desktop_id])
82
+ return
83
+ except ActionError:
84
+ continue
85
+ binary = shutil.which(name.strip().lower().replace(" ", "-"))
86
+ if binary is None:
87
+ raise ActionError(f"I couldn't find an app called {name}.")
88
+ subprocess.Popen(
89
+ [binary], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True
90
+ )
91
+
92
+ def close_app(self, name: str) -> int:
93
+ return processes.close_app(name, _executables(name))
94
+
95
+ def media(self, action: str, app: str | None) -> str:
96
+ return mpris.control(action, app)
97
+
98
+ def open_url(self, url: str) -> None:
99
+ webbrowser.open(url)
100
+
101
+ def power(self, kind: str) -> None:
102
+ command = {"shutdown": "poweroff", "restart": "reboot", "suspend": "suspend"}[kind]
103
+ run(["systemctl", command])
104
+
105
+
106
+ APP_FOLDERS = (
107
+ Path("/usr/share/applications"),
108
+ Path.home() / ".local/share/applications",
109
+ Path("/var/lib/flatpak/exports/share/applications"),
110
+ Path("/var/lib/snapd/desktop/applications"),
111
+ )
112
+ FILLER = frozenset({"the", "a", "my", "app", "application", "program", "browser", "web"})
113
+
114
+
115
+ def _desktop_entries(folders: tuple[Path, ...] = APP_FOLDERS) -> list[tuple[str, str, str]]:
116
+ """(entry id, display name, program) for installed, visible applications."""
117
+ entries = []
118
+ for folder in folders:
119
+ if not folder.is_dir():
120
+ continue
121
+ for entry in sorted(folder.glob("*.desktop")):
122
+ try:
123
+ text = entry.read_text(errors="ignore")
124
+ except OSError:
125
+ continue
126
+ if re.search(r"^NoDisplay=true$", text, re.M):
127
+ continue
128
+ found = re.search(r"^Name=(.+)$", text, re.M)
129
+ program = re.search(r"^Exec=(.+)$", text, re.M)
130
+ entries.append(
131
+ (
132
+ entry.stem,
133
+ found.group(1).strip() if found else entry.stem,
134
+ _program(program.group(1)) if program else "",
135
+ )
136
+ )
137
+ return entries
138
+
139
+
140
+ def _screenshot_with_cli() -> Path | None:
141
+ """Screenshot tools for X11 and non-GNOME desktops."""
142
+ folder = screen.screenshots_folder()
143
+ folder.mkdir(parents=True, exist_ok=True)
144
+ target = folder / f"Screenshot {datetime.now():%Y-%m-%d %H-%M-%S}.png"
145
+ commands = (
146
+ ["gnome-screenshot", "-f", str(target)],
147
+ ["spectacle", "-b", "-n", "-f", "-o", str(target)],
148
+ ["grim", str(target)],
149
+ ["scrot", str(target)],
150
+ ["import", "-window", "root", str(target)],
151
+ )
152
+ for argv in commands:
153
+ if shutil.which(argv[0]):
154
+ try:
155
+ run(argv, timeout=15)
156
+ except ActionError:
157
+ continue
158
+ if target.exists():
159
+ return target
160
+ return None
161
+
162
+
163
+ def _program(exec_line: str) -> str:
164
+ """The binary an Exec= line runs: "env FOO=1 /snap/bin/firefox %u" -> "firefox"."""
165
+ for token in exec_line.split():
166
+ if token in {"env", "flatpak", "run"} or "=" in token or token.startswith("-"):
167
+ continue
168
+ return Path(token.strip('"')).name
169
+ return ""
170
+
171
+
172
+ def _executables(name: str) -> list[str]:
173
+ """Programs behind the desktop entries a spoken app name matches."""
174
+ entries = _desktop_entries()
175
+ ids = set(_desktop_ids(name, entries)[:3])
176
+ return [program for entry_id, _display, program in entries if entry_id in ids and program]
177
+
178
+
179
+ def _desktop_ids(name: str, entries: Sequence[tuple[str, ...]] | None = None) -> list[str]:
180
+ """Desktop entry IDs to try for a spoken app name, best match first.
181
+
182
+ "firefox" -> firefox; "chrome browser" -> google-chrome; "visual studio code" -> code.
183
+ """
184
+ spoken = name.strip().lower()
185
+ words = [word for word in re.findall(r"[a-z0-9]+", spoken) if word not in FILLER]
186
+ exact: list[str] = []
187
+ partial: list[str] = []
188
+ for entry_id, display, *_ in entries if entries is not None else _desktop_entries():
189
+ if display.lower() == spoken or entry_id.lower() == spoken:
190
+ exact.append(entry_id)
191
+ elif words and all(word in f"{display} {entry_id}".lower() for word in words):
192
+ partial.append(entry_id)
193
+ guesses = [spoken, spoken.replace(" ", "-"), spoken.replace(" ", "")]
194
+ return list(dict.fromkeys(exact + sorted(partial, key=len) + guesses))
@@ -0,0 +1,100 @@
1
+ """Media control on Linux through MPRIS, the D-Bus interface Spotify, VLC and browsers expose."""
2
+
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+
7
+ from hi_puter.core.errors import ActionError
8
+
9
+ PREFIX = "org.mpris.MediaPlayer2."
10
+ OBJECT = "/org/mpris/MediaPlayer2"
11
+ METHODS = {
12
+ "play": "Play",
13
+ "pause": "Pause",
14
+ "toggle": "PlayPause",
15
+ "next": "Next",
16
+ "previous": "Previous",
17
+ }
18
+ SANDBOX_HINT = (
19
+ "{app} blocked the request. Start Hi-Puter from a normal terminal: apps installed as snaps "
20
+ "only accept media controls from regular programs."
21
+ )
22
+
23
+
24
+ def _gdbus(*args: str) -> str:
25
+ binary = shutil.which("gdbus")
26
+ if binary is None:
27
+ raise ActionError("Media control needs gdbus (part of GLib), which isn't installed.")
28
+ result = subprocess.run(
29
+ [binary, "call", "--session", *args], capture_output=True, text=True, timeout=5, check=False
30
+ )
31
+ if result.returncode != 0:
32
+ raise ActionError(result.stderr.strip() or "D-Bus call failed")
33
+ return result.stdout
34
+
35
+
36
+ def players() -> list[str]:
37
+ """Bus names of running media players, e.g. org.mpris.MediaPlayer2.spotify."""
38
+ listing = _gdbus(
39
+ "--dest", "org.freedesktop.DBus", "--object-path", "/org/freedesktop/DBus",
40
+ "--method", "org.freedesktop.DBus.ListNames",
41
+ ) # fmt: skip
42
+ return re.findall(rf"'({re.escape(PREFIX)}[^']+)'", listing)
43
+
44
+
45
+ def _label(bus_name: str) -> str:
46
+ """org.mpris.MediaPlayer2.spotify -> Spotify; ...firefox.instance_1_23 -> Firefox."""
47
+ return bus_name.removeprefix(PREFIX).split(".")[0].replace("_", " ").title()
48
+
49
+
50
+ def _is_playing(bus_name: str) -> bool:
51
+ try:
52
+ status = _gdbus(
53
+ "--dest", bus_name, "--object-path", OBJECT,
54
+ "--method", "org.freedesktop.DBus.Properties.Get",
55
+ "org.mpris.MediaPlayer2.Player", "PlaybackStatus",
56
+ ) # fmt: skip
57
+ except ActionError:
58
+ return False
59
+ return "Playing" in status
60
+
61
+
62
+ def choose_player(available: list[str], app: str | None, playing: list[str]) -> str | None:
63
+ """The player for `app` if named, otherwise the one playing now, otherwise the only one."""
64
+ if app:
65
+ words = [w for w in re.findall(r"[a-z0-9]+", app.lower()) if w not in {"the", "app"}]
66
+ for bus_name in available:
67
+ short = bus_name.removeprefix(PREFIX).lower()
68
+ if any(word in short for word in words):
69
+ return bus_name
70
+ return None
71
+ if playing:
72
+ return playing[0]
73
+ return available[0] if len(available) == 1 else None
74
+
75
+
76
+ def control(action: str, app: str | None = None) -> str:
77
+ """Send play/pause/next/previous; returns the player's display name."""
78
+ method = METHODS.get(action)
79
+ if method is None:
80
+ raise ActionError(f"Unknown media action {action}.")
81
+ available = players()
82
+ if not available:
83
+ raise ActionError("No music or video app is open.")
84
+ playing = [] if app else [name for name in available if _is_playing(name)]
85
+ target = choose_player(available, app, playing)
86
+ if target is None:
87
+ if app:
88
+ raise ActionError(f"{app.title()} isn't open or doesn't support media controls.")
89
+ names = ", ".join(_label(name) for name in available)
90
+ raise ActionError(f"Which app? I can control {names}.")
91
+ try:
92
+ _gdbus(
93
+ "--dest", target, "--object-path", OBJECT,
94
+ "--method", f"org.mpris.MediaPlayer2.Player.{method}",
95
+ ) # fmt: skip
96
+ except ActionError as exc:
97
+ if "AccessDenied" in str(exc) or "AppArmor" in str(exc):
98
+ raise ActionError(SANDBOX_HINT.format(app=_label(target))) from exc
99
+ raise
100
+ return _label(target)
@@ -0,0 +1,177 @@
1
+ """Screenshots and screen recordings on Linux desktops through D-Bus.
2
+
3
+ Wayland does not let ordinary programs read the screen. Screenshots go through the
4
+ xdg-desktop-portal (the route apps are meant to use) and recordings through GNOME Shell's
5
+ built-in screen recorder, which keeps recording only while the connection that started it
6
+ stays open.
7
+ """
8
+
9
+ import logging
10
+ import shutil
11
+ import threading
12
+ import uuid
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+ from urllib.parse import unquote, urlparse
17
+
18
+ from hi_puter.core.errors import ActionError
19
+
20
+ log = logging.getLogger("hi_puter")
21
+
22
+ PORTAL = "org.freedesktop.portal.Desktop"
23
+ PORTAL_PATH = "/org/freedesktop/portal/desktop"
24
+ SCREENCAST = "org.gnome.Shell.Screencast"
25
+ SCREENCAST_PATH = "/org/gnome/Shell/Screencast"
26
+ MAX_RECORDING_SECONDS = 60 * 60 # stop a forgotten recording after an hour
27
+
28
+
29
+ def screenshots_folder() -> Path:
30
+ return Path.home() / "Pictures" / "Screenshots"
31
+
32
+
33
+ def recordings_folder() -> Path:
34
+ return Path.home() / "Videos" / "Screencasts"
35
+
36
+
37
+ def _jeepney() -> Any:
38
+ try:
39
+ import jeepney
40
+ import jeepney.io.blocking
41
+ except ImportError as exc:
42
+ raise ActionError("Screen capture needs the jeepney package: pip install jeepney") from exc
43
+ return jeepney
44
+
45
+
46
+ def _open_session() -> Any:
47
+ jeepney = _jeepney()
48
+ try:
49
+ return jeepney.io.blocking.open_dbus_connection(bus="SESSION")
50
+ except Exception as exc: # no session bus (e.g. over SSH)
51
+ raise ActionError("No desktop session to capture.") from exc
52
+
53
+
54
+ def _keep(path: Path) -> Path:
55
+ """Move a capture into ~/Pictures/Screenshots with a readable name."""
56
+ folder = screenshots_folder()
57
+ folder.mkdir(parents=True, exist_ok=True)
58
+ if path.parent == folder:
59
+ return path
60
+ target = folder / f"Screenshot {datetime.now():%Y-%m-%d %H-%M-%S}{path.suffix or '.png'}"
61
+ shutil.move(str(path), target)
62
+ return target
63
+
64
+
65
+ def portal_screenshot(interactive: bool, timeout: float = 120) -> Path | None:
66
+ """Ask the desktop portal for a screenshot.
67
+
68
+ Returns the saved file, or None if the user cancelled or the portal refused (a silent
69
+ capture needs a one-time permission that some desktops only grant to known apps).
70
+ """
71
+ jeepney = _jeepney()
72
+ connection = _open_session()
73
+ try:
74
+ token = "hiputer" + uuid.uuid4().hex[:8]
75
+ sender = connection.unique_name[1:].replace(".", "_")
76
+ handle = f"{PORTAL_PATH}/request/{sender}/{token}"
77
+ rule = jeepney.MatchRule(
78
+ type="signal",
79
+ interface="org.freedesktop.portal.Request",
80
+ member="Response",
81
+ path=handle,
82
+ )
83
+ jeepney.io.blocking.Proxy(jeepney.message_bus, connection).AddMatch(rule)
84
+ portal = jeepney.DBusAddress(
85
+ PORTAL_PATH, bus_name=PORTAL, interface="org.freedesktop.portal.Screenshot"
86
+ )
87
+ options = {"handle_token": ("s", token), "interactive": ("b", interactive)}
88
+ with connection.filter(rule) as queue:
89
+ reply = connection.send_and_get_reply(
90
+ jeepney.new_method_call(portal, "Screenshot", "sa{sv}", ("", options))
91
+ )
92
+ if reply.header.message_type.name == "error":
93
+ raise ActionError("The screenshot service isn't available on this desktop.")
94
+ signal = connection.recv_until_filtered(queue, timeout=timeout)
95
+ code, results = signal.body
96
+ if code != 0:
97
+ log.info("Portal screenshot not taken (response %s)", code)
98
+ return None
99
+ path = Path(unquote(urlparse(results.get("uri", ("s", ""))[1]).path))
100
+ return _keep(path) if path.is_file() else None
101
+ except TimeoutError:
102
+ return None
103
+ finally:
104
+ connection.close()
105
+
106
+
107
+ def open_screenshot_tool() -> None:
108
+ """Open the desktop's screenshot tool and save whatever the user captures, in the background."""
109
+
110
+ def wait_for_capture() -> None:
111
+ try:
112
+ path = portal_screenshot(interactive=True, timeout=600)
113
+ log.info("Screenshot %s", f"saved to {path}" if path else "cancelled")
114
+ except ActionError as exc:
115
+ log.warning("Screenshot tool failed: %s", exc)
116
+
117
+ threading.Thread(target=wait_for_capture, daemon=True).start()
118
+
119
+
120
+ class ScreenRecorder:
121
+ """GNOME Shell's built-in recorder, held open by one D-Bus connection."""
122
+
123
+ def __init__(self) -> None:
124
+ self._connection: Any = None
125
+ self._path: Path | None = None
126
+ self._timer: threading.Timer | None = None
127
+ self._lock = threading.Lock()
128
+
129
+ @property
130
+ def recording(self) -> bool:
131
+ return self._connection is not None
132
+
133
+ def start(self, seconds: float | None = None) -> Path:
134
+ jeepney = _jeepney()
135
+ with self._lock:
136
+ if self._connection is not None and self._path is not None:
137
+ return self._path
138
+ folder = recordings_folder()
139
+ folder.mkdir(parents=True, exist_ok=True)
140
+ connection = _open_session()
141
+ shell = jeepney.DBusAddress(SCREENCAST_PATH, bus_name=SCREENCAST, interface=SCREENCAST)
142
+ template = str(folder / "Screencast from %d %t.webm")
143
+ reply = connection.send_and_get_reply(
144
+ jeepney.new_method_call(
145
+ shell, "Screencast", "sa{sv}", (template, {"draw-cursor": ("b", True)})
146
+ )
147
+ )
148
+ started = reply.header.message_type.name != "error" and bool(reply.body[0])
149
+ if not started:
150
+ connection.close()
151
+ raise ActionError("The screen recorder couldn't start on this desktop.")
152
+ self._connection = connection
153
+ self._path = Path(reply.body[1])
154
+ limit = min(seconds, MAX_RECORDING_SECONDS) if seconds else MAX_RECORDING_SECONDS
155
+ self._timer = threading.Timer(limit, self.stop)
156
+ self._timer.daemon = True
157
+ self._timer.start()
158
+ return self._path
159
+
160
+ def stop(self) -> Path | None:
161
+ jeepney = _jeepney()
162
+ with self._lock:
163
+ if self._connection is None:
164
+ return None
165
+ if self._timer is not None:
166
+ self._timer.cancel()
167
+ shell = jeepney.DBusAddress(SCREENCAST_PATH, bus_name=SCREENCAST, interface=SCREENCAST)
168
+ try:
169
+ self._connection.send_and_get_reply(
170
+ jeepney.new_method_call(shell, "StopScreencast")
171
+ )
172
+ finally:
173
+ # Closing the connection also ends the recording if the call failed.
174
+ self._connection.close()
175
+ self._connection = None
176
+ path, self._path = self._path, None
177
+ return path