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