4.2.0r15
[enigma2.git] / usr / lib / enigma2 / python / Screens / Wizard.py
1 from Screen import Screen
2 from Screens.MessageBox import MessageBox
3 from Components.config import ConfigText, ConfigPassword, KEY_LEFT, KEY_RIGHT, KEY_0, KEY_DELETE, KEY_BACKSPACE, KEY_ASCII,\
4         ConfigSelection, ConfigBoolean
5
6 from Components.Label import Label
7 from Components.Sources.StaticText import StaticText
8 from Components.Slider import Slider
9 from Components.ActionMap import NumberActionMap
10 from Components.ConfigList import ConfigList
11 from Components.Sources.List import List
12 from Components.config import config
13 from enigma import eTimer, eEnv
14
15 from Tools.BoundFunction import boundFunction
16 from Tools.Log import Log
17
18 from xml.sax import make_parser
19 from xml.sax.handler import ContentHandler
20
21 class WizardSummary(Screen):
22         skin = """
23         <screen position="0,0" size="132,64">
24                 <widget source="text" render="Label" position="6,0" size="120,16" font="Regular;16" transparent="1" />
25                 <widget source="parent.list" render="Label" position="6,18" size="120,46" font="Regular;12">
26                         <convert type="StringListSelection" />
27                 </widget>
28         </screen>"""
29         
30         def __init__(self, session, parent):
31                 Screen.__init__(self, session, parent)
32                 
33                 #names = parent.skinName
34                 #if not isinstance(names, list):
35                         #names = [names]
36 #                       
37                 #self.skinName = [x + "_summary" for x in names ]
38                 #self.skinName.append("Wizard")
39                 #print "*************+++++++++++++++++****************++++++++++******************* WizardSummary", self.skinName
40                         #
41                 self["text"] = StaticText("")
42                 self.onShow.append(self.setCallback)
43                 
44         def setCallback(self):
45                 self.parent.setLCDTextCallback(self.setText)
46
47         def setText(self, text):
48                 pass
49
50         def setTitle(self, title):
51                 Log.i(title)
52                 self["text"].setText(title)
53
54 class Wizard(Screen):
55         def createSummary(self):
56                         print "WizardCreateSummary"
57                         return WizardSummary
58
59         class parseWizard(ContentHandler):
60                 def __init__(self, wizard, parentWizard = None):
61                         self.isPointsElement, self.isReboundsElement = 0, 0
62                         self.wizard = wizard
63                         self.parentWizard = parentWizard
64                         self.currContent = ""
65                         self.lastStep = 0       
66
67                 def startElement(self, name, attrs):
68                         #print "startElement", name
69                         self.currContent = name
70                         if (name == "step"):
71                                 self.lastStep += 1
72                                 if attrs.has_key('id'):
73                                         id = str(attrs.get('id'))
74                                 else:
75                                         id = ""
76                                 #print "id:", id
77                                 if attrs.has_key('nextstep'):
78                                         nextstep = str(attrs.get('nextstep'))
79                                 else:
80                                         nextstep = None
81                                 if attrs.has_key('timeout'):
82                                         timeout = int(attrs.get('timeout'))
83                                 else:
84                                         timeout = None
85                                 if attrs.has_key('timeoutaction'):
86                                         timeoutaction = str(attrs.get('timeoutaction'))
87                                 else:
88                                         timeoutaction = 'nextpage'
89
90                                 if attrs.has_key('timeoutstep'):
91                                         timeoutstep = str(attrs.get('timeoutstep'))
92                                 else:
93                                         timeoutstep = ''
94                                 self.wizard[self.lastStep] = {"id": id, "condition": "", "text": "", "timeout": timeout, "timeoutaction": timeoutaction, "timeoutstep": timeoutstep, "list": [], "config": {"screen": None, "args": None, "type": "" }, "code": "", "codeafter": "", "code_async": "", "codeafter_async": "", "nextstep": nextstep}
95                                 if attrs.has_key('laststep'):
96                                         self.wizard[self.lastStep]["laststep"] = str(attrs.get('laststep'))
97                         elif (name == "text"):
98                                 if attrs.has_key("dynamictext"):
99                                         self.wizard[self.lastStep]["dynamictext"] = str(attrs.get('dynamictext'))
100                                 else:
101                                         self.wizard[self.lastStep]["text"] = str(attrs.get('value')).replace("\\n", "\n")
102                         elif name == "displaytext" or name =="short_title":
103                                 self.wizard[self.lastStep]["short_title"] = str(attrs.get('value')).replace("\\n", "\n")
104                         elif (name == "list"):
105                                 if (attrs.has_key('type')):
106                                         if attrs["type"] == "dynamic":
107                                                 self.wizard[self.lastStep]["dynamiclist"] = attrs.get("source")
108                                         if attrs["type"] == "config":
109                                                 self.wizard[self.lastStep]["configelement"] = attrs.get("configelement")
110                                 if (attrs.has_key("evaluation")):
111                                         self.wizard[self.lastStep]["listevaluation"] = attrs.get("evaluation")
112                                 if (attrs.has_key("onselect")):
113                                         self.wizard[self.lastStep]["onselect"] = attrs.get("onselect")
114                         elif (name == "multicontentlist"):
115                                 if (attrs.has_key('type')):
116                                         if attrs["type"] == "dynamic":
117                                                 self.wizard[self.lastStep]["dynamicmulticontentlist"] = attrs.get("setfunction")
118                                 if (attrs.has_key("onselect")):
119                                         self.wizard[self.lastStep]["onselect"] = attrs.get("onselect")
120                                 if (attrs.has_key("evaluation")):
121                                         self.wizard[self.lastStep]["evaluation"] = attrs.get("evaluation")
122                         elif (name == "listentry"):
123                                 self.wizard[self.lastStep]["list"].append((str(attrs.get('caption')), str(attrs.get('step'))))
124                         elif (name == "config"):
125                                 type = str(attrs.get('type'))
126                                 self.wizard[self.lastStep]["config"]["type"] = type
127                                 if type == "ConfigList" or type == "standalone":
128                                         try:
129                                                 exec "from Screens." + str(attrs.get('module')) + " import *"
130                                         except:
131                                                 exec "from " + str(attrs.get('module')) + " import *"
132                                 
133                                         self.wizard[self.lastStep]["config"]["screen"] = eval(str(attrs.get('screen')))
134                                         if (attrs.has_key('args')):
135                                                 #print "has args"
136                                                 self.wizard[self.lastStep]["config"]["args"] = str(attrs.get('args'))
137                                 elif type == "dynamic":
138                                         self.wizard[self.lastStep]["config"]["source"] = str(attrs.get('source'))
139                                         if (attrs.has_key('evaluation')):
140                                                 self.wizard[self.lastStep]["config"]["evaluation"] = str(attrs.get('evaluation'))
141                         elif (name == "code"):
142                                 self.async_code = attrs.has_key('async') and str(attrs.get('async')) == "yes"
143                                 if attrs.has_key('pos') and str(attrs.get('pos')) == "after":
144                                         self.codeafter = True
145                                 else:
146                                         self.codeafter = False
147                         elif (name == "condition"):
148                                 pass
149                         elif (name == "wizard"):
150                                 if self.parentWizard is not None:
151                                         if (attrs.has_key('nextstepanimation')):
152                                                 self.parentWizard.setAnimation(self.parentWizard.NEXT_STEP_ANIMATION, str(attrs.get('nextstepanimation')))
153                                         if (attrs.has_key('previousstepanimation')):
154                                                 self.parentWizard.setAnimation(self.parentWizard.PREVIOUS_STEP_ANIMATION, str(attrs.get('previousstepanimation')))                                              
155
156                 def endElement(self, name):
157                         self.currContent = ""
158                         if name == 'code':
159                                 if self.async_code:
160                                         if self.codeafter:
161                                                 self.wizard[self.lastStep]["codeafter_async"] = self.wizard[self.lastStep]["codeafter_async"].strip()
162                                         else:
163                                                 self.wizard[self.lastStep]["code_async"] = self.wizard[self.lastStep]["code_async"].strip()
164                                 else:
165                                         if self.codeafter:
166                                                 self.wizard[self.lastStep]["codeafter"] = self.wizard[self.lastStep]["codeafter"].strip()
167                                         else:
168                                                 self.wizard[self.lastStep]["code"] = self.wizard[self.lastStep]["code"].strip()
169                         elif name == 'condition':
170                                 self.wizard[self.lastStep]["condition"] = self.wizard[self.lastStep]["condition"].strip()
171                         elif name == 'step':
172                                 #print "Step number", self.lastStep, ":", self.wizard[self.lastStep]
173                                 pass
174                                                                 
175                 def characters(self, ch):
176                         if self.currContent == "code":
177                                 if self.async_code:
178                                         if self.codeafter:
179                                                 self.wizard[self.lastStep]["codeafter_async"] = self.wizard[self.lastStep]["codeafter_async"] + ch
180                                         else:
181                                                 self.wizard[self.lastStep]["code_async"] = self.wizard[self.lastStep]["code_async"] + ch
182                                 else:
183                                         if self.codeafter:
184                                                 self.wizard[self.lastStep]["codeafter"] = self.wizard[self.lastStep]["codeafter"] + ch
185                                         else:
186                                                 self.wizard[self.lastStep]["code"] = self.wizard[self.lastStep]["code"] + ch
187                         elif self.currContent == "condition":
188                                  self.wizard[self.lastStep]["condition"] = self.wizard[self.lastStep]["condition"] + ch
189         
190         def __init__(self, session, showSteps = True, showStepSlider = True, showList = True, showConfig = True, showMulticontentList = False):
191                 Screen.__init__(self, session)
192                 
193                 self.isLastWizard = False # can be used to skip a "goodbye"-screen in a wizard
194
195                 self.stepHistory = []
196                 self.__nextStepAnimation = Wizard.NEXT_STEP_ANIMATION_KEY
197                 self.__previousStepAnimation = Wizard.PREVIOUS_STEP_ANIMATION_KEY
198
199                 self.wizard = {}
200                 parser = make_parser()
201                 if not isinstance(self.xmlfile, list):
202                         self.xmlfile = [self.xmlfile]
203                 print "Reading ", self.xmlfile
204                 wizardHandler = self.parseWizard(self.wizard, self)
205                 parser.setContentHandler(wizardHandler)
206                 for xmlfile in self.xmlfile:
207                         if xmlfile[0] != '/':
208                                 parser.parse(eEnv.resolve('${datadir}/enigma2/') + xmlfile)
209                         else:
210                                 parser.parse(xmlfile)
211
212                 self.showSteps = showSteps
213                 self.showStepSlider = showStepSlider
214                 self.showList = showList
215                 self.showConfig = showConfig
216                 self.showMulticontentList = showMulticontentList
217
218                 self.numSteps = len(self.wizard)
219                 self.currStep = self.getStepWithID("start") + 1
220                 
221                 self.timeoutTimer = eTimer()
222                 self.timeoutTimer_conn = self.timeoutTimer.timeout.connect(self.timeoutCounterFired)
223
224                 self["text"] = Label()
225
226                 if showConfig:
227                         self["config"] = ConfigList([], session = session)
228
229                 if self.showSteps:
230                         self["step"] = Label()
231                 
232                 if self.showStepSlider:
233                         self["stepslider"] = Slider(1, self.numSteps)
234                 
235                 if self.showMulticontentList:
236                         self.multicontentlist = []
237                         self["multicontentlist"] = List(self.multicontentlist)
238                         self["multicontentlist"].onSelectionChanged.append(self.selChanged)
239
240                 if self.showList:
241                         self.list = []
242                         self["list"] = List(self.list, enableWrapAround = True)
243                         self["list"].onSelectionChanged.append(self.selChanged)
244                         #self["list"] = MenuList(self.list, enableWrapAround = True)
245
246                 self.onShown.append(self.updateValues)
247                 self.onShow.append(self._setTitle)
248
249                 self.configInstance = None
250                 self.currentConfigIndex = None
251                 
252                 self.lcdCallbacks = []
253                 
254                 self.disableKeys = False
255                 
256                 self["actions"] = NumberActionMap(["WizardActions", "NumberActions", "ColorActions", "SetupActions", "InputAsciiActions", "KeyboardInputActions"],
257                 {
258                         "gotAsciiCode": self.keyGotAscii,
259                         "ok": self.ok,
260                         "back": self.back,
261                         "left": self.left,
262                         "right": self.right,
263                         "up": self.up,
264                         "down": self.down,
265                         "red": self.red,
266                         "green": self.green,
267                         "yellow": self.yellow,
268                         "blue":self.blue,
269                         "deleteBackward": self.deleteBackward,
270                         "deleteForward": self.deleteForward,
271                         "video": self.setNoAnimations,
272                         "1": self.keyNumberGlobal,
273                         "2": self.keyNumberGlobal,
274                         "3": self.keyNumberGlobal,
275                         "4": self.keyNumberGlobal,
276                         "5": self.keyNumberGlobal,
277                         "6": self.keyNumberGlobal,
278                         "7": self.keyNumberGlobal,
279                         "8": self.keyNumberGlobal,
280                         "9": self.keyNumberGlobal,
281                         "0": self.keyNumberGlobal
282                 }, -1)
283
284                 self.__title = None
285
286                 self["VirtualKB"] = NumberActionMap(["VirtualKeyboardActions"],
287                 {
288                         "showVirtualKeyboard": self.KeyText,
289                 }, -2)
290                 
291                 self["VirtualKB"].setEnabled(False)
292                 
293                 self.onHideFinished.append(self.__hideFinished)
294                 self.onFirstExecBegin.append(self._initAnimation)
295
296         def _setTitle(self):
297                 if self.__title:
298                         self.setTitle(self.__title)
299
300         NEXT_STEP_ANIMATION = 0
301         PREVIOUS_STEP_ANIMATION = 1
302         NEXT_STEP_ANIMATION_KEY = "wizard_next"
303         PREVIOUS_STEP_ANIMATION_KEY = "wizard_previous"
304         def setAnimation(self, type, animation):
305                 if type == self.NEXT_STEP_ANIMATION:
306                         self.__nextStepAnimation = animation
307                 elif type == self.PREVIOUS_STEP_ANIMATION:
308                         self.__previousStepAnimation = animation
309
310         def setNoAnimations(self):
311                 key = ""
312                 Wizard.NEXT_STEP_ANIMATION_KEY = key
313                 Wizard.PREVIOUS_STEP_ANIMATION_KEY = key
314                 self.setAnimation(self.NEXT_STEP_ANIMATION, key)
315                 self.setAnimation(self.PREVIOUS_STEP_ANIMATION, key)
316
317         def _initAnimation(self):
318                 self.setShowHideAnimation(self.__nextStepAnimation)
319
320         def openScreen(self, *args, **kwargs):
321                 self.onHideFinished.remove(self.__hideFinished)
322                 self.session.openWithCallback(self.__foreignScreenInstanceFinished, *args, **kwargs)
323
324         def red(self):
325                 print "red"
326                 pass
327
328         def green(self):
329                 print "green"
330                 pass
331         
332         def yellow(self):
333                 print "yellow"
334                 pass
335         
336         def blue(self):
337                 print "blue"
338                 pass
339
340         def deleteForward(self):
341                 self.resetCounter()
342                 if (self.wizard[self.currStep]["config"]["screen"] != None):
343                         self.configInstance.keyDelete()
344                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
345                         self["config"].handleKey(KEY_DELETE)
346                 print "deleteForward"
347
348         def deleteBackward(self):
349                 self.resetCounter()
350                 if (self.wizard[self.currStep]["config"]["screen"] != None):
351                         self.configInstance.keyBackspace()
352                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
353                         self["config"].handleKey(KEY_BACKSPACE)
354                 print "deleteBackward"
355         
356         def setLCDTextCallback(self, callback):
357                 self.lcdCallbacks.append(callback)
358
359         def back(self):
360                 self.instance.setShowHideAnimation(self.__previousStepAnimation)
361                 if self.disableKeys:
362                         return
363                 print "getting back..."
364                 print "stepHistory:", self.stepHistory
365                 if len(self.stepHistory) > 1:
366                         self.currStep = self.stepHistory[-2]
367                         self.stepHistory = self.stepHistory[:-2]
368                         self.hide()
369                         self.updateValues()
370                 else:
371                         self.session.openWithCallback(self.exitWizardQuestion, MessageBox, (_("Are you sure you want to exit this wizard?") ) )
372                 if self.currStep < 1:
373                         self.currStep = 1
374                 print "currStep:", self.currStep
375                 print "new stepHistory:", self.stepHistory
376                 print "after updateValues stepHistory:", self.stepHistory
377                 
378         def exitWizardQuestion(self, ret = False):
379                 if (ret):
380                         self.markDone()
381                         self.close()
382                 
383         def markDone(self):
384                 pass
385         
386         def getStepWithID(self, id):
387                 print "getStepWithID:", id
388                 count = 0
389                 for x in self.wizard.keys():
390                         if self.wizard[x]["id"] == id:
391                                 print "result:", count
392                                 return count
393                         count += 1
394                 print "result: nothing"
395                 return 0
396
397         def finished(self, gotoStep = None, *args, **kwargs):
398                 self.hide()
399
400                 print "finished"
401                 currStep = self.currStep
402
403                 if self.updateValues not in self.onShown:
404                         self.onShown.append(self.updateValues)
405                         
406                 if self.showConfig:
407                         if self.wizard[currStep]["config"]["type"] == "dynamic":
408                                 eval("self." + self.wizard[currStep]["config"]["evaluation"])()
409
410                 if self.showList:
411                         if (len(self.wizard[currStep].get("evaluatedlist", [])) > 0):
412                                 print "current:", self["list"].current
413                                 nextStep = self["list"].current[1]
414                                 if (self.wizard[currStep].has_key("listevaluation")):
415                                         exec("self." + self.wizard[self.currStep]["listevaluation"] + "('" + nextStep + "')")
416                                 elif (self.wizard[currStep].has_key("configelement")):
417                                                 configelement = self.wizard[currStep]["configelement"]
418                                                 element = eval(configelement)
419                                                 element.value = self["list"].current[1]
420                                                 element.save()
421                                 else:
422                                         self.currStep = self.getStepWithID(nextStep)
423
424                 if self.showMulticontentList:
425                         if (len(self.wizard[currStep].get("evaluatedmulticontentlist", [])) > 0):
426                                 if (self.wizard[currStep].has_key("evaluation")):
427                                         exec("self." + self.wizard[self.currStep]["evaluation"] + "('" + self["multicontentlist"].current[0] + "')")
428
429                 print_now = True
430                 if ((currStep == self.numSteps and self.wizard[currStep]["nextstep"] is None) or self.wizard[currStep]["id"] == "end"): # wizard finished
431                         print "wizard finished"
432                         self.markDone()
433                         self.close()
434                 else:
435                         self.codeafter = True
436                         self.runCode(self.wizard[currStep]["codeafter"])
437                         self.prevStep = currStep
438                         self.gotoStep = gotoStep
439                         if not self.runCode(self.wizard[currStep]["codeafter_async"]):
440                                 self.afterAsyncCode()
441                         else:
442                                 if self.updateValues in self.onShown:
443                                         self.onShown.remove(self.updateValues)
444
445                 if print_now:
446                         print "Now: " + str(self.currStep)
447
448         def __hideFinished(self):
449                 self.show()
450
451         def ok(self):
452                 print "OK"
453                 self.instance.setShowHideAnimation(self.__nextStepAnimation)
454                 if self.disableKeys:
455                         return
456                 currStep = self.currStep
457                 
458                 if self.showConfig:
459                         if (self.wizard[currStep]["config"]["screen"] != None):
460                                 # TODO: don't die, if no run() is available
461                                 # there was a try/except here, but i can't see a reason
462                                 # for this. If there is one, please do a more specific check
463                                 # and/or a comment in which situation there is no run()
464                                 if callable(getattr(self.configInstance, "runAsync", None)):
465                                         if self.updateValues in self.onShown:
466                                                 self.onShown.remove(self.updateValues)
467
468                                         # we need to remove the callback so it doesn't show the wizard screen after hiding it. the onHideFinished is
469                                         # fired glpbally, not just for our own Screen
470                                         self.onHideFinished.remove(self.__hideFinished)
471                                         self.configInstance.runAsync(self.__foreignScreenInstanceFinished)
472                                 else:
473                                         self.configInstance.run()
474                 self.finished()
475
476         def __foreignScreenInstanceFinished(self, *args, **kwargs):
477                 # re-register the callback for the next wizard steps
478                 self.onHideFinished.append(self.__hideFinished)
479
480                 # we need to show the wizard Screen again. we don't call show() to prevent future features in __hideFinished()
481                 self.__hideFinished()
482
483         def keyNumberGlobal(self, number):
484                 if (self.wizard[self.currStep]["config"]["screen"] != None):
485                         self.configInstance.keyNumberGlobal(number)
486                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
487                         self["config"].handleKey(KEY_0 + number)
488
489         def keyGotAscii(self):
490                 if (self.wizard[self.currStep]["config"]["screen"] != None):
491                         self["config"].handleKey(KEY_ASCII)
492                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
493                         self["config"].handleKey(KEY_ASCII)
494                 
495         def left(self):
496                 self.resetCounter()
497                 if (self.wizard[self.currStep]["config"]["screen"] != None):
498                         self.configInstance.keyLeft()
499                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
500                         self["config"].handleKey(KEY_LEFT)
501                 print "left"
502         
503         def right(self):
504                 self.resetCounter()
505                 if (self.wizard[self.currStep]["config"]["screen"] != None):
506                         self.configInstance.keyRight()
507                 elif (self.wizard[self.currStep]["config"]["type"] == "dynamic"):
508                         self["config"].handleKey(KEY_RIGHT)     
509                 print "right"
510
511         def up(self):
512                 self.resetCounter()
513                 if (self.showConfig and self.wizard[self.currStep]["config"]["screen"] != None  or self.wizard[self.currStep]["config"]["type"] == "dynamic"):
514                         self["config"].instance.moveSelection(self["config"].instance.moveUp)
515                         self.handleInputHelpers()
516                 elif (self.showList and len(self.wizard[self.currStep]["evaluatedlist"]) > 0):
517                         self["list"].selectPrevious()
518                         if self.wizard[self.currStep].has_key("onselect"):
519                                 print "current:", self["list"].current
520                                 self.selection = self["list"].current[-1]
521                                 #self.selection = self.wizard[self.currStep]["evaluatedlist"][self["list"].l.getCurrentSelectionIndex()][1]
522                                 exec("self." + self.wizard[self.currStep]["onselect"] + "()")
523                 elif (self.showMulticontentList and len(self.wizard[self.currStep]["evaluatedmulticontentlist"]) > 0):
524                         self["multicontentlist"].selectPrevious()
525                         if self.wizard[self.currStep].has_key("onselect"):
526                                 self.selection = self["multicontentlist"].current
527                                 exec("self." + self.wizard[self.currStep]["onselect"] + "()")
528                 print "up"
529                 
530         def down(self):
531                 self.resetCounter()
532                 if (self.showConfig and self.wizard[self.currStep]["config"]["screen"] != None  or self.wizard[self.currStep]["config"]["type"] == "dynamic"):
533                         self["config"].instance.moveSelection(self["config"].instance.moveDown)
534                         self.handleInputHelpers()
535                 elif (self.showList and len(self.wizard[self.currStep]["evaluatedlist"]) > 0):
536                         #self["list"].instance.moveSelection(self["list"].instance.moveDown)
537                         self["list"].selectNext()
538                         if self.wizard[self.currStep].has_key("onselect"):
539                                 print "current:", self["list"].current
540                                 #self.selection = self.wizard[self.currStep]["evaluatedlist"][self["list"].l.getCurrentSelectionIndex()][1]
541                                 #exec("self." + self.wizard[self.currStep]["onselect"] + "()")
542                                 self.selection = self["list"].current[-1]
543                                 #self.selection = self.wizard[self.currStep]["evaluatedlist"][self["list"].l.getCurrentSelectionIndex()][1]
544                                 exec("self." + self.wizard[self.currStep]["onselect"] + "()")
545                 elif (self.showMulticontentList and len(self.wizard[self.currStep]["evaluatedmulticontentlist"]) > 0):
546                         self["multicontentlist"].selectNext()
547                         if self.wizard[self.currStep].has_key("onselect"):
548                                 self.selection = self["multicontentlist"].current
549                                 exec("self." + self.wizard[self.currStep]["onselect"] + "()")
550                 print "down"
551                 
552         def selChanged(self):
553                 self.resetCounter()
554                 
555                 if (self.showConfig and self.wizard[self.currStep]["config"]["screen"] != None):
556                         self["config"].instance.moveSelection(self["config"].instance.moveUp)
557                 elif (self.showList and len(self.wizard[self.currStep].get("evaluatedlist", [])) > 0):
558                         if self.wizard[self.currStep].has_key("onselect"):
559                                 self.selection = self["list"].current[-1]
560                                 print "self.selection:", self.selection
561                                 exec("self." + self.wizard[self.currStep]["onselect"] + "()")
562
563         def resetCounter(self):
564                 self.timeoutCounter = self.wizard[self.currStep]["timeout"]
565                 
566         def runCode(self, code):
567                 if code != "":
568                         print "code", code
569                         exec(code)
570                         return True
571                 return False
572
573         def getTranslation(self, text):
574                 return _(text)
575                         
576         def updateText(self, firstset = False):
577                 if self.wizard[self.currStep].has_key("dynamictext"):
578                         text = eval("self." + self.wizard[self.currStep]["dynamictext"] + "(\"" + self.wizard[self.currStep]["id"] + "\")")
579                 else:
580                         text = self.wizard[self.currStep]["text"]
581                 text = self.getTranslation(text)
582                 if text.find("[timeout]") != -1:
583                         text = text.replace("[timeout]", str(self.timeoutCounter))
584                         self["text"].setText(text)
585                 else:
586                         if firstset:
587                                 self["text"].setText(text)
588
589         def updateValues(self):
590                 print "Updating values in step " + str(self.currStep)
591                 # calling a step which doesn't exist can only happen if the condition in the last step is not fulfilled
592                 # if a non-existing step is called, end the wizard 
593                 if self.currStep > len(self.wizard):
594                         self.markDone()
595                         self.close()
596                         return
597
598                 self.timeoutTimer.stop()
599                 
600                 if self.configInstance is not None:
601                         # remove callbacks
602                         self.configInstance["config"].onSelectionChanged = []
603                         del self.configInstance["config"]
604                         self.configInstance.doClose()
605                         self.configInstance = None
606
607                 self.condition = True
608                 exec (self.wizard[self.currStep]["condition"])
609                 if not self.condition:
610                         print "keys*******************:", self.wizard[self.currStep].keys()
611                         if self.wizard[self.currStep].has_key("laststep"): # exit wizard, if condition of laststep doesn't hold
612                                 self.markDone()
613                                 self.close()
614                                 return
615                         else:
616                                 self.currStep += 1
617                                 self.updateValues()
618                 else:
619                         if len(self.stepHistory) == 0 or self.stepHistory[-1] != self.currStep:
620                                 self.stepHistory.append(self.currStep)
621                         print "wizard step:", self.wizard[self.currStep]
622                         
623                         if self.showSteps:
624                                 self["step"].setText(self.getTranslation("Step ") + str(self.currStep) + "/" + str(self.numSteps))
625                         if self.showStepSlider:
626                                 self["stepslider"].setValue(self.currStep)
627                 
628                         if self.wizard[self.currStep]["timeout"] is not None:
629                                 self.resetCounter() 
630                                 self.timeoutTimer.start(1000)
631                         
632                         print "wizard text", self.getTranslation(self.wizard[self.currStep]["text"])
633                         self.updateText(firstset = True)
634                         if self.wizard[self.currStep].has_key("short_title"):
635                                 short_title = _(self.wizard[self.currStep]["short_title"])
636                                 print "set Title"
637                                 self.__title = short_title
638
639                         self.codeafter=False
640                         self.runCode(self.wizard[self.currStep]["code"])
641                         if self.runCode(self.wizard[self.currStep]["code_async"]):
642                                 if self.updateValues in self.onShown:
643                                         self.onShown.remove(self.updateValues)
644                         else:
645                                 self.afterAsyncCode()
646
647         def showHideList(self, name, show = True):
648                 for renderer in self.renderer:
649                         rootrenderer = renderer
650                         while renderer.source is not None:
651                                 if renderer.source is self[name]:
652                                         if show:
653                                                 rootrenderer.instance.setZPosition(1)
654                                                 rootrenderer.instance.show()
655                                         else:
656                                                 rootrenderer.instance.setZPosition(0)
657                                                 rootrenderer.instance.hide()
658
659                                 renderer = renderer.source
660
661         def afterAsyncCode(self):
662                 if not self.updateValues in self.onShown:
663                         self.onShown.append(self.updateValues)
664
665                 if self.codeafter:
666                         if self.wizard[self.prevStep]["nextstep"] is not None:
667                                 self.currStep = self.getStepWithID(self.wizard[self.prevStep]["nextstep"])
668                         if self.gotoStep is not None:
669                                 self.currStep = self.getStepWithID(self.gotoStep)
670                         self.currStep += 1
671                         self.updateValues()
672                         print "Now: " + str(self.currStep)
673                 else:
674                         if self.showList:
675                                 print "showing list,", self.currStep
676                                 index = 0
677                                 self.showHideList("list", show = True)
678
679                                 #self["list"].instance.setZPosition(1)
680                                 self.list = []
681                                 if (self.wizard[self.currStep].has_key("dynamiclist")):
682                                         dynamiclist = self.wizard[self.currStep]["dynamiclist"]
683                                         print "dynamic list, calling", dynamiclist
684                                         newlist = eval("self." + self.wizard[self.currStep]["dynamiclist"] + "()")
685                                         #self.wizard[self.currStep]["evaluatedlist"] = []
686                                         for entry in newlist:
687                                                 #self.wizard[self.currStep]["evaluatedlist"].append(entry)
688                                                 self.list.append(entry)
689                                         #del self.wizard[self.currStep]["dynamiclist"]
690                                 if (self.wizard[self.currStep].has_key("configelement")):
691                                         configelement = self.wizard[self.currStep]["configelement"]
692                                         print "configelement:", configelement
693                                         element = eval(configelement)
694                                         
695                                         if isinstance(element, ConfigSelection):
696                                                 for choice in element.choices.choices:
697                                                         print "choice:", choice
698                                                         self.list.append((choice[1], choice[0]))
699                                                 index = element.getIndex()
700                                         elif isinstance(element, ConfigBoolean):
701                                                 self.list.append((_(element.descriptions[True]), True))
702                                                 self.list.append((_(element.descriptions[False]), False))
703                                                 index = 1
704                                                 if element.value:
705                                                         index = 0
706                                 if (len(self.wizard[self.currStep]["list"]) > 0):
707                                         #self["list"].instance.setZPosition(2)
708                                         for x in self.wizard[self.currStep]["list"]:
709                                                 self.list.append((self.getTranslation(x[0]), x[1]))
710                                 self.wizard[self.currStep]["evaluatedlist"] = self.list
711                                 self["list"].list = self.list
712                                 self["list"].index = index
713                                 if not self.list:
714                                         self.showHideList("list", show = False)
715 #                       else:
716 #                               self.showHideList("list", show = False)
717                                 
718                         if self.showMulticontentList:
719                                 print "showing multi content list"
720                                 self.showHideList("multicontentlist", show = True)
721                                 self.multicontentlist = []
722                                 if (self.wizard[self.currStep].has_key("dynamicmulticontentlist")):
723                                         dynamiclist = self.wizard[self.currStep]["dynamicmulticontentlist"]
724                                         exec("self." + self.wizard[self.currStep]["dynamicmulticontentlist"] + "()")
725                                 else:
726                                         self.showHideList("multicontentlist", show = False)
727                                 self.wizard[self.currStep]["evaluatedmulticontentlist"] = self.multicontentlist
728 #                       else:
729 #                               self.showHideList("multicontentlist", show = False)
730
731                         if self.showConfig:
732                                 print "showing config"
733 #                               self["config"].instance.setZPosition(1)
734                                 if self.wizard[self.currStep]["config"]["type"] == "dynamic":
735                                                 print "config type is dynamic"
736                                                 self["config"].instance.setZPosition(2)
737                                                 self["config"].l.setList(eval("self." + self.wizard[self.currStep]["config"]["source"])())
738                                 elif (self.wizard[self.currStep]["config"]["screen"] != None):
739                                         if self.wizard[self.currStep]["config"]["type"] == "standalone":
740                                                 print "Type is standalone"
741                                                 self.session.openWithCallback(self.ok, self.wizard[self.currStep]["config"]["screen"])
742                                         else:
743                                                 self["config"].instance.setZPosition(2)
744                                                 print "wizard screen", self.wizard[self.currStep]["config"]["screen"]
745                                                 if self.wizard[self.currStep]["config"]["args"] == None:
746                                                         self.configInstance = self.session.instantiateDialog(self.wizard[self.currStep]["config"]["screen"])
747                                                 else:
748                                                         self.configInstance = self.session.instantiateDialog(self.wizard[self.currStep]["config"]["screen"], eval(self.wizard[self.currStep]["config"]["args"]))
749                                                 self["config"].l.setList(self.configInstance["config"].list)
750                                                 callbacks = self.configInstance["config"].onSelectionChanged
751                                                 self.configInstance["config"].destroy()
752                                                 print "clearConfigList", self.configInstance["config"], self["config"]
753                                                 self.configInstance["config"] = self["config"]
754                                                 self.configInstance["config"].onSelectionChanged = callbacks
755                                                 print "clearConfigList", self.configInstance["config"], self["config"]
756                                 else:
757                                         self["config"].l.setList([])
758                                         self.handleInputHelpers()
759                                         
760                                         
761                         else:
762                                 if self.has_key("config"):
763                                         self["config"].hide()
764
765         def timeoutCounterFired(self):
766                 self.timeoutCounter -= 1
767                 print "timeoutCounter:", self.timeoutCounter
768                 if self.timeoutCounter == 0:
769                         if self.wizard[self.currStep]["timeoutaction"] == "selectnext":
770                                 print "selection next item"
771                                 self.down()
772                         else:
773                                 if self.wizard[self.currStep]["timeoutaction"] == "changestep":
774                                         self.finished(gotoStep = self.wizard[self.currStep]["timeoutstep"])
775                 self.updateText()
776
777         def handleInputHelpers(self):
778                 if self["config"].getCurrent() is not None:
779                         if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
780                                 if self.has_key("VKeyIcon"):
781                                         self["VirtualKB"].setEnabled(True)
782                                         self["VKeyIcon"].boolean = True
783                                 if self.has_key("HelpWindow"):
784                                         if self["config"].getCurrent()[1].help_window.instance is not None:
785                                                 helpwindowpos = self["HelpWindow"].getPosition()
786                                                 from enigma import ePoint
787                                                 self["config"].getCurrent()[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
788                         else:
789                                 if self.has_key("VKeyIcon"):
790                                         self["VirtualKB"].setEnabled(False)
791                                         self["VKeyIcon"].boolean = False
792                 else:
793                         if self.has_key("VKeyIcon"):
794                                 self["VirtualKB"].setEnabled(False)
795                                 self["VKeyIcon"].boolean = False
796
797         def KeyText(self):
798                 from Screens.VirtualKeyBoard import VirtualKeyBoard
799                 self.currentConfigIndex = self["config"].getCurrentIndex()
800                 self.session.openWithCallback(self.VirtualKeyBoardCallback, VirtualKeyBoard, title = self["config"].getCurrent()[0], text = self["config"].getCurrent()[1].getValue())
801
802         def VirtualKeyBoardCallback(self, callback = None):
803                 if callback is not None and len(callback):
804                         if isinstance(self["config"].getCurrent()[1], ConfigText) or isinstance(self["config"].getCurrent()[1], ConfigPassword):
805                                 if self.has_key("HelpWindow"):
806                                         if self["config"].getCurrent()[1].help_window.instance is not None:
807                                                 helpwindowpos = self["HelpWindow"].getPosition()
808                                                 from enigma import ePoint
809                                                 self["config"].getCurrent()[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
810                         self["config"].instance.moveSelectionTo(self.currentConfigIndex)
811                         self["config"].setCurrentIndex(self.currentConfigIndex)
812                         self["config"].getCurrent()[1].setValue(callback)
813                         self["config"].invalidate(self["config"].getCurrent())
814
815 class WizardManager:
816         def __init__(self):
817                 self.wizards = []
818         
819         def registerWizard(self, wizard, precondition, priority = 0):
820                 self.wizards.append((wizard, precondition, priority))
821         
822         def getWizards(self):
823                 # x[1] is precondition
824                 for wizard in self.wizards:
825                         wizard[0].isLastWizard = False
826                 if len(self.wizards) > 0:
827                         self.wizards[-1][0].isLastWizard = True
828                 return [(x[2], x[0]) for x in self.wizards if x[1] == 1]
829
830 wizardManager = WizardManager()