enigma2 20131118 (master) -> 20140214 (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, eListboxPythonConfigContent
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", "progress_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" or attrib == "progress_pointer":
262                         (name, pos) = value.split(':')
263                         pos = parsePosition(pos, scale)
264                         ptr = loadPixmap(name, desktop)
265                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1, "progress_pointer": 2}[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 listboxcontent offset '%s'' but 'left' or 'right' is allowed only" % name)
343                 for font in c.findall("font"):
344                         get_attr = font.attrib.get
345                         name = get_attr("name")
346                         font = get_attr("font")
347                         if name and font:
348                                 if name == "string":
349                                         eListboxPythonStringContent.setFont(parseFont(font, ((1,1),(1,1))))
350                                 elif name == "config_description":
351                                         eListboxPythonConfigContent.setDescriptionFont(parseFont(font, ((1,1),(1,1))))
352                                 elif name == "config_value":
353                                         eListboxPythonConfigContent.setValueFont(parseFont(font, ((1,1),(1,1))))
354                                 else:
355                                         raise SkinError("got listboxcontent font '%s' but 'string', 'config_description' or 'config_value' is allowed only" % name)
356                 for value in c.findall("value"):
357                         get_attr = value.attrib.get
358                         name = get_attr("name")
359                         value = get_attr("value")
360                         if name and value:
361                                 if name == "string_item_height":
362                                         eListboxPythonStringContent.setItemHeight(parseValue(value))
363                                 elif name == "config_item_height":
364                                         eListboxPythonConfigContent.setItemHeight(parseValue(value))
365                                 else:
366                                         raise SkinError("got listboxcontent value '%s' but 'string_item_height' or 'config_item_height' is allowed only" % name)
367
368         for c in skin.findall("fonts"):
369                 for font in c.findall("font"):
370                         get_attr = font.attrib.get
371                         filename = get_attr("filename", "<NONAME>")
372                         name = get_attr("name", "Regular")
373                         scale = get_attr("scale")
374                         if scale:
375                                 scale = int(scale)
376                         else:
377                                 scale = 100
378                         is_replacement = get_attr("replacement") and True or False
379                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
380                         if not fileExists(resolved_font): #when font is not available look at current skin path
381                                 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
382                                 if fileExists(skin_path):
383                                         resolved_font = skin_path
384                         addFont(resolved_font, name, scale, is_replacement)
385                         #print "Font: ", resolved_font, name, scale, is_replacement
386
387         for c in skin.findall("subtitles"):
388                 from enigma import eWidget, eSubtitleWidget
389                 scale = ((1,1),(1,1))
390                 for substyle in c.findall("sub"):
391                         get_attr = substyle.attrib.get
392                         font = parseFont(get_attr("font"), scale)
393                         col = get_attr("foregroundColor")
394                         if col:
395                                 foregroundColor = parseColor(col)
396                                 haveColor = 1
397                         else:
398                                 foregroundColor = gRGB(0xFFFFFF)
399                                 haveColor = 0
400                         col = get_attr("shadowColor")
401                         if col:
402                                 shadowColor = parseColor(col)
403                         else:
404                                 shadowColor = gRGB(0)
405                         shadowOffset = parsePosition(get_attr("shadowOffset"), scale)
406                         face = eSubtitleWidget.__dict__[get_attr("name")]
407                         eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, shadowColor, shadowOffset)
408
409         for windowstyle in skin.findall("windowstyle"):
410                 style = eWindowStyleSkinned()
411                 id = windowstyle.attrib.get("id")
412                 if id:
413                         id = int(id)
414                 else:
415                         id = 0
416                 #print "windowstyle:", id
417
418                 # defaults
419                 font = gFont("Regular", 20)
420                 offset = eSize(20, 5)
421
422                 for title in windowstyle.findall("title"):
423                         get_attr = title.attrib.get
424                         offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
425                         font = parseFont(get_attr("font"), ((1,1),(1,1)))
426
427                 style.setTitleFont(font);
428                 style.setTitleOffset(offset)
429                 #print "  ", font, offset
430
431                 for borderset in windowstyle.findall("borderset"):
432                         bsName = str(borderset.attrib.get("name"))
433                         for pixmap in borderset.findall("pixmap"):
434                                 get_attr = pixmap.attrib.get
435                                 bpName = get_attr("pos")
436                                 filename = get_attr("filename")
437                                 if filename and bpName:
438                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
439                                         style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
440                                 #print "  borderset:", bpName, filename
441
442                 for color in windowstyle.findall("color"):
443                         get_attr = color.attrib.get
444                         colorType = get_attr("name")
445                         color = parseColor(get_attr("color"))
446                         try:
447                                 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
448                         except:
449                                 raise SkinError("Unknown color %s" % (colorType))
450                                 #pass
451
452                         #print "  color:", type, color
453
454                 x = eWindowStyleManager.getInstance()
455                 x.setStyle(id, style)
456
457         for windowstylescrollbar in skin.findall("windowstylescrollbar"):
458                 style = eWindowStyleScrollbar()
459                 id = windowstylescrollbar.attrib.get("id")
460                 if id:
461                         id = int(id)
462                 else:
463                         id = 4
464                 for value in windowstylescrollbar.findall("value"):
465                         get_attr = value.attrib.get
466                         vType = get_attr("name")
467                         v = get_attr("value")
468                         if vType == "BackgroundPixmapTopHeight":
469                                 style.setBackgroundPixmapTopHeight(int(v))
470                         elif vType == "BackgroundPixmapBottomHeight":
471                                 style.setBackgroundPixmapBottomHeight(int(v))
472                         elif vType == "ValuePixmapTopHeight":
473                                 style.setValuePixmapTopHeight(int(v))
474                         elif vType == "ValuePixmapBottomHeight":
475                                 style.setValuePixmapBottomHeight(int(v))
476                         elif vType == "ScrollbarWidth":
477                                 style.setScrollbarWidth(int(v))
478                         elif vType == "ScrollbarBorderWidth":
479                                 style.setScrollbarBorderWidth(int(v))
480                 for pixmap in windowstylescrollbar.findall("pixmap"):
481                         get_attr = pixmap.attrib.get
482                         vType = get_attr("name")
483                         filename = get_attr("filename")
484                         if filename:
485                                 if vType == "BackgroundPixmap":
486                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
487                                         style.setBackgroundPixmap(png)
488                                 elif vType == "ValuePixmap":
489                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
490                                         style.setValuePixmap(png)
491                 x = eWindowStyleManager.getInstance()
492                 x.setStyle(id, style)
493
494 def loadSkinData(desktop):
495         skins = dom_skins[:]
496         skins.reverse()
497         for (path, dom_skin) in skins:
498                 loadSingleSkinData(desktop, dom_skin, path)
499
500 def lookupScreen(name, style_id):
501         for (path, skin) in dom_skins:
502                 # first, find the corresponding screen element
503                 for x in skin.findall("screen"):
504                         if x.attrib.get('name', '') == name:
505                                 screen_style_id = x.attrib.get('id', '-1')
506                                 if screen_style_id == '-1' and name.find('ummary') > 0:
507                                         screen_style_id = '1'
508                                 if (style_id != 2 and int(screen_style_id) == -1) or int(screen_style_id) == style_id:
509                                         return x, path
510         return None, None
511
512 class additionalWidget:
513         pass
514
515 def readSkin(screen, skin, names, desktop):
516         if not isinstance(names, list):
517                 names = [names]
518
519         name = "<embedded-in-'%s'>" % screen.__class__.__name__
520
521         style_id = desktop.getStyleID();
522
523         # try all skins, first existing one have priority
524         for n in names:
525                 myscreen, path = lookupScreen(n, style_id)
526                 if myscreen is not None:
527                         # use this name for debug output
528                         name = n
529                         break
530
531         # otherwise try embedded skin
532         if myscreen is None:
533                 myscreen = getattr(screen, "parsedSkin", None)
534
535         # try uncompiled embedded skin
536         if myscreen is None and getattr(screen, "skin", None):
537                 print "Looking for embedded skin"
538                 skin_tuple = screen.skin
539                 if not isinstance(skin_tuple, tuple):
540                         skin_tuple = (skin_tuple,)
541                 for sskin in skin_tuple:
542                         parsedSkin = xml.etree.cElementTree.fromstring(sskin)
543                         screen_style_id = parsedSkin.attrib.get('id', '-1')
544                         if (style_id != 2 and int(screen_style_id) == -1) or int(screen_style_id) == style_id:
545                                 myscreen = screen.parsedSkin = parsedSkin
546                                 break
547
548         #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
549         if myscreen is None:
550                 print "No skin to read..."
551                 emptySkin = "<screen></screen>"
552                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
553
554         screen.skinAttributes = [ ]
555
556         skin_path_prefix = getattr(screen, "skin_path", path)
557
558         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
559
560         screen.additionalWidgets = [ ]
561         screen.renderer = [ ]
562
563         visited_components = set()
564
565         # now walk all widgets
566         for widget in myscreen.findall("widget"):
567                 get_attr = widget.attrib.get
568                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
569                 # widgets (source->renderer).
570
571                 wname = get_attr('name')
572                 wsource = get_attr('source')
573
574                 if wname is None and wsource is None:
575                         print "widget has no name and no source!"
576                         continue
577
578                 if wname:
579                         #print "Widget name=", wname
580                         visited_components.add(wname)
581
582                         # get corresponding 'gui' object
583                         try:
584                                 attributes = screen[wname].skinAttributes = [ ]
585                         except:
586                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
587                                 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
588
589 #                       assert screen[wname] is not Source
590
591                         # and collect attributes for this
592                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
593                 elif wsource:
594                         # get corresponding source
595                         #print "Widget source=", wsource
596
597                         while True: # until we found a non-obsolete source
598
599                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
600                                 # for example to reference a parent, global or session-global screen.
601                                 scr = screen
602
603                                 # resolve all path components
604                                 path = wsource.split('.')
605                                 while len(path) > 1:
606                                         scr = screen.getRelatedScreen(path[0])
607                                         if scr is None:
608                                                 #print wsource
609                                                 #print name
610                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
611                                         path = path[1:]
612
613                                 # resolve the source.
614                                 source = scr.get(path[0])
615                                 if isinstance(source, ObsoleteSource):
616                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
617                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
618                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
619                                         if source.description:
620                                                 print source.description
621
622                                         wsource = source.new_source
623                                 else:
624                                         # otherwise, use that source.
625                                         break
626
627                         if source is None:
628                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
629
630                         wrender = get_attr('render')
631
632                         if not wrender:
633                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
634
635                         for converter in widget.findall("convert"):
636                                 ctype = converter.get('type')
637                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
638                                 #print "Converter:", ctype
639                                 try:
640                                         parms = converter.text.strip()
641                                 except:
642                                         parms = ""
643                                 #print "Params:", parms
644                                 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
645
646                                 c = None
647
648                                 for i in source.downstream_elements:
649                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
650                                                 c = i
651
652                                 if c is None:
653                                         print "allocating new converter!"
654                                         c = converter_class(parms)
655                                         c.connect(source)
656                                 else:
657                                         print "reused converter!"
658                                         hasattr(c, "reuse") and c.reuse()
659
660                                 source = c
661
662                         renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
663
664                         renderer = renderer_class() # instantiate renderer
665
666                         renderer.connect(source) # connect to source
667                         attributes = renderer.skinAttributes = [ ]
668                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
669
670                         screen.renderer.append(renderer)
671
672         from Components.GUIComponent import GUIComponent
673         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
674         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
675
676         # now walk additional objects
677         for widget in myscreen.getchildren():
678                 w_tag = widget.tag
679
680                 if w_tag == "widget":
681                         continue
682
683                 if w_tag == "applet":
684                         try:
685                                 codeText = widget.text.strip()
686                         except:
687                                 codeText = ""
688
689                         #print "Found code:"
690                         #print codeText
691                         widgetType = widget.attrib.get('type')
692
693                         code = compile(codeText, "skin applet", "exec")
694
695                         if widgetType == "onLayoutFinish":
696                                 screen.onLayoutFinish.append(code)
697                                 #print "onLayoutFinish = ", codeText
698                         else:
699                                 raise SkinError("applet type '%s' unknown!" % widgetType)
700                                 #print "applet type '%s' unknown!" % type
701
702                         continue
703
704                 w = additionalWidget()
705
706                 if w_tag == "eLabel":
707                         w.widget = eLabel
708                 elif w_tag == "ePixmap":
709                         w.widget = ePixmap
710                 else:
711                         raise SkinError("unsupported stuff : %s" % w_tag)
712                         #print "unsupported stuff : %s" % widget.tag
713
714                 w.skinAttributes = [ ]
715                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
716
717                 # applyAttributes(guiObject, widget, desktop)
718                 # guiObject.thisown = 0
719                 screen.additionalWidgets.append(w)
720
721 class TemplatedColors():
722         def __init__(self, style_id = 0):
723                 from enigma import eWindowStyleManager, eWindowStyleSkinned, gRGB
724                 x = eWindowStyleManager.getInstance()
725                 style = x.getStyle(style_id)
726                 self.colors = {}
727                 for color_name in ("Background", "LabelForeground", "ListboxForeground", "ListboxSelectedForeground", "ListboxBackground", "ListboxSelectedBackground", "ListboxMarkedForeground", "ListboxMarkedAndSelectedForeground", "ListboxMarkedBackground", "ListboxMarkedAndSelectedBackground", "WindowTitleForeground", "WindowTitleBackground"):
728                         color = gRGB(0)
729                         style.getColor(eWindowStyleSkinned.__dict__["col"+color_name], color)
730                         self.colors[color_name] = color.argb()
731         
732         def __getitem__(self, color_name):
733                 return color_name in self.colors and self.colors[color_name] or 0x000000
734