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 Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS
10 from Tools.Import import my_import
12 from Tools.XMLTools import elementsWithTag, mergeText
17 print " " * i + str(x)
19 for n in x.childNodes:
24 class SkinError(Exception):
25 def __init__(self, message):
26 self.message = message
35 filename = resolveFilename(SCOPE_SKIN, name)
36 mpath = path.dirname(filename) + "/"
37 dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
39 # we do our best to always select the "right" value
40 # skins are loaded in order of priority: skin with
41 # highest priority is loaded last, usually the user-provided
44 # currently, loadSingleSkinData (colors, bordersets etc.)
45 # are applied one-after-each, in order of ascending priority.
46 # the dom_skin will keep all screens in descending priority,
47 # so the first screen found will be used.
49 # example: loadSkin("nemesis_greenline/skin.xml")
50 config.skin = ConfigSubsection()
51 config.skin.primary_skin = ConfigText(default = "skin.xml")
54 loadSkin(config.skin.primary_skin.value)
55 except (SkinError, IOError, AssertionError), err:
56 print "SKIN ERROR:", err
57 print "defaulting to standard skin..."
59 loadSkin('skin_default.xml')
61 def parsePosition(str):
63 return ePoint(int(x), int(y))
67 return eSize(int(x), int(y))
70 name, size = str.split(';')
71 return gFont(name, int(size))
76 return colorNames[str]
78 raise ("color '%s' must be #aarrggbb or valid named color" % (str))
79 return gRGB(int(str[1:], 0x10))
81 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
83 for p in range(node.attributes.length):
84 a = node.attributes.item(p)
86 # convert to string (was: unicode)
88 # TODO: localization? as in e1?
89 value = a.value.encode("utf-8")
91 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
92 value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
94 if attrib not in ignore:
95 skinAttributes.append((attrib, value))
100 raise "pixmap file %s not found!" % (path)
103 def applySingleAttribute(guiObject, desktop, attrib, value):
106 if attrib == 'position':
107 guiObject.move(parsePosition(value))
108 elif attrib == 'size':
109 guiObject.resize(parseSize(value))
110 elif attrib == 'title':
111 guiObject.setTitle(_(value))
112 elif attrib == 'text':
113 guiObject.setText(_(value))
114 elif attrib == 'font':
115 guiObject.setFont(parseFont(value))
116 elif attrib == 'zPosition':
117 guiObject.setZPosition(int(value))
118 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
119 ptr = loadPixmap(value) # this should already have been filename-resolved.
120 desktop.makeCompatiblePixmap(ptr)
121 if attrib == "pixmap":
122 guiObject.setPixmap(ptr)
123 elif attrib == "backgroundPixmap":
124 guiObject.setBackgroundPicture(ptr)
125 elif attrib == "selectionPixmap":
126 guiObject.setSelectionPicture(ptr)
127 # guiObject.setPixmapFromFile(value)
128 elif attrib == "alphatest": # used by ePixmap
129 guiObject.setAlphatest(
133 elif attrib == "orientation": # used by eSlider
135 guiObject.setOrientation(
136 { "orVertical": guiObject.orVertical,
137 "orHorizontal": guiObject.orHorizontal
140 print "oprientation must be either orVertical or orHorizontal!"
141 elif attrib == "valign":
144 { "top": guiObject.alignTop,
145 "center": guiObject.alignCenter,
146 "bottom": guiObject.alignBottom
149 print "valign must be either top, center or bottom!"
150 elif attrib == "halign":
153 { "left": guiObject.alignLeft,
154 "center": guiObject.alignCenter,
155 "right": guiObject.alignRight,
156 "block": guiObject.alignBlock
159 print "halign must be either left, center, right or block!"
160 elif attrib == "flags":
161 flags = value.split(',')
164 fv = eWindow.__dict__[f]
165 guiObject.setFlag(fv)
167 print "illegal flag %s!" % f
168 elif attrib == "backgroundColor":
169 guiObject.setBackgroundColor(parseColor(value))
170 elif attrib == "foregroundColor":
171 guiObject.setForegroundColor(parseColor(value))
172 elif attrib == "shadowColor":
173 guiObject.setShadowColor(parseColor(value))
174 elif attrib == "selectionDisabled":
175 guiObject.setSelectionEnable(0)
176 elif attrib == "transparent":
177 guiObject.setTransparent(int(value))
178 elif attrib == "borderColor":
179 guiObject.setBorderColor(parseColor(value))
180 elif attrib == "borderWidth":
181 guiObject.setBorderWidth(int(value))
182 elif attrib == "scrollbarMode":
183 guiObject.setScrollbarMode(
184 { "showOnDemand": guiObject.showOnDemand,
185 "showAlways": guiObject.showAlways,
186 "showNever": guiObject.showNever
188 elif attrib == "enableWrapAround":
189 guiObject.setWrapAround(True)
190 elif attrib == "pointer" or attrib == "seek_pointer":
191 (name, pos) = value.split(':')
192 pos = parsePosition(pos)
193 ptr = loadPixmap(name)
194 desktop.makeCompatiblePixmap(ptr)
195 guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
196 elif attrib == 'shadowOffset':
197 guiObject.setShadowOffset(parsePosition(value))
198 elif attrib == 'noWrap':
199 guiObject.setNoWrap(1)
201 raise "unsupported attribute " + attrib + "=" + value
204 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
206 def applyAllAttributes(guiObject, desktop, attributes):
207 for (attrib, value) in attributes:
208 applySingleAttribute(guiObject, desktop, attrib, value)
210 def loadSingleSkinData(desktop, dom_skin, path_prefix):
211 """loads skin data like colors, windowstyle etc."""
213 skin = dom_skin.childNodes[0]
214 assert skin.tagName == "skin", "root element in skin must be 'skin'!"
216 for c in elementsWithTag(skin.childNodes, "colors"):
217 for color in elementsWithTag(c.childNodes, "color"):
218 name = str(color.getAttribute("name"))
219 color = str(color.getAttribute("value"))
222 raise ("need color and name, got %s %s" % (name, color))
224 colorNames[name] = parseColor(color)
226 for c in elementsWithTag(skin.childNodes, "fonts"):
227 for font in elementsWithTag(c.childNodes, "font"):
228 filename = str(font.getAttribute("filename") or "<NONAME>")
229 name = str(font.getAttribute("name") or "Regular")
230 scale = int(font.getAttribute("scale") or "100")
231 is_replacement = font.getAttribute("replacement") != ""
232 addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
234 for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
235 style = eWindowStyleSkinned()
236 id = int(windowstyle.getAttribute("id") or "0")
239 font = gFont("Regular", 20)
240 offset = eSize(20, 5)
242 for title in elementsWithTag(windowstyle.childNodes, "title"):
243 offset = parseSize(title.getAttribute("offset"))
244 font = parseFont(str(title.getAttribute("font")))
246 style.setTitleFont(font);
247 style.setTitleOffset(offset)
249 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
250 bsName = str(borderset.getAttribute("name"))
251 for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
252 bpName = str(pixmap.getAttribute("pos"))
253 filename = str(pixmap.getAttribute("filename"))
255 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
258 desktop.makeCompatiblePixmap(png)
259 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
261 for color in elementsWithTag(windowstyle.childNodes, "color"):
262 type = str(color.getAttribute("name"))
263 color = parseColor(color.getAttribute("color"))
266 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
268 raise ("Unknown color %s" % (type))
270 x = eWindowStyleManager.getInstance()
271 x.setStyle(id, style)
273 def loadSkinData(desktop):
276 for (path, dom_skin) in skins:
277 loadSingleSkinData(desktop, dom_skin, path)
279 def lookupScreen(name):
280 for (path, dom_skin) in dom_skins:
281 # first, find the corresponding screen element
282 skin = dom_skin.childNodes[0]
283 for x in elementsWithTag(skin.childNodes, "screen"):
284 if x.getAttribute('name') == name:
288 def readSkin(screen, skin, name, desktop):
289 if not isinstance(name, list):
292 # try all skins, first existing one have priority
294 myscreen, path = lookupScreen(n)
295 if myscreen is not None:
298 # otherwise try embedded skin
299 myscreen = myscreen or getattr(screen, "parsedSkin", None)
301 # try uncompiled embedded skin
302 if myscreen is None and getattr(screen, "skin", None):
303 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
305 assert myscreen is not None, "no skin for screen '" + repr(name) + "' found!"
307 screen.skinAttributes = [ ]
309 skin_path_prefix = getattr(screen, "skin_path", path)
311 collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
313 screen.additionalWidgets = [ ]
314 screen.renderer = [ ]
316 visited_components = set()
318 # now walk all widgets
319 for widget in elementsWithTag(myscreen.childNodes, "widget"):
320 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
321 # widgets (source->renderer).
323 wname = widget.getAttribute('name')
324 wsource = widget.getAttribute('source')
327 if wname is None and wsource is None:
328 print "widget has no name and no source!"
332 visited_components.add(wname)
334 # get corresponding 'gui' object
336 attributes = screen[wname].skinAttributes = [ ]
338 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
340 # assert screen[wname] is not Source
342 # and collect attributes for this
343 collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
345 # get corresponding source
346 source = screen.get(wsource)
348 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
350 wrender = widget.getAttribute('render')
353 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
355 for converter in elementsWithTag(widget.childNodes, "convert"):
356 ctype = converter.getAttribute('type')
357 assert ctype, "'convert'-tag needs a 'type'-attribute"
358 parms = mergeText(converter.childNodes).strip()
359 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
363 for i in source.downstream_elements:
364 if isinstance(i, converter_class) and i.converter_arguments == parms:
368 print "allocating new converter!"
369 c = converter_class(parms)
372 print "reused conveter!"
376 renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
378 renderer = renderer_class() # instantiate renderer
380 renderer.connect(source) # connect to source
381 attributes = renderer.skinAttributes = [ ]
382 collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
384 screen.renderer.append(renderer)
386 from Components.GUIComponent import GUIComponent
387 nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
389 assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
391 # now walk additional objects
392 for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
393 if widget.tagName == "applet":
394 codeText = mergeText(widget.childNodes).strip()
395 type = widget.getAttribute('type')
397 code = compile(codeText, "skin applet", "exec")
399 if type == "onLayoutFinish":
400 screen.onLayoutFinish.append(code)
402 raise SkinError("applet type '%s' unknown!" % type)
406 class additionalWidget:
409 w = additionalWidget()
411 if widget.tagName == "eLabel":
413 elif widget.tagName == "ePixmap":
416 raise SkinError("unsupported stuff : %s" % widget.tagName)
418 w.skinAttributes = [ ]
419 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
421 # applyAttributes(guiObject, widget, desktop)
422 # guiObject.thisown = 0
423 screen.additionalWidgets.append(w)