Fixed very useful TestPlugin-plugin (callback wasn't called correctly)
[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         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, ObsoleteSource
10 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
11 from Tools.Import import my_import
12 from Tools.LoadPixmap import LoadPixmap
13
14 from Tools.XMLTools import elementsWithTag, mergeText
15
16 colorNames = dict()
17
18 def dump(x, i=0):
19         print " " * i + str(x)
20         try:
21                 for n in x.childNodes:
22                         dump(n, i + 1)
23         except:
24                 None
25
26 class SkinError(Exception):
27         def __init__(self, message):
28                 self.message = message
29
30         def __str__(self):
31                 return self.message
32
33 dom_skins = [ ]
34
35 def loadSkin(name):
36         # read the skin
37         filename = resolveFilename(SCOPE_SKIN, name)
38         mpath = path.dirname(filename) + "/"
39         dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
40
41 # we do our best to always select the "right" value
42 # skins are loaded in order of priority: skin with
43 # highest priority is loaded last, usually the user-provided
44 # skin.
45
46 # currently, loadSingleSkinData (colors, bordersets etc.)
47 # are applied one-after-each, in order of ascending priority.
48 # the dom_skin will keep all screens in descending priority,
49 # so the first screen found will be used.
50
51 # example: loadSkin("nemesis_greenline/skin.xml")
52 config.skin = ConfigSubsection()
53 config.skin.primary_skin = ConfigText(default = "skin.xml")
54
55 try:
56         loadSkin(config.skin.primary_skin.value)
57 except (SkinError, IOError, AssertionError), err:
58         print "SKIN ERROR:", err
59         print "defaulting to standard skin..."
60         config.skin.primary_skin.value = 'skin.xml'
61         loadSkin('skin.xml')
62
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 SkinError("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, desktop):
102         ptr = LoadPixmap(path, desktop)
103         if ptr is None:
104                 raise SkinError("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, desktop) # this should already have been filename-resolved.
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": 1,
134                                   "off": 0,
135                                   "blend": 2,
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 == "backgroundColorSelected":
175                         guiObject.setBackgroundColorSelected(parseColor(value))
176                 elif attrib == "foregroundColor":
177                         guiObject.setForegroundColor(parseColor(value))
178                 elif attrib == "foregroundColorSelected":
179                         guiObject.setForegroundColorSelected(parseColor(value))
180                 elif attrib == "shadowColor":
181                         guiObject.setShadowColor(parseColor(value))
182                 elif attrib == "selectionDisabled":
183                         guiObject.setSelectionEnable(0)
184                 elif attrib == "transparent":
185                         guiObject.setTransparent(int(value))
186                 elif attrib == "borderColor":
187                         guiObject.setBorderColor(parseColor(value))
188                 elif attrib == "borderWidth":
189                         guiObject.setBorderWidth(int(value))
190                 elif attrib == "scrollbarMode":
191                         guiObject.setScrollbarMode(
192                                 { "showOnDemand": guiObject.showOnDemand,
193                                         "showAlways": guiObject.showAlways,
194                                         "showNever": guiObject.showNever
195                                 }[value])
196                 elif attrib == "enableWrapAround":
197                         guiObject.setWrapAround(True)
198                 elif attrib == "pointer" or attrib == "seek_pointer":
199                         (name, pos) = value.split(':')
200                         pos = parsePosition(pos)
201                         ptr = loadPixmap(name, desktop)
202                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
203                 elif attrib == 'shadowOffset':
204                         guiObject.setShadowOffset(parsePosition(value))
205                 elif attrib == 'noWrap':
206                         guiObject.setNoWrap(1)
207                 else:
208                         raise SkinError("unsupported attribute " + attrib + "=" + value)
209         except int:
210 # AttributeError:
211                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
212
213 def applyAllAttributes(guiObject, desktop, attributes):
214         for (attrib, value) in attributes:
215                 applySingleAttribute(guiObject, desktop, attrib, value)
216
217 def loadSingleSkinData(desktop, dom_skin, path_prefix):
218         """loads skin data like colors, windowstyle etc."""
219         
220         skin = dom_skin.childNodes[0]
221         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
222
223         for c in elementsWithTag(skin.childNodes, "output"):
224                 id = int(c.getAttribute("id") or "0")
225                 if id == 0: # framebuffer
226                         for res in elementsWithTag(c.childNodes, "resolution"):
227                                 xres = int(res.getAttribute("xres" or "720"))
228                                 yres = int(res.getAttribute("yres" or "576"))
229                                 bpp = int(res.getAttribute("bpp" or "32"))
230
231                                 from enigma import gFBDC
232                                 i = gFBDC.getInstance()
233                                 i.setResolution(xres, yres)
234
235                                 if bpp != 32:
236                                         # load palette (not yet implemented)
237                                         pass
238
239         for c in elementsWithTag(skin.childNodes, "colors"):
240                 for color in elementsWithTag(c.childNodes, "color"):
241                         name = str(color.getAttribute("name"))
242                         color = str(color.getAttribute("value"))
243                         
244                         if not len(color):
245                                 raise ("need color and name, got %s %s" % (name, color))
246                                 
247                         colorNames[name] = parseColor(color)
248         
249         for c in elementsWithTag(skin.childNodes, "fonts"):
250                 for font in elementsWithTag(c.childNodes, "font"):
251                         filename = str(font.getAttribute("filename") or "<NONAME>")
252                         name = str(font.getAttribute("name") or "Regular")
253                         scale = int(font.getAttribute("scale") or "100")
254                         is_replacement = font.getAttribute("replacement") != ""
255                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
256         
257         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
258                 style = eWindowStyleSkinned()
259                 id = int(windowstyle.getAttribute("id") or "0")
260                 
261                 # defaults
262                 font = gFont("Regular", 20)
263                 offset = eSize(20, 5)
264                 
265                 for title in elementsWithTag(windowstyle.childNodes, "title"):
266                         offset = parseSize(title.getAttribute("offset"))
267                         font = parseFont(str(title.getAttribute("font")))
268
269                 style.setTitleFont(font);
270                 style.setTitleOffset(offset)
271                 
272                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
273                         bsName = str(borderset.getAttribute("name"))
274                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
275                                 bpName = str(pixmap.getAttribute("pos"))
276                                 filename = str(pixmap.getAttribute("filename"))
277                                 
278                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
279                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
280
281                 for color in elementsWithTag(windowstyle.childNodes, "color"):
282                         type = str(color.getAttribute("name"))
283                         color = parseColor(color.getAttribute("color"))
284                         
285                         try:
286                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
287                         except:
288                                 raise ("Unknown color %s" % (type))
289                         
290                 x = eWindowStyleManager.getInstance()
291                 x.setStyle(id, style)
292
293 def loadSkinData(desktop):
294         skins = dom_skins[:]
295         skins.reverse()
296         for (path, dom_skin) in skins:
297                 loadSingleSkinData(desktop, dom_skin, path)
298
299 def lookupScreen(name):
300         for (path, dom_skin) in dom_skins:
301                 # first, find the corresponding screen element
302                 skin = dom_skin.childNodes[0] 
303                 for x in elementsWithTag(skin.childNodes, "screen"):
304                         if x.getAttribute('name') == name:
305                                 return x, path
306         return None, None
307
308 def readSkin(screen, skin, names, desktop):
309         if not isinstance(names, list):
310                 names = [names]
311
312         name = "<embedded-in-'%s'>" % screen.__class__.__name__
313
314         # try all skins, first existing one have priority
315         for n in names:
316                 myscreen, path = lookupScreen(n)
317                 if myscreen is not None:
318                         # use this name for debug output
319                         name = n
320                         break
321
322         # otherwise try embedded skin
323         myscreen = myscreen or getattr(screen, "parsedSkin", None)
324
325         # try uncompiled embedded skin
326         if myscreen is None and getattr(screen, "skin", None):
327                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
328
329         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
330
331         screen.skinAttributes = [ ]
332         
333         skin_path_prefix = getattr(screen, "skin_path", path)
334
335         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
336         
337         screen.additionalWidgets = [ ]
338         screen.renderer = [ ]
339         
340         visited_components = set()
341         
342         # now walk all widgets
343         for widget in elementsWithTag(myscreen.childNodes, "widget"):
344                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
345                 # widgets (source->renderer).
346
347                 wname = widget.getAttribute('name')
348                 wsource = widget.getAttribute('source')
349                 
350
351                 if wname is None and wsource is None:
352                         print "widget has no name and no source!"
353                         continue
354                 
355                 if wname:
356                         visited_components.add(wname)
357
358                         # get corresponding 'gui' object
359                         try:
360                                 attributes = screen[wname].skinAttributes = [ ]
361                         except:
362                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
363
364 #                       assert screen[wname] is not Source
365
366                         # and collect attributes for this
367                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
368                 elif wsource:
369                         # get corresponding source
370
371                         while True: # until we found a non-obsolete source
372
373                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
374                                 # for example to reference a parent, global or session-global screen.
375                                 scr = screen
376
377                                 # resolve all path components
378                                 path = wsource.split('.')
379                                 while len(path) > 1:
380                                         scr = screen.getRelatedScreen(path[0])
381                                         if scr is None:
382                                                 print wsource
383                                                 print name
384                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
385                                         path = path[1:]
386
387                                 # resolve the source.
388                                 source = scr.get(path[0])
389                                 if isinstance(source, ObsoleteSource):
390                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
391                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
392                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
393                                         if source.description:
394                                                 print source.description
395
396                                         wsource = source.new_source
397                                 else:
398                                         # otherwise, use that source.
399                                         break
400
401                         if source is None:
402                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
403                         
404                         wrender = widget.getAttribute('render')
405                         
406                         if not wrender:
407                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
408                         
409                         for converter in elementsWithTag(widget.childNodes, "convert"):
410                                 ctype = converter.getAttribute('type')
411                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
412                                 parms = mergeText(converter.childNodes).strip()
413                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
414                                 
415                                 c = None
416                                 
417                                 for i in source.downstream_elements:
418                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
419                                                 c = i
420
421                                 if c is None:
422                                         print "allocating new converter!"
423                                         c = converter_class(parms)
424                                         c.connect(source)
425                                 else:
426                                         print "reused converter!"
427         
428                                 source = c
429                         
430                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
431                         
432                         renderer = renderer_class() # instantiate renderer
433                         
434                         renderer.connect(source) # connect to source
435                         attributes = renderer.skinAttributes = [ ]
436                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
437                         
438                         screen.renderer.append(renderer)
439
440         from Components.GUIComponent import GUIComponent
441         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
442         
443         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
444
445         # now walk additional objects
446         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
447                 if widget.tagName == "applet":
448                         codeText = mergeText(widget.childNodes).strip()
449                         type = widget.getAttribute('type')
450
451                         code = compile(codeText, "skin applet", "exec")
452                         
453                         if type == "onLayoutFinish":
454                                 screen.onLayoutFinish.append(code)
455                         else:
456                                 raise SkinError("applet type '%s' unknown!" % type)
457                         
458                         continue
459                 
460                 class additionalWidget:
461                         pass
462                 
463                 w = additionalWidget()
464                 
465                 if widget.tagName == "eLabel":
466                         w.widget = eLabel
467                 elif widget.tagName == "ePixmap":
468                         w.widget = ePixmap
469                 else:
470                         raise SkinError("unsupported stuff : %s" % widget.tagName)
471                 
472                 w.skinAttributes = [ ]
473                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
474                 
475                 # applyAttributes(guiObject, widget, desktop)
476                 # guiObject.thisown = 0
477                 screen.additionalWidgets.append(w)