add lt language, thanks to Adga
[enigma2.git] / skin.py
1 import xml.dom.minidom
2 from os import path
3
4 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
5         loadPNG, addFont, gRGB, eWindowStyleSkinned
6
7 from Components.config import ConfigSubsection, ConfigText, config
8 from Components.Converter.Converter import Converter
9 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
10 from Tools.Import import my_import
11
12 from Tools.XMLTools import elementsWithTag, mergeText
13
14 colorNames = dict()
15
16 def dump(x, i=0):
17         print " " * i + str(x)
18         try:
19                 for n in x.childNodes:
20                         dump(n, i + 1)
21         except:
22                 None
23
24 class SkinError(Exception):
25         def __init__(self, message):
26                 self.message = message
27
28         def __str__(self):
29                 return self.message
30
31 dom_skins = [ ]
32
33 def loadSkin(name):
34         # read the skin
35         filename = resolveFilename(SCOPE_SKIN, name)
36         mpath = path.dirname(filename) + "/"
37         dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
38
39 # we do our best to always select the "right" value
40 # skins are loaded in order of priority: skin with
41 # highest priority is loaded last, usually the user-provided
42 # skin.
43
44 # currently, loadSingleSkinData (colors, bordersets etc.)
45 # are applied one-after-each, in order of ascending priority.
46 # the dom_skin will keep all screens in descending priority,
47 # so the first screen found will be used.
48
49 # example: loadSkin("nemesis_greenline/skin.xml")
50 config.skin = ConfigSubsection()
51 config.skin.primary_skin = ConfigText(default = "skin.xml")
52
53 try:
54         loadSkin(config.skin.primary_skin.value)
55 except (SkinError, IOError, AssertionError), err:
56         print "SKIN ERROR:", err
57         print "defaulting to standard skin..."
58         loadSkin('skin.xml')
59 loadSkin('skin_default.xml')
60
61 def parsePosition(str):
62         x, y = str.split(',')
63         return ePoint(int(x), int(y))
64
65 def parseSize(str):
66         x, y = str.split(',')
67         return eSize(int(x), int(y))
68
69 def parseFont(str):
70         name, size = str.split(';')
71         return gFont(name, int(size))
72
73 def parseColor(str):
74         if str[0] != '#':
75                 try:
76                         return colorNames[str]
77                 except:
78                         raise ("color '%s' must be #aarrggbb or valid named color" % (str))
79         return gRGB(int(str[1:], 0x10))
80
81 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
82         # walk all attributes
83         for p in range(node.attributes.length):
84                 a = node.attributes.item(p)
85                 
86                 # convert to string (was: unicode)
87                 attrib = str(a.name)
88                 # TODO: localization? as in e1?
89                 value = a.value.encode("utf-8")
90                 
91                 if attrib in ["pixmap", "pointer", "seek_pointer"]:
92                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
93                 
94                 if attrib not in ignore:
95                         skinAttributes.append((attrib, value))
96
97 def loadPixmap(path):
98         ptr = loadPNG(path)
99         if ptr is None:
100                 raise "pixmap file %s not found!" % (path)
101         return ptr
102
103 def applySingleAttribute(guiObject, desktop, attrib, value):
104         # and set attributes
105         try:
106                 if attrib == 'position':
107                         guiObject.move(parsePosition(value))
108                 elif attrib == 'size':
109                         guiObject.resize(parseSize(value))
110                 elif attrib == 'title':
111                         guiObject.setTitle(_(value))
112                 elif attrib == 'text':
113                         guiObject.setText(_(value))
114                 elif attrib == 'font':
115                         guiObject.setFont(parseFont(value))
116                 elif attrib == 'zPosition':
117                         guiObject.setZPosition(int(value))
118                 elif attrib == "pixmap":
119                         ptr = loadPixmap(value) # this should already have been filename-resolved.
120                         desktop.makeCompatiblePixmap(ptr)
121                         guiObject.setPixmap(ptr)
122                         # guiObject.setPixmapFromFile(value)
123                 elif attrib == "alphatest": # used by ePixmap
124                         guiObject.setAlphatest(
125                                 { "on": True,
126                                   "off": False
127                                 }[value])
128                 elif attrib == "orientation": # used by eSlider
129                         try:
130                                 guiObject.setOrientation(
131                                         { "orVertical": guiObject.orVertical,
132                                                 "orHorizontal": guiObject.orHorizontal
133                                         }[value])
134                         except KeyError:
135                                 print "oprientation must be either orVertical or orHorizontal!"
136                 elif attrib == "valign":
137                         try:
138                                 guiObject.setVAlign(
139                                         { "top": guiObject.alignTop,
140                                                 "center": guiObject.alignCenter,
141                                                 "bottom": guiObject.alignBottom
142                                         }[value])
143                         except KeyError:
144                                 print "valign must be either top, center or bottom!"
145                 elif attrib == "halign":
146                         try:
147                                 guiObject.setHAlign(
148                                         { "left": guiObject.alignLeft,
149                                                 "center": guiObject.alignCenter,
150                                                 "right": guiObject.alignRight,
151                                                 "block": guiObject.alignBlock
152                                         }[value])
153                         except KeyError:
154                                 print "halign must be either left, center, right or block!"
155                 elif attrib == "flags":
156                         flags = value.split(',')
157                         for f in flags:
158                                 try:
159                                         fv = eWindow.__dict__[f]
160                                         guiObject.setFlag(fv)
161                                 except KeyError:
162                                         print "illegal flag %s!" % f
163                 elif attrib == "backgroundColor":
164                         guiObject.setBackgroundColor(parseColor(value))
165                 elif attrib == "foregroundColor":
166                         guiObject.setForegroundColor(parseColor(value))
167                 elif attrib == "shadowColor":
168                         guiObject.setShadowColor(parseColor(value))
169                 elif attrib == "selectionDisabled":
170                         guiObject.setSelectionEnable(0)
171                 elif attrib == "transparent":
172                         guiObject.setTransparent(int(value))
173                 elif attrib == "borderColor":
174                         guiObject.setBorderColor(parseColor(value))
175                 elif attrib == "borderWidth":
176                         guiObject.setBorderWidth(int(value))
177                 elif attrib == "scrollbarMode":
178                         guiObject.setScrollbarMode(
179                                 { "showOnDemand": guiObject.showOnDemand,
180                                         "showAlways": guiObject.showAlways,
181                                         "showNever": guiObject.showNever
182                                 }[value])
183                 elif attrib == "enableWrapAround":
184                         guiObject.setWrapAround(True)
185                 elif attrib == "pointer" or attrib == "seek_pointer":
186                         (name, pos) = value.split(':')
187                         pos = parsePosition(pos)
188                         ptr = loadPixmap(name)
189                         desktop.makeCompatiblePixmap(ptr)
190                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
191                 elif attrib == 'shadowOffset':
192                         guiObject.setShadowOffset(parsePosition(value))
193                 elif attrib == 'noWrap':
194                         guiObject.setNoWrap(1)
195                 else:
196                         raise "unsupported attribute " + attrib + "=" + value
197         except int:
198 # AttributeError:
199                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
200
201 def applyAllAttributes(guiObject, desktop, attributes):
202         for (attrib, value) in attributes:
203                 applySingleAttribute(guiObject, desktop, attrib, value)
204
205 def loadSingleSkinData(desktop, dom_skin, path_prefix):
206         """loads skin data like colors, windowstyle etc."""
207         
208         skin = dom_skin.childNodes[0]
209         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
210         
211         for c in elementsWithTag(skin.childNodes, "colors"):
212                 for color in elementsWithTag(c.childNodes, "color"):
213                         name = str(color.getAttribute("name"))
214                         color = str(color.getAttribute("value"))
215                         
216                         if not len(color):
217                                 raise ("need color and name, got %s %s" % (name, color))
218                                 
219                         colorNames[name] = parseColor(color)
220         
221         for c in elementsWithTag(skin.childNodes, "fonts"):
222                 for font in elementsWithTag(c.childNodes, "font"):
223                         filename = str(font.getAttribute("filename") or "<NONAME>")
224                         name = str(font.getAttribute("name") or "Regular")
225                         scale = int(font.getAttribute("scale") or "100")
226                         is_replacement = font.getAttribute("replacement") != ""
227                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
228         
229         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
230                 style = eWindowStyleSkinned()
231                 id = int(windowstyle.getAttribute("id") or "0")
232                 
233                 # defaults
234                 font = gFont("Regular", 20)
235                 offset = eSize(20, 5)
236                 
237                 for title in elementsWithTag(windowstyle.childNodes, "title"):
238                         offset = parseSize(title.getAttribute("offset"))
239                         font = parseFont(str(title.getAttribute("font")))
240
241                 style.setTitleFont(font);
242                 style.setTitleOffset(offset)
243                 
244                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
245                         bsName = str(borderset.getAttribute("name"))
246                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
247                                 bpName = str(pixmap.getAttribute("pos"))
248                                 filename = str(pixmap.getAttribute("filename"))
249                                 
250                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
251                                 
252                                 # adapt palette
253                                 desktop.makeCompatiblePixmap(png)
254                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
255
256                 for color in elementsWithTag(windowstyle.childNodes, "color"):
257                         type = str(color.getAttribute("name"))
258                         color = parseColor(color.getAttribute("color"))
259                         
260                         try:
261                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
262                         except:
263                                 raise ("Unknown color %s" % (type))
264                         
265                 x = eWindowStyleManager.getInstance()
266                 x.setStyle(id, style)
267
268 def loadSkinData(desktop):
269         skins = dom_skins[:]
270         skins.reverse()
271         for (path, dom_skin) in skins:
272                 loadSingleSkinData(desktop, dom_skin, path)
273
274 def lookupScreen(name):
275         for (path, dom_skin) in dom_skins:
276                 # first, find the corresponding screen element
277                 skin = dom_skin.childNodes[0] 
278                 for x in elementsWithTag(skin.childNodes, "screen"):
279                         if x.getAttribute('name') == name:
280                                 return x, path
281         return None, None
282
283 def readSkin(screen, skin, name, desktop):
284         
285         myscreen, path = lookupScreen(name)
286         
287         # otherwise try embedded skin
288         myscreen = myscreen or getattr(screen, "parsedSkin", None)
289         
290         # try uncompiled embedded skin
291         if myscreen is None and getattr(screen, "skin", None):
292                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
293         
294         assert myscreen is not None, "no skin for screen '" + name + "' found!"
295
296         screen.skinAttributes = [ ]
297         
298         skin_path_prefix = getattr(screen, "skin_path", path)
299
300         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
301         
302         screen.additionalWidgets = [ ]
303         screen.renderer = [ ]
304         
305         visited_components = set()
306         
307         # now walk all widgets
308         for widget in elementsWithTag(myscreen.childNodes, "widget"):
309                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
310                 # widgets (source->renderer).
311
312                 wname = widget.getAttribute('name')
313                 wsource = widget.getAttribute('source')
314                 
315
316                 if wname is None and wsource is None:
317                         print "widget has no name and no source!"
318                         continue
319                 
320                 if wname:
321                         visited_components.add(wname)
322
323                         # get corresponding 'gui' object
324                         try:
325                                 attributes = screen[wname].skinAttributes = [ ]
326                         except:
327                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
328
329 #                       assert screen[wname] is not Source
330
331                         # and collect attributes for this
332                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
333                 elif wsource:
334                         # get corresponding source
335                         source = screen.get(wsource)
336                         if source is None:
337                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
338                         
339                         wrender = widget.getAttribute('render')
340                         
341                         if not wrender:
342                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
343                         
344                         for converter in elementsWithTag(widget.childNodes, "convert"):
345                                 ctype = converter.getAttribute('type')
346                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
347                                 parms = mergeText(converter.childNodes).strip()
348                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
349                                 
350                                 c = None
351                                 
352                                 for i in source.downstream_elements:
353                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
354                                                 c = i
355
356                                 if c is None:
357                                         print "allocating new converter!"
358                                         c = converter_class(parms)
359                                         c.connect(source)
360                                 else:
361                                         print "reused conveter!"
362         
363                                 source = c
364                         
365                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
366                         
367                         renderer = renderer_class() # instantiate renderer
368                         
369                         renderer.connect(source) # connect to source
370                         attributes = renderer.skinAttributes = [ ]
371                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
372                         
373                         screen.renderer.append(renderer)
374
375         from Components.GUIComponent import GUIComponent
376         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
377         
378         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
379
380         # now walk additional objects
381         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
382                 if widget.tagName == "applet":
383                         codeText = mergeText(widget.childNodes).strip()
384                         type = widget.getAttribute('type')
385
386                         code = compile(codeText, "skin applet", "exec")
387                         
388                         if type == "onLayoutFinish":
389                                 screen.onLayoutFinish.append(code)
390                         else:
391                                 raise SkinError("applet type '%s' unknown!" % type)
392                         
393                         continue
394                 
395                 class additionalWidget:
396                         pass
397                 
398                 w = additionalWidget()
399                 
400                 if widget.tagName == "eLabel":
401                         w.widget = eLabel
402                 elif widget.tagName == "ePixmap":
403                         w.widget = ePixmap
404                 else:
405                         raise SkinError("unsupported stuff : %s" % widget.tagName)
406                 
407                 w.skinAttributes = [ ]
408                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
409                 
410                 # applyAttributes(guiObject, widget, desktop)
411                 # guiObject.thisown = 0
412                 screen.additionalWidgets.append(w)