add globals,session globals
[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, name, desktop):
293         if not isinstance(name, list):
294                 name = [name]
295
296         # try all skins, first existing one have priority
297         for n in name:
298                 myscreen, path = lookupScreen(n)
299                 if myscreen is not None:
300                         # use this name for debug output
301                         name = n
302                         break
303
304         # otherwise try embedded skin
305         myscreen = myscreen or getattr(screen, "parsedSkin", None)
306
307         # try uncompiled embedded skin
308         if myscreen is None and getattr(screen, "skin", None):
309                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
310
311         assert myscreen is not None, "no skin for screen '" + repr(name) + "' found!"
312
313         screen.skinAttributes = [ ]
314         
315         skin_path_prefix = getattr(screen, "skin_path", path)
316
317         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
318         
319         screen.additionalWidgets = [ ]
320         screen.renderer = [ ]
321         
322         visited_components = set()
323         
324         # now walk all widgets
325         for widget in elementsWithTag(myscreen.childNodes, "widget"):
326                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
327                 # widgets (source->renderer).
328
329                 wname = widget.getAttribute('name')
330                 wsource = widget.getAttribute('source')
331                 
332
333                 if wname is None and wsource is None:
334                         print "widget has no name and no source!"
335                         continue
336                 
337                 if wname:
338                         visited_components.add(wname)
339
340                         # get corresponding 'gui' object
341                         try:
342                                 attributes = screen[wname].skinAttributes = [ ]
343                         except:
344                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
345
346 #                       assert screen[wname] is not Source
347
348                         # and collect attributes for this
349                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
350                 elif wsource:
351                         # get corresponding source
352
353                         while True: # until we found a non-obsolete source
354
355                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
356                                 # for example to reference a parent, global or session-global screen.
357                                 scr = screen
358
359                                 # resolve all path components
360                                 path = wsource.split('.')
361                                 while len(path) > 1:
362                                         scr = screen.getRelatedScreen(path[0])
363                                         if scr is None:
364                                                 print wsource
365                                                 print name
366                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
367                                         path = path[1:]
368
369                                 # resolve the source.
370                                 source = scr.get(path[0])
371                                 if isinstance(source, ObsoleteSource):
372                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
373                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
374                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
375                                         if source.description:
376                                                 print source.description
377
378                                         wsource = source.new_source
379                                 else:
380                                         # otherwise, use that source.
381                                         break
382
383                         if source is None:
384                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
385                         
386                         wrender = widget.getAttribute('render')
387                         
388                         if not wrender:
389                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
390                         
391                         for converter in elementsWithTag(widget.childNodes, "convert"):
392                                 ctype = converter.getAttribute('type')
393                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
394                                 parms = mergeText(converter.childNodes).strip()
395                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
396                                 
397                                 c = None
398                                 
399                                 for i in source.downstream_elements:
400                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
401                                                 c = i
402
403                                 if c is None:
404                                         print "allocating new converter!"
405                                         c = converter_class(parms)
406                                         c.connect(source)
407                                 else:
408                                         print "reused converter!"
409         
410                                 source = c
411                         
412                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
413                         
414                         renderer = renderer_class() # instantiate renderer
415                         
416                         renderer.connect(source) # connect to source
417                         attributes = renderer.skinAttributes = [ ]
418                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
419                         
420                         screen.renderer.append(renderer)
421
422         from Components.GUIComponent import GUIComponent
423         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
424         
425         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
426
427         # now walk additional objects
428         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
429                 if widget.tagName == "applet":
430                         codeText = mergeText(widget.childNodes).strip()
431                         type = widget.getAttribute('type')
432
433                         code = compile(codeText, "skin applet", "exec")
434                         
435                         if type == "onLayoutFinish":
436                                 screen.onLayoutFinish.append(code)
437                         else:
438                                 raise SkinError("applet type '%s' unknown!" % type)
439                         
440                         continue
441                 
442                 class additionalWidget:
443                         pass
444                 
445                 w = additionalWidget()
446                 
447                 if widget.tagName == "eLabel":
448                         w.widget = eLabel
449                 elif widget.tagName == "ePixmap":
450                         w.widget = ePixmap
451                 else:
452                         raise SkinError("unsupported stuff : %s" % widget.tagName)
453                 
454                 w.skinAttributes = [ ]
455                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
456                 
457                 # applyAttributes(guiObject, widget, desktop)
458                 # guiObject.thisown = 0
459                 screen.additionalWidgets.append(w)