1 """Loading icons."""
2
3
4
5 from zeroinstall import _, logger
6 import gtk
7 import math
8
9 -def load_icon(icon_path, icon_width=None, icon_height=None):
10 """Load icon from path. Icon MUST be in PNG format.
11 @param icon_path: pathname of icon, or None to load nothing
12 @return: a GdkPixbuf, or None on failure"""
13 if not icon_path:
14 return None
15
16 def size_prepared_cb(loader, width, height):
17 dest_width = icon_width or width
18 dest_height = icon_height or height
19
20 if dest_width == width and dest_height == height:
21 return
22
23 ratio_width = float(dest_width) / width
24 ratio_height = float(dest_height) / height
25 ratio = min(ratio_width, ratio_height)
26
27
28 if ratio_width != ratio:
29 dest_width = int(math.ceil(width * ratio))
30 elif ratio_height != ratio:
31 dest_height = int(math.ceil(height * ratio))
32
33 loader.set_size(int(dest_width), int(dest_height))
34
35
36 try:
37 loader = gtk.gdk.PixbufLoader('png')
38 if icon_width or icon_height:
39 loader.connect('size-prepared', size_prepared_cb)
40 try:
41 with open(icon_path, 'rb') as stream:
42 loader.write(stream.read())
43 finally:
44 loader.close()
45 return loader.get_pixbuf()
46 except Exception as ex:
47 logger.warning(_("Failed to load cached PNG icon: %s") % ex)
48 return None
49