waysnip 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 (43) hide show
  1. waysnip/__init__.py +1 -0
  2. waysnip/__main__.py +6 -0
  3. waysnip/app.py +275 -0
  4. waysnip/capture/__init__.py +14 -0
  5. waysnip/capture/clipboard.py +62 -0
  6. waysnip/capture/portal.py +137 -0
  7. waysnip/capture/region_selector.py +400 -0
  8. waysnip/cli.py +270 -0
  9. waysnip/config.py +121 -0
  10. waysnip/constants.py +52 -0
  11. waysnip/editor/__init__.py +29 -0
  12. waysnip/editor/canvas.py +129 -0
  13. waysnip/editor/commands.py +114 -0
  14. waysnip/editor/editor_window.py +441 -0
  15. waysnip/editor/properties_panel.py +297 -0
  16. waysnip/editor/scene.py +118 -0
  17. waysnip/editor/toolbar.py +231 -0
  18. waysnip/editor/tools/__init__.py +46 -0
  19. waysnip/editor/tools/arrow.py +168 -0
  20. waysnip/editor/tools/base.py +311 -0
  21. waysnip/editor/tools/blur.py +209 -0
  22. waysnip/editor/tools/crop.py +151 -0
  23. waysnip/editor/tools/ellipse.py +120 -0
  24. waysnip/editor/tools/freehand.py +119 -0
  25. waysnip/editor/tools/highlight.py +126 -0
  26. waysnip/editor/tools/line.py +149 -0
  27. waysnip/editor/tools/numbered_marker.py +177 -0
  28. waysnip/editor/tools/rectangle.py +137 -0
  29. waysnip/editor/tools/select_tool.py +178 -0
  30. waysnip/editor/tools/text.py +240 -0
  31. waysnip/gallery/__init__.py +14 -0
  32. waysnip/gallery/gallery_window.py +191 -0
  33. waysnip/gallery/thumbnail_delegate.py +76 -0
  34. waysnip/gallery/thumbnail_model.py +81 -0
  35. waysnip/resources/style.qss +262 -0
  36. waysnip/save.py +156 -0
  37. waysnip/settings_dialog.py +312 -0
  38. waysnip/tray.py +100 -0
  39. waysnip-0.1.0.dist-info/METADATA +147 -0
  40. waysnip-0.1.0.dist-info/RECORD +43 -0
  41. waysnip-0.1.0.dist-info/WHEEL +4 -0
  42. waysnip-0.1.0.dist-info/entry_points.txt +2 -0
  43. waysnip-0.1.0.dist-info/licenses/LICENSE +674 -0
waysnip/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """WaySnip - Lightweight Wayland screenshot and annotation tool."""
waysnip/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Allow running as `python -m waysnip`."""
2
+
3
+ from waysnip.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
waysnip/app.py ADDED
@@ -0,0 +1,275 @@
1
+ """Application singleton — single-instance IPC, orchestration, lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from PyQt6.QtCore import QByteArray
11
+ from PyQt6.QtGui import QPixmap
12
+ from PyQt6.QtNetwork import QLocalServer, QLocalSocket
13
+ from PyQt6.QtWidgets import QApplication
14
+
15
+ from waysnip.config import AppConfig
16
+ from waysnip.constants import APP_DISPLAY_NAME, SOCKET_NAME_TEMPLATE
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Optional imports for modules built by other agents. Stubs are used when
20
+ # the real modules are not yet available.
21
+ # ---------------------------------------------------------------------------
22
+ from waysnip.capture.portal import capture_fullscreen, capture_interactive
23
+ from waysnip.capture.region_selector import RegionSelector
24
+ from waysnip.capture.clipboard import ClipboardManager
25
+ from waysnip.editor.editor_window import EditorWindow
26
+ from waysnip.save import save_screenshot
27
+
28
+
29
+ def _socket_name() -> str:
30
+ return SOCKET_NAME_TEMPLATE.format(uid=os.getuid())
31
+
32
+
33
+ def _try_send_to_running_instance(command: str) -> bool:
34
+ """Attempt to send *command* to an already-running WaySnip instance.
35
+
36
+ Returns True if the message was sent (meaning we should exit), False if no
37
+ running instance was found.
38
+ """
39
+ sock = QLocalSocket()
40
+ sock.connectToServer(_socket_name())
41
+ if not sock.waitForConnected(500):
42
+ return False
43
+
44
+ payload = json.dumps({"command": command}).encode()
45
+ sock.write(QByteArray(payload))
46
+ sock.waitForBytesWritten(1000)
47
+ sock.disconnectFromServer()
48
+ return True
49
+
50
+
51
+ class WaySnipApp:
52
+ """Top-level application object that owns the Qt event loop."""
53
+
54
+ def __init__(self, command: str) -> None:
55
+ self._app = QApplication.instance() or QApplication(sys.argv)
56
+ self._app.setApplicationName(APP_DISPLAY_NAME)
57
+ self._app.setQuitOnLastWindowClosed(False)
58
+
59
+ self._config = AppConfig.load()
60
+ self._server: QLocalServer | None = None
61
+ self._tray = None
62
+ self._gallery_window = None
63
+ self._settings_dialog = None
64
+ self._pending_command = command
65
+
66
+ self._load_stylesheet()
67
+
68
+ # ---- Lifecycle ---------------------------------------------------------
69
+
70
+ def start(self) -> int:
71
+ """Set up the local server, tray icon, and execute the initial command."""
72
+ self._start_server()
73
+
74
+ if self._config.tray.enabled:
75
+ from waysnip.tray import TrayIcon
76
+
77
+ self._tray = TrayIcon(self)
78
+ self._tray.show()
79
+
80
+ # Keep app alive until we explicitly allow quitting.
81
+ # Without tray, the app should quit when the last editor/gallery
82
+ # window closes — but NOT when the region selector closes.
83
+ self._app.setQuitOnLastWindowClosed(False)
84
+
85
+ self._dispatch(self._pending_command)
86
+
87
+ return self._app.exec()
88
+
89
+ # ---- IPC Server --------------------------------------------------------
90
+
91
+ def _start_server(self) -> None:
92
+ self._server = QLocalServer(self._app)
93
+ # Remove stale socket if present.
94
+ QLocalServer.removeServer(_socket_name())
95
+ if not self._server.listen(_socket_name()):
96
+ print(f"Warning: could not start IPC server: {self._server.errorString()}")
97
+ return
98
+ self._server.newConnection.connect(self._on_new_connection)
99
+
100
+ def _on_new_connection(self) -> None:
101
+ conn = self._server.nextPendingConnection()
102
+ if conn is None:
103
+ return
104
+ conn.waitForReadyRead(1000)
105
+ data = conn.readAll().data()
106
+ conn.close()
107
+ try:
108
+ msg = json.loads(data.decode())
109
+ self._dispatch(msg.get("command", "region"))
110
+ except (json.JSONDecodeError, UnicodeDecodeError):
111
+ pass
112
+
113
+ # ---- Command dispatch --------------------------------------------------
114
+
115
+ def _dispatch(self, command: str) -> None:
116
+ if command == "tray":
117
+ # Just stay in tray, no action
118
+ return
119
+ actions = {
120
+ "region": self.do_capture_region,
121
+ "window": self.do_capture_window,
122
+ "fullscreen": self.do_capture_fullscreen,
123
+ "gallery": self.do_open_gallery,
124
+ "config": self.do_open_settings,
125
+ }
126
+ action = actions.get(command, self.do_capture_region)
127
+ action()
128
+
129
+ # ---- Capture orchestration ---------------------------------------------
130
+
131
+ def do_capture_region(self) -> None:
132
+ show_cursor = self._config.capture.show_cursor
133
+ path = capture_fullscreen(show_cursor=show_cursor)
134
+ if path is None:
135
+ return
136
+ pixmap = QPixmap(str(path))
137
+ if pixmap.isNull():
138
+ return
139
+
140
+ def _on_region_selected(cropped):
141
+ if cropped is None or cropped.isNull():
142
+ return
143
+ self._copy_to_clipboard(cropped)
144
+ self._post_capture(cropped)
145
+
146
+ def _on_cancelled():
147
+ if not self._config.tray.enabled:
148
+ self._app.quit()
149
+
150
+ self._region_selector = RegionSelector(pixmap)
151
+ self._region_selector.region_selected.connect(_on_region_selected)
152
+ self._region_selector.cancelled.connect(_on_cancelled)
153
+ self._region_selector.show()
154
+
155
+ def do_capture_window(self) -> None:
156
+ path = capture_interactive()
157
+ if path is None:
158
+ return
159
+ pixmap = QPixmap(str(path))
160
+ if pixmap.isNull():
161
+ return
162
+ self._copy_to_clipboard(pixmap)
163
+ self._post_capture(pixmap)
164
+
165
+ def do_capture_fullscreen(self) -> None:
166
+ show_cursor = self._config.capture.show_cursor
167
+ path = capture_fullscreen(show_cursor=show_cursor)
168
+ if path is None:
169
+ return
170
+ pixmap = QPixmap(str(path))
171
+ if pixmap.isNull():
172
+ return
173
+ self._copy_to_clipboard(pixmap)
174
+ self._post_capture(pixmap)
175
+
176
+ # ---- Gallery / Settings ------------------------------------------------
177
+
178
+ def do_open_gallery(self) -> None:
179
+ from waysnip.gallery.gallery_window import GalleryWindow
180
+
181
+ if self._gallery_window is None:
182
+ self._gallery_window = GalleryWindow(self._config)
183
+ self._gallery_window.show()
184
+ self._gallery_window.raise_()
185
+ self._gallery_window.activateWindow()
186
+
187
+ def do_open_settings(self) -> None:
188
+ from waysnip.settings_dialog import SettingsDialog
189
+
190
+ if self._settings_dialog is None or not self._settings_dialog.isVisible():
191
+ self._settings_dialog = SettingsDialog(self._config)
192
+ self._settings_dialog.config_saved.connect(self._on_config_saved)
193
+ self._settings_dialog.show()
194
+ self._settings_dialog.raise_()
195
+ self._settings_dialog.activateWindow()
196
+
197
+ # ---- Helpers -----------------------------------------------------------
198
+
199
+ def _post_capture(self, pixmap) -> None:
200
+ """Open editor or save, depending on config."""
201
+ action = self._config.capture.after_capture
202
+ if action == "editor":
203
+ self._open_editor(pixmap)
204
+ elif action == "save":
205
+ self._save_pixmap(pixmap)
206
+ elif action == "clipboard+save":
207
+ self._save_pixmap(pixmap)
208
+ # "clipboard" — already copied above, nothing more to do.
209
+
210
+ def _open_editor(self, pixmap) -> None:
211
+ win = EditorWindow(pixmap, self._config)
212
+ # Keep a reference so the window isn't garbage collected
213
+ if not hasattr(self, "_editor_windows"):
214
+ self._editor_windows = []
215
+ self._editor_windows.append(win)
216
+ def _on_editor_destroyed():
217
+ if win in self._editor_windows:
218
+ self._editor_windows.remove(win)
219
+ # If no tray and no more windows, quit
220
+ if not self._config.tray.enabled and not self._editor_windows:
221
+ self._app.quit()
222
+
223
+ win.destroyed.connect(_on_editor_destroyed)
224
+ win.image_saved.connect(self._on_image_saved)
225
+ win.show()
226
+ win.raise_()
227
+ win.activateWindow()
228
+
229
+ def _save_pixmap(self, pixmap, annotations=None, original_pixmap=None) -> None:
230
+ path = save_screenshot(pixmap, annotations or [], original_pixmap, self._config)
231
+ return path
232
+
233
+ @staticmethod
234
+ def _copy_to_clipboard(pixmap) -> None:
235
+ ClipboardManager.copy_image_from_pixmap(pixmap)
236
+
237
+ def _on_image_saved(self, path: str) -> None:
238
+ """Refresh the gallery when an editor saves."""
239
+ if self._gallery_window is not None:
240
+ self._gallery_window.refresh()
241
+
242
+ def _on_config_saved(self) -> None:
243
+ self._config = AppConfig.load()
244
+ if self._tray is not None:
245
+ self._tray.reload_config(self._config)
246
+ # Propagate to open editor windows
247
+ if hasattr(self, "_editor_windows"):
248
+ for win in self._editor_windows:
249
+ if hasattr(win, "_config"):
250
+ win._config = self._config
251
+ # Propagate to gallery
252
+ if self._gallery_window is not None:
253
+ self._gallery_window._config = self._config
254
+
255
+ def _load_stylesheet(self) -> None:
256
+ qss_path = Path(__file__).parent / "resources" / "style.qss"
257
+ if qss_path.exists():
258
+ self._app.setStyleSheet(qss_path.read_text())
259
+
260
+
261
+
262
+ # ---------------------------------------------------------------------------
263
+ # Public entry point called from cli.py
264
+ # ---------------------------------------------------------------------------
265
+
266
+ def run(command: str) -> None:
267
+ """Start WaySnip or talk to an existing instance."""
268
+ # We need a QApplication for QLocalSocket even when just sending IPC.
269
+ _temp_app = QApplication.instance() or QApplication(sys.argv)
270
+
271
+ if _try_send_to_running_instance(command):
272
+ sys.exit(0)
273
+
274
+ app = WaySnipApp(command)
275
+ sys.exit(app.start())
@@ -0,0 +1,14 @@
1
+ """Capture pipeline — portal integration, region selection, and clipboard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from waysnip.capture.clipboard import ClipboardManager
6
+ from waysnip.capture.portal import capture_fullscreen, capture_interactive
7
+ from waysnip.capture.region_selector import RegionSelector
8
+
9
+ __all__ = [
10
+ "ClipboardManager",
11
+ "RegionSelector",
12
+ "capture_fullscreen",
13
+ "capture_interactive",
14
+ ]
@@ -0,0 +1,62 @@
1
+ """Clipboard integration via wl-copy for Wayland."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from PyQt6.QtCore import QBuffer, QIODevice
9
+ from PyQt6.QtGui import QPixmap
10
+
11
+
12
+ class ClipboardManager:
13
+ """Manage Wayland clipboard via ``wl-copy``.
14
+
15
+ Wayland uses a lazy-clipboard model — the source process must stay alive
16
+ for other apps to paste. We keep the ``wl-copy`` subprocess around until
17
+ a new copy replaces it (or the manager is garbage-collected).
18
+ """
19
+
20
+ _process: subprocess.Popen | None = None
21
+
22
+ @classmethod
23
+ def copy_image(cls, image_data: bytes) -> None:
24
+ """Copy raw PNG bytes to the Wayland clipboard.
25
+
26
+ Any previously running ``wl-copy`` process is killed first.
27
+ """
28
+ cls._kill_previous()
29
+ cls._process = subprocess.Popen(
30
+ ["wl-copy", "--type", "image/png"],
31
+ stdin=subprocess.PIPE,
32
+ )
33
+ # Write all data and close stdin so wl-copy knows the payload is
34
+ # complete, but do NOT wait — the process must stay alive.
35
+ assert cls._process.stdin is not None
36
+ cls._process.stdin.write(image_data)
37
+ cls._process.stdin.close()
38
+
39
+ @classmethod
40
+ def copy_image_from_file(cls, path: Path) -> None:
41
+ """Read a PNG file and copy it to the clipboard."""
42
+ data = path.read_bytes()
43
+ cls.copy_image(data)
44
+
45
+ @classmethod
46
+ def copy_image_from_pixmap(cls, pixmap: QPixmap) -> None:
47
+ """Convert a QPixmap to PNG and copy it to the clipboard."""
48
+ buf = QBuffer()
49
+ buf.open(QIODevice.OpenModeFlag.WriteOnly)
50
+ pixmap.save(buf, "PNG")
51
+ cls.copy_image(bytes(buf.data()))
52
+
53
+ @classmethod
54
+ def _kill_previous(cls) -> None:
55
+ """Terminate any existing wl-copy process."""
56
+ if cls._process is not None:
57
+ try:
58
+ cls._process.kill()
59
+ cls._process.wait(timeout=2)
60
+ except (ProcessLookupError, subprocess.TimeoutExpired):
61
+ pass
62
+ cls._process = None
@@ -0,0 +1,137 @@
1
+ """Screen capture backends for Wayland.
2
+
3
+ On GNOME: uses gnome-screenshot for fast silent capture, falls back to
4
+ xdg-desktop-portal interactive mode for window selection.
5
+
6
+ On wlroots compositors: could use grim (not yet implemented).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import subprocess
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+
16
+ def capture_fullscreen(show_cursor: bool = False) -> Path | None:
17
+ """Take a full-screen screenshot silently.
18
+
19
+ Uses gnome-screenshot which works on GNOME Wayland without portal
20
+ permission dialogs.
21
+ """
22
+ tmp = tempfile.NamedTemporaryFile(suffix=".png", prefix="waysnip_", delete=False)
23
+ tmp.close()
24
+ path = Path(tmp.name)
25
+
26
+ cmd = ["gnome-screenshot", "-f", str(path)]
27
+ if show_cursor:
28
+ cmd.append("--include-pointer")
29
+
30
+ try:
31
+ result = subprocess.run(cmd, capture_output=True, timeout=10)
32
+ if result.returncode != 0:
33
+ print(f"gnome-screenshot failed: {result.stderr.decode()}")
34
+ return None
35
+ if not path.exists() or path.stat().st_size == 0:
36
+ print("gnome-screenshot produced no output")
37
+ return None
38
+ return path
39
+ except FileNotFoundError:
40
+ print("gnome-screenshot not found, falling back to portal")
41
+ return _capture_via_portal(interactive=False)
42
+ except subprocess.TimeoutExpired:
43
+ print("gnome-screenshot timed out")
44
+ return None
45
+
46
+
47
+ def capture_interactive() -> Path | None:
48
+ """Open the portal's interactive screenshot picker (GNOME's own UI).
49
+
50
+ This shows GNOME's built-in screenshot tool where the user can select
51
+ a region, window, or full screen.
52
+ """
53
+ # For interactive mode, the portal is the right approach since GNOME
54
+ # shows its own polished UI.
55
+ return _capture_via_portal(interactive=True)
56
+
57
+
58
+ def _capture_via_portal(interactive: bool) -> Path | None:
59
+ """Use gdbus to call the xdg-desktop-portal Screenshot method.
60
+
61
+ We use gdbus subprocess instead of Qt's D-Bus bindings because
62
+ PyQt6's QDBusConnection.connect() has issues with portal response
63
+ signals on GNOME.
64
+ """
65
+
66
+ interactive_str = "true" if interactive else "false"
67
+ cmd = [
68
+ "gdbus", "call", "--session",
69
+ "--dest", "org.freedesktop.portal.Desktop",
70
+ "--object-path", "/org/freedesktop/portal/desktop",
71
+ "--method", "org.freedesktop.portal.Screenshot.Screenshot",
72
+ "",
73
+ f'{{"interactive": <{interactive_str}>}}',
74
+ ]
75
+
76
+ try:
77
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
78
+ if result.returncode != 0:
79
+ print(f"Portal call failed: {result.stderr}")
80
+ return None
81
+ except subprocess.TimeoutExpired:
82
+ print("Portal call timed out")
83
+ return None
84
+
85
+ # The gdbus call returns immediately with a request path.
86
+ # The actual screenshot happens asynchronously via GNOME's UI.
87
+ # We need to listen for the response signal.
88
+ # Use gdbus monitor for this.
89
+ try:
90
+ monitor = subprocess.Popen(
91
+ [
92
+ "dbus-monitor", "--session",
93
+ "type='signal',interface='org.freedesktop.portal.Request',member='Response'",
94
+ ],
95
+ stdout=subprocess.PIPE,
96
+ stderr=subprocess.PIPE,
97
+ )
98
+ # Wait for the user to complete the screenshot in GNOME's UI
99
+ # (up to 60 seconds for interactive mode)
100
+ timeout = 60 if interactive else 15
101
+ output_lines = []
102
+ import select
103
+ import time
104
+
105
+ deadline = time.monotonic() + timeout
106
+ while time.monotonic() < deadline:
107
+ remaining = deadline - time.monotonic()
108
+ if remaining <= 0:
109
+ break
110
+ ready, _, _ = select.select([monitor.stdout], [], [], min(remaining, 0.5))
111
+ if ready:
112
+ line = monitor.stdout.readline().decode("utf-8", errors="replace")
113
+ if not line:
114
+ break
115
+ output_lines.append(line)
116
+ # Look for the uri in the response
117
+ if "string" in line and "file://" in line:
118
+ monitor.kill()
119
+ uri = line.strip().split('"')[1] if '"' in line else ""
120
+ if uri.startswith("file://"):
121
+ from urllib.parse import urlparse, unquote
122
+ return Path(unquote(urlparse(uri).path))
123
+
124
+ # Check for response code indicating failure
125
+ if "uint32 1" in line or "uint32 2" in line:
126
+ monitor.kill()
127
+ print("Portal screenshot was cancelled or denied")
128
+ return None
129
+
130
+ monitor.kill()
131
+ monitor.wait(timeout=2)
132
+ print("Portal interactive screenshot timed out")
133
+ return None
134
+
135
+ except Exception as e:
136
+ print(f"Portal monitor error: {e}")
137
+ return None