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, SCOPE_CONFIG, 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):
32 return "{%s}: %s" % (config.skin.primary_skin, self.msg)
36 def loadSkin(name, scope = SCOPE_SKIN):
38 filename = resolveFilename(scope, 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('skin_user.xml', SCOPE_CONFIG)
59 except (SkinError, IOError, AssertionError), err:
60 print "not loading user skin: ", err
63 loadSkin(config.skin.primary_skin.value)
64 except (SkinError, IOError, AssertionError), err:
65 print "SKIN ERROR:", err
66 print "defaulting to standard skin..."
67 config.skin.primary_skin.value = 'skin.xml'
70 profile("LoadSkinDefault")
71 loadSkin('skin_default.xml')
72 profile("LoadSkinDefaultDone")
74 def parsePosition(str, scale):
76 return ePoint(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
78 def parseSize(str, scale):
80 return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
82 def parseFont(str, scale):
83 name, size = str.split(';')
84 return gFont(name, int(size) * scale[0][0] / scale[0][1])
89 return colorNames[str]
91 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
92 return gRGB(int(str[1:], 0x10))
94 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
96 for a in node.items():
101 if attrib in ("pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"):
102 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
104 if attrib not in ignore:
105 skinAttributes.append((attrib, value))
107 def loadPixmap(path, desktop):
109 option = path.find("#")
111 options = path[option+1:].split(',')
113 cached = "cached" in options
114 ptr = LoadPixmap(path, desktop, cached)
116 raise SkinError("pixmap file %s not found!" % (path))
119 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
122 if attrib == 'position':
123 guiObject.move(parsePosition(value, scale))
124 elif attrib == 'size':
125 guiObject.resize(parseSize(value, scale))
126 elif attrib == 'title':
127 guiObject.setTitle(_(value))
128 elif attrib == 'text':
129 guiObject.setText(_(value))
130 elif attrib == 'font':
131 guiObject.setFont(parseFont(value, scale))
132 elif attrib == 'zPosition':
133 guiObject.setZPosition(int(value))
134 elif attrib in ("pixmap", "backgroundPixmap", "selectionPixmap"):
135 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
136 if attrib == "pixmap":
137 guiObject.setPixmap(ptr)
138 elif attrib == "backgroundPixmap":
139 guiObject.setBackgroundPicture(ptr)
140 elif attrib == "selectionPixmap":
141 guiObject.setSelectionPicture(ptr)
142 # guiObject.setPixmapFromFile(value)
143 elif attrib == "alphatest": # used by ePixmap
144 guiObject.setAlphatest(
149 elif attrib == "orientation": # used by eSlider
151 guiObject.setOrientation(*
152 { "orVertical": (guiObject.orVertical, False),
153 "orTopToBottom": (guiObject.orVertical, False),
154 "orBottomToTop": (guiObject.orVertical, True),
155 "orHorizontal": (guiObject.orHorizontal, False),
156 "orLeftToRight": (guiObject.orHorizontal, False),
157 "orRightToLeft": (guiObject.orHorizontal, True),
160 print "oprientation must be either orVertical or orHorizontal!"
161 elif attrib == "valign":
164 { "top": guiObject.alignTop,
165 "center": guiObject.alignCenter,
166 "bottom": guiObject.alignBottom
169 print "valign must be either top, center or bottom!"
170 elif attrib == "halign":
173 { "left": guiObject.alignLeft,
174 "center": guiObject.alignCenter,
175 "right": guiObject.alignRight,
176 "block": guiObject.alignBlock
179 print "halign must be either left, center, right or block!"
180 elif attrib == "flags":
181 flags = value.split(',')
184 fv = eWindow.__dict__[f]
185 guiObject.setFlag(fv)
187 print "illegal flag %s!" % f
188 elif attrib == "backgroundColor":
189 guiObject.setBackgroundColor(parseColor(value))
190 elif attrib == "backgroundColorSelected":
191 guiObject.setBackgroundColorSelected(parseColor(value))
192 elif attrib == "foregroundColor":
193 guiObject.setForegroundColor(parseColor(value))
194 elif attrib == "foregroundColorSelected":
195 guiObject.setForegroundColorSelected(parseColor(value))
196 elif attrib == "shadowColor":
197 guiObject.setShadowColor(parseColor(value))
198 elif attrib == "selectionDisabled":
199 guiObject.setSelectionEnable(0)
200 elif attrib == "transparent":
201 guiObject.setTransparent(int(value))
202 elif attrib == "borderColor":
203 guiObject.setBorderColor(parseColor(value))
204 elif attrib == "borderWidth":
205 guiObject.setBorderWidth(int(value))
206 elif attrib == "scrollbarMode":
207 guiObject.setScrollbarMode(
208 { "showOnDemand": guiObject.showOnDemand,
209 "showAlways": guiObject.showAlways,
210 "showNever": guiObject.showNever
212 elif attrib == "enableWrapAround":
213 guiObject.setWrapAround(True)
214 elif attrib == "pointer" or attrib == "seek_pointer":
215 (name, pos) = value.split(':')
216 pos = parsePosition(pos, scale)
217 ptr = loadPixmap(name, desktop)
218 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
219 elif attrib == 'shadowOffset':
220 guiObject.setShadowOffset(parsePosition(value, scale))
221 elif attrib == 'noWrap':
222 guiObject.setNoWrap(1)
224 raise SkinError("unsupported attribute " + attrib + "=" + value)
227 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
229 def applyAllAttributes(guiObject, desktop, attributes, scale):
230 for (attrib, value) in attributes:
231 applySingleAttribute(guiObject, desktop, attrib, value, scale)
233 def loadSingleSkinData(desktop, skin, path_prefix):
234 """loads skin data like colors, windowstyle etc."""
235 assert skin.tag == "skin", "root element in skin must be 'skin'!"
237 #print "***SKIN: ", path_prefix
239 for c in skin.findall("output"):
240 id = c.attrib.get('id')
245 if id == 0: # framebuffer
246 for res in c.findall("resolution"):
247 get_attr = res.attrib.get
248 xres = get_attr("xres")
253 yres = get_attr("yres")
258 bpp = get_attr("bpp")
263 #print "Resolution:", xres,yres,bpp
264 from enigma import gFBDC
265 gFBDC.getInstance().setResolution(xres, yres)
266 desktop.resize(eSize(xres, yres))
268 # load palette (not yet implemented)
271 for c in skin.findall("colors"):
272 for color in c.findall("color"):
273 get_attr = color.attrib.get
274 name = get_attr("name")
275 color = get_attr("value")
277 colorNames[name] = parseColor(color)
278 #print "Color:", name, color
280 raise SkinError("need color and name, got %s %s" % (name, color))
282 for c in skin.findall("fonts"):
283 for font in c.findall("font"):
284 get_attr = font.attrib.get
285 filename = get_attr("filename", "<NONAME>")
286 name = get_attr("name", "Regular")
287 scale = get_attr("scale")
292 is_replacement = get_attr("replacement") and True or False
293 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
294 if not fileExists(resolved_font): #when font is not available look at current skin path
295 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
296 if fileExists(skin_path):
297 resolved_font = skin_path
298 addFont(resolved_font, name, scale, is_replacement)
299 #print "Font: ", resolved_font, name, scale, is_replacement
301 for windowstyle in skin.findall("windowstyle"):
302 style = eWindowStyleSkinned()
303 id = windowstyle.attrib.get("id")
308 #print "windowstyle:", id
311 font = gFont("Regular", 20)
312 offset = eSize(20, 5)
314 for title in windowstyle.findall("title"):
315 get_attr = title.attrib.get
316 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
317 font = parseFont(get_attr("font"), ((1,1),(1,1)))
319 style.setTitleFont(font);
320 style.setTitleOffset(offset)
321 #print " ", font, offset
323 for borderset in windowstyle.findall("borderset"):
324 bsName = str(borderset.attrib.get("name"))
325 for pixmap in borderset.findall("pixmap"):
326 get_attr = pixmap.attrib.get
327 bpName = get_attr("pos")
328 filename = get_attr("filename")
329 if filename and bpName:
330 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
331 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
332 #print " borderset:", bpName, filename
334 for color in windowstyle.findall("color"):
335 get_attr = color.attrib.get
336 type = get_attr("name")
337 color = parseColor(get_attr("color"))
339 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
341 raise SkinError("Unknown color %s" % (type))
344 #print " color:", type, color
346 x = eWindowStyleManager.getInstance()
347 x.setStyle(id, style)
349 def loadSkinData(desktop):
352 for (path, dom_skin) in skins:
353 loadSingleSkinData(desktop, dom_skin, path)
355 def lookupScreen(name):
356 for (path, skin) in dom_skins:
357 # first, find the corresponding screen element
358 for x in skin.findall("screen"):
359 if x.attrib.get('name', '') == name:
363 class additionalWidget:
366 def readSkin(screen, skin, names, desktop):
367 if not isinstance(names, list):
370 name = "<embedded-in-'%s'>" % screen.__class__.__name__
372 # try all skins, first existing one have priority
374 myscreen, path = lookupScreen(n)
375 if myscreen is not None:
376 # use this name for debug output
380 # otherwise try embedded skin
382 myscreen = getattr(screen, "parsedSkin", None)
384 # try uncompiled embedded skin
385 if myscreen is None and getattr(screen, "skin", None):
386 print "Looking for embedded skin"
387 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
389 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
391 print "No skin to read..."
392 emptySkin = "<screen></screen>"
393 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
395 screen.skinAttributes = [ ]
397 skin_path_prefix = getattr(screen, "skin_path", path)
399 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
401 screen.additionalWidgets = [ ]
402 screen.renderer = [ ]
404 visited_components = set()
406 # now walk all widgets
407 for widget in myscreen.findall("widget"):
408 get_attr = widget.attrib.get
409 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
410 # widgets (source->renderer).
412 wname = get_attr('name')
413 wsource = get_attr('source')
415 if wname is None and wsource is None:
416 print "widget has no name and no source!"
420 #print "Widget name=", wname
421 visited_components.add(wname)
423 # get corresponding 'gui' object
425 attributes = screen[wname].skinAttributes = [ ]
427 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
428 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
430 # assert screen[wname] is not Source
432 # and collect attributes for this
433 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
435 # get corresponding source
436 #print "Widget source=", wsource
438 while True: # until we found a non-obsolete source
440 # parse our current "wsource", which might specifiy a "related screen" before the dot,
441 # for example to reference a parent, global or session-global screen.
444 # resolve all path components
445 path = wsource.split('.')
447 scr = screen.getRelatedScreen(path[0])
451 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
454 # resolve the source.
455 source = scr.get(path[0])
456 if isinstance(source, ObsoleteSource):
457 # however, if we found an "obsolete source", issue warning, and resolve the real source.
458 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
459 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
460 if source.description:
461 print source.description
463 wsource = source.new_source
465 # otherwise, use that source.
469 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
471 wrender = get_attr('render')
474 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
476 for converter in widget.findall("convert"):
477 ctype = converter.get('type')
478 assert ctype, "'convert'-tag needs a 'type'-attribute"
479 #print "Converter:", ctype
481 parms = converter.text.strip()
484 #print "Params:", parms
485 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
489 for i in source.downstream_elements:
490 if isinstance(i, converter_class) and i.converter_arguments == parms:
494 print "allocating new converter!"
495 c = converter_class(parms)
498 print "reused converter!"
502 renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
504 renderer = renderer_class() # instantiate renderer
506 renderer.connect(source) # connect to source
507 attributes = renderer.skinAttributes = [ ]
508 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
510 screen.renderer.append(renderer)
512 from Components.GUIComponent import GUIComponent
513 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
514 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
516 # now walk additional objects
517 for widget in myscreen.getchildren():
520 if w_tag == "widget":
523 if w_tag == "applet":
525 codeText = widget.text.strip()
531 type = widget.attrib.get('type')
533 code = compile(codeText, "skin applet", "exec")
535 if type == "onLayoutFinish":
536 screen.onLayoutFinish.append(code)
537 #print "onLayoutFinish = ", codeText
539 raise SkinError("applet type '%s' unknown!" % type)
540 #print "applet type '%s' unknown!" % type
544 w = additionalWidget()
546 if w_tag == "eLabel":
548 elif w_tag == "ePixmap":
551 raise SkinError("unsupported stuff : %s" % w_tag)
552 #print "unsupported stuff : %s" % widget.tag
554 w.skinAttributes = [ ]
555 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
557 # applyAttributes(guiObject, widget, desktop)
558 # guiObject.thisown = 0
559 screen.additionalWidgets.append(w)