Fixed some bugs spotted by pychecker
[zeroinstall/solver.git] / zeroinstall / gtkui / icon.py
blobe1dc68d361256f9a183ff94a5cfb7ebf9a6c6169
1 """Loading icons."""
2 # Copyright (C) 2009, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 from zeroinstall import _
6 import gtk
7 from logging import warn, debug
8 import math
10 def load_icon(icon_path, icon_width=None, icon_height=None):
11 """Load icon from path. Icon MUST be in PNG format.
12 @param icon_path: pathname of icon, or None to load nothing
13 @return: a GdkPixbuf, or None on failure"""
14 if not icon_path:
15 return None
17 def size_prepared_cb(loader, width, height):
18 dest_width = icon_width or width
19 dest_height = icon_height or height
21 if dest_width == width and dest_height == height:
22 return
24 ratio_width = float(dest_width) / width
25 ratio_height = float(dest_height) / height
26 ratio = min(ratio_width, ratio_height)
28 # preserve original ration
29 if ratio_width != ratio:
30 dest_width = int(math.ceil(width * ratio))
31 elif ratio_height != ratio:
32 dest_height = int(math.ceil(height * ratio))
34 loader.set_size(int(dest_width), int(dest_height))
36 # Restrict icon formats to avoid attacks
37 for format in ('png', 'svg'):
38 try:
39 loader = gtk.gdk.PixbufLoader(format)
40 if icon_width or icon_height:
41 loader.connect('size-prepared', size_prepared_cb)
42 try:
43 loader.write(file(icon_path).read())
44 finally:
45 loader.close()
46 return loader.get_pixbuf()
47 except Exception, ex:
48 debug(_("Failed to load icon: %s") % ex)
50 warn(_("Failed to load cached icon"))
51 return None