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