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
10 from Components.config import ConfigSubsection, ConfigText, config
11 from Components.Converter.Converter import Converter
12 from Components.Sources.Source import Source, ObsoleteSource
13 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS, SCOPE_CURRENT_SKIN, fileExists
14 from Tools.Import import my_import
15 from Tools.LoadPixmap import LoadPixmap
20 print " " * i + str(x)
22 for n in x.childNodes:
27 class SkinError(Exception):
28 def __init__(self, message):
29 self.message = message
32 return "{%s}: %s" % (config.skin.primary_skin, self.message)
38 filename = resolveFilename(SCOPE_SKIN, name)
39 mpath = path.dirname(filename) + "/"
40 dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
42 # we do our best to always select the "right" value
43 # skins are loaded in order of priority: skin with
44 # highest priority is loaded last, usually the user-provided
47 # currently, loadSingleSkinData (colors, bordersets etc.)
48 # are applied one-after-each, in order of ascending priority.
49 # the dom_skin will keep all screens in descending priority,
50 # so the first screen found will be used.
52 # example: loadSkin("nemesis_greenline/skin.xml")
53 config.skin = ConfigSubsection()
54 config.skin.primary_skin = ConfigText(default = "skin.xml")
58 loadSkin(config.skin.primary_skin.value)
59 except (SkinError, IOError, AssertionError), err:
60 print "SKIN ERROR:", err
61 print "defaulting to standard skin..."
62 config.skin.primary_skin.value = 'skin.xml'
65 profile("LoadSkinDefault")
66 loadSkin('skin_default.xml')
67 profile("LoadSkinDefaultDone")
69 def parsePosition(str, scale):
71 return ePoint(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
73 def parseSize(str, scale):
75 return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
77 def parseFont(str, scale):
78 name, size = str.split(';')
79 return gFont(name, int(size) * scale[0][0] / scale[0][1])
84 return colorNames[str]
86 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
87 return gRGB(int(str[1:], 0x10))
89 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
91 for a in node.items():
96 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
97 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
99 if attrib not in ignore:
100 skinAttributes.append((attrib, value))
102 def loadPixmap(path, desktop):
104 option = path.find("#")
106 options = path[option+1:].split(',')
108 cached = "cached" in options
109 ptr = LoadPixmap(path, desktop, cached)
111 raise SkinError("pixmap file %s not found!" % (path))
114 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
117 if attrib == 'position':
118 guiObject.move(parsePosition(value, scale))
119 elif attrib == 'size':
120 guiObject.resize(parseSize(value, scale))
121 elif attrib == 'title':
122 guiObject.setTitle(_(value))
123 elif attrib == 'text':
124 guiObject.setText(_(value))
125 elif attrib == 'font':
126 guiObject.setFont(parseFont(value, scale))
127 elif attrib == 'zPosition':
128 guiObject.setZPosition(int(value))
129 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
130 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
131 if attrib == "pixmap":
132 guiObject.setPixmap(ptr)
133 elif attrib == "backgroundPixmap":
134 guiObject.setBackgroundPicture(ptr)
135 elif attrib == "selectionPixmap":
136 guiObject.setSelectionPicture(ptr)
137 # guiObject.setPixmapFromFile(value)
138 elif attrib == "alphatest": # used by ePixmap
139 guiObject.setAlphatest(
144 elif attrib == "orientation": # used by eSlider
146 guiObject.setOrientation(*
147 { "orVertical": (guiObject.orVertical, False),
148 "orTopToBottom": (guiObject.orVertical, False),
149 "orBottomToTop": (guiObject.orVertical, True),
150 "orHorizontal": (guiObject.orHorizontal, False),
151 "orLeftToRight": (guiObject.orHorizontal, False),
152 "orRightToLeft": (guiObject.orHorizontal, True),
155 print "oprientation must be either orVertical or orHorizontal!"
156 elif attrib == "valign":
159 { "top": guiObject.alignTop,
160 "center": guiObject.alignCenter,
161 "bottom": guiObject.alignBottom
164 print "valign must be either top, center or bottom!"
165 elif attrib == "halign":
168 { "left": guiObject.alignLeft,
169 "center": guiObject.alignCenter,
170 "right": guiObject.alignRight,
171 "block": guiObject.alignBlock
174 print "halign must be either left, center, right or block!"
175 elif attrib == "flags":
176 flags = value.split(',')
179 fv = eWindow.__dict__[f]
180 guiObject.setFlag(fv)
182 print "illegal flag %s!" % f
183 elif attrib == "backgroundColor":
184 guiObject.setBackgroundColor(parseColor(value))
185 elif attrib == "backgroundColorSelected":
186 guiObject.setBackgroundColorSelected(parseColor(value))
187 elif attrib == "foregroundColor":
188 guiObject.setForegroundColor(parseColor(value))
189 elif attrib == "foregroundColorSelected":
190 guiObject.setForegroundColorSelected(parseColor(value))
191 elif attrib == "shadowColor":
192 guiObject.setShadowColor(parseColor(value))
193 elif attrib == "selectionDisabled":
194 guiObject.setSelectionEnable(0)
195 elif attrib == "transparent":
196 guiObject.setTransparent(int(value))
197 elif attrib == "borderColor":
198 guiObject.setBorderColor(parseColor(value))
199 elif attrib == "borderWidth":
200 guiObject.setBorderWidth(int(value))
201 elif attrib == "scrollbarMode":
202 guiObject.setScrollbarMode(
203 { "showOnDemand": guiObject.showOnDemand,
204 "showAlways": guiObject.showAlways,
205 "showNever": guiObject.showNever
207 elif attrib == "enableWrapAround":
208 guiObject.setWrapAround(True)
209 elif attrib == "pointer" or attrib == "seek_pointer":
210 (name, pos) = value.split(':')
211 pos = parsePosition(pos, scale)
212 ptr = loadPixmap(name, desktop)
213 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
214 elif attrib == 'shadowOffset':
215 guiObject.setShadowOffset(parsePosition(value, scale))
216 elif attrib == 'noWrap':
217 guiObject.setNoWrap(1)
219 raise SkinError("unsupported attribute " + attrib + "=" + value)
222 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
224 def applyAllAttributes(guiObject, desktop, attributes, scale):
225 for (attrib, value) in attributes:
226 applySingleAttribute(guiObject, desktop, attrib, value, scale)
228 def loadSingleSkinData(desktop, skin, path_prefix):
229 """loads skin data like colors, windowstyle etc."""
230 assert skin.tag == "skin", "root element in skin must be 'skin'!"
232 #print "***SKIN: ", path_prefix
234 for c in skin.findall("output"):
235 id = c.attrib.get('id')
240 if id == 0: # framebuffer
241 for res in c.findall("resolution"):
242 get_attr = res.attrib.get
243 xres = get_attr("xres")
248 yres = get_attr("yres")
253 bpp = get_attr("bpp")
258 #print "Resolution:", xres,yres,bpp
259 from enigma import gFBDC
260 gFBDC.getInstance().setResolution(xres, yres)
261 desktop.resize(eSize(xres, yres))
263 # load palette (not yet implemented)
266 for c in skin.findall("colors"):
267 for color in c.findall("color"):
268 get_attr = color.attrib.get
269 name = get_attr("name")
270 color = get_attr("value")
272 colorNames[name] = parseColor(color)
273 #print "Color:", name, color
275 raise SkinError("need color and name, got %s %s" % (name, color))
277 for c in skin.findall("fonts"):
278 for font in c.findall("font"):
279 get_attr = font.attrib.get
280 filename = get_attr("filename", "<NONAME>")
281 name = get_attr("name", "Regular")
282 scale = get_attr("scale")
287 is_replacement = get_attr("replacement") and True or False
288 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
289 if not fileExists(resolved_font): #when font is not available look at current skin path
290 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
291 if fileExists(skin_path):
292 resolved_font = skin_path
293 addFont(resolved_font, name, scale, is_replacement)
294 #print "Font: ", resolved_font, name, scale, is_replacement
296 for windowstyle in skin.findall("windowstyle"):
297 style = eWindowStyleSkinned()
298 id = windowstyle.attrib.get("id")
303 #print "windowstyle:", id
306 font = gFont("Regular", 20)
307 offset = eSize(20, 5)
309 for title in windowstyle.findall("title"):
310 get_attr = title.attrib.get
311 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
312 font = parseFont(get_attr("font"), ((1,1),(1,1)))
314 style.setTitleFont(font);
315 style.setTitleOffset(offset)
316 #print " ", font, offset
318 for borderset in windowstyle.findall("borderset"):
319 bsName = str(borderset.attrib.get("name"))
320 for pixmap in borderset.findall("pixmap"):
321 get_attr = pixmap.attrib.get
322 bpName = get_attr("pos")
323 filename = get_attr("filename")
324 if filename and bpName:
325 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
326 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
327 #print " borderset:", bpName, filename
329 for color in windowstyle.findall("color"):
330 get_attr = color.attrib.get
331 type = get_attr("name")
332 color = parseColor(get_attr("color"))
334 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
336 raise SkinError("Unknown color %s" % (type))
339 #print " color:", type, color
341 x = eWindowStyleManager.getInstance()
342 x.setStyle(id, style)
344 def loadSkinData(desktop):
347 for (path, dom_skin) in skins:
348 loadSingleSkinData(desktop, dom_skin, path)
350 def lookupScreen(name):
351 for (path, skin) in dom_skins:
352 # first, find the corresponding screen element
353 for x in skin.findall("screen"):
354 if x.attrib.get('name', '') == name:
358 class additionalWidget:
361 def readSkin(screen, skin, names, desktop):
362 if not isinstance(names, list):
365 name = "<embedded-in-'%s'>" % screen.__class__.__name__
367 # try all skins, first existing one have priority
369 myscreen, path = lookupScreen(n)
370 if myscreen is not None:
371 # use this name for debug output
375 # otherwise try embedded skin
377 myscreen = getattr(screen, "parsedSkin", None)
379 # try uncompiled embedded skin
380 if myscreen is None and getattr(screen, "skin", None):
381 print "Looking for embedded skin"
382 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
384 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
386 print "No skin to read..."
387 emptySkin = "<screen></screen>"
388 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
390 screen.skinAttributes = [ ]
392 skin_path_prefix = getattr(screen, "skin_path", path)
394 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
396 screen.additionalWidgets = [ ]
397 screen.renderer = [ ]
399 visited_components = set()
401 # now walk all widgets
402 for widget in myscreen.findall("widget"):
403 get_attr = widget.attrib.get
404 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
405 # widgets (source->renderer).
407 wname = get_attr('name')
408 wsource = get_attr('source')
410 if wname is None and wsource is None:
411 print "widget has no name and no source!"
415 #print "Widget name=", wname
416 visited_components.add(wname)
418 # get corresponding 'gui' object
420 attributes = screen[wname].skinAttributes = [ ]
422 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
423 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
425 # assert screen[wname] is not Source
427 # and collect attributes for this
428 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
430 # get corresponding source
431 #print "Widget source=", wsource
433 while True: # until we found a non-obsolete source
435 # parse our current "wsource", which might specifiy a "related screen" before the dot,
436 # for example to reference a parent, global or session-global screen.
439 # resolve all path components
440 path = wsource.split('.')
442 scr = screen.getRelatedScreen(path[0])
446 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
449 # resolve the source.
450 source = scr.get(path[0])
451 if isinstance(source, ObsoleteSource):
452 # however, if we found an "obsolete source", issue warning, and resolve the real source.
453 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
454 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
455 if source.description:
456 print source.description
458 wsource = source.new_source
460 # otherwise, use that source.
464 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
466 wrender = get_attr('render')
469 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
471 for converter in widget.findall("convert"):
472 ctype = converter.get('type')
473 assert ctype, "'convert'-tag needs a 'type'-attribute"
474 #print "Converter:", ctype
476 parms = converter.text.strip()
479 #print "Params:", parms
480 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
484 for i in source.downstream_elements:
485 if isinstance(i, converter_class) and i.converter_arguments == parms:
489 print "allocating new converter!"
490 c = converter_class(parms)
493 print "reused converter!"
497 renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
499 renderer = renderer_class() # instantiate renderer
501 renderer.connect(source) # connect to source
502 attributes = renderer.skinAttributes = [ ]
503 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
505 screen.renderer.append(renderer)
507 from Components.GUIComponent import GUIComponent
508 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
509 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
511 # now walk additional objects
512 for widget in myscreen.getchildren():
515 if w_tag == "widget":
518 if w_tag == "applet":
520 codeText = widget.text.strip()
526 type = widget.attrib.get('type')
528 code = compile(codeText, "skin applet", "exec")
530 if type == "onLayoutFinish":
531 screen.onLayoutFinish.append(code)
532 #print "onLayoutFinish = ", codeText
534 raise SkinError("applet type '%s' unknown!" % type)
535 #print "applet type '%s' unknown!" % type
539 w = additionalWidget()
541 if w_tag == "eLabel":
543 elif w_tag == "ePixmap":
546 raise SkinError("unsupported stuff : %s" % w_tag)
547 #print "unsupported stuff : %s" % widget.tag
549 w.skinAttributes = [ ]
550 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
552 # applyAttributes(guiObject, widget, desktop)
553 # guiObject.thisown = 0
554 screen.additionalWidgets.append(w)