2 # Copyright (C) 2009, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 from zeroinstall
import _
7 from logging
import warn
, debug
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"""
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
:
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'):
39 loader
= gtk
.gdk
.PixbufLoader(format
)
40 if icon_width
or icon_height
:
41 loader
.connect('size-prepared', size_prepared_cb
)
43 loader
.write(file(icon_path
).read())
46 return loader
.get_pixbuf()
48 debug(_("Failed to load icon: %s") % ex
)
50 warn(_("Failed to load cached icon"))