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