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