fix close return values for non execing dialogs
[enigma2.git] / skin.py
1 import xml.dom.minidom
2 from os import path
3
4 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
5         loadPNG, addFont, gRGB, eWindowStyleSkinned
6
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
12
13 from Tools.XMLTools import elementsWithTag, mergeText
14
15 colorNames = dict()
16
17 def dump(x, i=0):
18         print " " * i + str(x)
19         try:
20                 for n in x.childNodes:
21                         dump(n, i + 1)
22         except:
23                 None
24
25 class SkinError(Exception):
26         def __init__(self, message):
27                 self.message = message
28
29         def __str__(self):
30                 return self.message
31
32 dom_skins = [ ]
33
34 def loadSkin(name):
35         # read the skin
36         filename = resolveFilename(SCOPE_SKIN, name)
37         mpath = path.dirname(filename) + "/"
38         dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
39
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
43 # skin.
44
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.
49
50 # example: loadSkin("nemesis_greenline/skin.xml")
51 config.skin = ConfigSubsection()
52 config.skin.primary_skin = ConfigText(default = "skin.xml")
53
54 try:
55         loadSkin(config.skin.primary_skin.value)
56 except (SkinError, IOError, AssertionError), err:
57         print "SKIN ERROR:", err
58         print "defaulting to standard skin..."
59         loadSkin('skin.xml')
60 loadSkin('skin_default.xml')
61
62 def parsePosition(str):
63         x, y = str.split(',')
64         return ePoint(int(x), int(y))
65
66 def parseSize(str):
67         x, y = str.split(',')
68         return eSize(int(x), int(y))
69
70 def parseFont(str):
71         name, size = str.split(';')
72         return gFont(name, int(size))
73
74 def parseColor(str):
75         if str[0] != '#':
76                 try:
77                         return colorNames[str]
78                 except:
79                         raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
80         return gRGB(int(str[1:], 0x10))
81
82 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
83         # walk all attributes
84         for p in range(node.attributes.length):
85                 a = node.attributes.item(p)
86                 
87                 # convert to string (was: unicode)
88                 attrib = str(a.name)
89                 # TODO: localization? as in e1?
90                 value = a.value.encode("utf-8")
91                 
92                 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
93                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
94                 
95                 if attrib not in ignore:
96                         skinAttributes.append((attrib, value))
97
98 def loadPixmap(path):
99         ptr = loadPNG(path)
100         if ptr is None:
101                 raise SkinError("pixmap file %s not found!" % (path))
102         return ptr
103
104 def applySingleAttribute(guiObject, desktop, attrib, value):
105         # and set attributes
106         try:
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(
131                                 { "on": True,
132                                   "off": False
133                                 }[value])
134                 elif attrib == "orientation": # used by eSlider
135                         try:
136                                 guiObject.setOrientation(
137                                         { "orVertical": guiObject.orVertical,
138                                                 "orHorizontal": guiObject.orHorizontal
139                                         }[value])
140                         except KeyError:
141                                 print "oprientation must be either orVertical or orHorizontal!"
142                 elif attrib == "valign":
143                         try:
144                                 guiObject.setVAlign(
145                                         { "top": guiObject.alignTop,
146                                                 "center": guiObject.alignCenter,
147                                                 "bottom": guiObject.alignBottom
148                                         }[value])
149                         except KeyError:
150                                 print "valign must be either top, center or bottom!"
151                 elif attrib == "halign":
152                         try:
153                                 guiObject.setHAlign(
154                                         { "left": guiObject.alignLeft,
155                                                 "center": guiObject.alignCenter,
156                                                 "right": guiObject.alignRight,
157                                                 "block": guiObject.alignBlock
158                                         }[value])
159                         except KeyError:
160                                 print "halign must be either left, center, right or block!"
161                 elif attrib == "flags":
162                         flags = value.split(',')
163                         for f in flags:
164                                 try:
165                                         fv = eWindow.__dict__[f]
166                                         guiObject.setFlag(fv)
167                                 except KeyError:
168                                         print "illegal flag %s!" % f
169                 elif attrib == "backgroundColor":
170                         guiObject.setBackgroundColor(parseColor(value))
171                 elif attrib == "backgroundColorSelected":
172                         guiObject.setBackgroundColorSelected(parseColor(value))
173                 elif attrib == "foregroundColor":
174                         guiObject.setForegroundColor(parseColor(value))
175                 elif attrib == "foregroundColorSelected":
176                         guiObject.setForegroundColorSelected(parseColor(value))
177                 elif attrib == "shadowColor":
178                         guiObject.setShadowColor(parseColor(value))
179                 elif attrib == "selectionDisabled":
180                         guiObject.setSelectionEnable(0)
181                 elif attrib == "transparent":
182                         guiObject.setTransparent(int(value))
183                 elif attrib == "borderColor":
184                         guiObject.setBorderColor(parseColor(value))
185                 elif attrib == "borderWidth":
186                         guiObject.setBorderWidth(int(value))
187                 elif attrib == "scrollbarMode":
188                         guiObject.setScrollbarMode(
189                                 { "showOnDemand": guiObject.showOnDemand,
190                                         "showAlways": guiObject.showAlways,
191                                         "showNever": guiObject.showNever
192                                 }[value])
193                 elif attrib == "enableWrapAround":
194                         guiObject.setWrapAround(True)
195                 elif attrib == "pointer" or attrib == "seek_pointer":
196                         (name, pos) = value.split(':')
197                         pos = parsePosition(pos)
198                         ptr = loadPixmap(name)
199                         desktop.makeCompatiblePixmap(ptr)
200                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
201                 elif attrib == 'shadowOffset':
202                         guiObject.setShadowOffset(parsePosition(value))
203                 elif attrib == 'noWrap':
204                         guiObject.setNoWrap(1)
205                 else:
206                         raise SkinError("unsupported attribute " + attrib + "=" + value)
207         except int:
208 # AttributeError:
209                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
210
211 def applyAllAttributes(guiObject, desktop, attributes):
212         for (attrib, value) in attributes:
213                 applySingleAttribute(guiObject, desktop, attrib, value)
214
215 def loadSingleSkinData(desktop, dom_skin, path_prefix):
216         """loads skin data like colors, windowstyle etc."""
217         
218         skin = dom_skin.childNodes[0]
219         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
220
221         for c in elementsWithTag(skin.childNodes, "output"):
222                 id = int(c.getAttribute("id") or "0")
223                 if id == 0: # framebuffer
224                         for res in elementsWithTag(c.childNodes, "resolution"):
225                                 xres = int(res.getAttribute("xres" or "720"))
226                                 yres = int(res.getAttribute("yres" or "576"))
227                                 bpp = int(res.getAttribute("bpp" or "32"))
228
229                                 from enigma import gFBDC
230                                 i = gFBDC.getInstance()
231                                 i.setResolution(xres, yres)
232
233                                 if bpp != 32:
234                                         # load palette (not yet implemented)
235                                         pass
236
237         for c in elementsWithTag(skin.childNodes, "colors"):
238                 for color in elementsWithTag(c.childNodes, "color"):
239                         name = str(color.getAttribute("name"))
240                         color = str(color.getAttribute("value"))
241                         
242                         if not len(color):
243                                 raise ("need color and name, got %s %s" % (name, color))
244                                 
245                         colorNames[name] = parseColor(color)
246         
247         for c in elementsWithTag(skin.childNodes, "fonts"):
248                 for font in elementsWithTag(c.childNodes, "font"):
249                         filename = str(font.getAttribute("filename") or "<NONAME>")
250                         name = str(font.getAttribute("name") or "Regular")
251                         scale = int(font.getAttribute("scale") or "100")
252                         is_replacement = font.getAttribute("replacement") != ""
253                         addFont(resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix), name, scale, is_replacement)
254         
255         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
256                 style = eWindowStyleSkinned()
257                 id = int(windowstyle.getAttribute("id") or "0")
258                 
259                 # defaults
260                 font = gFont("Regular", 20)
261                 offset = eSize(20, 5)
262                 
263                 for title in elementsWithTag(windowstyle.childNodes, "title"):
264                         offset = parseSize(title.getAttribute("offset"))
265                         font = parseFont(str(title.getAttribute("font")))
266
267                 style.setTitleFont(font);
268                 style.setTitleOffset(offset)
269                 
270                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
271                         bsName = str(borderset.getAttribute("name"))
272                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
273                                 bpName = str(pixmap.getAttribute("pos"))
274                                 filename = str(pixmap.getAttribute("filename"))
275                                 
276                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix))
277                                 
278                                 # adapt palette
279                                 desktop.makeCompatiblePixmap(png)
280                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
281
282                 for color in elementsWithTag(windowstyle.childNodes, "color"):
283                         type = str(color.getAttribute("name"))
284                         color = parseColor(color.getAttribute("color"))
285                         
286                         try:
287                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
288                         except:
289                                 raise ("Unknown color %s" % (type))
290                         
291                 x = eWindowStyleManager.getInstance()
292                 x.setStyle(id, style)
293
294 def loadSkinData(desktop):
295         skins = dom_skins[:]
296         skins.reverse()
297         for (path, dom_skin) in skins:
298                 loadSingleSkinData(desktop, dom_skin, path)
299
300 def lookupScreen(name):
301         for (path, dom_skin) in dom_skins:
302                 # first, find the corresponding screen element
303                 skin = dom_skin.childNodes[0] 
304                 for x in elementsWithTag(skin.childNodes, "screen"):
305                         if x.getAttribute('name') == name:
306                                 return x, path
307         return None, None
308
309 def readSkin(screen, skin, names, desktop):
310         if not isinstance(names, list):
311                 names = [names]
312
313         name = "<embedded-in-'%s'>" % screen.__class__.__name__
314
315         # try all skins, first existing one have priority
316         for n in names:
317                 myscreen, path = lookupScreen(n)
318                 if myscreen is not None:
319                         # use this name for debug output
320                         name = n
321                         break
322
323         # otherwise try embedded skin
324         myscreen = myscreen or getattr(screen, "parsedSkin", None)
325
326         # try uncompiled embedded skin
327         if myscreen is None and getattr(screen, "skin", None):
328                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
329
330         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
331
332         screen.skinAttributes = [ ]
333         
334         skin_path_prefix = getattr(screen, "skin_path", path)
335
336         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
337         
338         screen.additionalWidgets = [ ]
339         screen.renderer = [ ]
340         
341         visited_components = set()
342         
343         # now walk all widgets
344         for widget in elementsWithTag(myscreen.childNodes, "widget"):
345                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
346                 # widgets (source->renderer).
347
348                 wname = widget.getAttribute('name')
349                 wsource = widget.getAttribute('source')
350                 
351
352                 if wname is None and wsource is None:
353                         print "widget has no name and no source!"
354                         continue
355                 
356                 if wname:
357                         visited_components.add(wname)
358
359                         # get corresponding 'gui' object
360                         try:
361                                 attributes = screen[wname].skinAttributes = [ ]
362                         except:
363                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
364
365 #                       assert screen[wname] is not Source
366
367                         # and collect attributes for this
368                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
369                 elif wsource:
370                         # get corresponding source
371
372                         while True: # until we found a non-obsolete source
373
374                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
375                                 # for example to reference a parent, global or session-global screen.
376                                 scr = screen
377
378                                 # resolve all path components
379                                 path = wsource.split('.')
380                                 while len(path) > 1:
381                                         scr = screen.getRelatedScreen(path[0])
382                                         if scr is None:
383                                                 print wsource
384                                                 print name
385                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
386                                         path = path[1:]
387
388                                 # resolve the source.
389                                 source = scr.get(path[0])
390                                 if isinstance(source, ObsoleteSource):
391                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
392                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
393                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
394                                         if source.description:
395                                                 print source.description
396
397                                         wsource = source.new_source
398                                 else:
399                                         # otherwise, use that source.
400                                         break
401
402                         if source is None:
403                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
404                         
405                         wrender = widget.getAttribute('render')
406                         
407                         if not wrender:
408                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
409                         
410                         for converter in elementsWithTag(widget.childNodes, "convert"):
411                                 ctype = converter.getAttribute('type')
412                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
413                                 parms = mergeText(converter.childNodes).strip()
414                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
415                                 
416                                 c = None
417                                 
418                                 for i in source.downstream_elements:
419                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
420                                                 c = i
421
422                                 if c is None:
423                                         print "allocating new converter!"
424                                         c = converter_class(parms)
425                                         c.connect(source)
426                                 else:
427                                         print "reused converter!"
428         
429                                 source = c
430                         
431                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
432                         
433                         renderer = renderer_class() # instantiate renderer
434                         
435                         renderer.connect(source) # connect to source
436                         attributes = renderer.skinAttributes = [ ]
437                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
438                         
439                         screen.renderer.append(renderer)
440
441         from Components.GUIComponent import GUIComponent
442         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
443         
444         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
445
446         # now walk additional objects
447         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
448                 if widget.tagName == "applet":
449                         codeText = mergeText(widget.childNodes).strip()
450                         type = widget.getAttribute('type')
451
452                         code = compile(codeText, "skin applet", "exec")
453                         
454                         if type == "onLayoutFinish":
455                                 screen.onLayoutFinish.append(code)
456                         else:
457                                 raise SkinError("applet type '%s' unknown!" % type)
458                         
459                         continue
460                 
461                 class additionalWidget:
462                         pass
463                 
464                 w = additionalWidget()
465                 
466                 if widget.tagName == "eLabel":
467                         w.widget = eLabel
468                 elif widget.tagName == "ePixmap":
469                         w.widget = ePixmap
470                 else:
471                         raise SkinError("unsupported stuff : %s" % widget.tagName)
472                 
473                 w.skinAttributes = [ ]
474                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
475                 
476                 # applyAttributes(guiObject, widget, desktop)
477                 # guiObject.thisown = 0
478                 screen.additionalWidgets.append(w)