[ScanSetup] Fix error on complete scan with T2 tuners.
[vuplus_dvbapp] / 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 == 'animationPaused':
144                         pass
145                 elif attrib == 'animationMode':
146                         guiObject.setAnimationMode(
147                                 { "disable": 0x00,
148                                         "off": 0x00,
149                                         "offshow": 0x10,
150                                         "offhide": 0x01,
151                                         "onshow": 0x01,
152                                         "onhide": 0x10,
153                                 }[value])
154                 elif attrib == 'title':
155                         guiObject.setTitle(_(value))
156                 elif attrib == 'text':
157                         guiObject.setText(_(value))
158                 elif attrib == 'font':
159                         guiObject.setFont(parseFont(value, scale))
160                 elif attrib == 'zPosition':
161                         guiObject.setZPosition(int(value))
162                 elif attrib == 'itemHeight':
163                         guiObject.setItemHeight(int(value))
164                 elif attrib in ("pixmap", "backgroundPixmap", "selectionPixmap"):
165                         ptr = loadPixmap(value, desktop) # this should already have been filename-resolved.
166                         if attrib == "pixmap":
167                                 guiObject.setPixmap(ptr)
168                         elif attrib == "backgroundPixmap":
169                                 guiObject.setBackgroundPicture(ptr)
170                         elif attrib == "selectionPixmap":
171                                 guiObject.setSelectionPicture(ptr)
172                         # guiObject.setPixmapFromFile(value)
173                 elif attrib == "alphatest": # used by ePixmap
174                         guiObject.setAlphatest(
175                                 { "on": 1,
176                                   "off": 0,
177                                   "blend": 2,
178                                 }[value])
179                 elif attrib == "scale":
180                         guiObject.setScale(1)
181                 elif attrib == "orientation": # used by eSlider
182                         try:
183                                 guiObject.setOrientation(*
184                                         { "orVertical": (guiObject.orVertical, False),
185                                                 "orTopToBottom": (guiObject.orVertical, False),
186                                                 "orBottomToTop": (guiObject.orVertical, True),
187                                                 "orHorizontal": (guiObject.orHorizontal, False),
188                                                 "orLeftToRight": (guiObject.orHorizontal, False),
189                                                 "orRightToLeft": (guiObject.orHorizontal, True),
190                                         }[value])
191                         except KeyError:
192                                 print "oprientation must be either orVertical or orHorizontal!"
193                 elif attrib == "valign":
194                         try:
195                                 guiObject.setVAlign(
196                                         { "top": guiObject.alignTop,
197                                                 "center": guiObject.alignCenter,
198                                                 "bottom": guiObject.alignBottom
199                                         }[value])
200                         except KeyError:
201                                 print "valign must be either top, center or bottom!"
202                 elif attrib == "halign":
203                         try:
204                                 guiObject.setHAlign(
205                                         { "left": guiObject.alignLeft,
206                                                 "center": guiObject.alignCenter,
207                                                 "right": guiObject.alignRight,
208                                                 "block": guiObject.alignBlock
209                                         }[value])
210                         except KeyError:
211                                 print "halign must be either left, center, right or block!"
212                 elif attrib == "flags":
213                         flags = value.split(',')
214                         for f in flags:
215                                 try:
216                                         fv = eWindow.__dict__[f]
217                                         guiObject.setFlag(fv)
218                                 except KeyError:
219                                         print "illegal flag %s!" % f
220                 elif attrib == "backgroundColor":
221                         guiObject.setBackgroundColor(parseColor(value))
222                 elif attrib == "backgroundColorSelected":
223                         guiObject.setBackgroundColorSelected(parseColor(value))
224                 elif attrib == "foregroundColor":
225                         guiObject.setForegroundColor(parseColor(value))
226                 elif attrib == "foregroundColorSelected":
227                         guiObject.setForegroundColorSelected(parseColor(value))
228                 elif attrib == "shadowColor":
229                         guiObject.setShadowColor(parseColor(value))
230                 elif attrib == "selectionDisabled":
231                         guiObject.setSelectionEnable(0)
232                 elif attrib == "transparent":
233                         guiObject.setTransparent(int(value))
234                 elif attrib == "borderColor":
235                         guiObject.setBorderColor(parseColor(value))
236                 elif attrib == "borderWidth":
237                         guiObject.setBorderWidth(int(value))
238                 elif attrib == "scrollbarMode":
239                         guiObject.setScrollbarMode(
240                                 { "showOnDemand": guiObject.showOnDemand,
241                                         "showAlways": guiObject.showAlways,
242                                         "showNever": guiObject.showNever
243                                 }[value])
244                 elif attrib == "enableWrapAround":
245                         guiObject.setWrapAround(True)
246                 elif attrib == "pointer" or attrib == "seek_pointer":
247                         (name, pos) = value.split(':')
248                         pos = parsePosition(pos, scale)
249                         ptr = loadPixmap(name, desktop)
250                         guiObject.setPointer({"pointer": 0, "seek_pointer": 1}[attrib], ptr, pos)
251                 elif attrib == 'shadowOffset':
252                         guiObject.setShadowOffset(parsePosition(value, scale))
253                 elif attrib == 'noWrap':
254                         guiObject.setNoWrap(1)
255                 elif attrib == 'id':
256                         pass
257                 else:
258                         raise SkinError("unsupported attribute " + attrib + "=" + value)
259         except int:
260 # AttributeError:
261                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
262
263 def applyAllAttributes(guiObject, desktop, attributes, scale):
264         for (attrib, value) in attributes:
265                 applySingleAttribute(guiObject, desktop, attrib, value, scale)
266
267 def loadSingleSkinData(desktop, skin, path_prefix):
268         """loads skin data like colors, windowstyle etc."""
269         assert skin.tag == "skin", "root element in skin must be 'skin'!"
270
271         #print "***SKIN: ", path_prefix
272
273         for c in skin.findall("output"):
274                 id = c.attrib.get('id')
275                 if id:
276                         id = int(id)
277                 else:
278                         id = 0
279                 if id == 0: # framebuffer
280                         for res in c.findall("resolution"):
281                                 get_attr = res.attrib.get
282                                 xres = get_attr("xres")
283                                 if xres:
284                                         xres = int(xres)
285                                 else:
286                                         xres = 720
287                                 yres = get_attr("yres")
288                                 if yres:
289                                         yres = int(yres)
290                                 else:
291                                         yres = 576
292                                 bpp = get_attr("bpp")
293                                 if bpp:
294                                         bpp = int(bpp)
295                                 else:
296                                         bpp = 32
297                                 #print "Resolution:", xres,yres,bpp
298                                 from enigma import gMainDC
299                                 gMainDC.getInstance().setResolution(xres, yres)
300                                 desktop.resize(eSize(xres, yres))
301                                 if bpp != 32:
302                                         # load palette (not yet implemented)
303                                         pass
304
305         for c in skin.findall("colors"):
306                 for color in c.findall("color"):
307                         get_attr = color.attrib.get
308                         name = get_attr("name")
309                         color = get_attr("value")
310                         if name and color:
311                                 colorNames[name] = parseColor(color)
312                                 #print "Color:", name, color
313                         else:
314                                 raise SkinError("need color and name, got %s %s" % (name, color))
315
316         for c in skin.findall("fonts"):
317                 for font in c.findall("font"):
318                         get_attr = font.attrib.get
319                         filename = get_attr("filename", "<NONAME>")
320                         name = get_attr("name", "Regular")
321                         scale = get_attr("scale")
322                         if scale:
323                                 scale = int(scale)
324                         else:
325                                 scale = 100
326                         is_replacement = get_attr("replacement") and True or False
327                         resolved_font = resolveFilename(SCOPE_FONTS, filename, path_prefix=path_prefix)
328                         if not fileExists(resolved_font): #when font is not available look at current skin path
329                                 skin_path = resolveFilename(SCOPE_CURRENT_SKIN, filename)
330                                 if fileExists(skin_path):
331                                         resolved_font = skin_path
332                         addFont(resolved_font, name, scale, is_replacement)
333                         #print "Font: ", resolved_font, name, scale, is_replacement
334
335         for c in skin.findall("subtitles"):
336                 from enigma import eWidget, eSubtitleWidget
337                 scale = ((1,1),(1,1))
338                 for substyle in c.findall("sub"):
339                         get_attr = substyle.attrib.get
340                         font = parseFont(get_attr("font"), scale)
341                         col = get_attr("foregroundColor")
342                         if col:
343                                 foregroundColor = parseColor(col)
344                                 haveColor = 1
345                         else:
346                                 foregroundColor = gRGB(0xFFFFFF)
347                                 haveColor = 0
348                         col = get_attr("shadowColor")
349                         if col:
350                                 shadowColor = parseColor(col)
351                         else:
352                                 shadowColor = gRGB(0)
353                         shadowOffset = parsePosition(get_attr("shadowOffset"), scale)
354                         face = eSubtitleWidget.__dict__[get_attr("name")]
355                         eSubtitleWidget.setFontStyle(face, font, haveColor, foregroundColor, shadowColor, shadowOffset)
356
357         for windowstyle in skin.findall("windowstyle"):
358                 style = eWindowStyleSkinned()
359                 id = windowstyle.attrib.get("id")
360                 if id:
361                         id = int(id)
362                 else:
363                         id = 0
364                 #print "windowstyle:", id
365
366                 # defaults
367                 font = gFont("Regular", 20)
368                 offset = eSize(20, 5)
369
370                 for title in windowstyle.findall("title"):
371                         get_attr = title.attrib.get
372                         offset = parseSize(get_attr("offset"), ((1,1),(1,1)))
373                         font = parseFont(get_attr("font"), ((1,1),(1,1)))
374
375                 style.setTitleFont(font);
376                 style.setTitleOffset(offset)
377                 #print "  ", font, offset
378
379                 for borderset in windowstyle.findall("borderset"):
380                         bsName = str(borderset.attrib.get("name"))
381                         for pixmap in borderset.findall("pixmap"):
382                                 get_attr = pixmap.attrib.get
383                                 bpName = get_attr("pos")
384                                 filename = get_attr("filename")
385                                 if filename and bpName:
386                                         png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename, path_prefix=path_prefix), desktop)
387                                         style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png)
388                                 #print "  borderset:", bpName, filename
389
390                 for color in windowstyle.findall("color"):
391                         get_attr = color.attrib.get
392                         colorType = get_attr("name")
393                         color = parseColor(get_attr("color"))
394                         try:
395                                 style.setColor(eWindowStyleSkinned.__dict__["col" + colorType], color)
396                         except:
397                                 raise SkinError("Unknown color %s" % (colorType))
398                                 #pass
399
400                         #print "  color:", type, color
401
402                 x = eWindowStyleManager.getInstance()
403                 x.setStyle(id, style)
404
405 def loadSkinData(desktop):
406         skins = dom_skins[:]
407         skins.reverse()
408         for (path, dom_skin) in skins:
409                 loadSingleSkinData(desktop, dom_skin, path)
410
411 def lookupScreen(name, style_id):
412         for (path, skin) in dom_skins:
413                 # first, find the corresponding screen element
414                 for x in skin.findall("screen"):
415                         if x.attrib.get('name', '') == name:
416                                 screen_style_id = x.attrib.get('id', '-1')
417                                 if screen_style_id == '-1' and name.find('ummary') > 0:
418                                         screen_style_id = '1'
419                                 if (style_id != 2 and int(screen_style_id) == -1) or int(screen_style_id) == style_id:
420                                         return x, path
421         return None, None
422
423 class additionalWidget:
424         pass
425
426 def readSkin(screen, skin, names, desktop):
427         if not isinstance(names, list):
428                 names = [names]
429
430         name = "<embedded-in-'%s'>" % screen.__class__.__name__
431
432         style_id = desktop.getStyleID();
433
434         # try all skins, first existing one have priority
435         for n in names:
436                 myscreen, path = lookupScreen(n, style_id)
437                 if myscreen is not None:
438                         # use this name for debug output
439                         name = n
440                         break
441
442         # otherwise try embedded skin
443         if myscreen is None:
444                 myscreen = getattr(screen, "parsedSkin", None)
445
446         # try uncompiled embedded skin
447         if myscreen is None and getattr(screen, "skin", None):
448                 print "Looking for embedded skin"
449                 skin_tuple = screen.skin
450                 if not isinstance(skin_tuple, tuple):
451                         skin_tuple = (skin_tuple,)
452                 for sskin in skin_tuple:
453                         parsedSkin = xml.etree.cElementTree.fromstring(sskin)
454                         screen_style_id = parsedSkin.attrib.get('id', '-1')
455                         if (style_id != 2 and int(screen_style_id) == -1) or int(screen_style_id) == style_id:
456                                 myscreen = screen.parsedSkin = parsedSkin
457                                 break
458
459         #assert myscreen is not None, "no skin for screen '" + repr(names) + "' found!"
460         if myscreen is None:
461                 print "No skin to read..."
462                 emptySkin = "<screen></screen>"
463                 myscreen = screen.parsedSkin = xml.etree.cElementTree.fromstring(emptySkin)
464
465         screen.skinAttributes = [ ]
466
467         skin_path_prefix = getattr(screen, "skin_path", path)
468
469         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix, ignore=["name"])
470
471         screen.additionalWidgets = [ ]
472         screen.renderer = [ ]
473
474         visited_components = set()
475
476         # now walk all widgets
477         for widget in myscreen.findall("widget"):
478                 get_attr = widget.attrib.get
479                 # ok, we either have 1:1-mapped widgets ('old style'), or 1:n-mapped
480                 # widgets (source->renderer).
481
482                 wname = get_attr('name')
483                 wsource = get_attr('source')
484
485                 if wname is None and wsource is None:
486                         print "widget has no name and no source!"
487                         continue
488
489                 if wname:
490                         #print "Widget name=", wname
491                         visited_components.add(wname)
492
493                         # get corresponding 'gui' object
494                         try:
495                                 attributes = screen[wname].skinAttributes = [ ]
496                         except:
497                                 raise SkinError("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
498                                 #print "WARNING: component with name '" + wname + "' was not found in skin of screen '" + name + "'!"
499
500 #                       assert screen[wname] is not Source
501
502                         # and collect attributes for this
503                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['name'])
504                 elif wsource:
505                         # get corresponding source
506                         #print "Widget source=", wsource
507
508                         while True: # until we found a non-obsolete source
509
510                                 # parse our current "wsource", which might specifiy a "related screen" before the dot,
511                                 # for example to reference a parent, global or session-global screen.
512                                 scr = screen
513
514                                 # resolve all path components
515                                 path = wsource.split('.')
516                                 while len(path) > 1:
517                                         scr = screen.getRelatedScreen(path[0])
518                                         if scr is None:
519                                                 #print wsource
520                                                 #print name
521                                                 raise SkinError("specified related screen '" + wsource + "' was not found in screen '" + name + "'!")
522                                         path = path[1:]
523
524                                 # resolve the source.
525                                 source = scr.get(path[0])
526                                 if isinstance(source, ObsoleteSource):
527                                         # however, if we found an "obsolete source", issue warning, and resolve the real source.
528                                         print "WARNING: SKIN '%s' USES OBSOLETE SOURCE '%s', USE '%s' INSTEAD!" % (name, wsource, source.new_source)
529                                         print "OBSOLETE SOURCE WILL BE REMOVED %s, PLEASE UPDATE!" % (source.removal_date)
530                                         if source.description:
531                                                 print source.description
532
533                                         wsource = source.new_source
534                                 else:
535                                         # otherwise, use that source.
536                                         break
537
538                         if source is None:
539                                 raise SkinError("source '" + wsource + "' was not found in screen '" + name + "'!")
540
541                         wrender = get_attr('render')
542
543                         if not wrender:
544                                 raise SkinError("you must define a renderer with render= for source '%s'" % (wsource))
545
546                         for converter in widget.findall("convert"):
547                                 ctype = converter.get('type')
548                                 assert ctype, "'convert'-tag needs a 'type'-attribute"
549                                 #print "Converter:", ctype
550                                 try:
551                                         parms = converter.text.strip()
552                                 except:
553                                         parms = ""
554                                 #print "Params:", parms
555                                 converter_class = my_import('.'.join(("Components", "Converter", ctype))).__dict__.get(ctype)
556
557                                 c = None
558
559                                 for i in source.downstream_elements:
560                                         if isinstance(i, converter_class) and i.converter_arguments == parms:
561                                                 c = i
562
563                                 if c is None:
564                                         print "allocating new converter!"
565                                         c = converter_class(parms)
566                                         c.connect(source)
567                                 else:
568                                         print "reused converter!"
569
570                                 source = c
571
572                         renderer_class = my_import('.'.join(("Components", "Renderer", wrender))).__dict__.get(wrender)
573
574                         renderer = renderer_class() # instantiate renderer
575
576                         renderer.connect(source) # connect to source
577                         attributes = renderer.skinAttributes = [ ]
578                         collectAttributes(attributes, widget, skin_path_prefix, ignore=['render', 'source'])
579
580                         screen.renderer.append(renderer)
581
582         from Components.GUIComponent import GUIComponent
583         nonvisited_components = [x for x in set(screen.keys()) - visited_components if isinstance(x, GUIComponent)]
584         assert not nonvisited_components, "the following components in %s don't have a skin entry: %s" % (name, ', '.join(nonvisited_components))
585
586         # now walk additional objects
587         for widget in myscreen.getchildren():
588                 w_tag = widget.tag
589
590                 if w_tag == "widget":
591                         continue
592
593                 if w_tag == "applet":
594                         try:
595                                 codeText = widget.text.strip()
596                         except:
597                                 codeText = ""
598
599                         #print "Found code:"
600                         #print codeText
601                         widgetType = widget.attrib.get('type')
602
603                         code = compile(codeText, "skin applet", "exec")
604
605                         if widgetType == "onLayoutFinish":
606                                 screen.onLayoutFinish.append(code)
607                                 #print "onLayoutFinish = ", codeText
608                         else:
609                                 raise SkinError("applet type '%s' unknown!" % widgetType)
610                                 #print "applet type '%s' unknown!" % type
611
612                         continue
613
614                 w = additionalWidget()
615
616                 if w_tag == "eLabel":
617                         w.widget = eLabel
618                 elif w_tag == "ePixmap":
619                         w.widget = ePixmap
620                 else:
621                         raise SkinError("unsupported stuff : %s" % w_tag)
622                         #print "unsupported stuff : %s" % widget.tag
623
624                 w.skinAttributes = [ ]
625                 collectAttributes(w.skinAttributes, widget, skin_path_prefix, ignore=['name'])
626
627                 # applyAttributes(guiObject, widget, desktop)
628                 # guiObject.thisown = 0
629                 screen.additionalWidgets.append(w)