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