allow changing titlebar offset / font by skin
[openblackhole/openblackhole-enigma2.git] / skin.py
1 from enigma import *
2 import xml.dom.minidom
3 from xml.dom import EMPTY_NAMESPACE
4
5 from Tools.XMLTools import elementsWithTag, mergeText
6
7 colorNames = dict()
8
9 def dump(x, i=0):
10         print " " * i + str(x)
11         try:
12                 for n in x.childNodes:
13                         dump(n, i + 1)
14         except:
15                 None
16
17 from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_SKIN_IMAGE
18
19 dom_skins = [ ]
20
21 def loadSkin(name):
22         # read the skin
23         dom_skins.append(xml.dom.minidom.parse(resolveFilename(SCOPE_SKIN, name)))
24
25 loadSkin('skin.xml')
26 loadSkin('skin_default.xml')
27
28 def parsePosition(str):
29         x, y = str.split(',')
30         return ePoint(int(x), int(y))
31
32 def parseSize(str):
33         x, y = str.split(',')
34         return eSize(int(x), int(y))
35
36 def parseFont(str):
37         name, size = str.split(';')
38         return gFont(name, int(size))
39
40 def parseColor(str):
41         if str[0] != '#':
42                 try:
43                         return colorNames[str]
44                 except:
45                         raise ("color '%s' must be #aarrggbb or valid named color" % (str))
46         return gRGB(int(str[1:], 0x10))
47
48 def collectAttributes(skinAttributes, node, skin_path_prefix=None):
49         # walk all attributes
50         for p in range(node.attributes.length):
51                 a = node.attributes.item(p)
52                 
53                 # convert to string (was: unicode)
54                 attrib = str(a.name)
55                 # TODO: localization? as in e1?
56                 value = a.value.encode("utf-8")
57                 
58                 if skin_path_prefix and attrib in ["pixmap", "pointer"] and len(value) and value[0:2] == "~/":
59                         value = skin_path_prefix + value[1:]
60                 
61                 skinAttributes.append((attrib, value))
62
63 def loadPixmap(path):
64         ptr = loadPNG(path)
65         if ptr is None:
66                 raise "pixmap file %s not found!" % (path)
67         return ptr
68
69 def applySingleAttribute(guiObject, desktop, attrib, value):
70         # and set attributes
71         try:
72                 if attrib == 'position':
73                         guiObject.move(parsePosition(value))
74                 elif attrib == 'size':
75                         guiObject.resize(parseSize(value))
76                 elif attrib == 'title':
77                         guiObject.setTitle(_(value))
78                 elif attrib == 'text':
79                         guiObject.setText(value)
80                 elif attrib == 'font':
81                         guiObject.setFont(parseFont(value))
82                 elif attrib == 'zPosition':
83                         guiObject.setZPosition(int(value))
84                 elif attrib == "pixmap":
85                         ptr = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, value))
86                         # that __deref__ still scares me!
87 #                       desktop.makeCompatiblePixmap(ptr.__deref__())
88                         guiObject.setPixmap(ptr.__deref__())
89                         # guiObject.setPixmapFromFile(value)
90                 elif attrib == "alphatest": # used by ePixmap
91                         guiObject.setAlphatest(
92                                 { "on": True,
93                                   "off": False
94                                 }[value])
95                 elif attrib == "orientation": # used by eSlider
96                         try:
97                                 guiObject.setOrientation(
98                                         { "orVertical": guiObject.orVertical,
99                                                 "orHorizontal": guiObject.orHorizontal
100                                         }[value])
101                         except KeyError:
102                                 print "oprientation must be either orVertical or orHorizontal!"
103                 elif attrib == "valign":
104                         try:
105                                 guiObject.setVAlign(
106                                         { "top": guiObject.alignTop,
107                                                 "center": guiObject.alignCenter,
108                                                 "bottom": guiObject.alignBottom
109                                         }[value])
110                         except KeyError:
111                                 print "valign must be either top, center or bottom!"
112                 elif attrib == "halign":
113                         try:
114                                 guiObject.setHAlign(
115                                         { "left": guiObject.alignLeft,
116                                                 "center": guiObject.alignCenter,
117                                                 "right": guiObject.alignRight,
118                                                 "block": guiObject.alignBlock
119                                         }[value])
120                         except KeyError:
121                                 print "halign must be either left, center, right or block!"
122                 elif attrib == "flags":
123                         flags = value.split(',')
124                         for f in flags:
125                                 try:
126                                         fv = eWindow.__dict__[f]
127                                         guiObject.setFlag(fv)
128                                 except KeyError:
129                                         print "illegal flag %s!" % f
130                 elif attrib == "backgroundColor":
131                         guiObject.setBackgroundColor(parseColor(value))
132                 elif attrib == "foregroundColor":
133                         guiObject.setForegroundColor(parseColor(value))
134                 elif attrib == "shadowColor":
135                         guiObject.setShadowColor(parseColor(value))
136                 elif attrib == "selectionDisabled":
137                         guiObject.setSelectionEnable(0)
138                 elif attrib == "transparent":
139                         guiObject.setTransparent(int(value))
140                 elif attrib == "borderColor":
141                         guiObject.setBorderColor(parseColor(value))
142                 elif attrib == "borderWidth":
143                         guiObject.setBorderWidth(int(value))
144                 elif attrib == "scrollbarMode":
145                         guiObject.setScrollbarMode(
146                                 { "showOnDemand": guiObject.showOnDemand,
147                                         "showAlways": guiObject.showAlways,
148                                         "showNever": guiObject.showNever
149                                 }[value])
150                 elif attrib == "enableWrapAround":
151                         guiObject.setWrapAround(True)
152                 elif attrib == "pointer":
153                         (name, pos) = value.split(':')
154                         pos = parsePosition(pos)
155                         ptr = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, name))
156                         desktop.makeCompatiblePixmap(ptr.__deref__())
157                         guiObject.setPointer(ptr.__deref__(), pos)
158                 elif attrib != 'name':
159                         print "unsupported attribute " + attrib + "=" + value
160                 elif attrib == 'shadowOffset':
161                         guiObject.setShadowOffset(parsePosition(value))
162         except int:
163 # AttributeError:
164                 print "widget %s (%s) doesn't support attribute %s!" % ("", guiObject.__class__.__name__, attrib)
165
166 def applyAllAttributes(guiObject, desktop, attributes):
167         for (attrib, value) in attributes:
168                 applySingleAttribute(guiObject, desktop, attrib, value)
169
170 def loadSingleSkinData(desktop, dom_skin):
171         """loads skin data like colors, windowstyle etc."""
172         
173         skin = dom_skin.childNodes[0]
174         assert skin.tagName == "skin", "root element in skin must be 'skin'!"
175         
176         for c in elementsWithTag(skin.childNodes, "colors"):
177                 for color in elementsWithTag(c.childNodes, "color"):
178                         name = str(color.getAttribute("name"))
179                         color = str(color.getAttribute("value"))
180                         
181                         if not len(color):
182                                 raise ("need color and name, got %s %s" % (name, color))
183                                 
184                         colorNames[name] = parseColor(color)
185         
186         for windowstyle in elementsWithTag(skin.childNodes, "windowstyle"):
187                 style = eWindowStyleSkinned()
188                 
189                 # defaults
190                 font = gFont("Regular", 20)
191                 offset = eSize(20, 5)
192                 
193                 for title in elementsWithTag(windowstyle.childNodes, "title"):
194                         offset = parseSize(title.getAttribute("offset"))
195                         font = parseFont(str(title.getAttribute("font")))
196
197                 style.setTitleFont(font);
198                 style.setTitleOffset(offset)
199                 
200                 for borderset in elementsWithTag(windowstyle.childNodes, "borderset"):
201                         bsName = str(borderset.getAttribute("name"))
202                         for pixmap in elementsWithTag(borderset.childNodes, "pixmap"):
203                                 bpName = str(pixmap.getAttribute("pos"))
204                                 filename = str(pixmap.getAttribute("filename"))
205                                 
206                                 png = loadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, filename))
207                                 
208                                 # adapt palette
209                                 desktop.makeCompatiblePixmap(png.__deref__())
210                                 style.setPixmap(eWindowStyleSkinned.__dict__[bsName], eWindowStyleSkinned.__dict__[bpName], png.__deref__())
211
212                 for color in elementsWithTag(windowstyle.childNodes, "color"):
213                         type = str(color.getAttribute("name"))
214                         color = parseColor(color.getAttribute("color"))
215                         
216                         try:
217                                 style.setColor(eWindowStyleSkinned.__dict__["col" + type], color)
218                         except:
219                                 raise ("Unknown color %s" % (type))
220                         
221                 x = eWindowStyleManagerPtr()
222                 eWindowStyleManager.getInstance(x)
223                 x.setStyle(style)
224
225 def loadSkinData(desktop):
226         for dom_skin in dom_skins:
227                 loadSingleSkinData(desktop, dom_skin)
228
229 def lookupScreen(name):
230         for dom_skin in dom_skins:
231                 # first, find the corresponding screen element
232                 skin = dom_skin.childNodes[0] 
233                 for x in elementsWithTag(skin.childNodes, "screen"):
234                         if x.getAttribute('name') == name:
235                                 return x
236         return None
237
238 def readSkin(screen, skin, name, desktop):
239         myscreen = lookupScreen(name)
240         
241         # otherwise try embedded skin
242         myscreen = myscreen or getattr(screen, "parsedSkin", None)
243         
244         # try uncompiled embedded skin
245         if myscreen is None and getattr(screen, "skin", None):
246                 myscreen = screen.parsedSkin = xml.dom.minidom.parseString(screen.skin).childNodes[0]
247         
248         assert myscreen is not None, "no skin for screen '" + name + "' found!"
249
250         screen.skinAttributes = [ ]
251         
252         skin_path_prefix = getattr(screen, "skin_path", None)
253
254         collectAttributes(screen.skinAttributes, myscreen, skin_path_prefix)
255         
256         screen.additionalWidgets = [ ]
257         
258         # now walk all widgets
259         for widget in elementsWithTag(myscreen.childNodes, "widget"):
260                 wname = widget.getAttribute('name')
261                 if wname == None:
262                         print "widget has no name!"
263                         continue
264                 
265                 # get corresponding gui object
266                 try:
267                         attributes = screen[wname].skinAttributes = [ ]
268                 except:
269                         raise str("component with name '" + wname + "' was not found in skin of screen '" + name + "'!")
270                 
271                 collectAttributes(attributes, widget, skin_path_prefix)
272
273         # now walk additional objects
274         for widget in elementsWithTag(myscreen.childNodes, lambda x: x != "widget"):
275                 if widget.tagName == "applet":
276                         codeText = mergeText(widget.childNodes).strip()
277                         type = widget.getAttribute('type')
278
279                         code = compile(codeText, "skin applet", "exec")
280                         
281                         if type == "onLayoutFinish":
282                                 screen.onLayoutFinish.append(code)
283                         else:
284                                 raise str("applet type '%s' unknown!" % type)
285                         
286                         continue
287                 
288                 class additionalWidget:
289                         pass
290                 
291                 w = additionalWidget()
292                 
293                 if widget.tagName == "eLabel":
294                         w.widget = eLabel
295                 elif widget.tagName == "ePixmap":
296                         w.widget = ePixmap
297                 else:
298                         raise str("unsupported stuff : %s" % widget.tagName)
299                 
300                 w.skinAttributes = [ ]
301                 collectAttributes(w.skinAttributes, widget, skin_path_prefix)
302                 
303                 # applyAttributes(guiObject, widget, desktop)
304                 # guiObject.thisown = 0
305                 screen.additionalWidgets.append(w)