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
148 guiObject.setOrientation(*
149 { "orVertical": (guiObject.orVertical, False),
150 "orTopToBottom": (guiObject.olVertical, False),
151 "orBottomToTop": (guiObject.orVertical, True),
152 "orHorizontal": (guiObject.orHorizontal, False),
153 "orLeftToRight": (guiObject.orHorizontal, False),
154 "orRightToRight": (guiObject.orHorizontal, True),
157 print "oprientation must be either orVertical or orHorizontal!"
158 elif attrib == "valign":
161 { "top": guiObject.alignTop,
162 "center": guiObject.alignCenter,
163 "bottom": guiObject.alignBottom
166 print "valign must be either top, center or bottom!"
167 elif attrib == "halign":
170 { "left": guiObject.alignLeft,
171 "center": guiObject.alignCenter,
172 "right": guiObject.alignRight,
173 "block": guiObject.alignBlock
176 print "halign must be either left, center, right or block!"
177 elif attrib == "flags":
178 flags = value.split(',')
181 fv = eWindow.__dict__[f]
182 guiObject.setFlag(fv)
184 print "illegal flag %s!" % f
185 elif attrib == "backgroundColor":
186 guiObject.setBackgroundColor(parseColor(value))
187 elif attrib == "backgroundColorSelected":
188 guiObject.setBackgroundColorSelected(parseColor(value))
189 elif attrib == "foregroundColor":
190 guiObject.setForegroundColor(parseColor(value))
191 elif attrib == "foregroundColorSelected":
192 guiObject.setForegroundColorSelected(parseColor(value))
193 elif attrib == "shadowColor":
194 guiObject.setShadowColor(parseColor(value))
195 elif attrib == "selectionDisabled":
196 guiObject.setSelectionEnable(0)
197 elif attrib == "transparent":
198 guiObject.setTransparent(int(value))
199 elif attrib == "borderColor":
200 guiObject.setBorderColor(parseColor(value))
201 elif attrib == "borderWidth":
202 guiObject.setBorderWidth(int(value))
203 elif attrib == "scrollbarMode":
204 guiObject.setScrollbarMode(
205 { "showOnDemand": guiObject.showOnDemand,
206 "showAlways": guiObject.showAlways,
207 "showNever": guiObject.showNever
209 elif attrib == "enableWrapAround":
210 guiObject.setWrapAround(True)
211 elif attrib == "pointer" or attrib == "seek_pointer":
212 (name, pos) = value.split(':')
213 pos = parsePosition(pos, scale)
214 ptr = loadPixmap(name, desktop)
215 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
216 elif attrib == 'shadowOffset':
217 guiObject.setShadowOffset(parsePosition(value, scale))
218 elif attrib == 'noWrap':
219 guiObject.setNoWrap(1)
221 raise SkinError("unsupported attribute " + attrib + "=" + value)
224 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
226 def applyAllAttributes(guiObject, desktop, attributes, scale):
227 for (attrib, value) in attributes:
228 applySingleAttribute(guiObject, desktop, attrib, value, scale)
230 def loadSingleSkinData(desktop, skin, path_prefix):
231 """loads skin data like colors, windowstyle etc."""
232 assert skin.tag == "skin", "root element in skin must be 'skin'!"
234 #print "***SKIN: ", path_prefix
236 for c in skin.findall("output"):
237 id = c.attrib.get('id')
242 if id == 0: # framebuffer
243 for res in c.findall("resolution"):
244 get_attr = res.attrib.get
245 xres = get_attr("xres")
250 yres = get_attr("yres")
255 bpp = get_attr("bpp")
260 #print "Resolution:", xres,yres,bpp
261 from enigma import gFBDC
262 gFBDC.getInstance().setResolution(xres, yres)
263 desktop.resize(eSize(xres, yres))
265 # load palette (not yet implemented)
268 for c in skin.findall("colors"):
269 for color in c.findall("color"):
270 get_attr = color.attrib.get
271 name = get_attr("name")
272 color = get_attr("value")
274 colorNames[name] = parseColor(color)
275 #print "Color:", name, color
277 raise ("need color and name, got %s %s" % (name, color))
279 for c in skin.findall("fonts"):
280 for font in c.findall("font"):
281 get_attr = font.attrib.get
282 filename = get_attr("filename", "<NONAME>")
283 name = get_attr("name", "Regular")
284 scale = get_attr("scale")
289 is_replacement = get_attr("replacement") and True or False
290 resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
291 if not fileExists(resolved_font): #when font is not available look at current skin path
292 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
293 if fileExists(skin_path):
294 resolved_font = skin_path
295 addFont(resolved_font, name, scale, is_replacement)
296 #print "Font: ", resolved_font, name, scale, is_replacement
298 for windowstyle in skin.findall("windowstyle"):
299 style = eWindowStyleSkinned()
300 id = windowstyle.attrib.get("id")
305 #print "windowstyle:", id
308 font = gFont("Regular", 20)
309 offset = eSize(20, 5)
311 for title in windowstyle.findall("title"):
312 get_attr = title.attrib.get
313 offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
314 font = parseFont(get_attr("font"), ((1,1),(1,1)))
316 style.setTitleFont(font);
317 style.setTitleOffset(offset)
318 #print " ", font, offset
320 for borderset in windowstyle.findall("borderset"):
321 bsName = str(borderset.attrib.get("name"))
322 for pixmap in borderset.findall("pixmap"):
323 get_attr = pixmap.attrib.get
324 bpName = get_attr("pos")
325 filename = get_attr("filename")
326 if filename and bpName:
327 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
328 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
329 #print " borderset:", bpName, filename
331 for color in windowstyle.findall("color"):
332 get_attr = color.attrib.get
333 type = get_attr("name")
334 color = parseColor(get_attr("color"))
336 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
338 raise ("Unknown color %s" % (type))
341 #print " color:", type, color
343 x = eWindowStyleManager.getInstance()
344 x.setStyle(id, style)
346 def loadSkinData(desktop):
349 for (path, dom_skin) in skins:
350 loadSingleSkinData(desktop, dom_skin, path)
352 def lookupScreen(name):
353 for (path, skin) in dom_skins:
354 # first, find the corresponding screen element
355 for x in skin.findall("screen"):
356 if x.attrib.get('name', '') == name:
360 class additionalWidget:
363 def readSkin(screen, skin, names, desktop):
364 if not isinstance(names, list):
367 name = "<embedded-in-'%s'>" % screen.__class__.__name__
369 # try all skins, first existing one have priority
371 myscreen, path = lookupScreen(n)
372 if myscreen is not None:
373 # use this name for debug output
377 # otherwise try embedded skin
379 myscreen = getattr(screen, "parsedSkin", None)
381 # try uncompiled embedded skin
382 if myscreen is None and getattr(screen, "skin", None):
383 print "Looking for embedded skin"
384 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
386 #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
388 print "No skin to read..."
389 emptySkin = "<screen></screen>"
390 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
392 screen.skinAttributes = [ ]
394 skin_path_prefix = getattr(screen, "skin_path", path)
396 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
398 screen.additionalWidgets = [ ]
399 screen.renderer = [ ]
401 visited_components = set()
403 # now walk all widgets
404 for widget in myscreen.findall("widget"):
405 get_attr = widget.attrib.get
406 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
407 # widgets (source->renderer).
409 wname = get_attr('name')
410 wsource = get_attr('source')
412 if wname is None and wsource is None:
413 print "widget has no name and no source!"
417 #print "Widget name=", wname
418 visited_components.add(wname)
420 # get corresponding 'gui' object
422 attributes = screen[wname].skinAttributes = [ ]
424 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
425 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
427 # assert screen[wname] is not Source
429 # and collect attributes for this
430 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
432 # get corresponding source
433 #print "Widget source=", wsource
435 while True: # until we found a non-obsolete source
437 # parse our current "wsource", which might specifiy a "related screen" before the dot,
438 # for example to reference a parent, global or session-global screen.
441 # resolve all path components
442 path = wsource.split('.')
444 scr = screen.getRelatedScreen(path[0])
448 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
451 # resolve the source.
452 source = scr.get(path[0])
453 if isinstance(source, ObsoleteSource):
454 # however, if we found an "obsolete source", issue warning, and resolve the real source.
455 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
456 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
457 if source.description:
458 print source.description
460 wsource = source.new_source
462 # otherwise, use that source.
466 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
468 wrender = get_attr('render')
471 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
473 for converter in widget.findall("convert"):
474 ctype = converter.get('type')
475 assert ctype, "'convert'-tag needs a 'type'-attribute"
476 #print "Converter:", ctype
477 #parms = mergeText(converter.childNodes).strip()
479 parms = converter.text.strip()
482 #print "Params:", ctype
483 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
487 for i in source.downstream_elements:
488 if isinstance(i, converter_class) and i.converter_arguments == parms:
492 print "allocating new converter!"
493 c = converter_class(parms)
496 print "reused converter!"
500 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
502 renderer = renderer_class() # instantiate renderer
504 renderer.connect(source) # connect to source
505 attributes = renderer.skinAttributes = [ ]
506 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
508 screen.renderer.append(renderer)
510 from Components.GUIComponent import GUIComponent
511 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
512 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
514 # now walk additional objects
515 for widget in myscreen.getchildren():
518 if w_tag == "widget":
521 if w_tag == "applet":
523 codeText = widget.text.strip()
529 type = widget.attrib.get('type')
531 code = compile(codeText, "skin applet", "exec")
533 if type == "onLayoutFinish":
534 screen.onLayoutFinish.append(code)
535 #print "onLayoutFinish = ", codeText
537 raise SkinError("applet type '%s' unknown!" % type)
538 #print "applet type '%s' unknown!" % type
542 w = additionalWidget()
544 if w_tag == "eLabel":
546 elif w_tag == "ePixmap":
549 raise SkinError("unsupported stuff : %s" % w_tag)
550 #print "unsupported stuff : %s" % widget.tag
552 w.skinAttributes = [ ]
553 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
555 # applyAttributes(guiObject, widget, desktop)
556 # guiObject.thisown = 0
557 screen.additionalWidgets.append(w)