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