Make pychecker happier.
[rox-lib.git] / python / rox / icon_theme.py
blob14e83696a22570363a60e677594f213220f84c1e
1 """This is an internal module. Do not use it. GTK 2.4 will contain functions
2 that replace those defined here."""
4 import os
5 import basedir
6 import rox
8 theme_dirs = [os.path.join(os.environ.get('HOME', '/'), '.icons')] + \
9 list(basedir.load_data_paths('icons'))
11 class Index:
12 def __init__(self, dir):
13 self.dir = dir
14 sections = file(os.path.join(dir, "index.theme")).read().split('\n[')
15 self.sections = {}
16 for s in sections:
17 lines = s.split('\n')
18 sname = lines[0].strip()
20 # Python < 2.2.2 doesn't support an argument to strip...
21 assert sname[-1] == ']'
22 if sname.startswith('['):
23 sname = sname[1:-1]
24 else:
25 sname = sname[:-1]
27 section = self.sections[sname] = {}
28 for line in lines[1:]:
29 if not line.strip(): continue
30 if line.startswith('#'): continue
31 key, value = map(str.strip, line.split('=', 1))
32 section[key] = value
34 self.subdirs = [SubDir(self, d) for
35 d in self.get('Icon Theme', 'Directories').split(';')]
37 def get(self, section, key):
38 "None if not found"
39 return self.sections.get(section, {}).get(key, None)
41 class SubDir:
42 def __init__(self, index, subdir):
43 type = index.get(subdir, 'Type')
44 self.name = subdir
45 self.size = int(index.get(subdir, 'Size'))
46 if type == "Fixed":
47 self.min_size = self.max_size = self.size
48 elif type == "Threshold":
49 threshold = int(index.get(subdir, 'Threshold'))
50 self.min_size = self.size - threshold
51 self.max_size = self.size + threshold
52 elif type == "Scaled":
53 self.min_size = int(index.get(subdir, 'MinSize'))
54 self.max_size = int(index.get(subdir, 'MaxSize'))
55 else:
56 self.min_size = self.max_size = 100000
58 class IconTheme:
59 def __init__(self, name):
60 self.name = name
62 self.indexes = []
63 for dir in theme_dirs:
64 theme_dir = os.path.join(dir, name)
65 index_file = os.path.join(theme_dir, 'index.theme')
66 if os.path.exists(os.path.join(index_file)):
67 try:
68 self.indexes.append(Index(theme_dir))
69 except:
70 rox.report_exception()
72 def lookup_icon(self, iconname, size):
73 icon = self._lookup_this_theme(iconname, size)
74 if icon: return icon
75 # XXX: inherits
77 def _lookup_this_theme(self, iconname, size):
78 dirs = []
79 for i in self.indexes:
80 for d in i.subdirs:
81 if size < d.min_size:
82 diff = d.min_size - size
83 elif size > d.max_size:
84 diff = size - d.max_size
85 else:
86 diff = 0
87 dirs.append((diff, os.path.join(i.dir, d.name)))
89 # Sort by closeness of size
90 dirs.sort()
92 for _, subdir in dirs:
93 for extension in ("png", "svg"):
94 filename = os.path.join(subdir,
95 iconname + '.' + extension)
96 if os.path.exists(filename):
97 return filename
99 rox_theme = IconTheme('ROX')