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