2 # Copyright (C) 2009, Thomas Leonard
3 # See the README file for details, or visit http://0install.net.
5 from zeroinstall
import _
, logger
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"""
16 def size_prepared_cb(loader
, width
, height
):
17 dest_width
= icon_width
or width
18 dest_height
= icon_height
or height
20 if dest_width
== width
and dest_height
== height
:
23 ratio_width
= float(dest_width
) / width
24 ratio_height
= float(dest_height
) / height
25 ratio
= min(ratio_width
, ratio_height
)
27 # preserve original ration
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
))
33 loader
.set_size(int(dest_width
), int(dest_height
))
35 # Restrict icon formats to avoid attacks
37 loader
= gtk
.gdk
.PixbufLoader('png')
38 if icon_width
or icon_height
:
39 loader
.connect('size-prepared', size_prepared_cb
)
41 with
open(icon_path
, 'rb') as stream
:
42 loader
.write(stream
.read())
45 return loader
.get_pixbuf()
46 except Exception as ex
:
47 logger
.warn(_("Failed to load cached PNG icon: %s") % ex
)