replace old screwed stone skin with Screwed Stone II (thx to nemesis)
[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         if not isinstance(name, list):
290                 name = [name]
291
292         # try all skins, first existing one have priority
293         for n in name:
294                 myscreen, path = lookupScreen(n)
295                 if myscreen is not None:
296                         break
297
298         # otherwise try embedded skin
299         myscreen = myscreen or getattr(screen, "parsedSkin", None)
300         
301         # try uncompiled embedded skin
302         if myscreen is None and getattr(screen, "skin", None):
303                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
304         
305         assert myscreen is not None, "no skin for screen '" + repr(name) + "' found!"
306
307         screen.skinAttributes = [ ]
308         
309         skin_path_prefix = getattr(screen, "skin_path", path)
310
311         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
312         
313         screen.additionalWidgets = [ ]
314         screen.renderer = [ ]
315         
316         visited_components = set()
317         
318         # now walk all widgets
319         for widget in elementsWithTag(myscreen.childNodes, "widget"):
320                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
321                 # widgets (source->renderer).
322
323                 wname = widget.getAttribute('name')
324                 wsource = widget.getAttribute('source')
325                 
326
327                 if wname is None and wsource is None:
328                         print "widget has no name and no source!"
329                         continue
330                 
331                 if wname:
332                         visited_components.add(wname)
333
334                         # get corresponding 'gui' object
335                         try:
336                                 attributes = screen[wname].skinAttributes = [ ]
337                         except:
338                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
339
340 #                       assert screen[wname] is not Source
341
342                         # and collect attributes for this
343                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
344                 elif wsource:
345                         # get corresponding source
346                         source = screen.get(wsource)
347                         if source is None:
348                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
349                         
350                         wrender = widget.getAttribute('render')
351                         
352                         if not wrender:
353                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
354                         
355                         for converter in elementsWithTag(widget.childNodes, "convert"):
356                                 ctype = converter.getAttribute('type')
357                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
358                                 parms = mergeText(converter.childNodes).strip()
359                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
360                                 
361                                 c = None
362                                 
363                                 for i in source.downstream_elements:
364                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
365                                                 c = i
366
367                                 if c is None:
368                                         print "allocating new converter!"
369                                         c = converter_class(parms)
370                                         c.connect(source)
371                                 else:
372                                         print "reused conveter!"
373         
374                                 source = c
375                         
376                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
377                         
378                         renderer = renderer_class() # instantiate renderer
379                         
380                         renderer.connect(source) # connect to source
381                         attributes = renderer.skinAttributes = [ ]
382                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
383                         
384                         screen.renderer.append(renderer)
385
386         from Components.GUIComponent import GUIComponent
387         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
388         
389         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
390
391         # now walk additional objects
392         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
393                 if widget.tagName == "applet":
394                         codeText = mergeText(widget.childNodes).strip()
395                         type = widget.getAttribute('type')
396
397                         code = compile(codeText, "skin applet", "exec")
398                         
399                         if type == "onLayoutFinish":
400                                 screen.onLayoutFinish.append(code)
401                         else:
402                                 raise SkinError("applet type '%s' unknown!" % type)
403                         
404                         continue
405                 
406                 class additionalWidget:
407                         pass
408                 
409                 w = additionalWidget()
410                 
411                 if widget.tagName == "eLabel":
412                         w.widget = eLabel
413                 elif widget.tagName == "ePixmap":
414                         w.widget = ePixmap
415                 else:
416                         raise SkinError("unsupported stuff : %s" % widget.tagName)
417                 
418                 w.skinAttributes = [ ]
419                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
420                 
421                 # applyAttributes(guiObject, widget, desktop)
422                 # guiObject.thisown = 0
423                 screen.additionalWidgets.append(w)