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