1 from Tools.Profile import profile
2 profile("LOAD:ElementTree")
3 import xml.etree.cElementTree
6 profile("LOAD:enigma_skin")
7 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
8 addFont, gRGB, eWindowStyleSkinned
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
19 print " " * i + str(x)
21 for n in x.childNodes:
26 class SkinError(Exception):
27 def __init__(self, message):
31 return "{%s}: %s" % (config.skin.primary_skin, self.msg)
35 def loadSkin(name, scope = SCOPE_SKIN):
37 filename = resolveFilename(scope, name)
38 mpath = path.dirname(filename) + "/"
39 dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
41 # we do our best to always select the "right" value
42 # skins are loaded in order of priority: skin with
43 # highest priority is loaded last, usually the user-provided
46 # currently, loadSingleSkinData (colors, bordersets etc.)
47 # are applied one-after-each, in order of ascending priority.
48 # the dom_skin will keep all screens in descending priority,
49 # so the first screen found will be used.
51 # example: loadSkin("nemesis_greenline/skin.xml")
52 config.skin = ConfigSubsection()
53 config.skin.primary_skin = ConfigText(default = "skin.xml")
57 loadSkin('skin_user.xml', SCOPE_CONFIG)
58 except (SkinError, IOError, AssertionError), err:
59 print "not loading user skin: ", err
62 loadSkin(config.skin.primary_skin.value)
63 except (SkinError, IOError, AssertionError), err:
64 print "SKIN ERROR:", err
65 print "defaulting to standard skin..."
66 config.skin.primary_skin.value = 'skin.xml'
69 profile("LoadSkinDefault")
70 loadSkin('skin_default.xml')
71 profile("LoadSkinDefaultDone")
73 def parsePosition(str, scale):
75 return ePoint(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
77 def parseSize(str, scale):
79 return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
81 def parseFont(str, scale):
82 name, size = str.split(';')
83 return gFont(name, int(size) * scale[0][0] / scale[0][1])
88 return colorNames[str]
90 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
91 return gRGB(int(str[1:], 0x10))
93 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
95 for a in node.items():
100 if attrib in ("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"):
101 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
103 if attrib not in ignore:
104 skinAttributes.append((attrib, value))
106 def loadPixmap(path, desktop):
108 option = path.find("#")
110 options = path[option+1:].split(',')
112 cached = "cached" in options
113 ptr = LoadPixmap(path, desktop, cached)
115 raise SkinError("pixmap file %s not found!" % (path))
118 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
121 if attrib == 'position':
122 guiObject.move(parsePosition(value, scale))
123 elif attrib == 'size':
124 guiObject.resize(parseSize(value, scale))
125 elif attrib == 'title':
126 guiObject.setTitle(_(value))
127 elif attrib == 'text':
128 guiObject.setText(_(value))
129 elif attrib == 'font':
130 guiObject.setFont(parseFont(value, scale))
131 elif attrib == 'zPosition':
132 guiObject.setZPosition(int(value))
133 elif attrib in ("pixmap", "backgroundPixmap", "selectionPixmap"):
134 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
135 if attrib == "pixmap":
136 guiObject.setPixmap(ptr)
137 elif attrib == "backgroundPixmap":
138 guiObject.setBackgroundPicture(ptr)
139 elif attrib == "selectionPixmap":
140 guiObject.setSelectionPicture(ptr)
141 # guiObject.setPixmapFromFile(value)
142 elif attrib == "alphatest": # used by ePixmap
143 guiObject.setAlphatest(
148 elif attrib == "orientation": # used by eSlider
150 guiObject.setOrientation(*
151 { "orVertical": (guiObject.orVertical, False),
152 "orTopToBottom": (guiObject.orVertical, False),
153 "orBottomToTop": (guiObject.orVertical, True),
154 "orHorizontal": (guiObject.orHorizontal, False),
155 "orLeftToRight": (guiObject.orHorizontal, False),
156 "orRightToLeft": (guiObject.orHorizontal, True),
159 print "oprientation must be either orVertical or orHorizontal!"
160 elif attrib == "valign":
163 { "top": guiObject.alignTop,
164 "center": guiObject.alignCenter,
165 "bottom": guiObject.alignBottom
168 print "valign must be either top, center or bottom!"
169 elif attrib == "halign":
172 { "left": guiObject.alignLeft,
173 "center": guiObject.alignCenter,
174 "right": guiObject.alignRight,
175 "block": guiObject.alignBlock
178 print "halign must be either left, center, right or block!"
179 elif attrib == "flags":
180 flags = value.split(',')
183 fv = eWindow.__dict__[f]
184 guiObject.setFlag(fv)
186 print "illegal flag %s!" % f
187 elif attrib == "backgroundColor":
188 guiObject.setBackgroundColor(parseColor(value))
189 elif attrib == "backgroundColorSelected":
190 guiObject.setBackgroundColorSelected(parseColor(value))
191 elif attrib == "foregroundColor":
192 guiObject.setForegroundColor(parseColor(value))
193 elif attrib == "foregroundColorSelected":
194 guiObject.setForegroundColorSelected(parseColor(value))
195 elif attrib == "shadowColor":
196 guiObject.setShadowColor(parseColor(value))
197 elif attrib == "selectionDisabled":
198 guiObject.setSelectionEnable(0)
199 elif attrib == "transparent":
200 guiObject.setTransparent(int(value))
201 elif attrib == "borderColor":
202 guiObject.setBorderColor(parseColor(value))
203 elif attrib == "borderWidth":
204 guiObject.setBorderWidth(int(value))
205 elif attrib == "scrollbarMode":
206 guiObject.setScrollbarMode(
207 { "showOnDemand": guiObject.showOnDemand,
208 "showAlways": guiObject.showAlways,
209 "showNever": guiObject.showNever
211 elif attrib == "enableWrapAround":
212 guiObject.setWrapAround(True)
213 elif attrib == "pointer" or attrib == "seek_pointer":
214 (name, pos) = value.split(':')
215 pos = parsePosition(pos, scale)
216 ptr = loadPixmap(name, desktop)
217 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
218 elif attrib == 'shadowOffset':
219 guiObject.setShadowOffset(parsePosition(value, scale))
220 elif attrib == 'noWrap':
221 guiObject.setNoWrap(1)
223 raise SkinError("unsupported attribute " + attrib + "=" + value)
226 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
228 def applyAllAttributes(guiObject, desktop, attributes, scale):
229 for (attrib, value) in attributes:
230 applySingleAttribute(guiObject, desktop, attrib, value, scale)
232 def loadSingleSkinData(desktop, skin, path_prefix):
233 """loads skin data like colors, windowstyle etc."""
234 assert skin.tag == "skin", "root element in skin must be 'skin'!"
236 #print "***SKIN: ", path_prefix
238 for c in skin.findall("output"):
239 id = c.attrib.get('id')
244 if id == 0: # framebuffer
245 for res in c.findall("resolution"):
246 get_attr = res.attrib.get
247 xres = get_attr("xres")
252 yres = get_attr("yres")
257 bpp = get_attr("bpp")
262 #print "Resolution:", xres,yres,bpp
263 from enigma import gFBDC
264 gFBDC.getInstance().setResolution(xres, yres)
265 desktop.resize(eSize(xres, yres))
267 # load palette (not yet implemented)
270 for c in skin.findall("colors"):
271 for color in c.findall("color"):
272 get_attr = color.attrib.get
273 name = get_attr("name")
274 color = get_attr("value")
276 colorNames[name] = parseColor(color)
277 #print "Color:", name, color
279 raise SkinError("need color and name, got %s %s" % (name, color))
281 for c in skin.findall("fonts"):
282 for font in c.findall("font"):
283 get_attr = font.attrib.get
284 filename = get_attr("filename", "<NONAME>")
285 name = get_attr("name", "Regular")
286 scale = get_attr("scale")
291 is_replacement = get_attr("replacement") and True or False
292 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
293 if not fileExists(resolved_font): #when font is not available look at current skin path
294 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
295 if fileExists(skin_path):
296 resolved_font = skin_path
297 addFont(resolved_font, name, scale, is_replacement)
298 #print "Font: ", resolved_font, name, scale, is_replacement
300 for c in skin.findall("subtitles"):
301 from enigma import eWidget, eSubtitleWidget
302 scale = ((1,1),(1,1))
303 for substyle in c.findall("sub"):
304 get_attr = substyle.attrib.get
305 font = parseFont(get_attr("font"), scale)
306 col = get_attr("foregroundColor")
308 foregroundColor = parseColor(col)
311 foregroundColor = gRGB(0xFFFFFF)
313 col = get_attr("shadowColor")
315 shadowColor = parseColor(col)
317 shadowColor = gRGB(0)
318 shadowOffset = parsePosition(get_attr("shadowOffset"), scale)
319 face = eval("eSubtitleWidget.%s" % get_attr("name"))
320 eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, shadowColor, shadowOffset)
322 for windowstyle in skin.findall("windowstyle"):
323 style = eWindowStyleSkinned()
324 id = windowstyle.attrib.get("id")
329 #print "windowstyle:", id
332 font = gFont("Regular", 20)
333 offset = eSize(20, 5)
335 for title in windowstyle.findall("title"):
336 get_attr = title.attrib.get
337 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
338 font = parseFont(get_attr("font"), ((1,1),(1,1)))
340 style.setTitleFont(font);
341 style.setTitleOffset(offset)
342 #print " ", font, offset
344 for borderset in windowstyle.findall("borderset"):
345 bsName = str(borderset.attrib.get("name"))
346 for pixmap in borderset.findall("pixmap"):
347 get_attr = pixmap.attrib.get
348 bpName = get_attr("pos")
349 filename = get_attr("filename")
350 if filename and bpName:
351 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
352 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
353 #print " borderset:", bpName, filename
355 for color in windowstyle.findall("color"):
356 get_attr = color.attrib.get
357 colorType = get_attr("name")
358 color = parseColor(get_attr("color"))
360 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
362 raise SkinError("Unknown color %s" % (colorType))
365 #print " color:", type, color
367 x = eWindowStyleManager.getInstance()
368 x.setStyle(id, style)
370 def loadSkinData(desktop):
373 for (path, dom_skin) in skins:
374 loadSingleSkinData(desktop, dom_skin, path)
376 def lookupScreen(name):
377 for (path, skin) in dom_skins:
378 # first, find the corresponding screen element
379 for x in skin.findall("screen"):
380 if x.attrib.get('name', '') == name:
384 class additionalWidget:
387 def readSkin(screen, skin, names, desktop):
388 if not isinstance(names, list):
391 name = "<embedded-in-'%s'>" % screen.__class__.__name__
393 # try all skins, first existing one have priority
395 myscreen, path = lookupScreen(n)
396 if myscreen is not None:
397 # use this name for debug output
401 # otherwise try embedded skin
403 myscreen = getattr(screen, "parsedSkin", None)
405 # try uncompiled embedded skin
406 if myscreen is None and getattr(screen, "skin", None):
407 print "Looking for embedded skin"
408 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
410 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
412 print "No skin to read..."
413 emptySkin = "<screen></screen>"
414 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
416 screen.skinAttributes = [ ]
418 skin_path_prefix = getattr(screen, "skin_path", path)
420 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
422 screen.additionalWidgets = [ ]
423 screen.renderer = [ ]
425 visited_components = set()
427 # now walk all widgets
428 for widget in myscreen.findall("widget"):
429 get_attr = widget.attrib.get
430 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
431 # widgets (source->renderer).
433 wname = get_attr('name')
434 wsource = get_attr('source')
436 if wname is None and wsource is None:
437 print "widget has no name and no source!"
441 #print "Widget name=", wname
442 visited_components.add(wname)
444 # get corresponding 'gui' object
446 attributes = screen[wname].skinAttributes = [ ]
448 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
449 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
451 # assert screen[wname] is not Source
453 # and collect attributes for this
454 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
456 # get corresponding source
457 #print "Widget source=", wsource
459 while True: # until we found a non-obsolete source
461 # parse our current "wsource", which might specifiy a "related screen" before the dot,
462 # for example to reference a parent, global or session-global screen.
465 # resolve all path components
466 path = wsource.split('.')
468 scr = screen.getRelatedScreen(path[0])
472 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
475 # resolve the source.
476 source = scr.get(path[0])
477 if isinstance(source, ObsoleteSource):
478 # however, if we found an "obsolete source", issue warning, and resolve the real source.
479 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
480 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
481 if source.description:
482 print source.description
484 wsource = source.new_source
486 # otherwise, use that source.
490 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
492 wrender = get_attr('render')
495 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
497 for converter in widget.findall("convert"):
498 ctype = converter.get('type')
499 assert ctype, "'convert'-tag needs a 'type'-attribute"
500 #print "Converter:", ctype
502 parms = converter.text.strip()
505 #print "Params:", parms
506 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
510 for i in source.downstream_elements:
511 if isinstance(i, converter_class) and i.converter_arguments == parms:
515 print "allocating new converter!"
516 c = converter_class(parms)
519 print "reused converter!"
523 renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
525 renderer = renderer_class() # instantiate renderer
527 renderer.connect(source) # connect to source
528 attributes = renderer.skinAttributes = [ ]
529 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
531 screen.renderer.append(renderer)
533 from Components.GUIComponent import GUIComponent
534 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
535 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
537 # now walk additional objects
538 for widget in myscreen.getchildren():
541 if w_tag == "widget":
544 if w_tag == "applet":
546 codeText = widget.text.strip()
552 widgetType = widget.attrib.get('type')
554 code = compile(codeText, "skin applet", "exec")
556 if widgetType == "onLayoutFinish":
557 screen.onLayoutFinish.append(code)
558 #print "onLayoutFinish = ", codeText
560 raise SkinError("applet type '%s' unknown!" % widgetType)
561 #print "applet type '%s' unknown!" % type
565 w = additionalWidget()
567 if w_tag == "eLabel":
569 elif w_tag == "ePixmap":
572 raise SkinError("unsupported stuff : %s" % w_tag)
573 #print "unsupported stuff : %s" % widget.tag
575 w.skinAttributes = [ ]
576 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
578 # applyAttributes(guiObject, widget, desktop)
579 # guiObject.thisown = 0
580 screen.additionalWidgets.append(w)