-
Notifications
You must be signed in to change notification settings - Fork 6
/
__init__.py
509 lines (419 loc) · 14.7 KB
/
__init__.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""FileChooserThumbView
====================
The FileChooserThumbView widget is similar to FileChooserIconView,
but if possible it shows a thumbnail instead of a normal icon.
Usage
-----
You can set some properties in order to control its performance:
* **showthumbs:** Thumbnail limit. If set to a number > 0, it will show the
thumbnails only if the directory doesn't contain more files or directories.
If set to 0 it won't show any thumbnail. If set to a number < 0 it will always
show the thumbnails, regardless of how many items the current directory
contains. By default it is set to -1, so it will show all the thumbnails.
* **thumbdir:** Custom directory for the thumbnails. By default it uses
tempfile to generate it randomly.
* **thumbsize:** The size of the thumbnails. It defaults to 64d
"""
# Thanks to allan-simon for making the code more readable and less "spaghetti" :)
import os
import mimetypes
#(enable for debugging)
import traceback
import shutil
import subprocess
from threading import Thread
from os.path import join, exists, dirname
from tempfile import mktemp, mkdtemp
from kivy.app import App
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.utils import QueryDict
from kivy.properties import StringProperty
from kivy.properties import DictProperty
from kivy.properties import ObjectProperty
from kivy.properties import BooleanProperty
from kivy.properties import NumericProperty
from kivy.uix.filechooser import FileChooserController
# directory with this package
_path = os.path.dirname(os.path.realpath(__file__))
Builder.load_string("""
<FileChooserThumbView>:
on_entry_added: stacklayout.add_widget(args[1])
on_entries_cleared: stacklayout.clear_widgets()
scrollview: scrollview
ScrollView:
id: scrollview
pos: root.pos
size: root.size
size_hint: None, None
do_scroll_x: False
Scatter:
do_rotation: False
do_scale: False
do_translation: False
size_hint_y: None
height: stacklayout.height
StackLayout:
id: stacklayout
width: scrollview.width
size_hint_y: None
height: self.minimum_height
spacing: '10dp'
padding: '10dp'
[FileThumbEntry@Widget]:
image: image
locked: False
path: ctx.path
selected: self.path in ctx.controller().selection
size_hint: None, None
on_touch_down: self.collide_point(*args[1].pos) and ctx.controller().entry_touched(self, args[1])
on_touch_up: self.collide_point(*args[1].pos) and ctx.controller().entry_released(self, args[1])
size: ctx.controller().thumbsize + dp(52), ctx.controller().thumbsize + dp(52)
canvas:
Color:
rgba: 1, 1, 1, 1 if self.selected else 0
BorderImage:
border: 8, 8, 8, 8
pos: root.pos
size: root.size
source: 'atlas://data/images/defaulttheme/filechooser_selected'
AsyncImage:
id: image
size: ctx.controller().thumbsize, ctx.controller().thumbsize
pos: root.x + dp(24), root.y + dp(40)
Label:
text: ctx.name
text_size: (ctx.controller().thumbsize, self.height)
halign: 'center'
shorten: True
size: ctx.controller().thumbsize, '16dp'
pos: root.center_x - self.width / 2, root.y + dp(16)
Label:
text: ctx.controller()._gen_label(ctx)
font_size: '11sp'
color: .8, .8, .8, 1
size: ctx.controller().thumbsize, '16sp'
pos: root.center_x - self.width / 2, root.y
halign: 'center'
""")
DEFAULT_THEME = 'atlas://data/images/defaulttheme/'
FILE_ICON = DEFAULT_THEME + 'filechooser_file'
FOLDER_ICON = DEFAULT_THEME + 'filechooser_folder'
FLAC_MIME = "audio/flac"
MP3_MIME = "audio/mpeg"
AVCONV_BIN = 'avconv'
FFMPEG_BIN = 'ffmpeg'
CONVERT_BIN = 'convert'
class FileChooserThumbView(FileChooserController):
'''Implementation of :class:`FileChooserController` using an icon view
with thumbnails.
'''
_ENTRY_TEMPLATE = 'FileThumbEntry'
thumbdir = StringProperty(mkdtemp(prefix="kivy-", suffix="-thumbs"))
'''Custom directory for the thumbnails. By default it uses tempfile to
generate it randomly.
'''
showthumbs = NumericProperty(-1)
'''Thumbnail limit. If set to a number > 0, it will show the thumbnails
only if the directory doesn't contain more files or directories. If set
to 0 it won't show any thumbnail. If set to a number < 0 it will always
show the thumbnails, regardless of how many items the current directory
contains.
By default it is set to -1, so it will show all the thumbnails.
'''
thumbsize = NumericProperty(dp(64))
"""The size of the thumbnails. It defaults to 64dp.
"""
play_overlay = StringProperty(os.path.join(_path, 'play_overlay.png'))
"""Path to a PIL supported image file (e.g. png) that will be put over
videos thumbnail (e.g. a "play" button). If it's an empty string nothing
will happen.
Defaults to "".
"""
filmstrip_left = StringProperty("")
filmstrip_right = StringProperty("")
_thumbs = DictProperty({})
scrollview = ObjectProperty(None)
def __init__(self, **kwargs):
super(FileChooserThumbView, self).__init__(**kwargs)
self.thumbnail_generator = ThreadedThumbnailGenerator()
if not exists(self.thumbdir):
os.mkdir(self.thumbdir)
def clear_cache(self, *args):
try:
shutil.rmtree(self.thumbdir, ignore_errors=True)
except:
traceback.print_exc()
def _dir_has_too_much_files(self, path):
if (self.showthumbs < 0):
return False
nbrFileInDir = len(
os.listdir(dirname(path))
)
return nbrFileInDir > self.showthumbs
def _create_entry_widget(self, ctx):
# instantiate the widget
widget = super(FileChooserThumbView, self)._create_entry_widget(ctx)
kctx = QueryDict(ctx)
# default icon
widget.image.source = FOLDER_ICON if kctx.isdir else FILE_ICON
# schedule generation for later execution
self.thumbnail_generator.append(widget.image, kctx, self._get_image)
self.thumbnail_generator.run()
return widget
def _get_image(self, ctx):
try:
App.get_running_app().bind(on_stop=self.clear_cache)
except AttributeError:
pass
except:
traceback.print_exc()
if ctx.isdir:
return FOLDER_ICON
# if the directory contains more files
# than what has been configurated
# we directly return a default file icon
if self._dir_has_too_much_files(ctx.path):
return FILE_ICON
try:
mime = get_mime(ctx.name)
# if we already have generated the thumb
# for this file, we get it directly from our
# cache
if ctx.path in self._thumbs.keys():
return self._thumbs[ctx.path]
# if it's a picture, we don't need to do
# any transormation
if is_picture(mime, ctx.name):
return ctx.path
# for mp3/flac an image can be embedded
# into the file, so we try to get it
if mime == MP3_MIME:
return self._generate_image_from_mp3(
ctx.path
)
if mime == FLAC_MIME:
return self._generate_image_from_flac(
ctx.path
)
# if it's a video we will extract a frame out of it
if "video/" in mime:
return self._generate_image_from_video(ctx.path)
except:
traceback.print_exc()
return FILE_ICON
return FILE_ICON
def _generate_image_from_flac(self, flacPath):
# if we don't have the python module to
# extract image from flac, we just return
# default file's icon
try:
from mutagen.flac import FLAC
except ImportError:
return FILE_ICON
try:
audio = FLAC(flacPath)
art = audio.pictures
return self._generate_image_from_art(
art,
flacPath
)
except (IndexError, TypeError):
return FILE_ICON
except:
return FILE_ICON
def _generate_image_from_mp3(self, mp3Path):
# if we don't have the python module to
# extract image from mp3, we just return
# default file's icon
try:
from mutagen.id3 import ID3
except ImportError:
return FILE_ICON
try:
audio = ID3(mp3Path)
art = audio.getall("APIC")
return self._generate_image_from_art(
art,
mp3Path
)
except (IndexError, TypeError):
return FILE_ICON
except:
return FILE_ICON
def _generate_image_from_art(self, art, path):
pix = pix_from_art(art)
ext = mimetypes.guess_extension(pix.mime)
if ext == 'jpe':
ext = 'jpg'
image = self._generate_image_from_data(
path,
ext,
pix.data
)
self._thumbs[path] = image
return image
def _gen_temp_file_name(self, extension):
_, temporary_file_name = os.path.split(mktemp())
return join(self.thumbdir, temporary_file_name) + extension
def _generate_image_from_data(self, path, extension, data):
# data contains the raw bytes
# we save it inside a file, and return this file's temporary path
image = self._gen_temp_file_name(extension)
with open(image, "wb") as img:
img.write(data)
return image
def _generate_image_from_video(self, videoPath):
# we try to use an external software (avconv or ffmpeg)
# to get a frame as an image, otherwise => default file icon
data = extract_image_from_video(videoPath, self.thumbsize, self.play_overlay)
try:
if data:
return self._generate_image_from_data(
videoPath,
".png",
data)
else:
return FILE_ICON
except:
traceback.print_exc()
return FILE_ICON
def _gen_label(self, ctx):
size = ctx.get_nice_size()
temp = ""
try:
temp = os.path.splitext(ctx.name)[1][1:].upper()
except IndexError:
pass
if ctx.name.endswith(".tar.gz"):
temp = "TAR.GZ"
if ctx.name.endswith(".tar.bz2"):
temp = "TAR.BZ2"
if temp == "":
label = size
else:
label = size + " - " + temp
return label
class ThreadedThumbnailGenerator(object):
"""
Class that runs thumbnail generators in a another thread and
asynchronously updates image widgets
"""
def __init__(self):
self.thumbnail_queue = []
self.thread = None
def append(self, widget, ctx, func):
self.thumbnail_queue.append([widget, ctx, func])
def run(self):
if self.thread is None or not self.thread.isAlive():
self.thread = Thread(target=self._loop)
self.thread.start()
def _loop(self):
while len(self.thumbnail_queue) != 0:
# call user function that generates the thumbnail
image, ctx, func = self.thumbnail_queue.pop(0)
image.source = func(ctx)
# test if the file is a supported picture
# file
def is_picture(mime, name):
if mime is None:
return False
return "image/" in mime and (
"jpeg" in mime or
"jpg" in mime or
"gif" in mime or
"png" in mime
) and not name.endswith(".jpe")
def pix_from_art(art):
pix = None
if len(art) == 1:
pix = art[0]
elif len(art) > 1:
for pic in art:
if pic.type == 3:
pix = pic
if not pix:
# This would raise an exception if no image is present,
# and the default one would be returned
pix = art[0]
return pix
def get_mime(fileName):
try:
mime = mimetypes.guess_type(fileName)[0]
if mime is None:
return ""
return mime
except TypeError:
return ""
return ""
def extract_image_from_video(path, size, play_overlay):
data = None
if exec_exists(AVCONV_BIN):
data = get_png_from_video(AVCONV_BIN, path, int(size), play_overlay)
elif exec_exists(FFMPEG_BIN):
data = get_png_from_video(FFMPEG_BIN, path, int(size), play_overlay)
return data
# generic function to call a software to extract a PNG
# from an video file, it return the raw bytes, not an
# image file
def get_png_from_video(software, video_path, size, play_overlay):
return subprocess.Popen(
[
software,
'-i',
video_path,
'-i',
play_overlay,
'-filter_complex',
'[0]scale=-1:' + str(size) + '[video],[1]scale=-1:' + str(size) + '[over],' +
'[video][over]overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2',
'-an',
'-vcodec',
'png',
'-vframes',
'1',
'-ss',
'00:00:01',
'-y',
'-f',
'rawvideo',
'-'
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0]
def stack_images(software, bg, fg, out):
# You need ImageMagick to stack one image onto another
p = subprocess.Popen([software, bg, "-gravity", "Center", fg, "-compose", "Over", "-composite", out])
p.wait()
def exec_exists(bin):
try:
subprocess.check_output(["which", bin])
return True
except subprocess.CalledProcessError:
return False
except OSError:
return False
except:
return False
def compute_size(maxs, imgw, imgh):
if imgw > imgh:
return maxs, maxs*imgh/imgw
else:
return maxs *imgw/imgh, maxs
if __name__ == "__main__":
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
box = BoxLayout(orientation="vertical")
fileChooser = FileChooserThumbView(thumbsize=128)
label = Label(markup=True, size_hint=(1, 0.05))
fileChooser.mylabel = label
box.add_widget(fileChooser)
box.add_widget(label)
def setlabel(instance, value):
instance.mylabel.text = "[b]Selected:[/b] {0}".format(value)
fileChooser.bind(selection=setlabel)
runTouchApp(box)