- hopefully fixed some python/refcount stuff (__deref__ is still evil!)
[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                 t = time.localtime()
163                 self.setText("%2d:%02d:%02d" % (t[3], t[4], t[5]))
164
165 # realisierung als GUI
166         def createWidget(self, parent, skindata):
167                 return eLabel(parent)
168
169         def removeWidget(self, w):
170                 del self.clockTimer
171
172 # ...und als HTML:
173         def produceHTML(self):
174                 return self.getText()
175                 
176 class Button(HTMLComponent, GUIComponent, VariableText):
177         def __init__(self, text="", onClick = [ ]):
178                 GUIComponent.__init__(self)
179                 VariableText.__init__(self)
180                 self.setText(text)
181                 self.onClick = onClick
182         
183         def push(self):
184                 for x in self.onClick:
185                         x()
186                 return 0
187         
188         def disable(self):
189 #               self.instance.hide()
190                 pass
191         
192         def enable(self):
193 #               self.instance.show()
194                 pass
195
196 # html:
197         def produceHTML(self):
198                 return "<input type=\"submit\" text=\"" + self.getText() + "\">\n"
199
200 # GUI:
201         def createWidget(self, parent, skindata):
202                 g = eButton(parent)
203                 g.selected.get().append(self.push)
204                 return g
205
206         def removeWidget(self, w):
207                 w.selected.get().remove(self.push)
208
209 class Label(HTMLComponent, GUIComponent, VariableText):
210         def __init__(self, text=""):
211                 GUIComponent.__init__(self)
212                 VariableText.__init__(self)
213                 self.setText(text)
214         
215 # html: 
216         def produceHTML(self):
217                 return self.getText()
218
219 # GUI:
220         def createWidget(self, parent, skindata):
221                 return eLabel(parent)
222         
223 class Header(HTMLComponent, GUIComponent, VariableText):
224
225         def __init__(self, message):
226                 GUIComponent.__init__(self)
227                 VariableText.__init__(self)
228                 self.setText(message)
229         
230         def produceHTML(self):
231                 return "<h2>" + self.getText() + "</h2>\n"
232
233         def createWidget(self, parent, skindata):
234                 g = eLabel(parent)
235                 return g
236
237 class VolumeBar(HTMLComponent, GUIComponent, VariableValue):
238         
239         def __init__(self):
240                 GUIComponent.__init__(self)
241                 VariableValue.__init__(self)
242
243         def createWidget(self, parent, skindata):
244                 g = eSlider(parent)
245                 g.setRange(0, 100)
246                 return g
247                 
248 # a general purpose progress bar
249 class ProgressBar(HTMLComponent, GUIComponent, VariableValue):
250         def __init__(self):
251                 GUIComponent.__init__(self)
252                 VariableValue.__init__(self)
253
254         def createWidget(self, parent, skindata):
255                 g = eSlider(parent)
256                 g.setRange(0, 100)
257                 return g
258         
259 class MenuList(HTMLComponent, GUIComponent):
260         def __init__(self, list):
261                 GUIComponent.__init__(self)
262                 self.l = eListboxPythonStringContent()
263                 self.l.setList(list)
264         
265         def getCurrent(self):
266                 return self.l.getCurrentSelection()
267         
268         def GUIcreate(self, parent, skindata):
269                 self.instance = eListbox(parent)
270                 self.instance.setContent(self.l)
271         
272         def GUIdelete(self):
273                 self.instance.setContent(None)
274                 del self.instance
275
276 class ServiceList(HTMLComponent, GUIComponent):
277         def __init__(self):
278                 GUIComponent.__init__(self)
279                 self.l = eListboxServiceContent()
280         
281         def getCurrent(self):
282                 r = eServiceReference()
283                 self.l.getCurrent(r)
284                 return r
285
286         def GUIcreate(self, parent, skindata):
287                 self.instance = eListbox(parent)
288                 self.instance.setContent(self.l)
289         
290         def GUIdelete(self):
291                 del self.instance
292
293         def setRoot(self, root):
294                 self.l.setRoot(root)
295
296 class ServiceScan:
297         
298         Idle = 1
299         Running = 2
300         Done = 3
301         Error = 4
302                 
303         def scanStatusChanged(self):
304                 if self.state == self.Running:
305                         self.progressbar.setValue(self.scan.getProgress())
306                         if self.scan.isDone():
307                                 self.state = self.Done
308                         else:
309                                 self.text.setText("scan in progress - %d %% done!\n%d services found!" % (self.scan.getProgress(), self.scan.getNumServices()))
310                 
311                 if self.state == self.Done:
312                         self.text.setText("scan done!")
313                 
314                 if self.state == self.Error:
315                         self.text.setText("ERROR - failed to scan!")
316         
317         def __init__(self, progressbar, text):
318                 self.progressbar = progressbar
319                 self.text = text
320                 self.scan = eComponentScan()
321                 self.state = self.Idle
322                 self.scanStatusChanged()
323                 
324         def execBegin(self):
325                 self.scan.statusChanged.get().append(self.scanStatusChanged)
326                 if self.scan.start():
327                         self.state = self.Error
328                 else:
329                         self.state = self.Running
330                 self.scanStatusChanged()
331         
332         def execEnd(self):
333                 self.scan.statusChanged.get().remove(self.scanStatusChanged)
334                 if not self.isDone():
335                         print "*** warning *** scan was not finished!"
336
337         def isDone(self):
338                 return self.state == self.Done
339         
340 class ActionMap:
341         def __init__(self, context, actions = { }, prio=0):
342                 self.actions = actions
343                 self.context = context
344                 self.prio = prio
345                 self.p = eActionMapPtr()
346                 eActionMap.getInstance(self.p)
347
348         def execBegin(self):
349                 self.p.bindAction(self.context, self.prio, self.action)
350         
351         def execEnd(self):
352                 self.p.unbindAction(self.context, self.action)
353         
354         def action(self, context, action):
355                 try:
356                         self.actions[action]()
357                 except KeyError:
358                         print "unknown action %s/%s! typo in keymap?" % (context, action)
359
360 class PerServiceDisplay(GUIComponent, VariableText):
361         """Mixin for building components which display something which changes on navigation events, for example "service name" """
362         
363         def __init__(self, navcore, eventmap):
364                 GUIComponent.__init__(self)
365                 VariableText.__init__(self)
366                 self.eventmap = eventmap
367                 navcore.m_event.get().append(self.event)
368                 self.navcore = navcore
369
370                 # start with stopped state, so simulate that
371                 self.event(pNavigation.evStopService)
372
373         def event(self, ev):
374                 # loop up if we need to handle this event
375                 if self.eventmap.has_key(ev):
376                         # call handler
377                         self.eventmap[ev]()
378         
379         def createWidget(self, parent, skindata):
380                 # by default, we use a label to display our data.
381                 g = eLabel(parent)
382                 return g
383
384 class EventInfo(PerServiceDisplay):
385         Now = 0
386         Next = 1
387         Now_Duration = 2
388         Next_Duration = 3
389         
390         def __init__(self, navcore, now_or_next):
391                 # listen to evUpdatedEventInfo and evStopService
392                 # note that evStopService will be called once to establish a known state
393                 PerServiceDisplay.__init__(self, navcore, 
394                         { 
395                                 pNavigation.evUpdatedEventInfo: self.ourEvent, 
396                                 pNavigation.evStopService: self.stopEvent 
397                         })
398                 self.now_or_next = now_or_next
399
400         def ourEvent(self):
401                 info = iServiceInformationPtr()
402                 service = iPlayableServicePtr()
403                 
404                 if not self.navcore.getCurrentService(service):
405                         if not service.info(info):
406                                 ev = eServiceEventPtr()
407                                 info.getEvent(ev, self.now_or_next & 1)
408                                 if self.now_or_next & 2:
409                                         self.setText("%d min" % (ev.m_duration / 60))
410                                 else:
411                                         self.setText(ev.m_event_name)
412                 print "new event info in EventInfo! yeah!"
413
414         def stopEvent(self):
415                         self.setText("waiting for event data...");
416
417 class ServiceName(PerServiceDisplay):
418         def __init__(self, navcore):
419                 PerServiceDisplay.__init__(self, navcore,
420                         {
421                                 pNavigation.evNewService: self.newService,
422                                 pNavigation.evStopService: self.stopEvent
423                         })
424
425         def newService(self):
426                 info = iServiceInformationPtr()
427                 service = iPlayableServicePtr()
428                 
429                 if not self.navcore.getCurrentService(service):
430                         if not service.info(info):
431                                 self.setText("no name known, but it should be here :)")
432         
433         def stopEvent(self):
434                         self.setText("");