fix crash (since audioselection) on playing audio only files
[enigma2.git] / mytest.py
1 import eBaseImpl
2 import enigma
3 enigma.eTimer = eBaseImpl.eTimer
4 enigma.eSocketNotifier = eBaseImpl.eSocketNotifier
5
6 from Tools.Profile import profile, profile_final
7
8 profile("PYTHON_START")
9
10 from enigma import runMainloop, eDVBDB, eTimer, quitMainloop, \
11         getDesktop, ePythonConfigQuery, eAVSwitch, eServiceEvent
12 from tools import *
13
14 profile("LANGUAGE")
15
16 from Components.Language import language
17
18 def setEPGLanguage():
19         print "language set to", language.getLanguage()
20         eServiceEvent.setEPGLanguage(language.getLanguage())
21
22 language.addCallback(setEPGLanguage)
23
24 from traceback import print_exc
25 profile("LOAD:InfoBar")
26 import Screens.InfoBar
27 from Screens.SimpleSummary import SimpleSummary
28
29 from sys import stdout, exc_info
30
31 profile("ParentalControl")
32 from Components.ParentalControl import InitParentalControl
33 InitParentalControl()
34
35 profile("LOAD:Navigation")
36 from Navigation import Navigation
37
38 profile("LOAD:skin")
39 from skin import readSkin
40
41 profile("LOAD:Tools")
42 from Tools.Directories import InitFallbackFiles, resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE
43 from Components.config import config, configfile, ConfigText
44 InitFallbackFiles()
45
46 profile("ReloadProfiles")
47 eDVBDB.getInstance().reloadBouquets()
48
49 config.misc.radiopic = ConfigText(default = resolveFilename(SCOPE_SKIN_IMAGE)+"radio.mvi")
50
51 profile("Twisted")
52 try:
53         import twisted.python.runtime
54         twisted.python.runtime.platform.supportsThreads = lambda: False
55
56         import e2reactor
57         e2reactor.install()
58
59         from twisted.internet import reactor
60
61         def runReactor():
62                 reactor.run()
63 except ImportError:
64         print "twisted not available"
65         def runReactor():
66                 runMainloop()
67
68 profile("LOAD:Plugin")
69
70 # initialize autorun plugins and plugin menu entries
71 from Components.PluginComponent import plugins
72
73 profile("LOAD:Wizard")
74 from Screens.Wizard import wizardManager
75 from Screens.DefaultWizard import *
76 from Screens.ImageWizard import *
77 from Screens.StartWizard import *
78 from Screens.TutorialWizard import *
79 import Screens.Rc
80 from Tools.BoundFunction import boundFunction
81 from Plugins.Plugin import PluginDescriptor
82
83 profile("misc")
84 had = dict()
85
86 def dump(dir, p = ""):
87         if isinstance(dir, dict):
88                 for (entry, val) in dir.items():
89                         dump(val, p + "(dict)/" + entry)
90         if hasattr(dir, "__dict__"):
91                 for name, value in dir.__dict__.items():
92                         if not had.has_key(str(value)):
93                                 had[str(value)] = 1
94                                 dump(value, p + "/" + str(name))
95                         else:
96                                 print p + "/" + str(name) + ":" + str(dir.__class__) + "(cycle)"
97         else:
98                 print p + ":" + str(dir)
99
100 # + ":" + str(dir.__class__)
101
102 # display
103
104 profile("LOAD:ScreenGlobals")
105 from Screens.Globals import Globals
106 from Screens.SessionGlobals import SessionGlobals
107 from Screens.Screen import Screen
108
109 profile("Screen")
110 Screen.global_screen = Globals()
111
112 # Session.open:
113 # * push current active dialog ('current_dialog') onto stack
114 # * call execEnd for this dialog
115 #   * clear in_exec flag
116 #   * hide screen
117 # * instantiate new dialog into 'current_dialog'
118 #   * create screens, components
119 #   * read, apply skin
120 #   * create GUI for screen
121 # * call execBegin for new dialog
122 #   * set in_exec
123 #   * show gui screen
124 #   * call components' / screen's onExecBegin
125 # ... screen is active, until it calls 'close'...
126 # Session.close:
127 # * assert in_exec
128 # * save return value
129 # * start deferred close handler ('onClose')
130 # * execEnd
131 #   * clear in_exec
132 #   * hide screen
133 # .. a moment later:
134 # Session.doClose:
135 # * destroy screen
136
137 class Session:
138         def __init__(self, desktop = None, summary_desktop = None, navigation = None):
139                 self.desktop = desktop
140                 self.summary_desktop = summary_desktop
141                 self.nav = navigation
142                 self.delay_timer = eTimer()
143                 self.delay_timer.callback.append(self.processDelay)
144
145                 self.current_dialog = None
146
147                 self.dialog_stack = [ ]
148                 self.summary_stack = [ ]
149                 self.summary = None
150
151                 self.in_exec = False
152
153                 self.screen = SessionGlobals(self)
154
155                 for p in plugins.getPlugins(PluginDescriptor.WHERE_SESSIONSTART):
156                         p(reason=0, session=self)
157
158         def processDelay(self):
159                 callback = self.current_dialog.callback
160
161                 retval = self.current_dialog.returnValue
162
163                 if self.current_dialog.isTmp:
164                         self.current_dialog.doClose()
165 #                       dump(self.current_dialog)
166                         del self.current_dialog
167                 else:
168                         del self.current_dialog.callback
169
170                 self.popCurrent()
171                 if callback is not None:
172                         callback(*retval)
173
174         def execBegin(self, first=True, do_show = True):
175                 assert not self.in_exec 
176                 self.in_exec = True
177                 c = self.current_dialog
178
179                 # when this is an execbegin after a execend of a "higher" dialog,
180                 # popSummary already did the right thing.
181                 if first:
182                         self.pushSummary()
183                         summary = c.createSummary() or SimpleSummary
184                         self.summary = self.instantiateSummaryDialog(summary, c)
185                         self.summary.show()
186                         c.addSummary(self.summary)
187
188                 c.execBegin()
189
190                 # when execBegin opened a new dialog, don't bother showing the old one.
191                 if c == self.current_dialog and do_show:
192                         c.show()
193
194         def execEnd(self, last=True):
195                 assert self.in_exec
196                 self.in_exec = False
197
198                 self.current_dialog.execEnd()
199                 self.current_dialog.hide()
200
201                 if last:
202                         self.current_dialog.removeSummary(self.summary)
203                         self.popSummary()
204
205         def create(self, screen, arguments, **kwargs):
206                 # creates an instance of 'screen' (which is a class)
207                 try:
208                         return screen(self, *arguments, **kwargs)
209                 except:
210                         errstr = "Screen %s(%s, %s): %s" % (str(screen), str(arguments), str(kwargs), exc_info()[0])
211                         print errstr
212                         print_exc(file=stdout)
213                         quitMainloop(5)
214
215         def instantiateDialog(self, screen, *arguments, **kwargs):
216                 return self.doInstantiateDialog(screen, arguments, kwargs, self.desktop)
217
218         def deleteDialog(self, screen):
219                 screen.hide()
220                 screen.doClose()
221
222         def instantiateSummaryDialog(self, screen, *arguments, **kwargs):
223                 return self.doInstantiateDialog(screen, arguments, kwargs, self.summary_desktop)
224
225         def doInstantiateDialog(self, screen, arguments, kwargs, desktop):
226                 # create dialog
227
228                 try:
229                         dlg = self.create(screen, arguments, **kwargs)
230                 except:
231                         print 'EXCEPTION IN DIALOG INIT CODE, ABORTING:'
232                         print '-'*60
233                         print_exc(file=stdout)
234                         quitMainloop(5)
235                         print '-'*60
236
237                 if dlg is None:
238                         return
239
240                 # read skin data
241                 readSkin(dlg, None, dlg.skinName, desktop)
242
243                 # create GUI view of this dialog
244                 assert desktop is not None
245
246                 dlg.setDesktop(desktop)
247                 dlg.applySkin()
248
249                 return dlg
250
251         def pushCurrent(self):
252                 if self.current_dialog is not None:
253                         self.dialog_stack.append((self.current_dialog, self.current_dialog.shown))
254                         self.execEnd(last=False)
255
256         def popCurrent(self):
257                 if len(self.dialog_stack):
258                         (self.current_dialog, do_show) = self.dialog_stack.pop()
259                         self.execBegin(first=False, do_show=do_show)
260                 else:
261                         self.current_dialog = None
262
263         def execDialog(self, dialog):
264                 self.pushCurrent()
265                 self.current_dialog = dialog
266                 self.current_dialog.isTmp = False
267                 self.current_dialog.callback = None # would cause re-entrancy problems.
268                 self.execBegin()
269
270         def openWithCallback(self, callback, screen, *arguments, **kwargs):
271                 dlg = self.open(screen, *arguments, **kwargs)
272                 dlg.callback = callback
273                 return dlg
274
275         def open(self, screen, *arguments, **kwargs):
276                 if len(self.dialog_stack) and not self.in_exec:
277                         raise "modal open are allowed only from a screen which is modal!"
278                         # ...unless it's the very first screen.
279
280                 self.pushCurrent()
281                 dlg = self.current_dialog = self.instantiateDialog(screen, *arguments, **kwargs)
282                 dlg.isTmp = True
283                 dlg.callback = None
284                 self.execBegin()
285                 return dlg
286
287         def close(self, screen, *retval):
288                 if not self.in_exec:
289                         print "close after exec!"
290                         return
291
292                 # be sure that the close is for the right dialog!
293                 # if it's not, you probably closed after another dialog
294                 # was opened. this can happen if you open a dialog
295                 # onExecBegin, and forget to do this only once.
296                 # after close of the top dialog, the underlying will
297                 # gain focus again (for a short time), thus triggering
298                 # the onExec, which opens the dialog again, closing the loop.
299                 assert screen == self.current_dialog
300
301                 self.current_dialog.returnValue = retval
302                 self.delay_timer.start(0, 1)
303                 self.execEnd()
304
305         def pushSummary(self):
306                 if self.summary is not None:
307                         self.summary.hide()
308                 self.summary_stack.append(self.summary)
309                 self.summary = None
310
311         def popSummary(self):
312                 if self.summary is not None:
313                         self.summary.doClose()
314                 self.summary = self.summary_stack.pop()
315                 if self.summary is not None:
316                         self.summary.show()
317
318 profile("Standby,PowerKey")
319 import Screens.Standby
320 from Screens.Menu import MainMenu, mdom
321 import xml.dom.minidom
322 from GlobalActions import globalActionMap
323
324 class PowerKey:
325         """ PowerKey stuff - handles the powerkey press and powerkey release actions"""
326
327         def __init__(self, session):
328                 self.session = session
329                 globalActionMap.actions["power_down"]=self.powerdown
330                 globalActionMap.actions["power_up"]=self.powerup
331                 globalActionMap.actions["power_long"]=self.powerlong
332                 globalActionMap.actions["deepstandby"]=self.shutdown # frontpanel long power button press
333                 self.standbyblocked = 1
334
335         def MenuClosed(self, *val):
336                 self.session.infobar = None
337
338         def shutdown(self):
339                 print "PowerOff - Now!"
340                 if not Screens.Standby.inTryQuitMainloop and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND:
341                         self.session.open(Screens.Standby.TryQuitMainloop, 1)
342
343         def powerlong(self):
344                 self.standbyblocked = 1
345                 action = config.usage.on_long_powerpress.value
346                 if action == "shutdown":
347                         self.shutdown()
348                 elif action == "show_menu":
349                         print "Show shutdown Menu"
350                         menu = mdom.childNodes[0]
351                         for x in menu.childNodes:
352                                 if x.nodeType != xml.dom.minidom.Element.nodeType:
353                                     continue
354                                 elif x.tagName == 'menu':
355                                         for y in x.childNodes:
356                                                 if y.nodeType != xml.dom.minidom.Element.nodeType:
357                                                         continue
358                                                 elif y.tagName == 'id':
359                                                         id = y.getAttribute("val")
360                                                         if id and id == "shutdown":
361                                                                 self.session.infobar = self
362                                                                 menu_screen = self.session.openWithCallback(self.MenuClosed, MainMenu, x, x.childNodes)
363                                                                 menu_screen.setTitle(_("Standby / Restart"))
364                                                                 return
365
366         def powerdown(self):
367                 self.standbyblocked = 0
368
369         def powerup(self):
370                 if self.standbyblocked == 0:
371                         self.standbyblocked = 1
372                         self.standby()
373
374         def standby(self):
375                 if not Screens.Standby.inStandby and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND:
376                         self.session.open(Screens.Standby.Standby)
377
378 profile("Scart")
379 from Screens.Scart import Scart
380
381 class AutoScartControl:
382         def __init__(self, session):
383                 self.force = False
384                 self.current_vcr_sb = eAVSwitch.getInstance().getVCRSlowBlanking()
385                 if self.current_vcr_sb and config.av.vcrswitch.value:
386                         self.scartDialog = session.instantiateDialog(Scart, True)
387                 else:
388                         self.scartDialog = session.instantiateDialog(Scart, False)
389                 config.av.vcrswitch.addNotifier(self.recheckVCRSb)
390                 eAVSwitch.getInstance().vcr_sb_notifier.get().append(self.VCRSbChanged)
391
392         def recheckVCRSb(self, configElement):
393                 self.VCRSbChanged(self.current_vcr_sb)
394
395         def VCRSbChanged(self, value):
396                 #print "vcr sb changed to", value
397                 self.current_vcr_sb = value
398                 if config.av.vcrswitch.value or value > 2:
399                         if value:
400                                 self.scartDialog.showMessageBox()
401                         else:
402                                 self.scartDialog.switchToTV()
403
404 profile("Load:CI")
405 from enigma import eDVBCIInterfaces
406 from Screens.Ci import CiHandler
407
408 profile("Load:VolumeControl")
409 from Components.VolumeControl import VolumeControl
410
411 def runScreenTest():
412         profile("readPluginList")
413         plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
414
415         profile("Init:Session")
416         session = Session(desktop = getDesktop(0), summary_desktop = getDesktop(1), navigation = Navigation())
417
418         CiHandler.setSession(session)
419
420         screensToRun = [ ]
421
422         for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD):
423                 screensToRun.append(p.__call__)
424
425         profile("wizards")
426         screensToRun += wizardManager.getWizards()
427
428         screensToRun.append((100, Screens.InfoBar.InfoBar))
429
430         screensToRun.sort()
431
432         ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)
433
434 #       eDVBCIInterfaces.getInstance().setDescrambleRules(0 # Slot Number
435 #               ,(      ["1:0:1:24:4:85:C00000:0:0:0:"], #service_list
436 #                       ["PREMIERE"], #provider_list,
437 #                       [] #caid_list
438 #               ));
439
440         def runNextScreen(session, screensToRun, *result):
441                 if result:
442                         quitMainloop(*result)
443                         return
444
445                 screen = screensToRun[0][1]
446
447                 if len(screensToRun):
448                         session.openWithCallback(boundFunction(runNextScreen, session, screensToRun[1:]), screen)
449                 else:
450                         session.open(screen)
451
452         runNextScreen(session, screensToRun)
453
454         profile("Init:VolumeControl")
455         vol = VolumeControl(session)
456         profile("Init:PowerKey")
457         power = PowerKey(session)
458
459         # we need session.scart to access it from within menu.xml
460         session.scart = AutoScartControl(session)
461
462         profile("RunReactor")
463         profile_final()
464         runReactor()
465         profile("configfile.save")
466         configfile.save()
467
468         profile("wakeup")
469         from time import time
470         from Tools.DreamboxHardware import setFPWakeuptime, getFPWakeuptime
471         #get currentTime
472         nowTime = time()
473         wakeupList = [
474                 x for x in
475                                 [session.nav.RecordTimer.getNextRecordingTime(),
476                                 session.nav.RecordTimer.getNextZapTime(),
477                                 plugins.getNextWakeupTime()]
478                 if x != -1
479         ]
480         wakeupList.sort()
481         if len(wakeupList):
482                 startTime = wakeupList.pop(0)
483                 if (startTime - nowTime) < 330: # no time to switch box back on
484                         wptime = nowTime + 30  # so switch back on in 30 seconds
485                 else:
486                         wptime = startTime - 300
487                 setFPWakeuptime(wptime)
488         profile("stopService")
489         session.nav.stopService()
490         profile("nav shutdown")
491         session.nav.shutdown()
492
493         return 0
494
495 profile("Init:skin")
496 import skin
497 skin.loadSkinData(getDesktop(0))
498
499 profile("InputDevice")
500 import Components.InputDevice
501 Components.InputDevice.InitInputDevices()
502
503 profile("AVSwitch")
504 import Components.AVSwitch
505 Components.AVSwitch.InitAVSwitch()
506
507 profile("RecordingConfig")
508 import Components.RecordingConfig
509 Components.RecordingConfig.InitRecordingConfig()
510
511 profile("UsageConfig")
512 import Components.UsageConfig
513 Components.UsageConfig.InitUsageConfig()
514
515 profile("keymapparser")
516 import keymapparser
517 keymapparser.readKeymap(config.usage.keymap.value)
518
519 profile("Network")
520 import Components.Network
521 Components.Network.InitNetwork()
522
523 profile("LCD")
524 import Components.Lcd
525 Components.Lcd.InitLcd()
526
527 profile("SetupDevices")
528 import Components.SetupDevices
529 Components.SetupDevices.InitSetupDevices()
530
531 profile("RFMod")
532 import Components.RFmod
533 Components.RFmod.InitRFmod()
534
535 profile("Init:CI")
536 import Screens.Ci
537 Screens.Ci.InitCiConfig()
538
539 #from enigma import dump_malloc_stats
540 #t = eTimer()
541 #t.callback.append(dump_malloc_stats)
542 #t.start(1000)
543
544 # first, setup a screen
545 try:
546         runScreenTest()
547
548         plugins.shutdown()
549
550         from Components.ParentalControl import parentalControl
551         parentalControl.save()
552 except:
553         print 'EXCEPTION IN PYTHON STARTUP CODE:'
554         print '-'*60
555         print_exc(file=stdout)
556         quitMainloop(5)
557         print '-'*60