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