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