4 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
5 loadPNG, addFont, gRGB, eWindowStyleSkinned
7 from Components.config import ConfigSubsection, ConfigText, config
8 from Components.Converter.Converter import Converter
9 from Components.Sources.Source import Source, ObsoleteSource
10 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
11 from Tools.Import import my_import
13 from Tools.XMLTools import elementsWithTag, mergeText
18 print " " * i + str(x)
20 for n in x.childNodes:
25 class SkinError(Exception):
26 def __init__(self, message):
27 self.message = message
36 filename = resolveFilename(SCOPE_SKIN, name)
37 mpath = path.dirname(filename) + "/"
38 dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
40 # we do our best to always select the "right" value
41 # skins are loaded in order of priority: skin with
42 # highest priority is loaded last, usually the user-provided
45 # currently, loadSingleSkinData (colors, bordersets etc.)
46 # are applied one-after-each, in order of ascending priority.
47 # the dom_skin will keep all screens in descending priority,
48 # so the first screen found will be used.
50 # example: loadSkin("nemesis_greenline/skin.xml")
51 config.skin = ConfigSubsection()
52 config.skin.primary_skin = ConfigText(default = "skin.xml")
55 loadSkin(config.skin.primary_skin.value)
56 except (SkinError, IOError, AssertionError), err:
57 print "SKIN ERROR:", err
58 print "defaulting to standard skin..."
60 loadSkin('skin_default.xml')
62 def parsePosition(str):
64 return ePoint(int(x), int(y))
68 return eSize(int(x), int(y))
71 name, size = str.split(';')
72 return gFont(name, int(size))
77 return colorNames[str]
79 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
80 return gRGB(int(str[1:], 0x10))
82 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
84 for p in range(node.attributes.length):
85 a = node.attributes.item(p)
87 # convert to string (was: unicode)
89 # TODO: localization? as in e1?
90 value = a.value.encode("utf-8")
92 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
93 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
95 if attrib not in ignore:
96 skinAttributes.append((attrib, value))
101 raise SkinError("pixmap file %s not found!" % (path))
104 def applySingleAttribute(guiObject, desktop, attrib, value):
107 if attrib == 'position':
108 guiObject.move(parsePosition(value))
109 elif attrib == 'size':
110 guiObject.resize(parseSize(value))
111 elif attrib == 'title':
112 guiObject.setTitle(_(value))
113 elif attrib == 'text':
114 guiObject.setText(_(value))
115 elif attrib == 'font':
116 guiObject.setFont(parseFont(value))
117 elif attrib == 'zPosition':
118 guiObject.setZPosition(int(value))
119 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
120 ptr = loadPixmap(value) # this should already have been filename-resolved.
121 desktop.makeCompatiblePixmap(ptr)
122 if attrib == "pixmap":
123 guiObject.setPixmap(ptr)
124 elif attrib == "backgroundPixmap":
125 guiObject.setBackgroundPicture(ptr)
126 elif attrib == "selectionPixmap":
127 guiObject.setSelectionPicture(ptr)
128 # guiObject.setPixmapFromFile(value)
129 elif attrib == "alphatest": # used by ePixmap
130 guiObject.setAlphatest(
134 elif attrib == "orientation": # used by eSlider
136 guiObject.setOrientation(
137 { "orVertical": guiObject.orVertical,
138 "orHorizontal": guiObject.orHorizontal
141 print "oprientation must be either orVertical or orHorizontal!"
142 elif attrib == "valign":
145 { "top": guiObject.alignTop,
146 "center": guiObject.alignCenter,
147 "bottom": guiObject.alignBottom
150 print "valign must be either top, center or bottom!"
151 elif attrib == "halign":
154 { "left": guiObject.alignLeft,
155 "center": guiObject.alignCenter,
156 "right": guiObject.alignRight,
157 "block": guiObject.alignBlock
160 print "halign must be either left, center, right or block!"
161 elif attrib == "flags":
162 flags = value.split(',')
165 fv = eWindow.__dict__[f]
166 guiObject.setFlag(fv)
168 print "illegal flag %s!" % f
169 elif attrib == "backgroundColor":
170 guiObject.setBackgroundColor(parseColor(value))
171 elif attrib == "backgroundColorSelected":
172 guiObject.setBackgroundColorSelected(parseColor(value))
173 elif attrib == "foregroundColor":
174 guiObject.setForegroundColor(parseColor(value))
175 elif attrib == "foregroundColorSelected":
176 guiObject.setForegroundColorSelected(parseColor(value))
177 elif attrib == "shadowColor":
178 guiObject.setShadowColor(parseColor(value))
179 elif attrib == "selectionDisabled":
180 guiObject.setSelectionEnable(0)
181 elif attrib == "transparent":
182 guiObject.setTransparent(int(value))
183 elif attrib == "borderColor":
184 guiObject.setBorderColor(parseColor(value))
185 elif attrib == "borderWidth":
186 guiObject.setBorderWidth(int(value))
187 elif attrib == "scrollbarMode":
188 guiObject.setScrollbarMode(
189 { "showOnDemand": guiObject.showOnDemand,
190 "showAlways": guiObject.showAlways,
191 "showNever": guiObject.showNever
193 elif attrib == "enableWrapAround":
194 guiObject.setWrapAround(True)
195 elif attrib == "pointer" or attrib == "seek_pointer":
196 (name, pos) = value.split(':')
197 pos = parsePosition(pos)
198 ptr = loadPixmap(name)
199 desktop.makeCompatiblePixmap(ptr)
200 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
201 elif attrib == 'shadowOffset':
202 guiObject.setShadowOffset(parsePosition(value))
203 elif attrib == 'noWrap':
204 guiObject.setNoWrap(1)
206 raise SkinError("unsupported attribute " + attrib + "=" + value)
209 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
211 def applyAllAttributes(guiObject, desktop, attributes):
212 for (attrib, value) in attributes:
213 applySingleAttribute(guiObject, desktop, attrib, value)
215 def loadSingleSkinData(desktop, dom_skin, path_prefix):
216 """loads skin data like colors, windowstyle etc."""
218 skin = dom_skin.childNodes[0]
219 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
221 for c in elementsWithTag(skin.childNodes, "output"):
222 id = int(c.getAttribute("id") or "0")
223 if id == 0: # framebuffer
224 for res in elementsWithTag(c.childNodes, "resolution"):
225 xres = int(res.getAttribute("xres" or "720"))
226 yres = int(res.getAttribute("yres" or "576"))
227 bpp = int(res.getAttribute("bpp" or "32"))
229 from enigma import gFBDC
230 i = gFBDC.getInstance()
231 i.setResolution(xres, yres)
234 # load palette (not yet implemented)
237 for c in elementsWithTag(skin.childNodes, "colors"):
238 for color in elementsWithTag(c.childNodes, "color"):
239 name = str(color.getAttribute("name"))
240 color = str(color.getAttribute("value"))
243 raise ("need color and name, got %s %s" % (name, color))
245 colorNames[name] = parseColor(color)
247 for c in elementsWithTag(skin.childNodes, "fonts"):
248 for font in elementsWithTag(c.childNodes, "font"):
249 filename = str(font.getAttribute("filename") or "<NONAME>")
250 name = str(font.getAttribute("name") or "Regular")
251 scale = int(font.getAttribute("scale") or "100")
252 is_replacement = font.getAttribute("replacement") != ""
253 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
255 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
256 style = eWindowStyleSkinned()
257 id = int(windowstyle.getAttribute("id") or "0")
260 font = gFont("Regular", 20)
261 offset = eSize(20, 5)
263 for title in elementsWithTag(windowstyle.childNodes, "title"):
264 offset = parseSize(title.getAttribute("offset"))
265 font = parseFont(str(title.getAttribute("font")))
267 style.setTitleFont(font);
268 style.setTitleOffset(offset)
270 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
271 bsName = str(borderset.getAttribute("name"))
272 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
273 bpName = str(pixmap.getAttribute("pos"))
274 filename = str(pixmap.getAttribute("filename"))
276 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
279 desktop.makeCompatiblePixmap(png)
280 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
282 for color in elementsWithTag(windowstyle.childNodes, "color"):
283 type = str(color.getAttribute("name"))
284 color = parseColor(color.getAttribute("color"))
287 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
289 raise ("Unknown color %s" % (type))
291 x = eWindowStyleManager.getInstance()
292 x.setStyle(id, style)
294 def loadSkinData(desktop):
297 for (path, dom_skin) in skins:
298 loadSingleSkinData(desktop, dom_skin, path)
300 def lookupScreen(name):
301 for (path, dom_skin) in dom_skins:
302 # first, find the corresponding screen element
303 skin = dom_skin.childNodes[0]
304 for x in elementsWithTag(skin.childNodes, "screen"):
305 if x.getAttribute('name') == name:
309 def readSkin(screen, skin, names, desktop):
310 if not isinstance(names, list):
313 name = "<embedded-in-'%s'>" % screen.__class__.__name__
315 # try all skins, first existing one have priority
317 myscreen, path = lookupScreen(n)
318 if myscreen is not None:
319 # use this name for debug output
323 # otherwise try embedded skin
324 myscreen = myscreen or getattr(screen, "parsedSkin", None)
326 # try uncompiled embedded skin
327 if myscreen is None and getattr(screen, "skin", None):
328 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
330 assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
332 screen.skinAttributes = [ ]
334 skin_path_prefix = getattr(screen, "skin_path", path)
336 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
338 screen.additionalWidgets = [ ]
339 screen.renderer = [ ]
341 visited_components = set()
343 # now walk all widgets
344 for widget in elementsWithTag(myscreen.childNodes, "widget"):
345 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
346 # widgets (source->renderer).
348 wname = widget.getAttribute('name')
349 wsource = widget.getAttribute('source')
352 if wname is None and wsource is None:
353 print "widget has no name and no source!"
357 visited_components.add(wname)
359 # get corresponding 'gui' object
361 attributes = screen[wname].skinAttributes = [ ]
363 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
365 # assert screen[wname] is not Source
367 # and collect attributes for this
368 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
370 # get corresponding source
372 while True: # until we found a non-obsolete source
374 # parse our current "wsource", which might specifiy a "related screen" before the dot,
375 # for example to reference a parent, global or session-global screen.
378 # resolve all path components
379 path = wsource.split('.')
381 scr = screen.getRelatedScreen(path[0])
385 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
388 # resolve the source.
389 source = scr.get(path[0])
390 if isinstance(source, ObsoleteSource):
391 # however, if we found an "obsolete source", issue warning, and resolve the real source.
392 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
393 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
394 if source.description:
395 print source.description
397 wsource = source.new_source
399 # otherwise, use that source.
403 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
405 wrender = widget.getAttribute('render')
408 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
410 for converter in elementsWithTag(widget.childNodes, "convert"):
411 ctype = converter.getAttribute('type')
412 assert ctype, "'convert'-tag needs a 'type'-attribute"
413 parms = mergeText(converter.childNodes).strip()
414 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
418 for i in source.downstream_elements:
419 if isinstance(i, converter_class) and i.converter_arguments == parms:
423 print "allocating new converter!"
424 c = converter_class(parms)
427 print "reused converter!"
431 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
433 renderer = renderer_class() # instantiate renderer
435 renderer.connect(source) # connect to source
436 attributes = renderer.skinAttributes = [ ]
437 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
439 screen.renderer.append(renderer)
441 from Components.GUIComponent import GUIComponent
442 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
444 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
446 # now walk additional objects
447 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
448 if widget.tagName == "applet":
449 codeText = mergeText(widget.childNodes).strip()
450 type = widget.getAttribute('type')
452 code = compile(codeText, "skin applet", "exec")
454 if type == "onLayoutFinish":
455 screen.onLayoutFinish.append(code)
457 raise SkinError("applet type '%s' unknown!" % type)
461 class additionalWidget:
464 w = additionalWidget()
466 if widget.tagName == "eLabel":
468 elif widget.tagName == "ePixmap":
471 raise SkinError("unsupported stuff : %s" % widget.tagName)
473 w.skinAttributes = [ ]
474 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
476 # applyAttributes(guiObject, widget, desktop)
477 # guiObject.thisown = 0
478 screen.additionalWidgets.append(w)