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