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
17 from Tools.XMLTools import mergeText
22 print " " * i + str(x)
24 for n in x.childNodes:
29 class SkinError(Exception):
30 def __init__(self, message):
31 self.message = message
40 filename = resolveFilename(SCOPE_SKIN, name)
41 mpath = path.dirname(filename) + "/"
42 dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
44 # we do our best to always select the "right" value
45 # skins are loaded in order of priority: skin with
46 # highest priority is loaded last, usually the user-provided
49 # currently, loadSingleSkinData (colors, bordersets etc.)
50 # are applied one-after-each, in order of ascending priority.
51 # the dom_skin will keep all screens in descending priority,
52 # so the first screen found will be used.
54 # example: loadSkin("nemesis_greenline/skin.xml")
55 config.skin = ConfigSubsection()
56 config.skin.primary_skin = ConfigText(default = "skin.xml")
60 loadSkin(config.skin.primary_skin.value)
61 except (SkinError, IOError, AssertionError), err:
62 print "SKIN ERROR:", err
63 print "defaulting to standard skin..."
64 config.skin.primary_skin.value = 'skin.xml'
67 profile("LoadSkinDefault")
68 loadSkin('skin_default.xml')
69 profile("LoadSkinDefaultDone")
71 def parsePosition(str, scale):
73 return ePoint(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
75 def parseSize(str, scale):
77 return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
79 def parseFont(str, scale):
80 name, size = str.split(';')
81 return gFont(name, int(size) * scale[0][0] / scale[0][1])
86 return colorNames[str]
88 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
89 return gRGB(int(str[1:], 0x10))
91 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
93 for a in node.items():
98 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
99 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
101 if attrib not in ignore:
102 skinAttributes.append((attrib, value))
104 def loadPixmap(path, desktop):
106 option = path.find("#")
108 options = path[option+1:].split(',')
110 cached = "cached" in options
111 ptr = LoadPixmap(path, desktop, cached)
113 raise SkinError("pixmap file %s not found!" % (path))
116 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
119 if attrib == 'position':
120 guiObject.move(parsePosition(value, scale))
121 elif attrib == 'size':
122 guiObject.resize(parseSize(value, scale))
123 elif attrib == 'title':
124 guiObject.setTitle(_(value))
125 elif attrib == 'text':
126 guiObject.setText(_(value))
127 elif attrib == 'font':
128 guiObject.setFont(parseFont(value, scale))
129 elif attrib == 'zPosition':
130 guiObject.setZPosition(int(value))
131 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
132 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
133 if attrib == "pixmap":
134 guiObject.setPixmap(ptr)
135 elif attrib == "backgroundPixmap":
136 guiObject.setBackgroundPicture(ptr)
137 elif attrib == "selectionPixmap":
138 guiObject.setSelectionPicture(ptr)
139 # guiObject.setPixmapFromFile(value)
140 elif attrib == "alphatest": # used by ePixmap
141 guiObject.setAlphatest(
146 elif attrib == "orientation": # used by eSlider
147 if value in ("orHorizontal", "orLeftToRight"):
148 orientation = guiObject.orHorizontal
149 direction = guiObject.dirNormal
150 elif value in ("orVertical", "orTopToBottom"):
151 orientation = guiObject.orVertical
152 direction = guiObject.dirNormal
153 elif value == "orRightToLeft":
154 orientation = guiObject.orHorizontal
155 direction = guiObject.dirSwapped
156 elif value == "orBottomToTop":
157 orientation = guiObject.orVertical
158 direction = guiObject.dirSwapped
160 print "orientation must be one of: orTopToBottom,orBottomToTop,orLeftToRight,orRightToLeft"
162 guiObject.setOrientation(orientation)
163 guiObject.setDirection(direction)
164 elif attrib == "valign":
167 { "top": guiObject.alignTop,
168 "center": guiObject.alignCenter,
169 "bottom": guiObject.alignBottom
172 print "valign must be either top, center or bottom!"
173 elif attrib == "halign":
176 { "left": guiObject.alignLeft,
177 "center": guiObject.alignCenter,
178 "right": guiObject.alignRight,
179 "block": guiObject.alignBlock
182 print "halign must be either left, center, right or block!"
183 elif attrib == "flags":
184 flags = value.split(',')
187 fv = eWindow.__dict__[f]
188 guiObject.setFlag(fv)
190 print "illegal flag %s!" % f
191 elif attrib == "backgroundColor":
192 guiObject.setBackgroundColor(parseColor(value))
193 elif attrib == "backgroundColorSelected":
194 guiObject.setBackgroundColorSelected(parseColor(value))
195 elif attrib == "foregroundColor":
196 guiObject.setForegroundColor(parseColor(value))
197 elif attrib == "foregroundColorSelected":
198 guiObject.setForegroundColorSelected(parseColor(value))
199 elif attrib == "shadowColor":
200 guiObject.setShadowColor(parseColor(value))
201 elif attrib == "selectionDisabled":
202 guiObject.setSelectionEnable(0)
203 elif attrib == "transparent":
204 guiObject.setTransparent(int(value))
205 elif attrib == "borderColor":
206 guiObject.setBorderColor(parseColor(value))
207 elif attrib == "borderWidth":
208 guiObject.setBorderWidth(int(value))
209 elif attrib == "scrollbarMode":
210 guiObject.setScrollbarMode(
211 { "showOnDemand": guiObject.showOnDemand,
212 "showAlways": guiObject.showAlways,
213 "showNever": guiObject.showNever
215 elif attrib == "enableWrapAround":
216 guiObject.setWrapAround(True)
217 elif attrib == "pointer" or attrib == "seek_pointer":
218 (name, pos) = value.split(':')
219 pos = parsePosition(pos, scale)
220 ptr = loadPixmap(name, desktop)
221 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
222 elif attrib == 'shadowOffset':
223 guiObject.setShadowOffset(parsePosition(value, scale))
224 elif attrib == 'noWrap':
225 guiObject.setNoWrap(1)
227 raise SkinError("unsupported attribute " + attrib + "=" + value)
230 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
232 def applyAllAttributes(guiObject, desktop, attributes, scale):
233 for (attrib, value) in attributes:
234 applySingleAttribute(guiObject, desktop, attrib, value, scale)
236 def loadSingleSkinData(desktop, skin, path_prefix):
237 """loads skin data like colors, windowstyle etc."""
238 assert skin.tag == "skin", "root element in skin must be 'skin'!"
240 #print "***SKIN: ", path_prefix
242 for c in skin.findall("output"):
243 id = c.attrib.get('id')
248 if id == 0: # framebuffer
249 for res in c.findall("resolution"):
250 get_attr = res.attrib.get
251 xres = get_attr("xres")
256 yres = get_attr("yres")
261 bpp = get_attr("bpp")
266 #print "Resolution:", xres,yres,bpp
267 from enigma import gFBDC
268 gFBDC.getInstance().setResolution(xres, yres)
269 desktop.resize(eSize(xres, yres))
271 # load palette (not yet implemented)
274 for c in skin.findall("colors"):
275 for color in c.findall("color"):
276 get_attr = color.attrib.get
277 name = get_attr("name")
278 color = get_attr("value")
280 colorNames[name] = parseColor(color)
281 #print "Color:", name, color
283 raise ("need color and name, got %s %s" % (name, color))
285 for c in skin.findall("fonts"):
286 for font in c.findall("font"):
287 get_attr = font.attrib.get
288 filename = get_attr("filename", "<NONAME>")
289 name = get_attr("name", "Regular")
290 scale = get_attr("scale")
295 is_replacement = get_attr("replacement") and True or False
296 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
297 if not fileExists(resolved_font): #when font is not available look at current skin path
298 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
299 if fileExists(skin_path):
300 resolved_font = skin_path
301 addFont(resolved_font, name, scale, is_replacement)
302 #print "Font: ", resolved_font, name, scale, is_replacement
304 for windowstyle in skin.findall("windowstyle"):
305 style = eWindowStyleSkinned()
306 id = windowstyle.attrib.get("id")
311 #print "windowstyle:", id
314 font = gFont("Regular", 20)
315 offset = eSize(20, 5)
317 for title in windowstyle.findall("title"):
318 get_attr = title.attrib.get
319 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
320 font = parseFont(get_attr("font"), ((1,1),(1,1)))
322 style.setTitleFont(font);
323 style.setTitleOffset(offset)
324 #print " ", font, offset
326 for borderset in windowstyle.findall("borderset"):
327 bsName = str(borderset.attrib.get("name"))
328 for pixmap in borderset.findall("pixmap"):
329 get_attr = pixmap.attrib.get
330 bpName = get_attr("pos")
331 filename = get_attr("filename")
332 if filename and bpName:
333 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
334 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
335 #print " borderset:", bpName, filename
337 for color in windowstyle.findall("color"):
338 get_attr = color.attrib.get
339 type = get_attr("name")
340 color = parseColor(get_attr("color"))
342 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
344 raise ("Unknown color %s" % (type))
347 #print " color:", type, color
349 x = eWindowStyleManager.getInstance()
350 x.setStyle(id, style)
352 def loadSkinData(desktop):
355 for (path, dom_skin) in skins:
356 loadSingleSkinData(desktop, dom_skin, path)
358 def lookupScreen(name):
359 for (path, skin) in dom_skins:
360 # first, find the corresponding screen element
361 for x in skin.findall("screen"):
362 if x.attrib.get('name', '') == name:
366 class additionalWidget:
369 def readSkin(screen, skin, names, desktop):
370 if not isinstance(names, list):
373 name = "<embedded-in-'%s'>" % screen.__class__.__name__
375 # try all skins, first existing one have priority
377 myscreen, path = lookupScreen(n)
378 if myscreen is not None:
379 # use this name for debug output
383 # otherwise try embedded skin
385 myscreen = getattr(screen, "parsedSkin", None)
387 # try uncompiled embedded skin
388 if myscreen is None and getattr(screen, "skin", None):
389 print "Looking for embedded skin"
390 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
392 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
394 print "No skin to read..."
395 emptySkin = "<screen></screen>"
396 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
398 screen.skinAttributes = [ ]
400 skin_path_prefix = getattr(screen, "skin_path", path)
402 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
404 screen.additionalWidgets = [ ]
405 screen.renderer = [ ]
407 visited_components = set()
409 # now walk all widgets
410 for widget in myscreen.findall("widget"):
411 get_attr = widget.attrib.get
412 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
413 # widgets (source->renderer).
415 wname = get_attr('name')
416 wsource = get_attr('source')
418 if wname is None and wsource is None:
419 print "widget has no name and no source!"
423 #print "Widget name=", wname
424 visited_components.add(wname)
426 # get corresponding 'gui' object
428 attributes = screen[wname].skinAttributes = [ ]
430 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
431 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
433 # assert screen[wname] is not Source
435 # and collect attributes for this
436 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
438 # get corresponding source
439 #print "Widget source=", wsource
441 while True: # until we found a non-obsolete source
443 # parse our current "wsource", which might specifiy a "related screen" before the dot,
444 # for example to reference a parent, global or session-global screen.
447 # resolve all path components
448 path = wsource.split('.')
450 scr = screen.getRelatedScreen(path[0])
454 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
457 # resolve the source.
458 source = scr.get(path[0])
459 if isinstance(source, ObsoleteSource):
460 # however, if we found an "obsolete source", issue warning, and resolve the real source.
461 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
462 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
463 if source.description:
464 print source.description
466 wsource = source.new_source
468 # otherwise, use that source.
472 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
474 wrender = get_attr('render')
477 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
479 for converter in widget.findall("convert"):
480 ctype = converter.get('type')
481 assert ctype, "'convert'-tag needs a 'type'-attribute"
482 #print "Converter:", ctype
483 #parms = mergeText(converter.childNodes).strip()
485 parms = converter.text.strip()
488 #print "Params:", ctype
489 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
493 for i in source.downstream_elements:
494 if isinstance(i, converter_class) and i.converter_arguments == parms:
498 print "allocating new converter!"
499 c = converter_class(parms)
502 print "reused converter!"
506 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
508 renderer = renderer_class() # instantiate renderer
510 renderer.connect(source) # connect to source
511 attributes = renderer.skinAttributes = [ ]
512 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
514 screen.renderer.append(renderer)
516 from Components.GUIComponent import GUIComponent
517 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
518 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
520 # now walk additional objects
521 for widget in myscreen.getchildren():
524 if w_tag == "widget":
527 if w_tag == "applet":
529 codeText = widget.text.strip()
535 type = widget.attrib.get('type')
537 code = compile(codeText, "skin applet", "exec")
539 if type == "onLayoutFinish":
540 screen.onLayoutFinish.append(code)
541 #print "onLayoutFinish = ", codeText
543 raise SkinError("applet type '%s' unknown!" % type)
544 #print "applet type '%s' unknown!" % type
548 w = additionalWidget()
550 if w_tag == "eLabel":
552 elif w_tag == "ePixmap":
555 raise SkinError("unsupported stuff : %s" % w_tag)
556 #print "unsupported stuff : %s" % widget.tag
558 w.skinAttributes = [ ]
559 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
561 # applyAttributes(guiObject, widget, desktop)
562 # guiObject.thisown = 0
563 screen.additionalWidgets.append(w)