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