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