-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag-gui
executable file
·481 lines (418 loc) · 15.6 KB
/
tag-gui
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python
# tag-gui - Edit the TMSU tags for the specified file(s) with a tab-completing gui.
# Shows the filename (or the common directory if tagging multiple) and the previous set of tags, and allows you to edit the set, with tab-completion of tag names.
# TODO:
# - make the completions list sort by the number of uses each tag has (and also show the number next to each tag)
# - support flex/fuzzy completion
# - handle tags with values (currently they show in red)
# - highlight the filename differently from the directory in the file name "label".
# - copy the filename to clipboard when clicked.
# - copy the old tags to clipboard when clicked.
# - put a scrollbar on the completion listbox.
# settings:
# whether to print extra debugging output to stdout.
debug_output = False
# whether or not to show a notification when saving tags about the tags saved.
show_notification = False
# when saving tags, if show_notification is on, which tags should we mention about saving? should be an array of one or more of: 'added', 'removed', or 'new'.
notify_about = ['added', 'removed', 'new']
# code:
import os, sys, subprocess
from tkinter import *
from tkinter import ttk, messagebox
import tkinter.font as tkFont
# utilities
def debug(*items):
"""Print ITEMS to standard output if debug_output is True."""
global debug_output
if debug_output:
print(*items)
def common_prefix(items):
"""Get the longest string shared by the start of all elements in ITEMS."""
if items == []:
return ''
if len(items) == 1:
return items[0]
n = 0
while True:
for item in items:
if item[:n+1] != items[0][:n+1]:
return items[0][:n]
n = n + 1
def common_items(*lists):
"""Get a list of all items that exist in all of the provided lists."""
res = set(lists[0])
for i in lists[1:]:
res = set(i).intersection(res)
return list(res)
def missing_items(list_a, list_b):
"""Get a list of items in LIST_A that don't exist in LIST_B."""
return list(set(list_a).difference(set(list_b)))
# clipboard
def set_clipboard(text):
"""Set the system clipboard's text to TEXT."""
root.clipboard_clear()
root.clipboard_append(text)
# osd-related
def osd_notify(text, title=None):
"""Send TEXT to the OSD to notify the user."""
title = title or "tag-gui - " + make_title(files)
subprocess.run(['notify-send', title, text])
# directories / filenames
def abbreviate_path(path):
"""Abbreviate PATH as much as possible by swapping the home directory path for ~."""
home = os.path.expanduser('~')
if path.startswith(home):
path = '~' + path[len(home):]
return path
def make_title(files):
"""Generate a summary of the file(s) being tagged."""
if len(files) == 1:
return abbreviate_path(files[0])
else:
return str(len(files)) + " files under " + abbreviate_path(os.path.commonpath(files))
# tmsu / tags
def tmsu_dir(path):
"""Starting from PATH, look up in the directory tree to find the directory containing the .tmsu directory. Returns None if it could not be found."""
tries = 100 # failsafe in case we're trapped in some kind of strange directory loop(?)
if not os.path.isdir(path):
path = os.path.dirname(path)
os.chdir(path)
while tries > 0:
if os.path.exists('./.tmsu'):
return os.path.realpath(os.curdir)
else:
tries = tries - 1
if os.pardir == os.path.realpath(os.curdir):
return None
else:
os.chdir(os.pardir)
return None
def get_all_tags():
"""Get a list of all tags from TMSU."""
return os.popen('tmsu tags').read().split()
def file_tags(file):
"""Get a list of tags that FILE is tagged with."""
file = os.path.realpath(file)
subp = subprocess.run(['tmsu', 'tags', file], stdout=subprocess.PIPE)
tags = subp.stdout.decode('utf8')
return tags[tags.rfind(':')+2:].split()
def tags_matching(input):
"""Get a list of tags matching INPUT, sorted so that tags that begin with INPUT are listed first."""
res = []
for tag in alltags:
if input in tag:
res = res + [tag]
for n, i in enumerate(res):
if i[:len(input)] == input:
res = res[n:] + res[:n]
break
return res
def save_tags(newtags):
"""Save NEWTAGS as the tags for the specified files."""
global tags
output = []
new_tags = []
add_tags = missing_items(newtags, tags)
if add_tags:
debug("Add tags:", add_tags)
subp = subprocess.run(['tmsu', 'tag', '--tags=' + ' '.join(add_tags), *files], stderr=subprocess.PIPE)
tmsu_out = subp.stderr.decode('utf8')
if tmsu_out:
debug("tmsu_out:", tmsu_out)
for i in tmsu_out.split('\n'):
if i.startswith('tmsu: new tag '):
new_tags += [i[14:].removeprefix("'").removesuffix("'")]
remove_tags = missing_items(tags, newtags)
if remove_tags:
debug("Remove tags:", remove_tags)
subprocess.run(['tmsu', 'untag', '--tags=' + ' '.join(remove_tags), *files])
if show_notification:
output = []
if add_tags and 'added' in notify_about:
output += ["Added tags: " + ' '.join(add_tags)]
if remove_tags and 'removed' in notify_about:
output += ["Removed tags: " + ' '.join(remove_tags)]
if new_tags and 'new' in notify_about:
output += ["New tags: " + ' '.join(new_tags)]
if len(output) == 0:
output += ["(No changes)"]
osd_notify('\n'.join(output))
# callbacks / gui actions
def get_end_pos(widget):
"""Get the length of the text in the input field."""
return len(get_input_text(widget))
def get_cursor_pos():
"""Get the integer position of the cursor in the text input field."""
return int(tagsinput.index(INSERT).split('.')[1])
def set_cursor_pos(pos):
"""Set the cursor position in the text input field."""
if type(pos) == int:
pos = "1." + str(pos)
tagsinput.mark_set(INSERT, pos)
def get_input_text(widget):
"""Get the string of text in the input field."""
return ''.join(map(lambda x: x[1], widget.dump('1.0', END, text=True)))[:-1]
def set_input_text(widget, text):
"""Set the text of WIDGET to STRING."""
widget.delete('1.0', END)
widget.insert('1.0', text)
def set_input_text_disable(widget, string):
"""Set the text of WIDGET to STRING and ensure it is disabled afterwards."""
widget.configure(state=NORMAL)
set_input_text(widget, string)
widget.configure(state=DISABLED)
def xview(widget, index):
"""Scroll the text input field to view the specified index."""
widget.xview_scroll(max(0, index-50), 'units')
def update_completions():
"""Update the listbox to show suggested completions based on the word next to the cursor in the text input field."""
pos = get_cursor_pos()
txt = get_input_text(tagsinput)
listbox.delete(0, END)
if txt == '' or txt[pos-1] == ' ':
matching = alltags
else:
prev_space = txt.rfind(' ', 0, pos)
next_space = txt.find(' ', pos)
if next_space == -1:
next_space = len(txt)
cursor_tag = txt[prev_space+1:next_space]
matching = tags_matching(cursor_tag)
for tag in matching:
listbox.insert(END, tag)
ind = get_cursor_pos()
xview(tagsinput, ind)
if len(matching) == 1:
set_selection(0)
else:
set_selection(None)
def update_highlighting():
"""Highlight unknown tags in red in the text input field, to make possible spelling errors more obvious."""
tagsinput.tag_remove('nonexistent', '1.0', END)
txt = get_input_text(tagsinput)
words = txt.split()
start = 0
for word in words:
loc = txt.find(word, start)
start = loc + len(word)
if not word in alltags:
tagsinput.tag_add('nonexistent', '1.' + str(loc), '1.' + str(loc + len(word)))
def key_release(*ignored):
"""Update the completions and the text highlighting after each keypress."""
global prev_cursor_loc
cursor = get_cursor_pos()
if cursor != prev_cursor_loc:
update_completions()
prev_cursor_loc = cursor
update_highlighting()
def tag_at_cursor_indexes():
"""Get the indexes of the tag near the cursor position, or None if the cursor is not near a word."""
cursor = get_cursor_pos()
txt = get_input_text(tagsinput)
if txt[cursor-1] == ' ':
return None
else:
prev_space = txt.rfind(' ', 0, cursor)
next_space = txt.find(' ', cursor)
if next_space == -1:
next_space = len(txt)
return [prev_space+1, next_space]
def tag_at_cursor():
"""Get the tag near the cursor position, or None if the cursor is not near a word."""
indexes = tag_at_cursor_indexes()
if indexes == None:
return None
else:
return get_input_text(tagsinput)[indexes[0]:indexes[1]]
def replace_tag_at_cursor(text, complete=False):
"""Remove the tag around the cursor if there is one, then insert TEXT at the cursor. Automatically adds spaces before and after the tag if necessary.
If COMPLETE is true, the replacement should be considered a "complete" tag, and an extra space should be added afterwards."""
indexes = tag_at_cursor_indexes()
txt = get_input_text(tagsinput)
if indexes == None:
txt = txt + ' ' + text
else:
txt = txt[0:indexes[0]] + text + txt[indexes[1]:]
set_input_text(tagsinput, txt)
new_cursor = tag_at_cursor_indexes()
if new_cursor == None:
new_cursor = len(txt)
else:
new_cursor = new_cursor[1]
if complete and (new_cursor == len(txt)):
set_input_text(tagsinput, txt + ' ')
new_cursor = new_cursor + 1
set_cursor_pos(new_cursor)
def move_cursor_by_word(num=1):
"""Move the cursor by NUM words relative to its current position by simulating ctrl+right or ctrl+left keypress(es)."""
key = '<Control-Right>'
if num < 0:
key = '<Control-Left>'
for idx in range(abs(num)):
tagsinput.event_generate(key)
def forward_word(event):
"""Move the cursor forward a word."""
move_cursor_by_word(1)
def backward_word(event):
"""Move the cursor backward a word."""
move_cursor_by_word(-1)
def tab(event):
"""Activate completion of the current input based on the selected item in the completions listbox."""
curselection = listbox.curselection()
cursor = get_cursor_pos()
txt = get_input_text(tagsinput)
if len(curselection) == 0:
if (cursor == get_end_pos(tagsinput)) or (txt[cursor] == ' '):
current = tag_at_cursor()
if not current:
return "break"
curlen = len(current)
# here we remove any that don't start with the current input, since we only want to complete based on the start of the input, but the completions box shows items that have the current input ANYWHERE in them.
citems = list(filter(lambda i: i[:curlen] == current, listbox.get(0, END)))
cpre = common_prefix(citems)
if cpre != '':
replace_tag_at_cursor(cpre, len(citems) == 1)
return "break"
selected_completion = listbox.get(curselection[0])
if selected_completion == '':
return "break"
replace_tag_at_cursor(selected_completion, True)
tagsinput.focus()
return "break"
def ret(event):
"""Commit the tags inputted and save them to the specified files."""
save_tags(get_input_text(tagsinput).split())
quit()
def set_selection(index):
"""Set the current selection of the completions listbox to the one with the specified index."""
listbox.selection_clear(0, END)
if index != None:
index = min(max(0, index), len(listbox.get(0, END))-1)
listbox.selection_set(index)
listbox.see(index)
def move_selection(direction=1):
"""Move the currently-selected item in the completions listbox by DIRECTION items, relative to the current selection."""
cur = listbox.curselection()
sel = None
length = len(listbox.get(0, END))
if cur == ():
if direction == 1:
sel = 0
else:
sel = length
else:
cur = cur[0]
if (cur == (length-1) and direction == 1) or (cur == 0 and direction == -1):
sel = None
else:
sel = cur + direction
set_selection(sel)
return 'break'
def comma(ignored):
"""Tags should be separated by spaces rather than commas, so we override the comma key to just insert a space instead."""
tagsinput.event_generate('<space>')
return "break"
def ctrl_backspace(ignored):
"""Delete the word to the left of the cursor."""
pos = get_cursor_pos()
txt = get_input_text(tagsinput)
next_space = txt.rfind(' ', 0, pos)+1
set_input_text(tagsinput, txt[:next_space] + txt[pos:])
set_cursor_pos(next_space)
return "break"
def copy_widget_text_to_clipboard(widget):
"""Copy the text of WIDGET to the system clipboard."""
text = get_input_text(widget)
set_clipboard(text)
osd_notify("Copied '%s' to clipboard." % (text))
# gui setup
def make_gui():
"""Make the actual GUI window."""
global root, mainframe, label, tagslabel, tagsinput, listbox, prev_cursor_loc
prev_cursor_loc = 0
root = Tk(className="tag-gui")
mainframe = ttk.Frame(root)
mainframe.pack(fill=BOTH, expand=True)
# We make a temporary Label to get the default background color to use in the next two Text widgets.
tmp_label = Label()
bg = tmp_label.cget('bg')
tmp_label.destroy()
# We use a Text widget instead of a Label so we can ensure it is scrolled to the right if the text is too long.
label = Text(mainframe, height=1, wrap=NONE, font=tkFont.Font(size=9), padx=0, pady=0, border=0, bg=bg)
label.pack(fill=X, expand=True)
set_input_text_disable(label, "Tagging...")
label.bind('<Button-1>', lambda e: copy_widget_text_to_clipboard(e.widget))
tagslabel = Text(mainframe, height=1, wrap=NONE, font=tkFont.Font(size=9), padx=0, pady=0, border=0, bg=bg)
tagslabel.pack(fill=X, expand=True)
set_input_text_disable(tagslabel, "Original tags: ...")
tagslabel.bind('<Button-1>', lambda e: copy_widget_text_to_clipboard(e.widget))
tagsinput = Text(mainframe, height=1, wrap=NONE, font=tkFont.Font(size=9))
tagsinput.pack(fill=X, expand=True)
tagsinput.bind('<Tab>', tab)
tagsinput.bind('<Return>', ret)
tagsinput.bind('<KeyRelease>', key_release)
tagsinput.bind('<comma>', comma)
tagsinput.tag_configure('nonexistent', foreground='red')
listbox = Listbox(mainframe, selectmode=SINGLE)
listbox.pack(fill=BOTH, expand=True)
root.bind('<Return>', ret)
root.bind('<Tab>', tab)
root.bind('<Escape>', lambda e: quit())
root.bind('<Control-g>', lambda e: quit())
root.bind('<Up>', lambda e: move_selection(-1))
root.bind('<Down>', lambda e: move_selection(1))
root.bind('<Control-p>', lambda e: move_selection(-1))
root.bind('<Control-n>', lambda e: move_selection(1))
root.bind('<Control-BackSpace>', ctrl_backspace)
root.bind('<Alt-b>', backward_word)
root.bind('<Alt-f>', forward_word)
tagsinput.focus()
root.minsize(500, 120)
root.maxsize(800, 120)
# main
if __name__ == '__main__':
global root, files, alltags, tags
if len(sys.argv) == 2 and (sys.argv[1] == '--help' or sys.argv[1] == '-h'):
print("tag-gui - A simple GUI to edit TMSU tags of one or more files.")
print("Usage: tag-gui [arguments] [files]")
print()
print(" -h/--help - Print help and exit.")
exit(0)
if len(sys.argv) > 1:
tmpfiles = sys.argv[1:]
else:
tmpfiles = []
for i in sys.stdin.readlines():
tmpfiles = tmpfiles + [i.rstrip()]
files = []
for i in tmpfiles:
files = files + [os.path.realpath(i)]
if len(files) == 0:
print("No files provided; exiting...")
exit(1)
cddir = tmsu_dir(files[0])
if cddir == None:
err = "Can't tag this file (%s) as it does not appear to be within a TMSU directory." % files[0]
print(err)
messagebox.showerror("TMSU error", err)
exit(1)
else:
os.chdir(cddir)
alltags = get_all_tags()
title = make_title(files)
make_gui()
root.title("Tagging " + title + "...")
set_input_text_disable(label, title)
xview(label, get_end_pos(label))
tags = []
for file in files:
tags = tags + [file_tags(file)]
tags = common_items(*tags)
tags.sort()
tagstxt = ' '.join(tags)
set_input_text_disable(tagslabel, "Original tags: " + tagstxt)
if not tags == []:
set_input_text(tagsinput, tagstxt + ' ')
set_cursor_pos(END)
root.mainloop()