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