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