1"""Loading icons.""" 2# Copyright (C) 2009, Thomas Leonard 3# See the README file for details, or visit http://0install.net. 4 5fromzeroinstallimport_,logger 6importgtk 7importmath 8
10"""Load icon from path. Icon MUST be in PNG format.11 @param icon_path: pathname of icon, or None to load nothing12 @return: a GdkPixbuf, or None on failure"""13ifnoticon_path:14returnNone1516defsize_prepared_cb(loader,width,height):17dest_width=icon_widthorwidth18dest_height=icon_heightorheight1920ifdest_width==widthanddest_height==height:21return2223ratio_width=float(dest_width)/width24ratio_height=float(dest_height)/height25ratio=min(ratio_width,ratio_height)2627# preserve original ration28ifratio_width!=ratio:29dest_width=int(math.ceil(width*ratio))30elifratio_height!=ratio:31dest_height=int(math.ceil(height*ratio))3233loader.set_size(int(dest_width),int(dest_height))
3435# Restrict icon formats to avoid attacks36try:37loader=gtk.gdk.PixbufLoader('png')38ificon_widthoricon_height:39loader.connect('size-prepared',size_prepared_cb)40try:41withopen(icon_path,'rb')asstream:42loader.write(stream.read())43finally:44loader.close()45returnloader.get_pixbuf()46exceptExceptionasex:47logger.warning(_("Failed to load cached PNG icon: %s")%ex)48returnNone49