Debian Codegraph @

nwg_clipman/main.py

raw
1 #!/usr/bin/env python
2
3 """
4 nwg-shell clipboard manager (GUI for cliphist by Senan Kelly)
5 Copyright (c) 2024-2025 Piotr Miller & Contributors
6 e-mail: [email protected]
7 Project: https://github.com/nwg-piotr/nwg-clipman
8 License: MIT
9 """
10
11 import argparse
12 import os.path
13 import signal
14 import sys
15
16 import gi
17
18 gi.require_version('Gtk', '3.0')
19 try:
20 gi.require_version('GtkLayerShell', '0.1')
21 except ValueError:
22 raise RuntimeError('\n\n' +
23 'If you haven\'t installed GTK Layer Shell, you need to point Python to the\n' +
24 'library by setting GI_TYPELIB_PATH and LD_LIBRARY_PATH to <build-dir>/src/.\n' +
25 'For example you might need to run:\n\n' +
26 'GI_TYPELIB_PATH=build/src LD_LIBRARY_PATH=build/src python3 ' + ' '.join(sys.argv))
27
28 from nwg_clipman.tools import *
29 from nwg_clipman.__about__ import __version__
30 from gi.repository import Gtk, Gdk, GtkLayerShell, GdkPixbuf, Pango
31
32 dir_name = os.path.dirname(__file__)
33 pid = os.getpid()
34 args = None
35 voc = {}
36 tmp_file = os.path.join(temp_dir(), "clipman.dump")
37 window = None
38 search_entry = None
39 flowbox_wrapper = None
40 flowbox = None
41 preview_frame = None
42 btn_copy = None
43 selected_item = None
44 exit_code = None
45
46 if not is_command("cliphist") or not is_command("wl-copy"):
47 # die if dependencies check failed
48 eprint("Dependencies (cliphist, wl-clipboard) check failed, terminating")
49 sys.exit(1)
50
51
52 def list_cliphist():
53 # query cliphist
54 try:
55 output = subprocess.check_output("cliphist list", shell=True).decode('utf-8', errors="ignore").splitlines()
56 return output
57 except subprocess.CalledProcessError:
58 return []
59
60
61 def quit_with_exit_code(ec):
62 global exit_code
63 exit_code = ec
64 Gtk.main_quit()
65
66
67 def signal_handler(sig, frame):
68 # gentle handle termination
69 desc = {2: "SIGINT", 15: "SIGTERM"}
70 if sig == 2 or sig == 15:
71 eprint("Terminated with {}".format(desc[sig]))
72 quit_with_exit_code(128 + sig)
73
74
75 def terminate_old_instance():
76 pid_file = os.path.join(temp_dir(), "nwg-clipman-pid")
77 if os.path.isfile(pid_file):
78 try:
79 old_pid = int(load_text_file(pid_file))
80 if old_pid != pid:
81 print(f"Attempting to kill the old instance in case it's still running, pid: {old_pid}")
82 os.kill(old_pid, signal.SIGINT)
83 except:
84 pass
85 # save new pid
86 save_string(str(pid), pid_file)
87
88
89 def handle_keyboard(win, event):
90 # on Esc key first search entry if not empty, else terminate
91 global search_entry
92 if event.type == Gdk.EventType.KEY_RELEASE and event.keyval == Gdk.KEY_Escape:
93 if search_entry.get_text():
94 search_entry.set_text("")
95 else:
96 quit_with_exit_code(1)
97
98
99 def load_vocabulary():
100 # translate UI
101 global voc
102 # basic vocabulary (en_US)
103 voc = load_json(os.path.join(dir_name, "langs", "en_US.json"))
104 if not voc:
105 eprint("Failed loading vocabulary, terminating")
106 sys.exit(1)
107
108 # check "interface-locale" forced in nwg-shell data file - if forced, and the file exists
109 shell_data = load_shell_data()
110
111 lang = os.getenv("LANG")
112 if lang is None:
113 lang = "en_US"
114 else:
115 lang = lang.split(".")[0] if not shell_data["interface-locale"] else shell_data["interface-locale"]
116
117 # translate if translation available
118 if lang != "en_US":
119 loc_file = os.path.join(dir_name, "langs", "{}.json".format(lang))
120 if os.path.isfile(loc_file):
121 # localized vocabulary
122 loc = load_json(loc_file)
123 if not loc:
124 eprint(f"Failed loading translation '{loc_file}'")
125 else:
126 print(f"Loaded translation file: '{loc_file}'")
127 for key in loc:
128 voc[key] = loc[key]
129 else:
130 eprint(f"Translation into {lang} not found")
131
132
133 def on_enter_notify_event(widget, event):
134 # highlight item
135 widget.set_state_flags(Gtk.StateFlags.DROP_ACTIVE, clear=False)
136 widget.set_state_flags(Gtk.StateFlags.SELECTED, clear=False)
137
138
139 def on_leave_notify_event(widget, event):
140 # clear highlight
141 widget.unset_state_flags(Gtk.StateFlags.DROP_ACTIVE)
142 widget.unset_state_flags(Gtk.StateFlags.SELECTED)
143
144
145 def flowbox_filter(_search_entry):
146 # filter flowbox visibility by search_entry content
147 def filter_func(fb_child, _text):
148 if _text in fb_child.get_name():
149 return True
150 else:
151 return False
152
153 text = _search_entry.get_text()
154 flowbox.set_filter_func(filter_func, text)
155
156
157 def on_child_activated(fb, child):
158 # on flowbox item clicked
159 global selected_item
160 selected_item = child.get_name()
161 name = bytes(child.get_name(), 'utf-8')
162 subprocess.run(f"cliphist decode > {tmp_file}", shell=True, input=name)
163 preview()
164
165
166 def preview():
167 # create preview frame content
168 pixbuf = None
169 try:
170 pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(tmp_file, 256, 256)
171 except Exception as e:
172 pass
173
174 for child in preview_frame.get_children():
175 child.destroy()
176 preview_frame.set_label(voc["preview"])
177
178 if pixbuf:
179 scrolled = Gtk.ScrolledWindow()
180 scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
181 scrolled.set_min_content_height(256)
182 preview_frame.add(scrolled)
183
184 image = Gtk.Image.new_from_pixbuf(pixbuf)
185 scrolled.add(image)
186 else:
187 scrolled = Gtk.ScrolledWindow()
188 scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
189 scrolled.set_min_content_height(256)
190 preview_frame.add(scrolled)
191
192 text = load_text_file(tmp_file)
193 if not text:
194 text = voc["preview-unavailable"]
195 label = Gtk.Label.new(text)
196 label.set_max_width_chars(80)
197 label.set_line_wrap(True)
198 label.set_line_wrap_mode(Pango.WrapMode.CHAR)
199
200 scrolled.add(label)
201 scrolled.set_property("name", "preview-window")
202
203 btn_copy.set_sensitive(True)
204 preview_frame.show_all()
205
206
207 def on_del_button(btn, name):
208 # delete entry from cliphist
209 eprint(f"Delete '{name}'")
210 name = bytes(name, 'utf-8')
211 subprocess.run("cliphist delete", shell=True, input=name)
212 search_entry.set_text("")
213 build_flowbox()
214
215
216 def on_copy_button(btn):
217 eprint(f"Copying: '{selected_item}'")
218 name = bytes(selected_item, 'utf-8')
219 subprocess.run("cliphist decode | wl-copy", shell=True, input=name)
220 Gtk.main_quit()
221
222
223 def on_wipe_button(btn):
224 win = ConfirmationWindow()
225
226
227 class ConfirmationWindow(Gtk.Window):
228 def __init__(self):
229 Gtk.Window.__init__(self, type=Gtk.WindowType.POPUP)
230 self.set_modal(True)
231 self.set_destroy_with_parent(True)
232
233 self.connect("key-release-event", self.handle_keyboard)
234
235 GtkLayerShell.init_for_window(self)
236 GtkLayerShell.set_layer(self, GtkLayerShell.Layer.OVERLAY)
237
238 vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
239 vbox.set_property("name", "warning")
240 self.add(vbox)
241 lbl = Gtk.Label.new(f'{voc["clear-clipboard-history"]}?')
242 vbox.pack_start(lbl, False, False, 6)
243 hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
244
245 vbox.pack_start(hbox, False, False, 6)
246 btn = Gtk.Button.new_with_label(voc["clear"])
247 btn.connect("clicked", self.clear_history)
248 hbox.pack_start(btn, False, False, 0)
249
250 btn = Gtk.Button.new_with_label(voc["close"])
251 btn.connect("clicked", self.quit)
252 hbox.pack_start(btn, False, False, 0)
253
254 self.show_all()
255
256 def quit(self, btn):
257 self.destroy()
258
259 def handle_keyboard(self, win, event):
260 if event.type == Gdk.EventType.KEY_RELEASE and event.keyval == Gdk.KEY_Escape:
261 self.destroy()
262
263 def clear_history(self, btn):
264 eprint("Wipe cliphist")
265 subprocess.run("cliphist wipe", shell=True)
266
267 quit_with_exit_code(2)
268
269
270 class FlowboxItem(Gtk.Box):
271 def __init__(self, parts):
272 Gtk.EventBox.__init__(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
273
274 if args.numbers:
275 label = Gtk.Label.new(parts[0])
276 self.add(label)
277
278 eb = Gtk.EventBox()
279 self.pack_start(eb, True, True, 0)
280 name = parts[1]
281 label = Gtk.Label.new(name)
282 label.set_max_width_chars(80)
283 label.set_line_wrap(True)
284 label.set_property("halign", Gtk.Align.START)
285 eb.add(label)
286
287 button = Gtk.Button.new_from_icon_name("edit-clear", Gtk.IconSize.MENU)
288 button.set_property("name", "del-btn")
289 button.set_property("margin-right", 9)
290 button.connect("clicked", on_del_button, "\t".join(parts))
291 self.pack_end(button, False, False, 0)
292
293 eb.connect('enter-notify-event', on_enter_notify_event)
294 eb.connect('leave-notify-event', on_leave_notify_event)
295
296
297 def build_flowbox():
298 global flowbox_wrapper
299 global flowbox
300 # destroy flowbox wrapper content, if any
301 for item in flowbox_wrapper.get_children():
302 item.destroy()
303
304 # build from scratch
305 scrolled = Gtk.ScrolledWindow()
306 scrolled.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
307 scrolled.set_min_content_height(300)
308 scrolled.set_propagate_natural_height(True)
309 flowbox_wrapper.add(scrolled)
310
311 flowbox = Gtk.FlowBox()
312 flowbox.set_selection_mode(Gtk.SelectionMode.NONE)
313 flowbox.connect("child-activated", on_child_activated)
314 flowbox.set_valign(Gtk.Align.START)
315 flowbox.set_max_children_per_line(1)
316 scrolled.add(flowbox)
317
318 # query cliphist
319 clip_hist = list_cliphist()
320
321 for line in clip_hist:
322 try:
323 parts = line.split("\t")
324 _name = parts[1]
325
326 item = FlowboxItem(parts)
327 child = Gtk.FlowBoxChild()
328 # we will be filtering by _name
329 child.set_name(line)
330 child.add(item)
331 flowbox.add(child)
332 except IndexError:
333 eprint(f"Error parsing line: {line}")
334
335 flowbox_wrapper.show_all()
336
337
338 def main():
339 # handle signals
340 catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP}
341 for sig in catchable_sigs:
342 signal.signal(sig, signal_handler)
343
344 # arguments
345 parser = argparse.ArgumentParser()
346 parser.add_argument("-v", "--version", action="version",
347 version="%(prog)s version {}".format(__version__),
348 help="display Version information")
349 parser.add_argument("-n", "--numbers", action="store_true", help="show item Numbers in the list")
350 parser.add_argument("-w", "--window", action="store_true", help="run in regular Window, w/o layer shell")
351
352 global args
353 args = parser.parse_args()
354
355 # kill running instance, if any
356 terminate_old_instance()
357
358 global search_entry
359
360 # UI strings localization
361 load_vocabulary()
362
363 global window
364 window = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
365
366 def exit_1(widget):
367 quit_with_exit_code(1)
368
369 if not args.window:
370 # attach to gtk-layer-shell
371 GtkLayerShell.init_for_window(window)
372 GtkLayerShell.set_layer(window, GtkLayerShell.Layer.TOP)
373 GtkLayerShell.set_exclusive_zone(window, 0)
374 GtkLayerShell.set_keyboard_mode(window, GtkLayerShell.KeyboardMode.ON_DEMAND)
375
376 window.connect('destroy', exit_1)
377 window.connect("key-release-event", handle_keyboard)
378
379 vbox = Gtk.Box.new(orientation=Gtk.Orientation.VERTICAL, spacing=6)
380 vbox.set_property("name", "main-wrapper")
381 window.add(vbox)
382
383 hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0)
384 vbox.pack_start(hbox, False, False, 0)
385
386 # search entry
387 search_entry = Gtk.SearchEntry()
388 search_entry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "edit-clear-symbolic")
389 search_entry.set_property("hexpand", True)
390 search_entry.set_property("margin", 12)
391 search_entry.set_size_request(700, 0)
392 search_entry.connect('search_changed', flowbox_filter)
393 hbox.pack_start(search_entry, False, True, 0)
394
395 # "Clear" button next to search entry
396 btn = Gtk.Button.new_with_label(voc["clear"])
397 btn.set_property("valign", Gtk.Align.CENTER)
398 btn.connect("clicked", on_wipe_button)
399 hbox.pack_start(btn, False, False, 6)
400
401 # wrapper for the flowbox
402 global flowbox_wrapper
403 flowbox_wrapper = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
404 flowbox_wrapper.set_property("margin-left", 12)
405 flowbox_wrapper.set_property("margin-right", 12)
406 vbox.pack_start(flowbox_wrapper, False, False, 0)
407
408 # clear flowbox wrapper, build content
409 build_flowbox()
410
411 hbox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
412 hbox.set_property("margin", 12)
413 vbox.pack_end(hbox, False, False, 0)
414
415 global preview_frame
416 preview_frame = Gtk.Frame.new(voc["preview"])
417 hbox.pack_start(preview_frame, True, True, 0)
418
419 # temporary placeholder for future content preview
420 placeholder_box = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
421 preview_frame.add(placeholder_box)
422 placeholder_box.set_size_request(0, 256)
423 preview_frame.show_all()
424
425 # "Clear" and "Close" buttons
426 ibox = Gtk.Box.new(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
427 ibox.set_homogeneous(True)
428 hbox.pack_end(ibox, False, False, 0)
429
430 # "Copy" button
431 global btn_copy
432 btn_copy = Gtk.Button.new_with_label(voc["copy"])
433 btn_copy.set_property("valign", Gtk.Align.END)
434 btn_copy.connect("clicked", on_copy_button)
435 btn_copy.set_sensitive(False)
436 ibox.pack_start(btn_copy, True, True, 0)
437
438 # "Close" button
439 btn = Gtk.Button.new_with_label(voc["close"])
440 btn.set_property("valign", Gtk.Align.END)
441 btn.connect("clicked", exit_1)
442 ibox.pack_start(btn, True, True, 0)
443
444 window.show_all()
445
446 # customize styling
447 screen = Gdk.Screen.get_default()
448 provider = Gtk.CssProvider()
449 style_context = Gtk.StyleContext()
450 style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
451
452 css = b"""
453 #main-wrapper { background-color: rgba(0, 0, 0, 0.1) }
454 #preview-window { padding: 0 6px 0 6px }
455 #del-btn { background: none; border: none; margin: 0; padding: 0 }
456 #del-btn:hover { background-color: rgba(255, 255, 255, 0.1) }
457 #warning { border: solid 1px; padding: 24px; margin: 6px}
458 """
459 provider.load_from_data(css)
460
461 Gtk.main()
462
463
464 if __name__ == "__main__":
465 main()
466 sys.exit(exit_code)