1 from Tools.Profile import profile, profile_final
3 profile("LOAD:minidom")
7 profile("LOAD:enigma_skin")
8 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
9 addFont, gRGB, eWindowStyleSkinned
11 from Components.config import ConfigSubsection, ConfigText, config
12 from Components.Converter.Converter import Converter
13 from Components.Sources.Source import Source, ObsoleteSource
14 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
15 from Tools.Import import my_import
16 from Tools.LoadPixmap import LoadPixmap
18 from Tools.XMLTools import elementsWithTag, mergeText
23 print " " * i + str(x)
25 for n in x.childNodes:
30 class SkinError(Exception):
31 def __init__(self, message):
32 self.message = message
41 filename = resolveFilename(SCOPE_SKIN, name)
42 mpath = path.dirname(filename) + "/"
43 dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
45 # we do our best to always select the "right" value
46 # skins are loaded in order of priority: skin with
47 # highest priority is loaded last, usually the user-provided
50 # currently, loadSingleSkinData (colors, bordersets etc.)
51 # are applied one-after-each, in order of ascending priority.
52 # the dom_skin will keep all screens in descending priority,
53 # so the first screen found will be used.
55 # example: loadSkin("nemesis_greenline/skin.xml")
56 config.skin = ConfigSubsection()
57 config.skin.primary_skin = ConfigText(default = "skin.xml")
61 loadSkin(config.skin.primary_skin.value)
62 except (SkinError, IOError, AssertionError), err:
63 print "SKIN ERROR:", err
64 print "defaulting to standard skin..."
65 config.skin.primary_skin.value = 'skin.xml'
68 profile("LoadSkinDefault")
69 loadSkin('skin_default.xml')
70 profile("LoadSkinDefaultDone")
72 def parsePosition(str):
74 return ePoint(int(x), int(y))
78 return eSize(int(x), int(y))
81 name, size = str.split(';')
82 return gFont(name, int(size))
87 return colorNames[str]
89 raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
90 return gRGB(int(str[1:], 0x10))
92 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
94 for p in range(node.attributes.length):
95 a = node.attributes.item(p)
97 # convert to string (was: unicode)
99 # TODO: localization? as in e1?
100 value = a.value.encode("utf-8")
102 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
103 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
105 if attrib not in ignore:
106 skinAttributes.append((attrib, value))
108 def loadPixmap(path, desktop):
109 ptr = LoadPixmap(path, desktop)
111 raise SkinError("pixmap file %s not found!" % (path))
114 def applySingleAttribute(guiObject, desktop, attrib, value):
117 if attrib == 'position':
118 guiObject.move(parsePosition(value))
119 elif attrib == 'size':
120 guiObject.resize(parseSize(value))
121 elif attrib == 'title':
122 guiObject.setTitle(_(value))
123 elif attrib == 'text':
124 guiObject.setText(_(value))
125 elif attrib == 'font':
126 guiObject.setFont(parseFont(value))
127 elif attrib == 'zPosition':
128 guiObject.setZPosition(int(value))
129 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
130 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
131 if attrib == "pixmap":
132 guiObject.setPixmap(ptr)
133 elif attrib == "backgroundPixmap":
134 guiObject.setBackgroundPicture(ptr)
135 elif attrib == "selectionPixmap":
136 guiObject.setSelectionPicture(ptr)
137 # guiObject.setPixmapFromFile(value)
138 elif attrib == "alphatest": # used by ePixmap
139 guiObject.setAlphatest(
144 elif attrib == "orientation": # used by eSlider
146 guiObject.setOrientation(
147 { "orVertical": guiObject.orVertical,
148 "orHorizontal": guiObject.orHorizontal
151 print "oprientation must be either orVertical or orHorizontal!"
152 elif attrib == "valign":
155 { "top": guiObject.alignTop,
156 "center": guiObject.alignCenter,
157 "bottom": guiObject.alignBottom
160 print "valign must be either top, center or bottom!"
161 elif attrib == "halign":
164 { "left": guiObject.alignLeft,
165 "center": guiObject.alignCenter,
166 "right": guiObject.alignRight,
167 "block": guiObject.alignBlock
170 print "halign must be either left, center, right or block!"
171 elif attrib == "flags":
172 flags = value.split(',')
175 fv = eWindow.__dict__[f]
176 guiObject.setFlag(fv)
178 print "illegal flag %s!" % f
179 elif attrib == "backgroundColor":
180 guiObject.setBackgroundColor(parseColor(value))
181 elif attrib == "backgroundColorSelected":
182 guiObject.setBackgroundColorSelected(parseColor(value))
183 elif attrib == "foregroundColor":
184 guiObject.setForegroundColor(parseColor(value))
185 elif attrib == "foregroundColorSelected":
186 guiObject.setForegroundColorSelected(parseColor(value))
187 elif attrib == "shadowColor":
188 guiObject.setShadowColor(parseColor(value))
189 elif attrib == "selectionDisabled":
190 guiObject.setSelectionEnable(0)
191 elif attrib == "transparent":
192 guiObject.setTransparent(int(value))
193 elif attrib == "borderColor":
194 guiObject.setBorderColor(parseColor(value))
195 elif attrib == "borderWidth":
196 guiObject.setBorderWidth(int(value))
197 elif attrib == "scrollbarMode":
198 guiObject.setScrollbarMode(
199 { "showOnDemand": guiObject.showOnDemand,
200 "showAlways": guiObject.showAlways,
201 "showNever": guiObject.showNever
203 elif attrib == "enableWrapAround":
204 guiObject.setWrapAround(True)
205 elif attrib == "pointer" or attrib == "seek_pointer":
206 (name, pos) = value.split(':')
207 pos = parsePosition(pos)
208 ptr = loadPixmap(name, desktop)
209 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
210 elif attrib == 'shadowOffset':
211 guiObject.setShadowOffset(parsePosition(value))
212 elif attrib == 'noWrap':
213 guiObject.setNoWrap(1)
215 raise SkinError("unsupported attribute " + attrib + "=" + value)
218 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
220 def applyAllAttributes(guiObject, desktop, attributes):
221 for (attrib, value) in attributes:
222 applySingleAttribute(guiObject, desktop, attrib, value)
224 def loadSingleSkinData(desktop, dom_skin, path_prefix):
225 """loads skin data like colors, windowstyle etc."""
227 skin = dom_skin.childNodes[0]
228 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
230 for c in elementsWithTag(skin.childNodes, "output"):
231 id = int(c.getAttribute("id") or "0")
232 if id == 0: # framebuffer
233 for res in elementsWithTag(c.childNodes, "resolution"):
234 xres = int(res.getAttribute("xres" or "720"))
235 yres = int(res.getAttribute("yres" or "576"))
236 bpp = int(res.getAttribute("bpp" or "32"))
238 from enigma import gFBDC
239 i = gFBDC.getInstance()
240 i.setResolution(xres, yres)
243 # load palette (not yet implemented)
246 for c in elementsWithTag(skin.childNodes, "colors"):
247 for color in elementsWithTag(c.childNodes, "color"):
248 name = str(color.getAttribute("name"))
249 color = str(color.getAttribute("value"))
252 raise ("need color and name, got %s %s" % (name, color))
254 colorNames[name] = parseColor(color)
256 for c in elementsWithTag(skin.childNodes, "fonts"):
257 for font in elementsWithTag(c.childNodes, "font"):
258 filename = str(font.getAttribute("filename") or "<NONAME>")
259 name = str(font.getAttribute("name") or "Regular")
260 scale = int(font.getAttribute("scale") or "100")
261 is_replacement = font.getAttribute("replacement") != ""
262 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
264 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
265 style = eWindowStyleSkinned()
266 id = int(windowstyle.getAttribute("id") or "0")
269 font = gFont("Regular", 20)
270 offset = eSize(20, 5)
272 for title in elementsWithTag(windowstyle.childNodes, "title"):
273 offset = parseSize(title.getAttribute("offset"))
274 font = parseFont(str(title.getAttribute("font")))
276 style.setTitleFont(font);
277 style.setTitleOffset(offset)
279 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
280 bsName = str(borderset.getAttribute("name"))
281 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
282 bpName = str(pixmap.getAttribute("pos"))
283 filename = str(pixmap.getAttribute("filename"))
285 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
286 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
288 for color in elementsWithTag(windowstyle.childNodes, "color"):
289 type = str(color.getAttribute("name"))
290 color = parseColor(color.getAttribute("color"))
293 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
295 raise ("Unknown color %s" % (type))
297 x = eWindowStyleManager.getInstance()
298 x.setStyle(id, style)
300 def loadSkinData(desktop):
303 for (path, dom_skin) in skins:
304 loadSingleSkinData(desktop, dom_skin, path)
306 def lookupScreen(name):
307 for (path, dom_skin) in dom_skins:
308 # first, find the corresponding screen element
309 skin = dom_skin.childNodes[0]
310 for x in elementsWithTag(skin.childNodes, "screen"):
311 if x.getAttribute('name') == name:
315 def readSkin(screen, skin, names, desktop):
316 if not isinstance(names, list):
319 name = "<embedded-in-'%s'>" % screen.__class__.__name__
321 # try all skins, first existing one have priority
323 myscreen, path = lookupScreen(n)
324 if myscreen is not None:
325 # use this name for debug output
329 # otherwise try embedded skin
330 myscreen = myscreen or getattr(screen, "parsedSkin", None)
332 # try uncompiled embedded skin
333 if myscreen is None and getattr(screen, "skin", None):
334 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
336 assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
338 screen.skinAttributes = [ ]
340 skin_path_prefix = getattr(screen, "skin_path", path)
342 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
344 screen.additionalWidgets = [ ]
345 screen.renderer = [ ]
347 visited_components = set()
349 # now walk all widgets
350 for widget in elementsWithTag(myscreen.childNodes, "widget"):
351 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
352 # widgets (source->renderer).
354 wname = widget.getAttribute('name')
355 wsource = widget.getAttribute('source')
358 if wname is None and wsource is None:
359 print "widget has no name and no source!"
363 visited_components.add(wname)
365 # get corresponding 'gui' object
367 attributes = screen[wname].skinAttributes = [ ]
369 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
371 # assert screen[wname] is not Source
373 # and collect attributes for this
374 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
376 # get corresponding source
378 while True: # until we found a non-obsolete source
380 # parse our current "wsource", which might specifiy a "related screen" before the dot,
381 # for example to reference a parent, global or session-global screen.
384 # resolve all path components
385 path = wsource.split('.')
387 scr = screen.getRelatedScreen(path[0])
391 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
394 # resolve the source.
395 source = scr.get(path[0])
396 if isinstance(source, ObsoleteSource):
397 # however, if we found an "obsolete source", issue warning, and resolve the real source.
398 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
399 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
400 if source.description:
401 print source.description
403 wsource = source.new_source
405 # otherwise, use that source.
409 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
411 wrender = widget.getAttribute('render')
414 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
416 for converter in elementsWithTag(widget.childNodes, "convert"):
417 ctype = converter.getAttribute('type')
418 assert ctype, "'convert'-tag needs a 'type'-attribute"
419 parms = mergeText(converter.childNodes).strip()
420 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
424 for i in source.downstream_elements:
425 if isinstance(i, converter_class) and i.converter_arguments == parms:
429 print "allocating new converter!"
430 c = converter_class(parms)
433 print "reused converter!"
437 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
439 renderer = renderer_class() # instantiate renderer
441 renderer.connect(source) # connect to source
442 attributes = renderer.skinAttributes = [ ]
443 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
445 screen.renderer.append(renderer)
447 from Components.GUIComponent import GUIComponent
448 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
450 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
452 # now walk additional objects
453 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
454 if widget.tagName == "applet":
455 codeText = mergeText(widget.childNodes).strip()
456 type = widget.getAttribute('type')
458 code = compile(codeText, "skin applet", "exec")
460 if type == "onLayoutFinish":
461 screen.onLayoutFinish.append(code)
463 raise SkinError("applet type '%s' unknown!" % type)
467 class additionalWidget:
470 w = additionalWidget()
472 if widget.tagName == "eLabel":
474 elif widget.tagName == "ePixmap":
477 raise SkinError("unsupported stuff : %s" % widget.tagName)
479 w.skinAttributes = [ ]
480 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
482 # applyAttributes(guiObject, widget, desktop)
483 # guiObject.thisown = 0
484 screen.additionalWidgets.append(w)