New Version 0.6: New Functions in Extensions- Menu, Using config.misc.standbyCounter...
[vuplus_dvbapp-plugin] / kiddytimer / src / KTmain.py
1 from Components.Label import Label
2 from Components.ProgressBar import ProgressBar
3 from KTMultiPixmap import KTmultiPixmap
4 from Components.config import config
5 from Screens.ChoiceBox import ChoiceBox
6 from Screens.InputBox import PinInput
7 from Screens.MessageBox import MessageBox
8 from Screens.MinuteInput import MinuteInput
9 from Screens.Screen import Screen
10 from Screens import Standby
11 from Tools.BoundFunction import boundFunction
12 from Tools import Notifications
13 from enigma import ePoint, eTimer
14 import KTglob
15 import NavigationInstance
16 import time
17
18 class KiddyTimerScreen(Screen):    
19
20     def __init__(self, session):
21         Screen.__init__(self, session)
22         self.skin = KTglob.SKIN
23         self.onShow.append(self.movePosition)
24         
25         self.skin_path = KTglob.plugin_path
26
27         self["TimerGraph"] = KTmultiPixmap()
28         self["TimerText"] = Label(_("??:??"))
29         self["TimerSlider"] = ProgressBar()
30         self["TimerSliderText"] = Label(_("??:??"))
31         
32     def renderScreen(self):
33         self["TimerSlider"].setValue(int(oKiddyTimer.remainingPercentage*100)) 
34         self["TimerGraph"].setPixmapNum(oKiddyTimer.curImg)
35         self.sTimeLeft = KTglob.getTimeFromSeconds( (oKiddyTimer.remainingTime + 59) , False ) # Add 59 Seconds to show one minute if less than 1 minute left...
36         self["TimerText"].setText(self.sTimeLeft)
37         self["TimerSliderText"].setText(self.sTimeLeft)
38
39         if config.plugins.KiddyTimer.timerStyle.value == "clock":
40             self["TimerGraph"].show()
41             self["TimerText"].show()
42             self["TimerSlider"].hide()    
43             self["TimerSliderText"].hide()
44         else:
45             self["TimerGraph"].hide()
46             self["TimerText"].hide()
47             self["TimerSlider"].show()
48             self["TimerSliderText"].show()
49
50     def movePosition(self):
51         if self.instance:
52             self.getPixmapList()
53             self.instance.move(ePoint(config.plugins.KiddyTimer.position_x.value, config.plugins.KiddyTimer.position_y.value))
54
55     def getPixmapList(self):
56         self.percentageList = []
57         for sPixmap in self["TimerGraph"].pixmapFiles:
58             i = int(sPixmap[-8:-4])
59             self.percentageList.append(i)
60       
61 ##############################################################################
62
63 class KiddyTimer():
64
65     def __init__(self):
66         self.session = None 
67         self.dialog = None
68         self.dialogEnabled = False
69
70         self.iServiceReference = None
71         self.curImg = 0
72                     
73         self.loopTimerStep = 10000
74         self.loopTimer = eTimer()
75         self.loopTimer.callback.append(self.calculateTimer)
76
77         config.misc.standbyCounter.addNotifier(self.enterStandby, initial_call = False)
78     
79     def gotSession(self, session):
80         self.session = session
81         self.enabled = config.plugins.KiddyTimer.enabled.value
82         # Start- Time of the plugin, used for calculating the remaining time
83         self.pluginStartTime = time.localtime()            
84         # Number of the current day
85         self.dayNr = int(time.strftime("%w" , self.pluginStartTime ))
86         # Current Day to compare with the last saved day. If different -> Reset counter
87         # Number of seconds for the current day
88         iDayTime = KTglob.getSecondsFromClock( config.plugins.KiddyTimer.dayTimes[self.dayNr].timeValue.getValue() )
89         self.currentDayTime = iDayTime
90         self.currentDay = time.strftime("%d.%m.%Y" , self.pluginStartTime)
91         self.lastSavedRemainingTime = config.plugins.KiddyTimer.remainingTime.getValue()
92         self.remainingTime = self.lastSavedRemainingTime
93         if self.enabled == True:            
94             if self.currentDay != config.plugins.KiddyTimer.lastStartDay.getValue():
95                 #Reset all Timers
96                 self.resetTimer()
97             
98             if self.dialog == None:
99                 self.dialog = self.session.instantiateDialog(KiddyTimerScreen)
100                 self.dialog.hide()
101                 
102             self.setDialogStatus(self.timerHasToRun())
103             if self.dialogEnabled == True:
104                 self.askForActivation()
105             else:
106                 self.calculateTimer()
107     
108     def askForActivation(self):
109         iTimeOut = config.plugins.KiddyTimer.activationDialogTimeout.getValue()
110         Notifications.AddNotificationWithCallback(self.activationCallback, MessageBox, _("Do you want to start the kiddytimer- plugin now."), MessageBox.TYPE_YESNO, iTimeOut)
111
112     def activationCallback(self, value):
113         self.setDialogStatus(self.timerHasToRun())
114
115         if value:
116             self.setDialogStatus( True )
117             if self.dialog == None:
118                 self.dialog = self.session.instantiateDialog(KiddyTimerScreen)
119                 self.dialog.hide()
120         else:
121             self.askForPassword(self.pinEnteredDialog)
122                                        
123         self.calculateTimer()
124
125     def askForPassword(self,callbackFunction):
126         self.session.openWithCallback( callbackFunction, PinInput, pinList = [config.plugins.KiddyTimer.pin.getValue()], triesEntry = self.getTriesEntry(), title = _("Please enter the correct pin code"), windowTitle = _("Enter pin code"))
127     
128     def getTriesEntry(self):
129         return config.ParentalControl.retries.setuppin
130         
131     def pinEnteredDialog(self, result):
132         if result is None:
133             pass
134         elif not result:
135             pass
136         else:
137             self.setDialogStatus( False )        
138     
139     def pinEnteredDesactivation(self, result):
140         if result is None:
141             pass
142         elif not result:
143             pass
144         else:
145             config.plugins.KiddyTimer.enabled.value = False
146             config.plugins.KiddyTimer.enabled.save()
147             self.stopMe()
148     
149     def pinEnteredIncreaseRemainingTime(self, result):
150         if result is None:
151             pass
152         elif not result:
153             pass
154         else:
155             self.session.openWithCallback(self.increaseRemainingCallback, MinuteInput)
156
157     def increaseRemainingCallback(self, iMinutes):
158         iSeconds = iMinutes * 60
159         self.lastSavedRemainingTime += iSeconds
160         if self.lastSavedRemainingTime > self.currentDayTime:
161             self.lastSavedRemainingTime = self.currentDayTime
162         self.calculateTimer()
163
164     def decreaseRemainingCallback(self, iMinutes):
165         iSeconds = iMinutes * 60
166         self.lastSavedRemainingTime -= iSeconds
167         if self.lastSavedRemainingTime < 0:
168             self.lastSavedRemainingTime = 0
169         self.calculateTimer()
170
171     def startLoop(self):
172         self.loopTimer.start(self.loopTimerStep,1)
173     
174     def stopLoop(self):
175         self.loopTimer.stop()
176     
177     def resetTimer(self):
178         iDayTime = KTglob.getSecondsFromClock( config.plugins.KiddyTimer.dayTimes[self.dayNr].timeValue.getValue() )
179         self.currentDayTime = iDayTime
180         
181         self.lastSavedRemainingTime = self.currentDayTime
182         self.remainingTime = self.currentDayTime
183                 
184         config.plugins.KiddyTimer.lastStartDay.setValue(self.currentDay)
185         self.remainingPercentage = self.remainingTime / self.currentDayTime
186         self.pluginStartTime = time.localtime()
187         
188         self.saveValues()
189     
190     def timerHasToRun(self):
191         iPluginStart = KTglob.getSecondsFromClock( [self.pluginStartTime[3],self.pluginStartTime[4]] )
192         iMonitorEnd = KTglob.getSecondsFromClock(config.plugins.KiddyTimer.monitorEndTime.getValue())  
193         return iPluginStart < iMonitorEnd 
194     
195     def setDialogStatus(self , bStatus):
196         if bStatus == True:
197             self.dialogEnabled = True
198             if self.dialog != None:
199                 self.dialog.show()
200         else:
201             self.dialogEnabled = False
202             if self.dialog != None:
203                 self.dialog.hide()
204
205     def calculateTimer(self):
206         if self.dialogEnabled == True:
207             odtEnd = time.mktime(time.localtime())
208             iDiff = odtEnd - time.mktime(self.pluginStartTime)
209             iRemaining = self.lastSavedRemainingTime - iDiff
210             if iRemaining < 0:
211                 iRemaining = 0
212             self.remainingTime = iRemaining
213             self.remainingPercentage = iRemaining / self.currentDayTime
214             self.saveValues()
215             
216             self.setImageNumber()
217             
218             if self.remainingTime == 0:
219                 self.iServiceReference = NavigationInstance.instance.getCurrentlyPlayingServiceReference()
220                 NavigationInstance.instance.stopService()
221             self.dialog.renderScreen()
222         self.startLoop()
223
224     def enterStandby(self,configElement):
225         Standby.inStandby.onClose.append(self.endStandby)
226         self.stopMe()            
227         
228     def showHide(self):
229         if config.plugins.KiddyTimer.enabled.value and self.timerHasToRun():
230             self.setDialogStatus(True)
231         else:
232             self.setDialogStatus(False)
233         
234     def endStandby(self):
235         self.gotSession(self.session)
236
237     def setImageNumber(self):
238         iCurPercent = int( self.remainingPercentage * 1000 )
239         iCount = 0
240         for iPercent in self.dialog.percentageList:
241            if iCurPercent <= iPercent:
242                iCount = iCount + 1
243         iCount = iCount - 1
244         if iCount < 0:
245             iCount = 0
246         self.curImg = iCount
247
248     def stopMe(self):
249         self.saveValues()
250         if self.dialog != None:
251             self.stopLoop()
252             self.dialog.hide()
253         self.iServiceReference = None
254         self.dialog = None
255         
256     def saveValues(self):
257         config.plugins.KiddyTimer.lastStartDay.save()
258         config.plugins.KiddyTimer.remainingTime.setValue(int(self.remainingTime))
259         config.plugins.KiddyTimer.remainingTime.save()
260
261     def showExtensionsMenu(self):
262         self.session.openWithCallback(self.DoSelectionExtensionsMenu,ChoiceBox,_("Please select your KiddyTimer- option"),self.getOptionList())
263
264     def getOptionList(self):
265         keyList = []
266         if config.plugins.KiddyTimer.enabled.value:
267             if self.dialogEnabled:
268                 keyList.append((_("Stop KiddyTimer (this session only)"),1))
269                 keyList.append((_("Increase remaining time"),5))
270                 keyList.append((_("Decrease remaining time"),6))
271             else:
272                 keyList.append((_("Start KiddyTimer"),2))
273             keyList.append((_("Disable KiddyTimer"),3))
274         else:
275             keyList.append((_("Enable KiddyTimer"),4))
276         return keyList
277     
278     def DoSelectionExtensionsMenu(self,answer):
279         if answer is None:
280             pass
281         elif answer[1] == 3:
282             self.askForPassword(self.pinEnteredDesactivation)
283         elif  answer[1] == 1:
284             self.activationCallback(False)
285         elif  answer[1] == 2:
286             self.activationCallback(True)
287         elif  answer[1] == 4:
288             config.plugins.KiddyTimer.enabled.value = True
289             config.plugins.KiddyTimer.enabled.save()
290             self.gotSession(self.session)
291         elif answer[1] ==5:
292             self.askForPassword(self.pinEnteredIncreaseRemainingTime)
293         elif answer[1] ==6:
294             self.session.openWithCallback(self.decreaseRemainingCallback, MinuteInput)
295         else:
296             self.session.open(MessageBox,_("Invalid selection"), MessageBox.TYPE_ERROR, 5)
297
298 # Assign global variable oKiddyTimer
299 oKiddyTimer = KiddyTimer()