reset config.skin.primary_skin to default skin on skin load error
[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         config.skin.primary_skin.value = 'skin.xml'
60         loadSkin('skin.xml')
61
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 SkinError("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 SkinError("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 == "backgroundColorSelected":
174                         guiObject.setBackgroundColorSelected(parseColor(value))
175                 elif attrib == "foregroundColor":
176                         guiObject.setForegroundColor(parseColor(value))
177                 elif attrib == "foregroundColorSelected":
178                         guiObject.setForegroundColorSelected(parseColor(value))
179                 elif attrib == "shadowColor":
180                         guiObject.setShadowColor(parseColor(value))
181                 elif attrib == "selectionDisabled":
182                         guiObject.setSelectionEnable(0)
183                 elif attrib == "transparent":
184                         guiObject.setTransparent(int(value))
185                 elif attrib == "borderColor":
186                         guiObject.setBorderColor(parseColor(value))
187                 elif attrib == "borderWidth":
188                         guiObject.setBorderWidth(int(value))
189                 elif attrib == "scrollbarMode":
190                         guiObject.setScrollbarMode(
191                                 { "showOnDemand": guiObject.showOnDemand,
192                                         "showAlways": guiObject.showAlways,
193                                         "showNever": guiObject.showNever
194                                 }[value])
195                 elif attrib == "enableWrapAround":
196                         guiObject.setWrapAround(True)
197                 elif attrib == "pointer" or attrib == "seek_pointer":
198                         (name, pos) = value.split(':')
199                         pos = parsePosition(pos)
200                         ptr = loadPixmap(name)
201                         desktop.makeCompatiblePixmap(ptr)
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))
279                                 
280                                 # adapt palette
281                                 desktop.makeCompatiblePixmap(png)
282                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
283
284                 for color in elementsWithTag(windowstyle.childNodes, "color"):
285                         type = str(color.getAttribute("name"))
286                         color = parseColor(color.getAttribute("color"))
287                         
288                         try:
289                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
290                         except:
291                                 raise ("Unknown color %s" % (type))
292                         
293                 x = eWindowStyleManager.getInstance()
294                 x.setStyle(id, style)
295
296 def loadSkinData(desktop):
297         skins = dom_skins[:]
298         skins.reverse()
299         for (path, dom_skin) in skins:
300                 loadSingleSkinData(desktop, dom_skin, path)
301
302 def lookupScreen(name):
303         for (path, dom_skin) in dom_skins:
304                 # first, find the corresponding screen element
305                 skin = dom_skin.childNodes[0] 
306                 for x in elementsWithTag(skin.childNodes, "screen"):
307                         if x.getAttribute('name') == name:
308                                 return x, path
309         return None, None
310
311 def readSkin(screen, skin, names, desktop):
312         if not isinstance(names, list):
313                 names = [names]
314
315         name = "<embedded-in-'%s'>" % screen.__class__.__name__
316
317         # try all skins, first existing one have priority
318         for n in names:
319                 myscreen, path = lookupScreen(n)
320                 if myscreen is not None:
321                         # use this name for debug output
322                         name = n
323                         break
324
325         # otherwise try embedded skin
326         myscreen = myscreen or getattr(screen, "parsedSkin", None)
327
328         # try uncompiled embedded skin
329         if myscreen is None and getattr(screen, "skin", None):
330                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
331
332         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
333
334         screen.skinAttributes = [ ]
335         
336         skin_path_prefix = getattr(screen, "skin_path", path)
337
338         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
339         
340         screen.additionalWidgets = [ ]
341         screen.renderer = [ ]
342         
343         visited_components = set()
344         
345         # now walk all widgets
346         for widget in elementsWithTag(myscreen.childNodes, "widget"):
347                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
348                 # widgets (source->renderer).
349
350                 wname = widget.getAttribute('name')
351                 wsource = widget.getAttribute('source')
352                 
353
354                 if wname is None and wsource is None:
355                         print "widget has no name and no source!"
356                         continue
357                 
358                 if wname:
359                         visited_components.add(wname)
360
361                         # get corresponding 'gui' object
362                         try:
363                                 attributes = screen[wname].skinAttributes = [ ]
364                         except:
365                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
366
367 #                       assert screen[wname] is not Source
368
369                         # and collect attributes for this
370                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
371                 elif wsource:
372                         # get corresponding source
373
374                         while True: # until we found a non-obsolete source
375
376                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
377                                 # for example to reference a parent, global or session-global screen.
378                                 scr = screen
379
380                                 # resolve all path components
381                                 path = wsource.split('.')
382                                 while len(path) > 1:
383                                         scr = screen.getRelatedScreen(path[0])
384                                         if scr is None:
385                                                 print wsource
386                                                 print name
387                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
388                                         path = path[1:]
389
390                                 # resolve the source.
391                                 source = scr.get(path[0])
392                                 if isinstance(source, ObsoleteSource):
393                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
394                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
395                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
396                                         if source.description:
397                                                 print source.description
398
399                                         wsource = source.new_source
400                                 else:
401                                         # otherwise, use that source.
402                                         break
403
404                         if source is None:
405                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
406                         
407                         wrender = widget.getAttribute('render')
408                         
409                         if not wrender:
410                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
411                         
412                         for converter in elementsWithTag(widget.childNodes, "convert"):
413                                 ctype = converter.getAttribute('type')
414                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
415                                 parms = mergeText(converter.childNodes).strip()
416                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
417                                 
418                                 c = None
419                                 
420                                 for i in source.downstream_elements:
421                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
422                                                 c = i
423
424                                 if c is None:
425                                         print "allocating new converter!"
426                                         c = converter_class(parms)
427                                         c.connect(source)
428                                 else:
429                                         print "reused converter!"
430         
431                                 source = c
432                         
433                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
434                         
435                         renderer = renderer_class() # instantiate renderer
436                         
437                         renderer.connect(source) # connect to source
438                         attributes = renderer.skinAttributes = [ ]
439                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
440                         
441                         screen.renderer.append(renderer)
442
443         from Components.GUIComponent import GUIComponent
444         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
445         
446         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
447
448         # now walk additional objects
449         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
450                 if widget.tagName == "applet":
451                         codeText = mergeText(widget.childNodes).strip()
452                         type = widget.getAttribute('type')
453
454                         code = compile(codeText, "skin applet", "exec")
455                         
456                         if type == "onLayoutFinish":
457                                 screen.onLayoutFinish.append(code)
458                         else:
459                                 raise SkinError("applet type '%s' unknown!" % type)
460                         
461                         continue
462                 
463                 class additionalWidget:
464                         pass
465                 
466                 w = additionalWidget()
467                 
468                 if widget.tagName == "eLabel":
469                         w.widget = eLabel
470                 elif widget.tagName == "ePixmap":
471                         w.widget = ePixmap
472                 else:
473                         raise SkinError("unsupported stuff : %s" % widget.tagName)
474                 
475                 w.skinAttributes = [ ]
476                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
477                 
478                 # applyAttributes(guiObject, widget, desktop)
479                 # guiObject.thisown = 0
480                 screen.additionalWidgets.append(w)