Large-scale API cleanup
[zeroinstall/zeroinstall-afb.git] / zeroinstall / gtkui / icon.py
blobf954e7621ead81a7561597a68c10fe5a297952e6
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
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 try:
38 loader = gtk.gdk.PixbufLoader('png')
39 if icon_width or icon_height:
40 loader.connect('size-prepared', size_prepared_cb)
41 try:
42 loader.write(file(icon_path).read())
43 finally:
44 loader.close()
45 return loader.get_pixbuf()
46 except Exception, ex:
47 warn(_("Failed to load cached PNG icon: %s") % ex)
48 return None