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