Load icons in binary mode (for Python 3)
[zeroinstall.git] / zeroinstall / gtkui / icon.py
blob4118921664e76914b60156afccbc39393a5c49f3
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 with open(icon_path, 'rb') as stream:
43 loader.write(stream.read())
44 finally:
45 loader.close()
46 return loader.get_pixbuf()
47 except Exception as ex:
48 warn(_("Failed to load cached PNG icon: %s") % ex)
49 return None