869c3041ba6c824fa01c1991929855414a256921
[openblackhole/openblackhole-enigma2.git] / skin.py
1 from Tools.Profile import profile
2 profile("LOAD:ElementTree")
3 import xml.etree.cElementTree
4 import os
5
6 profile("LOAD:enigma_skin")
7 from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
8         addFont, gRGB, eWindowStyleSkinned, getDesktop
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_FONTS, SCOPE_CURRENT_SKIN, SCOPE_CONFIG, fileExists, SCOPE_SKIN_IMAGE
13 from Tools.Import import my_import
14 from Tools.LoadPixmap import LoadPixmap
15 from Components.RcModel import rc_model
16
17 colorNames = {}
18 # Predefined fonts, typically used in built-in screens and for components like
19 # the movie list and so.
20 fonts = {
21         "Body": ("Regular", 18, 22, 16),
22         "ChoiceList": ("Regular", 20, 24, 18),
23 }
24
25 parameters = {}
26
27 def dump(x, i=0):
28         print " " * i + str(x)
29         try:
30                 for n in x.childNodes:
31                         dump(n, i + 1)
32         except:
33                 None
34
35 class SkinError(Exception):
36         def __init__(self, message):
37                 self.msg = message
38
39         def __str__(self):
40                 return "{%s}: %s. Please contact the skin's author!" % (config.skin.primary_skin.value, self.msg)
41
42 dom_skins = [ ]
43
44 def addSkin(name, scope = SCOPE_SKIN):
45         # read the skin
46         filename = resolveFilename(scope, name)
47         if fileExists(filename):
48                 mpath = os.path.dirname(filename) + "/"
49                 try:
50                         dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
51                 except:
52                         print "[SKIN ERROR] error in %s" % filename
53                         return False
54                 else:
55                         return True
56         return False
57
58 # get own skin_user_skinname.xml file, if exist
59 def skin_user_skinname():
60         name = "skin_user_" + config.skin.primary_skin.value[:config.skin.primary_skin.value.rfind('/')] + ".xml"
61         filename = resolveFilename(SCOPE_CONFIG, name)
62         if fileExists(filename):
63                 return name
64         return None
65
66 # we do our best to always select the "right" value
67 # skins are loaded in order of priority: skin with
68 # highest priority is loaded last, usually the user-provided
69 # skin.
70
71 # currently, loadSingleSkinData (colors, bordersets etc.)
72 # are applied one-after-each, in order of ascending priority.
73 # the dom_skin will keep all screens in descending priority,
74 # so the first screen found will be used.
75
76 # example: loadSkin("nemesis_greenline/skin.xml")
77 config.skin = ConfigSubsection()
78 DEFAULT_SKIN = "PLi-HD/skin.xml"
79 # on SD hardware, PLi-HD will not be available
80 if not fileExists(resolveFilename(SCOPE_SKIN, DEFAULT_SKIN)):
81         # in that case, fallback to Magic (which is an SD skin)
82         DEFAULT_SKIN = "Magic/skin.xml"
83 config.skin.primary_skin = ConfigText(default=DEFAULT_SKIN)
84
85 profile("LoadSkin")
86 res = None
87 name = skin_user_skinname()
88 if name:
89         res = addSkin(name, SCOPE_CONFIG)
90 if not name or not res:
91         addSkin('skin_user.xml', SCOPE_CONFIG)
92
93 # some boxes lie about their dimensions
94 addSkin('skin_box.xml')
95 # add optional discrete second infobar
96 addSkin('skin_second_infobar.xml')
97 # Only one of these is present, compliments of AM_CONDITIONAL
98 display_skin_id = 1
99 addSkin('skin_display.xml')
100 if addSkin('skin_display96.xml'):
101         # Color OLED
102         display_skin_id = 2
103 addSkin('skin_text.xml')
104
105 addSkin('skin_subtitles.xml')
106
107 try:
108         if not addSkin(config.skin.primary_skin.value):
109                 raise SkinError, "primary skin not found"
110 except Exception, err:
111         print "SKIN ERROR:", err
112         skin = DEFAULT_SKIN
113         if config.skin.primary_skin.value == skin:
114                 skin = 'skin.xml'
115         print "defaulting to standard skin...", skin
116         config.skin.primary_skin.value = skin
117         addSkin(skin)
118         del skin
119
120 addSkin('skin_default.xml')
121 profile("LoadSkinDefaultDone")
122
123 def parseCoordinate(s, e, size=0, font=None):
124         s = s.strip()
125         if s == "center":
126                 val = (e - size)/2
127         elif s == '*':
128                 return None
129         else:
130                 if s[0] is 'e':
131                         val = e
132                         s = s[1:]
133                 elif s[0] is 'c':
134                         val = e/2
135                         s = s[1:]
136                 else:
137                         val = 0;
138                 if s:
139                         if s[-1] is '%':
140                                 val += e * int(s[:-1]) / 100
141                         elif s[-1] is 'w':
142                                 val += fonts[font][3] * int(s[:-1]);
143                         elif s[-1] is 'h':
144                                 val += fonts[font][2] * int(s[:-1]);
145                         else:
146                                 val += int(s)
147         if val < 0:
148                 val = 0
149         return val
150
151
152 def getParentSize(object, desktop):
153         size = eSize()
154         if object:
155                 parent = object.getParent()
156                 # For some widgets (e.g. ScrollLabel) the skin attributes are applied to
157                 # a child widget, instead of to the widget itself. In that case, the parent
158                 # we have here is not the real parent, but it is the main widget.
159                 # We have to go one level higher to get the actual parent.
160                 # We can detect this because the 'parent' will not have a size yet
161                 # (the main widget's size will be calculated internally, as soon as the child
162                 # widget has parsed the skin attributes)
163                 if parent and parent.size().isEmpty():
164                         parent = parent.getParent()
165                 if parent:
166                         size = parent.size()
167                 elif desktop:
168                         #widget has no parent, use desktop size instead for relative coordinates
169                         size = desktop.size()
170         return size
171
172 def parsePosition(s, scale, object = None, desktop = None, size = None):
173         x, y = s.split(',')
174         parentsize = eSize()
175         if object and (x[0] in ('c', 'e') or y[0] in ('c', 'e')):
176                 parentsize = getParentSize(object, desktop)
177         xval = parseCoordinate(x, parentsize.width(), size and size.width())
178         yval = parseCoordinate(y, parentsize.height(), size and size.height())
179         return ePoint(xval * scale[0][0] / scale[0][1], yval * scale[1][0] / scale[1][1])
180
181 def parseSize(s, scale, object = None, desktop = None):
182         x, y = s.split(',')
183         parentsize = eSize()
184         if object and (x[0] in ('c', 'e') or y[0] in ('c', 'e')):
185                 parentsize = getParentSize(object, desktop)
186         xval = parseCoordinate(x, parentsize.width())
187         yval = parseCoordinate(y, parentsize.height())
188         return eSize(xval * scale[0][0] / scale[0][1], yval * scale[1][0] / scale[1][1])
189
190 def parseFont(s, scale):
191         try:
192                 f = fonts[s]
193                 name = f[0]
194                 size = f[1]
195         except:
196                 name, size = s.split(';')
197         return gFont(name, int(size) * scale[0][0] / scale[0][1])
198
199 def parseColor(s):
200         if s[0] != '#':
201                 try:
202                         return colorNames[s]
203                 except:
204                         raise SkinError("color '%s' must be #aarrggbb or valid named color" % (s))
205         return gRGB(int(s[1:], 0x10))
206
207 def collectAttributes(skinAttributes, node, context, skin_path_prefix=None, ignore=(), filenames=frozenset(("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap", "sliderPixmap", "scrollbarbackgroundPixmap"))):
208         # walk all attributes
209         size = None
210         pos = None
211         font = None
212         for attrib, value in node.items():
213                 if attrib not in ignore:
214                         if attrib in filenames:
215                                 value = resolveFilename(SCOPE_CURRENT_SKIN, value, path_prefix=skin_path_prefix)
216                         # Bit of a hack this, really. When a window has a flag (e.g. wfNoBorder)
217                         # it needs to be set at least before the size is set, in order for the
218                         # window dimensions to be calculated correctly in all situations.
219                         # If wfNoBorder is applied after the size has been set, the window will fail to clear the title area.
220                         # Similar situation for a scrollbar in a listbox; when the scrollbar setting is applied after
221                         # the size, a scrollbar will not be shown until the selection moves for the first time
222                         if attrib == 'size':
223                                 size = value.encode("utf-8")
224                         elif attrib == 'position':
225                                 pos = value.encode("utf-8")
226                         elif attrib == 'font':
227                                 font = value.encode("utf-8")
228                                 skinAttributes.append((attrib, font))
229                         else:
230                                 skinAttributes.append((attrib, value.encode("utf-8")))
231         if pos is not None:
232                 pos, size = context.parse(pos, size, font)
233                 skinAttributes.append(('position', pos))
234         if size is not None:
235                 skinAttributes.append(('size', size))
236
237 def morphRcImagePath(value):
238         if rc_model.rcIsDefault() is False:
239                 if value == '/usr/share/enigma2/skin_default/rc.png' or value == '/usr/share/enigma2/skin_default/rcold.png':
240                         value = rc_model.getRcImg()
241         return value
242
243 def loadPixmap(path, desktop):
244         option = path.find("#")
245         if option != -1:
246                 path = path[:option]
247         ptr = LoadPixmap(morphRcImagePath(path), desktop)
248         if ptr is None:
249                 raise SkinError("pixmap file %s not found!" % (path))
250         return ptr
251
252 class AttributeParser:
253         def __init__(self, guiObject, desktop, scale=((1,1),(1,1))):
254                 self.guiObject = guiObject
255                 self.desktop = desktop
256                 self.scaleTuple = scale
257         def applyOne(self, attrib, value):
258                 try:
259                         getattr(self, attrib)(value)
260                 except AttributeError:
261                         print "[Skin] Attribute not implemented:", attrib, "value:", value
262                 except SkinError, ex:
263                         print "[Skin] Error:", ex
264         def applyAll(self, attrs):
265                 for attrib, value in attrs:
266                         self.applyOne(attrib, value)
267         def conditional(self, value):
268                 pass
269         def position(self, value):
270                 if isinstance(value, tuple):
271                         self.guiObject.move(ePoint(*value))
272                 else:
273                         self.guiObject.move(parsePosition(value, self.scaleTuple, self.guiObject, self.desktop, self.guiObject.csize()))
274         def size(self, value):
275                 if isinstance(value, tuple):
276                         self.guiObject.resize(eSize(*value))
277                 else:
278                         self.guiObject.resize(parseSize(value, self.scaleTuple, self.guiObject, self.desktop))
279         def title(self, value):
280                 self.guiObject.setTitle(_(value))
281         def text(self, value):
282                 self.guiObject.setText(_(value))
283         def font(self, value):
284                 self.guiObject.setFont(parseFont(value, self.scaleTuple))
285         def zPosition(self, value):
286                 self.guiObject.setZPosition(int(value))
287         def itemHeight(self, value):
288                 self.guiObject.setItemHeight(int(value))
289         def pixmap(self, value):
290                 ptr = loadPixmap(value, self.desktop)
291                 self.guiObject.setPixmap(ptr)
292         def backgroundPixmap(self, value):
293                 ptr = loadPixmap(value, self.desktop)
294                 self.guiObject.setBackgroundPicture(ptr)
295         def selectionPixmap(self, value):
296                 ptr = loadPixmap(value, self.desktop)
297                 self.guiObject.setSelectionPicture(ptr)
298         def sliderPixmap(self, value):
299                 ptr = loadPixmap(value, self.desktop)
300                 self.guiObject.setSliderPicture(ptr)
301         def scrollbarbackgroundPixmap(self, value):
302                 ptr = loadPixmap(value, self.desktop)
303                 self.guiObject.setScrollbarBackgroundPicture(ptr)
304         def alphatest(self, value):
305                 self.guiObject.setAlphatest(
306                         { "on": 1,
307                           "off": 0,
308                           "blend": 2,
309                         }[value])
310         def scale(self, value):
311                 self.guiObject.setScale(1)
312         def orientation(self, value): # used by eSlider
313                 try:
314                         self.guiObject.setOrientation(*
315                                 { "orVertical": (self.guiObject.orVertical, False),
316                                         "orTopToBottom": (self.guiObject.orVertical, False),
317                                         "orBottomToTop": (self.guiObject.orVertical, True),
318                                         "orHorizontal": (self.guiObject.orHorizontal, False),
319                                         "orLeftToRight": (self.guiObject.orHorizontal, False),
320                                         "orRightToLeft": (self.guiObject.orHorizontal, True),
321                                 }[value])
322                 except KeyError:
323                         print "oprientation must be either orVertical or orHorizontal!"
324         def valign(self, value):
325                 try:
326                         self.guiObject.setVAlign(
327                                 { "top": self.guiObject.alignTop,
328                                         "center": self.guiObject.alignCenter,
329                                         "bottom": self.guiObject.alignBottom
330                                 }[value])
331                 except KeyError:
332                         print "valign must be either top, center or bottom!"
333         def halign(self, value):
334                 try:
335                         self.guiObject.setHAlign(
336                                 { "left": self.guiObject.alignLeft,
337                                         "center": self.guiObject.alignCenter,
338                                         "right": self.guiObject.alignRight,
339                                         "block": self.guiObject.alignBlock
340                                 }[value])
341                 except KeyError:
342                         print "halign must be either left, center, right or block!"
343         def textOffset(self, value):
344                 x, y = value.split(',')
345                 self.guiObject.setTextOffset(ePoint(int(x) * self.scaleTuple[0][0] / self.scaleTuple[0][1], int(y) * self.scaleTuple[1][0] / self.scaleTuple[1][1]))
346         def flags(self, value):
347                 flags = value.split(',')
348                 for f in flags:
349                         try:
350                                 fv = eWindow.__dict__[f]
351                                 self.guiObject.setFlag(fv)
352                         except KeyError:
353                                 print "illegal flag %s!" % f
354         def backgroundColor(self, value):
355                 self.guiObject.setBackgroundColor(parseColor(value))
356         def backgroundColorSelected(self, value):
357                 self.guiObject.setBackgroundColorSelected(parseColor(value))
358         def foregroundColor(self, value):
359                 self.guiObject.setForegroundColor(parseColor(value))
360         def foregroundColorSelected(self, value):
361                 self.guiObject.setForegroundColorSelected(parseColor(value))
362         def shadowColor(self, value):
363                 self.guiObject.setShadowColor(parseColor(value))
364         def selectionDisabled(self, value):
365                 self.guiObject.setSelectionEnable(0)
366         def transparent(self, value):
367                 self.guiObject.setTransparent(int(value))
368         def borderColor(self, value):
369                 self.guiObject.setBorderColor(parseColor(value))
370         def borderWidth(self, value):
371                 self.guiObject.setBorderWidth(int(value))
372         def scrollbarMode(self, value):
373                 self.guiObject.setScrollbarMode(getattr(self.guiObject, value))
374                 #       { "showOnDemand": self.guiObject.showOnDemand,
375                 #               "showAlways": self.guiObject.showAlways,
376                 #               "showNever": self.guiObject.showNever,
377                 #               "showLeft": self.guiObject.showLeft
378                 #       }[value])
379         def enableWrapAround(self, value):
380                 self.guiObject.setWrapAround(True)
381         def itemHeight(self, value):
382                 self.guiObject.setItemHeight(int(value))
383         def pointer(self, value):
384                 (name, pos) = value.split(':')
385                 pos = parsePosition(pos, self.scaleTuple)
386                 ptr = loadPixmap(name, self.desktop)
387                 self.guiObject.setPointer(0, ptr, pos)
388         def seek_pointer(self, value):
389                 (name, pos) = value.split(':')
390                 pos = parsePosition(pos, self.scaleTuple)
391                 ptr = loadPixmap(name, self.desktop)
392                 self.guiObject.setPointer(1, ptr, pos)
393         def shadowOffset(self, value):
394                 self.guiObject.setShadowOffset(parsePosition(value, self.scaleTuple))
395         def noWrap(self, value):
396                 self.guiObject.setNoWrap(1)
397
398 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
399         # Someone still using applySingleAttribute?
400         AttributeParser(guiObject, desktop, scale).applyOne(attrib, value)
401
402 def applyAllAttributes(guiObject, desktop, attributes, scale):
403         AttributeParser(guiObject, desktop, scale).applyAll(attributes)
404
405 def loadSingleSkinData(desktop, skin, path_prefix):
406         """loads skin data like colors, windowstyle etc."""
407         assert skin.tag == "skin", "root element in skin must be 'skin'!"
408         for c in skin.findall("output"):
409                 id = c.attrib.get('id')
410                 if id:
411                         id = int(id)
412                 else:
413                         id = 0
414                 if id == 0: # framebuffer
415                         for res in c.findall("resolution"):
416                                 get_attr = res.attrib.get
417                                 xres = get_attr("xres")
418                                 if xres:
419                                         xres = int(xres)
420                                 else:
421                                         xres = 720
422                                 yres = get_attr("yres")
423                                 if yres:
424                                         yres = int(yres)
425                                 else:
426                                         yres = 576
427                                 bpp = get_attr("bpp")
428                                 if bpp:
429                                         bpp = int(bpp)
430                                 else:
431                                         bpp = 32
432                                 #print "Resolution:", xres,yres,bpp
433                                 from enigma import gMainDC
434                                 gMainDC.getInstance().setResolution(xres, yres)
435                                 desktop.resize(eSize(xres, yres))
436                                 if bpp != 32:
437                                         # load palette (not yet implemented)
438                                         pass
439
440         for skininclude in skin.findall("include"):
441                 filename = skininclude.attrib.get("filename")
442                 if filename:
443                         skinfile = resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix)
444                         if not fileExists(skinfile):
445                                 skinfile = resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix)
446                         if fileExists(skinfile):
447                                 print "[SKIN] loading include:", skinfile
448                                 loadSkin(skinfile)
449
450         for c in skin.findall("colors"):
451                 for color in c.findall("color"):
452                         get_attr = color.attrib.get
453                         name = get_attr("name")
454                         color = get_attr("value")
455                         if name and color:
456                                 colorNames[name] = parseColor(color)
457                                 #print "Color:", name, color
458                         else:
459                                 raise SkinError("need color and name, got %s %s" % (name, color))
460
461         for c in skin.findall("fonts"):
462                 for font in c.findall("font"):
463                         get_attr = font.attrib.get
464                         filename = get_attr("filename", "<NONAME>")
465                         name = get_attr("name", "Regular")
466                         scale = get_attr("scale")
467                         if scale:
468                                 scale = int(scale)
469                         else:
470                                 scale = 100
471                         is_replacement = get_attr("replacement") and True or False
472                         render = get_attr("render")
473                         if render:
474                                 render = int(render)
475                         else:
476                                 render = 0
477                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
478                         if not fileExists(resolved_font): #when font is not available look at current skin path
479                                 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
480                                 if fileExists(skin_path):
481                                         resolved_font = skin_path
482                         addFont(resolved_font, name, scale, is_replacement, render)
483                         #print "Font: ", resolved_font, name, scale, is_replacement
484                 for alias in c.findall("alias"):
485                         get = alias.attrib.get
486                         try:
487                                 name = get("name")
488                                 font = get("font")
489                                 size = int(get("size"))
490                                 height = int(get("height", size)) # to be calculated some day
491                                 width = int(get("width", size))
492                                 global fonts
493                                 fonts[name] = (font, size, height, width)
494                         except Exception, ex:
495                                 print "[SKIN] bad font alias", ex
496
497         for c in skin.findall("parameters"):
498                 for parameter in c.findall("parameter"):
499                         get = parameter.attrib.get
500                         try:
501                                 name = get("name")
502                                 value = get("value")
503                                 parameters[name] = map(int, value.split(","))
504                         except Exception, ex:
505                                 print "[SKIN] bad parameter", ex
506
507         for c in skin.findall("subtitles"):
508                 from enigma import eWidget, eSubtitleWidget
509                 scale = ((1,1),(1,1))
510                 for substyle in c.findall("sub"):
511                         get_attr = substyle.attrib.get
512                         font = parseFont(get_attr("font"), scale)
513                         col = get_attr("foregroundColor")
514                         if col:
515                                 foregroundColor = parseColor(col)
516                                 haveColor = 1
517                         else:
518                                 foregroundColor = gRGB(0xFFFFFF)
519                                 haveColor = 0
520                         col = get_attr("borderColor")
521                         if col:
522                                 borderColor = parseColor(col)
523                         else:
524                                 borderColor = gRGB(0)
525                         borderwidth = get_attr("borderWidth")
526                         if borderwidth is None:
527                                 # default: use a subtitle border
528                                 borderWidth = 3
529                         else:
530                                 borderWidth = int(borderwidth)
531                         face = eSubtitleWidget.__dict__[get_attr("name")]
532                         eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, borderColor, borderWidth)
533
534         for windowstyle in skin.findall("windowstyle"):
535                 style = eWindowStyleSkinned()
536                 style_id = windowstyle.attrib.get("id")
537                 if style_id:
538                         style_id = int(style_id)
539                 else:
540                         style_id = 0
541                 # defaults
542                 font = gFont("Regular", 20)
543                 offset = eSize(20, 5)
544                 for title in windowstyle.findall("title"):
545                         get_attr = title.attrib.get
546                         offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
547                         font = parseFont(get_attr("font"), ((1,1),(1,1)))
548
549                 style.setTitleFont(font);
550                 style.setTitleOffset(offset)
551                 #print "  ", font, offset
552                 for borderset in windowstyle.findall("borderset"):
553                         bsName = str(borderset.attrib.get("name"))
554                         for pixmap in borderset.findall("pixmap"):
555                                 get_attr = pixmap.attrib.get
556                                 bpName = get_attr("pos")
557                                 filename = get_attr("filename")
558                                 if filename and bpName:
559                                         png = loadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, filename, path_prefix=path_prefix), desktop)
560                                         style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
561                                 #print "  borderset:", bpName, filename
562                 for color in windowstyle.findall("color"):
563                         get_attr = color.attrib.get
564                         colorType = get_attr("name")
565                         color = parseColor(get_attr("color"))
566                         try:
567                                 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
568                         except:
569                                 raise SkinError("Unknown color %s" % (colorType))
570                                 #pass
571                         #print "  color:", type, color
572                 x = eWindowStyleManager.getInstance()
573                 x.setStyle(style_id, style)
574         for margin in skin.findall("margin"):
575                 style_id = margin.attrib.get("id")
576                 if style_id:
577                         style_id = int(style_id)
578                 else:
579                         style_id = 0
580                 r = eRect(0,0,0,0)
581                 v = margin.attrib.get("left")
582                 if v:
583                         r.setLeft(int(v))
584                 v = margin.attrib.get("top")
585                 if v:
586                         r.setTop(int(v))
587                 v = margin.attrib.get("right")
588                 if v:
589                         r.setRight(int(v))
590                 v = margin.attrib.get("bottom")
591                 if v:
592                         r.setBottom(int(v))
593                 # the "desktop" parameter is hardcoded to the UI screen, so we must ask
594                 # for the one that this actually applies to.
595                 getDesktop(style_id).setMargins(r)
596
597 dom_screens = {}
598
599 def loadSkin(name, scope = SCOPE_SKIN):
600         # Now a utility for plugins to add skin data to the screens
601         global dom_screens, display_skin_id
602         filename = resolveFilename(scope, name)
603         if fileExists(filename):
604                 path = os.path.dirname(filename) + "/"
605                 for elem in xml.etree.cElementTree.parse(filename).getroot():
606                         if elem.tag == 'screen':
607                                 name = elem.attrib.get('name', None)
608                                 if name:
609                                         sid = elem.attrib.get('id', None)
610                                         if sid and (sid != display_skin_id):
611                                                 # not for this display
612                                                 elem.clear()
613                                                 continue
614                                         if name in dom_screens:
615                                                 print "loadSkin: Screen already defined elsewhere:", name
616                                                 elem.clear()
617                                         else:
618                                                 dom_screens[name] = (elem, path)
619                                 else:
620                                         elem.clear()
621                         else:
622                                 elem.clear()
623
624 def loadSkinData(desktop):
625         # Kinda hackish, but this is called once by mytest.py
626         global dom_skins
627         skins = dom_skins[:]
628         skins.reverse()
629         for (path, dom_skin) in skins:
630                 loadSingleSkinData(desktop, dom_skin, path)
631                 for elem in dom_skin:
632                         if elem.tag == 'screen':
633                                 name = elem.attrib.get('name', None)
634                                 if name:
635                                         sid = elem.attrib.get('id', None)
636                                         if sid and (sid != display_skin_id):
637                                                 # not for this display
638                                                 elem.clear()
639                                                 continue
640                                         if name in dom_screens:
641                                                 # Kill old versions, save memory
642                                                 dom_screens[name][0].clear()
643                                         dom_screens[name] = (elem, path)
644                                 else:
645                                         # without name, it's useless!
646                                         elem.clear()
647                         else:
648                                 # non-screen element, no need for it any longer
649                                 elem.clear()
650         # no longer needed, we know where the screens are now.
651         del dom_skins
652
653 class additionalWidget:
654         pass
655
656 # Class that makes a tuple look like something else. Some plugins just assume
657 # that size is a string and try to parse it. This class makes that work.
658 class SizeTuple(tuple):
659         def split(self, *args):
660                 return (str(self[0]), str(self[1]))
661         def strip(self, *args):
662                 return '%s,%s' % self
663         def __str__(self):
664                 return '%s,%s' % self
665
666 class SkinContext:
667         def __init__(self, parent=None, pos=None, size=None, font=None):
668                 if parent is not None:
669                         if pos is not None:
670                                 pos, size = parent.parse(pos, size, font)
671                                 self.x, self.y = pos
672                                 self.w, self.h = size
673                         else:
674                                 self.x = None
675                                 self.y = None
676                                 self.w = None
677                                 self.h = None
678         def __str__(self):
679                 return "Context (%s,%s)+(%s,%s) " % (self.x, self.y, self.w, self.h)
680         def parse(self, pos, size, font):
681                 if pos == "fill":
682                         pos = (self.x, self.y)
683                         size = (self.w, self.h)
684                         self.w = 0
685                         self.h = 0
686                 else:
687                         w,h = size.split(',')
688                         w = parseCoordinate(w, self.w, 0, font)
689                         h = parseCoordinate(h, self.h, 0, font)
690                         if pos == "bottom":
691                                 pos = (self.x, self.y + self.h - h)
692                                 size = (self.w, h)
693                                 self.h -= h
694                         elif pos == "top":
695                                 pos = (self.x, self.y)
696                                 size = (self.w, h)
697                                 self.h -= h
698                                 self.y += h
699                         elif pos == "left":
700                                 pos = (self.x, self.y)
701                                 size = (w, self.h)
702                                 self.x += w
703                                 self.w -= w
704                         elif pos == "right":
705                                 pos = (self.x + self.w - w, self.y)
706                                 size = (w, self.h)
707                                 self.w -= w
708                         else:
709                                 size = (w, h)
710                                 pos = pos.split(',')
711                                 pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font))
712                 return (SizeTuple(pos), SizeTuple(size))
713
714 class SkinContextStack(SkinContext):
715         # A context that stacks things instead of aligning them
716         def parse(self, pos, size, font):
717                 if pos == "fill":
718                         pos = (self.x, self.y)
719                         size = (self.w, self.h)
720                 else:
721                         w,h = size.split(',')
722                         w = parseCoordinate(w, self.w, 0, font)
723                         h = parseCoordinate(h, self.h, 0, font)
724                         if pos == "bottom":
725                                 pos = (self.x, self.y + self.h - h)
726                                 size = (self.w, h)
727                         elif pos == "top":
728                                 pos = (self.x, self.y)
729                                 size = (self.w, h)
730                         elif pos == "left":
731                                 pos = (self.x, self.y)
732                                 size = (w, self.h)
733                         elif pos == "right":
734                                 pos = (self.x + self.w - w, self.y)
735                                 size = (w, self.h)
736                         else:
737                                 size = (w, h)
738                                 pos = pos.split(',')
739                                 pos = (self.x + parseCoordinate(pos[0], self.w, size[0], font), self.y + parseCoordinate(pos[1], self.h, size[1], font))
740                 return (SizeTuple(pos), SizeTuple(size))
741
742 def readSkin(screen, skin, names, desktop):
743         if not isinstance(names, list):
744                 names = [names]
745
746         # try all skins, first existing one have priority
747         global dom_screens
748         for n in names:
749                 myscreen, path = dom_screens.get(n, (None,None))
750                 if myscreen is not None:
751                         # use this name for debug output
752                         name = n
753                         break
754         else:
755                 name = "<embedded-in-'%s'>" % screen.__class__.__name__
756
757         # otherwise try embedded skin
758         if myscreen is None:
759                 myscreen = getattr(screen, "parsedSkin", None)
760
761         # try uncompiled embedded skin
762         if myscreen is None and getattr(screen, "skin", None):
763                 skin = screen.skin
764                 print "[SKIN] Parsing embedded skin", name
765                 if (isinstance(skin, tuple)):
766                         for s in skin:
767                                 candidate = xml.etree.cElementTree.fromstring(s)
768                                 if candidate.tag == 'screen':
769                                         sid = candidate.attrib.get('id', None)
770                                         if (not sid) or (int(sid) == display_skin_id):
771                                                 myscreen = candidate
772                                                 break;
773                         else:
774                                 print "[SKIN] Hey, no suitable screen!"
775                 else:
776                         myscreen = xml.etree.cElementTree.fromstring(skin)
777                 if myscreen:
778                         screen.parsedSkin = myscreen
779         if myscreen is None:
780                 print "[SKIN] No skin to read..."
781                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring("<screen></screen>")
782
783         screen.skinAttributes = [ ]
784         skin_path_prefix = getattr(screen, "skin_path", path)
785
786         context = SkinContextStack()
787         s = desktop.bounds()
788         context.x = s.left()
789         context.y = s.top()
790         context.w = s.width()
791         context.h = s.height()
792         del s
793         collectAttributes(screen.skinAttributes, myscreen, context, skin_path_prefix, ignore=("name",))
794         context = SkinContext(context, myscreen.attrib.get('position'), myscreen.attrib.get('size'))
795
796         screen.additionalWidgets = [ ]
797         screen.renderer = [ ]
798         visited_components = set()
799
800         # now walk all widgets and stuff
801         def process_none(widget, context):
802                 pass
803
804         def process_widget(widget, context):
805                 get_attr = widget.attrib.get
806                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
807                 # widgets (source->renderer).
808                 wname = get_attr('name')
809                 wsource = get_attr('source')
810                 if wname is None and wsource is None:
811                         print "widget has no name and no source!"
812                         return
813                 if wname:
814                         #print "Widget name=", wname
815                         visited_components.add(wname)
816                         # get corresponding 'gui' object
817                         try:
818                                 attributes = screen[wname].skinAttributes = [ ]
819                         except:
820                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
821                         # assert screen[wname] is not Source
822                         collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('name',))
823                 elif wsource:
824                         # get corresponding source
825                         #print "Widget source=", wsource
826                         while True: # until we found a non-obsolete source
827                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
828                                 # for example to reference a parent, global or session-global screen.
829                                 scr = screen
830                                 # resolve all path components
831                                 path = wsource.split('.')
832                                 while len(path) > 1:
833                                         scr = screen.getRelatedScreen(path[0])
834                                         if scr is None:
835                                                 #print wsource
836                                                 #print name
837                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
838                                         path = path[1:]
839                                 # resolve the source.
840                                 source = scr.get(path[0])
841                                 if isinstance(source, ObsoleteSource):
842                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
843                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
844                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
845                                         if source.description:
846                                                 print source.description
847                                         wsource = source.new_source
848                                 else:
849                                         # otherwise, use that source.
850                                         break
851
852                         if source is None:
853                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
854
855                         wrender = get_attr('render')
856                         if not wrender:
857                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
858                         for converter in widget.findall("convert"):
859                                 ctype = converter.get('type')
860                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
861                                 #print "Converter:", ctype
862                                 try:
863                                         parms = converter.text.strip()
864                                 except:
865                                         parms = ""
866                                 #print "Params:", parms
867                                 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
868                                 c = None
869                                 for i in source.downstream_elements:
870                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
871                                                 c = i
872                                 if c is None:
873                                         c = converter_class(parms)
874                                         c.connect(source)
875                                 source = c
876
877                         renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
878                         renderer = renderer_class() # instantiate renderer
879                         renderer.connect(source) # connect to source
880                         attributes = renderer.skinAttributes = [ ]
881                         collectAttributes(attributes, widget, context, skin_path_prefix, ignore=('render', 'source'))
882                         screen.renderer.append(renderer)
883
884         def process_applet(widget, context):
885                 try:
886                         codeText = widget.text.strip()
887                         widgetType = widget.attrib.get('type')
888                         code = compile(codeText, "skin applet", "exec")
889                 except Exception, ex:
890                         raise SkinError("applet failed to compile: " + str(ex))
891                 if widgetType == "onLayoutFinish":
892                         screen.onLayoutFinish.append(code)
893                 else:
894                         raise SkinError("applet type '%s' unknown!" % widgetType)
895
896         def process_elabel(widget, context):
897                 w = additionalWidget()
898                 w.widget = eLabel
899                 w.skinAttributes = [ ]
900                 collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',))
901                 screen.additionalWidgets.append(w)
902
903         def process_epixmap(widget, context):
904                 w = additionalWidget()
905                 w.widget = ePixmap
906                 w.skinAttributes = [ ]
907                 collectAttributes(w.skinAttributes, widget, context, skin_path_prefix, ignore=('name',))
908                 screen.additionalWidgets.append(w)
909
910         def process_screen(widget, context):
911                 for w in widget.getchildren():
912                         conditional = w.attrib.get('conditional')
913                         if conditional and not [i for i in conditional.split(",") if i in screen.keys()]:
914                                 continue
915                         p = processors.get(w.tag, process_none)
916                         try:
917                                 p(w, context)
918                         except SkinError, e:
919                                 print "[Skin] SKIN ERROR in screen '%s' widget '%s':" % (name, w.tag), e
920
921         def process_panel(widget, context):
922                 n = widget.attrib.get('name')
923                 if n:
924                         try:
925                                 s = dom_screens[n]
926                         except KeyError:
927                                 print "[SKIN] Unable to find screen '%s' referred in screen '%s'" % (n, name)
928                         else:
929                                 process_screen(s[0], context)
930                 layout = widget.attrib.get('layout')
931                 if layout == 'stack':
932                         cc = SkinContextStack
933                 else:
934                         cc = SkinContext
935                 try:
936                         c = cc(context, widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font'))
937                 except Exception, ex:
938                         raise SkinError("Failed to create skincontext (%s,%s,%s) in %s: %s" % (widget.attrib.get('position'), widget.attrib.get('size'), widget.attrib.get('font'), context, ex) )
939                 process_screen(widget, c)
940
941         processors = {
942                 None: process_none,
943                 "widget": process_widget,
944                 "applet": process_applet,
945                 "eLabel": process_elabel,
946                 "ePixmap": process_epixmap,
947                 "panel": process_panel
948         }
949
950         try:
951                 context.x = 0 # reset offsets, all components are relative to screen
952                 context.y = 0 # coordinates.
953                 process_screen(myscreen, context)
954         except Exception, e:
955                 print "[Skin] SKIN ERROR in %s:" % name, e
956
957         from Components.GUIComponent import GUIComponent
958         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
959         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
960         # This may look pointless, but it unbinds 'screen' from the nested scope. A better
961         # solution is to avoid the nested scope above and use the context object to pass
962         # things around.
963         screen = None
964         visited_components = None