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