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