2 from xml.dom import EMPTY_NAMESPACE
5 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
6 loadPNG, addFont, gRGB, eWindowStyleSkinned
8 from Components.config import ConfigSubsection, ConfigText, config
9 from Components.Element import Element
10 from Components.Converter.Converter import Converter
11 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
12 from Tools.Import import my_import
14 from Tools.XMLTools import elementsWithTag, mergeText
19 print " " * i + str(x)
21 for n in x.childNodes:
26 class SkinError(Exception):
27 def __init__(self, message):
28 self.message = message
37 filename = resolveFilename(SCOPE_SKIN, name)
38 mpath = path.dirname(filename) + "/"
39 dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
41 # we do our best to always select the "right" value
42 # skins are loaded in order of priority: skin with
43 # highest priority is loaded last, usually the user-provided
46 # currently, loadSingleSkinData (colors, bordersets etc.)
47 # are applied one-after-each, in order of ascending priority.
48 # the dom_skin will keep all screens in descending priority,
49 # so the first screen found will be used.
51 # example: loadSkin("nemesis_greenline/skin.xml")
52 config.skin = ConfigSubsection()
53 config.skin.primary_skin = ConfigText(default = "skin.xml")
56 loadSkin(config.skin.primary_skin.value)
57 except (SkinError, IOError, AssertionError), err:
58 print "SKIN ERROR:", err
59 print "defaulting to standard skin..."
61 loadSkin('skin_default.xml')
63 def parsePosition(str):
65 return ePoint(int(x), int(y))
69 return eSize(int(x), int(y))
72 name, size = str.split(';')
73 return gFont(name, int(size))
78 return colorNames[str]
80 raise ("color '%s' must be #aarrggbb or valid named color" % (str))
81 return gRGB(int(str[1:], 0x10))
83 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
85 for p in range(node.attributes.length):
86 a = node.attributes.item(p)
88 # convert to string (was: unicode)
90 # TODO: localization? as in e1?
91 value = a.value.encode("utf-8")
93 if attrib in ["pixmap", "pointer", "seek_pointer"]:
94 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
96 if attrib not in ignore:
97 skinAttributes.append((attrib, value))
102 raise "pixmap file %s not found!" % (path)
105 def applySingleAttribute(guiObject, desktop, attrib, value):
108 if attrib == 'position':
109 guiObject.move(parsePosition(value))
110 elif attrib == 'size':
111 guiObject.resize(parseSize(value))
112 elif attrib == 'title':
113 guiObject.setTitle(_(value))
114 elif attrib == 'text':
115 guiObject.setText(_(value))
116 elif attrib == 'font':
117 guiObject.setFont(parseFont(value))
118 elif attrib == 'zPosition':
119 guiObject.setZPosition(int(value))
120 elif attrib == "pixmap":
121 ptr = loadPixmap(value) # this should already have been filename-resolved.
122 # that __deref__ still scares me!
123 desktop.makeCompatiblePixmap(ptr.__deref__())
124 guiObject.setPixmap(ptr.__deref__())
125 # guiObject.setPixmapFromFile(value)
126 elif attrib == "alphatest": # used by ePixmap
127 guiObject.setAlphatest(
131 elif attrib == "orientation": # used by eSlider
133 guiObject.setOrientation(
134 { "orVertical": guiObject.orVertical,
135 "orHorizontal": guiObject.orHorizontal
138 print "oprientation must be either orVertical or orHorizontal!"
139 elif attrib == "valign":
142 { "top": guiObject.alignTop,
143 "center": guiObject.alignCenter,
144 "bottom": guiObject.alignBottom
147 print "valign must be either top, center or bottom!"
148 elif attrib == "halign":
151 { "left": guiObject.alignLeft,
152 "center": guiObject.alignCenter,
153 "right": guiObject.alignRight,
154 "block": guiObject.alignBlock
157 print "halign must be either left, center, right or block!"
158 elif attrib == "flags":
159 flags = value.split(',')
162 fv = eWindow.__dict__[f]
163 guiObject.setFlag(fv)
165 print "illegal flag %s!" % f
166 elif attrib == "backgroundColor":
167 guiObject.setBackgroundColor(parseColor(value))
168 elif attrib == "foregroundColor":
169 guiObject.setForegroundColor(parseColor(value))
170 elif attrib == "shadowColor":
171 guiObject.setShadowColor(parseColor(value))
172 elif attrib == "selectionDisabled":
173 guiObject.setSelectionEnable(0)
174 elif attrib == "transparent":
175 guiObject.setTransparent(int(value))
176 elif attrib == "borderColor":
177 guiObject.setBorderColor(parseColor(value))
178 elif attrib == "borderWidth":
179 guiObject.setBorderWidth(int(value))
180 elif attrib == "scrollbarMode":
181 guiObject.setScrollbarMode(
182 { "showOnDemand": guiObject.showOnDemand,
183 "showAlways": guiObject.showAlways,
184 "showNever": guiObject.showNever
186 elif attrib == "enableWrapAround":
187 guiObject.setWrapAround(True)
188 elif attrib == "pointer" or attrib == "seek_pointer":
189 (name, pos) = value.split(':')
190 pos = parsePosition(pos)
191 ptr = loadPixmap(name)
192 desktop.makeCompatiblePixmap(ptr.__deref__())
193 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr.__deref__(), pos)
194 elif attrib == 'shadowOffset':
195 guiObject.setShadowOffset(parsePosition(value))
196 elif attrib == 'noWrap':
197 guiObject.setNoWrap(1)
199 raise "unsupported attribute " + attrib + "=" + value
202 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
204 def applyAllAttributes(guiObject, desktop, attributes):
205 for (attrib, value) in attributes:
206 applySingleAttribute(guiObject, desktop, attrib, value)
208 def loadSingleSkinData(desktop, dom_skin, path_prefix):
209 """loads skin data like colors, windowstyle etc."""
211 skin = dom_skin.childNodes[0]
212 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
214 for c in elementsWithTag(skin.childNodes, "colors"):
215 for color in elementsWithTag(c.childNodes, "color"):
216 name = str(color.getAttribute("name"))
217 color = str(color.getAttribute("value"))
220 raise ("need color and name, got %s %s" % (name, color))
222 colorNames[name] = parseColor(color)
224 for c in elementsWithTag(skin.childNodes, "fonts"):
225 for font in elementsWithTag(c.childNodes, "font"):
226 filename = str(font.getAttribute("filename") or "<NONAME>")
227 name = str(font.getAttribute("name") or "Regular")
228 scale = int(font.getAttribute("scale") or "100")
229 is_replacement = font.getAttribute("replacement") != ""
230 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
232 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
233 style = eWindowStyleSkinned()
234 id = int(windowstyle.getAttribute("id") or "0")
237 font = gFont("Regular", 20)
238 offset = eSize(20, 5)
240 for title in elementsWithTag(windowstyle.childNodes, "title"):
241 offset = parseSize(title.getAttribute("offset"))
242 font = parseFont(str(title.getAttribute("font")))
244 style.setTitleFont(font);
245 style.setTitleOffset(offset)
247 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
248 bsName = str(borderset.getAttribute("name"))
249 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
250 bpName = str(pixmap.getAttribute("pos"))
251 filename = str(pixmap.getAttribute("filename"))
253 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
256 desktop.makeCompatiblePixmap(png.__deref__())
257 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png.__deref__())
259 for color in elementsWithTag(windowstyle.childNodes, "color"):
260 type = str(color.getAttribute("name"))
261 color = parseColor(color.getAttribute("color"))
264 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
266 raise ("Unknown color %s" % (type))
268 x = eWindowStyleManager.getInstance()
269 x.setStyle(id, style)
271 def loadSkinData(desktop):
274 for (path, dom_skin) in skins:
275 loadSingleSkinData(desktop, dom_skin, path)
277 def lookupScreen(name):
278 for (path, dom_skin) in dom_skins:
279 # first, find the corresponding screen element
280 skin = dom_skin.childNodes[0]
281 for x in elementsWithTag(skin.childNodes, "screen"):
282 if x.getAttribute('name') == name:
286 def readSkin(screen, skin, name, desktop):
288 myscreen, path = lookupScreen(name)
290 # otherwise try embedded skin
291 myscreen = myscreen or getattr(screen, "parsedSkin", None)
293 # try uncompiled embedded skin
294 if myscreen is None and getattr(screen, "skin", None):
295 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
297 assert myscreen is not None, "no skin for screen '" + name + "' found!"
299 screen.skinAttributes = [ ]
301 skin_path_prefix = getattr(screen, "skin_path", path)
303 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
305 screen.additionalWidgets = [ ]
306 screen.renderer = [ ]
308 visited_components = set()
310 # now walk all widgets
311 for widget in elementsWithTag(myscreen.childNodes, "widget"):
312 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
313 # widgets (source->renderer).
315 wname = widget.getAttribute('name')
316 wsource = widget.getAttribute('source')
319 if wname is None and wsource is None:
320 print "widget has no name and no source!"
324 visited_components.add(wname)
326 # get corresponding 'gui' object
328 attributes = screen[wname].skinAttributes = [ ]
330 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
332 # assert screen[wname] is not Source
334 # and collect attributes for this
335 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
337 # get corresponding source
338 source = screen.get(wsource)
340 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
342 wrender = widget.getAttribute('render')
345 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
347 for converter in elementsWithTag(widget.childNodes, "convert"):
348 ctype = converter.getAttribute('type')
349 assert ctype, "'convert'-tag needs a 'type'-attribute"
350 parms = mergeText(converter.childNodes).strip()
351 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
355 for i in source.downstream_elements:
356 if isinstance(i, converter_class) and i.converter_arguments == parms:
360 print "allocating new converter!"
361 c = converter_class(parms)
364 print "reused conveter!"
368 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
370 renderer = renderer_class() # instantiate renderer
372 renderer.connect(source) # connect to source
373 attributes = renderer.skinAttributes = [ ]
374 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
376 screen.renderer.append(renderer)
378 from Components.GUIComponent import GUIComponent
379 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
381 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
383 # now walk additional objects
384 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
385 if widget.tagName == "applet":
386 codeText = mergeText(widget.childNodes).strip()
387 type = widget.getAttribute('type')
389 code = compile(codeText, "skin applet", "exec")
391 if type == "onLayoutFinish":
392 screen.onLayoutFinish.append(code)
394 raise SkinError("applet type '%s' unknown!" % type)
398 class additionalWidget:
401 w = additionalWidget()
403 if widget.tagName == "eLabel":
405 elif widget.tagName == "ePixmap":
408 raise SkinError("unsupported stuff : %s" % widget.tagName)
410 w.skinAttributes = [ ]
411 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
413 # applyAttributes(guiObject, widget, desktop)
414 # guiObject.thisown = 0
415 screen.additionalWidgets.append(w)