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 == "scale":
149 guiObject.setScale(1)
150 elif attrib == "orientation": # used by eSlider
152 guiObject.setOrientation(*
153 { "orVertical": (guiObject.orVertical, False),
154 "orTopToBottom": (guiObject.orVertical, False),
155 "orBottomToTop": (guiObject.orVertical, True),
156 "orHorizontal": (guiObject.orHorizontal, False),
157 "orLeftToRight": (guiObject.orHorizontal, False),
158 "orRightToLeft": (guiObject.orHorizontal, True),
161 print "oprientation must be either orVertical or orHorizontal!"
162 elif attrib == "valign":
165 { "top": guiObject.alignTop,
166 "center": guiObject.alignCenter,
167 "bottom": guiObject.alignBottom
170 print "valign must be either top, center or bottom!"
171 elif attrib == "halign":
174 { "left": guiObject.alignLeft,
175 "center": guiObject.alignCenter,
176 "right": guiObject.alignRight,
177 "block": guiObject.alignBlock
180 print "halign must be either left, center, right or block!"
181 elif attrib == "flags":
182 flags = value.split(',')
185 fv = eWindow.__dict__[f]
186 guiObject.setFlag(fv)
188 print "illegal flag %s!" % f
189 elif attrib == "backgroundColor":
190 guiObject.setBackgroundColor(parseColor(value))
191 elif attrib == "backgroundColorSelected":
192 guiObject.setBackgroundColorSelected(parseColor(value))
193 elif attrib == "foregroundColor":
194 guiObject.setForegroundColor(parseColor(value))
195 elif attrib == "foregroundColorSelected":
196 guiObject.setForegroundColorSelected(parseColor(value))
197 elif attrib == "shadowColor":
198 guiObject.setShadowColor(parseColor(value))
199 elif attrib == "selectionDisabled":
200 guiObject.setSelectionEnable(0)
201 elif attrib == "transparent":
202 guiObject.setTransparent(int(value))
203 elif attrib == "borderColor":
204 guiObject.setBorderColor(parseColor(value))
205 elif attrib == "borderWidth":
206 guiObject.setBorderWidth(int(value))
207 elif attrib == "scrollbarMode":
208 guiObject.setScrollbarMode(
209 { "showOnDemand": guiObject.showOnDemand,
210 "showAlways": guiObject.showAlways,
211 "showNever": guiObject.showNever
213 elif attrib == "enableWrapAround":
214 guiObject.setWrapAround(True)
215 elif attrib == "pointer" or attrib == "seek_pointer":
216 (name, pos) = value.split(':')
217 pos = parsePosition(pos, scale)
218 ptr = loadPixmap(name, desktop)
219 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
220 elif attrib == 'shadowOffset':
221 guiObject.setShadowOffset(parsePosition(value, scale))
222 elif attrib == 'noWrap':
223 guiObject.setNoWrap(1)
225 raise SkinError("unsupported attribute " + attrib + "=" + value)
228 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
230 def applyAllAttributes(guiObject, desktop, attributes, scale):
231 for (attrib, value) in attributes:
232 applySingleAttribute(guiObject, desktop, attrib, value, scale)
234 def loadSingleSkinData(desktop, skin, path_prefix):
235 """loads skin data like colors, windowstyle etc."""
236 assert skin.tag == "skin", "root element in skin must be 'skin'!"
238 #print "***SKIN: ", path_prefix
240 for c in skin.findall("output"):
241 id = c.attrib.get('id')
246 if id == 0: # framebuffer
247 for res in c.findall("resolution"):
248 get_attr = res.attrib.get
249 xres = get_attr("xres")
254 yres = get_attr("yres")
259 bpp = get_attr("bpp")
264 #print "Resolution:", xres,yres,bpp
265 from enigma import gFBDC
266 gFBDC.getInstance().setResolution(xres, yres)
267 desktop.resize(eSize(xres, yres))
269 # load palette (not yet implemented)
272 for c in skin.findall("colors"):
273 for color in c.findall("color"):
274 get_attr = color.attrib.get
275 name = get_attr("name")
276 color = get_attr("value")
278 colorNames[name] = parseColor(color)
279 #print "Color:", name, color
281 raise SkinError("need color and name, got %s %s" % (name, color))
283 for c in skin.findall("fonts"):
284 for font in c.findall("font"):
285 get_attr = font.attrib.get
286 filename = get_attr("filename", "<NONAME>")
287 name = get_attr("name", "Regular")
288 scale = get_attr("scale")
293 is_replacement = get_attr("replacement") and True or False
294 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
295 if not fileExists(resolved_font): #when font is not available look at current skin path
296 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
297 if fileExists(skin_path):
298 resolved_font = skin_path
299 addFont(resolved_font, name, scale, is_replacement)
300 #print "Font: ", resolved_font, name, scale, is_replacement
302 for c in skin.findall("subtitles"):
303 from enigma import eWidget, eSubtitleWidget
304 scale = ((1,1),(1,1))
305 for substyle in c.findall("sub"):
306 get_attr = substyle.attrib.get
307 font = parseFont(get_attr("font"), scale)
308 col = get_attr("foregroundColor")
310 foregroundColor = parseColor(col)
313 foregroundColor = gRGB(0xFFFFFF)
315 col = get_attr("shadowColor")
317 shadowColor = parseColor(col)
319 shadowColor = gRGB(0)
320 shadowOffset = parsePosition(get_attr("shadowOffset"), scale)
321 face = eSubtitleWidget.__dict__[get_attr("name")]
322 eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, shadowColor, shadowOffset)
324 for windowstyle in skin.findall("windowstyle"):
325 style = eWindowStyleSkinned()
326 id = windowstyle.attrib.get("id")
331 #print "windowstyle:", id
334 font = gFont("Regular", 20)
335 offset = eSize(20, 5)
337 for title in windowstyle.findall("title"):
338 get_attr = title.attrib.get
339 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
340 font = parseFont(get_attr("font"), ((1,1),(1,1)))
342 style.setTitleFont(font);
343 style.setTitleOffset(offset)
344 #print " ", font, offset
346 for borderset in windowstyle.findall("borderset"):
347 bsName = str(borderset.attrib.get("name"))
348 for pixmap in borderset.findall("pixmap"):
349 get_attr = pixmap.attrib.get
350 bpName = get_attr("pos")
351 filename = get_attr("filename")
352 if filename and bpName:
353 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
354 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
355 #print " borderset:", bpName, filename
357 for color in windowstyle.findall("color"):
358 get_attr = color.attrib.get
359 colorType = get_attr("name")
360 color = parseColor(get_attr("color"))
362 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
364 raise SkinError("Unknown color %s" % (colorType))
367 #print " color:", type, color
369 x = eWindowStyleManager.getInstance()
370 x.setStyle(id, style)
372 def loadSkinData(desktop):
375 for (path, dom_skin) in skins:
376 loadSingleSkinData(desktop, dom_skin, path)
378 def lookupScreen(name):
379 for (path, skin) in dom_skins:
380 # first, find the corresponding screen element
381 for x in skin.findall("screen"):
382 if x.attrib.get('name', '') == name:
386 class additionalWidget:
389 def readSkin(screen, skin, names, desktop):
390 if not isinstance(names, list):
393 name = "<embedded-in-'%s'>" % screen.__class__.__name__
395 # try all skins, first existing one have priority
397 myscreen, path = lookupScreen(n)
398 if myscreen is not None:
399 # use this name for debug output
403 # otherwise try embedded skin
405 myscreen = getattr(screen, "parsedSkin", None)
407 # try uncompiled embedded skin
408 if myscreen is None and getattr(screen, "skin", None):
409 print "Looking for embedded skin"
410 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
412 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
414 print "No skin to read..."
415 emptySkin = "<screen></screen>"
416 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
418 screen.skinAttributes = [ ]
420 skin_path_prefix = getattr(screen, "skin_path", path)
422 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
424 screen.additionalWidgets = [ ]
425 screen.renderer = [ ]
427 visited_components = set()
429 # now walk all widgets
430 for widget in myscreen.findall("widget"):
431 get_attr = widget.attrib.get
432 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
433 # widgets (source->renderer).
435 wname = get_attr('name')
436 wsource = get_attr('source')
438 if wname is None and wsource is None:
439 print "widget has no name and no source!"
443 #print "Widget name=", wname
444 visited_components.add(wname)
446 # get corresponding 'gui' object
448 attributes = screen[wname].skinAttributes = [ ]
450 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
451 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
453 # assert screen[wname] is not Source
455 # and collect attributes for this
456 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
458 # get corresponding source
459 #print "Widget source=", wsource
461 while True: # until we found a non-obsolete source
463 # parse our current "wsource", which might specifiy a "related screen" before the dot,
464 # for example to reference a parent, global or session-global screen.
467 # resolve all path components
468 path = wsource.split('.')
470 scr = screen.getRelatedScreen(path[0])
474 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
477 # resolve the source.
478 source = scr.get(path[0])
479 if isinstance(source, ObsoleteSource):
480 # however, if we found an "obsolete source", issue warning, and resolve the real source.
481 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
482 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
483 if source.description:
484 print source.description
486 wsource = source.new_source
488 # otherwise, use that source.
492 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
494 wrender = get_attr('render')
497 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
499 for converter in widget.findall("convert"):
500 ctype = converter.get('type')
501 assert ctype, "'convert'-tag needs a 'type'-attribute"
502 #print "Converter:", ctype
504 parms = converter.text.strip()
507 #print "Params:", parms
508 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
512 for i in source.downstream_elements:
513 if isinstance(i, converter_class) and i.converter_arguments == parms:
517 print "allocating new converter!"
518 c = converter_class(parms)
521 print "reused converter!"
525 renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
527 renderer = renderer_class() # instantiate renderer
529 renderer.connect(source) # connect to source
530 attributes = renderer.skinAttributes = [ ]
531 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
533 screen.renderer.append(renderer)
535 from Components.GUIComponent import GUIComponent
536 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
537 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
539 # now walk additional objects
540 for widget in myscreen.getchildren():
543 if w_tag == "widget":
546 if w_tag == "applet":
548 codeText = widget.text.strip()
554 widgetType = widget.attrib.get('type')
556 code = compile(codeText, "skin applet", "exec")
558 if widgetType == "onLayoutFinish":
559 screen.onLayoutFinish.append(code)
560 #print "onLayoutFinish = ", codeText
562 raise SkinError("applet type '%s' unknown!" % widgetType)
563 #print "applet type '%s' unknown!" % type
567 w = additionalWidget()
569 if w_tag == "eLabel":
571 elif w_tag == "ePixmap":
574 raise SkinError("unsupported stuff : %s" % w_tag)
575 #print "unsupported stuff : %s" % widget.tag
577 w.skinAttributes = [ ]
578 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
580 # applyAttributes(guiObject, widget, desktop)
581 # guiObject.thisown = 0
582 screen.additionalWidgets.append(w)