fix typo
[enigma2.git] / lib / python / Screens / NetworkSetup.py
1 from Screen import Screen
2 from Screens.MessageBox import MessageBox
3 from Screens.InputBox import InputBox
4 from Screens.Standby import *
5 from Screens.VirtualKeyBoard import VirtualKeyBoard
6 from Screens.HelpMenu import HelpableScreen
7 from Components.Network import iNetwork
8 from Components.Label import Label,MultiColorLabel
9 from Components.Pixmap import Pixmap,MultiPixmap
10 from Components.MenuList import MenuList
11 from Components.config import config, ConfigYesNo, ConfigIP, NoSave, ConfigText, ConfigPassword, ConfigSelection, getConfigListEntry, ConfigNothing
12 from Components.ConfigList import ConfigListScreen
13 from Components.PluginComponent import plugins
14 from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
15 from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
16 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE
17 from Tools.LoadPixmap import LoadPixmap
18 from Plugins.Plugin import PluginDescriptor
19 from enigma import eTimer, ePoint, eSize, RT_HALIGN_LEFT, eListboxPythonMultiContent, gFont
20 from os import path as os_path, system as os_system, unlink
21 from re import compile as re_compile, search as re_search
22
23
24 class InterfaceList(MenuList):
25         def __init__(self, list, enableWrapAround=False):
26                 MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
27                 self.l.setFont(0, gFont("Regular", 20))
28                 self.l.setItemHeight(30)
29
30 def InterfaceEntryComponent(index,name,default,active ):
31         res = [ (index) ]
32         res.append(MultiContentEntryText(pos=(80, 5), size=(430, 25), font=0, text=name))
33         num_configured_if = len(iNetwork.getConfiguredAdapters())
34         if num_configured_if >= 2:
35                 if default is True:
36                         png = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/buttons/button_blue.png"))
37                 if default is False:
38                         png = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/buttons/button_blue_off.png"))
39                 res.append(MultiContentEntryPixmapAlphaTest(pos=(10, 5), size=(25, 25), png = png))
40         if active is True:
41                 png2 = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/icons/lock_on.png"))
42         if active is False:
43                 png2 = LoadPixmap(resolveFilename(SCOPE_SKIN_IMAGE, "skin_default/icons/lock_error.png"))
44         res.append(MultiContentEntryPixmapAlphaTest(pos=(40, 1), size=(25, 25), png = png2))
45         return res
46
47
48 class NetworkAdapterSelection(Screen,HelpableScreen):
49         def __init__(self, session):
50                 Screen.__init__(self, session)
51                 HelpableScreen.__init__(self)
52                 
53                 self.wlan_errortext = _("No working wireless networkadapter found.\nPlease verify that you have attached a compatible WLAN USB Stick and your Network is configured correctly.")
54                 self.lan_errortext = _("No working local networkadapter found.\nPlease verify that you have attached a network cable and your Network is configured correctly.")
55                 self.oktext = _("Press OK on your remote control to continue.")
56                 self.restartLanRef = None
57                 
58                 self["ButtonBluetext"] = Label(_("Set as default Interface"))
59                 self["ButtonBlue"] = Pixmap()
60                 self["ButtonRedtext"] = Label(_("Close"))
61                 self["introduction"] = Label(_("Press OK to edit the settings."))
62                 
63                 self.adapters = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
64                 
65                 if len(self.adapters) == 0:
66                         self.onFirstExecBegin.append(self.NetworkFallback)
67                         
68                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
69                         {
70                         "cancel": (self.close, _("exit networkinterface list")),
71                         "ok": (self.okbuttonClick, _("select interface")),
72                         })
73
74                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
75                         {
76                         "red": (self.close, _("exit networkinterface list")),   
77                         })
78                 
79                 self["DefaultInterfaceAction"] = HelpableActionMap(self, "ColorActions",
80                         {
81                         "blue": (self.setDefaultInterface, [_("Set interface as default Interface"),_("* Only available if more then one interface is active.")] ),     
82                         })
83                 
84                 self.list = []
85                 self["list"] = InterfaceList(self.list)
86                 self.updateList()
87                 
88                 if len(self.adapters) == 1:
89                         self.onFirstExecBegin.append(self.okbuttonClick)
90                 self.onClose.append(self.cleanup)
91                 
92         def updateList(self):
93                 iNetwork.getInterfaces()
94                 self.list = []
95                 default_gw = None
96                 num_configured_if = len(iNetwork.getConfiguredAdapters())
97                 if num_configured_if >= 2:
98                         self["ButtonBlue"].show()
99                         self["ButtonBluetext"].show()
100                         self["DefaultInterfaceAction"].setEnabled(True)
101                 else:
102                         self["ButtonBlue"].hide()
103                         self["ButtonBluetext"].hide()
104                         self["DefaultInterfaceAction"].setEnabled(False)
105
106                 if num_configured_if < 2 and os_path.exists("/etc/default_gw"):
107                         unlink("/etc/default_gw")
108                         
109                 if os_path.exists("/etc/default_gw"):
110                         fp = file('/etc/default_gw', 'r')
111                         result = fp.read()
112                         fp.close()
113                         default_gw = result
114                                         
115                 if len(self.adapters) == 0: # no interface available => display only eth0
116                         self.list.append(InterfaceEntryComponent("eth0",iNetwork.getFriendlyAdapterName('eth0'),True,True ))
117                 else:
118                         for x in self.adapters:
119                                 if x[1] == default_gw:
120                                         default_int = True
121                                 else:
122                                         default_int = False
123                                 if iNetwork.getAdapterAttribute(x[1], 'up') is True:
124                                         active_int = True
125                                 else:
126                                         active_int = False
127                                 self.list.append(InterfaceEntryComponent(index = x[1],name = _(x[0]),default=default_int,active=active_int ))
128                 self["list"].l.setList(self.list)
129
130         def setDefaultInterface(self):
131                 selection = self["list"].getCurrent()
132                 num_if = len(self.list)
133                 old_default_gw = None
134                 num_configured_if = len(iNetwork.getConfiguredAdapters())
135                 if os_path.exists("/etc/default_gw"):
136                         fp = open('/etc/default_gw', 'r')
137                         old_default_gw = fp.read()
138                         fp.close()
139                 if num_configured_if > 1 and (not old_default_gw or old_default_gw != selection[0]):
140                         fp = open('/etc/default_gw', 'w+')
141                         fp.write(selection[0])
142                         fp.close()
143                         self.restartLan()
144                 elif old_default_gw and num_configured_if < 2:
145                         unlink("/etc/default_gw")
146                         self.restartLan()
147
148         def okbuttonClick(self):
149                 selection = self["list"].getCurrent()
150                 if selection is not None:
151                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, selection[0])
152
153         def AdapterSetupClosed(self, *ret):
154                 if len(self.adapters) == 1:
155                         self.close()
156                 else:
157                         self.updateList()
158
159         def NetworkFallback(self):
160                 if iNetwork.configuredNetworkAdapters.has_key('wlan0') is True:
161                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.wlan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
162                 if iNetwork.configuredNetworkAdapters.has_key('ath0') is True:
163                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.wlan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
164                 else:
165                         self.session.openWithCallback(self.ErrorMessageClosed, MessageBox, self.lan_errortext, type = MessageBox.TYPE_INFO,timeout = 10)
166
167         def ErrorMessageClosed(self, *ret):
168                 if iNetwork.configuredNetworkAdapters.has_key('wlan0') is True:
169                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'wlan0')
170                 elif iNetwork.configuredNetworkAdapters.has_key('ath0') is True:
171                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'ath0')
172                 else:
173                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetupConfiguration, 'eth0')
174
175         def cleanup(self):
176                 iNetwork.stopLinkStateConsole()
177                 iNetwork.stopRestartConsole()
178
179         def restartLan(self):
180                 iNetwork.restartNetwork(self.restartLanDataAvail)
181                 self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while we configure your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
182                         
183         def restartLanDataAvail(self, data):
184                 if data is True:
185                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
186
187         def getInterfacesDataAvail(self, data):
188                 if data is True:
189                         self.restartLanRef.close(True)
190
191         def restartfinishedCB(self,data):
192                 if data is True:
193                         self.updateList()
194                         self.session.open(MessageBox, _("Finished configuring your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
195
196
197 class NameserverSetup(Screen, ConfigListScreen, HelpableScreen):
198         def __init__(self, session):
199                 Screen.__init__(self, session)
200                 HelpableScreen.__init__(self)
201                 self.backupNameserverList = iNetwork.getNameserverList()[:]
202                 print "backup-list:", self.backupNameserverList
203                 
204                 self["ButtonGreentext"] = Label(_("Add"))
205                 self["ButtonYellowtext"] = Label(_("Delete"))
206                 self["ButtonRedtext"] = Label(_("Close"))
207                 self["introduction"] = Label(_("Press OK to activate the settings."))
208                 self.createConfig()
209                 
210                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
211                         {
212                         "cancel": (self.cancel, _("exit nameserver configuration")),
213                         "ok": (self.ok, _("activate current configuration")),
214                         })
215                 
216                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
217                         {
218                         "red": (self.cancel, _("exit nameserver configuration")),
219                         "green": (self.add, _("add a nameserver entry")),
220                         "yellow": (self.remove, _("remove a nameserver entry")),
221                         })
222                 
223                 
224                 self.list = []
225                 ConfigListScreen.__init__(self, self.list)
226                 self.createSetup()
227
228         def createConfig(self):
229                 self.nameservers = iNetwork.getNameserverList()
230                 self.nameserverEntries = []
231                 
232                 for nameserver in self.nameservers:
233                         self.nameserverEntries.append(NoSave(ConfigIP(default=nameserver)))
234
235         def createSetup(self):
236                 self.list = []
237                 
238                 for i in range(len(self.nameserverEntries)):
239                         self.list.append(getConfigListEntry(_("Nameserver %d") % (i + 1), self.nameserverEntries[i]))
240                 
241                 self["config"].list = self.list
242                 self["config"].l.setList(self.list)
243
244         def ok(self):
245                 iNetwork.clearNameservers()
246                 for nameserver in self.nameserverEntries:
247                         iNetwork.addNameserver(nameserver.value)
248                 iNetwork.writeNameserverConfig()
249                 self.close()
250
251         def run(self):
252                 self.ok()
253
254         def cancel(self):
255                 iNetwork.clearNameservers()
256                 print "backup-list:", self.backupNameserverList
257                 for nameserver in self.backupNameserverList:
258                         iNetwork.addNameserver(nameserver)
259                 self.close()
260
261         def add(self):
262                 iNetwork.addNameserver([0,0,0,0])
263                 self.createConfig()
264                 self.createSetup()
265
266         def remove(self):
267                 print "currentIndex:", self["config"].getCurrentIndex()
268                 
269                 index = self["config"].getCurrentIndex()
270                 if index < len(self.nameservers):
271                         iNetwork.removeNameserver(self.nameservers[index])
272                         self.createConfig()
273                         self.createSetup()
274         
275 class AdapterSetup(Screen, ConfigListScreen, HelpableScreen):
276         def __init__(self, session, iface,essid=None, aplist=None):
277                 Screen.__init__(self, session)
278                 HelpableScreen.__init__(self)
279                 self.session = session
280                 self.iface = iface
281                 self.essid = essid
282                 self.aplist = aplist
283                 self.extended = None
284                 self.applyConfigRef = None
285                 self.finished_cb = None
286                 self.oktext = _("Press OK on your remote control to continue.")
287                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
288                 #iNetwork.getInterfaces()
289                 
290                 self.createConfig()
291
292                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
293                         {
294                         "cancel": (self.close, _("exit networkadapter setup menu")),
295                         "ok": (self.ok, _("select menu entry")),
296                         })
297
298                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
299                         {
300                         "red": (self.cancel, _("exit networkadapter configuration")),
301                         "blue": (self.KeyBlue, _("open nameserver configuration")),
302                         })
303
304                 self["VirtualKB"] = HelpableActionMap(self, "ColorActions",
305                         {
306                         "green": (self.KeyGreen, [_("open virtual keyboard input help"),_("* Only available when entering hidden ssid or network key")] ),                                      
307                         })
308
309                 self["actions"] = NumberActionMap(["SetupActions"],
310                 {
311                         "ok": self.ok,
312                 }, -2)
313                 
314                 
315                 self.list = []
316                 ConfigListScreen.__init__(self, self.list,session = self.session)
317                 self.createSetup()
318                 self.onLayoutFinish.append(self.layoutFinished)
319                 self.onClose.append(self.cleanup)
320                 
321                 self["DNS1text"] = Label(_("Primary DNS"))
322                 self["DNS2text"] = Label(_("Secondary DNS"))
323                 self["DNS1"] = Label()
324                 self["DNS2"] = Label()
325                 
326                 self["introduction"] = Label(_("Current settings:"))
327                 
328                 self["IPtext"] = Label(_("IP Address"))
329                 self["Netmasktext"] = Label(_("Netmask"))
330                 self["Gatewaytext"] = Label(_("Gateway"))
331                 
332                 self["IP"] = Label()
333                 self["Mask"] = Label()
334                 self["Gateway"] = Label()
335                 
336                 self["BottomBG"] = Pixmap()
337                 self["Adaptertext"] = Label(_("Network:"))
338                 self["Adapter"] = Label()
339                 self["introduction2"] = Label(_("Press OK to activate the settings."))
340                 self["ButtonRed"] = Pixmap()
341                 self["ButtonRedtext"] = Label(_("Close"))
342                 self["ButtonBlue"] = Pixmap()
343                 self["ButtonBluetext"] = Label(_("Edit DNS"))
344                 self["ButtonGreen"] = Pixmap()
345                 self["VKeyIcon"] = Pixmap()
346                 self["HelpWindow"] = Pixmap()
347
348         def layoutFinished(self):
349                 self["DNS1"].setText(self.primaryDNS.getText())
350                 self["DNS2"].setText(self.secondaryDNS.getText())
351                 if self.ipConfigEntry.getText() is not None:
352                         if self.ipConfigEntry.getText() == "0.0.0.0":
353                                 self["IP"].setText(_("N/A"))
354                         else:   
355                                 self["IP"].setText(self.ipConfigEntry.getText())
356                 else:
357                         self["IP"].setText(_("N/A"))
358                 if self.netmaskConfigEntry.getText() is not None:
359                         if self.netmaskConfigEntry.getText() == "0.0.0.0":
360                                         self["Mask"].setText(_("N/A"))
361                         else:   
362                                 self["Mask"].setText(self.netmaskConfigEntry.getText())
363                 else:
364                         self["IP"].setText(_("N/A"))                    
365                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
366                         if self.gatewayConfigEntry.getText() == "0.0.0.0":
367                                 self["Gateway"].setText(_("N/A"))
368                         else:
369                                 self["Gateway"].setText(self.gatewayConfigEntry.getText())
370                 else:
371                         self["Gateway"].hide()
372                         self["Gatewaytext"].hide()
373                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
374                 self["ButtonGreen"].hide()
375                 self["VKeyIcon"].hide()
376                 self["VirtualKB"].setEnabled(False)
377                 self["HelpWindow"].hide()
378
379         def createConfig(self):
380                 self.InterfaceEntry = None
381                 self.dhcpEntry = None
382                 self.gatewayEntry = None
383                 self.hiddenSSID = None
384                 self.wlanSSID = None
385                 self.encryptionEnabled = None
386                 self.encryptionKey = None
387                 self.encryptionType = None
388                 self.nwlist = None
389                 self.encryptionlist = None
390                 self.weplist = None
391                 self.wsconfig = None
392                 self.default = None
393                 
394                 if self.iface == "wlan0" or self.iface == "ath0" :
395                         from Plugins.SystemPlugins.WirelessLan.Wlan import wpaSupplicant,Wlan
396                         self.w = Wlan(self.iface)
397                         self.ws = wpaSupplicant()
398                         self.encryptionlist = []
399                         self.encryptionlist.append(("WEP", _("WEP")))
400                         self.encryptionlist.append(("WPA", _("WPA")))
401                         self.encryptionlist.append(("WPA2", _("WPA2")))
402                         self.encryptionlist.append(("WPA/WPA2", _("WPA or WPA2")))
403                         self.weplist = []
404                         self.weplist.append("ASCII")
405                         self.weplist.append("HEX")
406                         if self.aplist is not None:
407                                 self.nwlist = self.aplist
408                                 self.nwlist.sort(key = lambda x: x[0])
409                         else:
410                                 self.nwlist = []
411                                 self.aps = None
412                                 try:
413                                         self.aps = self.w.getNetworkList()
414                                         if self.aps is not None:
415                                                 print "[NetworkSetup.py] got Accespoints!"
416                                                 #print self.aps
417                                                 for ap in self.aps:
418                                                         a = self.aps[ap]
419                                                         if a['active']:
420                                                                 if a['essid'] == "":
421                                                                         a['essid'] = a['bssid']
422                                                                 self.nwlist.append( a['essid'])
423                                         self.nwlist.sort(key = lambda x: x[0])
424                                 except:
425                                         self.nwlist.append("No Networks found")
426
427                         self.wsconfig = self.ws.loadConfig()
428                         if self.essid is not None: # ssid from wlan scan
429                                 self.default = self.essid
430                         else:
431                                 self.default = self.wsconfig['ssid']
432                                 
433                         if "hidden..." not in self.nwlist:
434                                 self.nwlist.append("hidden...")
435                         if self.default not in self.nwlist:
436                                 self.nwlist.append(self.default)
437
438                         config.plugins.wlan.essid = NoSave(ConfigSelection(self.nwlist, default = self.default ))
439                         config.plugins.wlan.hiddenessid = NoSave(ConfigText(default = self.wsconfig['hiddenessid'], visible_width = 50, fixed_size = False))
440
441                         config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = self.wsconfig['encryption'] ))
442                         config.plugins.wlan.encryption.type = NoSave(ConfigSelection(self.encryptionlist, default = self.wsconfig['encryption_type'] ))
443                         config.plugins.wlan.encryption.wepkeytype = NoSave(ConfigSelection(self.weplist, default = self.wsconfig['encryption_wepkeytype'] ))
444                         config.plugins.wlan.encryption.psk = NoSave(ConfigPassword(default = self.wsconfig['key'], visible_width = 50, fixed_size = False))
445                 
446                 self.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "up") or False))
447                 self.dhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "dhcp") or False))
448                 self.ipConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0])
449                 self.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0]))
450                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
451                         self.dhcpdefault=True
452                 else:
453                         self.dhcpdefault=False
454                 self.hasGatewayConfigEntry = NoSave(ConfigYesNo(default=self.dhcpdefault or False))
455                 self.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0]))
456                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
457                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
458                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
459
460         def createSetup(self):
461                 self.list = []
462                 self.InterfaceEntry = getConfigListEntry(_("Use Interface"), self.activateInterfaceEntry)
463                 
464                 self.list.append(self.InterfaceEntry)
465                 if self.activateInterfaceEntry.value:
466                         self.dhcpEntry = getConfigListEntry(_("Use DHCP"), self.dhcpConfigEntry)
467                         self.list.append(self.dhcpEntry)
468                         if not self.dhcpConfigEntry.value:
469                                 self.list.append(getConfigListEntry(_('IP Address'), self.ipConfigEntry))
470                                 self.list.append(getConfigListEntry(_('Netmask'), self.netmaskConfigEntry))
471                                 self.gatewayEntry = getConfigListEntry(_('Use a gateway'), self.hasGatewayConfigEntry)
472                                 self.list.append(self.gatewayEntry)
473                                 if self.hasGatewayConfigEntry.value:
474                                         self.list.append(getConfigListEntry(_('Gateway'), self.gatewayConfigEntry))
475                         
476                         self.extended = None            
477                         for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
478                                 callFnc = p.__call__["ifaceSupported"](self.iface)
479                                 if callFnc is not None:
480                                         if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
481                                                 self.extended = callFnc
482                                                 if p.__call__.has_key("configStrings"):
483                                                         self.configStrings = p.__call__["configStrings"]
484                                                 else:
485                                                         self.configStrings = None
486                                                 if config.plugins.wlan.essid.value == 'hidden...':
487                                                         self.wlanSSID = getConfigListEntry(_("Network SSID"), config.plugins.wlan.essid)
488                                                         self.list.append(self.wlanSSID)
489                                                         self.hiddenSSID = getConfigListEntry(_("Hidden network SSID"), config.plugins.wlan.hiddenessid)
490                                                         self.list.append(self.hiddenSSID)
491                                                 else:
492                                                         self.wlanSSID = getConfigListEntry(_("Network SSID"), config.plugins.wlan.essid)
493                                                         self.list.append(self.wlanSSID)
494                                                 self.encryptionEnabled = getConfigListEntry(_("Encryption"), config.plugins.wlan.encryption.enabled)
495                                                 self.list.append(self.encryptionEnabled)
496                                                 
497                                                 if config.plugins.wlan.encryption.enabled.value:
498                                                         self.encryptionType = getConfigListEntry(_("Encryption Type"), config.plugins.wlan.encryption.type)
499                                                         self.list.append(self.encryptionType)
500                                                         if config.plugins.wlan.encryption.type.value == 'WEP':
501                                                                 self.list.append(getConfigListEntry(_("Encryption Keytype"), config.plugins.wlan.encryption.wepkeytype))
502                                                                 self.encryptionKey = getConfigListEntry(_("Encryption Key"), config.plugins.wlan.encryption.psk)                                                
503                                                                 self.list.append(self.encryptionKey)                                                    
504                                                         else:                                                           
505                                                                 self.encryptionKey = getConfigListEntry(_("Encryption Key"), config.plugins.wlan.encryption.psk)                                                
506                                                                 self.list.append(self.encryptionKey)
507         
508                 
509                 self["config"].list = self.list
510                 self["config"].l.setList(self.list)
511                 if not self.selectionChanged in self["config"].onSelectionChanged:
512                         self["config"].onSelectionChanged.append(self.selectionChanged)
513
514         def KeyBlue(self):
515                 self.session.openWithCallback(self.NameserverSetupClosed, NameserverSetup)
516
517         def KeyGreen(self):
518                 if self.iface == "wlan0" or self.iface == "ath0" :      
519                         if self["config"].getCurrent() == self.hiddenSSID:
520                                 if config.plugins.wlan.essid.value == 'hidden...':
521                                         self.session.openWithCallback(self.VirtualKeyBoardSSIDCallback, VirtualKeyBoard, title = (_("Enter WLAN networkname/SSID:")), text = config.plugins.wlan.essid.value)
522                         if self["config"].getCurrent() == self.encryptionKey:
523                                 self.session.openWithCallback(self.VirtualKeyBoardKeyCallback, VirtualKeyBoard, title = (_("Enter WLAN passphrase/key:")), text = config.plugins.wlan.encryption.psk.value)
524         
525         def VirtualKeyBoardSSIDCallback(self, callback = None):
526                 if callback is not None and len(callback):
527                         config.plugins.wlan.hiddenessid = NoSave(ConfigText(default = callback, visible_width = 50, fixed_size = False))
528                         self.createSetup()
529                         
530         def VirtualKeyBoardKeyCallback(self, callback = None):
531                 if callback is not None and len(callback):
532                         config.plugins.wlan.encryption.psk = NoSave(ConfigPassword(default = callback, visible_width = 50, fixed_size = False))
533                         self.createSetup()
534                         
535         def newConfig(self):
536                 if self["config"].getCurrent() == self.InterfaceEntry:
537                         self.createSetup()
538                 if self["config"].getCurrent() == self.dhcpEntry:
539                         self.createSetup()
540                 if self["config"].getCurrent() == self.gatewayEntry:
541                         self.createSetup()
542                 if self.iface == "wlan0" or self.iface == "ath0" :      
543                         if self["config"].getCurrent() == self.wlanSSID:
544                                 self.createSetup()
545                         if self["config"].getCurrent() == self.encryptionEnabled:
546                                 self.createSetup()
547                         if self["config"].getCurrent() == self.encryptionType:
548                                 self.createSetup()      
549         def keyLeft(self):
550                 ConfigListScreen.keyLeft(self)
551                 self.newConfig()
552
553         def keyRight(self):
554                 ConfigListScreen.keyRight(self)
555                 self.newConfig()
556
557         def selectionChanged(self):
558                 current = self["config"].getCurrent()
559                 if current == self.hiddenSSID and config.plugins.wlan.essid.value == 'hidden...':
560                         helpwindowpos = self["HelpWindow"].getPosition()
561                         if current[1].help_window.instance is not None:
562                                 current[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
563                                 self["ButtonGreen"].show()
564                                 self["VKeyIcon"].show()
565                                 self["VirtualKB"].setEnabled(True)                      
566                 elif current == self.encryptionKey and config.plugins.wlan.encryption.enabled.value:
567                         helpwindowpos = self["HelpWindow"].getPosition()
568                         if current[1].help_window.instance is not None:
569                                 current[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
570                                 self["ButtonGreen"].show()
571                                 self["VKeyIcon"].show()
572                                 self["VirtualKB"].setEnabled(True)                      
573                 else:   
574                         self["ButtonGreen"].hide()
575                         self["VKeyIcon"].hide()
576                         self["VirtualKB"].setEnabled(False)
577
578         def ok(self):
579                 current = self["config"].getCurrent()
580                 if current == self.hiddenSSID and config.plugins.wlan.essid.value == 'hidden...':
581                         if current[1].help_window.instance is not None:
582                                 current[1].help_window.instance.hide()
583                 elif current == self.encryptionKey and config.plugins.wlan.encryption.enabled.value:
584                         if current[1].help_window.instance is not None:
585                                 current[1].help_window.instance.hide()
586                 self.session.openWithCallback(self.applyConfig, MessageBox, (_("Are you sure you want to activate this network configuration?\n\n") + self.oktext ) )
587
588         def applyConfig(self, ret = False):
589                 if (ret == True):
590                         iNetwork.setAdapterAttribute(self.iface, "up", self.activateInterfaceEntry.value)
591                         iNetwork.setAdapterAttribute(self.iface, "dhcp", self.dhcpConfigEntry.value)
592                         iNetwork.setAdapterAttribute(self.iface, "ip", self.ipConfigEntry.value)
593                         iNetwork.setAdapterAttribute(self.iface, "netmask", self.netmaskConfigEntry.value)
594                         if self.hasGatewayConfigEntry.value:
595                                 iNetwork.setAdapterAttribute(self.iface, "gateway", self.gatewayConfigEntry.value)
596                         else:
597                                 iNetwork.removeAdapterAttribute(self.iface, "gateway")
598                         if self.extended is not None and self.configStrings is not None:
599                                 iNetwork.setAdapterAttribute(self.iface, "configStrings", self.configStrings(self.iface))
600                                 self.ws.writeConfig()
601                         if self.activateInterfaceEntry.value is False:
602                                 iNetwork.deactivateInterface(self.iface)
603                         iNetwork.writeNetworkConfig()                   
604                         iNetwork.restartNetwork(self.applyConfigDataAvail)
605                         self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait while activating your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
606                 else:
607                         self.cancel()
608                         
609         def applyConfigDataAvail(self, data):
610                 if data is True:
611                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
612
613         def getInterfacesDataAvail(self, data):
614                 if data is True:
615                         self.applyConfigRef.close(True)
616
617         def applyConfigfinishedCB(self,data):
618                 if data is True:
619                         num_configured_if = len(iNetwork.getConfiguredAdapters())
620                         if num_configured_if >= 2:
621                                 self.session.openWithCallback(self.secondIfaceFoundCB, MessageBox, _("Your network configuration has been activated.\nA second configured interface has been found.\n\nDo you want to disable the second networkinterface?"), default = True)
622                         else:
623                                 if self.finished_cb:
624                                         self.session.openWithCallback(self.finished_cb, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
625                                 else:
626                                         self.session.openWithCallback(self.ConfigfinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
627         
628         def secondIfaceFoundCB(self,data):
629                 if data is False:
630                         self.close('ok')
631                 else:
632                         configuredInterfaces = iNetwork.getConfiguredAdapters()
633                         for interface in configuredInterfaces:
634                                 if interface == self.iface:
635                                         continue
636                                 iNetwork.setAdapterAttribute(interface, "up", False)
637                                 iNetwork.deactivateInterface(interface)
638                                 self.applyConfig(True)
639                         
640         def ConfigfinishedCB(self,data):
641                 if data is True:
642                         self.close('ok')
643
644         def cancel(self):
645                 iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
646                 self.activateInterfaceEntry.value = self.oldInterfaceState
647                 if self.activateInterfaceEntry.value is False:
648                         iNetwork.deactivateInterface(self.iface)
649                 iNetwork.getInterfaces()
650                 self.close('cancel')
651
652         def runAsync(self, finished_cb):
653                 self.finished_cb = finished_cb
654                 self.ok()
655                 
656         def NameserverSetupClosed(self, *ret):
657                 iNetwork.loadNameserverConfig()
658                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
659                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
660                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
661                 self.createSetup()
662                 self.layoutFinished()
663                 
664         def cleanup(self):
665                 iNetwork.stopLinkStateConsole()
666                 iNetwork.stopRestartConsole()   
667
668 class AdapterSetupConfiguration(Screen, HelpableScreen):
669         def __init__(self, session,iface):
670                 Screen.__init__(self, session)
671                 HelpableScreen.__init__(self)
672                 self.session = session
673                 self.iface = iface
674                 self.restartLanRef = None
675                 self.mainmenu = self.genMainMenu()
676                 self["menulist"] = MenuList(self.mainmenu)
677                 self["description"] = Label()
678                 self["IFtext"] = Label()
679                 self["IF"] = Label()
680                 self["BottomBG"] = Label()
681                 self["Statustext"] = Label()
682                 self["statuspic"] = MultiPixmap()
683                 self["statuspic"].hide()
684                 self["BottomBG"] = Pixmap()
685                 self["ButtonRed"] = Pixmap()
686                 self["ButtonRedtext"] = Label(_("Close"))
687                 
688                 self.oktext = _("Press OK on your remote control to continue.")
689                 self.reboottext = _("Your Dreambox will restart after pressing OK on your remote control.")
690                 self.errortext = _("No working wireless interface found.\n Please verify that you have attached a compatible WLAN device or enable you local network interface.")       
691                 
692                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
693                         {
694                         "up": (self.up, _("move up to previous entry")),
695                         "down": (self.down, _("move down to next entry")),
696                         "left": (self.left, _("move up to first entry")),
697                         "right": (self.right, _("move down to last entry")),
698                         })
699                 
700                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
701                         {
702                         "cancel": (self.close, _("exit networkadapter setup menu")),
703                         "ok": (self.ok, _("select menu entry")),
704                         })
705
706                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
707                         {
708                         "red": (self.close, _("exit networkadapter setup menu")),       
709                         })
710
711                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
712                 {
713                         "ok": self.ok,
714                         "back": self.close,
715                         "up": self.up,
716                         "down": self.down,
717                         "red": self.close,
718                         "left": self.left,
719                         "right": self.right,
720                 }, -2)
721                 
722                 iNetwork.getInterfaces(self.updateStatusbar)
723                 self.onLayoutFinish.append(self.layoutFinished)
724                 self.onClose.append(self.cleanup)
725                 self.onHide.append(self.cleanup)
726
727         def ok(self):
728                 if self["menulist"].getCurrent()[1] == 'edit':
729                         if self.iface == 'wlan0' or self.iface == 'ath0':
730                                 try:
731                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
732                                         from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
733                                 except ImportError:
734                                         self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
735                                 else:
736                                         ifobj = Wireless(self.iface) # a Wireless NIC Object
737                                         self.wlanresponse = ifobj.getStatistics()
738                                         if self.wlanresponse[0] != 19: # Wlan Interface found.
739                                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
740                                         else:
741                                                 # Display Wlan not available Message
742                                                 self.showErrorMessage()
743                         else:
744                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
745                 if self["menulist"].getCurrent()[1] == 'test':
746                         self.session.open(NetworkAdapterTest,self.iface)
747                 if self["menulist"].getCurrent()[1] == 'dns':
748                         self.session.open(NameserverSetup)
749                 if self["menulist"].getCurrent()[1] == 'scanwlan':
750                         try:
751                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
752                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
753                         except ImportError:
754                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
755                         else:
756                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
757                                 self.wlanresponse = ifobj.getStatistics()
758                                 if self.wlanresponse[0] != 19:
759                                         self.session.openWithCallback(self.WlanScanClosed, WlanScan, self.iface)
760                                 else:
761                                         # Display Wlan not available Message
762                                         self.showErrorMessage()
763                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
764                         try:
765                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
766                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
767                         except ImportError:
768                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
769                         else:   
770                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
771                                 self.wlanresponse = ifobj.getStatistics()
772                                 if self.wlanresponse[0] != 19:
773                                         self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
774                                 else:
775                                         # Display Wlan not available Message
776                                         self.showErrorMessage()
777                 if self["menulist"].getCurrent()[1] == 'lanrestart':
778                         self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
779                 if self["menulist"].getCurrent()[1] == 'openwizard':
780                         from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
781                         self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard)
782                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
783                         self.extended = self["menulist"].getCurrent()[1][2]
784                         self.extended(self.session, self.iface)
785         
786         def up(self):
787                 self["menulist"].up()
788                 self.loadDescription()
789
790         def down(self):
791                 self["menulist"].down()
792                 self.loadDescription()
793
794         def left(self):
795                 self["menulist"].pageUp()
796                 self.loadDescription()
797
798         def right(self):
799                 self["menulist"].pageDown()
800                 self.loadDescription()
801
802         def layoutFinished(self):
803                 idx = 0
804                 self["menulist"].moveToIndex(idx)
805                 self.loadDescription()
806
807         def loadDescription(self):
808                 print self["menulist"].getCurrent()[1]
809                 if self["menulist"].getCurrent()[1] == 'edit':
810                         self["description"].setText(_("Edit the network configuration of your Dreambox.\n" ) + self.oktext )
811                 if self["menulist"].getCurrent()[1] == 'test':
812                         self["description"].setText(_("Test the network configuration of your Dreambox.\n" ) + self.oktext )
813                 if self["menulist"].getCurrent()[1] == 'dns':
814                         self["description"].setText(_("Edit the Nameserver configuration of your Dreambox.\n" ) + self.oktext )
815                 if self["menulist"].getCurrent()[1] == 'scanwlan':
816                         self["description"].setText(_("Scan your network for wireless Access Points and connect to them using your WLAN USB Stick\n" ) + self.oktext )
817                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
818                         self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
819                 if self["menulist"].getCurrent()[1] == 'lanrestart':
820                         self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
821                 if self["menulist"].getCurrent()[1] == 'openwizard':
822                         self["description"].setText(_("Use the Networkwizard to configure your Network\n" ) + self.oktext )
823                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
824                         self["description"].setText(_(self["menulist"].getCurrent()[1][1]) + self.oktext )
825                 
826         def updateStatusbar(self, data = None):
827                 self["IFtext"].setText(_("Network:"))
828                 self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
829                 self["Statustext"].setText(_("Link:"))
830                 
831                 if self.iface == 'wlan0' or self.iface == 'ath0':
832                         try:
833                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
834                         except:
835                                         self["statuspic"].setPixmapNum(1)
836                                         self["statuspic"].show()
837                         else:
838                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
839                 else:
840                         iNetwork.getLinkState(self.iface,self.dataAvail)
841
842         def doNothing(self):
843                 pass
844
845         def genMainMenu(self):
846                 menu = []
847                 menu.append((_("Adapter settings"), "edit"))
848                 menu.append((_("Nameserver settings"), "dns"))
849                 menu.append((_("Network test"), "test"))
850                 menu.append((_("Restart network"), "lanrestart"))
851
852                 self.extended = None
853                 self.extendedSetup = None               
854                 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
855                         callFnc = p.__call__["ifaceSupported"](self.iface)
856                         if callFnc is not None:
857                                 self.extended = callFnc
858                                 print p.__call__
859                                 if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
860                                         menu.append((_("Scan Wireless Networks"), "scanwlan"))
861                                         if iNetwork.getAdapterAttribute(self.iface, "up"):
862                                                 menu.append((_("Show WLAN Status"), "wlanstatus"))
863                                 else:
864                                         if p.__call__.has_key("menuEntryName"):
865                                                 menuEntryName = p.__call__["menuEntryName"](self.iface)
866                                         else:
867                                                 menuEntryName = _('Extended Setup...')
868                                         if p.__call__.has_key("menuEntryDescription"):
869                                                 menuEntryDescription = p.__call__["menuEntryDescription"](self.iface)
870                                         else:
871                                                 menuEntryDescription = _('Extended Networksetup Plugin...')
872                                         self.extendedSetup = ('extendedSetup',menuEntryDescription, self.extended)
873                                         menu.append((menuEntryName,self.extendedSetup))                                 
874                         
875                 if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
876                         menu.append((_("NetworkWizard"), "openwizard"))
877
878                 return menu
879
880         def AdapterSetupClosed(self, *ret):
881                 if ret is not None and len(ret):
882                         if ret[0] == 'ok' and (self.iface == 'wlan0' or self.iface == 'ath0') and iNetwork.getAdapterAttribute(self.iface, "up") is True:
883                                 try:
884                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
885                                         from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
886                                 except ImportError:
887                                         self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
888                                 else:   
889                                         ifobj = Wireless(self.iface) # a Wireless NIC Object
890                                         self.wlanresponse = ifobj.getStatistics()
891                                         if self.wlanresponse[0] != 19:
892                                                 self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
893                                         else:
894                                                 # Display Wlan not available Message
895                                                 self.showErrorMessage()
896                         else:
897                                 self.mainmenu = self.genMainMenu()
898                                 self["menulist"].l.setList(self.mainmenu)
899                                 iNetwork.getInterfaces(self.updateStatusbar)
900                 else:
901                         self.mainmenu = self.genMainMenu()
902                         self["menulist"].l.setList(self.mainmenu)
903                         iNetwork.getInterfaces(self.updateStatusbar)
904
905         def WlanStatusClosed(self, *ret):
906                 if ret is not None and len(ret):
907                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
908                         iStatus.stopWlanConsole()
909                         self.mainmenu = self.genMainMenu()
910                         self["menulist"].l.setList(self.mainmenu)
911                         iNetwork.getInterfaces(self.updateStatusbar)
912
913         def WlanScanClosed(self,*ret):
914                 if ret[0] is not None:
915                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,ret[0],ret[1])
916                 else:
917                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,None,None)
918
919         def restartLan(self, ret = False):
920                 if (ret == True):
921                         iNetwork.restartNetwork(self.restartLanDataAvail)
922                         self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
923                         
924         def restartLanDataAvail(self, data):
925                 if data is True:
926                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
927
928         def getInterfacesDataAvail(self, data):
929                 if data is True:
930                         self.restartLanRef.close(True)
931
932         def restartfinishedCB(self,data):
933                 if data is True:
934                         self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
935
936         def dataAvail(self,data):
937                 self.output = data.strip()
938                 result = self.output.split('\n')
939                 pattern = re_compile("Link detected: yes")
940                 for item in result:
941                         if re_search(pattern, item):
942                                 self["statuspic"].setPixmapNum(1)
943                         else:
944                                 self["statuspic"].setPixmapNum(0)
945                 self["statuspic"].show()
946
947         def showErrorMessage(self):
948                 self.session.open(MessageBox, self.errortext, type = MessageBox.TYPE_INFO,timeout = 10 )
949                 
950         def cleanup(self):
951                 iNetwork.stopLinkStateConsole()
952                 try:
953                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
954                 except ImportError:
955                         pass
956                 else:
957                         iStatus.stopWlanConsole()
958
959         def getInfoCB(self,data,status):
960                 if data is not None:
961                         if data is True:
962                                 if status is not None:
963                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
964                                                 self["statuspic"].setPixmapNum(1)
965                                         else:
966                                                 self["statuspic"].setPixmapNum(0)
967                                         self["statuspic"].show()
968
969 class NetworkAdapterTest(Screen):       
970         def __init__(self, session,iface):
971                 Screen.__init__(self, session)
972                 self.iface = iface
973                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
974                 iNetwork.getInterfaces()
975                 self.setLabels()
976                 self.onClose.append(self.cleanup)
977                 self.onHide.append(self.cleanup)
978                 
979                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
980                 {
981                         "ok": self.KeyOK,
982                         "blue": self.KeyOK,
983                         "up": lambda: self.updownhandler('up'),
984                         "down": lambda: self.updownhandler('down'),
985                 
986                 }, -2)
987                 
988                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
989                 {
990                         "red": self.cancel,
991                         "back": self.cancel,
992                 }, -2)
993                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
994                 {
995                         "red": self.closeInfo,
996                         "back": self.closeInfo,
997                 }, -2)
998                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
999                 {
1000                         "green": self.KeyGreen,
1001                 }, -2)
1002                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
1003                 {
1004                         "green": self.KeyGreenRestart,
1005                 }, -2)
1006                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
1007                 {
1008                         "yellow": self.KeyYellow,
1009                 }, -2)
1010                 
1011                 self["shortcutsgreen_restart"].setEnabled(False)
1012                 self["updown_actions"].setEnabled(False)
1013                 self["infoshortcuts"].setEnabled(False)
1014                 self.onClose.append(self.delTimer)      
1015                 self.onLayoutFinish.append(self.layoutFinished)
1016                 self.steptimer = False
1017                 self.nextstep = 0
1018                 self.activebutton = 0
1019                 self.nextStepTimer = eTimer()
1020                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
1021
1022         def cancel(self):
1023                 if self.oldInterfaceState is False:
1024                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
1025                         iNetwork.deactivateInterface(self.iface)
1026                 self.close()
1027
1028         def closeInfo(self):
1029                 self["shortcuts"].setEnabled(True)              
1030                 self["infoshortcuts"].setEnabled(False)
1031                 self["InfoText"].hide()
1032                 self["InfoTextBorder"].hide()
1033                 self["ButtonRedtext"].setText(_("Close"))
1034
1035         def delTimer(self):
1036                 del self.steptimer
1037                 del self.nextStepTimer
1038
1039         def nextStepTimerFire(self):
1040                 self.nextStepTimer.stop()
1041                 self.steptimer = False
1042                 self.runTest()
1043
1044         def updownhandler(self,direction):
1045                 if direction == 'up':
1046                         if self.activebutton >=2:
1047                                 self.activebutton -= 1
1048                         else:
1049                                 self.activebutton = 6
1050                         self.setActiveButton(self.activebutton)
1051                 if direction == 'down':
1052                         if self.activebutton <=5:
1053                                 self.activebutton += 1
1054                         else:
1055                                 self.activebutton = 1
1056                         self.setActiveButton(self.activebutton)
1057
1058         def setActiveButton(self,button):
1059                 if button == 1:
1060                         self["EditSettingsButton"].setPixmapNum(0)
1061                         self["EditSettings_Text"].setForegroundColorNum(0)
1062                         self["NetworkInfo"].setPixmapNum(0)
1063                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1064                         self["AdapterInfo"].setPixmapNum(1)               # active
1065                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
1066                 if button == 2:
1067                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1068                         self["AdapterInfo"].setPixmapNum(0)
1069                         self["DhcpInfo"].setPixmapNum(0)
1070                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1071                         self["NetworkInfo"].setPixmapNum(1)               # active
1072                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
1073                 if button == 3:
1074                         self["NetworkInfo"].setPixmapNum(0)
1075                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1076                         self["IPInfo"].setPixmapNum(0)
1077                         self["IPInfo_Text"].setForegroundColorNum(1)
1078                         self["DhcpInfo"].setPixmapNum(1)                  # active
1079                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
1080                 if button == 4:
1081                         self["DhcpInfo"].setPixmapNum(0)
1082                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1083                         self["DNSInfo"].setPixmapNum(0)
1084                         self["DNSInfo_Text"].setForegroundColorNum(1)
1085                         self["IPInfo"].setPixmapNum(1)                  # active
1086                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
1087                 if button == 5:
1088                         self["IPInfo"].setPixmapNum(0)
1089                         self["IPInfo_Text"].setForegroundColorNum(1)
1090                         self["EditSettingsButton"].setPixmapNum(0)
1091                         self["EditSettings_Text"].setForegroundColorNum(0)
1092                         self["DNSInfo"].setPixmapNum(1)                 # active
1093                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
1094                 if button == 6:
1095                         self["DNSInfo"].setPixmapNum(0)
1096                         self["DNSInfo_Text"].setForegroundColorNum(1)
1097                         self["EditSettingsButton"].setPixmapNum(1)         # active
1098                         self["EditSettings_Text"].setForegroundColorNum(2) # active
1099                         self["AdapterInfo"].setPixmapNum(0)
1100                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1101                         
1102         def runTest(self):
1103                 next = self.nextstep
1104                 if next == 0:
1105                         self.doStep1()
1106                 elif next == 1:
1107                         self.doStep2()
1108                 elif next == 2:
1109                         self.doStep3()
1110                 elif next == 3:
1111                         self.doStep4()
1112                 elif next == 4:
1113                         self.doStep5()
1114                 elif next == 5:
1115                         self.doStep6()
1116                 self.nextstep += 1
1117
1118         def doStep1(self):
1119                 self.steptimer = True
1120                 self.nextStepTimer.start(3000)
1121                 self["ButtonYellow_Check"].show()
1122                 self["ButtonYellowtext"].show()
1123
1124         def doStep2(self):
1125                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
1126                 self["Adapter"].setForegroundColorNum(2)
1127                 self["Adaptertext"].setForegroundColorNum(1)
1128                 self["AdapterInfo_Text"].setForegroundColorNum(1)
1129                 self["AdapterInfo_OK"].show()
1130                 self.steptimer = True
1131                 self.nextStepTimer.start(3000)
1132
1133         def doStep3(self):
1134                 self["Networktext"].setForegroundColorNum(1)
1135                 self["Network"].setText(_("Please wait..."))
1136                 self.getLinkState(self.iface)
1137                 self["NetworkInfo_Text"].setForegroundColorNum(1)
1138                 self.steptimer = True
1139                 self.nextStepTimer.start(3000)
1140
1141         def doStep4(self):
1142                 self["Dhcptext"].setForegroundColorNum(1)
1143                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
1144                         self["Dhcp"].setForegroundColorNum(2)
1145                         self["Dhcp"].setText(_("enabled"))
1146                         self["DhcpInfo_Check"].setPixmapNum(0)
1147                 else:
1148                         self["Dhcp"].setForegroundColorNum(1)
1149                         self["Dhcp"].setText(_("disabled"))
1150                         self["DhcpInfo_Check"].setPixmapNum(1)
1151                 self["DhcpInfo_Check"].show()
1152                 self["DhcpInfo_Text"].setForegroundColorNum(1)
1153                 self.steptimer = True
1154                 self.nextStepTimer.start(3000)
1155
1156         def doStep5(self):
1157                 self["IPtext"].setForegroundColorNum(1)
1158                 self["IP"].setText(_("Please wait..."))
1159                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
1160
1161         def doStep6(self):
1162                 self.steptimer = False
1163                 self.nextStepTimer.stop()
1164                 self["DNStext"].setForegroundColorNum(1)
1165                 self["DNS"].setText(_("Please wait..."))
1166                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1167
1168         def KeyGreen(self):
1169                 self["shortcutsgreen"].setEnabled(False)
1170                 self["shortcutsyellow"].setEnabled(True)
1171                 self["updown_actions"].setEnabled(False)
1172                 self["ButtonYellow_Check"].setPixmapNum(0)
1173                 self["ButtonGreen_Check"].setPixmapNum(1)
1174                 self.steptimer = True
1175                 self.nextStepTimer.start(1000)
1176
1177         def KeyGreenRestart(self):
1178                 self.nextstep = 0
1179                 self.layoutFinished()
1180                 self["Adapter"].setText((""))
1181                 self["Network"].setText((""))
1182                 self["Dhcp"].setText((""))
1183                 self["IP"].setText((""))
1184                 self["DNS"].setText((""))
1185                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1186                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1187                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1188                 self["IPInfo_Text"].setForegroundColorNum(0)
1189                 self["DNSInfo_Text"].setForegroundColorNum(0)
1190                 self["shortcutsgreen_restart"].setEnabled(False)
1191                 self["shortcutsgreen"].setEnabled(False)
1192                 self["shortcutsyellow"].setEnabled(True)
1193                 self["updown_actions"].setEnabled(False)
1194                 self["ButtonYellow_Check"].setPixmapNum(0)
1195                 self["ButtonGreen_Check"].setPixmapNum(1)
1196                 self.steptimer = True
1197                 self.nextStepTimer.start(1000)
1198
1199         def KeyOK(self):
1200                 self["infoshortcuts"].setEnabled(True)
1201                 self["shortcuts"].setEnabled(False)
1202                 if self.activebutton == 1: # Adapter Check
1203                         self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
1204                         self["InfoTextBorder"].show()
1205                         self["InfoText"].show()
1206                         self["ButtonRedtext"].setText(_("Back"))
1207                 if self.activebutton == 2: #LAN Check
1208                         self["InfoText"].setText(_("This test checks whether a network cable is connected to your LAN-Adapter.\nIf you get a \"disconnected\" message:\n- verify that a network cable is attached\n- verify that the cable is not broken"))
1209                         self["InfoTextBorder"].show()
1210                         self["InfoText"].show()
1211                         self["ButtonRedtext"].setText(_("Back"))
1212                 if self.activebutton == 3: #DHCP Check
1213                         self["InfoText"].setText(_("This test checks whether your LAN Adapter is set up for automatic IP Address configuration with DHCP.\nIf you get a \"disabled\" message:\n - then your LAN Adapter is configured for manual IP Setup\n- verify thay you have entered correct IP informations in the AdapterSetup dialog.\nIf you get an \"enabeld\" message:\n-verify that you have a configured and working DHCP Server in your network."))
1214                         self["InfoTextBorder"].show()
1215                         self["InfoText"].show()
1216                         self["ButtonRedtext"].setText(_("Back"))
1217                 if self.activebutton == 4: # IP Check
1218                         self["InfoText"].setText(_("This test checks whether a valid IP Address is found for your LAN Adapter.\nIf you get a \"unconfirmed\" message:\n- no valid IP Address was found\n- please check your DHCP, cabling and adapter setup"))
1219                         self["InfoTextBorder"].show()
1220                         self["InfoText"].show()
1221                         self["ButtonRedtext"].setText(_("Back"))
1222                 if self.activebutton == 5: # DNS Check
1223                         self["InfoText"].setText(_("This test checks for configured Nameservers.\nIf you get a \"unconfirmed\" message:\n- please check your DHCP, cabling and Adapter setup\n- if you configured your Nameservers manually please verify your entries in the \"Nameserver\" Configuration"))
1224                         self["InfoTextBorder"].show()
1225                         self["InfoText"].show()
1226                         self["ButtonRedtext"].setText(_("Back"))
1227                 if self.activebutton == 6: # Edit Settings
1228                         self.session.open(AdapterSetup,self.iface)
1229
1230         def KeyYellow(self):
1231                 self.nextstep = 0
1232                 self["shortcutsgreen_restart"].setEnabled(True)
1233                 self["shortcutsgreen"].setEnabled(False)
1234                 self["shortcutsyellow"].setEnabled(False)
1235                 self["ButtonGreentext"].setText(_("Restart test"))
1236                 self["ButtonYellow_Check"].setPixmapNum(1)
1237                 self["ButtonGreen_Check"].setPixmapNum(0)
1238                 self.steptimer = False
1239                 self.nextStepTimer.stop()
1240
1241         def layoutFinished(self):
1242                 self["shortcutsyellow"].setEnabled(False)
1243                 self["AdapterInfo_OK"].hide()
1244                 self["NetworkInfo_Check"].hide()
1245                 self["DhcpInfo_Check"].hide()
1246                 self["IPInfo_Check"].hide()
1247                 self["DNSInfo_Check"].hide()
1248                 self["EditSettings_Text"].hide()
1249                 self["EditSettingsButton"].hide()
1250                 self["InfoText"].hide()
1251                 self["InfoTextBorder"].hide()
1252                 self["ButtonYellow_Check"].hide()
1253                 self["ButtonYellowtext"].hide()
1254
1255         def setLabels(self):
1256                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1257                 self["Adapter"] = MultiColorLabel()
1258                 self["AdapterInfo"] = MultiPixmap()
1259                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1260                 self["AdapterInfo_OK"] = Pixmap()
1261                 
1262                 if self.iface == 'wlan0' or self.iface == 'ath0':
1263                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1264                 else:
1265                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1266                 
1267                 self["Network"] = MultiColorLabel()
1268                 self["NetworkInfo"] = MultiPixmap()
1269                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1270                 self["NetworkInfo_Check"] = MultiPixmap()
1271                 
1272                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1273                 self["Dhcp"] = MultiColorLabel()
1274                 self["DhcpInfo"] = MultiPixmap()
1275                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1276                 self["DhcpInfo_Check"] = MultiPixmap()
1277                 
1278                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1279                 self["IP"] = MultiColorLabel()
1280                 self["IPInfo"] = MultiPixmap()
1281                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1282                 self["IPInfo_Check"] = MultiPixmap()
1283                 
1284                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1285                 self["DNS"] = MultiColorLabel()
1286                 self["DNSInfo"] = MultiPixmap()
1287                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1288                 self["DNSInfo_Check"] = MultiPixmap()
1289                 
1290                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1291                 self["EditSettingsButton"] = MultiPixmap()
1292                 
1293                 self["ButtonRedtext"] = Label(_("Close"))
1294                 self["ButtonRed"] = Pixmap()
1295
1296                 self["ButtonGreentext"] = Label(_("Start test"))
1297                 self["ButtonGreen_Check"] = MultiPixmap()
1298                 
1299                 self["ButtonYellowtext"] = Label(_("Stop test"))
1300                 self["ButtonYellow_Check"] = MultiPixmap()
1301                 
1302                 self["InfoTextBorder"] = Pixmap()
1303                 self["InfoText"] = Label()
1304
1305         def getLinkState(self,iface):
1306                 if iface == 'wlan0' or iface == 'ath0':
1307                         try:
1308                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
1309                         except:
1310                                         self["Network"].setForegroundColorNum(1)
1311                                         self["Network"].setText(_("disconnected"))
1312                                         self["NetworkInfo_Check"].setPixmapNum(1)
1313                                         self["NetworkInfo_Check"].show()
1314                         else:
1315                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
1316                 else:
1317                         iNetwork.getLinkState(iface,self.LinkStatedataAvail)
1318
1319         def LinkStatedataAvail(self,data):
1320                 self.output = data.strip()
1321                 result = self.output.split('\n')
1322                 pattern = re_compile("Link detected: yes")
1323                 for item in result:
1324                         if re_search(pattern, item):
1325                                 self["Network"].setForegroundColorNum(2)
1326                                 self["Network"].setText(_("connected"))
1327                                 self["NetworkInfo_Check"].setPixmapNum(0)
1328                         else:
1329                                 self["Network"].setForegroundColorNum(1)
1330                                 self["Network"].setText(_("disconnected"))
1331                                 self["NetworkInfo_Check"].setPixmapNum(1)
1332                 self["NetworkInfo_Check"].show()
1333
1334         def NetworkStatedataAvail(self,data):
1335                 if data <= 2:
1336                         self["IP"].setForegroundColorNum(2)
1337                         self["IP"].setText(_("confirmed"))
1338                         self["IPInfo_Check"].setPixmapNum(0)
1339                 else:
1340                         self["IP"].setForegroundColorNum(1)
1341                         self["IP"].setText(_("unconfirmed"))
1342                         self["IPInfo_Check"].setPixmapNum(1)
1343                 self["IPInfo_Check"].show()
1344                 self["IPInfo_Text"].setForegroundColorNum(1)            
1345                 self.steptimer = True
1346                 self.nextStepTimer.start(3000)          
1347                 
1348         def DNSLookupdataAvail(self,data):
1349                 if data <= 2:
1350                         self["DNS"].setForegroundColorNum(2)
1351                         self["DNS"].setText(_("confirmed"))
1352                         self["DNSInfo_Check"].setPixmapNum(0)
1353                 else:
1354                         self["DNS"].setForegroundColorNum(1)
1355                         self["DNS"].setText(_("unconfirmed"))
1356                         self["DNSInfo_Check"].setPixmapNum(1)
1357                 self["DNSInfo_Check"].show()
1358                 self["DNSInfo_Text"].setForegroundColorNum(1)
1359                 self["EditSettings_Text"].show()
1360                 self["EditSettingsButton"].setPixmapNum(1)
1361                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1362                 self["EditSettingsButton"].show()
1363                 self["ButtonYellow_Check"].setPixmapNum(1)
1364                 self["ButtonGreentext"].setText(_("Restart test"))
1365                 self["ButtonGreen_Check"].setPixmapNum(0)
1366                 self["shortcutsgreen"].setEnabled(False)
1367                 self["shortcutsgreen_restart"].setEnabled(True)
1368                 self["shortcutsyellow"].setEnabled(False)
1369                 self["updown_actions"].setEnabled(True)
1370                 self.activebutton = 6
1371
1372         def getInfoCB(self,data,status):
1373                 if data is not None:
1374                         if data is True:
1375                                 if status is not None:
1376                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
1377                                                 self["Network"].setForegroundColorNum(1)
1378                                                 self["Network"].setText(_("disconnected"))
1379                                                 self["NetworkInfo_Check"].setPixmapNum(1)
1380                                                 self["NetworkInfo_Check"].show()
1381                                         else:
1382                                                 self["Network"].setForegroundColorNum(2)
1383                                                 self["Network"].setText(_("connected"))
1384                                                 self["NetworkInfo_Check"].setPixmapNum(0)
1385                                                 self["NetworkInfo_Check"].show()
1386                                                 
1387         def cleanup(self):
1388                 iNetwork.stopLinkStateConsole()
1389                 iNetwork.stopDNSConsole()
1390                 try:
1391                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
1392                 except ImportError:
1393                         pass
1394                 else:
1395                         iStatus.stopWlanConsole()