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