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