do not use obsolete sources in radio infobar
[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 SkinError("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 SkinError("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 == "backgroundColorSelected":
172                         guiObject.setBackgroundColorSelected(parseColor(value))
173                 elif attrib == "foregroundColor":
174                         guiObject.setForegroundColor(parseColor(value))
175                 elif attrib == "foregroundColorSelected":
176                         guiObject.setForegroundColorSelected(parseColor(value))
177                 elif attrib == "shadowColor":
178                         guiObject.setShadowColor(parseColor(value))
179                 elif attrib == "selectionDisabled":
180                         guiObject.setSelectionEnable(0)
181                 elif attrib == "transparent":
182                         guiObject.setTransparent(int(value))
183                 elif attrib == "borderColor":
184                         guiObject.setBorderColor(parseColor(value))
185                 elif attrib == "borderWidth":
186                         guiObject.setBorderWidth(int(value))
187                 elif attrib == "scrollbarMode":
188                         guiObject.setScrollbarMode(
189                                 { "showOnDemand": guiObject.showOnDemand,
190                                         "showAlways": guiObject.showAlways,
191                                         "showNever": guiObject.showNever
192                                 }[value])
193                 elif attrib == "enableWrapAround":
194                         guiObject.setWrapAround(True)
195                 elif attrib == "pointer" or attrib == "seek_pointer":
196                         (name, pos) = value.split(':')
197                         pos = parsePosition(pos)
198                         ptr = loadPixmap(name)
199                         desktop.makeCompatiblePixmap(ptr)
200                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
201                 elif attrib == 'shadowOffset':
202                         guiObject.setShadowOffset(parsePosition(value))
203                 elif attrib == 'noWrap':
204                         guiObject.setNoWrap(1)
205                 else:
206                         raise SkinError("unsupported attribute " + attrib + "=" + value)
207         except int:
208 # AttributeError:
209                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
210
211 def applyAllAttributes(guiObject, desktop, attributes):
212         for (attrib, value) in attributes:
213                 applySingleAttribute(guiObject, desktop, attrib, value)
214
215 def loadSingleSkinData(desktop, dom_skin, path_prefix):
216         """loads skin data like colors, windowstyle etc."""
217         
218         skin = dom_skin.childNodes[0]
219         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
220         
221         for c in elementsWithTag(skin.childNodes, "colors"):
222                 for color in elementsWithTag(c.childNodes, "color"):
223                         name = str(color.getAttribute("name"))
224                         color = str(color.getAttribute("value"))
225                         
226                         if not len(color):
227                                 raise ("need color and name, got %s %s" % (name, color))
228                                 
229                         colorNames[name] = parseColor(color)
230         
231         for c in elementsWithTag(skin.childNodes, "fonts"):
232                 for font in elementsWithTag(c.childNodes, "font"):
233                         filename = str(font.getAttribute("filename") or "<NONAME>")
234                         name = str(font.getAttribute("name") or "Regular")
235                         scale = int(font.getAttribute("scale") or "100")
236                         is_replacement = font.getAttribute("replacement") != ""
237                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
238         
239         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
240                 style = eWindowStyleSkinned()
241                 id = int(windowstyle.getAttribute("id") or "0")
242                 
243                 # defaults
244                 font = gFont("Regular", 20)
245                 offset = eSize(20, 5)
246                 
247                 for title in elementsWithTag(windowstyle.childNodes, "title"):
248                         offset = parseSize(title.getAttribute("offset"))
249                         font = parseFont(str(title.getAttribute("font")))
250
251                 style.setTitleFont(font);
252                 style.setTitleOffset(offset)
253                 
254                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
255                         bsName = str(borderset.getAttribute("name"))
256                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
257                                 bpName = str(pixmap.getAttribute("pos"))
258                                 filename = str(pixmap.getAttribute("filename"))
259                                 
260                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
261                                 
262                                 # adapt palette
263                                 desktop.makeCompatiblePixmap(png)
264                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
265
266                 for color in elementsWithTag(windowstyle.childNodes, "color"):
267                         type = str(color.getAttribute("name"))
268                         color = parseColor(color.getAttribute("color"))
269                         
270                         try:
271                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
272                         except:
273                                 raise ("Unknown color %s" % (type))
274                         
275                 x = eWindowStyleManager.getInstance()
276                 x.setStyle(id, style)
277
278 def loadSkinData(desktop):
279         skins = dom_skins[:]
280         skins.reverse()
281         for (path, dom_skin) in skins:
282                 loadSingleSkinData(desktop, dom_skin, path)
283
284 def lookupScreen(name):
285         for (path, dom_skin) in dom_skins:
286                 # first, find the corresponding screen element
287                 skin = dom_skin.childNodes[0] 
288                 for x in elementsWithTag(skin.childNodes, "screen"):
289                         if x.getAttribute('name') == name:
290                                 return x, path
291         return None, None
292
293 def readSkin(screen, skin, names, desktop):
294         if not isinstance(names, list):
295                 names = [names]
296
297         name = "<embedded-in-'%s'>" % screen.__class__.__name__
298
299         # try all skins, first existing one have priority
300         for n in names:
301                 myscreen, path = lookupScreen(n)
302                 if myscreen is not None:
303                         # use this name for debug output
304                         name = n
305                         break
306
307         # otherwise try embedded skin
308         myscreen = myscreen or getattr(screen, "parsedSkin", None)
309
310         # try uncompiled embedded skin
311         if myscreen is None and getattr(screen, "skin", None):
312                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
313
314         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
315
316         screen.skinAttributes = [ ]
317         
318         skin_path_prefix = getattr(screen, "skin_path", path)
319
320         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
321         
322         screen.additionalWidgets = [ ]
323         screen.renderer = [ ]
324         
325         visited_components = set()
326         
327         # now walk all widgets
328         for widget in elementsWithTag(myscreen.childNodes, "widget"):
329                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
330                 # widgets (source->renderer).
331
332                 wname = widget.getAttribute('name')
333                 wsource = widget.getAttribute('source')
334                 
335
336                 if wname is None and wsource is None:
337                         print "widget has no name and no source!"
338                         continue
339                 
340                 if wname:
341                         visited_components.add(wname)
342
343                         # get corresponding 'gui' object
344                         try:
345                                 attributes = screen[wname].skinAttributes = [ ]
346                         except:
347                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
348
349 #                       assert screen[wname] is not Source
350
351                         # and collect attributes for this
352                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
353                 elif wsource:
354                         # get corresponding source
355
356                         while True: # until we found a non-obsolete source
357
358                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
359                                 # for example to reference a parent, global or session-global screen.
360                                 scr = screen
361
362                                 # resolve all path components
363                                 path = wsource.split('.')
364                                 while len(path) > 1:
365                                         scr = screen.getRelatedScreen(path[0])
366                                         if scr is None:
367                                                 print wsource
368                                                 print name
369                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
370                                         path = path[1:]
371
372                                 # resolve the source.
373                                 source = scr.get(path[0])
374                                 if isinstance(source, ObsoleteSource):
375                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
376                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
377                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
378                                         if source.description:
379                                                 print source.description
380
381                                         wsource = source.new_source
382                                 else:
383                                         # otherwise, use that source.
384                                         break
385
386                         if source is None:
387                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
388                         
389                         wrender = widget.getAttribute('render')
390                         
391                         if not wrender:
392                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
393                         
394                         for converter in elementsWithTag(widget.childNodes, "convert"):
395                                 ctype = converter.getAttribute('type')
396                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
397                                 parms = mergeText(converter.childNodes).strip()
398                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
399                                 
400                                 c = None
401                                 
402                                 for i in source.downstream_elements:
403                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
404                                                 c = i
405
406                                 if c is None:
407                                         print "allocating new converter!"
408                                         c = converter_class(parms)
409                                         c.connect(source)
410                                 else:
411                                         print "reused converter!"
412         
413                                 source = c
414                         
415                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
416                         
417                         renderer = renderer_class() # instantiate renderer
418                         
419                         renderer.connect(source) # connect to source
420                         attributes = renderer.skinAttributes = [ ]
421                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
422                         
423                         screen.renderer.append(renderer)
424
425         from Components.GUIComponent import GUIComponent
426         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
427         
428         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
429
430         # now walk additional objects
431         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
432                 if widget.tagName == "applet":
433                         codeText = mergeText(widget.childNodes).strip()
434                         type = widget.getAttribute('type')
435
436                         code = compile(codeText, "skin applet", "exec")
437                         
438                         if type == "onLayoutFinish":
439                                 screen.onLayoutFinish.append(code)
440                         else:
441                                 raise SkinError("applet type '%s' unknown!" % type)
442                         
443                         continue
444                 
445                 class additionalWidget:
446                         pass
447                 
448                 w = additionalWidget()
449                 
450                 if widget.tagName == "eLabel":
451                         w.widget = eLabel
452                 elif widget.tagName == "ePixmap":
453                         w.widget = ePixmap
454                 else:
455                         raise SkinError("unsupported stuff : %s" % widget.tagName)
456                 
457                 w.skinAttributes = [ ]
458                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
459                 
460                 # applyAttributes(guiObject, widget, desktop)
461                 # guiObject.thisown = 0
462                 screen.additionalWidgets.append(w)