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