-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaypaste.py
More file actions
177 lines (140 loc) · 5.09 KB
/
waypaste.py
File metadata and controls
177 lines (140 loc) · 5.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""
waypaste — clipboard image saver for Wayland/Sway
Usage: waypaste
Bind to Ctrl+Alt+V in ~/.config/sway/config:
bindsym Ctrl+Alt+v exec ~/.local/bin/waypaste
"""
# /// script
# requires-python = ">=3.10"
# ///
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path
LAST_DIR_FILE = Path.home() / ".local/share/waypaste/last-dir"
DEFAULT_DIR = Path.home() / "Pictures"
def _check_deps() -> None:
if not shutil.which("wl-paste"):
print("Error: wl-paste not found. Install with: sudo pacman -S wl-clipboard", file=sys.stderr)
sys.exit(1)
try:
import gi # noqa: F401
except ImportError:
print("Error: python-gobject not found. Install with: sudo pacman -S python-gobject", file=sys.stderr)
sys.exit(1)
if not shutil.which("notify-send"):
print("Warning: notify-send not found. Notifications disabled. Install with: sudo pacman -S libnotify", file=sys.stderr)
def get_clipboard_types() -> list[str]:
try:
result = subprocess.run(
["wl-paste", "--list-types"],
capture_output=True, text=True, timeout=5
)
if result.returncode != 0:
return []
return [t.strip() for t in result.stdout.strip().split("\n") if t.strip()]
except (FileNotFoundError, subprocess.TimeoutExpired):
return []
def get_image_bytes() -> bytes | None:
try:
result = subprocess.run(
["wl-paste", "--type", "image/png"],
capture_output=True, timeout=10
)
return result.stdout if result.returncode == 0 and result.stdout else None
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
def notify(summary: str, body: str = "", urgency: str = "normal") -> None:
subprocess.run(
["notify-send", "-u", urgency, summary, body],
check=False
)
def get_last_dir() -> str:
if LAST_DIR_FILE.exists():
path = LAST_DIR_FILE.read_text().strip()
if path and Path(path).is_dir():
return path
return str(DEFAULT_DIR)
def save_last_dir(directory: str) -> None:
LAST_DIR_FILE.parent.mkdir(parents=True, exist_ok=True)
LAST_DIR_FILE.write_text(directory.rstrip("/"))
def default_filename() -> str:
return datetime.now().strftime("%Y-%m-%d-%H%M%S.png")
def _make_preview_widget(image_bytes: bytes):
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import Gtk, GdkPixbuf
try:
loader = GdkPixbuf.PixbufLoader.new_with_type("png")
loader.write(image_bytes)
loader.close()
pixbuf = loader.get_pixbuf()
MAX_SIZE = 200
w, h = pixbuf.get_width(), pixbuf.get_height()
scale = min(MAX_SIZE / w, MAX_SIZE / h, 1.0)
if scale < 1.0:
pixbuf = pixbuf.scale_simple(
int(w * scale), int(h * scale),
GdkPixbuf.InterpType.BILINEAR,
)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
box.pack_start(Gtk.Label(label="Clipboard image"), False, False, 0)
box.pack_start(Gtk.Image.new_from_pixbuf(pixbuf), False, False, 0)
box.show_all()
return box
except Exception:
return None
def show_save_dialog(default_dir: str, default_name: str, image_bytes: bytes) -> str | None:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
dialog = Gtk.FileChooserDialog(
title="Save Clipboard Image",
action=Gtk.FileChooserAction.SAVE,
)
dialog.add_buttons(
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE, Gtk.ResponseType.OK,
)
dialog.set_do_overwrite_confirmation(True)
dialog.set_current_folder(default_dir)
dialog.set_current_name(default_name)
png_filter = Gtk.FileFilter()
png_filter.set_name("PNG Images")
png_filter.add_mime_type("image/png")
dialog.add_filter(png_filter)
preview = _make_preview_widget(image_bytes)
if preview:
dialog.set_preview_widget(preview)
dialog.set_preview_widget_active(True)
response = dialog.run()
path = dialog.get_filename() if response == Gtk.ResponseType.OK else None
dialog.destroy()
# Flush GTK events so the window closes before we proceed
while Gtk.events_pending():
Gtk.main_iteration()
return path
def main() -> None:
_check_deps()
types = get_clipboard_types()
if "image/png" not in types:
notify("waypaste", "No image on clipboard")
sys.exit(0)
image_bytes = get_image_bytes()
if not image_bytes:
notify("waypaste", "Failed to read image from clipboard", urgency="critical")
sys.exit(1)
save_path = show_save_dialog(get_last_dir(), default_filename(), image_bytes)
if save_path is None:
sys.exit(0)
if not save_path.lower().endswith(".png"):
save_path += ".png"
dest = Path(save_path)
dest.write_bytes(image_bytes)
save_last_dir(str(dest.parent))
notify("waypaste", f"Saved: {dest.name}")
if __name__ == "__main__":
main()