5d378524de8fcba18dd8707429e5f688eefe4f2d
[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.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
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, aplist=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                         self.aplist = networkinfo[2]
307                 else:
308                         self.iface = networkinfo
309                         self.essid = essid
310                         self.aplist = aplist
311                 self.extended = None
312                 self.applyConfigRef = None
313                 self.finished_cb = None
314                 self.oktext = _("Press OK on your remote control to continue.")
315                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
316
317                 self.createConfig()
318
319                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
320                         {
321                         "cancel": (self.keyCancel, _("exit network adapter configuration")),
322                         "ok": (self.keySave, _("activate network adapter configuration")),
323                         })
324
325                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
326                         {
327                         "red": (self.keyCancel, _("exit network adapter configuration")),
328                         "blue": (self.KeyBlue, _("open nameserver configuration")),
329                         })
330
331                 self["actions"] = NumberActionMap(["SetupActions"],
332                 {
333                         "ok": self.keySave,
334                 }, -2)
335
336                 self.list = []
337                 ConfigListScreen.__init__(self, self.list,session = self.session)
338                 self.createSetup()
339                 self.onLayoutFinish.append(self.layoutFinished)
340                 self.onClose.append(self.cleanup)
341
342                 self["DNS1text"] = StaticText(_("Primary DNS"))
343                 self["DNS2text"] = StaticText(_("Secondary DNS"))
344                 self["DNS1"] = StaticText()
345                 self["DNS2"] = StaticText()
346                 self["introduction"] = StaticText(_("Current settings:"))
347
348                 self["IPtext"] = StaticText(_("IP Address"))
349                 self["Netmasktext"] = StaticText(_("Netmask"))
350                 self["Gatewaytext"] = StaticText(_("Gateway"))
351
352                 self["IP"] = StaticText()
353                 self["Mask"] = StaticText()
354                 self["Gateway"] = StaticText()
355
356                 self["Adaptertext"] = StaticText(_("Network:"))
357                 self["Adapter"] = StaticText()
358                 self["introduction2"] = StaticText(_("Press OK to activate the settings."))
359                 self["key_red"] = StaticText(_("Cancel"))
360                 self["key_blue"] = StaticText(_("Edit DNS"))
361
362                 self["VKeyIcon"] = Boolean(False)
363                 self["HelpWindow"] = Pixmap()
364                 self["HelpWindow"].hide()
365                 
366         def layoutFinished(self):
367                 self["DNS1"].setText(self.primaryDNS.getText())
368                 self["DNS2"].setText(self.secondaryDNS.getText())
369                 if self.ipConfigEntry.getText() is not None:
370                         if self.ipConfigEntry.getText() == "0.0.0.0":
371                                 self["IP"].setText(_("N/A"))
372                         else:   
373                                 self["IP"].setText(self.ipConfigEntry.getText())
374                 else:
375                         self["IP"].setText(_("N/A"))
376                 if self.netmaskConfigEntry.getText() is not None:
377                         if self.netmaskConfigEntry.getText() == "0.0.0.0":
378                                         self["Mask"].setText(_("N/A"))
379                         else:   
380                                 self["Mask"].setText(self.netmaskConfigEntry.getText())
381                 else:
382                         self["IP"].setText(_("N/A"))                    
383                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
384                         if self.gatewayConfigEntry.getText() == "0.0.0.0":
385                                 self["Gatewaytext"].setText(_("Gateway"))
386                                 self["Gateway"].setText(_("N/A"))
387                         else:
388                                 self["Gatewaytext"].setText(_("Gateway"))
389                                 self["Gateway"].setText(self.gatewayConfigEntry.getText())
390                 else:
391                         self["Gateway"].setText("")
392                         self["Gatewaytext"].setText("")
393                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
394
395         def createConfig(self):
396                 self.InterfaceEntry = None
397                 self.dhcpEntry = None
398                 self.gatewayEntry = None
399                 self.hiddenSSID = None
400                 self.wlanSSID = None
401                 self.encryptionEnabled = None
402                 self.encryptionKey = None
403                 self.encryptionType = None
404                 self.nwlist = None
405                 self.encryptionlist = None
406                 self.weplist = None
407                 self.wsconfig = None
408                 self.default = None
409
410                 if iNetwork.isWirelessInterface(self.iface):
411                         from Plugins.SystemPlugins.WirelessLan.Wlan import wpaSupplicant, iWlan
412                         iWlan.setInterface(self.iface)
413                         self.w = iWlan.getInterface()
414                         self.ws = wpaSupplicant()
415                         self.encryptionlist = []
416                         self.encryptionlist.append(("WEP", _("WEP")))
417                         self.encryptionlist.append(("WPA", _("WPA")))
418                         self.encryptionlist.append(("WPA2", _("WPA2")))
419                         self.encryptionlist.append(("WPA/WPA2", _("WPA or WPA2")))
420                         self.weplist = []
421                         self.weplist.append("ASCII")
422                         self.weplist.append("HEX")
423                         if self.aplist is not None:
424                                 self.nwlist = self.aplist
425                                 self.nwlist.sort(key = lambda x: x[0])
426                         else:
427                                 self.nwlist = []
428                                 self.aps = None
429                                 try:
430                                         self.aps = iWlan.getNetworkList()
431                                         if self.aps is not None:
432                                                 for ap in self.aps:
433                                                         a = self.aps[ap]
434                                                         if a['active']:
435                                                                 if a['essid'] != '':
436                                                                         self.nwlist.append((a['essid'],a['essid']))
437                                         self.nwlist.sort(key = lambda x: x[0])
438                                         iWlan.stopGetNetworkList()
439                                 except:
440                                         self.nwlist.append(("No Networks found",_("No Networks found")))
441
442                         self.wsconfig = self.ws.loadConfig(self.iface)
443                         if self.essid is not None: # ssid from wlan scan
444                                 self.default = self.essid
445                         else:
446                                 self.default = self.wsconfig['ssid']
447
448                         if "hidden..." not in self.nwlist:
449                                 self.nwlist.append(("hidden...",_("enter hidden network SSID")))
450                         if self.default not in self.nwlist:
451                                 self.nwlist.append((self.default,self.default))
452                         config.plugins.wlan.essid = NoSave(ConfigSelection(self.nwlist, default = self.default ))
453                         config.plugins.wlan.hiddenessid = NoSave(ConfigText(default = self.wsconfig['hiddenessid'], visible_width = 50, fixed_size = False))
454
455                         config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = self.wsconfig['encryption'] ))
456                         config.plugins.wlan.encryption.type = NoSave(ConfigSelection(self.encryptionlist, default = self.wsconfig['encryption_type'] ))
457                         config.plugins.wlan.encryption.wepkeytype = NoSave(ConfigSelection(self.weplist, default = self.wsconfig['encryption_wepkeytype'] ))
458                         config.plugins.wlan.encryption.psk = NoSave(ConfigPassword(default = self.wsconfig['key'], visible_width = 50, fixed_size = False))
459
460                 self.activateInterfaceEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "up") or False))
461                 self.dhcpConfigEntry = NoSave(ConfigYesNo(default=iNetwork.getAdapterAttribute(self.iface, "dhcp") or False))
462                 self.ipConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "ip")) or [0,0,0,0])
463                 self.netmaskConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "netmask") or [255,0,0,0]))
464                 if iNetwork.getAdapterAttribute(self.iface, "gateway"):
465                         self.dhcpdefault=True
466                 else:
467                         self.dhcpdefault=False
468                 self.hasGatewayConfigEntry = NoSave(ConfigYesNo(default=self.dhcpdefault or False))
469                 self.gatewayConfigEntry = NoSave(ConfigIP(default=iNetwork.getAdapterAttribute(self.iface, "gateway") or [0,0,0,0]))
470                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
471                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
472                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
473
474         def createSetup(self):
475                 self.list = []
476                 self.InterfaceEntry = getConfigListEntry(_("Use Interface"), self.activateInterfaceEntry)
477
478                 self.list.append(self.InterfaceEntry)
479                 if self.activateInterfaceEntry.value:
480                         self.dhcpEntry = getConfigListEntry(_("Use DHCP"), self.dhcpConfigEntry)
481                         self.list.append(self.dhcpEntry)
482                         if not self.dhcpConfigEntry.value:
483                                 self.list.append(getConfigListEntry(_('IP Address'), self.ipConfigEntry))
484                                 self.list.append(getConfigListEntry(_('Netmask'), self.netmaskConfigEntry))
485                                 self.gatewayEntry = getConfigListEntry(_('Use a gateway'), self.hasGatewayConfigEntry)
486                                 self.list.append(self.gatewayEntry)
487                                 if self.hasGatewayConfigEntry.value:
488                                         self.list.append(getConfigListEntry(_('Gateway'), self.gatewayConfigEntry))
489
490                         self.extended = None
491                         self.configStrings = None
492                         for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
493                                 callFnc = p.__call__["ifaceSupported"](self.iface)
494                                 if callFnc is not None:
495                                         if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
496                                                 self.extended = callFnc
497                                                 if p.__call__.has_key("configStrings"):
498                                                         self.configStrings = p.__call__["configStrings"]
499
500                                                 if config.plugins.wlan.essid.value == 'hidden...':
501                                                         self.wlanSSID = getConfigListEntry(_("Network SSID"), config.plugins.wlan.essid)
502                                                         self.list.append(self.wlanSSID)
503                                                         self.hiddenSSID = getConfigListEntry(_("Hidden network SSID"), config.plugins.wlan.hiddenessid)
504                                                         self.list.append(self.hiddenSSID)
505                                                 else:
506                                                         self.wlanSSID = getConfigListEntry(_("Network SSID"), config.plugins.wlan.essid)
507                                                         self.list.append(self.wlanSSID)
508                                                 self.encryptionEnabled = getConfigListEntry(_("Encryption"), config.plugins.wlan.encryption.enabled)
509                                                 self.list.append(self.encryptionEnabled)
510                                                 
511                                                 if config.plugins.wlan.encryption.enabled.value:
512                                                         self.encryptionType = getConfigListEntry(_("Encryption Type"), config.plugins.wlan.encryption.type)
513                                                         self.list.append(self.encryptionType)
514                                                         if config.plugins.wlan.encryption.type.value == 'WEP':
515                                                                 self.list.append(getConfigListEntry(_("Encryption Keytype"), config.plugins.wlan.encryption.wepkeytype))
516                                                                 self.encryptionKey = getConfigListEntry(_("Encryption Key"), config.plugins.wlan.encryption.psk)
517                                                                 self.list.append(self.encryptionKey)
518                                                         else:
519                                                                 self.encryptionKey = getConfigListEntry(_("Encryption Key"), config.plugins.wlan.encryption.psk)
520                                                                 self.list.append(self.encryptionKey)
521
522                 self["config"].list = self.list
523                 self["config"].l.setList(self.list)
524
525         def KeyBlue(self):
526                 self.session.openWithCallback(self.NameserverSetupClosed, NameserverSetup)
527
528         def newConfig(self):
529                 if self["config"].getCurrent() == self.InterfaceEntry:
530                         self.createSetup()
531                 if self["config"].getCurrent() == self.dhcpEntry:
532                         self.createSetup()
533                 if self["config"].getCurrent() == self.gatewayEntry:
534                         self.createSetup()
535                 if iNetwork.isWirelessInterface(self.iface):    
536                         if self["config"].getCurrent() == self.wlanSSID:
537                                 self.createSetup()
538                         if self["config"].getCurrent() == self.encryptionEnabled:
539                                 self.createSetup()
540                         if self["config"].getCurrent() == self.encryptionType:
541                                 self.createSetup()
542
543         def keyLeft(self):
544                 ConfigListScreen.keyLeft(self)
545                 self.newConfig()
546
547         def keyRight(self):
548                 ConfigListScreen.keyRight(self)
549                 self.newConfig()
550         
551         def keySave(self):
552                 self.hideInputHelp()
553                 if self["config"].isChanged():
554                         self.session.openWithCallback(self.keySaveConfirm, MessageBox, (_("Are you sure you want to activate this network configuration?\n\n") + self.oktext ) )
555                 else:
556                         if self.finished_cb:
557                                 self.finished_cb()
558                         else:
559                                 self.close('cancel')
560
561         def keySaveConfirm(self, ret = False):
562                 if (ret == True):               
563                         num_configured_if = len(iNetwork.getConfiguredAdapters())
564                         if num_configured_if >= 1:
565                                 if self.iface in iNetwork.getConfiguredAdapters():      
566                                         self.applyConfig(True)
567                                 else:
568                                         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)
569                         else:
570                                 self.applyConfig(True)
571                 else:
572                         self.keyCancel()                
573
574         def secondIfaceFoundCB(self,data):
575                 if data is False:
576                         self.applyConfig(True)
577                 else:
578                         configuredInterfaces = iNetwork.getConfiguredAdapters()
579                         for interface in configuredInterfaces:
580                                 if interface == self.iface:
581                                         continue
582                                 iNetwork.setAdapterAttribute(interface, "up", False)
583                         iNetwork.deactivateInterface(configuredInterfaces,self.deactivateSecondInterfaceCB)
584
585         def deactivateSecondInterfaceCB(self, data):
586                 if data is True:
587                         self.applyConfig(True)
588
589         def applyConfig(self, ret = False):
590                 if (ret == True):
591                         self.applyConfigRef = None
592                         iNetwork.setAdapterAttribute(self.iface, "up", self.activateInterfaceEntry.value)
593                         iNetwork.setAdapterAttribute(self.iface, "dhcp", self.dhcpConfigEntry.value)
594                         iNetwork.setAdapterAttribute(self.iface, "ip", self.ipConfigEntry.value)
595                         iNetwork.setAdapterAttribute(self.iface, "netmask", self.netmaskConfigEntry.value)
596                         if self.hasGatewayConfigEntry.value:
597                                 iNetwork.setAdapterAttribute(self.iface, "gateway", self.gatewayConfigEntry.value)
598                         else:
599                                 iNetwork.removeAdapterAttribute(self.iface, "gateway")
600                         if self.extended is not None and self.configStrings is not None:
601                                 iNetwork.setAdapterAttribute(self.iface, "configStrings", self.configStrings(self.iface))
602                                 self.ws.writeConfig(self.iface)
603
604                         if self.activateInterfaceEntry.value is False:
605                                 iNetwork.deactivateInterface(self.iface,self.deactivateInterfaceCB)
606                                 iNetwork.writeNetworkConfig()
607                                 self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
608                         else:
609                                 iNetwork.deactivateInterface(self.iface,self.activateInterfaceCB)
610                                 iNetwork.writeNetworkConfig()
611                                 self.applyConfigRef = self.session.openWithCallback(self.applyConfigfinishedCB, MessageBox, _("Please wait for activation of your network configuration..."), type = MessageBox.TYPE_INFO, enable_input = False)
612                 else:
613                         self.keyCancel()
614
615         def deactivateInterfaceCB(self, data):
616                 if data is True:
617                         self.applyConfigDataAvail(True)
618
619         def activateInterfaceCB(self, data):
620                 if data is True:
621                         iNetwork.activateInterface(self.iface,self.applyConfigDataAvail)
622
623         def applyConfigDataAvail(self, data):
624                 if data is True:
625                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
626
627         def getInterfacesDataAvail(self, data):
628                 if data is True:
629                         self.applyConfigRef.close(True)
630
631         def applyConfigfinishedCB(self,data):
632                 if data is True:
633                         if self.finished_cb:
634                                 self.session.openWithCallback(lambda x : self.finished_cb(), MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
635                         else:
636                                 self.session.openWithCallback(self.ConfigfinishedCB, MessageBox, _("Your network configuration has been activated."), type = MessageBox.TYPE_INFO, timeout = 10)
637
638         def ConfigfinishedCB(self,data):
639                 if data is not None:
640                         if data is True:
641                                 self.close('ok')
642
643         def keyCancelConfirm(self, result):
644                 if not result:
645                         return
646                 if self.oldInterfaceState is False:
647                         iNetwork.deactivateInterface(self.iface,self.keyCancelCB)
648                 else:
649                         self.close('cancel')
650
651         def keyCancel(self):
652                 self.hideInputHelp()
653                 if self["config"].isChanged():
654                         self.session.openWithCallback(self.keyCancelConfirm, MessageBox, _("Really close without saving settings?"))
655                 else:
656                         self.close('cancel')
657
658         def keyCancelCB(self,data):
659                 if data is not None:
660                         if data is True:
661                                 self.close('cancel')
662
663         def runAsync(self, finished_cb):
664                 self.finished_cb = finished_cb
665                 self.keySave()
666
667         def NameserverSetupClosed(self, *ret):
668                 iNetwork.loadNameserverConfig()
669                 nameserver = (iNetwork.getNameserverList() + [[0,0,0,0]] * 2)[0:2]
670                 self.primaryDNS = NoSave(ConfigIP(default=nameserver[0]))
671                 self.secondaryDNS = NoSave(ConfigIP(default=nameserver[1]))
672                 self.createSetup()
673                 self.layoutFinished()
674
675         def cleanup(self):
676                 iNetwork.stopLinkStateConsole()
677                 
678         def hideInputHelp(self):
679                 current = self["config"].getCurrent()
680                 if current == self.hiddenSSID and config.plugins.wlan.essid.value == 'hidden...':
681                         if current[1].help_window.instance is not None:
682                                 current[1].help_window.instance.hide()
683                 elif current == self.encryptionKey and config.plugins.wlan.encryption.enabled.value:
684                         if current[1].help_window.instance is not None:
685                                 current[1].help_window.instance.hide()
686
687
688 class AdapterSetupConfiguration(Screen, HelpableScreen):
689         def __init__(self, session,iface):
690                 Screen.__init__(self, session)
691                 HelpableScreen.__init__(self)
692                 self.session = session
693                 self.iface = iface
694                 self.restartLanRef = None
695                 self.LinkState = None
696                 self.mainmenu = self.genMainMenu()
697                 self["menulist"] = MenuList(self.mainmenu)
698                 self["key_red"] = StaticText(_("Close"))
699                 self["description"] = StaticText()
700                 self["IFtext"] = StaticText()
701                 self["IF"] = StaticText()
702                 self["Statustext"] = StaticText()
703                 self["statuspic"] = MultiPixmap()
704                 self["statuspic"].hide()
705                 
706                 self.oktext = _("Press OK on your remote control to continue.")
707                 self.reboottext = _("Your Dreambox will restart after pressing OK on your remote control.")
708                 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.")
709                 self.missingwlanplugintxt = _("The wireless LAN plugin is not installed!\nPlease install it.")
710                 
711                 self["WizardActions"] = HelpableActionMap(self, "WizardActions",
712                         {
713                         "up": (self.up, _("move up to previous entry")),
714                         "down": (self.down, _("move down to next entry")),
715                         "left": (self.left, _("move up to first entry")),
716                         "right": (self.right, _("move down to last entry")),
717                         })
718                 
719                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
720                         {
721                         "cancel": (self.close, _("exit networkadapter setup menu")),
722                         "ok": (self.ok, _("select menu entry")),
723                         })
724
725                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
726                         {
727                         "red": (self.close, _("exit networkadapter setup menu")),       
728                         })
729
730                 self["actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
731                 {
732                         "ok": self.ok,
733                         "back": self.close,
734                         "up": self.up,
735                         "down": self.down,
736                         "red": self.close,
737                         "left": self.left,
738                         "right": self.right,
739                 }, -2)
740                 
741                 self.updateStatusbar()
742                 self.onLayoutFinish.append(self.layoutFinished)
743                 self.onClose.append(self.cleanup)
744
745
746         def queryWirelessDevice(self,iface):
747                 try:
748                         from pythonwifi.iwlibs import Wireless
749                         import errno
750                 except ImportError:
751                         return False
752                 else:
753                         try:
754                                 ifobj = Wireless(iface) # a Wireless NIC Object
755                                 wlanresponse = ifobj.getAPaddr()
756                         except IOError, (error_no, error_str):
757                                 if error_no in (errno.EOPNOTSUPP, errno.EINVAL, errno.ENODEV, errno.EPERM):
758                                         return False
759                                 else:
760                                         print "error: ",error_no,error_str
761                                         return True
762                         else:
763                                 return True
764
765         def ok(self):
766                 self.cleanup()
767                 if self["menulist"].getCurrent()[1] == 'edit':
768                         if iNetwork.isWirelessInterface(self.iface):
769                                 try:
770                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
771                                 except ImportError:
772                                         self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
773                                 else:
774                                         if self.queryWirelessDevice(self.iface):
775                                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
776                                         else:
777                                                 self.showErrorMessage() # Display Wlan not available Message
778                         else:
779                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
780                 if self["menulist"].getCurrent()[1] == 'test':
781                         self.session.open(NetworkAdapterTest,self.iface)
782                 if self["menulist"].getCurrent()[1] == 'dns':
783                         self.session.open(NameserverSetup)
784                 if self["menulist"].getCurrent()[1] == 'scanwlan':
785                         try:
786                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
787                         except ImportError:
788                                 self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
789                         else:
790                                 if self.queryWirelessDevice(self.iface):
791                                         self.session.openWithCallback(self.WlanScanClosed, WlanScan, self.iface)
792                                 else:
793                                         self.showErrorMessage() # Display Wlan not available Message
794                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
795                         try:
796                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
797                         except ImportError:
798                                 self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
799                         else:
800                                 if self.queryWirelessDevice(self.iface):
801                                         self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
802                                 else:
803                                         self.showErrorMessage() # Display Wlan not available Message
804                 if self["menulist"].getCurrent()[1] == 'lanrestart':
805                         self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
806                 if self["menulist"].getCurrent()[1] == 'openwizard':
807                         from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
808                         self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard, self.iface)
809                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
810                         self.extended = self["menulist"].getCurrent()[1][2]
811                         self.extended(self.session, self.iface)
812         
813         def up(self):
814                 self["menulist"].up()
815                 self.loadDescription()
816
817         def down(self):
818                 self["menulist"].down()
819                 self.loadDescription()
820
821         def left(self):
822                 self["menulist"].pageUp()
823                 self.loadDescription()
824
825         def right(self):
826                 self["menulist"].pageDown()
827                 self.loadDescription()
828
829         def layoutFinished(self):
830                 idx = 0
831                 self["menulist"].moveToIndex(idx)
832                 self.loadDescription()
833
834         def loadDescription(self):
835                 if self["menulist"].getCurrent()[1] == 'edit':
836                         self["description"].setText(_("Edit the network configuration of your Dreambox.\n" ) + self.oktext )
837                 if self["menulist"].getCurrent()[1] == 'test':
838                         self["description"].setText(_("Test the network configuration of your Dreambox.\n" ) + self.oktext )
839                 if self["menulist"].getCurrent()[1] == 'dns':
840                         self["description"].setText(_("Edit the Nameserver configuration of your Dreambox.\n" ) + self.oktext )
841                 if self["menulist"].getCurrent()[1] == 'scanwlan':
842                         self["description"].setText(_("Scan your network for wireless access points and connect to them using your selected wireless device.\n" ) + self.oktext )
843                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
844                         self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
845                 if self["menulist"].getCurrent()[1] == 'lanrestart':
846                         self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
847                 if self["menulist"].getCurrent()[1] == 'openwizard':
848                         self["description"].setText(_("Use the Networkwizard to configure your Network\n" ) + self.oktext )
849                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
850                         self["description"].setText(_(self["menulist"].getCurrent()[1][1]) + self.oktext )
851                 
852         def updateStatusbar(self, data = None):
853                 self.mainmenu = self.genMainMenu()
854                 self["menulist"].l.setList(self.mainmenu)
855                 self["IFtext"].setText(_("Network:"))
856                 self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
857                 self["Statustext"].setText(_("Link:"))
858                 
859                 if iNetwork.isWirelessInterface(self.iface):
860                         try:
861                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
862                         except:
863                                 self["statuspic"].setPixmapNum(1)
864                                 self["statuspic"].show()
865                         else:
866                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
867                 else:
868                         iNetwork.getLinkState(self.iface,self.dataAvail)
869
870         def doNothing(self):
871                 pass
872
873         def genMainMenu(self):
874                 menu = []
875                 menu.append((_("Adapter settings"), "edit"))
876                 menu.append((_("Nameserver settings"), "dns"))
877                 menu.append((_("Network test"), "test"))
878                 menu.append((_("Restart network"), "lanrestart"))
879
880                 self.extended = None
881                 self.extendedSetup = None               
882                 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
883                         callFnc = p.__call__["ifaceSupported"](self.iface)
884                         if callFnc is not None:
885                                 self.extended = callFnc
886                                 if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
887                                         menu.append((_("Scan Wireless Networks"), "scanwlan"))
888                                         if iNetwork.getAdapterAttribute(self.iface, "up"):
889                                                 menu.append((_("Show WLAN Status"), "wlanstatus"))
890                                 else:
891                                         if p.__call__.has_key("menuEntryName"):
892                                                 menuEntryName = p.__call__["menuEntryName"](self.iface)
893                                         else:
894                                                 menuEntryName = _('Extended Setup...')
895                                         if p.__call__.has_key("menuEntryDescription"):
896                                                 menuEntryDescription = p.__call__["menuEntryDescription"](self.iface)
897                                         else:
898                                                 menuEntryDescription = _('Extended Networksetup Plugin...')
899                                         self.extendedSetup = ('extendedSetup',menuEntryDescription, self.extended)
900                                         menu.append((menuEntryName,self.extendedSetup))                                 
901                         
902                 if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
903                         menu.append((_("NetworkWizard"), "openwizard"))
904
905                 return menu
906
907         def AdapterSetupClosed(self, *ret):
908                 if ret is not None and len(ret):
909                         if ret[0] == 'ok' and (iNetwork.isWirelessInterface(self.iface) and iNetwork.getAdapterAttribute(self.iface, "up") is True):
910                                 try:
911                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
912                                 except ImportError:
913                                         self.session.open(MessageBox, self.missingwlanplugintxt, type = MessageBox.TYPE_INFO,timeout = 10 )
914                                 else:   
915                                         if self.queryWirelessDevice(self.iface):
916                                                 self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
917                                         else:
918                                                 self.showErrorMessage() # Display Wlan not available Message
919                         else:
920                                 self.updateStatusbar()
921                 else:
922                         self.updateStatusbar()
923
924         def WlanStatusClosed(self, *ret):
925                 if ret is not None and len(ret):
926                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
927                         iStatus.stopWlanConsole()
928                         self.updateStatusbar()
929
930         def WlanScanClosed(self,*ret):
931                 if ret[0] is not None:
932                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,ret[0],ret[1])
933                 else:
934                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
935                         iStatus.stopWlanConsole()
936                         self.updateStatusbar()
937                         
938         def restartLan(self, ret = False):
939                 if (ret == True):
940                         iNetwork.restartNetwork(self.restartLanDataAvail)
941                         self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
942                         
943         def restartLanDataAvail(self, data):
944                 if data is True:
945                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
946
947         def getInterfacesDataAvail(self, data):
948                 if data is True:
949                         self.restartLanRef.close(True)
950
951         def restartfinishedCB(self,data):
952                 if data is True:
953                         self.updateStatusbar()
954                         self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
955
956         def dataAvail(self,data):
957                 self.LinkState = None
958                 for line in data.splitlines():
959                         line = line.strip()
960                         if 'Link detected:' in line:
961                                 if "yes" in line:
962                                         self.LinkState = True
963                                 else:
964                                         self.LinkState = False
965                 if self.LinkState == True:
966                         iNetwork.checkNetworkState(self.checkNetworkCB)
967                 else:
968                         self["statuspic"].setPixmapNum(1)
969                         self["statuspic"].show()                        
970
971         def showErrorMessage(self):
972                 self.session.open(MessageBox, self.errortext, type = MessageBox.TYPE_INFO,timeout = 10 )
973                 
974         def cleanup(self):
975                 iNetwork.stopLinkStateConsole()
976                 iNetwork.stopDeactivateInterfaceConsole()
977                 iNetwork.stopActivateInterfaceConsole()
978                 iNetwork.stopPingConsole()
979                 try:
980                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
981                 except ImportError:
982                         pass
983                 else:
984                         iStatus.stopWlanConsole()
985
986         def getInfoCB(self,data,status):
987                 self.LinkState = None
988                 if data is not None:
989                         if data is True:
990                                 if status is not None:
991                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
992                                                 self.LinkState = False
993                                                 self["statuspic"].setPixmapNum(1)
994                                                 self["statuspic"].show()
995                                         else:
996                                                 self.LinkState = True
997                                                 iNetwork.checkNetworkState(self.checkNetworkCB)
998
999         def checkNetworkCB(self,data):
1000                 if iNetwork.getAdapterAttribute(self.iface, "up") is True:
1001                         if self.LinkState is True:
1002                                 if data <= 2:
1003                                         self["statuspic"].setPixmapNum(0)
1004                                 else:
1005                                         self["statuspic"].setPixmapNum(1)
1006                                 self["statuspic"].show()        
1007                         else:
1008                                 self["statuspic"].setPixmapNum(1)
1009                                 self["statuspic"].show()
1010                 else:
1011                         self["statuspic"].setPixmapNum(1)
1012                         self["statuspic"].show()
1013
1014
1015 class NetworkAdapterTest(Screen):       
1016         def __init__(self, session,iface):
1017                 Screen.__init__(self, session)
1018                 self.iface = iface
1019                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
1020                 self.setLabels()
1021                 self.onClose.append(self.cleanup)
1022                 self.onHide.append(self.cleanup)
1023                 
1024                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
1025                 {
1026                         "ok": self.KeyOK,
1027                         "blue": self.KeyOK,
1028                         "up": lambda: self.updownhandler('up'),
1029                         "down": lambda: self.updownhandler('down'),
1030                 
1031                 }, -2)
1032                 
1033                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1034                 {
1035                         "red": self.cancel,
1036                         "back": self.cancel,
1037                 }, -2)
1038                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1039                 {
1040                         "red": self.closeInfo,
1041                         "back": self.closeInfo,
1042                 }, -2)
1043                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
1044                 {
1045                         "green": self.KeyGreen,
1046                 }, -2)
1047                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
1048                 {
1049                         "green": self.KeyGreenRestart,
1050                 }, -2)
1051                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
1052                 {
1053                         "yellow": self.KeyYellow,
1054                 }, -2)
1055                 
1056                 self["shortcutsgreen_restart"].setEnabled(False)
1057                 self["updown_actions"].setEnabled(False)
1058                 self["infoshortcuts"].setEnabled(False)
1059                 self.onClose.append(self.delTimer)      
1060                 self.onLayoutFinish.append(self.layoutFinished)
1061                 self.steptimer = False
1062                 self.nextstep = 0
1063                 self.activebutton = 0
1064                 self.nextStepTimer = eTimer()
1065                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
1066
1067         def cancel(self):
1068                 if self.oldInterfaceState is False:
1069                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
1070                         iNetwork.deactivateInterface(self.iface)
1071                 self.close()
1072
1073         def closeInfo(self):
1074                 self["shortcuts"].setEnabled(True)              
1075                 self["infoshortcuts"].setEnabled(False)
1076                 self["InfoText"].hide()
1077                 self["InfoTextBorder"].hide()
1078                 self["key_red"].setText(_("Close"))
1079
1080         def delTimer(self):
1081                 del self.steptimer
1082                 del self.nextStepTimer
1083
1084         def nextStepTimerFire(self):
1085                 self.nextStepTimer.stop()
1086                 self.steptimer = False
1087                 self.runTest()
1088
1089         def updownhandler(self,direction):
1090                 if direction == 'up':
1091                         if self.activebutton >=2:
1092                                 self.activebutton -= 1
1093                         else:
1094                                 self.activebutton = 6
1095                         self.setActiveButton(self.activebutton)
1096                 if direction == 'down':
1097                         if self.activebutton <=5:
1098                                 self.activebutton += 1
1099                         else:
1100                                 self.activebutton = 1
1101                         self.setActiveButton(self.activebutton)
1102
1103         def setActiveButton(self,button):
1104                 if button == 1:
1105                         self["EditSettingsButton"].setPixmapNum(0)
1106                         self["EditSettings_Text"].setForegroundColorNum(0)
1107                         self["NetworkInfo"].setPixmapNum(0)
1108                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1109                         self["AdapterInfo"].setPixmapNum(1)               # active
1110                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
1111                 if button == 2:
1112                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1113                         self["AdapterInfo"].setPixmapNum(0)
1114                         self["DhcpInfo"].setPixmapNum(0)
1115                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1116                         self["NetworkInfo"].setPixmapNum(1)               # active
1117                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
1118                 if button == 3:
1119                         self["NetworkInfo"].setPixmapNum(0)
1120                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1121                         self["IPInfo"].setPixmapNum(0)
1122                         self["IPInfo_Text"].setForegroundColorNum(1)
1123                         self["DhcpInfo"].setPixmapNum(1)                  # active
1124                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
1125                 if button == 4:
1126                         self["DhcpInfo"].setPixmapNum(0)
1127                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1128                         self["DNSInfo"].setPixmapNum(0)
1129                         self["DNSInfo_Text"].setForegroundColorNum(1)
1130                         self["IPInfo"].setPixmapNum(1)                  # active
1131                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
1132                 if button == 5:
1133                         self["IPInfo"].setPixmapNum(0)
1134                         self["IPInfo_Text"].setForegroundColorNum(1)
1135                         self["EditSettingsButton"].setPixmapNum(0)
1136                         self["EditSettings_Text"].setForegroundColorNum(0)
1137                         self["DNSInfo"].setPixmapNum(1)                 # active
1138                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
1139                 if button == 6:
1140                         self["DNSInfo"].setPixmapNum(0)
1141                         self["DNSInfo_Text"].setForegroundColorNum(1)
1142                         self["EditSettingsButton"].setPixmapNum(1)         # active
1143                         self["EditSettings_Text"].setForegroundColorNum(2) # active
1144                         self["AdapterInfo"].setPixmapNum(0)
1145                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1146                         
1147         def runTest(self):
1148                 next = self.nextstep
1149                 if next == 0:
1150                         self.doStep1()
1151                 elif next == 1:
1152                         self.doStep2()
1153                 elif next == 2:
1154                         self.doStep3()
1155                 elif next == 3:
1156                         self.doStep4()
1157                 elif next == 4:
1158                         self.doStep5()
1159                 elif next == 5:
1160                         self.doStep6()
1161                 self.nextstep += 1
1162
1163         def doStep1(self):
1164                 self.steptimer = True
1165                 self.nextStepTimer.start(3000)
1166                 self["key_yellow"].setText(_("Stop test"))
1167
1168         def doStep2(self):
1169                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
1170                 self["Adapter"].setForegroundColorNum(2)
1171                 self["Adaptertext"].setForegroundColorNum(1)
1172                 self["AdapterInfo_Text"].setForegroundColorNum(1)
1173                 self["AdapterInfo_OK"].show()
1174                 self.steptimer = True
1175                 self.nextStepTimer.start(3000)
1176
1177         def doStep3(self):
1178                 self["Networktext"].setForegroundColorNum(1)
1179                 self["Network"].setText(_("Please wait..."))
1180                 self.getLinkState(self.iface)
1181                 self["NetworkInfo_Text"].setForegroundColorNum(1)
1182                 self.steptimer = True
1183                 self.nextStepTimer.start(3000)
1184
1185         def doStep4(self):
1186                 self["Dhcptext"].setForegroundColorNum(1)
1187                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
1188                         self["Dhcp"].setForegroundColorNum(2)
1189                         self["Dhcp"].setText(_("enabled"))
1190                         self["DhcpInfo_Check"].setPixmapNum(0)
1191                 else:
1192                         self["Dhcp"].setForegroundColorNum(1)
1193                         self["Dhcp"].setText(_("disabled"))
1194                         self["DhcpInfo_Check"].setPixmapNum(1)
1195                 self["DhcpInfo_Check"].show()
1196                 self["DhcpInfo_Text"].setForegroundColorNum(1)
1197                 self.steptimer = True
1198                 self.nextStepTimer.start(3000)
1199
1200         def doStep5(self):
1201                 self["IPtext"].setForegroundColorNum(1)
1202                 self["IP"].setText(_("Please wait..."))
1203                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
1204
1205         def doStep6(self):
1206                 self.steptimer = False
1207                 self.nextStepTimer.stop()
1208                 self["DNStext"].setForegroundColorNum(1)
1209                 self["DNS"].setText(_("Please wait..."))
1210                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1211
1212         def KeyGreen(self):
1213                 self["shortcutsgreen"].setEnabled(False)
1214                 self["shortcutsyellow"].setEnabled(True)
1215                 self["updown_actions"].setEnabled(False)
1216                 self["key_yellow"].setText("")
1217                 self["key_green"].setText("")
1218                 self.steptimer = True
1219                 self.nextStepTimer.start(1000)
1220
1221         def KeyGreenRestart(self):
1222                 self.nextstep = 0
1223                 self.layoutFinished()
1224                 self["Adapter"].setText((""))
1225                 self["Network"].setText((""))
1226                 self["Dhcp"].setText((""))
1227                 self["IP"].setText((""))
1228                 self["DNS"].setText((""))
1229                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1230                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1231                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1232                 self["IPInfo_Text"].setForegroundColorNum(0)
1233                 self["DNSInfo_Text"].setForegroundColorNum(0)
1234                 self["shortcutsgreen_restart"].setEnabled(False)
1235                 self["shortcutsgreen"].setEnabled(False)
1236                 self["shortcutsyellow"].setEnabled(True)
1237                 self["updown_actions"].setEnabled(False)
1238                 self["key_yellow"].setText("")
1239                 self["key_green"].setText("")
1240                 self.steptimer = True
1241                 self.nextStepTimer.start(1000)
1242
1243         def KeyOK(self):
1244                 self["infoshortcuts"].setEnabled(True)
1245                 self["shortcuts"].setEnabled(False)
1246                 if self.activebutton == 1: # Adapter Check
1247                         self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
1248                         self["InfoTextBorder"].show()
1249                         self["InfoText"].show()
1250                         self["key_red"].setText(_("Back"))
1251                 if self.activebutton == 2: #LAN Check
1252                         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"))
1253                         self["InfoTextBorder"].show()
1254                         self["InfoText"].show()
1255                         self["key_red"].setText(_("Back"))
1256                 if self.activebutton == 3: #DHCP Check
1257                         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."))
1258                         self["InfoTextBorder"].show()
1259                         self["InfoText"].show()
1260                         self["key_red"].setText(_("Back"))
1261                 if self.activebutton == 4: # IP Check
1262                         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"))
1263                         self["InfoTextBorder"].show()
1264                         self["InfoText"].show()
1265                         self["key_red"].setText(_("Back"))
1266                 if self.activebutton == 5: # DNS Check
1267                         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"))
1268                         self["InfoTextBorder"].show()
1269                         self["InfoText"].show()
1270                         self["key_red"].setText(_("Back"))
1271                 if self.activebutton == 6: # Edit Settings
1272                         self.session.open(AdapterSetup,self.iface)
1273
1274         def KeyYellow(self):
1275                 self.nextstep = 0
1276                 self["shortcutsgreen_restart"].setEnabled(True)
1277                 self["shortcutsgreen"].setEnabled(False)
1278                 self["shortcutsyellow"].setEnabled(False)
1279                 self["key_green"].setText(_("Restart test"))
1280                 self["key_yellow"].setText("")
1281                 self.steptimer = False
1282                 self.nextStepTimer.stop()
1283
1284         def layoutFinished(self):
1285                 self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
1286                 self["shortcutsyellow"].setEnabled(False)
1287                 self["AdapterInfo_OK"].hide()
1288                 self["NetworkInfo_Check"].hide()
1289                 self["DhcpInfo_Check"].hide()
1290                 self["IPInfo_Check"].hide()
1291                 self["DNSInfo_Check"].hide()
1292                 self["EditSettings_Text"].hide()
1293                 self["EditSettingsButton"].hide()
1294                 self["InfoText"].hide()
1295                 self["InfoTextBorder"].hide()
1296                 self["key_yellow"].setText("")
1297
1298         def setLabels(self):
1299                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1300                 self["Adapter"] = MultiColorLabel()
1301                 self["AdapterInfo"] = MultiPixmap()
1302                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1303                 self["AdapterInfo_OK"] = Pixmap()
1304                 
1305                 if self.iface in iNetwork.wlan_interfaces:
1306                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1307                 else:
1308                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1309                 
1310                 self["Network"] = MultiColorLabel()
1311                 self["NetworkInfo"] = MultiPixmap()
1312                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1313                 self["NetworkInfo_Check"] = MultiPixmap()
1314                 
1315                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1316                 self["Dhcp"] = MultiColorLabel()
1317                 self["DhcpInfo"] = MultiPixmap()
1318                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1319                 self["DhcpInfo_Check"] = MultiPixmap()
1320                 
1321                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1322                 self["IP"] = MultiColorLabel()
1323                 self["IPInfo"] = MultiPixmap()
1324                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1325                 self["IPInfo_Check"] = MultiPixmap()
1326                 
1327                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1328                 self["DNS"] = MultiColorLabel()
1329                 self["DNSInfo"] = MultiPixmap()
1330                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1331                 self["DNSInfo_Check"] = MultiPixmap()
1332                 
1333                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1334                 self["EditSettingsButton"] = MultiPixmap()
1335                 
1336                 self["key_red"] = StaticText(_("Close"))
1337                 self["key_green"] = StaticText(_("Start test"))
1338                 self["key_yellow"] = StaticText(_("Stop test"))
1339                 
1340                 self["InfoTextBorder"] = Pixmap()
1341                 self["InfoText"] = Label()
1342
1343         def getLinkState(self,iface):
1344                 if iface in iNetwork.wlan_interfaces:
1345                         try:
1346                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
1347                         except:
1348                                         self["Network"].setForegroundColorNum(1)
1349                                         self["Network"].setText(_("disconnected"))
1350                                         self["NetworkInfo_Check"].setPixmapNum(1)
1351                                         self["NetworkInfo_Check"].show()
1352                         else:
1353                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
1354                 else:
1355                         iNetwork.getLinkState(iface,self.LinkStatedataAvail)
1356
1357         def LinkStatedataAvail(self,data):
1358                 self.output = data.strip()
1359                 result = self.output.splitlines()
1360                 pattern = re_compile("Link detected: yes")
1361                 for item in result:
1362                         if re_search(pattern, item):
1363                                 self["Network"].setForegroundColorNum(2)
1364                                 self["Network"].setText(_("connected"))
1365                                 self["NetworkInfo_Check"].setPixmapNum(0)
1366                         else:
1367                                 self["Network"].setForegroundColorNum(1)
1368                                 self["Network"].setText(_("disconnected"))
1369                                 self["NetworkInfo_Check"].setPixmapNum(1)
1370                 self["NetworkInfo_Check"].show()
1371
1372         def NetworkStatedataAvail(self,data):
1373                 if data <= 2:
1374                         self["IP"].setForegroundColorNum(2)
1375                         self["IP"].setText(_("confirmed"))
1376                         self["IPInfo_Check"].setPixmapNum(0)
1377                 else:
1378                         self["IP"].setForegroundColorNum(1)
1379                         self["IP"].setText(_("unconfirmed"))
1380                         self["IPInfo_Check"].setPixmapNum(1)
1381                 self["IPInfo_Check"].show()
1382                 self["IPInfo_Text"].setForegroundColorNum(1)            
1383                 self.steptimer = True
1384                 self.nextStepTimer.start(3000)          
1385                 
1386         def DNSLookupdataAvail(self,data):
1387                 if data <= 2:
1388                         self["DNS"].setForegroundColorNum(2)
1389                         self["DNS"].setText(_("confirmed"))
1390                         self["DNSInfo_Check"].setPixmapNum(0)
1391                 else:
1392                         self["DNS"].setForegroundColorNum(1)
1393                         self["DNS"].setText(_("unconfirmed"))
1394                         self["DNSInfo_Check"].setPixmapNum(1)
1395                 self["DNSInfo_Check"].show()
1396                 self["DNSInfo_Text"].setForegroundColorNum(1)
1397                 self["EditSettings_Text"].show()
1398                 self["EditSettingsButton"].setPixmapNum(1)
1399                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1400                 self["EditSettingsButton"].show()
1401                 self["key_yellow"].setText("")
1402                 self["key_green"].setText(_("Restart test"))
1403                 self["shortcutsgreen"].setEnabled(False)
1404                 self["shortcutsgreen_restart"].setEnabled(True)
1405                 self["shortcutsyellow"].setEnabled(False)
1406                 self["updown_actions"].setEnabled(True)
1407                 self.activebutton = 6
1408
1409         def getInfoCB(self,data,status):
1410                 if data is not None:
1411                         if data is True:
1412                                 if status is not None:
1413                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
1414                                                 self["Network"].setForegroundColorNum(1)
1415                                                 self["Network"].setText(_("disconnected"))
1416                                                 self["NetworkInfo_Check"].setPixmapNum(1)
1417                                                 self["NetworkInfo_Check"].show()
1418                                         else:
1419                                                 self["Network"].setForegroundColorNum(2)
1420                                                 self["Network"].setText(_("connected"))
1421                                                 self["NetworkInfo_Check"].setPixmapNum(0)
1422                                                 self["NetworkInfo_Check"].show()
1423                                                 
1424         def cleanup(self):
1425                 iNetwork.stopLinkStateConsole()
1426                 iNetwork.stopDNSConsole()
1427                 try:
1428                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
1429                 except ImportError:
1430                         pass
1431                 else:
1432                         iStatus.stopWlanConsole()
1433