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