- added hack for disabling actions on hidden windows. FIX ME
[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                 # mark stuff
297         def clearMarked(self):
298                 self.l.clearMarked()
299         
300         def isMarked(self, ref):
301                 return self.l.isMarked(ref)
302
303         def addMarked(self, ref):
304                 self.l.addMarked(ref)
305         
306         def removeMarked(self, ref):
307                 self.l.removeMarked(ref)
308
309 class ServiceScan:
310         
311         Idle = 1
312         Running = 2
313         Done = 3
314         Error = 4
315                 
316         def scanStatusChanged(self):
317                 if self.state == self.Running:
318                         self.progressbar.setValue(self.scan.getProgress())
319                         if self.scan.isDone():
320                                 self.state = self.Done
321                         else:
322                                 self.text.setText("scan in progress - %d %% done!\n%d services found!" % (self.scan.getProgress(), self.scan.getNumServices()))
323                 
324                 if self.state == self.Done:
325                         self.text.setText("scan done!")
326                 
327                 if self.state == self.Error:
328                         self.text.setText("ERROR - failed to scan!")
329         
330         def __init__(self, progressbar, text):
331                 self.progressbar = progressbar
332                 self.text = text
333                 self.scan = eComponentScan()
334                 self.state = self.Idle
335                 self.scanStatusChanged()
336                 
337         def execBegin(self):
338                 self.scan.statusChanged.get().append(self.scanStatusChanged)
339                 if self.scan.start():
340                         self.state = self.Error
341                 else:
342                         self.state = self.Running
343                 self.scanStatusChanged()
344         
345         def execEnd(self):
346                 self.scan.statusChanged.get().remove(self.scanStatusChanged)
347                 if not self.isDone():
348                         print "*** warning *** scan was not finished!"
349
350         def isDone(self):
351                 return self.state == self.Done
352         
353 class ActionMap:
354         def __init__(self, contexts = [ ], actions = { }, prio=0):
355                 self.actions = actions
356                 self.contexts = contexts
357                 self.prio = prio
358                 self.p = eActionMapPtr()
359                 eActionMap.getInstance(self.p)
360
361         def execBegin(self):
362                 for ctx in self.contexts:
363                         self.p.bindAction(ctx, self.prio, self.action)
364         
365         def execEnd(self):
366                 for ctx in self.contexts:
367                         self.p.unbindAction(ctx, self.action)
368         
369         def action(self, context, action):
370                 print " ".join(("action -> ", context, action))
371                 try:
372                         self.actions[action]()
373                 except KeyError:
374                         print "unknown action %s/%s! typo in keymap?" % (context, action)
375
376 class PerServiceDisplay(GUIComponent, VariableText):
377         """Mixin for building components which display something which changes on navigation events, for example "service name" """
378         
379         def __init__(self, navcore, eventmap):
380                 GUIComponent.__init__(self)
381                 VariableText.__init__(self)
382                 self.eventmap = eventmap
383                 navcore.m_event.get().append(self.event)
384                 self.navcore = navcore
385
386                 # start with stopped state, so simulate that
387                 self.event(pNavigation.evStopService)
388
389         def event(self, ev):
390                 # loop up if we need to handle this event
391                 if self.eventmap.has_key(ev):
392                         # call handler
393                         self.eventmap[ev]()
394         
395         def createWidget(self, parent, skindata):
396                 # by default, we use a label to display our data.
397                 g = eLabel(parent)
398                 return g
399
400 class EventInfo(PerServiceDisplay):
401         Now = 0
402         Next = 1
403         Now_Duration = 2
404         Next_Duration = 3
405         
406         def __init__(self, navcore, now_or_next):
407                 # listen to evUpdatedEventInfo and evStopService
408                 # note that evStopService will be called once to establish a known state
409                 PerServiceDisplay.__init__(self, navcore, 
410                         { 
411                                 pNavigation.evUpdatedEventInfo: self.ourEvent, 
412                                 pNavigation.evStopService: self.stopEvent 
413                         })
414                 self.now_or_next = now_or_next
415
416         def ourEvent(self):
417                 info = iServiceInformationPtr()
418                 service = iPlayableServicePtr()
419                 
420                 if not self.navcore.getCurrentService(service):
421                         if not service.info(info):
422                                 ev = eServiceEventPtr()
423                                 info.getEvent(ev, self.now_or_next & 1)
424                                 if self.now_or_next & 2:
425                                         self.setText("%d min" % (ev.m_duration / 60))
426                                 else:
427                                         self.setText(ev.m_event_name)
428                 print "new event info in EventInfo! yeah!"
429
430         def stopEvent(self):
431                         self.setText("waiting for event data...");
432
433 class ServiceName(PerServiceDisplay):
434         def __init__(self, navcore):
435                 PerServiceDisplay.__init__(self, navcore,
436                         {
437                                 pNavigation.evNewService: self.newService,
438                                 pNavigation.evStopService: self.stopEvent
439                         })
440
441         def newService(self):
442                 info = iServiceInformationPtr()
443                 service = iPlayableServicePtr()
444                 
445                 if not self.navcore.getCurrentService(service):
446                         if not service.info(info):
447                                 self.setText("no name known, but it should be here :)")
448         
449         def stopEvent(self):
450                         self.setText("");