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