Merge branch '219_negative_ac3_pcm_delay' into experimental
[enigma2.git] / skin.py
1 from Tools.Profile import profile
2 profile("LOAD:ElementTree")
3 import xml.etree.cElementTree
4 from os import path
5
6 profile("LOAD:enigma_skin")
7 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
8         addFont, gRGB, eWindowStyleSkinned
9 from Components.config import ConfigSubsection, ConfigText, config
10 from Components.Converter.Converter import Converter
11 from Components.Sources.Source import Source, ObsoleteSource
12 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS, SCOPE_CURRENT_SKIN, SCOPE_CONFIG, fileExists
13 from Tools.Import import my_import
14 from Tools.LoadPixmap import LoadPixmap
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.msg = message
29
30         def __str__(self):
31                 return "{%s}: %s" % (config.skin.primary_skin.value, self.msg)
32
33 dom_skins = [ ]
34
35 def loadSkin(name, scope = SCOPE_SKIN):
36         # read the skin
37         filename = resolveFilename(scope, name)
38         mpath = path.dirname(filename) + "/"
39         dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
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 profile("LoadSkin")
56 try:
57         loadSkin('skin_user.xml', SCOPE_CONFIG)
58 except (SkinError, IOError, AssertionError), err:
59         print "not loading user skin: ", err
60
61 try:
62         loadSkin(config.skin.primary_skin.value)
63 except (SkinError, IOError, AssertionError), err:
64         print "SKIN ERROR:", err
65         print "defaulting to standard skin..."
66         config.skin.primary_skin.value = 'skin.xml'
67         loadSkin('skin.xml')
68
69 profile("LoadSkinDefault")
70 loadSkin('skin_default.xml')
71 profile("LoadSkinDefaultDone")
72
73 def evalPos(pos, wsize, ssize, scale):
74         if pos == "center":
75                 pos = (ssize - wsize) / 2
76         else:
77                 pos = int(pos) * scale[0] / scale[1]
78         return int(pos)
79
80 def parsePosition(str, scale, desktop = None, size = None):
81         x, y = str.split(',')
82         
83         wsize = 1, 1
84         ssize = 1, 1
85         if desktop is not None:
86                 ssize = desktop.size().width(), desktop.size().height()
87         if size is not None:
88                 wsize = size.width(), size.height()
89
90         x = evalPos(x, wsize[0], ssize[0], scale[0])
91         y = evalPos(y, wsize[1], ssize[1], scale[1])
92
93         return ePoint(x, y)
94
95 def parseSize(str, scale):
96         x, y = str.split(',')
97         return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
98
99 def parseFont(str, scale):
100         name, size = str.split(';')
101         return gFont(name, int(size) * scale[0][0] / scale[0][1])
102
103 def parseColor(str):
104         if str[0] != '#':
105                 try:
106                         return colorNames[str]
107                 except:
108                         raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
109         return gRGB(int(str[1:], 0x10))
110
111 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
112         # walk all attributes
113         for a in node.items():
114                 #print a
115                 attrib = a[0]
116                 value = a[1]
117
118                 if attrib in ("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"):
119                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
120
121                 if attrib not in ignore:
122                         skinAttributes.append((attrib, value.encode("utf-8")))
123
124 def loadPixmap(path, desktop):
125         cached = False
126         option = path.find("#")
127         if option != -1:
128                 options = path[option+1:].split(',')
129                 path = path[:option]
130                 cached = "cached" in options
131         ptr = LoadPixmap(path, desktop, cached)
132         if ptr is None:
133                 raise SkinError("pixmap file %s not found!" % (path))
134         return ptr
135
136 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
137         # and set attributes
138         try:
139                 if attrib == 'position':
140                         guiObject.move(parsePosition(value, scale, desktop, guiObject.csize()))
141                 elif attrib == 'size':
142                         guiObject.resize(parseSize(value, scale))
143                 elif attrib == 'title':
144                         guiObject.setTitle(_(value))
145                 elif attrib == 'text':
146                         guiObject.setText(_(value))
147                 elif attrib == 'font':
148                         guiObject.setFont(parseFont(value, scale))
149                 elif attrib == 'zPosition':
150                         guiObject.setZPosition(int(value))
151                 elif attrib in ("pixmap", "backgroundPixmap", "selectionPixmap"):
152                         ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
153                         if attrib == "pixmap":
154                                 guiObject.setPixmap(ptr)
155                         elif attrib == "backgroundPixmap":
156                                 guiObject.setBackgroundPicture(ptr)
157                         elif attrib == "selectionPixmap":
158                                 guiObject.setSelectionPicture(ptr)
159                         # guiObject.setPixmapFromFile(value)
160                 elif attrib == "alphatest": # used by ePixmap
161                         guiObject.setAlphatest(
162                                 { "on": 1,
163                                   "off": 0,
164                                   "blend": 2,
165                                 }[value])
166                 elif attrib == "scale":
167                         guiObject.setScale(1)
168                 elif attrib == "orientation": # used by eSlider
169                         try:
170                                 guiObject.setOrientation(*
171                                         { "orVertical": (guiObject.orVertical, False),
172                                                 "orTopToBottom": (guiObject.orVertical, False),
173                                                 "orBottomToTop": (guiObject.orVertical, True),
174                                                 "orHorizontal": (guiObject.orHorizontal, False),
175                                                 "orLeftToRight": (guiObject.orHorizontal, False),
176                                                 "orRightToLeft": (guiObject.orHorizontal, True),
177                                         }[value])
178                         except KeyError:
179                                 print "oprientation must be either orVertical or orHorizontal!"
180                 elif attrib == "valign":
181                         try:
182                                 guiObject.setVAlign(
183                                         { "top": guiObject.alignTop,
184                                                 "center": guiObject.alignCenter,
185                                                 "bottom": guiObject.alignBottom
186                                         }[value])
187                         except KeyError:
188                                 print "valign must be either top, center or bottom!"
189                 elif attrib == "halign":
190                         try:
191                                 guiObject.setHAlign(
192                                         { "left": guiObject.alignLeft,
193                                                 "center": guiObject.alignCenter,
194                                                 "right": guiObject.alignRight,
195                                                 "block": guiObject.alignBlock
196                                         }[value])
197                         except KeyError:
198                                 print "halign must be either left, center, right or block!"
199                 elif attrib == "flags":
200                         flags = value.split(',')
201                         for f in flags:
202                                 try:
203                                         fv = eWindow.__dict__[f]
204                                         guiObject.setFlag(fv)
205                                 except KeyError:
206                                         print "illegal flag %s!" % f
207                 elif attrib == "backgroundColor":
208                         guiObject.setBackgroundColor(parseColor(value))
209                 elif attrib == "backgroundColorSelected":
210                         guiObject.setBackgroundColorSelected(parseColor(value))
211                 elif attrib == "foregroundColor":
212                         guiObject.setForegroundColor(parseColor(value))
213                 elif attrib == "foregroundColorSelected":
214                         guiObject.setForegroundColorSelected(parseColor(value))
215                 elif attrib == "shadowColor":
216                         guiObject.setShadowColor(parseColor(value))
217                 elif attrib == "selectionDisabled":
218                         guiObject.setSelectionEnable(0)
219                 elif attrib == "transparent":
220                         guiObject.setTransparent(int(value))
221                 elif attrib == "borderColor":
222                         guiObject.setBorderColor(parseColor(value))
223                 elif attrib == "borderWidth":
224                         guiObject.setBorderWidth(int(value))
225                 elif attrib == "scrollbarMode":
226                         guiObject.setScrollbarMode(
227                                 { "showOnDemand": guiObject.showOnDemand,
228                                         "showAlways": guiObject.showAlways,
229                                         "showNever": guiObject.showNever
230                                 }[value])
231                 elif attrib == "enableWrapAround":
232                         guiObject.setWrapAround(True)
233                 elif attrib == "pointer" or attrib == "seek_pointer":
234                         (name, pos) = value.split(':')
235                         pos = parsePosition(pos, scale)
236                         ptr = loadPixmap(name, desktop)
237                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
238                 elif attrib == 'shadowOffset':
239                         guiObject.setShadowOffset(parsePosition(value, scale))
240                 elif attrib == 'noWrap':
241                         guiObject.setNoWrap(1)
242                 else:
243                         raise SkinError("unsupported attribute " + attrib + "=" + value)
244         except int:
245 # AttributeError:
246                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
247
248 def applyAllAttributes(guiObject, desktop, attributes, scale):
249         for (attrib, value) in attributes:
250                 applySingleAttribute(guiObject, desktop, attrib, value, scale)
251
252 def loadSingleSkinData(desktop, skin, path_prefix):
253         """loads skin data like colors, windowstyle etc."""
254         assert skin.tag == "skin", "root element in skin must be 'skin'!"
255
256         #print "***SKIN: ", path_prefix
257
258         for c in skin.findall("output"):
259                 id = c.attrib.get('id')
260                 if id:
261                         id = int(id)
262                 else:
263                         id = 0
264                 if id == 0: # framebuffer
265                         for res in c.findall("resolution"):
266                                 get_attr = res.attrib.get
267                                 xres = get_attr("xres")
268                                 if xres:
269                                         xres = int(xres)
270                                 else:
271                                         xres = 720
272                                 yres = get_attr("yres")
273                                 if yres:
274                                         yres = int(yres)
275                                 else:
276                                         yres = 576
277                                 bpp = get_attr("bpp")
278                                 if bpp:
279                                         bpp = int(bpp)
280                                 else:
281                                         bpp = 32
282                                 #print "Resolution:", xres,yres,bpp
283                                 from enigma import gFBDC
284                                 gFBDC.getInstance().setResolution(xres, yres)
285                                 desktop.resize(eSize(xres, yres))
286                                 if bpp != 32:
287                                         # load palette (not yet implemented)
288                                         pass
289
290         for c in skin.findall("colors"):
291                 for color in c.findall("color"):
292                         get_attr = color.attrib.get
293                         name = get_attr("name")
294                         color = get_attr("value")
295                         if name and color:
296                                 colorNames[name] = parseColor(color)
297                                 #print "Color:", name, color
298                         else:
299                                 raise SkinError("need color and name, got %s %s" % (name, color))
300
301         for c in skin.findall("fonts"):
302                 for font in c.findall("font"):
303                         get_attr = font.attrib.get
304                         filename = get_attr("filename", "<NONAME>")
305                         name = get_attr("name", "Regular")
306                         scale = get_attr("scale")
307                         if scale:
308                                 scale = int(scale)
309                         else:
310                                 scale = 100
311                         is_replacement = get_attr("replacement") and True or False
312                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
313                         if not fileExists(resolved_font): #when font is not available look at current skin path
314                                 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
315                                 if fileExists(skin_path):
316                                         resolved_font = skin_path
317                         addFont(resolved_font, name, scale, is_replacement)
318                         #print "Font: ", resolved_font, name, scale, is_replacement
319
320         for c in skin.findall("subtitles"):
321                 from enigma import eWidget, eSubtitleWidget
322                 scale = ((1,1),(1,1))
323                 for substyle in c.findall("sub"):
324                         get_attr = substyle.attrib.get
325                         font = parseFont(get_attr("font"), scale)
326                         col = get_attr("foregroundColor")
327                         if col:
328                                 foregroundColor = parseColor(col)
329                                 haveColor = 1
330                         else:
331                                 foregroundColor = gRGB(0xFFFFFF)
332                                 haveColor = 0
333                         col = get_attr("shadowColor")
334                         if col:
335                                 shadowColor = parseColor(col)
336                         else:
337                                 shadowColor = gRGB(0)
338                         shadowOffset = parsePosition(get_attr("shadowOffset"), scale)
339                         face = eSubtitleWidget.__dict__[get_attr("name")]
340                         eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, shadowColor, shadowOffset)
341
342         for windowstyle in skin.findall("windowstyle"):
343                 style = eWindowStyleSkinned()
344                 id = windowstyle.attrib.get("id")
345                 if id:
346                         id = int(id)
347                 else:
348                         id = 0
349                 #print "windowstyle:", id
350
351                 # defaults
352                 font = gFont("Regular", 20)
353                 offset = eSize(20, 5)
354
355                 for title in windowstyle.findall("title"):
356                         get_attr = title.attrib.get
357                         offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
358                         font = parseFont(get_attr("font"), ((1,1),(1,1)))
359
360                 style.setTitleFont(font);
361                 style.setTitleOffset(offset)
362                 #print "  ", font, offset
363
364                 for borderset in windowstyle.findall("borderset"):
365                         bsName = str(borderset.attrib.get("name"))
366                         for pixmap in borderset.findall("pixmap"):
367                                 get_attr = pixmap.attrib.get
368                                 bpName = get_attr("pos")
369                                 filename = get_attr("filename")
370                                 if filename and bpName:
371                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
372                                         style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
373                                 #print "  borderset:", bpName, filename
374
375                 for color in windowstyle.findall("color"):
376                         get_attr = color.attrib.get
377                         colorType = get_attr("name")
378                         color = parseColor(get_attr("color"))
379                         try:
380                                 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
381                         except:
382                                 raise SkinError("Unknown color %s" % (colorType))
383                                 #pass
384
385                         #print "  color:", type, color
386
387                 x = eWindowStyleManager.getInstance()
388                 x.setStyle(id, style)
389
390 def loadSkinData(desktop):
391         skins = dom_skins[:]
392         skins.reverse()
393         for (path, dom_skin) in skins:
394                 loadSingleSkinData(desktop, dom_skin, path)
395
396 def lookupScreen(name):
397         for (path, skin) in dom_skins:
398                 # first, find the corresponding screen element
399                 for x in skin.findall("screen"):
400                         if x.attrib.get('name', '') == name:
401                                 return x, path
402         return None, None
403
404 class additionalWidget:
405         pass
406
407 def readSkin(screen, skin, names, desktop):
408         if not isinstance(names, list):
409                 names = [names]
410
411         name = "<embedded-in-'%s'>" % screen.__class__.__name__
412
413         # try all skins, first existing one have priority
414         for n in names:
415                 myscreen, path = lookupScreen(n)
416                 if myscreen is not None:
417                         # use this name for debug output
418                         name = n
419                         break
420
421         # otherwise try embedded skin
422         if myscreen is None:
423                 myscreen = getattr(screen, "parsedSkin", None)
424
425         # try uncompiled embedded skin
426         if myscreen is None and getattr(screen, "skin", None):
427                 print "Looking for embedded skin"
428                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
429
430         #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
431         if myscreen is None:
432                 print "No skin to read..."
433                 emptySkin = "<screen></screen>"
434                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
435
436         screen.skinAttributes = [ ]
437
438         skin_path_prefix = getattr(screen, "skin_path", path)
439
440         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
441
442         screen.additionalWidgets = [ ]
443         screen.renderer = [ ]
444
445         visited_components = set()
446
447         # now walk all widgets
448         for widget in myscreen.findall("widget"):
449                 get_attr = widget.attrib.get
450                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
451                 # widgets (source->renderer).
452
453                 wname = get_attr('name')
454                 wsource = get_attr('source')
455
456                 if wname is None and wsource is None:
457                         print "widget has no name and no source!"
458                         continue
459
460                 if wname:
461                         #print "Widget name=", wname
462                         visited_components.add(wname)
463
464                         # get corresponding 'gui' object
465                         try:
466                                 attributes = screen[wname].skinAttributes = [ ]
467                         except:
468                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
469                                 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
470
471 #                       assert screen[wname] is not Source
472
473                         # and collect attributes for this
474                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
475                 elif wsource:
476                         # get corresponding source
477                         #print "Widget source=", wsource
478
479                         while True: # until we found a non-obsolete source
480
481                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
482                                 # for example to reference a parent, global or session-global screen.
483                                 scr = screen
484
485                                 # resolve all path components
486                                 path = wsource.split('.')
487                                 while len(path) > 1:
488                                         scr = screen.getRelatedScreen(path[0])
489                                         if scr is None:
490                                                 #print wsource
491                                                 #print name
492                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
493                                         path = path[1:]
494
495                                 # resolve the source.
496                                 source = scr.get(path[0])
497                                 if isinstance(source, ObsoleteSource):
498                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
499                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
500                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
501                                         if source.description:
502                                                 print source.description
503
504                                         wsource = source.new_source
505                                 else:
506                                         # otherwise, use that source.
507                                         break
508
509                         if source is None:
510                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
511
512                         wrender = get_attr('render')
513
514                         if not wrender:
515                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
516
517                         for converter in widget.findall("convert"):
518                                 ctype = converter.get('type')
519                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
520                                 #print "Converter:", ctype
521                                 try:
522                                         parms = converter.text.strip()
523                                 except:
524                                         parms = ""
525                                 #print "Params:", parms
526                                 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
527
528                                 c = None
529
530                                 for i in source.downstream_elements:
531                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
532                                                 c = i
533
534                                 if c is None:
535                                         print "allocating new converter!"
536                                         c = converter_class(parms)
537                                         c.connect(source)
538                                 else:
539                                         print "reused converter!"
540
541                                 source = c
542
543                         renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
544
545                         renderer = renderer_class() # instantiate renderer
546
547                         renderer.connect(source) # connect to source
548                         attributes = renderer.skinAttributes = [ ]
549                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
550
551                         screen.renderer.append(renderer)
552
553         from Components.GUIComponent import GUIComponent
554         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
555         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
556
557         # now walk additional objects
558         for widget in myscreen.getchildren():
559                 w_tag = widget.tag
560
561                 if w_tag == "widget":
562                         continue
563
564                 if w_tag == "applet":
565                         try:
566                                 codeText = widget.text.strip()
567                         except:
568                                 codeText = ""
569
570                         #print "Found code:"
571                         #print codeText
572                         widgetType = widget.attrib.get('type')
573
574                         code = compile(codeText, "skin applet", "exec")
575
576                         if widgetType == "onLayoutFinish":
577                                 screen.onLayoutFinish.append(code)
578                                 #print "onLayoutFinish = ", codeText
579                         else:
580                                 raise SkinError("applet type '%s' unknown!" % widgetType)
581                                 #print "applet type '%s' unknown!" % type
582
583                         continue
584
585                 w = additionalWidget()
586
587                 if w_tag == "eLabel":
588                         w.widget = eLabel
589                 elif w_tag == "ePixmap":
590                         w.widget = ePixmap
591                 else:
592                         raise SkinError("unsupported stuff : %s" % w_tag)
593                         #print "unsupported stuff : %s" % widget.tag
594
595                 w.skinAttributes = [ ]
596                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
597
598                 # applyAttributes(guiObject, widget, desktop)
599                 # guiObject.thisown = 0
600                 screen.additionalWidgets.append(w)