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):
110 option = path.find("#")
112 options = path[option+1:].split(',')
114 cached = "cached" in options
115 ptr = LoadPixmap(path, desktop, cached)
117 raise SkinError("pixmap file %s not found!" % (path))
120 def applySingleAttribute(guiObject, desktop, attrib, value):
123 if attrib == 'position':
124 guiObject.move(parsePosition(value))
125 elif attrib == 'size':
126 guiObject.resize(parseSize(value))
127 elif attrib == 'title':
128 guiObject.setTitle(_(value))
129 elif attrib == 'text':
130 guiObject.setText(_(value))
131 elif attrib == 'font':
132 guiObject.setFont(parseFont(value))
133 elif attrib == 'zPosition':
134 guiObject.setZPosition(int(value))
135 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
136 ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
137 if attrib == "pixmap":
138 guiObject.setPixmap(ptr)
139 elif attrib == "backgroundPixmap":
140 guiObject.setBackgroundPicture(ptr)
141 elif attrib == "selectionPixmap":
142 guiObject.setSelectionPicture(ptr)
143 # guiObject.setPixmapFromFile(value)
144 elif attrib == "alphatest": # used by ePixmap
145 guiObject.setAlphatest(
150 elif attrib == "orientation": # used by eSlider
152 guiObject.setOrientation(
153 { "orVertical": guiObject.orVertical,
154 "orHorizontal": guiObject.orHorizontal
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)
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))
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):
227 for (attrib, value) in attributes:
228 applySingleAttribute(guiObject, desktop, attrib, value)
230 def loadSingleSkinData(desktop, dom_skin, path_prefix):
231 """loads skin data like colors, windowstyle etc."""
233 skin = dom_skin.childNodes[0]
234 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
236 for c in elementsWithTag(skin.childNodes, "output"):
237 id = int(c.getAttribute("id") or "0")
238 if id == 0: # framebuffer
239 for res in elementsWithTag(c.childNodes, "resolution"):
240 xres = int(res.getAttribute("xres" or "720"))
241 yres = int(res.getAttribute("yres" or "576"))
242 bpp = int(res.getAttribute("bpp" or "32"))
244 from enigma import gFBDC
245 i = gFBDC.getInstance()
246 i.setResolution(xres, yres)
249 # load palette (not yet implemented)
252 for c in elementsWithTag(skin.childNodes, "colors"):
253 for color in elementsWithTag(c.childNodes, "color"):
254 name = str(color.getAttribute("name"))
255 color = str(color.getAttribute("value"))
258 raise ("need color and name, got %s %s" % (name, color))
260 colorNames[name] = parseColor(color)
262 for c in elementsWithTag(skin.childNodes, "fonts"):
263 for font in elementsWithTag(c.childNodes, "font"):
264 filename = str(font.getAttribute("filename") or "<NONAME>")
265 name = str(font.getAttribute("name") or "Regular")
266 scale = int(font.getAttribute("scale") or "100")
267 is_replacement = font.getAttribute("replacement") != ""
268 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
270 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
271 style = eWindowStyleSkinned()
272 id = int(windowstyle.getAttribute("id") or "0")
275 font = gFont("Regular", 20)
276 offset = eSize(20, 5)
278 for title in elementsWithTag(windowstyle.childNodes, "title"):
279 offset = parseSize(title.getAttribute("offset"))
280 font = parseFont(str(title.getAttribute("font")))
282 style.setTitleFont(font);
283 style.setTitleOffset(offset)
285 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
286 bsName = str(borderset.getAttribute("name"))
287 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
288 bpName = str(pixmap.getAttribute("pos"))
289 filename = str(pixmap.getAttribute("filename"))
291 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
292 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
294 for color in elementsWithTag(windowstyle.childNodes, "color"):
295 type = str(color.getAttribute("name"))
296 color = parseColor(color.getAttribute("color"))
299 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
301 raise ("Unknown color %s" % (type))
303 x = eWindowStyleManager.getInstance()
304 x.setStyle(id, style)
306 def loadSkinData(desktop):
309 for (path, dom_skin) in skins:
310 loadSingleSkinData(desktop, dom_skin, path)
312 def lookupScreen(name):
313 for (path, dom_skin) in dom_skins:
314 # first, find the corresponding screen element
315 skin = dom_skin.childNodes[0]
316 for x in elementsWithTag(skin.childNodes, "screen"):
317 if x.getAttribute('name') == name:
321 def readSkin(screen, skin, names, desktop):
322 if not isinstance(names, list):
325 name = "<embedded-in-'%s'>" % screen.__class__.__name__
327 # try all skins, first existing one have priority
329 myscreen, path = lookupScreen(n)
330 if myscreen is not None:
331 # use this name for debug output
335 # otherwise try embedded skin
336 myscreen = myscreen or getattr(screen, "parsedSkin", None)
338 # try uncompiled embedded skin
339 if myscreen is None and getattr(screen, "skin", None):
340 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
342 assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
344 screen.skinAttributes = [ ]
346 skin_path_prefix = getattr(screen, "skin_path", path)
348 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
350 screen.additionalWidgets = [ ]
351 screen.renderer = [ ]
353 visited_components = set()
355 # now walk all widgets
356 for widget in elementsWithTag(myscreen.childNodes, "widget"):
357 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
358 # widgets (source->renderer).
360 wname = widget.getAttribute('name')
361 wsource = widget.getAttribute('source')
364 if wname is None and wsource is None:
365 print "widget has no name and no source!"
369 visited_components.add(wname)
371 # get corresponding 'gui' object
373 attributes = screen[wname].skinAttributes = [ ]
375 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
377 # assert screen[wname] is not Source
379 # and collect attributes for this
380 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
382 # get corresponding source
384 while True: # until we found a non-obsolete source
386 # parse our current "wsource", which might specifiy a "related screen" before the dot,
387 # for example to reference a parent, global or session-global screen.
390 # resolve all path components
391 path = wsource.split('.')
393 scr = screen.getRelatedScreen(path[0])
397 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
400 # resolve the source.
401 source = scr.get(path[0])
402 if isinstance(source, ObsoleteSource):
403 # however, if we found an "obsolete source", issue warning, and resolve the real source.
404 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
405 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
406 if source.description:
407 print source.description
409 wsource = source.new_source
411 # otherwise, use that source.
415 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
417 wrender = widget.getAttribute('render')
420 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
422 for converter in elementsWithTag(widget.childNodes, "convert"):
423 ctype = converter.getAttribute('type')
424 assert ctype, "'convert'-tag needs a 'type'-attribute"
425 parms = mergeText(converter.childNodes).strip()
426 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
430 for i in source.downstream_elements:
431 if isinstance(i, converter_class) and i.converter_arguments == parms:
435 print "allocating new converter!"
436 c = converter_class(parms)
439 print "reused converter!"
443 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
445 renderer = renderer_class() # instantiate renderer
447 renderer.connect(source) # connect to source
448 attributes = renderer.skinAttributes = [ ]
449 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
451 screen.renderer.append(renderer)
453 from Components.GUIComponent import GUIComponent
454 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
456 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
458 # now walk additional objects
459 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
460 if widget.tagName == "applet":
461 codeText = mergeText(widget.childNodes).strip()
462 type = widget.getAttribute('type')
464 code = compile(codeText, "skin applet", "exec")
466 if type == "onLayoutFinish":
467 screen.onLayoutFinish.append(code)
469 raise SkinError("applet type '%s' unknown!" % type)
473 class additionalWidget:
476 w = additionalWidget()
478 if widget.tagName == "eLabel":
480 elif widget.tagName == "ePixmap":
483 raise SkinError("unsupported stuff : %s" % widget.tagName)
485 w.skinAttributes = [ ]
486 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
488 # applyAttributes(guiObject, widget, desktop)
489 # guiObject.thisown = 0
490 screen.additionalWidgets.append(w)