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