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