make video stream type for running service accessible from python
[enigma2.git] / mytest.py
1 from Tools import RedirectOutput
2 from enigma import *
3 from tools import *
4
5 from Components.Language import language
6
7 def setEPGLanguage():
8         print "language set to", language.getLanguage()
9         eServiceEvent.setEPGLanguage(language.getLanguage())
10         
11 language.addCallback(setEPGLanguage)
12
13 import traceback
14 import Screens.InfoBar
15 from Screens.SimpleSummary import SimpleSummary
16
17 import sys
18 import time
19
20 import ServiceReference
21
22 from Navigation import Navigation
23
24 from skin import readSkin, applyAllAttributes
25
26 from Components.config import configfile
27 from Tools.Directories import InitFallbackFiles, resolveFilename, SCOPE_PLUGINS
28 InitFallbackFiles()
29 eDVBDB.getInstance().reloadBouquets()
30
31 try:
32         import e2reactor
33         e2reactor.install()
34         
35         from twisted.internet import reactor
36         
37         def runReactor():
38                 reactor.run()
39 except ImportError:
40         print "twisted not available"
41         def runReactor():
42                 runMainloop()
43
44 # initialize autorun plugins and plugin menu entries
45 from Components.PluginComponent import plugins
46
47 from Screens.Wizard import wizardManager
48 from Screens.ImageWizard import *
49 from Screens.StartWizard import *
50 from Screens.TutorialWizard import *
51 from Tools.BoundFunction import boundFunction
52 from Plugins.Plugin import PluginDescriptor
53
54 had = dict()
55
56 def dump(dir, p = ""):
57         if isinstance(dir, dict):
58                 for (entry, val) in dir.items():
59                         dump(val, p + "(dict)/" + entry)
60         if hasattr(dir, "__dict__"):
61                 for name, value in dir.__dict__.items():
62                         if not had.has_key(str(value)):
63                                 had[str(value)] = 1
64                                 dump(value, p + "/" + str(name))
65                         else:
66                                 print p + "/" + str(name) + ":" + str(dir.__class__) + "(cycle)"
67         else:
68                 print p + ":" + str(dir)
69
70 # + ":" + str(dir.__class__)
71
72 # display
73
74 class OutputDevice:
75         def create(self, screen): pass
76
77 # display: HTML
78
79 class HTMLOutputDevice(OutputDevice):
80         def create(self, comp):
81                 print comp.produceHTML()
82
83 html = HTMLOutputDevice()
84
85 class GUIOutputDevice(OutputDevice):
86         parent = None
87         def create(self, comp, desktop):
88                 comp.createGUIScreen(self.parent, desktop)
89
90 # Session.open:
91 # * push current active dialog ('current_dialog') onto stack
92 # * call execEnd for this dialog
93 #   * clear in_exec flag
94 #   * hide screen
95 # * instantiate new dialog into 'current_dialog'
96 #   * create screens, components
97 #   * read, apply skin
98 #   * create GUI for screen
99 # * call execBegin for new dialog
100 #   * set in_exec
101 #   * show gui screen
102 #   * call components' / screen's onExecBegin
103 # ... screen is active, until it calls 'close'...
104 # Session.close:
105 # * assert in_exec
106 # * save return value
107 # * start deferred close handler ('onClose')
108 # * execEnd
109 #   * clear in_exec
110 #   * hide screen
111 # .. a moment later:
112 # Session.doClose:
113 # * destroy screen
114
115 class Session:
116         def __init__(self, desktop = None, summary_desktop = None, navigation = None):
117                 self.desktop = desktop
118                 self.summary_desktop = summary_desktop
119                 self.nav = navigation
120                 self.delay_timer = eTimer()
121                 self.delay_timer.timeout.get().append(self.processDelay)
122                 
123                 self.current_dialog = None
124                 
125                 self.dialog_stack = [ ]
126                 self.summary_stack = [ ]
127                 self.summary = None
128                 
129                 self.in_exec = False
130                 
131                 for p in plugins.getPlugins(PluginDescriptor.WHERE_SESSIONSTART):
132                         p(reason=0, session=self)
133         
134         def processDelay(self):
135                 callback = self.current_dialog.callback
136
137                 retval = self.current_dialog.returnValue
138
139                 if self.current_dialog.isTmp:
140                         self.current_dialog.doClose()
141 #                       dump(self.current_dialog)
142                         del self.current_dialog
143                 else:
144                         del self.current_dialog.callback
145                 
146                 self.popCurrent()
147                 if callback is not None:
148                         callback(*retval)
149
150         def execBegin(self):
151                 assert not self.in_exec 
152                 self.in_exec = True
153                 c = self.current_dialog
154                 
155                 self.pushSummary()
156
157                 summary = c.createSummary() or SimpleSummary
158                 self.summary = self.instantiateSummaryDialog(summary, c)
159                 self.summary.show()
160
161                 c.addSummary(self.summary)
162                 c.execBegin()
163
164                 # when execBegin opened a new dialog, don't bother showing the old one.
165                 if c == self.current_dialog:
166                         c.show()
167                 
168         def execEnd(self):
169                 assert self.in_exec
170                 self.in_exec = False
171
172                 self.current_dialog.execEnd()
173                 self.current_dialog.hide()
174                 self.current_dialog.removeSummary(self.summary)
175                 self.popSummary()
176         
177         def create(self, screen, arguments, **kwargs):
178                 # creates an instance of 'screen' (which is a class)
179                 try:
180                         return screen(self, *arguments, **kwargs)
181                 except:
182                         errstr = "Screen %s(%s, %s): %s" % (str(screen), str(arguments), str(kwargs), sys.exc_info()[0])
183                         print errstr
184                         traceback.print_exc(file=sys.stdout)
185                         quitMainloop(5)
186         
187         def instantiateDialog(self, screen, *arguments, **kwargs):
188                 return self.doInstantiateDialog(screen, arguments, kwargs, self.desktop)
189         
190         def instantiateSummaryDialog(self, screen, *arguments, **kwargs):
191                 return self.doInstantiateDialog(screen, arguments, kwargs, self.summary_desktop)
192         
193         def doInstantiateDialog(self, screen, arguments, kwargs, desktop):
194                 # create dialog
195                 
196                 try:
197                         dlg = self.create(screen, arguments, **kwargs)
198                 except:
199                         print 'EXCEPTION IN DIALOG INIT CODE, ABORTING:'
200                         print '-'*60
201                         traceback.print_exc(file=sys.stdout)
202                         quitMainloop(5)
203                         print '-'*60
204                 
205                 if dlg is None:
206                         return
207
208                 # read skin data
209                 readSkin(dlg, None, dlg.skinName, desktop)
210
211                 # create GUI view of this dialog
212                 assert desktop is not None
213                 
214                 z = 0
215                 title = ""
216                 for (key, value) in dlg.skinAttributes:
217                         if key == "zPosition":
218                                 z = int(value)
219                         elif key == "title":
220                                 title = value
221                 
222                 dlg.instance = eWindow(desktop, z)
223                 dlg.title = title
224                 applyAllAttributes(dlg.instance, desktop, dlg.skinAttributes)
225                 gui = GUIOutputDevice()
226                 gui.parent = dlg.instance
227                 gui.create(dlg, desktop)
228                 
229                 return dlg
230          
231         def pushCurrent(self):
232                 if self.current_dialog is not None:
233                         self.dialog_stack.append(self.current_dialog)
234                         self.execEnd()
235         
236         def popCurrent(self):
237                 if len(self.dialog_stack):
238                         self.current_dialog = self.dialog_stack.pop()
239                         self.execBegin()
240                 else:
241                         self.current_dialog = None
242
243         def execDialog(self, dialog):
244                 self.pushCurrent()
245                 self.current_dialog = dialog
246                 self.current_dialog.isTmp = False
247                 self.current_dialog.callback = None # would cause re-entrancy problems.
248                 self.execBegin()
249
250         def openWithCallback(self, callback, screen, *arguments, **kwargs):
251                 dlg = self.open(screen, *arguments, **kwargs)
252                 dlg.callback = callback
253                 return dlg
254
255         def open(self, screen, *arguments, **kwargs):
256                 if len(self.dialog_stack) and not self.in_exec:
257                         raise "modal open are allowed only from a screen which is modal!"
258                         # ...unless it's the very first screen.
259                 
260                 self.pushCurrent()
261                 dlg = self.current_dialog = self.instantiateDialog(screen, *arguments, **kwargs)
262                 dlg.isTmp = True
263                 dlg.callback = None
264                 self.execBegin()
265                 return dlg
266
267         def keyEvent(self, code):
268                 print "code " + str(code)
269
270         def close(self, screen, *retval):
271                 if not self.in_exec:
272                         print "close after exec!"
273                         return
274                 
275                 # be sure that the close is for the right dialog!
276                 # if it's not, you probably closed after another dialog
277                 # was opened. this can happen if you open a dialog
278                 # onExecBegin, and forget to do this only once.
279                 # after close of the top dialog, the underlying will
280                 # gain focus again (for a short time), thus triggering
281                 # the onExec, which opens the dialog again, closing the loop.
282                 assert screen == self.current_dialog
283                 
284                 self.current_dialog.returnValue = retval
285                 self.delay_timer.start(0, 1)
286                 self.execEnd()
287
288         def pushSummary(self):
289                 if self.summary is not None:
290                         self.summary.hide()
291                 self.summary_stack.append(self.summary)
292                 self.summary = None
293
294         def popSummary(self):
295                 if self.summary is not None:
296                         self.summary.doClose()
297                 self.summary = self.summary_stack.pop()
298                 if self.summary is not None:
299                         self.summary.show()
300
301 from Screens.Volume import Volume
302 from Screens.Mute import Mute
303 from GlobalActions import globalActionMap
304 from Components.config import ConfigSubsection, configSequence, configElement, configsequencearg
305
306 #TODO .. move this to a own .py file
307 class VolumeControl:
308         """Volume control, handles volUp, volDown, volMute actions and display
309         a corresponding dialog"""
310         def __init__(self, session):
311                 global globalActionMap
312                 globalActionMap.actions["volumeUp"]=self.volUp
313                 globalActionMap.actions["volumeDown"]=self.volDown
314                 globalActionMap.actions["volumeMute"]=self.volMute
315
316                 config.audio = ConfigSubsection()
317                 config.audio.volume = configElement("config.audio.volume", configSequence, [100], configsequencearg.get("INTEGER", (0, 100)))
318
319                 self.volumeDialog = session.instantiateDialog(Volume)
320                 self.muteDialog = session.instantiateDialog(Mute)
321
322                 self.hideVolTimer = eTimer()
323                 self.hideVolTimer.timeout.get().append(self.volHide)
324
325                 vol = config.audio.volume.value[0]
326                 self.volumeDialog.setValue(vol)
327                 eDVBVolumecontrol.getInstance().setVolume(vol, vol)
328
329         def volSave(self):
330                 config.audio.volume.value = eDVBVolumecontrol.getInstance().getVolume()
331                 config.audio.volume.save()
332
333         def     volUp(self):
334                 if (eDVBVolumecontrol.getInstance().isMuted()):
335                         self.volMute()
336                 eDVBVolumecontrol.getInstance().volumeUp()
337                 self.volumeDialog.show()
338                 self.volumeDialog.setValue(eDVBVolumecontrol.getInstance().getVolume())
339                 self.volSave()
340                 self.hideVolTimer.start(3000, True)
341
342         def     volDown(self):
343                 if (eDVBVolumecontrol.getInstance().isMuted()):
344                         self.volMute()
345                 eDVBVolumecontrol.getInstance().volumeDown()
346                 self.volumeDialog.show()
347                 self.volumeDialog.setValue(eDVBVolumecontrol.getInstance().getVolume())
348                 self.volSave()
349                 self.hideVolTimer.start(3000, True)
350
351         def volHide(self):
352                 self.volumeDialog.hide()
353
354         def     volMute(self):
355                 eDVBVolumecontrol.getInstance().volumeToggleMute()
356                 self.volumeDialog.setValue(eDVBVolumecontrol.getInstance().getVolume())
357
358                 if (eDVBVolumecontrol.getInstance().isMuted()):
359                         self.muteDialog.show()
360                 else:
361                         self.muteDialog.hide()
362
363 from Screens.Standby import Standby
364
365 class PowerKey:
366         """ PowerKey stuff - handles the powerkey press and powerkey release actions"""
367         
368         def __init__(self, session):
369                 self.session = session
370                 self.powerKeyTimer = eTimer()
371                 self.powerKeyTimer.timeout.get().append(self.powertimer)
372                 globalActionMap.actions["powerdown"]=self.powerdown
373                 globalActionMap.actions["powerup"]=self.powerup
374                 self.standbyblocked = 0
375 #               self["PowerKeyActions"] = HelpableActionMap(self, "PowerKeyActions",
376                         #{
377                                 #"powerdown": self.powerdown,
378                                 #"powerup": self.powerup,
379                                 #"discreteStandby": (self.standby, "Go standby"),
380                                 #"discretePowerOff": (self.quit, "Go to deep standby"),
381                         #})
382
383         def powertimer(self):   
384                 print "PowerOff - Now!"
385                 self.quit()
386         
387         def powerdown(self):
388                 self.standbyblocked = 0
389                 self.powerKeyTimer.start(3000, True)
390
391         def powerup(self):
392                 self.powerKeyTimer.stop()
393                 if self.standbyblocked == 0:
394                         self.standbyblocked = 1
395                         self.standby()
396
397         def standby(self):
398                 self.session.open(Standby, self)
399
400         def quit(self):
401                 # halt
402                 quitMainloop(1)
403
404 def runScreenTest():
405         plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
406
407         session = Session(desktop = getDesktop(0), summary_desktop = getDesktop(1), navigation = Navigation())
408         
409         screensToRun = [ ]
410         
411         for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD):
412                 screensToRun.append(p.__call__)
413         
414         screensToRun += wizardManager.getWizards()
415         
416         screensToRun.append(Screens.InfoBar.InfoBar)
417
418         ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)
419
420         def runNextScreen(session, screensToRun, *result):
421                 if result:
422                         quitMainloop(*result)
423                         return
424         
425                 screen = screensToRun[0]
426                 
427                 if len(screensToRun):
428                         session.openWithCallback(boundFunction(runNextScreen, session, screensToRun[1:]), screen)
429                 else:
430                         session.open(screen)
431         
432         runNextScreen(session, screensToRun)
433         
434         CONNECT(keyPressedSignal(), session.keyEvent)
435         
436         vol = VolumeControl(session)
437         power = PowerKey(session)
438         
439         runReactor()
440         
441         configfile.save()
442         
443         from Tools.DreamboxHardware import setFPWakeuptime
444         from time import time
445         nextRecordingTime = session.nav.RecordTimer.getNextRecordingTime()
446         if nextRecordingTime != -1:
447                 if (nextRecordingTime - time() < 330): # no time to switch box back on
448                         setFPWakeuptime(time() + 30) # so switch back on in 30 seconds
449                 else:
450                         setFPWakeuptime(nextRecordingTime - (300))
451         
452         session.nav.shutdown()
453         
454         return 0
455
456 import keymapparser
457 keymapparser.readKeymap()
458 import skin
459 skin.loadSkinData(getDesktop(0))
460
461 import Components.InputDevice
462 Components.InputDevice.InitInputDevices()
463
464 import Components.AVSwitch
465 Components.AVSwitch.InitAVSwitch()
466
467 import Components.RecordingConfig
468 Components.RecordingConfig.InitRecordingConfig()
469
470 import Components.UsageConfig
471 Components.UsageConfig.InitUsageConfig()
472
473 import Components.Network
474 Components.Network.InitNetwork()
475
476 import Components.Lcd
477 Components.Lcd.InitLcd()
478
479 import Components.SetupDevices
480 Components.SetupDevices.InitSetupDevices()
481
482 import Components.RFmod
483 Components.RFmod.InitRFmod()
484
485 import Components.NimManager
486
487 # first, setup a screen
488 try:
489         runScreenTest()
490
491         plugins.shutdown()
492 except:
493         print 'EXCEPTION IN PYTHON STARTUP CODE:'
494         print '-'*60
495         traceback.print_exc(file=sys.stdout)
496         quitMainloop(5)
497         print '-'*60