- work on actions
[enigma2.git] / components.py
1 from enigma import *
2 import time
3 import sys
4
5 # some helper classes first:
6 class HTMLComponent:
7         def produceHTML(self):
8                 return ""
9                 
10 class HTMLSkin:
11         order = ()
12
13         def __init__(self, order):
14                 self.order = order
15
16         def produceHTML(self):
17                 res = "<html>\n"
18                 for name in self.order:
19                         res += self[name].produceHTML()
20                 res += "</html>\n";
21                 return res
22
23 class GUISkin:
24         def __init__(self):
25                 pass
26         
27         def createGUIScreen(self, parent):
28                 for (name, val) in self.items():
29                         if isinstance(val, GUIComponent):
30                                 val.GUIcreate(parent, None)
31         
32         def deleteGUIScreen(self):
33                 for (name, val) in self.items():
34                         if isinstance(val, GUIComponent):
35                                 val.GUIdelete()
36                         try:
37                                 val.fix()
38                         except:
39                                 pass
40                         
41                         # note: you'll probably run into this assert. if this happens, don't panic!
42                         # yes, it's evil. I told you that programming in python is just fun, and 
43                         # suddently, you have to care about things you don't even know.
44                         #
45                         # but calm down, the solution is easy, at least on paper:
46                         #
47                         # Each Component, which is a GUIComponent, owns references to each
48                         # instantiated eWidget (namely in screen.data[name]["instance"], in case
49                         # you care.)
50                         # on deleteGUIscreen, all eWidget *must* (!) be deleted (otherwise,
51                         # well, problems appear. I don't want to go into details too much,
52                         # but this would be a memory leak anyway.)
53                         # The assert beyond checks for that. It asserts that the corresponding
54                         # eWidget is about to be removed (i.e., that the refcount becomes 0 after
55                         # running deleteGUIscreen).
56                         # (You might wonder why the refcount is checked for 2 and not for 1 or 0 -
57                         # one reference is still hold by the local variable 'w', another one is
58                         # hold be the function argument to sys.getrefcount itself. So only if it's
59                         # 2 at this point, the object will be destroyed after leaving deleteGUIscreen.)
60                         #
61                         # Now, how to fix this problem? You're holding a reference somewhere. (References
62                         # can only be hold from Python, as eWidget itself isn't related to the c++
63                         # way of having refcounted objects. So it must be in python.)
64                         #
65                         # It could be possible that you're calling deleteGUIscreen trough a call of
66                         # a PSignal. For example, you could try to call screen.doClose() in response
67                         # to a Button::click. This will fail. (It wouldn't work anyway, as you would
68                         # remove a dialog while running it. It never worked - enigma1 just set a 
69                         # per-mainloop variable on eWidget::close() to leave the exec()...)
70                         # That's why Session supports delayed closes. Just call Session.close() and
71                         # it will work.
72                         #
73                         # Another reason is that you just stored the data["instance"] somewhere. or
74                         # added it into a notifier list and didn't removed it.
75                         #
76                         # If you can't help yourself, just ask me. I'll be glad to help you out.
77                         # Sorry for not keeping this code foolproof. I really wanted to archive
78                         # that, but here I failed miserably. All I could do was to add this assert.
79 #                       assert sys.getrefcount(w) == 2, "too many refs hold to " + str(w)
80         
81         def close(self):
82                 self.deleteGUIScreen()
83
84 class GUIComponent:
85         """ GUI component """
86
87         def __init__(self):
88                 pass
89                 
90         def execBegin(self):
91                 pass
92         
93         def execEnd(self):
94                 pass
95
96 class VariableText:
97         """VariableText can be used for components which have a variable text, based on any widget with setText call"""
98         
99         def __init__(self):
100                 self.message = ""
101                 self.instance = None
102         
103         def setText(self, text):
104                 self.message = text
105                 if self.instance:
106                         self.instance.setText(self.message)
107
108         def getText(self):
109                 return self.message
110         
111         def GUIcreate(self, parent, skindata):
112                 self.instance = self.createWidget(parent, skindata)
113                 self.instance.setText(self.message)
114         
115         def GUIdelete(self):
116                 self.removeWidget(self.instance)
117                 del self.instance
118         
119         def removeWidget(self, instance):
120                 pass
121
122 class VariableValue:
123         """VariableValue can be used for components which have a variable value (like eSlider), based on any widget with setValue call"""
124         
125         def __init__(self):
126                 self.value = 0
127                 self.instance = None
128         
129         def setValue(self, value):
130                 self.value = value
131                 if self.instance:
132                         self.instance.setValue(self.value)
133
134         def getValue(self):
135                 return self.value
136                 
137         def GUIcreate(self, parent, skindata):
138                 self.instance = self.createWidget(parent, skindata)
139                 self.instance.setValue(self.value)
140         
141         def GUIdelete(self):
142                 self.removeWidget(self.instance)
143                 del self.instance
144         
145         def removeWidget(self, instance):
146                 pass
147
148 # now some "real" components:
149
150 class Clock(HTMLComponent, GUIComponent, VariableText):
151         def __init__(self):
152                 VariableText.__init__(self)
153                 GUIComponent.__init__(self)
154                 self.doClock()
155                 
156                 self.clockTimer = eTimer()
157                 self.clockTimer.timeout.get().append(self.doClock)
158                 self.clockTimer.start(1000)
159
160 # "funktionalitaet"     
161         def doClock(self):
162                 self.setText("clock: " + time.asctime())
163
164 # realisierung als GUI
165         def createWidget(self, parent, skindata):
166                 return eLabel(parent)
167
168         def removeWidget(self, w):
169                 del self.clockTimer
170
171 # ...und als HTML:
172         def produceHTML(self):
173                 return self.getText()
174                 
175 class Button(HTMLComponent, GUIComponent, VariableText):
176         def __init__(self, text="", onClick = [ ]):
177                 GUIComponent.__init__(self)
178                 VariableText.__init__(self)
179                 self.setText(text)
180                 self.onClick = onClick
181         
182         def push(self):
183                 for x in self.onClick:
184                         x()
185                 return 0
186         
187         def disable(self):
188 #               self.instance.hide()
189                 pass
190         
191         def enable(self):
192 #               self.instance.show()
193                 pass
194
195 # html:
196         def produceHTML(self):
197                 return "<input type=\"submit\" text=\"" + self.getText() + "\">\n"
198
199 # GUI:
200         def createWidget(self, parent, skindata):
201                 g = eButton(parent)
202                 g.selected.get().append(self.push)
203                 return g
204
205         def removeWidget(self, w):
206                 w.selected.get().remove(self.push)
207
208 class Label(HTMLComponent, GUIComponent, VariableText):
209         def __init__(self, text=""):
210                 GUIComponent.__init__(self)
211                 VariableText.__init__(self)
212                 self.setText(text)
213         
214 # html: 
215         def produceHTML(self):
216                 return self.getText()
217
218 # GUI:
219         def createWidget(self, parent, skindata):
220                 return eLabel(parent)
221         
222 class Header(HTMLComponent, GUIComponent, VariableText):
223
224         def __init__(self, message):
225                 GUIComponent.__init__(self)
226                 VariableText.__init__(self)
227                 self.setText(message)
228         
229         def produceHTML(self):
230                 return "<h2>" + self.getText() + "</h2>\n"
231
232         def createWidget(self, parent, skindata):
233                 g = eLabel(parent)
234                 return g
235
236 class VolumeBar(HTMLComponent, GUIComponent, VariableValue):
237         
238         def __init__(self):
239                 GUIComponent.__init__(self)
240                 VariableValue.__init__(self)
241
242         def createWidget(self, parent, skindata):
243                 g = eSlider(parent)
244                 g.setRange(0, 100)
245                 return g
246                 
247 # a general purpose progress bar
248 class ProgressBar(HTMLComponent, GUIComponent, VariableValue):
249         def __init__(self):
250                 GUIComponent.__init__(self)
251                 VariableValue.__init__(self)
252
253         def createWidget(self, parent, skindata):
254                 g = eSlider(parent)
255                 g.setRange(0, 100)
256                 return g
257         
258 class MenuList(HTMLComponent, GUIComponent):
259         def __init__(self, list):
260                 GUIComponent.__init__(self)
261                 self.l = eListboxPythonStringContent()
262                 self.l.setList(list)
263         
264         def getCurrent(self):
265                 return self.l.getCurrentSelection()
266         
267         def GUIcreate(self, parent, skindata):
268                 self.instance = eListbox(parent)
269                 self.instance.setContent(self.l)
270         
271         def GUIdelete(self):
272                 self.instance.setContent(None)
273
274 class ServiceList(HTMLComponent, GUIComponent):
275         def __init__(self):
276                 GUIComponent.__init__(self)
277                 self.l = eListboxServiceContent()
278         
279         def getCurrent(self):
280                 r = eServiceReference()
281                 self.l.getCurrent(r)
282                 return r
283
284         def GUIcreate(self, parent, skindata):
285                 self.instance = eListbox(parent)
286                 self.instance.setContent(self.l)
287         
288         def GUIdelete(self):
289                 del self.instance
290
291         def setRoot(self, root):
292                 self.l.setRoot(root)
293
294 class ServiceScan:
295         
296         Idle = 1
297         Running = 2
298         Done = 3
299         Error = 4
300                 
301         def scanStatusChanged(self):
302                 if self.state == self.Running:
303                         self.progressbar.setValue(self.scan.getProgress())
304                         if self.scan.isDone():
305                                 self.state = self.Done
306                         else:
307                                 self.text.setText("scan in progress - %d %% done!\n%d services found!" % (self.scan.getProgress(), self.scan.getNumServices()))
308                 
309                 if self.state == self.Done:
310                         self.text.setText("scan done!")
311                 
312                 if self.state == self.Error:
313                         self.text.setText("ERROR - failed to scan!")
314         
315         def __init__(self, progressbar, text):
316                 self.progressbar = progressbar
317                 self.text = text
318                 self.scan = eComponentScan()
319                 if self.scan.start():
320                         self.state = self.Error
321                 else:
322                         self.state = self.Running
323                 self.scan.statusChanged.get().append(self.scanStatusChanged)
324                 self.scanStatusChanged()
325
326         def isDone(self):
327                 return self.state == self.Done
328
329         def fix(self):
330                 self.scan.statusChanged.get().remove(self.scanStatusChanged)
331         
332 class ActionMap:
333         def __init__(self, context, actions = { }, prio=0):
334                 self.actions = actions
335                 self.context = context
336                 self.prio = prio
337                 self.p = eActionMapPtr()
338                 eActionMap.getInstance(self.p)
339
340         def execBegin(self):
341                 self.p.bindAction(self.context, self.prio, self.action)
342         
343         def execEnd(self):
344                 self.p.unbindAction(self.context, self.action)
345         
346         def action(self, context, action):
347                 try:
348                         self.actions[action]()
349                 except KeyError:
350                         print "unknown action %s/%s! typo in keymap?" % (context, action)
351
352 class PerServiceDisplay(GUIComponent, VariableText):
353         """Mixin for building components which display something which changes on navigation events, for example "service name" """
354         
355         def __init__(self, navcore, eventmap):
356                 GUIComponent.__init__(self)
357                 VariableText.__init__(self)
358                 self.eventmap = eventmap
359                 navcore.m_event.get().append(self.event)
360                 self.navcore = navcore
361
362                 # start with stopped state, so simulate that
363                 self.event(pNavigation.evStopService)
364
365         def event(self, ev):
366                 # loop up if we need to handle this event
367                 if self.eventmap.has_key(ev):
368                         # call handler
369                         self.eventmap[ev]()
370         
371         def createWidget(self, parent, skindata):
372                 # by default, we use a label to display our data.
373                 g = eLabel(parent)
374                 return g
375
376 class EventInfo(PerServiceDisplay):
377         Now = 0
378         Next = 1
379         def __init__(self, navcore, now_or_next):
380                 # listen to evUpdatedEventInfo and evStopService
381                 # note that evStopService will be called once to establish a known state
382                 PerServiceDisplay.__init__(self, navcore, 
383                         { 
384                                 pNavigation.evUpdatedEventInfo: self.ourEvent, 
385                                 pNavigation.evStopService: self.stopEvent 
386                         })
387                 self.now_or_next = now_or_next
388
389         def ourEvent(self):
390                 info = iServiceInformationPtr()
391                 service = iPlayableServicePtr()
392                 
393                 if not self.navcore.getCurrentService(service):
394                         if not service.info(info):
395                                 print "got info !"
396                                 ev = eServiceEventPtr()
397                                 info.getEvent(ev, self.now_or_next)
398                                 self.setText(ev.m_event_name)
399                 print "new event info in EventInfo! yeah!"
400
401         def stopEvent(self):
402                         self.setText("waiting for event data...");
403
404 class ServiceName(PerServiceDisplay):
405         def __init__(self, navcore):
406                 PerServiceDisplay.__init__(self, navcore,
407                         {
408                                 pNavigation.evNewService: self.newService,
409                                 pNavigation.evStopService: self.stopEvent
410                         })
411
412         def newService(self):
413                 info = iServiceInformationPtr()
414                 service = iPlayableServicePtr()
415                 
416                 if not self.navcore.getCurrentService(service):
417                         if not service.info(info):
418                                 self.setText("no name known, but it should be here :)")
419         
420         def stopEvent(self):
421                         self.setText("");