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