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