handle day wrap arounds more user friendly
[enigma2.git] / lib / python / Screens / TimerEntry.py
1 from Screen import Screen
2 import ChannelSelection
3 from ServiceReference import ServiceReference
4 from Components.config import *
5 from Components.ActionMap import ActionMap, NumberActionMap
6 from Components.ConfigList import ConfigList
7 from Components.MenuList import MenuList
8 from Components.Button import Button
9 from Components.NimManager import nimmanager
10 from Components.Label import Label
11 from Components.Pixmap import Pixmap
12 from Screens.MessageBox import MessageBox
13 from Screens.ChoiceBox import ChoiceBox
14 from RecordTimer import AFTEREVENT
15 from enigma import eEPGCache
16 import time
17 import datetime
18
19 class TimerEntry(Screen):
20         def __init__(self, session, timer):
21                 Screen.__init__(self, session)
22                 self.timer = timer
23                 
24                 self["oktext"] = Label(_("OK"))
25                 self["canceltext"] = Label(_("Cancel"))
26                 self["ok"] = Pixmap()
27                 self["cancel"] = Pixmap()
28
29                 self.createConfig()
30
31                 self["actions"] = NumberActionMap(["SetupActions", "TextEntryActions"],
32                 {
33                         "ok": self.keySelect,
34                         "save": self.keyGo,
35                         "cancel": self.keyCancel,
36                         "left": self.keyLeft,
37                         "right": self.keyRight,
38                         "delete": self.keyDelete,
39                         "1": self.keyNumberGlobal,
40                         "2": self.keyNumberGlobal,
41                         "3": self.keyNumberGlobal,
42                         "4": self.keyNumberGlobal,
43                         "5": self.keyNumberGlobal,
44                         "6": self.keyNumberGlobal,
45                         "7": self.keyNumberGlobal,
46                         "8": self.keyNumberGlobal,
47                         "9": self.keyNumberGlobal,
48                         "0": self.keyNumberGlobal
49                 }, -1)
50
51                 self.list = []
52                 self["config"] = ConfigList(self.list)
53                 self.createSetup("config")
54
55         def createConfig(self):
56                         config.timerentry = ConfigSubsection()
57                         
58                         if (self.timer.justplay):
59                                 justplay = 0
60                         else:
61                                 justplay = 1
62                                 
63                         afterevent = { AFTEREVENT.NONE: 0, AFTEREVENT.DEEPSTANDBY: 1, AFTEREVENT.STANDBY: 2}[self.timer.afterEvent]
64
65                         # calculate default values
66                         day = []
67                         weekday = 0
68                         for x in range(0,7):
69                                 day.append(1)
70                         if (self.timer.repeated != 0): # repeated
71                                 type = 1 # repeated
72                                 if (self.timer.repeated == 31): # Mon-Fri
73                                         repeated = 2 # Mon - Fri
74                                 elif (self.timer.repeated == 127): # daily
75                                         repeated = 0 # daily
76                                 else:
77                                         flags = self.timer.repeated
78                                         repeated = 3 # user defined
79                                         count = 0
80                                         for x in range(0, 7):
81                                                 if (flags == 1): # weekly
82                                                         print "Set to weekday " + str(x)
83                                                         weekday = x
84                                                 if (flags & 1 == 1): # set user defined flags
85                                                         day[x] = 0
86                                                         count += 1
87                                                 else:
88                                                         day[x] = 1
89                                                 flags = flags >> 1
90                                         if (count == 1):
91                                                 repeated = 1 # weekly
92                         else: # once
93                                 type = 0
94                                 repeated = 0
95                                 weekday = (int(strftime("%w", time.localtime(self.timer.begin))) - 1) % 7
96                                 day[weekday] = 0
97                         
98                         config.timerentry.justplay = configElement_nonSave("config.timerentry.justplay", configSelection, justplay, (("zap", _("zap")), ("record", _("record"))))
99                         config.timerentry.afterevent = configElement_nonSave("config.timerentry.afterevent", configSelection, afterevent, (("nothing", _("do nothing")), ("deepstandby", _("go to deep standby"))))
100                         config.timerentry.type = configElement_nonSave("config.timerentry.type", configSelection, type, (_("once"), _("repeated")))
101                         config.timerentry.name = configElement_nonSave("config.timerentry.name", configText, self.timer.name, (configText.extendableSize, self.keyRightCallback))
102                         config.timerentry.description = configElement_nonSave("config.timerentry.description", configText, self.timer.description, (configText.extendableSize, self.keyRightCallback))
103
104                         config.timerentry.repeated = configElement_nonSave("config.timerentry.repeated", configSelection, repeated, (_("daily"), _("weekly"), _("Mon-Fri"), _("user defined")))
105
106                         config.timerentry.startdate = configElement_nonSave("config.timerentry.startdate", configDateTime, self.timer.begin, (_("%d.%B %Y"), 86400))
107                         config.timerentry.starttime = configElement_nonSave("config.timerentry.starttime", configSequence, [int(time.strftime("%H", time.localtime(self.timer.begin))), int(time.strftime("%M", time.localtime(self.timer.begin)))], configsequencearg.get("CLOCK"))
108
109                         config.timerentry.enddate = configElement_nonSave("config.timerentry.enddate", configDateTime, self.timer.end, (_("%d.%B %Y"), 86400))
110                         config.timerentry.endtime = configElement_nonSave("config.timerentry.endtime", configSequence, [int(time.strftime("%H", time.localtime(self.timer.end))), int(time.strftime("%M", time.localtime(self.timer.end)))], configsequencearg.get("CLOCK"))
111
112                         config.timerentry.weekday = configElement_nonSave("config.timerentry.weekday", configSelection, weekday, (_("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday"), _("Friday"), _("Saturday"), _("Sunday")))
113
114                         config.timerentry.day = []
115                         for x in range(0,7):
116                                 config.timerentry.day.append(configElement_nonSave("config.timerentry.day[" + str(x) + "]", configSelection, day[x], (_("yes"), _("no"))))
117
118
119                         # FIXME some service-chooser needed here
120                         servicename = "N/A"
121                         try: # no current service available?
122                                 servicename = str(self.timer.service_ref.getServiceName())
123                         except:
124                                 pass
125                         config.timerentry.service = configElement_nonSave("config.timerentry.service", configSelection, 0, ((servicename),))
126                         
127                         config.timerentry.startdate.addNotifier(self.checkDate)
128                         config.timerentry.enddate.addNotifier(self.checkDate)
129
130         def checkDate(self, configElement):
131                 if (configElement.getConfigPath() == "config.timerentry.startdate"):
132                         if (config.timerentry.enddate.value < config.timerentry.startdate.value):
133                                 config.timerentry.enddate.value = config.timerentry.startdate.value
134                                 config.timerentry.enddate.change()
135                                 try:
136                                         self["config"].invalidate(config.timerentry.enddate)
137                                 except: # FIXME: what could go wrong here?
138                                         pass
139                 if (configElement.getConfigPath() == "config.timerentry.enddate"):
140                         if (config.timerentry.enddate.value < config.timerentry.startdate.value):
141                                 config.timerentry.startdate.value = config.timerentry.enddate.value
142                                 config.timerentry.startdate.change()
143                                 try:
144                                         self["config"].invalidate(config.timerentry.startdate)
145                                 except: # FIXME: what could go wrong here?
146                                         pass
147
148         def createSetup(self, widget):
149                 self.list = []
150                 self.list.append(getConfigListEntry(_("Name"), config.timerentry.name))
151                 self.list.append(getConfigListEntry(_("Description"), config.timerentry.description))
152                 self.timerJustplayEntry = getConfigListEntry(_("Timer Type"), config.timerentry.justplay)
153                 self.list.append(self.timerJustplayEntry)
154                 self.timerTypeEntry = getConfigListEntry(_("Repeat Type"), config.timerentry.type)
155                 self.list.append(self.timerTypeEntry)
156
157                 if (config.timerentry.type.value == 0): # once
158                         self.frequencyEntry = None
159                 else: # repeated
160                         self.frequencyEntry = getConfigListEntry(_("Frequency"), config.timerentry.repeated)
161                         self.list.append(self.frequencyEntry)
162                         if (config.timerentry.repeated.value == 0): # daily
163                                 pass
164                         if (config.timerentry.repeated.value == 2): # Mon-Fri
165                                 pass
166                         if (config.timerentry.repeated.value == 1): # weekly
167                                 self.list.append(getConfigListEntry(_("Weekday"), config.timerentry.weekday))
168
169                         if (config.timerentry.repeated.value == 3): # user defined
170                                 self.list.append(getConfigListEntry(_("Monday"), config.timerentry.day[0]))
171                                 self.list.append(getConfigListEntry(_("Tuesday"), config.timerentry.day[1]))
172                                 self.list.append(getConfigListEntry(_("Wednesday"), config.timerentry.day[2]))
173                                 self.list.append(getConfigListEntry(_("Thursday"), config.timerentry.day[3]))
174                                 self.list.append(getConfigListEntry(_("Friday"), config.timerentry.day[4]))
175                                 self.list.append(getConfigListEntry(_("Saturday"), config.timerentry.day[5]))
176                                 self.list.append(getConfigListEntry(_("Sunday"), config.timerentry.day[6]))
177
178                         #self.list.append(getConfigListEntry("StartDate", config.timerentry.startdate))
179 #               self.list.append(getConfigListEntry("Weekday", config.timerentry.weekday))
180
181                 if (config.timerentry.type.value == 0): # once
182                         self.list.append(getConfigListEntry(_("Start"), config.timerentry.startdate))
183                         self.list.append(getConfigListEntry(" ", config.timerentry.starttime))
184                 else:
185                         self.list.append(getConfigListEntry(_("StartTime"), config.timerentry.starttime))
186                 if (config.timerentry.type.value == 0): # once
187                         if currentConfigSelectionElement(config.timerentry.justplay) != "zap":
188                                 self.list.append(getConfigListEntry(_("End"), config.timerentry.enddate))
189                                 self.list.append(getConfigListEntry(" ", config.timerentry.endtime))
190                 else:
191                         if currentConfigSelectionElement(config.timerentry.justplay) != "zap":
192                                 self.list.append(getConfigListEntry(_("EndTime"), config.timerentry.endtime))
193
194                 if currentConfigSelectionElement(config.timerentry.justplay) != "zap":
195                         self.list.append(getConfigListEntry(_("After event"), config.timerentry.afterevent))
196
197                 self.channelEntry = getConfigListEntry(_("Channel"), config.timerentry.service)
198                 self.list.append(self.channelEntry)
199
200                 self[widget].list = self.list
201                 self[widget].l.setList(self.list)
202
203         def newConfig(self):
204                 print "newConfig", self["config"].getCurrent()
205                 if self["config"].getCurrent() == self.timerTypeEntry:
206                         self.createSetup("config")
207                 if self["config"].getCurrent() == self.timerJustplayEntry:
208                         self.createSetup("config")
209                 if self["config"].getCurrent() == self.frequencyEntry:
210                         self.createSetup("config")
211
212         def keyLeft(self):
213                 if self["config"].getCurrent() == self.channelEntry:
214                         self.keySelect()
215                 else:
216                         self["config"].handleKey(config.key["prevElement"])
217                         self.newConfig()
218
219         def keyDelete(self):
220                 self["config"].handleKey(config.key["delete"])
221                         
222         def keyRightCallback(self, configPath):
223                 currentConfigPath = self["config"].getCurrent()[1].parent.getConfigPath()
224                 # check if we are still on the same config entry
225                 if (currentConfigPath == configPath):
226                         self.keyRight()
227
228         def keyRight(self):
229                 if self["config"].getCurrent() == self.channelEntry:
230                         self.keySelect()
231                 else:
232                         self["config"].handleKey(config.key["nextElement"])
233                         self.newConfig()
234                 
235         def keySelect(self):
236                 if self["config"].getCurrent() == self.channelEntry:
237                         self.session.openWithCallback(self.finishedChannelSelection, ChannelSelection.SimpleChannelSelection, _("Select channel to record from"))
238                 else:
239                         self.keyGo()
240
241         def finishedChannelSelection(self, *args):
242                 if len(args):
243                         self.timer.service_ref = ServiceReference(args[0])
244                         config.timerentry.service.vals = (str(self.timer.service_ref.getServiceName()),)
245                         self["config"].invalidate(config.timerentry.service)
246
247         def keyNumberGlobal(self, number):
248                 print "You pressed number " + str(number)
249                 if (self["config"].getCurrent()[1].parent.enabled == True):
250                         self["config"].handleKey(config.key[str(number)])
251
252         def getTimestamp(self, date, mytime):
253                 d = time.localtime(date)
254                 dt = datetime.datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
255                 return int(mktime(dt.timetuple()))
256
257         def getBeginEnd(self):
258                 enddate = config.timerentry.enddate.value
259                 endtime = config.timerentry.endtime.value
260                 
261                 startdate = config.timerentry.startdate.value
262                 starttime = config.timerentry.starttime.value
263                 
264                 begin = self.getTimestamp(startdate, starttime)
265                 end = self.getTimestamp(enddate, endtime)
266                 
267                 # because of the dateChecks, startdate can't be < enddate.
268                 # however, the endtime can be less than the starttime.
269                 # in this case, add 1 day.
270                 if end < begin:
271                         end += 86400
272                 return begin, end
273
274         def keyGo(self):
275                 self.timer.name = config.timerentry.name.value
276                 self.timer.description = config.timerentry.description.value
277                 self.timer.justplay = (currentConfigSelectionElement(config.timerentry.justplay) == "zap")
278                 self.timer.resetRepeated()
279                 self.timer.afterEvent = { 0: AFTEREVENT.NONE, 1: AFTEREVENT.DEEPSTANDBY, 2: AFTEREVENT.STANDBY}[config.timerentry.afterevent.value]
280                 
281                 if (config.timerentry.type.value == 0): # once
282                         self.timer.begin, self.timer.end = self.getBeginEnd()
283                 if (config.timerentry.type.value == 1): # repeated
284                         if (config.timerentry.repeated.value == 0): # daily
285                                 for x in range(0,7):
286                                         self.timer.setRepeated(x)
287
288                         if (config.timerentry.repeated.value == 1): # weekly
289                                 self.timer.setRepeated(config.timerentry.weekday.value)
290                                 
291                         if (config.timerentry.repeated.value == 2): # Mon-Fri
292                                 for x in range(0,5):
293                                         self.timer.setRepeated(x)
294                                 
295                         if (config.timerentry.repeated.value == 3): # user defined
296                                 for x in range(0,7):
297                                         if (config.timerentry.day[x].value == 0): self.timer.setRepeated(x)
298
299                         self.timer.begin = self.getTimestamp(time.time(), config.timerentry.starttime.value)
300                         self.timer.end = self.getTimestamp(time.time(), config.timerentry.endtime.value)
301                         
302                         # when a timer end is set before the start, add 1 day
303                         if self.timer.end < self.timer.begin:
304                                 self.timer.end += 86400
305
306                 if self.timer.eit is not None:
307                         event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
308                         if event is not None:
309                                 n = event.getNumOfLinkageServices()
310                                 if n > 0:
311                                         tlist = []
312                                         ref = self.session.nav.getCurrentlyPlayingServiceReference()
313                                         parent = self.timer.service_ref.ref
314                                         selection = 0
315                                         for x in range(n):
316                                                 i = event.getLinkageService(parent, x)
317                                                 if i.toString() == ref.toString():
318                                                         selection = x
319                                                 tlist.append((i.getName(), i))
320                                         self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
321                                         return
322                 self.close((True, self.timer))
323
324         def subserviceSelected(self, service):
325                 if not service is None:
326                         self.timer.service_ref = ServiceReference(service[1])
327                 self.close((True, self.timer))
328
329         def keyCancel(self):
330                 self.close((False,))
331                 
332 class TimerLog(Screen):
333         def __init__(self, session, timer):
334                 Screen.__init__(self, session)
335                 self.timer = timer;
336                 self.log_entries = self.timer.log_entries[:]
337                 
338                 self.fillLogList()
339                 
340                 self["loglist"] = MenuList(self.list)
341                 self["logentry"] = Label()
342                 
343                 self["key_red"] = Button(_("Delete entry"))
344                 self["key_green"] = Button()
345                 self["key_yellow"] = Button("")
346                 self["key_blue"] = Button(_("Clear log"))
347                 
348                 self.onShown.append(self.updateText)
349
350                 self["actions"] = NumberActionMap(["OkCancelActions", "DirectionActions", "ColorActions"],
351                 {
352                         "ok": self.keyClose,
353                         "cancel": self.keyClose,
354                         "up": self.up,
355                         "down": self.down,
356                         "left": self.left,
357                         "right": self.right,
358                         "red": self.deleteEntry,
359                         "blue": self.clearLog
360                 }, -1)
361
362         def deleteEntry(self):
363                 self.log_entries.remove(self["loglist"].getCurrent()[1])
364                 self.fillLogList()
365                 self["loglist"].l.setList(self.list)
366                 self.updateText()
367
368         def fillLogList(self):
369                 self.list = [ ]
370                 for x in self.log_entries:
371                         self.list.append((str(strftime("%Y-%m-%d %H-%M", localtime(x[0])) + " - " + x[2]), x))
372         
373         def clearLog(self):             
374                 self.log_entries = []
375                 self.fillLogList()
376                 self["loglist"].l.setList(self.list)
377                 self.updateText()
378                 
379         def keyClose(self):
380                 if self.timer.log_entries != self.log_entries:
381                         self.timer.log_entries = self.log_entries
382                         self.close((True, self.timer))
383                 else:
384                         self.close((False,))
385                 
386         def up(self):
387                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveUp)
388                 self.updateText()
389                 
390         def down(self):
391                 self["loglist"].instance.moveSelection(self["loglist"].instance.moveDown)
392                 self.updateText()
393
394         def left(self):
395                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageUp)
396                 self.updateText()
397                 
398         def right(self):
399                 self["loglist"].instance.moveSelection(self["loglist"].instance.pageDown)
400                 self.updateText()
401
402         def updateText(self):
403                 if len(self.list) > 0:
404                         self["logentry"].setText(str(self["loglist"].getCurrent()[1][2]))
405                 else:
406                         self["logentry"].setText("")