1# vim:set et sts=4 sw=4: 2# 3# ibus - The Input Bus 4# 5# Copyright (c) 2007-2010 Peng Huang <shawn.p.huang@gmail.com> 6# Copyright (c) 2007-2010 Red Hat, Inc. 7# 8# This library is free software; you can redistribute it and/or 9# modify it under the terms of the GNU Lesser General Public 10# License as published by the Free Software Foundation; either 11# version 2.1 of the License, or (at your option) any later version. 12# 13# This library is distributed in the hope that it will be useful, 14# but WITHOUT ANY WARRANTY; without even the implied warranty of 15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16# Lesser General Public License for more details. 17# 18# You should have received a copy of the GNU Lesser General Public 19# License along with this library; if not, write to the Free Software 20# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 21# USA 22 23__all__ = ( 24 "load_icon" 25) 26 27from gi.repository import Gdk 28from gi.repository import GdkPixbuf 29from gi.repository import Gtk 30from os import path 31 32 33icon_theme = Gtk.IconTheme.get_default() 34dir = path.dirname(__file__) 35icondir = path.join(dir, "..", "icons") 36icon_theme.prepend_search_path(icondir) 37 38icon_cache = {} 39 40# load_icon: 41# @icon_name_or_path: Can be a name or path but not stock id 42# because gtk_icon_theme_load_icon() cannot fallback the stock id to 43# a real file name against gtk_image_new_from_stock(). 44# @size: #GtkIconSize 45def load_icon(icon_name_or_path, size): 46 if (icon_name_or_path, size) in icon_cache: 47 return icon_cache[(icon_name_or_path, size)] 48 49 icon_size = Gtk.icon_size_lookup(size) 50 if icon_size[0]: 51 icon_size = icon_size[1] 52 53 pixbuf = None 54 try: 55 pixbuf = GdkPixbuf.Pixbuf.new_from_file(icon_name_or_path) 56 w, h = pixbuf.get_width(), pixbuf.get_height() 57 rate = max(w, h) / float(icon_size) 58 w = int(w / rate) 59 h = int(h / rate) 60 pixbuf = pixbuf.scale_simple(w, h, GdkPixbuf.InterpType.BILINEAR) 61 except: 62 # import traceback 63 # traceback.print_exc() 64 pass 65 if pixbuf == None: 66 try: 67 theme = Gtk.IconTheme.get_default() 68 pixbuf = theme.load_icon(icon_name_or_path, icon_size, 0) 69 except: 70 # import traceback 71 # traceback.print_exc() 72 pass 73 if pixbuf == None: 74 try: 75 theme = Gtk.IconTheme.get_default() 76 pixbuf = theme.load_icon('ibus-engine', icon_size, 0) 77 except: 78 # import traceback 79 # traceback.print_exc() 80 pass 81 if pixbuf == None: 82 try: 83 theme = Gtk.IconTheme.get_default() 84 pixbuf = theme.load_icon('image-missing', icon_size, 0) 85 except: 86 # import traceback 87 # traceback.print_exc() 88 pass 89 icon_cache[(icon_name_or_path, size)] = pixbuf 90 return pixbuf 91