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