search font in current skin path when not found in font dir
[vuplus_dvbapp] / skin.py
1 from Tools.Profile import profile, profile_final
2
3 profile("LOAD:minidom")
4 import xml.dom.minidom
5 from os import path
6
7 profile("LOAD:enigma_skin")
8 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
9         addFont, gRGB, eWindowStyleSkinned
10
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, fileExists
15 from Tools.Import import my_import
16 from Tools.LoadPixmap import LoadPixmap
17
18 from Tools.XMLTools import elementsWithTag, mergeText
19
20 colorNames = dict()
21
22 def dump(x, i=0):
23         print " " * i + str(x)
24         try:
25                 for n in x.childNodes:
26                         dump(n, i + 1)
27         except:
28                 None
29
30 class SkinError(Exception):
31         def __init__(self, message):
32                 self.message = message
33
34         def __str__(self):
35                 return self.message
36
37 dom_skins = [ ]
38
39 def loadSkin(name):
40         # read the skin
41         filename = resolveFilename(SCOPE_SKIN, name)
42         mpath = path.dirname(filename) + "/"
43         dom_skins.append((mpath, xml.dom.minidom.parse(filename)))
44
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
48 # skin.
49
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.
54
55 # example: loadSkin("nemesis_greenline/skin.xml")
56 config.skin = ConfigSubsection()
57 config.skin.primary_skin = ConfigText(default = "skin.xml")
58
59 profile("LoadSkin")
60 try:
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'
66         loadSkin('skin.xml')
67
68 profile("LoadSkinDefault")
69 loadSkin('skin_default.xml')
70 profile("LoadSkinDefaultDone")
71
72 def parsePosition(str):
73         x, y = str.split(',')
74         return ePoint(int(x), int(y))
75
76 def parseSize(str):
77         x, y = str.split(',')
78         return eSize(int(x), int(y))
79
80 def parseFont(str):
81         name, size = str.split(';')
82         return gFont(name, int(size))
83
84 def parseColor(str):
85         if str[0] != '#':
86                 try:
87                         return colorNames[str]
88                 except:
89                         raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
90         return gRGB(int(str[1:], 0x10))
91
92 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
93         # walk all attributes
94         for p in range(node.attributes.length):
95                 a = node.attributes.item(p)
96                 
97                 # convert to string (was: unicode)
98                 attrib = str(a.name)
99                 # TODO: localization? as in e1?
100                 value = a.value.encode("utf-8")
101                 
102                 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
103                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
104                 
105                 if attrib not in ignore:
106                         skinAttributes.append((attrib, value))
107
108 def loadPixmap(path, desktop):
109         cached = False
110         option = path.find("#")
111         if option != -1:
112                 options = path[option+1:].split(',')
113                 path = path[:option]
114                 cached = "cached" in options
115         ptr = LoadPixmap(path, desktop, cached)
116         if ptr is None:
117                 raise SkinError("pixmap file %s not found!" % (path))
118         return ptr
119
120 def applySingleAttribute(guiObject, desktop, attrib, value):
121         # and set attributes
122         try:
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(
146                                 { "on": 1,
147                                   "off": 0,
148                                   "blend": 2,
149                                 }[value])
150                 elif attrib == "orientation": # used by eSlider
151                         try:
152                                 guiObject.setOrientation(
153                                         { "orVertical": guiObject.orVertical,
154                                                 "orHorizontal": guiObject.orHorizontal
155                                         }[value])
156                         except KeyError:
157                                 print "oprientation must be either orVertical or orHorizontal!"
158                 elif attrib == "valign":
159                         try:
160                                 guiObject.setVAlign(
161                                         { "top": guiObject.alignTop,
162                                                 "center": guiObject.alignCenter,
163                                                 "bottom": guiObject.alignBottom
164                                         }[value])
165                         except KeyError:
166                                 print "valign must be either top, center or bottom!"
167                 elif attrib == "halign":
168                         try:
169                                 guiObject.setHAlign(
170                                         { "left": guiObject.alignLeft,
171                                                 "center": guiObject.alignCenter,
172                                                 "right": guiObject.alignRight,
173                                                 "block": guiObject.alignBlock
174                                         }[value])
175                         except KeyError:
176                                 print "halign must be either left, center, right or block!"
177                 elif attrib == "flags":
178                         flags = value.split(',')
179                         for f in flags:
180                                 try:
181                                         fv = eWindow.__dict__[f]
182                                         guiObject.setFlag(fv)
183                                 except KeyError:
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
208                                 }[value])
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)
220                 else:
221                         raise SkinError("unsupported attribute " + attrib + "=" + value)
222         except int:
223 # AttributeError:
224                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
225
226 def applyAllAttributes(guiObject, desktop, attributes):
227         for (attrib, value) in attributes:
228                 applySingleAttribute(guiObject, desktop, attrib, value)
229
230 def loadSingleSkinData(desktop, dom_skin, path_prefix):
231         """loads skin data like colors, windowstyle etc."""
232         
233         skin = dom_skin.childNodes[0]
234         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
235
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"))
243
244                                 from enigma import gFBDC
245                                 i = gFBDC.getInstance()
246                                 i.setResolution(xres, yres)
247
248                                 if bpp != 32:
249                                         # load palette (not yet implemented)
250                                         pass
251
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"))
256                         
257                         if not len(color):
258                                 raise ("need color and name, got %s %s" % (name, color))
259                                 
260                         colorNames[name] = parseColor(color)
261         
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                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
269                         if not fileExists(resolved_font): #when font is not available look at current skin path
270                                 pos = config.skin.primary_skin.value.rfind('/')
271                                 if pos != -1:
272                                         skin_path = resolveFilename(SCOPE_SKIN, config.skin.primary_skin.value[:pos+1]+filename, path_prefix=path_prefix)
273                                         if fileExists(skin_path):
274                                                 resolved_font = skin_path
275                         addFont(resolved_font, name, scale, is_replacement)
276         
277         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
278                 style = eWindowStyleSkinned()
279                 id = int(windowstyle.getAttribute("id") or "0")
280                 
281                 # defaults
282                 font = gFont("Regular", 20)
283                 offset = eSize(20, 5)
284                 
285                 for title in elementsWithTag(windowstyle.childNodes, "title"):
286                         offset = parseSize(title.getAttribute("offset"))
287                         font = parseFont(str(title.getAttribute("font")))
288
289                 style.setTitleFont(font);
290                 style.setTitleOffset(offset)
291                 
292                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
293                         bsName = str(borderset.getAttribute("name"))
294                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
295                                 bpName = str(pixmap.getAttribute("pos"))
296                                 filename = str(pixmap.getAttribute("filename"))
297                                 
298                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
299                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
300
301                 for color in elementsWithTag(windowstyle.childNodes, "color"):
302                         type = str(color.getAttribute("name"))
303                         color = parseColor(color.getAttribute("color"))
304                         
305                         try:
306                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
307                         except:
308                                 raise ("Unknown color %s" % (type))
309                         
310                 x = eWindowStyleManager.getInstance()
311                 x.setStyle(id, style)
312
313 def loadSkinData(desktop):
314         skins = dom_skins[:]
315         skins.reverse()
316         for (path, dom_skin) in skins:
317                 loadSingleSkinData(desktop, dom_skin, path)
318
319 def lookupScreen(name):
320         for (path, dom_skin) in dom_skins:
321                 # first, find the corresponding screen element
322                 skin = dom_skin.childNodes[0] 
323                 for x in elementsWithTag(skin.childNodes, "screen"):
324                         if x.getAttribute('name') == name:
325                                 return x, path
326         return None, None
327
328 def readSkin(screen, skin, names, desktop):
329         if not isinstance(names, list):
330                 names = [names]
331
332         name = "<embedded-in-'%s'>" % screen.__class__.__name__
333
334         # try all skins, first existing one have priority
335         for n in names:
336                 myscreen, path = lookupScreen(n)
337                 if myscreen is not None:
338                         # use this name for debug output
339                         name = n
340                         break
341
342         # otherwise try embedded skin
343         myscreen = myscreen or getattr(screen, "parsedSkin", None)
344
345         # try uncompiled embedded skin
346         if myscreen is None and getattr(screen, "skin", None):
347                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
348
349         assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
350
351         screen.skinAttributes = [ ]
352         
353         skin_path_prefix = getattr(screen, "skin_path", path)
354
355         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
356         
357         screen.additionalWidgets = [ ]
358         screen.renderer = [ ]
359         
360         visited_components = set()
361         
362         # now walk all widgets
363         for widget in elementsWithTag(myscreen.childNodes, "widget"):
364                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped 
365                 # widgets (source->renderer).
366
367                 wname = widget.getAttribute('name')
368                 wsource = widget.getAttribute('source')
369                 
370
371                 if wname is None and wsource is None:
372                         print "widget has no name and no source!"
373                         continue
374                 
375                 if wname:
376                         visited_components.add(wname)
377
378                         # get corresponding 'gui' object
379                         try:
380                                 attributes = screen[wname].skinAttributes = [ ]
381                         except:
382                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
383
384 #                       assert screen[wname] is not Source
385
386                         # and collect attributes for this
387                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
388                 elif wsource:
389                         # get corresponding source
390
391                         while True: # until we found a non-obsolete source
392
393                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
394                                 # for example to reference a parent, global or session-global screen.
395                                 scr = screen
396
397                                 # resolve all path components
398                                 path = wsource.split('.')
399                                 while len(path) > 1:
400                                         scr = screen.getRelatedScreen(path[0])
401                                         if scr is None:
402                                                 print wsource
403                                                 print name
404                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
405                                         path = path[1:]
406
407                                 # resolve the source.
408                                 source = scr.get(path[0])
409                                 if isinstance(source, ObsoleteSource):
410                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
411                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
412                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
413                                         if source.description:
414                                                 print source.description
415
416                                         wsource = source.new_source
417                                 else:
418                                         # otherwise, use that source.
419                                         break
420
421                         if source is None:
422                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
423                         
424                         wrender = widget.getAttribute('render')
425                         
426                         if not wrender:
427                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
428                         
429                         for converter in elementsWithTag(widget.childNodes, "convert"):
430                                 ctype = converter.getAttribute('type')
431                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
432                                 parms = mergeText(converter.childNodes).strip()
433                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
434                                 
435                                 c = None
436                                 
437                                 for i in source.downstream_elements:
438                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
439                                                 c = i
440
441                                 if c is None:
442                                         print "allocating new converter!"
443                                         c = converter_class(parms)
444                                         c.connect(source)
445                                 else:
446                                         print "reused converter!"
447         
448                                 source = c
449                         
450                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
451                         
452                         renderer = renderer_class() # instantiate renderer
453                         
454                         renderer.connect(source) # connect to source
455                         attributes = renderer.skinAttributes = [ ]
456                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
457                         
458                         screen.renderer.append(renderer)
459
460         from Components.GUIComponent import GUIComponent
461         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
462         
463         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
464
465         # now walk additional objects
466         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
467                 if widget.tagName == "applet":
468                         codeText = mergeText(widget.childNodes).strip()
469                         type = widget.getAttribute('type')
470
471                         code = compile(codeText, "skin applet", "exec")
472                         
473                         if type == "onLayoutFinish":
474                                 screen.onLayoutFinish.append(code)
475                         else:
476                                 raise SkinError("applet type '%s' unknown!" % type)
477                         
478                         continue
479                 
480                 class additionalWidget:
481                         pass
482                 
483                 w = additionalWidget()
484                 
485                 if widget.tagName == "eLabel":
486                         w.widget = eLabel
487                 elif widget.tagName == "ePixmap":
488                         w.widget = ePixmap
489                 else:
490                         raise SkinError("unsupported stuff : %s" % widget.tagName)
491                 
492                 w.skinAttributes = [ ]
493                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
494                 
495                 # applyAttributes(guiObject, widget, desktop)
496                 # guiObject.thisown = 0
497                 screen.additionalWidgets.append(w)