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
17 def queryColor(colorName):
18 return colorNames.get(colorName)
21 print " " * i + str(x)
23 for n in x.childNodes:
28 class SkinError(Exception):
29 def __init__(self, message):
30 self.message = message
39 filename = resolveFilename(SCOPE_SKIN, name)
40 mpath = path.dirname(filename) + "/"
41 dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
43 # we do our best to always select the "right" value
44 # skins are loaded in order of priority: skin with
45 # highest priority is loaded last, usually the user-provided
48 # currently, loadSingleSkinData (colors, bordersets etc.)
49 # are applied one-after-each, in order of ascending priority.
50 # the dom_skin will keep all screens in descending priority,
51 # so the first screen found will be used.
53 # example: loadSkin("nemesis_greenline/skin.xml")
54 config.skin = ConfigSubsection()
55 config.skin.primary_skin = ConfigText(default = "skin.xml")
58 loadSkin(config.skin.primary_skin.value)
59 except (SkinError, IOError, AssertionError), err:
60 print "SKIN ERROR:", err
61 print "defaulting to standard skin..."
63 loadSkin('skin_default.xml')
65 def parsePosition(str):
67 return ePoint(int(x), int(y))
71 return eSize(int(x), int(y))
74 name, size = str.split(';')
75 return gFont(name, int(size))
80 return colorNames[str]
82 raise ("color '%s' must be #aarrggbb or valid named color" % (str))
83 return gRGB(int(str[1:], 0x10))
85 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
87 for p in range(node.attributes.length):
88 a = node.attributes.item(p)
90 # convert to string (was: unicode)
92 # TODO: localization? as in e1?
93 value = a.value.encode("utf-8")
95 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
96 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
98 if attrib not in ignore:
99 skinAttributes.append((attrib, value))
101 def loadPixmap(path):
104 raise "pixmap file %s not found!" % (path)
107 def applySingleAttribute(guiObject, desktop, attrib, value):
110 if attrib == 'position':
111 guiObject.move(parsePosition(value))
112 elif attrib == 'size':
113 guiObject.resize(parseSize(value))
114 elif attrib == 'title':
115 guiObject.setTitle(_(value))
116 elif attrib == 'text':
117 guiObject.setText(_(value))
118 elif attrib == 'font':
119 guiObject.setFont(parseFont(value))
120 elif attrib == 'zPosition':
121 guiObject.setZPosition(int(value))
122 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
123 ptr = loadPixmap(value) # this should already have been filename-resolved.
124 desktop.makeCompatiblePixmap(ptr)
125 if attrib == "pixmap":
126 guiObject.setPixmap(ptr)
127 elif attrib == "backgroundPixmap":
128 guiObject.setBackgroundPicture(ptr)
129 elif attrib == "selectionPixmap":
130 guiObject.setSelectionPicture(ptr)
131 # guiObject.setPixmapFromFile(value)
132 elif attrib == "alphatest": # used by ePixmap
133 guiObject.setAlphatest(
137 elif attrib == "orientation": # used by eSlider
139 guiObject.setOrientation(
140 { "orVertical": guiObject.orVertical,
141 "orHorizontal": guiObject.orHorizontal
144 print "oprientation must be either orVertical or orHorizontal!"
145 elif attrib == "valign":
148 { "top": guiObject.alignTop,
149 "center": guiObject.alignCenter,
150 "bottom": guiObject.alignBottom
153 print "valign must be either top, center or bottom!"
154 elif attrib == "halign":
157 { "left": guiObject.alignLeft,
158 "center": guiObject.alignCenter,
159 "right": guiObject.alignRight,
160 "block": guiObject.alignBlock
163 print "halign must be either left, center, right or block!"
164 elif attrib == "flags":
165 flags = value.split(',')
168 fv = eWindow.__dict__[f]
169 guiObject.setFlag(fv)
171 print "illegal flag %s!" % f
172 elif attrib == "backgroundColor":
173 guiObject.setBackgroundColor(parseColor(value))
174 elif attrib == "foregroundColor":
175 guiObject.setForegroundColor(parseColor(value))
176 elif attrib == "shadowColor":
177 guiObject.setShadowColor(parseColor(value))
178 elif attrib == "selectionDisabled":
179 guiObject.setSelectionEnable(0)
180 elif attrib == "transparent":
181 guiObject.setTransparent(int(value))
182 elif attrib == "borderColor":
183 guiObject.setBorderColor(parseColor(value))
184 elif attrib == "borderWidth":
185 guiObject.setBorderWidth(int(value))
186 elif attrib == "scrollbarMode":
187 guiObject.setScrollbarMode(
188 { "showOnDemand": guiObject.showOnDemand,
189 "showAlways": guiObject.showAlways,
190 "showNever": guiObject.showNever
192 elif attrib == "enableWrapAround":
193 guiObject.setWrapAround(True)
194 elif attrib == "pointer" or attrib == "seek_pointer":
195 (name, pos) = value.split(':')
196 pos = parsePosition(pos)
197 ptr = loadPixmap(name)
198 desktop.makeCompatiblePixmap(ptr)
199 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
200 elif attrib == 'shadowOffset':
201 guiObject.setShadowOffset(parsePosition(value))
202 elif attrib == 'noWrap':
203 guiObject.setNoWrap(1)
205 raise "unsupported attribute " + attrib + "=" + value
208 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
210 def applyAllAttributes(guiObject, desktop, attributes):
211 for (attrib, value) in attributes:
212 applySingleAttribute(guiObject, desktop, attrib, value)
214 def loadSingleSkinData(desktop, dom_skin, path_prefix):
215 """loads skin data like colors, windowstyle etc."""
217 skin = dom_skin.childNodes[0]
218 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
220 for c in elementsWithTag(skin.childNodes, "colors"):
221 for color in elementsWithTag(c.childNodes, "color"):
222 name = str(color.getAttribute("name"))
223 color = str(color.getAttribute("value"))
226 raise ("need color and name, got %s %s" % (name, color))
228 colorNames[name] = parseColor(color)
230 for c in elementsWithTag(skin.childNodes, "fonts"):
231 for font in elementsWithTag(c.childNodes, "font"):
232 filename = str(font.getAttribute("filename") or "<NONAME>")
233 name = str(font.getAttribute("name") or "Regular")
234 scale = int(font.getAttribute("scale") or "100")
235 is_replacement = font.getAttribute("replacement") != ""
236 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
238 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
239 style = eWindowStyleSkinned()
240 id = int(windowstyle.getAttribute("id") or "0")
243 font = gFont("Regular", 20)
244 offset = eSize(20, 5)
246 for title in elementsWithTag(windowstyle.childNodes, "title"):
247 offset = parseSize(title.getAttribute("offset"))
248 font = parseFont(str(title.getAttribute("font")))
250 style.setTitleFont(font);
251 style.setTitleOffset(offset)
253 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
254 bsName = str(borderset.getAttribute("name"))
255 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
256 bpName = str(pixmap.getAttribute("pos"))
257 filename = str(pixmap.getAttribute("filename"))
259 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
262 desktop.makeCompatiblePixmap(png)
263 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
265 for color in elementsWithTag(windowstyle.childNodes, "color"):
266 type = str(color.getAttribute("name"))
267 color = parseColor(color.getAttribute("color"))
270 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
272 raise ("Unknown color %s" % (type))
274 x = eWindowStyleManager.getInstance()
275 x.setStyle(id, style)
277 def loadSkinData(desktop):
280 for (path, dom_skin) in skins:
281 loadSingleSkinData(desktop, dom_skin, path)
283 def lookupScreen(name):
284 for (path, dom_skin) in dom_skins:
285 # first, find the corresponding screen element
286 skin = dom_skin.childNodes[0]
287 for x in elementsWithTag(skin.childNodes, "screen"):
288 if x.getAttribute('name') == name:
292 def readSkin(screen, skin, names, desktop):
293 if not isinstance(names, list):
296 name = "<embedded-in-'%s'>" % screen.__class__.__name__
298 # try all skins, first existing one have priority
300 myscreen, path = lookupScreen(n)
301 if myscreen is not None:
302 # use this name for debug output
306 # otherwise try embedded skin
307 myscreen = myscreen or getattr(screen, "parsedSkin", None)
309 # try uncompiled embedded skin
310 if myscreen is None and getattr(screen, "skin", None):
311 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
313 assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
315 screen.skinAttributes = [ ]
317 skin_path_prefix = getattr(screen, "skin_path", path)
319 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
321 screen.additionalWidgets = [ ]
322 screen.renderer = [ ]
324 visited_components = set()
326 # now walk all widgets
327 for widget in elementsWithTag(myscreen.childNodes, "widget"):
328 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
329 # widgets (source->renderer).
331 wname = widget.getAttribute('name')
332 wsource = widget.getAttribute('source')
335 if wname is None and wsource is None:
336 print "widget has no name and no source!"
340 visited_components.add(wname)
342 # get corresponding 'gui' object
344 attributes = screen[wname].skinAttributes = [ ]
346 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
348 # assert screen[wname] is not Source
350 # and collect attributes for this
351 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
353 # get corresponding source
355 while True: # until we found a non-obsolete source
357 # parse our current "wsource", which might specifiy a "related screen" before the dot,
358 # for example to reference a parent, global or session-global screen.
361 # resolve all path components
362 path = wsource.split('.')
364 scr = screen.getRelatedScreen(path[0])
368 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
371 # resolve the source.
372 source = scr.get(path[0])
373 if isinstance(source, ObsoleteSource):
374 # however, if we found an "obsolete source", issue warning, and resolve the real source.
375 print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
376 print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
377 if source.description:
378 print source.description
380 wsource = source.new_source
382 # otherwise, use that source.
386 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
388 wrender = widget.getAttribute('render')
391 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
393 for converter in elementsWithTag(widget.childNodes, "convert"):
394 ctype = converter.getAttribute('type')
395 assert ctype, "'convert'-tag needs a 'type'-attribute"
396 parms = mergeText(converter.childNodes).strip()
397 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
401 for i in source.downstream_elements:
402 if isinstance(i, converter_class) and i.converter_arguments == parms:
406 print "allocating new converter!"
407 c = converter_class(parms)
410 print "reused converter!"
414 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
416 renderer = renderer_class() # instantiate renderer
418 renderer.connect(source) # connect to source
419 attributes = renderer.skinAttributes = [ ]
420 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
422 screen.renderer.append(renderer)
424 from Components.GUIComponent import GUIComponent
425 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
427 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
429 # now walk additional objects
430 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
431 if widget.tagName == "applet":
432 codeText = mergeText(widget.childNodes).strip()
433 type = widget.getAttribute('type')
435 code = compile(codeText, "skin applet", "exec")
437 if type == "onLayoutFinish":
438 screen.onLayoutFinish.append(code)
440 raise SkinError("applet type '%s' unknown!" % type)
444 class additionalWidget:
447 w = additionalWidget()
449 if widget.tagName == "eLabel":
451 elif widget.tagName == "ePixmap":
454 raise SkinError("unsupported stuff : %s" % widget.tagName)
456 w.skinAttributes = [ ]
457 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
459 # applyAttributes(guiObject, widget, desktop)
460 # guiObject.thisown = 0
461 screen.additionalWidgets.append(w)