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