delete generated file libopen.so.0.0 on 'make clean'
[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         cached = False
110         option = path.find("#")
111         if option != -1:
112                 options = path[option+1:].split(',')
113                 path = path[:option]
114                 cached = "cached" in options
115         ptr = LoadPixmap(path, desktop, cached)
116         if ptr is None:
117                 raise SkinError("pixmap file %s not found!" % (path))
118         return ptr
119
120 def applySingleAttribute(guiObject, desktop, attrib, value):
121         # and set attributes
122         try:
123                 if attrib == 'position':
124                         guiObject.move(parsePosition(value))
125                 elif attrib == 'size':
126                         guiObject.resize(parseSize(value))
127                 elif attrib == 'title':
128                         guiObject.setTitle(_(value))
129                 elif attrib == 'text':
130                         guiObject.setText(_(value))
131                 elif attrib == 'font':
132                         guiObject.setFont(parseFont(value))
133                 elif attrib == 'zPosition':
134                         guiObject.setZPosition(int(value))
135                 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
136                         ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
137                         if attrib == "pixmap":
138                                 guiObject.setPixmap(ptr)
139                         elif attrib == "backgroundPixmap":
140                                 guiObject.setBackgroundPicture(ptr)
141                         elif attrib == "selectionPixmap":
142                                 guiObject.setSelectionPicture(ptr)
143                         # guiObject.setPixmapFromFile(value)
144                 elif attrib == "alphatest": # used by ePixmap
145                         guiObject.setAlphatest(
146                                 { "on": 1,
147                                   "off": 0,
148                                   "blend": 2,
149                                 }[value])
150                 elif attrib == "orientation": # used by eSlider
151                         try:
152                                 guiObject.setOrientation(
153                                         { "orVertical": guiObject.orVertical,
154                                                 "orHorizontal": guiObject.orHorizontal
155                                         }[value])
156                         except KeyError:
157                                 print "oprientation must be either orVertical or orHorizontal!"
158                 elif attrib == "valign":
159                         try:
160                                 guiObject.setVAlign(
161                                         { "top": guiObject.alignTop,
162                                                 "center": guiObject.alignCenter,
163                                                 "bottom": guiObject.alignBottom
164                                         }[value])
165                         except KeyError:
166                                 print "valign must be either top, center or bottom!"
167                 elif attrib == "halign":
168                         try:
169                                 guiObject.setHAlign(
170                                         { "left": guiObject.alignLeft,
171                                                 "center": guiObject.alignCenter,
172                                                 "right": guiObject.alignRight,
173                                                 "block": guiObject.alignBlock
174                                         }[value])
175                         except KeyError:
176                                 print "halign must be either left, center, right or block!"
177                 elif attrib == "flags":
178                         flags = value.split(',')
179                         for f in flags:
180                                 try:
181                                         fv = eWindow.__dict__[f]
182                                         guiObject.setFlag(fv)
183                                 except KeyError:
184                                         print "illegal flag %s!" % f
185                 elif attrib == "backgroundColor":
186                         guiObject.setBackgroundColor(parseColor(value))
187                 elif attrib == "backgroundColorSelected":
188                         guiObject.setBackgroundColorSelected(parseColor(value))
189                 elif attrib == "foregroundColor":
190                         guiObject.setForegroundColor(parseColor(value))
191                 elif attrib == "foregroundColorSelected":
192                         guiObject.setForegroundColorSelected(parseColor(value))
193                 elif attrib == "shadowColor":
194                         guiObject.setShadowColor(parseColor(value))
195                 elif attrib == "selectionDisabled":
196                         guiObject.setSelectionEnable(0)
197                 elif attrib == "transparent":
198                         guiObject.setTransparent(int(value))
199                 elif attrib == "borderColor":
200                         guiObject.setBorderColor(parseColor(value))
201                 elif attrib == "borderWidth":
202                         guiObject.setBorderWidth(int(value))
203                 elif attrib == "scrollbarMode":
204                         guiObject.setScrollbarMode(
205                                 { "showOnDemand": guiObject.showOnDemand,
206                                         "showAlways": guiObject.showAlways,
207                                         "showNever": guiObject.showNever
208                                 }[value])
209                 elif attrib == "enableWrapAround":
210                         guiObject.setWrapAround(True)
211                 elif attrib == "pointer" or attrib == "seek_pointer":
212                         (name, pos) = value.split(':')
213                         pos = parsePosition(pos)
214                         ptr = loadPixmap(name, desktop)
215                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
216                 elif attrib == 'shadowOffset':
217                         guiObject.setShadowOffset(parsePosition(value))
218                 elif attrib == 'noWrap':
219                         guiObject.setNoWrap(1)
220                 else:
221                         raise SkinError("unsupported attribute " + attrib + "=" + value)
222         except int:
223 # AttributeError:
224                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
225
226 def applyAllAttributes(guiObject, desktop, attributes):
227         for (attrib, value) in attributes:
228                 applySingleAttribute(guiObject, desktop, attrib, value)
229
230 def loadSingleSkinData(desktop, dom_skin, path_prefix):
231         """loads skin data like colors, windowstyle etc."""
232         
233         skin = dom_skin.childNodes[0]
234         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
235
236         for c in elementsWithTag(skin.childNodes, "output"):
237                 id = int(c.getAttribute("id") or "0")
238                 if id == 0: # framebuffer
239                         for res in elementsWithTag(c.childNodes, "resolution"):
240                                 xres = int(res.getAttribute("xres" or "720"))
241                                 yres = int(res.getAttribute("yres" or "576"))
242                                 bpp = int(res.getAttribute("bpp" or "32"))
243
244                                 from enigma import gFBDC
245                                 i = gFBDC.getInstance()
246                                 i.setResolution(xres, yres)
247
248                                 if bpp != 32:
249                                         # load palette (not yet implemented)
250                                         pass
251
252         for c in elementsWithTag(skin.childNodes, "colors"):
253                 for color in elementsWithTag(c.childNodes, "color"):
254                         name = str(color.getAttribute("name"))
255                         color = str(color.getAttribute("value"))
256                         
257                         if not len(color):
258                                 raise ("need color and name, got %s %s" % (name, color))
259                                 
260                         colorNames[name] = parseColor(color)
261         
262         for c in elementsWithTag(skin.childNodes, "fonts"):
263                 for font in elementsWithTag(c.childNodes, "font"):
264                         filename = str(font.getAttribute("filename") or "<NONAME>")
265                         name = str(font.getAttribute("name") or "Regular")
266                         scale = int(font.getAttribute("scale") or "100")
267                         is_replacement = font.getAttribute("replacement") != ""
268                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
269         
270         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
271                 style = eWindowStyleSkinned()
272                 id = int(windowstyle.getAttribute("id") or "0")
273                 
274                 # defaults
275                 font = gFont("Regular", 20)
276                 offset = eSize(20, 5)
277                 
278                 for title in elementsWithTag(windowstyle.childNodes, "title"):
279                         offset = parseSize(title.getAttribute("offset"))
280                         font = parseFont(str(title.getAttribute("font")))
281
282                 style.setTitleFont(font);
283                 style.setTitleOffset(offset)
284                 
285                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
286                         bsName = str(borderset.getAttribute("name"))
287                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
288                                 bpName = str(pixmap.getAttribute("pos"))
289                                 filename = str(pixmap.getAttribute("filename"))
290                                 
291                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
292                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
293
294                 for color in elementsWithTag(windowstyle.childNodes, "color"):
295                         type = str(color.getAttribute("name"))
296                         color = parseColor(color.getAttribute("color"))
297                         
298                         try:
299                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
300                         except:
301                                 raise ("Unknown color %s" % (type))
302                         
303                 x = eWindowStyleManager.getInstance()
304                 x.setStyle(id, style)
305
306 def loadSkinData(desktop):
307         skins = dom_skins[:]
308         skins.reverse()
309         for (path, dom_skin) in skins:
310                 loadSingleSkinData(desktop, dom_skin, path)
311
312 def lookupScreen(name):
313         for (path, dom_skin) in dom_skins:
314                 # first, find the corresponding screen element
315                 skin = dom_skin.childNodes[0] 
316                 for x in elementsWithTag(skin.childNodes, "screen"):
317                         if x.getAttribute('name') == name:
318                                 return x, path
319         return None, None
320
321 def readSkin(screen, skin, names, desktop):
322         if not isinstance(names, list):
323                 names = [names]
324
325         name = "<embedded-in-'%s'>" % screen.__class__.__name__
326
327         # try all skins, first existing one have priority
328         for n in names:
329                 myscreen, path = lookupScreen(n)
330                 if myscreen is not None:
331                         # use this name for debug output
332                         name = n
333                         break
334
335         # otherwise try embedded skin
336         myscreen = myscreen or getattr(screen, "parsedSkin", None)
337
338         # try uncompiled embedded skin
339         if myscreen is None and getattr(screen, "skin", None):
340                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
341
342         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
343
344         screen.skinAttributes = [ ]
345         
346         skin_path_prefix = getattr(screen, "skin_path", path)
347
348         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
349         
350         screen.additionalWidgets = [ ]
351         screen.renderer = [ ]
352         
353         visited_components = set()
354         
355         # now walk all widgets
356         for widget in elementsWithTag(myscreen.childNodes, "widget"):
357                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
358                 # widgets (source->renderer).
359
360                 wname = widget.getAttribute('name')
361                 wsource = widget.getAttribute('source')
362                 
363
364                 if wname is None and wsource is None:
365                         print "widget has no name and no source!"
366                         continue
367                 
368                 if wname:
369                         visited_components.add(wname)
370
371                         # get corresponding 'gui' object
372                         try:
373                                 attributes = screen[wname].skinAttributes = [ ]
374                         except:
375                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
376
377 #                       assert screen[wname] is not Source
378
379                         # and collect attributes for this
380                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
381                 elif wsource:
382                         # get corresponding source
383
384                         while True: # until we found a non-obsolete source
385
386                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
387                                 # for example to reference a parent, global or session-global screen.
388                                 scr = screen
389
390                                 # resolve all path components
391                                 path = wsource.split('.')
392                                 while len(path) > 1:
393                                         scr = screen.getRelatedScreen(path[0])
394                                         if scr is None:
395                                                 print wsource
396                                                 print name
397                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
398                                         path = path[1:]
399
400                                 # resolve the source.
401                                 source = scr.get(path[0])
402                                 if isinstance(source, ObsoleteSource):
403                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
404                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
405                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
406                                         if source.description:
407                                                 print source.description
408
409                                         wsource = source.new_source
410                                 else:
411                                         # otherwise, use that source.
412                                         break
413
414                         if source is None:
415                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
416                         
417                         wrender = widget.getAttribute('render')
418                         
419                         if not wrender:
420                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
421                         
422                         for converter in elementsWithTag(widget.childNodes, "convert"):
423                                 ctype = converter.getAttribute('type')
424                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
425                                 parms = mergeText(converter.childNodes).strip()
426                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
427                                 
428                                 c = None
429                                 
430                                 for i in source.downstream_elements:
431                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
432                                                 c = i
433
434                                 if c is None:
435                                         print "allocating new converter!"
436                                         c = converter_class(parms)
437                                         c.connect(source)
438                                 else:
439                                         print "reused converter!"
440         
441                                 source = c
442                         
443                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
444                         
445                         renderer = renderer_class() # instantiate renderer
446                         
447                         renderer.connect(source) # connect to source
448                         attributes = renderer.skinAttributes = [ ]
449                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
450                         
451                         screen.renderer.append(renderer)
452
453         from Components.GUIComponent import GUIComponent
454         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
455         
456         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
457
458         # now walk additional objects
459         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
460                 if widget.tagName == "applet":
461                         codeText = mergeText(widget.childNodes).strip()
462                         type = widget.getAttribute('type')
463
464                         code = compile(codeText, "skin applet", "exec")
465                         
466                         if type == "onLayoutFinish":
467                                 screen.onLayoutFinish.append(code)
468                         else:
469                                 raise SkinError("applet type '%s' unknown!" % type)
470                         
471                         continue
472                 
473                 class additionalWidget:
474                         pass
475                 
476                 w = additionalWidget()
477                 
478                 if widget.tagName == "eLabel":
479                         w.widget = eLabel
480                 elif widget.tagName == "ePixmap":
481                         w.widget = ePixmap
482                 else:
483                         raise SkinError("unsupported stuff : %s" % widget.tagName)
484                 
485                 w.skinAttributes = [ ]
486                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
487                 
488                 # applyAttributes(guiObject, widget, desktop)
489                 # guiObject.thisown = 0
490                 screen.additionalWidgets.append(w)