int -> size_t
[enigma2.git] / mytest.py
1 from enigma import runMainloop, eDVBDB, eTimer, quitMainloop, eDVBVolumecontrol, \
2         getDesktop, ePythonConfigQuery, eAVSwitch, eWindow, eServiceEvent
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 from traceback import print_exc
14 import Screens.InfoBar
15 from Screens.SimpleSummary import SimpleSummary
16
17 from sys import stdout, exc_info
18
19 from Components.ParentalControl import InitParentalControl
20 InitParentalControl()
21
22 from Navigation import Navigation
23
24 from skin import readSkin, applyAllAttributes
25
26 from Tools.Directories import InitFallbackFiles, resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE
27 from Components.config import config, configfile, ConfigText, ConfigSubsection, ConfigInteger
28 InitFallbackFiles()
29 eDVBDB.getInstance().reloadBouquets()
30
31 config.misc.radiopic = ConfigText(default = resolveFilename(SCOPE_SKIN_IMAGE)+"radio.mvi")
32
33 try:
34         import e2reactor
35         e2reactor.install()
36
37         import twisted.python.runtime
38         twisted.python.runtime.platform.supportsThreads = lambda: False
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, do_show = 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 and do_show:
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), exc_info()[0])
192                         print errstr
193                         print_exc(file=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                         print_exc(file=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, self.current_dialog.shown))
247                         self.execEnd(last=False)
248
249         def popCurrent(self):
250                 if len(self.dialog_stack):
251                         (self.current_dialog, do_show) = self.dialog_stack.pop()
252                         self.execBegin(first=False, do_show=do_show)
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                 self.volumeDialog.setValue(vol)
336                 self.volctrl = eDVBVolumecontrol.getInstance()
337                 self.volctrl.setVolume(vol, vol)
338
339         def volSave(self):
340                 if self.volctrl.isMuted():
341                         config.audio.volume.value = 0
342                 else:
343                         config.audio.volume.value = self.volctrl.getVolume()
344                 config.audio.volume.save()
345
346         def volUp(self):
347                 self.setVolume(+1)
348
349         def volDown(self):
350                 self.setVolume(-1)
351
352         def setVolume(self, direction):
353                 oldvol = self.volctrl.getVolume()
354                 if direction > 0:
355                         self.volctrl.volumeUp()
356                 else:
357                         self.volctrl.volumeDown()
358                 is_muted = self.volctrl.isMuted()
359                 vol = self.volctrl.getVolume()
360                 self.volumeDialog.show()
361                 if is_muted:
362                         self.volMute() # unmute
363                 elif not vol:
364                         self.volMute(False, True) # mute but dont show mute symbol
365                 if self.volctrl.isMuted():
366                         self.volumeDialog.setValue(0)
367                 else:
368                         self.volumeDialog.setValue(self.volctrl.getVolume())
369                 self.volSave()
370                 self.hideVolTimer.start(3000, True)
371
372         def volHide(self):
373                 self.volumeDialog.hide()
374
375         def volMute(self, showMuteSymbol=True, force=False):
376                 vol = self.volctrl.getVolume()
377                 if vol or force:
378                         self.volctrl.volumeToggleMute()
379                         if self.volctrl.isMuted():
380                                 if showMuteSymbol:
381                                         self.muteDialog.show()
382                                 self.volumeDialog.setValue(0)
383                         else:
384                                 self.muteDialog.hide()
385                                 self.volumeDialog.setValue(vol)
386
387 import Screens.Standby
388
389 class PowerKey:
390         """ PowerKey stuff - handles the powerkey press and powerkey release actions"""
391
392         def __init__(self, session):
393                 self.session = session
394                 self.powerKeyTimer = eTimer()
395                 self.powerKeyTimer.timeout.get().append(self.powertimer)
396                 globalActionMap.actions["powerdown"]=self.powerdown
397                 globalActionMap.actions["powerup"]=self.powerup
398                 self.standbyblocked = 1
399 #               self["PowerKeyActions"] = HelpableActionMap(self, "PowerKeyActions",
400                         #{
401                                 #"powerdown": self.powerdown,
402                                 #"powerup": self.powerup,
403                                 #"discreteStandby": (self.standby, "Go standby"),
404                                 #"discretePowerOff": (self.quit, "Go to deep standby"),
405                         #})
406
407         def powertimer(self):
408                 print "PowerOff - Now!"
409                 if not Screens.Standby.inTryQuitMainloop:
410                         self.session.open(Screens.Standby.TryQuitMainloop, 1)
411
412         def powerdown(self):
413                 self.standbyblocked = 0
414                 self.powerKeyTimer.start(3000, True)
415
416         def powerup(self):
417                 self.powerKeyTimer.stop()
418                 if self.standbyblocked == 0:
419                         self.standbyblocked = 1
420                         self.standby()
421
422         def standby(self):
423                 if not Screens.Standby.inStandby and self.session.current_dialog and self.session.current_dialog.ALLOW_SUSPEND:
424                         self.session.open(Screens.Standby.Standby)
425
426 from Screens.Scart import Scart
427
428 class AutoScartControl:
429         def __init__(self, session):
430                 self.force = False
431                 self.current_vcr_sb = eAVSwitch.getInstance().getVCRSlowBlanking()
432                 if self.current_vcr_sb and config.av.vcrswitch.value:
433                         self.scartDialog = session.instantiateDialog(Scart, True)
434                 else:
435                         self.scartDialog = session.instantiateDialog(Scart, False)
436                 config.av.vcrswitch.addNotifier(self.recheckVCRSb)
437                 eAVSwitch.getInstance().vcr_sb_notifier.get().append(self.VCRSbChanged)
438
439         def recheckVCRSb(self, configElement):
440                 self.VCRSbChanged(self.current_vcr_sb)
441
442         def VCRSbChanged(self, value):
443                 #print "vcr sb changed to", value
444                 self.current_vcr_sb = value
445                 if config.av.vcrswitch.value or value > 2:
446                         if value:
447                                 self.scartDialog.showMessageBox()
448                         else:
449                                 self.scartDialog.switchToTV()
450
451 from enigma import eDVBCIInterfaces
452
453 def runScreenTest():
454         plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
455
456         session = Session(desktop = getDesktop(0), summary_desktop = getDesktop(1), navigation = Navigation())
457
458         screensToRun = [ ]
459
460         for p in plugins.getPlugins(PluginDescriptor.WHERE_WIZARD):
461                 screensToRun.append(p.__call__)
462
463         screensToRun += wizardManager.getWizards()
464
465         screensToRun.append(Screens.InfoBar.InfoBar)
466
467         ePythonConfigQuery.setQueryFunc(configfile.getResolvedKey)
468
469 #       eDVBCIInterfaces.getInstance().setDescrambleRules(0 # Slot Number
470 #               ,(      ["1:0:1:24:4:85:C00000:0:0:0:"], #service_list
471 #                       ["PREMIERE"], #provider_list,
472 #                       [] #caid_list
473 #               ));
474
475         def runNextScreen(session, screensToRun, *result):
476                 if result:
477                         quitMainloop(*result)
478                         return
479
480                 screen = screensToRun[0]
481
482                 if len(screensToRun):
483                         session.openWithCallback(boundFunction(runNextScreen, session, screensToRun[1:]), screen)
484                 else:
485                         session.open(screen)
486
487         runNextScreen(session, screensToRun)
488
489         vol = VolumeControl(session)
490         power = PowerKey(session)
491
492         # we need session.scart to access it from within menu.xml
493         session.scart = AutoScartControl(session)
494
495         runReactor()
496
497         configfile.save()
498
499         from time import time
500         from Tools.DreamboxHardware import setFPWakeuptime
501         #get next record timer start time
502         nextRecordingTime = session.nav.RecordTimer.getNextRecordingTime()
503         #get next zap timer start time
504         nextZapTime = session.nav.RecordTimer.getNextZapTime()
505         #get currentTime
506         nowTime = time()
507         if nextZapTime != -1 and nextRecordingTime != -1:
508                 startTime = nextZapTime < nextRecordingTime and nextZapTime or nextRecordingTime
509         else:
510                 startTime = nextZapTime != -1 and nextZapTime or nextRecordingTime
511         if startTime != -1:
512                 if (startTime - nowTime < 330): # no time to switch box back on
513                         setFPWakeuptime(nowTime + 30) # so switch back on in 30 seconds
514                 else:
515                         setFPWakeuptime(startTime - 300)
516         session.nav.stopService()
517         session.nav.shutdown()
518
519         return 0
520
521 import skin
522 skin.loadSkinData(getDesktop(0))
523
524 import Components.InputDevice
525 Components.InputDevice.InitInputDevices()
526
527 import Components.AVSwitch
528 Components.AVSwitch.InitAVSwitch()
529
530 import Components.RecordingConfig
531 Components.RecordingConfig.InitRecordingConfig()
532
533 import Components.UsageConfig
534 Components.UsageConfig.InitUsageConfig()
535
536 import keymapparser
537 keymapparser.readKeymap(config.usage.keymap.value)
538
539 import Components.Network
540 Components.Network.InitNetwork()
541
542 import Components.Lcd
543 Components.Lcd.InitLcd()
544
545 import Components.SetupDevices
546 Components.SetupDevices.InitSetupDevices()
547
548 import Components.RFmod
549 Components.RFmod.InitRFmod()
550
551 import Screens.Ci
552 Screens.Ci.InitCiConfig()
553
554 # first, setup a screen
555 try:
556         runScreenTest()
557
558         plugins.shutdown()
559
560         from Components.ParentalControl import parentalControl
561         parentalControl.save()
562 except:
563         print 'EXCEPTION IN PYTHON STARTUP CODE:'
564         print '-'*60
565         print_exc(file=stdout)
566         quitMainloop(5)
567         print '-'*60