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