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 ("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 "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 == "foregroundColor":
172 guiObject.setForegroundColor(parseColor(value))
173 elif attrib == "shadowColor":
174 guiObject.setShadowColor(parseColor(value))
175 elif attrib == "selectionDisabled":
176 guiObject.setSelectionEnable(0)
177 elif attrib == "transparent":
178 guiObject.setTransparent(int(value))
179 elif attrib == "borderColor":
180 guiObject.setBorderColor(parseColor(value))
181 elif attrib == "borderWidth":
182 guiObject.setBorderWidth(int(value))
183 elif attrib == "scrollbarMode":
184 guiObject.setScrollbarMode(
185 { "showOnDemand": guiObject.showOnDemand,
186 "showAlways": guiObject.showAlways,
187 "showNever": guiObject.showNever
189 elif attrib == "enableWrapAround":
190 guiObject.setWrapAround(True)
191 elif attrib == "pointer" or attrib == "seek_pointer":
192 (name, pos) = value.split(':')
193 pos = parsePosition(pos)
194 ptr = loadPixmap(name)
195 desktop.makeCompatiblePixmap(ptr)
196 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
197 elif attrib == 'shadowOffset':
198 guiObject.setShadowOffset(parsePosition(value))
199 elif attrib == 'noWrap':
200 guiObject.setNoWrap(1)
202 raise "unsupported attribute " + attrib + "=" + value
205 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
207 def applyAllAttributes(guiObject, desktop, attributes):
208 for (attrib, value) in attributes:
209 applySingleAttribute(guiObject, desktop, attrib, value)
211 def loadSingleSkinData(desktop, dom_skin, path_prefix):
212 """loads skin data like colors, windowstyle etc."""
214 skin = dom_skin.childNodes[0]
215 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
217 for c in elementsWithTag(skin.childNodes, "colors"):
218 for color in elementsWithTag(c.childNodes, "color"):
219 name = str(color.getAttribute("name"))
220 color = str(color.getAttribute("value"))
223 raise ("need color and name, got %s %s" % (name, color))
225 colorNames[name] = parseColor(color)
227 for c in elementsWithTag(skin.childNodes, "fonts"):
228 for font in elementsWithTag(c.childNodes, "font"):
229 filename = str(font.getAttribute("filename") or "<NONAME>")
230 name = str(font.getAttribute("name") or "Regular")
231 scale = int(font.getAttribute("scale") or "100")
232 is_replacement = font.getAttribute("replacement") != ""
233 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
235 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
236 style = eWindowStyleSkinned()
237 id = int(windowstyle.getAttribute("id") or "0")
240 font = gFont("Regular", 20)
241 offset = eSize(20, 5)
243 for title in elementsWithTag(windowstyle.childNodes, "title"):
244 offset = parseSize(title.getAttribute("offset"))
245 font = parseFont(str(title.getAttribute("font")))
247 style.setTitleFont(font);
248 style.setTitleOffset(offset)
250 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
251 bsName = str(borderset.getAttribute("name"))
252 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
253 bpName = str(pixmap.getAttribute("pos"))
254 filename = str(pixmap.getAttribute("filename"))
256 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
259 desktop.makeCompatiblePixmap(png)
260 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
262 for color in elementsWithTag(windowstyle.childNodes, "color"):
263 type = str(color.getAttribute("name"))
264 color = parseColor(color.getAttribute("color"))
267 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
269 raise ("Unknown color %s" % (type))
271 x = eWindowStyleManager.getInstance()
272 x.setStyle(id, style)
274 def loadSkinData(desktop):
277 for (path, dom_skin) in skins:
278 loadSingleSkinData(desktop, dom_skin, path)
280 def lookupScreen(name):
281 for (path, dom_skin) in dom_skins:
282 # first, find the corresponding screen element
283 skin = dom_skin.childNodes[0]
284 for x in elementsWithTag(skin.childNodes, "screen"):
285 if x.getAttribute('name') == name:
289 def readSkin(screen, skin, names, desktop):
290 if not isinstance(names, list):
293 name = "<embedded-in-'%s'>" % screen.__class__.__name__
295 # try all skins, first existing one have priority
297 myscreen, path = lookupScreen(n)
298 if myscreen is not None:
299 # use this name for debug output
303 # otherwise try embedded skin
304 myscreen = myscreen or getattr(screen, "parsedSkin", None)
306 # try uncompiled embedded skin
307 if myscreen is None and getattr(screen, "skin", None):
308 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
310 assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
312 screen.skinAttributes = [ ]
314 skin_path_prefix = getattr(screen, "skin_path", path)
316 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
318 screen.additionalWidgets = [ ]
319 screen.renderer = [ ]
321 visited_components = set()
323 # now walk all widgets
324 for widget in elementsWithTag(myscreen.childNodes, "widget"):
325 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
326 # widgets (source->renderer).
328 wname = widget.getAttribute('name')
329 wsource = widget.getAttribute('source')
332 if wname is None and wsource is None:
333 print "widget has no name and no source!"
337 visited_components.add(wname)
339 # get corresponding 'gui' object
341 attributes = screen[wname].skinAttributes = [ ]
343 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
345 # assert screen[wname] is not Source
347 # and collect attributes for this
348 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
350 # get corresponding source
352 while True: # until we found a non-obsolete source
354 # parse our current "wsource", which might specifiy a "related screen" before the dot,
355 # for example to reference a parent, global or session-global screen.
358 # resolve all path components
359 path = wsource.split('.')
361 scr = screen.getRelatedScreen(path[0])
365 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
368 # resolve the source.
369 source = scr.get(path[0])
370 if isinstance(source, ObsoleteSource):
371 # however, if we found an "obsolete source", issue warning, and resolve the real source.
372 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
373 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
374 if source.description:
375 print source.description
377 wsource = source.new_source
379 # otherwise, use that source.
383 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
385 wrender = widget.getAttribute('render')
388 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
390 for converter in elementsWithTag(widget.childNodes, "convert"):
391 ctype = converter.getAttribute('type')
392 assert ctype, "'convert'-tag needs a 'type'-attribute"
393 parms = mergeText(converter.childNodes).strip()
394 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
398 for i in source.downstream_elements:
399 if isinstance(i, converter_class) and i.converter_arguments == parms:
403 print "allocating new converter!"
404 c = converter_class(parms)
407 print "reused converter!"
411 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
413 renderer = renderer_class() # instantiate renderer
415 renderer.connect(source) # connect to source
416 attributes = renderer.skinAttributes = [ ]
417 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
419 screen.renderer.append(renderer)
421 from Components.GUIComponent import GUIComponent
422 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
424 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
426 # now walk additional objects
427 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
428 if widget.tagName == "applet":
429 codeText = mergeText(widget.childNodes).strip()
430 type = widget.getAttribute('type')
432 code = compile(codeText, "skin applet", "exec")
434 if type == "onLayoutFinish":
435 screen.onLayoutFinish.append(code)
437 raise SkinError("applet type '%s' unknown!" % type)
441 class additionalWidget:
444 w = additionalWidget()
446 if widget.tagName == "eLabel":
448 elif widget.tagName == "ePixmap":
451 raise SkinError("unsupported stuff : %s" % widget.tagName)
453 w.skinAttributes = [ ]
454 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
456 # applyAttributes(guiObject, widget, desktop)
457 # guiObject.thisown = 0
458 screen.additionalWidgets.append(w)