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