fix frontend_source,
[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 Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
10 from Tools.Import import my_import
11
12 from Tools.XMLTools import elementsWithTag, mergeText
13
14 colorNames = dict()
15
16 def dump(x, i=0):
17         print " " * i + str(x)
18         try:
19                 for n in x.childNodes:
20                         dump(n, i + 1)
21         except:
22                 None
23
24 class SkinError(Exception):
25         def __init__(self, message):
26                 self.message = message
27
28         def __str__(self):
29                 return self.message
30
31 dom_skins = [ ]
32
33 def loadSkin(name):
34         # read the skin
35         filename = resolveFilename(SCOPE_SKIN, name)
36         mpath = path.dirname(filename) + "/"
37         dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
38
39 # we do our best to always select the "right" value
40 # skins are loaded in order of priority: skin with
41 # highest priority is loaded last, usually the user-provided
42 # skin.
43
44 # currently, loadSingleSkinData (colors, bordersets etc.)
45 # are applied one-after-each, in order of ascending priority.
46 # the dom_skin will keep all screens in descending priority,
47 # so the first screen found will be used.
48
49 # example: loadSkin("nemesis_greenline/skin.xml")
50 config.skin = ConfigSubsection()
51 config.skin.primary_skin = ConfigText(default = "skin.xml")
52
53 try:
54         loadSkin(config.skin.primary_skin.value)
55 except (SkinError, IOError, AssertionError), err:
56         print "SKIN ERROR:", err
57         print "defaulting to standard skin..."
58         loadSkin('skin.xml')
59 loadSkin('skin_default.xml')
60
61 def parsePosition(str):
62         x, y = str.split(',')
63         return ePoint(int(x), int(y))
64
65 def parseSize(str):
66         x, y = str.split(',')
67         return eSize(int(x), int(y))
68
69 def parseFont(str):
70         name, size = str.split(';')
71         return gFont(name, int(size))
72
73 def parseColor(str):
74         if str[0] != '#':
75                 try:
76                         return colorNames[str]
77                 except:
78                         raise ("color '%s' must be #aarrggbb or valid named color" % (str))
79         return gRGB(int(str[1:], 0x10))
80
81 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
82         # walk all attributes
83         for p in range(node.attributes.length):
84                 a = node.attributes.item(p)
85                 
86                 # convert to string (was: unicode)
87                 attrib = str(a.name)
88                 # TODO: localization? as in e1?
89                 value = a.value.encode("utf-8")
90                 
91                 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
92                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
93                 
94                 if attrib not in ignore:
95                         skinAttributes.append((attrib, value))
96
97 def loadPixmap(path):
98         ptr = loadPNG(path)
99         if ptr is None:
100                 raise "pixmap file %s not found!" % (path)
101         return ptr
102
103 def applySingleAttribute(guiObject, desktop, attrib, value):
104         # and set attributes
105         try:
106                 if attrib == 'position':
107                         guiObject.move(parsePosition(value))
108                 elif attrib == 'size':
109                         guiObject.resize(parseSize(value))
110                 elif attrib == 'title':
111                         guiObject.setTitle(_(value))
112                 elif attrib == 'text':
113                         guiObject.setText(_(value))
114                 elif attrib == 'font':
115                         guiObject.setFont(parseFont(value))
116                 elif attrib == 'zPosition':
117                         guiObject.setZPosition(int(value))
118                 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
119                         ptr = loadPixmap(value) # this should already have been filename-resolved.
120                         desktop.makeCompatiblePixmap(ptr)
121                         if attrib == "pixmap":
122                                 guiObject.setPixmap(ptr)
123                         elif attrib == "backgroundPixmap":
124                                 guiObject.setBackgroundPicture(ptr)
125                         elif attrib == "selectionPixmap":
126                                 guiObject.setSelectionPicture(ptr)
127                         # guiObject.setPixmapFromFile(value)
128                 elif attrib == "alphatest": # used by ePixmap
129                         guiObject.setAlphatest(
130                                 { "on": True,
131                                   "off": False
132                                 }[value])
133                 elif attrib == "orientation": # used by eSlider
134                         try:
135                                 guiObject.setOrientation(
136                                         { "orVertical": guiObject.orVertical,
137                                                 "orHorizontal": guiObject.orHorizontal
138                                         }[value])
139                         except KeyError:
140                                 print "oprientation must be either orVertical or orHorizontal!"
141                 elif attrib == "valign":
142                         try:
143                                 guiObject.setVAlign(
144                                         { "top": guiObject.alignTop,
145                                                 "center": guiObject.alignCenter,
146                                                 "bottom": guiObject.alignBottom
147                                         }[value])
148                         except KeyError:
149                                 print "valign must be either top, center or bottom!"
150                 elif attrib == "halign":
151                         try:
152                                 guiObject.setHAlign(
153                                         { "left": guiObject.alignLeft,
154                                                 "center": guiObject.alignCenter,
155                                                 "right": guiObject.alignRight,
156                                                 "block": guiObject.alignBlock
157                                         }[value])
158                         except KeyError:
159                                 print "halign must be either left, center, right or block!"
160                 elif attrib == "flags":
161                         flags = value.split(',')
162                         for f in flags:
163                                 try:
164                                         fv = eWindow.__dict__[f]
165                                         guiObject.setFlag(fv)
166                                 except KeyError:
167                                         print "illegal flag %s!" % f
168                 elif attrib == "backgroundColor":
169                         guiObject.setBackgroundColor(parseColor(value))
170                 elif attrib == "foregroundColor":
171                         guiObject.setForegroundColor(parseColor(value))
172                 elif attrib == "shadowColor":
173                         guiObject.setShadowColor(parseColor(value))
174                 elif attrib == "selectionDisabled":
175                         guiObject.setSelectionEnable(0)
176                 elif attrib == "transparent":
177                         guiObject.setTransparent(int(value))
178                 elif attrib == "borderColor":
179                         guiObject.setBorderColor(parseColor(value))
180                 elif attrib == "borderWidth":
181                         guiObject.setBorderWidth(int(value))
182                 elif attrib == "scrollbarMode":
183                         guiObject.setScrollbarMode(
184                                 { "showOnDemand": guiObject.showOnDemand,
185                                         "showAlways": guiObject.showAlways,
186                                         "showNever": guiObject.showNever
187                                 }[value])
188                 elif attrib == "enableWrapAround":
189                         guiObject.setWrapAround(True)
190                 elif attrib == "pointer" or attrib == "seek_pointer":
191                         (name, pos) = value.split(':')
192                         pos = parsePosition(pos)
193                         ptr = loadPixmap(name)
194                         desktop.makeCompatiblePixmap(ptr)
195                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
196                 elif attrib == 'shadowOffset':
197                         guiObject.setShadowOffset(parsePosition(value))
198                 elif attrib == 'noWrap':
199                         guiObject.setNoWrap(1)
200                 else:
201                         raise "unsupported attribute " + attrib + "=" + value
202         except int:
203 # AttributeError:
204                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
205
206 def applyAllAttributes(guiObject, desktop, attributes):
207         for (attrib, value) in attributes:
208                 applySingleAttribute(guiObject, desktop, attrib, value)
209
210 def loadSingleSkinData(desktop, dom_skin, path_prefix):
211         """loads skin data like colors, windowstyle etc."""
212         
213         skin = dom_skin.childNodes[0]
214         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
215         
216         for c in elementsWithTag(skin.childNodes, "colors"):
217                 for color in elementsWithTag(c.childNodes, "color"):
218                         name = str(color.getAttribute("name"))
219                         color = str(color.getAttribute("value"))
220                         
221                         if not len(color):
222                                 raise ("need color and name, got %s %s" % (name, color))
223                                 
224                         colorNames[name] = parseColor(color)
225         
226         for c in elementsWithTag(skin.childNodes, "fonts"):
227                 for font in elementsWithTag(c.childNodes, "font"):
228                         filename = str(font.getAttribute("filename") or "<NONAME>")
229                         name = str(font.getAttribute("name") or "Regular")
230                         scale = int(font.getAttribute("scale") or "100")
231                         is_replacement = font.getAttribute("replacement") != ""
232                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
233         
234         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
235                 style = eWindowStyleSkinned()
236                 id = int(windowstyle.getAttribute("id") or "0")
237                 
238                 # defaults
239                 font = gFont("Regular", 20)
240                 offset = eSize(20, 5)
241                 
242                 for title in elementsWithTag(windowstyle.childNodes, "title"):
243                         offset = parseSize(title.getAttribute("offset"))
244                         font = parseFont(str(title.getAttribute("font")))
245
246                 style.setTitleFont(font);
247                 style.setTitleOffset(offset)
248                 
249                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
250                         bsName = str(borderset.getAttribute("name"))
251                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
252                                 bpName = str(pixmap.getAttribute("pos"))
253                                 filename = str(pixmap.getAttribute("filename"))
254                                 
255                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
256                                 
257                                 # adapt palette
258                                 desktop.makeCompatiblePixmap(png)
259                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
260
261                 for color in elementsWithTag(windowstyle.childNodes, "color"):
262                         type = str(color.getAttribute("name"))
263                         color = parseColor(color.getAttribute("color"))
264                         
265                         try:
266                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
267                         except:
268                                 raise ("Unknown color %s" % (type))
269                         
270                 x = eWindowStyleManager.getInstance()
271                 x.setStyle(id, style)
272
273 def loadSkinData(desktop):
274         skins = dom_skins[:]
275         skins.reverse()
276         for (path, dom_skin) in skins:
277                 loadSingleSkinData(desktop, dom_skin, path)
278
279 def lookupScreen(name):
280         for (path, dom_skin) in dom_skins:
281                 # first, find the corresponding screen element
282                 skin = dom_skin.childNodes[0] 
283                 for x in elementsWithTag(skin.childNodes, "screen"):
284                         if x.getAttribute('name') == name:
285                                 return x, path
286         return None, None
287
288 def readSkin(screen, skin, name, desktop):
289         
290         myscreen, path = lookupScreen(name)
291         
292         # otherwise try embedded skin
293         myscreen = myscreen or getattr(screen, "parsedSkin", None)
294         
295         # try uncompiled embedded skin
296         if myscreen is None and getattr(screen, "skin", None):
297                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
298         
299         assert myscreen is not None, "no skin for screen '" + name + "' found!"
300
301         screen.skinAttributes = [ ]
302         
303         skin_path_prefix = getattr(screen, "skin_path", path)
304
305         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
306         
307         screen.additionalWidgets = [ ]
308         screen.renderer = [ ]
309         
310         visited_components = set()
311         
312         # now walk all widgets
313         for widget in elementsWithTag(myscreen.childNodes, "widget"):
314                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
315                 # widgets (source->renderer).
316
317                 wname = widget.getAttribute('name')
318                 wsource = widget.getAttribute('source')
319                 
320
321                 if wname is None and wsource is None:
322                         print "widget has no name and no source!"
323                         continue
324                 
325                 if wname:
326                         visited_components.add(wname)
327
328                         # get corresponding 'gui' object
329                         try:
330                                 attributes = screen[wname].skinAttributes = [ ]
331                         except:
332                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
333
334 #                       assert screen[wname] is not Source
335
336                         # and collect attributes for this
337                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
338                 elif wsource:
339                         # get corresponding source
340                         source = screen.get(wsource)
341                         if source is None:
342                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
343                         
344                         wrender = widget.getAttribute('render')
345                         
346                         if not wrender:
347                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
348                         
349                         for converter in elementsWithTag(widget.childNodes, "convert"):
350                                 ctype = converter.getAttribute('type')
351                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
352                                 parms = mergeText(converter.childNodes).strip()
353                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
354                                 
355                                 c = None
356                                 
357                                 for i in source.downstream_elements:
358                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
359                                                 c = i
360
361                                 if c is None:
362                                         print "allocating new converter!"
363                                         c = converter_class(parms)
364                                         c.connect(source)
365                                 else:
366                                         print "reused conveter!"
367         
368                                 source = c
369                         
370                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
371                         
372                         renderer = renderer_class() # instantiate renderer
373                         
374                         renderer.connect(source) # connect to source
375                         attributes = renderer.skinAttributes = [ ]
376                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
377                         
378                         screen.renderer.append(renderer)
379
380         from Components.GUIComponent import GUIComponent
381         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
382         
383         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
384
385         # now walk additional objects
386         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
387                 if widget.tagName == "applet":
388                         codeText = mergeText(widget.childNodes).strip()
389                         type = widget.getAttribute('type')
390
391                         code = compile(codeText, "skin applet", "exec")
392                         
393                         if type == "onLayoutFinish":
394                                 screen.onLayoutFinish.append(code)
395                         else:
396                                 raise SkinError("applet type '%s' unknown!" % type)
397                         
398                         continue
399                 
400                 class additionalWidget:
401                         pass
402                 
403                 w = additionalWidget()
404                 
405                 if widget.tagName == "eLabel":
406                         w.widget = eLabel
407                 elif widget.tagName == "ePixmap":
408                         w.widget = ePixmap
409                 else:
410                         raise SkinError("unsupported stuff : %s" % widget.tagName)
411                 
412                 w.skinAttributes = [ ]
413                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
414                 
415                 # applyAttributes(guiObject, widget, desktop)
416                 # guiObject.thisown = 0
417                 screen.additionalWidgets.append(w)