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