call loadBouquet after installing a bouquet
[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, eDVBVolumecontrol, \
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, applyAllAttributes
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, ConfigSubsection, ConfigInteger
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.ImageWizard import *
76 from Screens.StartWizard import *
77 from Screens.DefaultWizard import *
78 from Screens.TutorialWizard import *
79 from Tools.BoundFunction import boundFunction
80 from Plugins.Plugin import PluginDescriptor
81
82 profile("misc")
83 had = dict()
84
85 def dump(dir, p = ""):
86         if isinstance(dir, dict):
87                 for (entry, val) in dir.items():
88                         dump(val, p + "(dict)/" + entry)
89         if hasattr(dir, "__dict__"):
90                 for name, value in dir.__dict__.items():
91                         if not had.has_key(str(value)):
92                                 had[str(value)] = 1
93                                 dump(value, p + "/" + str(name))
94                         else:
95                                 print p + "/" + str(name) + ":" + str(dir.__class__) + "(cycle)"
96         else:
97                 print p + ":" + str(dir)
98
99 # + ":" + str(dir.__class__)
100
101 # display
102
103 profile("LOAD:ScreenGlobals")
104 from Screens.Globals import Globals
105 from Screens.SessionGlobals import SessionGlobals
106 from Screens.Screen import Screen
107
108 profile("Screen")
109 Screen.global_screen = Globals()
110
111 # Session.open:
112 # * push current active dialog ('current_dialog') onto stack
113 # * call execEnd for this dialog
114 #   * clear in_exec flag
115 #   * hide screen
116 # * instantiate new dialog into 'current_dialog'
117 #   * create screens, components
118 #   * read, apply skin
119 #   * create GUI for screen
120 # * call execBegin for new dialog
121 #   * set in_exec
122 #   * show gui screen
123 #   * call components' / screen's onExecBegin
124 # ... screen is active, until it calls 'close'...
125 # Session.close:
126 # * assert in_exec
127 # * save return value
128 # * start deferred close handler ('onClose')
129 # * execEnd
130 #   * clear in_exec
131 #   * hide screen
132 # .. a moment later:
133 # Session.doClose:
134 # * destroy screen
135
136 class Session:
137         def __init__(self, desktop = None, summary_desktop = None, navigation = None):
138                 self.desktop = desktop
139                 self.summary_desktop = summary_desktop
140                 self.nav = navigation
141                 self.delay_timer = eTimer()
142                 self.delay_timer.callback.append(self.processDelay)
143
144                 self.current_dialog = None
145
146                 self.dialog_stack = [ ]
147                 self.summary_stack = [ ]
148                 self.summary = None
149
150                 self.in_exec = False
151
152                 self.screen = SessionGlobals(self)
153
154                 for p in plugins.getPlugins(PluginDescriptor.WHERE_SESSIONSTART):
155                         p(reason=0, session=self)
156
157         def processDelay(self):
158                 callback = self.current_dialog.callback
159
160                 retval = self.current_dialog.returnValue
161
162                 if self.current_dialog.isTmp:
163                         self.current_dialog.doClose()
164 #                       dump(self.current_dialog)
165                         del self.current_dialog
166                 else:
167                         del self.current_dialog.callback
168
169                 self.popCurrent()
170                 if callback is not None:
171                         callback(*retval)
172
173         def execBegin(self, first=True, do_show = True):
174                 assert not self.in_exec 
175                 self.in_exec = True
176                 c = self.current_dialog
177
178                 # when this is an execbegin after a execend of a "higher" dialog,
179                 # popSummary already did the right thing.
180                 if first:
181                         self.pushSummary()
182                         summary = c.createSummary() or SimpleSummary
183                         self.summary = self.instantiateSummaryDialog(summary, c)
184                         self.summary.show()
185                         c.addSummary(self.summary)
186
187                 c.execBegin()
188
189                 # when execBegin opened a new dialog, don't bother showing the old one.
190                 if c == self.current_dialog and do_show:
191                         c.show()
192
193         def execEnd(self, last=True):
194                 assert self.in_exec
195                 self.in_exec = False
196
197                 self.current_dialog.execEnd()
198                 self.current_dialog.hide()
199
200                 if last:
201                         self.current_dialog.removeSummary(self.summary)
202                         self.popSummary()
203
204         def create(self, screen, arguments, **kwargs):
205                 # creates an instance of 'screen' (which is a class)
206                 try:
207                         return screen(self, *arguments, **kwargs)
208                 except:
209                         errstr = "Screen %s(%s, %s): %s" % (str(screen), str(arguments), str(kwargs), exc_info()[0])
210                         print errstr
211                         print_exc(file=stdout)
212                         quitMainloop(5)
213
214         def instantiateDialog(self, screen, *arguments, **kwargs):
215                 return self.doInstantiateDialog(screen, arguments, kwargs, self.desktop)
216
217         def deleteDialog(self, screen):
218                 screen.hide()
219                 screen.doClose()
220
221         def instantiateSummaryDialog(self, screen, *arguments, **kwargs):
222                 return self.doInstantiateDialog(screen, arguments, kwargs, self.summary_desktop)
223
224         def doInstantiateDialog(self, screen, arguments, kwargs, desktop):
225                 # create dialog
226
227                 try:
228                         dlg = self.create(screen, arguments, **kwargs)
229                 except:
230                         print 'EXCEPTION IN DIALOG INIT CODE, ABORTING:'
231                         print '-'*60
232                         print_exc(file=stdout)
233                         quitMainloop(5)
234                         print '-'*60
235
236                 if dlg is None:
237                         return
238
239                 # read skin data
240                 readSkin(dlg, None, dlg.skinName, desktop)
241
242                 # create GUI view of this dialog
243                 assert desktop is not None
244
245                 dlg.setDesktop(desktop)
246                 dlg.applySkin()
247
248                 return dlg
249
250         def pushCurrent(self):
251                 if self.current_dialog is not None:
252                         self.dialog_stack.append((self.current_dialog, self.current_dialog.shown))
253                         self.execEnd(last=False)
254
255         def popCurrent(self):
256                 if len(self.dialog_stack):
257                         (self.current_dialog, do_show) = self.dialog_stack.pop()
258                         self.execBegin(first=False, do_show=do_show)
259                 else:
260                         self.current_dialog = None
261
262         def execDialog(self, dialog):
263                 self.pushCurrent()
264                 self.current_dialog = dialog
265                 self.current_dialog.isTmp = False
266                 self.current_dialog.callback = None # would cause re-entrancy problems.
267                 self.execBegin()
268
269         def openWithCallback(self, callback, screen, *arguments, **kwargs):
270                 dlg = self.open(screen, *arguments, **kwargs)
271                 dlg.callback = callback
272                 return dlg
273
274         def open(self, screen, *arguments, **kwargs):
275                 if len(self.dialog_stack) and not self.in_exec:
276                         raise "modal open are allowed only from a screen which is modal!"
277                         # ...unless it's the very first screen.
278
279                 self.pushCurrent()
280                 dlg = self.current_dialog = self.instantiateDialog(screen, *arguments, **kwargs)
281                 dlg.isTmp = True
282                 dlg.callback = None
283                 self.execBegin()
284                 return dlg
285
286         def close(self, screen, *retval):
287                 if not self.in_exec:
288                         print "close after exec!"
289                         return
290
291                 # be sure that the close is for the right dialog!
292                 # if it's not, you probably closed after another dialog
293                 # was opened. this can happen if you open a dialog
294                 # onExecBegin, and forget to do this only once.
295                 # after close of the top dialog, the underlying will
296                 # gain focus again (for a short time), thus triggering
297                 # the onExec, which opens the dialog again, closing the loop.
298                 assert screen == self.current_dialog
299
300                 self.current_dialog.returnValue = retval
301                 self.delay_timer.start(0, 1)
302                 self.execEnd()
303
304         def pushSummary(self):
305                 if self.summary is not None:
306                         self.summary.hide()
307                 self.summary_stack.append(self.summary)
308                 self.summary = None
309
310         def popSummary(self):
311                 if self.summary is not None:
312                         self.summary.doClose()
313                 self.summary = self.summary_stack.pop()
314                 if self.summary is not None:
315                         self.summary.show()
316
317 from Screens.Volume import Volume
318 from Screens.Mute import Mute
319 from GlobalActions import globalActionMap
320
321 profile("VolumeControl")
322 #TODO .. move this to a own .py file
323 class VolumeControl:
324         """Volume control, handles volUp, volDown, volMute actions and display
325         a corresponding dialog"""
326         def __init__(self, session):
327                 global globalActionMap
328                 globalActionMap.actions["volumeUp"]=self.volUp
329                 globalActionMap.actions["volumeDown"]=self.volDown
330                 globalActionMap.actions["volumeMute"]=self.volMute
331
332                 config.audio = ConfigSubsection()
333                 config.audio.volume = ConfigInteger(default = 100, limits = (0, 100))
334
335                 self.volumeDialog = session.instantiateDialog(Volume)
336                 self.muteDialog = session.instantiateDialog(Mute)
337
338                 self.hideVolTimer = eTimer()
339                 self.hideVolTimer.callback.append(self.volHide)
340
341                 vol = config.audio.volume.value
342                 self.volumeDialog.setValue(vol)
343                 self.volctrl = eDVBVolumecontrol.getInstance()
344                 self.volctrl.setVolume(vol, vol)
345
346         def volSave(self):
347                 if self.volctrl.isMuted():
348                         config.audio.volume.value = 0
349                 else:
350                         config.audio.volume.value = self.volctrl.getVolume()
351                 config.audio.volume.save()
352
353         def volUp(self):
354                 self.setVolume(+1)
355
356         def volDown(self):
357                 self.setVolume(-1)
358
359         def setVolume(self, direction):
360                 oldvol = self.volctrl.getVolume()
361                 if direction > 0:
362                         self.volctrl.volumeUp()
363                 else:
364                         self.volctrl.volumeDown()
365                 is_muted = self.volctrl.isMuted()
366                 vol = self.volctrl.getVolume()
367                 self.volumeDialog.show()
368                 if is_muted:
369                         self.volMute() # unmute
370                 elif not vol:
371                         self.volMute(False, True) # mute but dont show mute symbol
372                 if self.volctrl.isMuted():
373                         self.volumeDialog.setValue(0)
374                 else:
375                         self.volumeDialog.setValue(self.volctrl.getVolume())
376                 self.volSave()
377                 self.hideVolTimer.start(3000, True)
378
379         def volHide(self):
380                 self.volumeDialog.hide()
381
382         def volMute(self, showMuteSymbol=True, force=False):
383                 vol = self.volctrl.getVolume()
384                 if vol or force:
385                         self.volctrl.volumeToggleMute()
386                         if self.volctrl.isMuted():
387                                 if showMuteSymbol:
388                                         self.muteDialog.show()
389                                 self.volumeDialog.setValue(0)
390                         else:
391                                 self.muteDialog.hide()
392                                 self.volumeDialog.setValue(vol)
393
394 profile("Standby,PowerKey")
395 import Screens.Standby
396 from Screens.Menu import MainMenu, mdom
397 import xml.dom.minidom
398
399 class PowerKey:
400         """ PowerKey stuff - handles the powerkey press and powerkey release actions"""
401
402         def __init__(self, session):
403                 self.session = session
404                 globalActionMap.actions["power_down"]=self.powerdown
405                 globalActionMap.actions["power_up"]=self.powerup
406                 globalActionMap.actions["power_long"]=self.powerlong
407                 globalActionMap.actions["deepstandby"]=self.shutdown # frontpanel long power button press
408                 self.standbyblocked = 1
409
410         def MenuClosed(self, *val):
411                 self.session.infobar = None
412
413         def shutdown(self):
414                 print "PowerOff - Now!"
415                 if not Screens.Standby.inTryQuitMainloop and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND:
416                         self.session.open(Screens.Standby.TryQuitMainloop, 1)
417
418         def powerlong(self):
419                 self.standbyblocked = 1
420                 action = config.usage.on_long_powerpress.value
421                 if action == "shutdown":
422                         self.shutdown()
423                 elif action == "show_menu":
424                         print "Show shutdown Menu"
425                         menu = mdom.childNodes[0]
426                         for x in menu.childNodes:
427                                 if x.nodeType != xml.dom.minidom.Element.nodeType:
428                                     continue
429                                 elif x.tagName == 'menu':
430                                         for y in x.childNodes:
431                                                 if y.nodeType != xml.dom.minidom.Element.nodeType:
432                                                         continue
433                                                 elif y.tagName == 'id':
434                                                         id = y.getAttribute("val")
435                                                         if id and id == "shutdown":
436                                                                 self.session.infobar = self
437                                                                 menu_screen = self.session.openWithCallback(self.MenuClosed, MainMenu, x, x.childNodes)
438                                                                 menu_screen.setTitle(_("Standby / Restart"))
439                                                                 return
440
441         def powerdown(self):
442                 self.standbyblocked = 0
443
444         def powerup(self):
445                 if self.standbyblocked == 0:
446                         self.standbyblocked = 1
447                         self.standby()
448
449         def standby(self):
450                 if not Screens.Standby.inStandby and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND:
451                         self.session.open(Screens.Standby.Standby)
452
453 profile("Scart")
454 from Screens.Scart import Scart
455
456 class AutoScartControl:
457         def __init__(self, session):
458                 self.force = False
459                 self.current_vcr_sb = eAVSwitch.getInstance().getVCRSlowBlanking()
460                 if self.current_vcr_sb and config.av.vcrswitch.value:
461                         self.scartDialog = session.instantiateDialog(Scart, True)
462                 else:
463                         self.scartDialog = session.instantiateDialog(Scart, False)
464                 config.av.vcrswitch.addNotifier(self.recheckVCRSb)
465                 eAVSwitch.getInstance().vcr_sb_notifier.get().append(self.VCRSbChanged)
466
467         def recheckVCRSb(self, configElement):
468                 self.VCRSbChanged(self.current_vcr_sb)
469
470         def VCRSbChanged(self, value):
471                 #print "vcr sb changed to", value
472                 self.current_vcr_sb = value
473                 if config.av.vcrswitch.value or value > 2:
474                         if value:
475                                 self.scartDialog.showMessageBox()
476                         else:
477                                 self.scartDialog.switchToTV()
478
479 profile("Load:CI")
480 from enigma import eDVBCIInterfaces
481 from Screens.Ci import CiHandler
482
483 def runScreenTest():
484         profile("readPluginList")
485         plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
486
487         profile("Init:Session")
488         session = Session(desktop = getDesktop(0), summary_desktop = getDesktop(1), navigation = Navigation())
489
490         CiHandler.setSession(session)
491
492         screensToRun = [ ]
493
494         for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD):
495                 screensToRun.append(p.__call__)
496
497         profile("wizards")
498         screensToRun += wizardManager.getWizards()
499
500         screensToRun.append((100, Screens.InfoBar.InfoBar))
501
502         screensToRun.sort()
503
504         ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)
505
506 #       eDVBCIInterfaces.getInstance().setDescrambleRules(0 # Slot Number
507 #               ,(      ["1:0:1:24:4:85:C00000:0:0:0:"], #service_list
508 #                       ["PREMIERE"], #provider_list,
509 #                       [] #caid_list
510 #               ));
511
512         def runNextScreen(session, screensToRun, *result):
513                 if result:
514                         quitMainloop(*result)
515                         return
516
517                 screen = screensToRun[0][1]
518
519                 if len(screensToRun):
520                         session.openWithCallback(boundFunction(runNextScreen, session, screensToRun[1:]), screen)
521                 else:
522                         session.open(screen)
523
524         runNextScreen(session, screensToRun)
525
526         profile("Init:VolumeControl")
527         vol = VolumeControl(session)
528         profile("Init:PowerKey")
529         power = PowerKey(session)
530
531         # we need session.scart to access it from within menu.xml
532         session.scart = AutoScartControl(session)
533
534         profile("RunReactor")
535         profile_final()
536         runReactor()
537         profile("configfile.save")
538         configfile.save()
539
540         profile("wakeup")
541         from time import time
542         from Tools.DreamboxHardware import setFPWakeuptime
543         #get currentTime
544         nowTime = time()
545         wakeupList = [
546                 x for x in
547                                 [session.nav.RecordTimer.getNextRecordingTime(),
548                                 session.nav.RecordTimer.getNextZapTime(),
549                                 plugins.getNextWakeupTime()]
550                 if x != -1
551         ]
552         wakeupList.sort()
553         if len(wakeupList):
554                 startTime = wakeupList.pop(0)
555                 if (startTime - nowTime < 330): # no time to switch box back on
556                         setFPWakeuptime(nowTime + 30) # so switch back on in 30 seconds
557                 else:
558                         setFPWakeuptime(startTime - 300)
559         profile("stopService")
560         session.nav.stopService()
561         profile("nav shutdown")
562         session.nav.shutdown()
563
564         return 0
565
566 profile("Init:skin")
567 import skin
568 skin.loadSkinData(getDesktop(0))
569
570 profile("InputDevice")
571 import Components.InputDevice
572 Components.InputDevice.InitInputDevices()
573
574 profile("AVSwitch")
575 import Components.AVSwitch
576 Components.AVSwitch.InitAVSwitch()
577
578 profile("RecordingConfig")
579 import Components.RecordingConfig
580 Components.RecordingConfig.InitRecordingConfig()
581
582 profile("UsageConfig")
583 import Components.UsageConfig
584 Components.UsageConfig.InitUsageConfig()
585
586 profile("keymapparser")
587 import keymapparser
588 keymapparser.readKeymap(config.usage.keymap.value)
589
590 profile("Network")
591 import Components.Network
592 Components.Network.InitNetwork()
593
594 profile("LCD")
595 import Components.Lcd
596 Components.Lcd.InitLcd()
597
598 profile("SetupDevices")
599 import Components.SetupDevices
600 Components.SetupDevices.InitSetupDevices()
601
602 profile("RFMod")
603 import Components.RFmod
604 Components.RFmod.InitRFmod()
605
606 profile("Init:CI")
607 import Screens.Ci
608 Screens.Ci.InitCiConfig()
609
610 #from enigma import dump_malloc_stats
611 #t = eTimer()
612 #t.callback.append(dump_malloc_stats)
613 #t.start(1000)
614
615 # first, setup a screen
616 try:
617         runScreenTest()
618
619         plugins.shutdown()
620
621         from Components.ParentalControl import parentalControl
622         parentalControl.save()
623 except:
624         print 'EXCEPTION IN PYTHON STARTUP CODE:'
625         print '-'*60
626         print_exc(file=stdout)
627         quitMainloop(5)
628         print '-'*60