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