- actionmap component will not catch (wrong) exceptions anymore
[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                         # DIESER KOMMENTAR IST NUTZLOS UND MITTLERWEILE VERALTET! (glaub ich)
42                         # BITTE NICHT LESEN!
43                         # note: you'll probably run into this assert. if this happens, don't panic!
44                         # yes, it's evil. I told you that programming in python is just fun, and 
45                         # suddently, you have to care about things you don't even know.
46                         #
47                         # but calm down, the solution is easy, at least on paper:
48                         #
49                         # Each Component, which is a GUIComponent, owns references to each
50                         # instantiated eWidget (namely in screen.data[name]["instance"], in case
51                         # you care.)
52                         # on deleteGUIscreen, all eWidget *must* (!) be deleted (otherwise,
53                         # well, problems appear. I don't want to go into details too much,
54                         # but this would be a memory leak anyway.)
55                         # The assert beyond checks for that. It asserts that the corresponding
56                         # eWidget is about to be removed (i.e., that the refcount becomes 0 after
57                         # running deleteGUIscreen).
58                         # (You might wonder why the refcount is checked for 2 and not for 1 or 0 -
59                         # one reference is still hold by the local variable 'w', another one is
60                         # hold be the function argument to sys.getrefcount itself. So only if it's
61                         # 2 at this point, the object will be destroyed after leaving deleteGUIscreen.)
62                         #
63                         # Now, how to fix this problem? You're holding a reference somewhere. (References
64                         # can only be hold from Python, as eWidget itself isn't related to the c++
65                         # way of having refcounted objects. So it must be in python.)
66                         #
67                         # It could be possible that you're calling deleteGUIscreen trough a call of
68                         # a PSignal. For example, you could try to call screen.doClose() in response
69                         # to a Button::click. This will fail. (It wouldn't work anyway, as you would
70                         # remove a dialog while running it. It never worked - enigma1 just set a 
71                         # per-mainloop variable on eWidget::close() to leave the exec()...)
72                         # That's why Session supports delayed closes. Just call Session.close() and
73                         # it will work.
74                         #
75                         # Another reason is that you just stored the data["instance"] somewhere. or
76                         # added it into a notifier list and didn't removed it.
77                         #
78                         # If you can't help yourself, just ask me. I'll be glad to help you out.
79                         # Sorry for not keeping this code foolproof. I really wanted to archive
80                         # that, but here I failed miserably. All I could do was to add this assert.
81 #                       assert sys.getrefcount(w) == 2, "too many refs hold to " + str(w)
82         
83         def close(self):
84                 self.deleteGUIScreen()
85
86 class GUIComponent:
87         """ GUI component """
88
89         def __init__(self):
90                 pass
91                 
92         def execBegin(self):
93                 pass
94         
95         def execEnd(self):
96                 pass
97
98 class VariableText:
99         """VariableText can be used for components which have a variable text, based on any widget with setText call"""
100         
101         def __init__(self):
102                 self.message = ""
103                 self.instance = None
104         
105         def setText(self, text):
106                 self.message = text
107                 if self.instance:
108                         self.instance.setText(self.message)
109
110         def getText(self):
111                 return self.message
112         
113         def GUIcreate(self, parent, skindata):
114                 self.instance = self.createWidget(parent, skindata)
115                 self.instance.setText(self.message)
116         
117         def GUIdelete(self):
118                 self.removeWidget(self.instance)
119                 del self.instance
120         
121         def removeWidget(self, instance):
122                 pass
123
124 class VariableValue:
125         """VariableValue can be used for components which have a variable value (like eSlider), based on any widget with setValue call"""
126         
127         def __init__(self):
128                 self.value = 0
129                 self.instance = None
130         
131         def setValue(self, value):
132                 self.value = value
133                 if self.instance:
134                         self.instance.setValue(self.value)
135
136         def getValue(self):
137                 return self.value
138                 
139         def GUIcreate(self, parent, skindata):
140                 self.instance = self.createWidget(parent, skindata)
141                 self.instance.setValue(self.value)
142         
143         def GUIdelete(self):
144                 self.removeWidget(self.instance)
145                 del self.instance
146         
147         def removeWidget(self, instance):
148                 pass
149
150 # now some "real" components:
151
152 class Clock(HTMLComponent, GUIComponent, VariableText):
153         def __init__(self):
154                 VariableText.__init__(self)
155                 GUIComponent.__init__(self)
156                 self.doClock()
157                 
158                 self.clockTimer = eTimer()
159                 self.clockTimer.timeout.get().append(self.doClock)
160                 self.clockTimer.start(1000)
161
162 # "funktionalitaet"     
163         def doClock(self):
164                 t = time.localtime()
165                 self.setText("%2d:%02d:%02d" % (t[3], t[4], t[5]))
166
167 # realisierung als GUI
168         def createWidget(self, parent, skindata):
169                 return eLabel(parent)
170
171         def removeWidget(self, w):
172                 del self.clockTimer
173
174 # ...und als HTML:
175         def produceHTML(self):
176                 return self.getText()
177                 
178 class Button(HTMLComponent, GUIComponent, VariableText):
179         def __init__(self, text="", onClick = [ ]):
180                 GUIComponent.__init__(self)
181                 VariableText.__init__(self)
182                 self.setText(text)
183                 self.onClick = onClick
184         
185         def push(self):
186                 for x in self.onClick:
187                         x()
188                 return 0
189         
190         def disable(self):
191 #               self.instance.hide()
192                 pass
193         
194         def enable(self):
195 #               self.instance.show()
196                 pass
197
198 # html:
199         def produceHTML(self):
200                 return "<input type=\"submit\" text=\"" + self.getText() + "\">\n"
201
202 # GUI:
203         def createWidget(self, parent, skindata):
204                 g = eButton(parent)
205                 g.selected.get().append(self.push)
206                 return g
207
208         def removeWidget(self, w):
209                 w.selected.get().remove(self.push)
210
211 class Label(HTMLComponent, GUIComponent, VariableText):
212         def __init__(self, text=""):
213                 GUIComponent.__init__(self)
214                 VariableText.__init__(self)
215                 self.setText(text)
216         
217 # html: 
218         def produceHTML(self):
219                 return self.getText()
220
221 # GUI:
222         def createWidget(self, parent, skindata):
223                 return eLabel(parent)
224         
225 class Header(HTMLComponent, GUIComponent, VariableText):
226
227         def __init__(self, message):
228                 GUIComponent.__init__(self)
229                 VariableText.__init__(self)
230                 self.setText(message)
231         
232         def produceHTML(self):
233                 return "<h2>" + self.getText() + "</h2>\n"
234
235         def createWidget(self, parent, skindata):
236                 g = eLabel(parent)
237                 return g
238
239 class VolumeBar(HTMLComponent, GUIComponent, VariableValue):
240         
241         def __init__(self):
242                 GUIComponent.__init__(self)
243                 VariableValue.__init__(self)
244
245         def createWidget(self, parent, skindata):
246                 g = eSlider(parent)
247                 g.setRange(0, 100)
248                 return g
249                 
250 # a general purpose progress bar
251 class ProgressBar(HTMLComponent, GUIComponent, VariableValue):
252         def __init__(self):
253                 GUIComponent.__init__(self)
254                 VariableValue.__init__(self)
255
256         def createWidget(self, parent, skindata):
257                 g = eSlider(parent)
258                 g.setRange(0, 100)
259                 return g
260         
261 class MenuList(HTMLComponent, GUIComponent):
262         def __init__(self, list):
263                 GUIComponent.__init__(self)
264                 self.l = eListboxPythonStringContent()
265                 self.l.setList(list)
266         
267         def getCurrent(self):
268                 return self.l.getCurrentSelection()
269         
270         def GUIcreate(self, parent, skindata):
271                 self.instance = eListbox(parent)
272                 self.instance.setContent(self.l)
273         
274         def GUIdelete(self):
275                 self.instance.setContent(None)
276                 del self.instance
277
278
279 #  temp stuff :)
280 class configBoolean:
281         def __init__(self, reg):
282                 self.reg = reg
283                 self.val = 0
284         
285         def toggle(self):
286                 self.val += 1
287                 self.val %= 3
288         
289         def __str__(self):
290                 return ("NO", "YES", "MAYBE")[self.val]
291
292 class configValue:
293         def __init__(self, obj):
294                 self.obj = obj
295                 
296         def __str__(self):
297                 return self.obj
298
299 def configEntry(obj):
300         # das hier ist ein zugriff auf die registry...
301         if obj == "HKEY_LOCAL_ENIGMA/IMPORTANT/USER_ANNOYING_STUFF/SDTV/FLASHES/GREEN":
302                 return ("SDTV green flashes", configBoolean(obj))
303         elif obj == "HKEY_LOCAL_ENIGMA/IMPORTANT/USER_ANNOYING_STUFF/HDTV/FLASHES/GREEN":
304                 return ("HDTV reen flashes", configBoolean(obj))
305         else:
306                 return ("invalid", "")
307
308 class ConfigList(HTMLComponent, GUIComponent):
309         def __init__(self, list):
310                 GUIComponent.__init__(self)
311                 self.l = eListboxPythonConfigContent()
312                 self.l.setList(list)
313                 self.l.setSeperation(100)
314         
315         def toggle(self):
316                 selection = self.getCurrent()
317                 selection[1].toggle()
318                 self.invalidateCurrent()
319         
320         def getCurrent(self):
321                 return self.l.getCurrentSelection()
322         
323         def invalidateCurrent(self):
324                 self.l.invalidateEntry(self.l.getCurrentSelectionIndex())
325         
326         def GUIcreate(self, parent, skindata):
327                 self.instance = eListbox(parent)
328                 self.instance.setContent(self.l)
329         
330         def GUIdelete(self):
331                 self.instance.setContent(None)
332                 del self.instance
333
334 class ServiceList(HTMLComponent, GUIComponent):
335         def __init__(self):
336                 GUIComponent.__init__(self)
337                 self.l = eListboxServiceContent()
338                 
339         def getCurrent(self):
340                 r = eServiceReference()
341                 self.l.getCurrent(r)
342                 return r
343                 
344         def moveUp(self):
345                 self.instance.moveSelection(self.instance.moveUp)
346
347         def moveDown(self):
348                 self.instance.moveSelection(self.instance.moveDown)
349
350         def GUIcreate(self, parent, skindata):
351                 self.instance = eListbox(parent)
352                 self.instance.setContent(self.l)
353         
354         def GUIdelete(self):
355                 del self.instance
356
357         def setRoot(self, root):
358                 self.l.setRoot(root)
359                 
360                 # mark stuff
361         def clearMarked(self):
362                 self.l.clearMarked()
363         
364         def isMarked(self, ref):
365                 return self.l.isMarked(ref)
366
367         def addMarked(self, ref):
368                 self.l.addMarked(ref)
369         
370         def removeMarked(self, ref):
371                 self.l.removeMarked(ref)
372
373 class ServiceScan:
374         
375         Idle = 1
376         Running = 2
377         Done = 3
378         Error = 4
379         
380         Errors = { 
381                 0: "error starting scanning",
382                 1: "error while scanning",
383                 2: "no resource manager",
384                 3: "no channel list"
385                 }
386         
387         def scanStatusChanged(self):
388                 if self.state == self.Running:
389                         self.progressbar.setValue(self.scan.getProgress())
390                         if self.scan.isDone():
391                                 errcode = self.scan.getError()
392                                 
393                                 if errcode == 0:
394                                         self.state = self.Done
395                                 else:
396                                         self.state = self.Error
397                                         self.errorcode = errcode
398                         else:
399                                 self.text.setText("scan in progress - %d %% done!\n%d services found!" % (self.scan.getProgress(), self.scan.getNumServices()))
400                 
401                 if self.state == self.Done:
402                         self.text.setText("scan done!")
403                 
404                 if self.state == self.Error:
405                         self.text.setText("ERROR - failed to scan (%s)!" % (self.Errors[self.errorcode]) )
406         
407         def __init__(self, progressbar, text):
408                 self.progressbar = progressbar
409                 self.text = text
410                 self.scan = eComponentScan()
411                 self.state = self.Idle
412                 self.scanStatusChanged()
413                 
414         def execBegin(self):
415                 self.scan.statusChanged.get().append(self.scanStatusChanged)
416                 self.state = self.Running
417                 err = self.scan.start()
418                 if err:
419                         self.state = self.Error
420                         self.errorcode = 0
421
422                 self.scanStatusChanged()
423         
424         def execEnd(self):
425                 self.scan.statusChanged.get().remove(self.scanStatusChanged)
426                 if not self.isDone():
427                         print "*** warning *** scan was not finished!"
428
429         def isDone(self):
430                 print "state is %d " % (self.state)
431                 return self.state == self.Done or self.state == self.Error
432         
433 class ActionMap:
434         def __init__(self, contexts = [ ], actions = { }, prio=0):
435                 self.actions = actions
436                 self.contexts = contexts
437                 self.prio = prio
438                 self.p = eActionMapPtr()
439                 eActionMap.getInstance(self.p)
440
441         def execBegin(self):
442                 for ctx in self.contexts:
443                         self.p.bindAction(ctx, self.prio, self.action)
444         
445         def execEnd(self):
446                 for ctx in self.contexts:
447                         self.p.unbindAction(ctx, self.action)
448         
449         def action(self, context, action):
450                 print " ".join(("action -> ", context, action))
451                 if self.actions.has_key(action):
452                         self.actions[action]()
453                 else:
454                         print "unknown action %s/%s! typo in keymap?" % (context, action)
455
456 class PerServiceDisplay(GUIComponent, VariableText):
457         """Mixin for building components which display something which changes on navigation events, for example "service name" """
458         
459         def __init__(self, navcore, eventmap):
460                 GUIComponent.__init__(self)
461                 VariableText.__init__(self)
462                 self.eventmap = eventmap
463                 navcore.m_event.get().append(self.event)
464                 self.navcore = navcore
465
466                 # start with stopped state, so simulate that
467                 self.event(pNavigation.evStopService)
468
469         def event(self, ev):
470                 # loop up if we need to handle this event
471                 if self.eventmap.has_key(ev):
472                         # call handler
473                         self.eventmap[ev]()
474         
475         def createWidget(self, parent, skindata):
476                 # by default, we use a label to display our data.
477                 g = eLabel(parent)
478                 return g
479
480 class EventInfo(PerServiceDisplay):
481         Now = 0
482         Next = 1
483         Now_Duration = 2
484         Next_Duration = 3
485         
486         def __init__(self, navcore, now_or_next):
487                 # listen to evUpdatedEventInfo and evStopService
488                 # note that evStopService will be called once to establish a known state
489                 self.now_or_next = now_or_next
490                 PerServiceDisplay.__init__(self, navcore, 
491                         { 
492                                 pNavigation.evUpdatedEventInfo: self.ourEvent, 
493                                 pNavigation.evStopService: self.stopEvent 
494                         })
495
496         def ourEvent(self):
497                 info = iServiceInformationPtr()
498                 service = iPlayableServicePtr()
499                 
500                 if not self.navcore.getCurrentService(service):
501                         if not service.info(info):
502                                 ev = eServiceEventPtr()
503                                 info.getEvent(ev, self.now_or_next & 1)
504                                 if self.now_or_next & 2:
505                                         self.setText("%d min" % (ev.m_duration / 60))
506                                 else:
507                                         self.setText(ev.m_event_name)
508                 print "new event info in EventInfo! yeah!"
509
510         def stopEvent(self):
511                 self.setText(
512                         ("waiting for event data...", "", "--:--",  "--:--")[self.now_or_next]);
513
514 class ServiceName(PerServiceDisplay):
515         def __init__(self, navcore):
516                 PerServiceDisplay.__init__(self, navcore,
517                         {
518                                 pNavigation.evNewService: self.newService,
519                                 pNavigation.evStopService: self.stopEvent
520                         })
521
522         def newService(self):
523                 info = iServiceInformationPtr()
524                 service = iPlayableServicePtr()
525                 
526                 if not self.navcore.getCurrentService(service):
527                         if not service.info(info):
528                                 self.setText("no name known, but it should be here :)")
529         
530         def stopEvent(self):
531                         self.setText("");
532