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