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