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