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