PositionerSetup/plugin.py: fix modulation, fix nim selection list size
[enigma2.git] / skin.py
1 from Tools.Profile import profile
2 profile("LOAD:ElementTree")
3 import xml.etree.cElementTree
4 from os import path
5
6 profile("LOAD:enigma_skin")
7 from enigma import eSize, ePoint, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \
8         addFont, gRGB, eWindowStyleSkinned
9
10 from Components.config import ConfigSubsection, ConfigText, config
11 from Components.Converter.Converter import Converter
12 from Components.Sources.Source import Source, ObsoleteSource
13 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE, SCOPE_FONTS, SCOPE_CURRENT_SKIN, fileExists
14 from Tools.Import import my_import
15 from Tools.LoadPixmap import LoadPixmap
16
17 from Tools.XMLTools import mergeText
18
19 colorNames = dict()
20
21 def dump(x, i=0):
22         print " " * i + str(x)
23         try:
24                 for n in x.childNodes:
25                         dump(n, i + 1)
26         except:
27                 None
28
29 class SkinError(Exception):
30         def __init__(self, message):
31                 self.message = message
32
33         def __str__(self):
34                 return self.message
35
36 dom_skins = [ ]
37
38 def loadSkin(name):
39         # read the skin
40         filename = resolveFilename(SCOPE_SKIN, name)
41         mpath = path.dirname(filename) + "/"
42         dom_skins.append((mpath, xml.etree.cElementTree.parse(filename).getroot()))
43
44 # we do our best to always select the "right" value
45 # skins are loaded in order of priority: skin with
46 # highest priority is loaded last, usually the user-provided
47 # skin.
48
49 # currently, loadSingleSkinData (colors, bordersets etc.)
50 # are applied one-after-each, in order of ascending priority.
51 # the dom_skin will keep all screens in descending priority,
52 # so the first screen found will be used.
53
54 # example: loadSkin("nemesis_greenline/skin.xml")
55 config.skin = ConfigSubsection()
56 config.skin.primary_skin = ConfigText(default = "skin.xml")
57
58 profile("LoadSkin")
59 try:
60         loadSkin(config.skin.primary_skin.value)
61 except (SkinError, IOError, AssertionError), err:
62         print "SKIN ERROR:", err
63         print "defaulting to standard skin..."
64         config.skin.primary_skin.value = 'skin.xml'
65         loadSkin('skin.xml')
66
67 profile("LoadSkinDefault")
68 loadSkin('skin_default.xml')
69 profile("LoadSkinDefaultDone")
70
71 def parsePosition(str, scale):
72         x, y = str.split(',')
73         return ePoint(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
74
75 def parseSize(str, scale):
76         x, y = str.split(',')
77         return eSize(int(x) * scale[0][0] / scale[0][1], int(y) * scale[1][0] / scale[1][1])
78
79 def parseFont(str, scale):
80         name, size = str.split(';')
81         return gFont(name, int(size) * scale[0][0] / scale[0][1])
82
83 def parseColor(str):
84         if str[0] != '#':
85                 try:
86                         return colorNames[str]
87                 except:
88                         raise SkinError("color '%s' must be #aarrggbb or valid named color" % (str))
89         return gRGB(int(str[1:], 0x10))
90
91 def collectAttributes(skinAttributes, node, skin_path_prefix=None, ignore=[]):
92         # walk all attributes
93         for a in node.items():
94                 #print a
95                 attrib = a[0]
96                 value = a[1]
97
98                 if attrib in ["pixmap", "pointer", "seek_pointer", "backgroundPixmap", "selectionPixmap"]:
99                         value = resolveFilename(SCOPE_SKIN_IMAGE, value, path_prefix=skin_path_prefix)
100
101                 if attrib not in ignore:
102                         skinAttributes.append((attrib, value))
103
104 def loadPixmap(path, desktop):
105         cached = False
106         option = path.find("#")
107         if option != -1:
108                 options = path[option+1:].split(',')
109                 path = path[:option]
110                 cached = "cached" in options
111         ptr = LoadPixmap(path, desktop, cached)
112         if ptr is None:
113                 raise SkinError("pixmap file %s not found!" % (path))
114         return ptr
115
116 def applySingleAttribute(guiObject, desktop, attrib, value, scale = ((1,1),(1,1))):
117         # and set attributes
118         try:
119                 if attrib == 'position':
120                         guiObject.move(parsePosition(value, scale))
121                 elif attrib == 'size':
122                         guiObject.resize(parseSize(value, scale))
123                 elif attrib == 'title':
124                         guiObject.setTitle(_(value))
125                 elif attrib == 'text':
126                         guiObject.setText(_(value))
127                 elif attrib == 'font':
128                         guiObject.setFont(parseFont(value, scale))
129                 elif attrib == 'zPosition':
130                         guiObject.setZPosition(int(value))
131                 elif attrib in ["pixmap", "backgroundPixmap", "selectionPixmap"]:
132                         ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
133                         if attrib == "pixmap":
134                                 guiObject.setPixmap(ptr)
135                         elif attrib == "backgroundPixmap":
136                                 guiObject.setBackgroundPicture(ptr)
137                         elif attrib == "selectionPixmap":
138                                 guiObject.setSelectionPicture(ptr)
139                         # guiObject.setPixmapFromFile(value)
140                 elif attrib == "alphatest": # used by ePixmap
141                         guiObject.setAlphatest(
142                                 { "on": 1,
143                                   "off": 0,
144                                   "blend": 2,
145                                 }[value])
146                 elif attrib == "orientation": # used by eSlider
147                         try:
148                                 guiObject.setOrientation(
149                                         { "orVertical": guiObject.orVertical,
150                                                 "orHorizontal": guiObject.orHorizontal
151                                         }[value])
152                         except KeyError:
153                                 print "oprientation must be either orVertical or orHorizontal!"
154                 elif attrib == "valign":
155                         try:
156                                 guiObject.setVAlign(
157                                         { "top": guiObject.alignTop,
158                                                 "center": guiObject.alignCenter,
159                                                 "bottom": guiObject.alignBottom
160                                         }[value])
161                         except KeyError:
162                                 print "valign must be either top, center or bottom!"
163                 elif attrib == "halign":
164                         try:
165                                 guiObject.setHAlign(
166                                         { "left": guiObject.alignLeft,
167                                                 "center": guiObject.alignCenter,
168                                                 "right": guiObject.alignRight,
169                                                 "block": guiObject.alignBlock
170                                         }[value])
171                         except KeyError:
172                                 print "halign must be either left, center, right or block!"
173                 elif attrib == "flags":
174                         flags = value.split(',')
175                         for f in flags:
176                                 try:
177                                         fv = eWindow.__dict__[f]
178                                         guiObject.setFlag(fv)
179                                 except KeyError:
180                                         print "illegal flag %s!" % f
181                 elif attrib == "backgroundColor":
182                         guiObject.setBackgroundColor(parseColor(value))
183                 elif attrib == "backgroundColorSelected":
184                         guiObject.setBackgroundColorSelected(parseColor(value))
185                 elif attrib == "foregroundColor":
186                         guiObject.setForegroundColor(parseColor(value))
187                 elif attrib == "foregroundColorSelected":
188                         guiObject.setForegroundColorSelected(parseColor(value))
189                 elif attrib == "shadowColor":
190                         guiObject.setShadowColor(parseColor(value))
191                 elif attrib == "selectionDisabled":
192                         guiObject.setSelectionEnable(0)
193                 elif attrib == "transparent":
194                         guiObject.setTransparent(int(value))
195                 elif attrib == "borderColor":
196                         guiObject.setBorderColor(parseColor(value))
197                 elif attrib == "borderWidth":
198                         guiObject.setBorderWidth(int(value))
199                 elif attrib == "scrollbarMode":
200                         guiObject.setScrollbarMode(
201                                 { "showOnDemand": guiObject.showOnDemand,
202                                         "showAlways": guiObject.showAlways,
203                                         "showNever": guiObject.showNever
204                                 }[value])
205                 elif attrib == "enableWrapAround":
206                         guiObject.setWrapAround(True)
207                 elif attrib == "pointer" or attrib == "seek_pointer":
208                         (name, pos) = value.split(':')
209                         pos = parsePosition(pos, scale)
210                         ptr = loadPixmap(name, desktop)
211                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
212                 elif attrib == 'shadowOffset':
213                         guiObject.setShadowOffset(parsePosition(value, scale))
214                 elif attrib == 'noWrap':
215                         guiObject.setNoWrap(1)
216                 else:
217                         raise SkinError("unsupported attribute " + attrib + "=" + value)
218         except int:
219 # AttributeError:
220                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
221
222 def applyAllAttributes(guiObject, desktop, attributes, scale):
223         for (attrib, value) in attributes:
224                 applySingleAttribute(guiObject, desktop, attrib, value, scale)
225
226 def loadSingleSkinData(desktop, skin, path_prefix):
227         """loads skin data like colors, windowstyle etc."""
228         assert skin.tag == "skin", "root element in skin must be 'skin'!"
229
230         #print "***SKIN: ", path_prefix
231
232         for c in skin.findall("output"):
233                 id = c.attrib.get('id')
234                 if id:
235                         id = int(id)
236                 else:
237                         id = 0
238                 if id == 0: # framebuffer
239                         for res in c.findall("resolution"):
240                                 get_attr = res.attrib.get
241                                 xres = get_attr("xres")
242                                 if xres:
243                                         xres = int(xres)
244                                 else:
245                                         xres = 720
246                                 yres = get_attr("yres")
247                                 if yres:
248                                         yres = int(yres)
249                                 else:
250                                         yres = 576
251                                 bpp = get_attr("bpp")
252                                 if bpp:
253                                         bpp = int(bpp)
254                                 else:
255                                         bpp = 32
256                                 #print "Resolution:", xres,yres,bpp
257                                 from enigma import gFBDC
258                                 gFBDC.getInstance().setResolution(xres, yres)
259                                 desktop.resize(eSize(xres, yres))
260                                 if bpp != 32:
261                                         # load palette (not yet implemented)
262                                         pass
263
264         for c in skin.findall("colors"):
265                 for color in c.findall("color"):
266                         get_attr = color.attrib.get
267                         name = get_attr("name")
268                         color = get_attr("value")
269                         if name and color:
270                                 colorNames[name] = parseColor(color)
271                                 #print "Color:", name, color
272                         else:
273                                 raise ("need color and name, got %s %s" % (name, color))
274
275         for c in skin.findall("fonts"):
276                 for font in c.findall("font"):
277                         get_attr = font.attrib.get
278                         filename = get_attr("filename", "<NONAME>")
279                         name = get_attr("name", "Regular")
280                         scale = get_attr("scale")
281                         if scale:
282                                 scale = int(scale)
283                         else:
284                                 scale = 100
285                         is_replacement = get_attr("replacement") and True or False
286                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
287                         if not fileExists(resolved_font): #when font is not available look at current skin path
288                                 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
289                                 if fileExists(skin_path):
290                                         resolved_font = skin_path
291                         addFont(resolved_font, name, scale, is_replacement)
292                         #print "Font: ", resolved_font, name, scale, is_replacement
293
294         for windowstyle in skin.findall("windowstyle"):
295                 style = eWindowStyleSkinned()
296                 id = windowstyle.attrib.get("id")
297                 if id:
298                         id = int(id)
299                 else:
300                         id = 0
301                 #print "windowstyle:", id
302
303                 # defaults
304                 font = gFont("Regular", 20)
305                 offset = eSize(20, 5)
306
307                 for title in windowstyle.findall("title"):
308                         get_attr = title.attrib.get
309                         offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
310                         font = parseFont(get_attr("font"), ((1,1),(1,1)))
311
312                 style.setTitleFont(font);
313                 style.setTitleOffset(offset)
314                 #print "  ", font, offset
315
316                 for borderset in windowstyle.findall("borderset"):
317                         bsName = str(borderset.attrib.get("name"))
318                         for pixmap in borderset.findall("pixmap"):
319                                 get_attr = pixmap.attrib.get
320                                 bpName = get_attr("pos")
321                                 filename = get_attr("filename")
322                                 if filename and bpName:
323                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
324                                         style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
325                                 #print "  borderset:", bpName, filename
326
327                 for color in windowstyle.findall("color"):
328                         get_attr = color.attrib.get
329                         type = get_attr("name")
330                         color = parseColor(get_attr("color"))
331                         try:
332                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
333                         except:
334                                 raise ("Unknown color %s" % (type))
335                                 #pass
336
337                         #print "  color:", type, color
338
339                 x = eWindowStyleManager.getInstance()
340                 x.setStyle(id, style)
341
342 def loadSkinData(desktop):
343         skins = dom_skins[:]
344         skins.reverse()
345         for (path, dom_skin) in skins:
346                 loadSingleSkinData(desktop, dom_skin, path)
347
348 def lookupScreen(name):
349         for (path, skin) in dom_skins:
350                 # first, find the corresponding screen element
351                 for x in skin.findall("screen"):
352                         if x.attrib.get('name', '') == name:
353                                 return x, path
354         return None, None
355
356 class additionalWidget:
357         pass
358
359 def readSkin(screen, skin, names, desktop):
360         if not isinstance(names, list):
361                 names = [names]
362
363         name = "<embedded-in-'%s'>" % screen.__class__.__name__
364
365         # try all skins, first existing one have priority
366         for n in names:
367                 myscreen, path = lookupScreen(n)
368                 if myscreen is not None:
369                         # use this name for debug output
370                         name = n
371                         break
372
373         # otherwise try embedded skin
374         if myscreen is None:
375                 myscreen = getattr(screen, "parsedSkin", None)
376
377         # try uncompiled embedded skin
378         if myscreen is None and getattr(screen, "skin", None):
379                 print "Looking for embedded skin"
380                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(screen.skin)
381
382         #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
383         if myscreen is None:
384                 print "No skin to read..."
385                 emptySkin = "<screen></screen>"
386                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
387
388         screen.skinAttributes = [ ]
389
390         skin_path_prefix = getattr(screen, "skin_path", path)
391
392         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
393
394         screen.additionalWidgets = [ ]
395         screen.renderer = [ ]
396
397         visited_components = set()
398
399         # now walk all widgets
400         for widget in myscreen.findall("widget"):
401                 get_attr = widget.attrib.get
402                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
403                 # widgets (source->renderer).
404
405                 wname = get_attr('name')
406                 wsource = get_attr('source')
407
408                 if wname is None and wsource is None:
409                         print "widget has no name and no source!"
410                         continue
411
412                 if wname:
413                         #print "Widget name=", wname
414                         visited_components.add(wname)
415
416                         # get corresponding 'gui' object
417                         try:
418                                 attributes = screen[wname].skinAttributes = [ ]
419                         except:
420                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
421                                 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
422
423 #                       assert screen[wname] is not Source
424
425                         # and collect attributes for this
426                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
427                 elif wsource:
428                         # get corresponding source
429                         #print "Widget source=", wsource
430
431                         while True: # until we found a non-obsolete source
432
433                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
434                                 # for example to reference a parent, global or session-global screen.
435                                 scr = screen
436
437                                 # resolve all path components
438                                 path = wsource.split('.')
439                                 while len(path) > 1:
440                                         scr = screen.getRelatedScreen(path[0])
441                                         if scr is None:
442                                                 #print wsource
443                                                 #print name
444                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
445                                         path = path[1:]
446
447                                 # resolve the source.
448                                 source = scr.get(path[0])
449                                 if isinstance(source, ObsoleteSource):
450                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
451                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
452                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
453                                         if source.description:
454                                                 print source.description
455
456                                         wsource = source.new_source
457                                 else:
458                                         # otherwise, use that source.
459                                         break
460
461                         if source is None:
462                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
463
464                         wrender = get_attr('render')
465
466                         if not wrender:
467                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
468
469                         for converter in widget.findall("convert"):
470                                 ctype = converter.get('type')
471                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
472                                 #print "Converter:", ctype
473                                 #parms = mergeText(converter.childNodes).strip()
474                                 try:
475                                         parms = converter.text.strip()
476                                 except:
477                                         parms = ""
478                                 #print "Params:", ctype
479                                 converter_class = my_import('.'.join(["Components", "Converter", ctype])).__dict__.get(ctype)
480
481                                 c = None
482
483                                 for i in source.downstream_elements:
484                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
485                                                 c = i
486
487                                 if c is None:
488                                         print "allocating new converter!"
489                                         c = converter_class(parms)
490                                         c.connect(source)
491                                 else:
492                                         print "reused converter!"
493
494                                 source = c
495
496                         renderer_class = my_import('.'.join(["Components", "Renderer", wrender])).__dict__.get(wrender)
497
498                         renderer = renderer_class() # instantiate renderer
499
500                         renderer.connect(source) # connect to source
501                         attributes = renderer.skinAttributes = [ ]
502                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
503
504                         screen.renderer.append(renderer)
505
506         from Components.GUIComponent import GUIComponent
507         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
508         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
509
510         # now walk additional objects
511         for widget in myscreen.getchildren():
512                 w_tag = widget.tag
513
514                 if w_tag == "widget":
515                         continue
516
517                 if w_tag == "applet":
518                         try:
519                                 codeText = widget.text.strip()
520                         except:
521                                 codeText = ""
522
523                         #print "Found code:"
524                         #print codeText
525                         type = widget.attrib.get('type')
526
527                         code = compile(codeText, "skin applet", "exec")
528
529                         if type == "onLayoutFinish":
530                                 screen.onLayoutFinish.append(code)
531                                 #print "onLayoutFinish = ", codeText
532                         else:
533                                 raise SkinError("applet type '%s' unknown!" % type)
534                                 #print "applet type '%s' unknown!" % type
535
536                         continue
537
538                 w = additionalWidget()
539
540                 if w_tag == "eLabel":
541                         w.widget = eLabel
542                 elif w_tag == "ePixmap":
543                         w.widget = ePixmap
544                 else:
545                         raise SkinError("unsupported stuff : %s" % w_tag)
546                         #print "unsupported stuff : %s" % widget.tag
547
548                 w.skinAttributes = [ ]
549                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
550
551                 # applyAttributes(guiObject, widget, desktop)
552                 # guiObject.thisown = 0
553                 screen.additionalWidgets.append(w)