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