6a21797384041d36b36c0a05a44356003d54dc88
[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         self.stopLoop()
207         if self.dialogEnabled == True:
208             odtEnd = time.mktime(time.localtime())
209             iDiff = odtEnd - time.mktime(self.pluginStartTime)
210             iRemaining = self.lastSavedRemainingTime - iDiff
211             if iRemaining < 0:
212                 iRemaining = 0
213             self.remainingTime = iRemaining
214             self.remainingPercentage = iRemaining / self.currentDayTime
215             self.saveValues()
216             
217             self.setImageNumber()
218             
219             if self.remainingTime == 0:
220                 self.iServiceReference = NavigationInstance.instance.getCurrentlyPlayingServiceReference()
221                 NavigationInstance.instance.stopService()
222             self.dialog.renderScreen()
223         self.startLoop()
224
225     def enterStandby(self,configElement):
226         Standby.inStandby.onClose.append(self.endStandby)
227         self.stopMe()            
228         
229     def showHide(self):
230         if config.plugins.KiddyTimer.enabled.value and self.timerHasToRun():
231             self.setDialogStatus(True)
232         else:
233             self.setDialogStatus(False)
234         
235     def endStandby(self):
236         self.gotSession(self.session)
237
238     def setImageNumber(self):
239         iCurPercent = int( self.remainingPercentage * 1000 )
240         iCount = 0
241         for iPercent in self.dialog.percentageList:
242            if iCurPercent <= iPercent:
243                iCount = iCount + 1
244         iCount = iCount - 1
245         if iCount < 0:
246             iCount = 0
247         self.curImg = iCount
248
249     def stopMe(self):
250         self.saveValues()
251         if self.dialog != None:
252             self.stopLoop()
253             self.dialog.hide()
254         self.iServiceReference = None
255         self.dialog = None
256         
257     def saveValues(self):
258         config.plugins.KiddyTimer.lastStartDay.save()
259         config.plugins.KiddyTimer.remainingTime.setValue(int(self.remainingTime))
260         config.plugins.KiddyTimer.remainingTime.save()
261
262     def showExtensionsMenu(self):
263         self.session.openWithCallback(self.DoSelectionExtensionsMenu,ChoiceBox,_("Please select your KiddyTimer- option"),self.getOptionList())
264
265     def getOptionList(self):
266         keyList = []
267         if config.plugins.KiddyTimer.enabled.value:
268             if self.dialogEnabled:
269                 keyList.append((_("Stop KiddyTimer (this session only)"),1))
270                 keyList.append((_("Increase remaining time"),5))
271                 keyList.append((_("Decrease remaining time"),6))
272             else:
273                 keyList.append((_("Start KiddyTimer"),2))
274             keyList.append((_("Disable KiddyTimer"),3))
275         else:
276             keyList.append((_("Enable KiddyTimer"),4))
277         return keyList
278     
279     def DoSelectionExtensionsMenu(self,answer):
280         if answer is None:
281             pass
282         elif answer[1] == 3:
283             self.askForPassword(self.pinEnteredDesactivation)
284         elif  answer[1] == 1:
285             self.activationCallback(False)
286         elif  answer[1] == 2:
287             self.activationCallback(True)
288         elif  answer[1] == 4:
289             config.plugins.KiddyTimer.enabled.value = True
290             config.plugins.KiddyTimer.enabled.save()
291             self.gotSession(self.session)
292         elif answer[1] ==5:
293             self.askForPassword(self.pinEnteredIncreaseRemainingTime)
294         elif answer[1] ==6:
295             self.session.openWithCallback(self.decreaseRemainingCallback, MinuteInput)
296         else:
297             self.session.open(MessageBox,_("Invalid selection"), MessageBox.TYPE_ERROR, 5)
298
299 # Assign global variable oKiddyTimer
300 oKiddyTimer = KiddyTimer()