-
Notifications
You must be signed in to change notification settings - Fork 9
/
pim
executable file
·610 lines (487 loc) · 16.7 KB
/
pim
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#!/usr/bin/env python3
# Thanks
# alterecco, for making [visible](http://drop.dotright.net/visible) (dead),
# and inspiring me (James Campos) to make this program.
# Pim
# Python image viewer with vim-like keybindings
# v0.10.1
import argparse
from random import shuffle
import mimetypes
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, Gdk, GdkPixbuf
import os
import shutil
import time
import uuid
# dict like, easy to use class, to avoid the hassle with global vars
g = argparse.Namespace(
drag = False,
fullscreen=False,
geometry='800x600',
hide_delay=1,
index=0,
rotation=0,
rotation_lock=False,
shuffle=False,
slideshow=False,
slideshow_delay=5,
sbar=False,
zoom_lock=False,
paths=[],
marked=[],
# Definition of buttons
buttons = {
'1': 'drag',
'8': 'prev',
'9': 'next'
},
# Definition of keybindings
keybinds = {
'S-space': 'prev',
'space': 'next',
'p': 'prev',
'n': 'next',
'H': 'pageLeft',
'J': 'pageDown',
'K': 'pageUp',
'L': 'pageRight',
'h': 'left',
'j': 'down',
'k': 'up',
'l': 'right',
'Left': 'left',
'Down': 'down',
'Up': 'up',
'Right': 'right',
'G': 'scrollEnd',
'g': 'scrollStart',
'm': 'mark_picture',
'C-r': 'rotation_lock',
'R': 'rotateL',
'r': 'rotateR',
't': 'slower',
'T': 'faster',
'b': 'status',
's': 'slideshow',
'f': 'fullscreen',
'q': 'quit',
'Q': 'saveq',
'x': 'delete',
'X': 'deleteb',
'w': 'zoom_fit',
'plus': 'zoom_in',
'minus': 'zoom_out',
'1': 'zoom_100',
'2': 'zoom_200',
'3': 'zoom_300',
'e': 'zoom_w',
'E': 'zoom_h',
'z': 'zoom_lock'
}
)
BUTTONS = {
Gdk.EventType.BUTTON_PRESS: 1,
Gdk.EventType._2BUTTON_PRESS: 2,
Gdk.EventType._3BUTTON_PRESS: 3
}
HOME = os.getenv('HOME')
XDG_DATA_HOME = os.getenv('XDG_DATA_HOME') or HOME + '/.local/share'
TRASH = XDG_DATA_HOME + '/Trash'
def cursor_hide():
g.win.get_window().set_cursor(g.cursor)
g.cursor_id = None
def delete(delta=0):
# https://specifications.freedesktop.org/trash-spec/trashspec-1.0.html
if not os.path.isdir(TRASH):
os.mkdir(TRASH)
os.mkdir(TRASH + '/files')
os.mkdir(TRASH + '/info')
path = g.paths.pop(g.index)
# Check if physical existing
if os.path.exists(path):
name = uuid.uuid4().hex
info = (
'[Trash Info]\n'
'Path={}\n'
'DeletionDate={}'
).format(path, time.strftime('%Y-%m-%dT%H:%M:%S'))
f = open(TRASH + '/info/' + name + '.trashinfo', 'w')
f.write(info)
f.close()
shutil.move(path, TRASH + '/files/' + name)
print(':: trashed:', path)
else:
print(':: removed', path, 'from the selection')
if not len(g.paths):
print(':: quitting, as no files remain')
quit()
else:
if g.index == len(g.paths):
g.index -= 1
move_index(delta)
def drag():
g.drag = True
def get_zoom_percent(zWidth=False, zHeight=False):
pboWidth = g.pixbufOriginal.get_width()
pboHeight = g.pixbufOriginal.get_height()
pboScale = pboWidth / pboHeight
if g.fullscreen:
winSize = (g.mon_size.width, g.mon_size.height)
wScale = g.mon_size.width / g.mon_size.height
else:
winSize = g.win_size
wScale = g.win_size[0] / g.win_size[1]
stickout = zWidth | zHeight
if pboWidth < winSize[0] and pboHeight < winSize[1] and not stickout:
return 1
elif (pboScale < wScale and not stickout) or zHeight:
return winSize[1] / pboHeight
else:
return winSize[0] / pboWidth
def handle_button_press(widget, event):
clicks = BUTTONS[event.type]
button = str(event.button)
name = g.buttons.get(button)
if clicks == 1 and name:
action = Actions[name]
action[0](*action[1:])
elif clicks == 2 and button == '1':
toggle_fullscreen()
return True # XXX without this, single clicks fire twice
def handle_button_release(win, event):
g.drag = False
return True
def handle_motion(win, event):
win.get_window().set_cursor(None)
if g.cursor_id:
GLib.source_remove(g.cursor_id)
g.cursor_id = GLib.timeout_add_seconds(g.hide_delay, cursor_hide)
if (g.drag):
xscale = g.hadj.props.upper / g.hadj.props.page_size
yscale = g.vadj.props.upper / g.vadj.props.page_size
g.hadj.set_value(event.x * xscale)
g.vadj.set_value(event.y * yscale)
def handle_key(win, event):
key = Gdk.keyval_name(event.keyval)
# XXX only support one modifier key, so we don't have to support
# modifiers in arbitrary order
if event.state & Gdk.ModifierType.MOD1_MASK:
key = 'A-' + key
elif event.state & Gdk.ModifierType.CONTROL_MASK:
key = 'C-' + key
elif event.state & Gdk.ModifierType.SHIFT_MASK and len(key) > 1:
key = 'S-' + key
name = g.keybinds.get(key)
if name:
action = Actions[name]
action[0](*action[1:])
def mark():
if g.paths[g.index] in g.marked:
g.marked.remove(g.paths[g.index])
else:
g.marked.append(g.paths[g.index])
update_info()
def move_index(delta, slide=False):
# Manual interaction stops slideshow
if g.slideshow and not slide:
toggle_slideshow()
g.index = (g.index + delta) % len(g.paths)
# reshuffle on wrap-around
if g.shuffle and g.index == 0 and delta > 0:
shuffle(g.paths)
path = g.paths[g.index]
try:
if not os.path.exists(path):
print(":: Error: Couldn't open", path)
delete()
return
else:
g.pixbufOriginal = GdkPixbuf.PixbufAnimation.new_from_file(path)
if g.pixbufOriginal.is_static_image():
g.pixbufOriginal = g.pixbufOriginal.get_static_image()
if g.rotation_lock:
g.pixbufOriginal = g.pixbufOriginal.rotate_simple(g.rotation)
else:
g.rotation = 0
if not g.zoom_lock:
if not g.fullscreen:
g.win_size = g.win.get_size()
g.zoom_percent = get_zoom_percent()
else:
g.zoom_percent = 1
update_image()
scroll(Gtk.ScrollType.START, False)
scroll(Gtk.ScrollType.START, True)
except GLib.Error as err:
print(":: couldn't read", path, 'because:', err)
move_index(1)
return True # for the slideshow
def parse_args():
# ToDo: As the vars are contained in a argparse dict -> Look at combining them
usage = '%(prog)s [options] path1 [path2 path3 ...]'
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-b', '--bar', action='store_true', dest='sbar',
help='display statusbar', default=g.sbar)
parser.add_argument('-f', '--fullscreen', action='store_true',
dest='fullscreen', help='start in fullscreen',
default=g.fullscreen)
parser.add_argument('-g', '--geometry', dest='geometry',
help='set window size', default=g.geometry)
parser.add_argument('-s', '--shuffle', action='store_true',
dest='shuffle', help='shuffle filelist',
default=g.shuffle)
parser.add_argument('-S', '--no-shuffle', action='store_false',
dest='shuffle', help="don't shuffle the filelist")
parser.add_argument('--slideshow-delay', type=int,
help='set the slideshow delay',
default=g.slideshow_delay)
parser.add_argument('path', nargs='+')
parser.parse_args(namespace=g)
if not populate(g.path):
parser.error('no loadable images detected')
def parse_geometry():
# Not nice, but adding type=int to argparse won't help because of the x
# ToDo: Look for a better solution
if g.geometry.find('x') >= 0:
g.geometry = g.geometry.split('x')
for ele in range(0, len(g.geometry)):
if len(g.geometry[ele]) > 0:
g.geometry[ele] = int(g.geometry[ele])
else:
print(':: Warning: Missing geometry parameter.'
' Replacing with default')
g.geometry[ele] = 200*(4-ele)
else:
print(':: Warning: The geometry should be like that: 800x600'
'\n::Falling back to default')
g.geometry = '800x600'
parse_geometry()
def populate(args):
""" Generate a list of paths from the given arguments """
# get supported mimetypes
types = []
for pixbuf_format in GdkPixbuf.Pixbuf.get_formats():
types.extend(pixbuf_format.get_mime_types())
args = g.path
# If only one path is passed do special stuff
single = None
if len(args) == 1:
arg = args[0]
if os.path.isfile(arg):
# use parent directory
single = os.path.abspath(arg)
directory = os.path.dirname(single)
args = (directory,)
elif os.path.isdir(arg) and os.path.isfile('pim-position'):
f = open('pim-position')
single = f.read()
print(':: Found position file. Starting with: '+single)
# add everything
for arg in args:
path = os.path.abspath(arg)
if os.path.isfile(path):
g.paths.append(path)
elif os.path.isdir(path):
paths = [os.path.join(path, x) for x in os.listdir(path)]
paths.sort()
g.paths.extend(paths)
else:
print(':: Error: {} is not a valid path!'.format(arg))
# remove unsupported files
g.paths = [path for path in g.paths if mimetypes.guess_type(path)[
0] in types]
# shuffle
if g.shuffle:
shuffle(g.paths)
# complete special stuff for single arg
if single and single in g.paths:
g.index = g.paths.index(single)
else:
g.index = 0
return len(g.paths)
def quit(remember_position=False):
if remember_position and len(g.paths):
try:
f = open('pim-position', 'w')
f.writelines(g.paths[g.index])
f.close()
except IOError as e:
print(e)
for pos in g.marked:
print(pos)
Gtk.main_quit()
def rotate(delta):
try:
g.pixbufOriginal = g.pixbufOriginal.rotate_simple(delta % 360)
g.rotation = (g.rotation + delta) % 360
if not g.zoom_lock:
g.zoom_percent = get_zoom_percent()
update_image()
except:
print(':: Warning: Animation object cannot be rotated')
def scroll(scrolltype, horizontal):
g.scrolled_win.emit('scroll-child', scrolltype, horizontal)
def set_default_window_size():
parse_geometry()
winWidth = g.geometry[0] if g.mon_size.width >= 800 else g.mon_size.width
winHeight = g.geometry[1] if g.mon_size.height >= 600 else g.mon_size.height
g.win.resize(winWidth, winHeight)
if g.fullscreen:
g.win.fullscreen()
def change_delay(delta):
if g.slideshow_delay == 1 and delta == -1:
return
else:
g.slideshow_delay += delta
if g.slideshow:
toggle_slideshow()
toggle_slideshow()
def toggle_fullscreen():
g.fullscreen = not g.fullscreen
if g.fullscreen:
g.win.fullscreen()
# Save previous window size. Possible since get_size gets old value
# And this is also the cause for some problems
# (zoomfactor for fullscreen on non fullscreen window)
g.win_size = g.win.get_size()
else:
g.win.unfullscreen()
if not g.zoom_lock:
g.zoom_percent = get_zoom_percent()
update_image()
def toggle_rotation_lock():
g.rotation_lock = not g.rotation_lock
def toggle_slideshow():
g.slideshow = not g.slideshow
if g.slideshow:
g.timer_id = GLib.timeout_add_seconds(g.slideshow_delay,
move_index, 1, True)
else:
GLib.source_remove(g.timer_id)
update_info()
def toggle_statusbar():
if not g.sbar:
Gtk.Widget.hide(g.statusbar)
else:
Gtk.Widget.show(g.statusbar)
g.sbar = not g.sbar
def toggle_zoom_lock():
g.zoom_lock = not g.zoom_lock
def update_image():
""" Show the final image """
pboWidth = g.pixbufOriginal.get_width()
pboHeight = g.pixbufOriginal.get_height()
try:
pbfWidth = int(pboWidth * g.zoom_percent)
pbfHeight = int(pboHeight * g.zoom_percent)
pixbufFinal = g.pixbufOriginal.scale_simple(
pbfWidth, pbfHeight, GdkPixbuf.InterpType.BILINEAR)
g.image.set_from_pixbuf(pixbufFinal)
except:
g.image.set_from_animation(g.pixbufOriginal)
update_info()
def update_info():
message = '[{0}/{1}] [ {3:3.0f}% ] {2: <50} {5: <3} {4: <11}'.format(
g.index+1, len(g.paths), g.paths[g.index],
g.zoom_percent *
100, '[slideshow ({0}s)]'.format(
g.slideshow_delay) if g.slideshow else '',
'[*]' if g.paths[g.index] in g.marked else '')
g.win.set_title('pim '+message)
g.statusbar.push(1, message)
def zoom_delta(delta):
try:
g.zoom_percent = g.zoom_percent + delta
if g.zoom_percent <= 0:
g.zoom_percent = 1/100
update_image()
except:
print(':: Warning: Animation object cannot be zoomed')
def zoom_to(percent, zWidth=False, zHeight=False):
try:
if not g.fullscreen:
g.win_size = g.win.get_size()
g.zoom_percent = percent if percent else get_zoom_percent(zWidth, zHeight)
update_image()
except:
print(':: Warning: Animation object cannot be zoomed')
def main():
parse_args()
dis = g.dis = Gdk.Display().get_default()
g.cursor = Gdk.Cursor.new_from_name(Gdk.Display.get_default(), 'none')
g.cursor_id = GLib.timeout_add_seconds(g.hide_delay, cursor_hide)
win = g.win = Gtk.Window()
win.add_events(Gdk.EventMask.KEY_PRESS_MASK |
Gdk.EventMask.POINTER_MOTION_MASK)
win.connect('destroy', Gtk.main_quit)
win.connect('button_press_event', handle_button_press)
win.connect('button-release-event', handle_button_release)
win.connect('key_press_event', handle_key)
win.connect('motion-notify-event', handle_motion)
win.set_icon_name('image-x-generic')
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
win.add(vbox)
g.scrolled_win = Gtk.ScrolledWindow()
vbox.pack_start(g.scrolled_win, True, True, 0)
viewport = Gtk.Viewport()
viewport.set_shadow_type(Gtk.ShadowType.NONE)
g.scrolled_win.add(viewport)
g.hadj = g.scrolled_win.get_hadjustment()
g.vadj = g.scrolled_win.get_vadjustment()
# Not nice in regard of hardcoded monitor
monitor = Gdk.Display.get_monitor(dis, 0)
g.mon_size = Gdk.Monitor.get_geometry(monitor)
set_default_window_size()
g.win_size = win.get_size()
g.image = Gtk.Image()
viewport.add(g.image)
g.statusbar = Gtk.Statusbar()
vbox.pack_end(g.statusbar, False, False, 0)
move_index(0)
win.show_all()
if g.fullscreen:
g.win.fullscreen()
toggle_statusbar()
Gtk.main()
Actions = {
# if True, scroll in the horizontal direction.
'scrollStart': (scroll, Gtk.ScrollType.START, False),
'scrollEnd': (scroll, Gtk.ScrollType.END, False),
'pageLeft': (scroll, Gtk.ScrollType.PAGE_BACKWARD, True),
'pageDown': (scroll, Gtk.ScrollType.PAGE_FORWARD, False),
'pageUp': (scroll, Gtk.ScrollType.PAGE_BACKWARD, False),
'pageRight': (scroll, Gtk.ScrollType.PAGE_FORWARD, True),
'left': (scroll, Gtk.ScrollType.STEP_BACKWARD, True),
'down': (scroll, Gtk.ScrollType.STEP_FORWARD, False),
'up': (scroll, Gtk.ScrollType.STEP_BACKWARD, False),
'right': (scroll, Gtk.ScrollType.STEP_FORWARD, True),
'delete': (delete, 0),
'deleteb': (delete, -1),
'drag': (drag,),
'fullscreen': (toggle_fullscreen,),
'next': (move_index, 1),
'prev': (move_index, -1),
'quit': (quit,),
'saveq': (quit, True),
'mark_picture': (mark,),
'rotation_lock': (toggle_rotation_lock,),
'rotateR': (rotate, -90),
'rotateL': (rotate, 90),
'slideshow': (toggle_slideshow,),
'slower': (change_delay, 1),
'faster': (change_delay, -1),
'status': (toggle_statusbar,),
'zoom_fit': (zoom_to, 0),
'zoom_in': (zoom_delta, +.25),
'zoom_out': (zoom_delta, -.25),
'zoom_100': (zoom_to, 1),
'zoom_200': (zoom_to, 2),
'zoom_300': (zoom_to, 3),
'zoom_h': (zoom_to, 0, False, True),
'zoom_w': (zoom_to, 0, True, False),
'zoom_lock': (toggle_zoom_lock,)
}
if __name__ == '__main__':
main()