Version 0.8a: Fix Bug with "Start KiddyTimer for x minutes"
[enigma2-plugins.git] / 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.show()
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                 self.enabled = config.plugins.KiddyTimer.enabled.value
153                 config.plugins.KiddyTimer.enabled.save()
154                 self.stopMe()                
155             elif self.callbackParameter == PARAM_INCREASETIMER:
156                 self.session.openWithCallback(self.increaseRemainingCallback, MinuteInput)
157             elif self.callbackParameter == PARAM_SETTIMER:
158                 self.session.openWithCallback(self.setRemainingCallback, MinuteInput)
159             elif self.callbackParameter == PARAM_ENABLETIMERONCE:
160                 self.session.openWithCallback(self.setRemainingOnceCallback, MinuteInput)
161                 
162     def increaseRemainingCallback(self, iMinutes):
163         iSeconds = iMinutes * 60
164         iSeconds += self.lastSavedRemainingTime 
165         self.setRemainingTime(iSeconds)
166
167     def decreaseRemainingCallback(self, iMinutes):
168         iSeconds = iMinutes * 60
169         iSeconds = self.lastSavedRemainingTime - iSeconds
170         self.setRemainingTime(iSeconds)
171
172     def setRemainingCallback(self, iMinutes):
173         iSeconds = iMinutes * 60
174         self.resetTimer(setTime=iSeconds)
175         self.calculateTimer()
176         
177     def setRemainingOnceCallback(self, iMinutes):
178         iSeconds = iMinutes * 60
179         if iSeconds > 0:
180             self.enabled = True
181             self.resetTimer(setTime=iSeconds)
182             self.activationCallback(True)
183         
184     def setRemainingTime(self, iSeconds):
185         self.lastSavedRemainingTime = iSeconds
186         if self.lastSavedRemainingTime > self.currentDayTime:
187             self.currentDayTime = self.lastSavedRemainingTime
188         if self.lastSavedRemainingTime < 0:
189             self.lastSavedRemainingTime = 0
190         self.calculateTimer()
191         
192     def startLoop(self):
193         self.loopTimer.start(self.loopTimerStep,1)
194     
195     def stopLoop(self):
196         self.loopTimer.stop()
197     
198     def resetTimer(self,**kwargs):
199         if "setTime" in kwargs.keys():
200             iDayTime = kwargs["setTime"]
201         else:            
202             iDayTime = KTglob.getSecondsFromClock( config.plugins.KiddyTimer.dayTimes[self.dayNr].timeValue.getValue() )
203         self.currentDayTime = iDayTime
204         
205         self.lastSavedRemainingTime = self.currentDayTime
206         self.remainingTime = self.currentDayTime
207                 
208         config.plugins.KiddyTimer.lastStartDay.setValue(self.currentDay)
209         self.remainingPercentage = self.remainingTime / self.currentDayTime
210         self.pluginStartTime = time.localtime()
211         
212         self.saveValues()
213     
214     def timerHasToRun(self):
215         iPluginStart = KTglob.getSecondsFromClock( [self.pluginStartTime[3],self.pluginStartTime[4]] )
216         iMonitorEnd = KTglob.getSecondsFromClock(config.plugins.KiddyTimer.monitorEndTime.getValue())  
217         return iPluginStart < iMonitorEnd 
218     
219     def setDialogStatus(self , bStatus):
220         if bStatus == True:
221             self.dialogEnabled = True
222             if self.dialog != None:
223                 self.dialog.show()
224         else:
225             self.dialogEnabled = False
226             if self.dialog != None:
227                 self.dialog.hide()
228
229     def calculateTimer(self):
230         self.stopLoop()
231         if self.dialogEnabled == True:
232             odtEnd = time.mktime(time.localtime())
233             iDiff = odtEnd - time.mktime(self.pluginStartTime)
234             iRemaining = self.lastSavedRemainingTime - iDiff
235             if iRemaining < 0:
236                 iRemaining = 0
237             self.remainingTime = iRemaining
238             self.remainingPercentage = iRemaining / self.currentDayTime
239             self.saveValues()
240             
241             self.setImageNumber()
242             
243             if self.remainingTime == 0:
244                 self.iServiceReference = NavigationInstance.instance.getCurrentlyPlayingServiceReference()
245                 NavigationInstance.instance.stopService()
246             self.dialog.renderScreen()
247         self.startLoop()
248
249     def enterStandby(self,configElement):
250         Standby.inStandby.onClose.append(self.endStandby)
251         self.stopMe()            
252         
253     def showHide(self):
254         if config.plugins.KiddyTimer.enabled.value and self.timerHasToRun():
255             self.setDialogStatus(True)
256         else:
257             self.setDialogStatus(False)
258         
259     def endStandby(self):
260         self.gotSession(self.session)
261
262     def setImageNumber(self):
263         iCurPercent = int( self.remainingPercentage * 1000 )
264         iCount = 0
265         for iPercent in self.dialog.percentageList:
266            if iCurPercent <= iPercent:
267                iCount = iCount + 1
268         iCount = iCount - 1
269         if iCount < 0:
270             iCount = 0
271         self.curImg = iCount
272
273     def stopMe(self):
274         self.saveValues()
275         if self.dialog != None:
276             self.stopLoop()
277             self.dialog.hide()
278         self.iServiceReference = None
279         self.dialog = None
280         
281     def saveValues(self):
282         config.plugins.KiddyTimer.lastStartDay.save()
283         config.plugins.KiddyTimer.remainingTime.setValue(int(self.remainingTime))
284         config.plugins.KiddyTimer.remainingTime.save()
285
286     def showExtensionsMenu(self):
287         self.session.openWithCallback(self.DoSelectionExtensionsMenu,ChoiceBox,_("Please select your KiddyTimer- option"),self.getOptionList())
288
289     def getOptionList(self):
290         keyList = []
291         if self.enabled:
292             if self.dialogEnabled:
293                 keyList.append((_("Stop KiddyTimer (this session only)"),PARAM_STOPTIMER))
294                 keyList.append((_("Increase remaining time"),PARAM_INCREASETIMER))
295                 keyList.append((_("Decrease remaining time"),PARAM_DECREASETIMER))
296                 keyList.append((_("Set remaining time"),PARAM_SETTIMER))
297             else:
298                 keyList.append((_("Start KiddyTimer"),PARAM_STARTTIMER))
299             keyList.append((_("Enable KiddyTimer for x minutes"),PARAM_ENABLETIMERONCE))
300             keyList.append((_("Disable KiddyTimer"),PARAM_DISABLETIMER))
301         else:
302             keyList.append((_("Enable KiddyTimer"),PARAM_ENABLETIMER))
303             keyList.append((_("Enable KiddyTimer for x minutes"),PARAM_ENABLETIMERONCE))
304         return keyList
305         
306     def DoSelectionExtensionsMenu(self,answer):
307         self.callbackParam = -1
308         if answer is None:
309             pass
310         elif answer[1] == PARAM_DISABLETIMER:
311             self.callbackParameter = PARAM_DISABLETIMER
312             self.askForPassword(self.pinEntered)
313         elif  answer[1] == PARAM_STOPTIMER:
314             self.activationCallback(False)
315         elif  answer[1] == PARAM_STARTTIMER:
316             self.activationCallback(True)
317         elif  answer[1] == PARAM_ENABLETIMER:
318             config.plugins.KiddyTimer.enabled.value = True
319             self.enabled = config.plugins.KiddyTimer.enabled.value
320             config.plugins.KiddyTimer.enabled.save()
321             self.gotSession(self.session)
322         elif answer[1] == PARAM_INCREASETIMER:
323             self.callbackParameter = PARAM_INCREASETIMER
324             self.askForPassword(self.pinEntered)
325         elif answer[1] == PARAM_DECREASETIMER:
326             self.session.openWithCallback(self.decreaseRemainingCallback, MinuteInput)
327         elif answer[1] == PARAM_SETTIMER:
328             self.callbackParameter = PARAM_SETTIMER
329             self.askForPassword(self.pinEntered)
330         elif answer[1] == PARAM_ENABLETIMERONCE:
331             self.callbackParameter = PARAM_ENABLETIMERONCE
332             self.askForPassword(self.pinEntered)
333         else:
334             self.session.open(MessageBox,_("Invalid selection"), MessageBox.TYPE_ERROR, 5)
335
336 # Assign global variable oKiddyTimer
337 oKiddyTimer = KiddyTimer()