Network.py,NetworkSetup.py,skin_default.xml: * Introduce new unified naming for netwo...
[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 Plugins.SystemPlugins.WirelessLan.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                                         self.wlanresponse = ifobj.getStatistics()
754                                         if self.wlanresponse[0] != 19: # Wlan Interface found.
755                                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
756                                         else:
757                                                 # Display Wlan not available Message
758                                                 self.showErrorMessage()
759                         else:
760                                 self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup,self.iface)
761                 if self["menulist"].getCurrent()[1] == 'test':
762                         self.session.open(NetworkAdapterTest,self.iface)
763                 if self["menulist"].getCurrent()[1] == 'dns':
764                         self.session.open(NameserverSetup)
765                 if self["menulist"].getCurrent()[1] == 'scanwlan':
766                         try:
767                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanScan
768                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
769                         except ImportError:
770                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
771                         else:
772                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
773                                 self.wlanresponse = ifobj.getStatistics()
774                                 if self.wlanresponse[0] != 19:
775                                         self.session.openWithCallback(self.WlanScanClosed, WlanScan, self.iface)
776                                 else:
777                                         # Display Wlan not available Message
778                                         self.showErrorMessage()
779                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
780                         try:
781                                 from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
782                                 from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
783                         except ImportError:
784                                 self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
785                         else:   
786                                 ifobj = Wireless(self.iface) # a Wireless NIC Object
787                                 self.wlanresponse = ifobj.getStatistics()
788                                 if self.wlanresponse[0] != 19:
789                                         self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
790                                 else:
791                                         # Display Wlan not available Message
792                                         self.showErrorMessage()
793                 if self["menulist"].getCurrent()[1] == 'lanrestart':
794                         self.session.openWithCallback(self.restartLan, MessageBox, (_("Are you sure you want to restart your network interfaces?\n\n") + self.oktext ) )
795                 if self["menulist"].getCurrent()[1] == 'openwizard':
796                         from Plugins.SystemPlugins.NetworkWizard.NetworkWizard import NetworkWizard
797                         self.session.openWithCallback(self.AdapterSetupClosed, NetworkWizard, self.iface)
798                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
799                         self.extended = self["menulist"].getCurrent()[1][2]
800                         self.extended(self.session, self.iface)
801         
802         def up(self):
803                 self["menulist"].up()
804                 self.loadDescription()
805
806         def down(self):
807                 self["menulist"].down()
808                 self.loadDescription()
809
810         def left(self):
811                 self["menulist"].pageUp()
812                 self.loadDescription()
813
814         def right(self):
815                 self["menulist"].pageDown()
816                 self.loadDescription()
817
818         def layoutFinished(self):
819                 idx = 0
820                 self["menulist"].moveToIndex(idx)
821                 self.loadDescription()
822
823         def loadDescription(self):
824                 if self["menulist"].getCurrent()[1] == 'edit':
825                         self["description"].setText(_("Edit the network configuration of your Dreambox.\n" ) + self.oktext )
826                 if self["menulist"].getCurrent()[1] == 'test':
827                         self["description"].setText(_("Test the network configuration of your Dreambox.\n" ) + self.oktext )
828                 if self["menulist"].getCurrent()[1] == 'dns':
829                         self["description"].setText(_("Edit the Nameserver configuration of your Dreambox.\n" ) + self.oktext )
830                 if self["menulist"].getCurrent()[1] == 'scanwlan':
831                         self["description"].setText(_("Scan your network for wireless access points and connect to them using your selected wireless device.\n" ) + self.oktext )
832                 if self["menulist"].getCurrent()[1] == 'wlanstatus':
833                         self["description"].setText(_("Shows the state of your wireless LAN connection.\n" ) + self.oktext )
834                 if self["menulist"].getCurrent()[1] == 'lanrestart':
835                         self["description"].setText(_("Restart your network connection and interfaces.\n" ) + self.oktext )
836                 if self["menulist"].getCurrent()[1] == 'openwizard':
837                         self["description"].setText(_("Use the Networkwizard to configure your Network\n" ) + self.oktext )
838                 if self["menulist"].getCurrent()[1][0] == 'extendedSetup':
839                         self["description"].setText(_(self["menulist"].getCurrent()[1][1]) + self.oktext )
840                 
841         def updateStatusbar(self, data = None):
842                 self.mainmenu = self.genMainMenu()
843                 self["menulist"].l.setList(self.mainmenu)
844                 self["IFtext"].setText(_("Network:"))
845                 self["IF"].setText(iNetwork.getFriendlyAdapterName(self.iface))
846                 self["Statustext"].setText(_("Link:"))
847                 
848                 if self.iface in iNetwork.wlan_interfaces:
849                         try:
850                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
851                         except:
852                                 self["statuspic"].setPixmapNum(1)
853                                 self["statuspic"].show()
854                         else:
855                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
856                 else:
857                         iNetwork.getLinkState(self.iface,self.dataAvail)
858
859         def doNothing(self):
860                 pass
861
862         def genMainMenu(self):
863                 menu = []
864                 menu.append((_("Adapter settings"), "edit"))
865                 menu.append((_("Nameserver settings"), "dns"))
866                 menu.append((_("Network test"), "test"))
867                 menu.append((_("Restart network"), "lanrestart"))
868
869                 self.extended = None
870                 self.extendedSetup = None               
871                 for p in plugins.getPlugins(PluginDescriptor.WHERE_NETWORKSETUP):
872                         callFnc = p.__call__["ifaceSupported"](self.iface)
873                         if callFnc is not None:
874                                 self.extended = callFnc
875                                 if p.__call__.has_key("WlanPluginEntry"): # internally used only for WLAN Plugin
876                                         menu.append((_("Scan Wireless Networks"), "scanwlan"))
877                                         if iNetwork.getAdapterAttribute(self.iface, "up"):
878                                                 menu.append((_("Show WLAN Status"), "wlanstatus"))
879                                 else:
880                                         if p.__call__.has_key("menuEntryName"):
881                                                 menuEntryName = p.__call__["menuEntryName"](self.iface)
882                                         else:
883                                                 menuEntryName = _('Extended Setup...')
884                                         if p.__call__.has_key("menuEntryDescription"):
885                                                 menuEntryDescription = p.__call__["menuEntryDescription"](self.iface)
886                                         else:
887                                                 menuEntryDescription = _('Extended Networksetup Plugin...')
888                                         self.extendedSetup = ('extendedSetup',menuEntryDescription, self.extended)
889                                         menu.append((menuEntryName,self.extendedSetup))                                 
890                         
891                 if os_path.exists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")):
892                         menu.append((_("NetworkWizard"), "openwizard"))
893
894                 return menu
895
896         def AdapterSetupClosed(self, *ret):
897                 if ret is not None and len(ret):
898                         if ret[0] == 'ok' and (self.iface in iNetwork.wlan_interfaces) and iNetwork.getAdapterAttribute(self.iface, "up") is True:
899                                 try:
900                                         from Plugins.SystemPlugins.WirelessLan.plugin import WlanStatus
901                                         from Plugins.SystemPlugins.WirelessLan.iwlibs import Wireless
902                                 except ImportError:
903                                         self.session.open(MessageBox, _("The wireless LAN plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
904                                 else:   
905                                         ifobj = Wireless(self.iface) # a Wireless NIC Object
906                                         self.wlanresponse = ifobj.getStatistics()
907                                         if self.wlanresponse[0] != 19:
908                                                 self.session.openWithCallback(self.WlanStatusClosed, WlanStatus,self.iface)
909                                         else:
910                                                 # Display Wlan not available Message
911                                                 self.showErrorMessage()
912                         else:
913                                 self.updateStatusbar()
914                 else:
915                         self.updateStatusbar()
916
917         def WlanStatusClosed(self, *ret):
918                 if ret is not None and len(ret):
919                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
920                         iStatus.stopWlanConsole()
921                         self.updateStatusbar()
922
923         def WlanScanClosed(self,*ret):
924                 if ret[0] is not None:
925                         self.session.openWithCallback(self.AdapterSetupClosed, AdapterSetup, self.iface,ret[0],ret[1])
926                 else:
927                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
928                         iStatus.stopWlanConsole()
929                         self.updateStatusbar()
930                         
931         def restartLan(self, ret = False):
932                 if (ret == True):
933                         iNetwork.restartNetwork(self.restartLanDataAvail)
934                         self.restartLanRef = self.session.openWithCallback(self.restartfinishedCB, MessageBox, _("Please wait while your network is restarting..."), type = MessageBox.TYPE_INFO, enable_input = False)
935                         
936         def restartLanDataAvail(self, data):
937                 if data is True:
938                         iNetwork.getInterfaces(self.getInterfacesDataAvail)
939
940         def getInterfacesDataAvail(self, data):
941                 if data is True:
942                         self.restartLanRef.close(True)
943
944         def restartfinishedCB(self,data):
945                 if data is True:
946                         self.updateStatusbar()
947                         self.session.open(MessageBox, _("Finished restarting your network"), type = MessageBox.TYPE_INFO, timeout = 10, default = False)
948
949         def dataAvail(self,data):
950                 self.LinkState = None
951                 for line in data.splitlines():
952                         line = line.strip()
953                         if 'Link detected:' in line:
954                                 if "yes" in line:
955                                         self.LinkState = True
956                                 else:
957                                         self.LinkState = False
958                 if self.LinkState == True:
959                         iNetwork.checkNetworkState(self.checkNetworkCB)
960                 else:
961                         self["statuspic"].setPixmapNum(1)
962                         self["statuspic"].show()                        
963
964         def showErrorMessage(self):
965                 self.session.open(MessageBox, self.errortext, type = MessageBox.TYPE_INFO,timeout = 10 )
966                 
967         def cleanup(self):
968                 iNetwork.stopLinkStateConsole()
969                 iNetwork.stopDeactivateInterfaceConsole()
970                 iNetwork.stopPingConsole()
971                 try:
972                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
973                 except ImportError:
974                         pass
975                 else:
976                         iStatus.stopWlanConsole()
977
978         def getInfoCB(self,data,status):
979                 self.LinkState = None
980                 if data is not None:
981                         if data is True:
982                                 if status is not None:
983                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
984                                                 self.LinkState = False
985                                                 self["statuspic"].setPixmapNum(1)
986                                                 self["statuspic"].show()
987                                         else:
988                                                 self.LinkState = True
989                                                 iNetwork.checkNetworkState(self.checkNetworkCB)
990
991         def checkNetworkCB(self,data):
992                 if iNetwork.getAdapterAttribute(self.iface, "up") is True:
993                         if self.LinkState is True:
994                                 if data <= 2:
995                                         self["statuspic"].setPixmapNum(0)
996                                 else:
997                                         self["statuspic"].setPixmapNum(1)
998                                 self["statuspic"].show()        
999                         else:
1000                                 self["statuspic"].setPixmapNum(1)
1001                                 self["statuspic"].show()
1002                 else:
1003                         self["statuspic"].setPixmapNum(1)
1004                         self["statuspic"].show()
1005
1006
1007 class NetworkAdapterTest(Screen):       
1008         def __init__(self, session,iface):
1009                 Screen.__init__(self, session)
1010                 self.iface = iface
1011                 self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
1012                 self.setLabels()
1013                 self.onClose.append(self.cleanup)
1014                 self.onHide.append(self.cleanup)
1015                 
1016                 self["updown_actions"] = NumberActionMap(["WizardActions","ShortcutActions"],
1017                 {
1018                         "ok": self.KeyOK,
1019                         "blue": self.KeyOK,
1020                         "up": lambda: self.updownhandler('up'),
1021                         "down": lambda: self.updownhandler('down'),
1022                 
1023                 }, -2)
1024                 
1025                 self["shortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1026                 {
1027                         "red": self.cancel,
1028                         "back": self.cancel,
1029                 }, -2)
1030                 self["infoshortcuts"] = ActionMap(["ShortcutActions","WizardActions"],
1031                 {
1032                         "red": self.closeInfo,
1033                         "back": self.closeInfo,
1034                 }, -2)
1035                 self["shortcutsgreen"] = ActionMap(["ShortcutActions"],
1036                 {
1037                         "green": self.KeyGreen,
1038                 }, -2)
1039                 self["shortcutsgreen_restart"] = ActionMap(["ShortcutActions"],
1040                 {
1041                         "green": self.KeyGreenRestart,
1042                 }, -2)
1043                 self["shortcutsyellow"] = ActionMap(["ShortcutActions"],
1044                 {
1045                         "yellow": self.KeyYellow,
1046                 }, -2)
1047                 
1048                 self["shortcutsgreen_restart"].setEnabled(False)
1049                 self["updown_actions"].setEnabled(False)
1050                 self["infoshortcuts"].setEnabled(False)
1051                 self.onClose.append(self.delTimer)      
1052                 self.onLayoutFinish.append(self.layoutFinished)
1053                 self.steptimer = False
1054                 self.nextstep = 0
1055                 self.activebutton = 0
1056                 self.nextStepTimer = eTimer()
1057                 self.nextStepTimer.callback.append(self.nextStepTimerFire)
1058
1059         def cancel(self):
1060                 if self.oldInterfaceState is False:
1061                         iNetwork.setAdapterAttribute(self.iface, "up", self.oldInterfaceState)
1062                         iNetwork.deactivateInterface(self.iface)
1063                 self.close()
1064
1065         def closeInfo(self):
1066                 self["shortcuts"].setEnabled(True)              
1067                 self["infoshortcuts"].setEnabled(False)
1068                 self["InfoText"].hide()
1069                 self["InfoTextBorder"].hide()
1070                 self["key_red"].setText(_("Close"))
1071
1072         def delTimer(self):
1073                 del self.steptimer
1074                 del self.nextStepTimer
1075
1076         def nextStepTimerFire(self):
1077                 self.nextStepTimer.stop()
1078                 self.steptimer = False
1079                 self.runTest()
1080
1081         def updownhandler(self,direction):
1082                 if direction == 'up':
1083                         if self.activebutton >=2:
1084                                 self.activebutton -= 1
1085                         else:
1086                                 self.activebutton = 6
1087                         self.setActiveButton(self.activebutton)
1088                 if direction == 'down':
1089                         if self.activebutton <=5:
1090                                 self.activebutton += 1
1091                         else:
1092                                 self.activebutton = 1
1093                         self.setActiveButton(self.activebutton)
1094
1095         def setActiveButton(self,button):
1096                 if button == 1:
1097                         self["EditSettingsButton"].setPixmapNum(0)
1098                         self["EditSettings_Text"].setForegroundColorNum(0)
1099                         self["NetworkInfo"].setPixmapNum(0)
1100                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1101                         self["AdapterInfo"].setPixmapNum(1)               # active
1102                         self["AdapterInfo_Text"].setForegroundColorNum(2) # active
1103                 if button == 2:
1104                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1105                         self["AdapterInfo"].setPixmapNum(0)
1106                         self["DhcpInfo"].setPixmapNum(0)
1107                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1108                         self["NetworkInfo"].setPixmapNum(1)               # active
1109                         self["NetworkInfo_Text"].setForegroundColorNum(2) # active
1110                 if button == 3:
1111                         self["NetworkInfo"].setPixmapNum(0)
1112                         self["NetworkInfo_Text"].setForegroundColorNum(1)
1113                         self["IPInfo"].setPixmapNum(0)
1114                         self["IPInfo_Text"].setForegroundColorNum(1)
1115                         self["DhcpInfo"].setPixmapNum(1)                  # active
1116                         self["DhcpInfo_Text"].setForegroundColorNum(2)    # active
1117                 if button == 4:
1118                         self["DhcpInfo"].setPixmapNum(0)
1119                         self["DhcpInfo_Text"].setForegroundColorNum(1)
1120                         self["DNSInfo"].setPixmapNum(0)
1121                         self["DNSInfo_Text"].setForegroundColorNum(1)
1122                         self["IPInfo"].setPixmapNum(1)                  # active
1123                         self["IPInfo_Text"].setForegroundColorNum(2)    # active                
1124                 if button == 5:
1125                         self["IPInfo"].setPixmapNum(0)
1126                         self["IPInfo_Text"].setForegroundColorNum(1)
1127                         self["EditSettingsButton"].setPixmapNum(0)
1128                         self["EditSettings_Text"].setForegroundColorNum(0)
1129                         self["DNSInfo"].setPixmapNum(1)                 # active
1130                         self["DNSInfo_Text"].setForegroundColorNum(2)   # active
1131                 if button == 6:
1132                         self["DNSInfo"].setPixmapNum(0)
1133                         self["DNSInfo_Text"].setForegroundColorNum(1)
1134                         self["EditSettingsButton"].setPixmapNum(1)         # active
1135                         self["EditSettings_Text"].setForegroundColorNum(2) # active
1136                         self["AdapterInfo"].setPixmapNum(0)
1137                         self["AdapterInfo_Text"].setForegroundColorNum(1)
1138                         
1139         def runTest(self):
1140                 next = self.nextstep
1141                 if next == 0:
1142                         self.doStep1()
1143                 elif next == 1:
1144                         self.doStep2()
1145                 elif next == 2:
1146                         self.doStep3()
1147                 elif next == 3:
1148                         self.doStep4()
1149                 elif next == 4:
1150                         self.doStep5()
1151                 elif next == 5:
1152                         self.doStep6()
1153                 self.nextstep += 1
1154
1155         def doStep1(self):
1156                 self.steptimer = True
1157                 self.nextStepTimer.start(3000)
1158                 self["key_yellow"].setText(_("Stop test"))
1159
1160         def doStep2(self):
1161                 self["Adapter"].setText(iNetwork.getFriendlyAdapterName(self.iface))
1162                 self["Adapter"].setForegroundColorNum(2)
1163                 self["Adaptertext"].setForegroundColorNum(1)
1164                 self["AdapterInfo_Text"].setForegroundColorNum(1)
1165                 self["AdapterInfo_OK"].show()
1166                 self.steptimer = True
1167                 self.nextStepTimer.start(3000)
1168
1169         def doStep3(self):
1170                 self["Networktext"].setForegroundColorNum(1)
1171                 self["Network"].setText(_("Please wait..."))
1172                 self.getLinkState(self.iface)
1173                 self["NetworkInfo_Text"].setForegroundColorNum(1)
1174                 self.steptimer = True
1175                 self.nextStepTimer.start(3000)
1176
1177         def doStep4(self):
1178                 self["Dhcptext"].setForegroundColorNum(1)
1179                 if iNetwork.getAdapterAttribute(self.iface, 'dhcp') is True:
1180                         self["Dhcp"].setForegroundColorNum(2)
1181                         self["Dhcp"].setText(_("enabled"))
1182                         self["DhcpInfo_Check"].setPixmapNum(0)
1183                 else:
1184                         self["Dhcp"].setForegroundColorNum(1)
1185                         self["Dhcp"].setText(_("disabled"))
1186                         self["DhcpInfo_Check"].setPixmapNum(1)
1187                 self["DhcpInfo_Check"].show()
1188                 self["DhcpInfo_Text"].setForegroundColorNum(1)
1189                 self.steptimer = True
1190                 self.nextStepTimer.start(3000)
1191
1192         def doStep5(self):
1193                 self["IPtext"].setForegroundColorNum(1)
1194                 self["IP"].setText(_("Please wait..."))
1195                 iNetwork.checkNetworkState(self.NetworkStatedataAvail)
1196
1197         def doStep6(self):
1198                 self.steptimer = False
1199                 self.nextStepTimer.stop()
1200                 self["DNStext"].setForegroundColorNum(1)
1201                 self["DNS"].setText(_("Please wait..."))
1202                 iNetwork.checkDNSLookup(self.DNSLookupdataAvail)
1203
1204         def KeyGreen(self):
1205                 self["shortcutsgreen"].setEnabled(False)
1206                 self["shortcutsyellow"].setEnabled(True)
1207                 self["updown_actions"].setEnabled(False)
1208                 self["key_yellow"].setText("")
1209                 self["key_green"].setText("")
1210                 self.steptimer = True
1211                 self.nextStepTimer.start(1000)
1212
1213         def KeyGreenRestart(self):
1214                 self.nextstep = 0
1215                 self.layoutFinished()
1216                 self["Adapter"].setText((""))
1217                 self["Network"].setText((""))
1218                 self["Dhcp"].setText((""))
1219                 self["IP"].setText((""))
1220                 self["DNS"].setText((""))
1221                 self["AdapterInfo_Text"].setForegroundColorNum(0)
1222                 self["NetworkInfo_Text"].setForegroundColorNum(0)
1223                 self["DhcpInfo_Text"].setForegroundColorNum(0)
1224                 self["IPInfo_Text"].setForegroundColorNum(0)
1225                 self["DNSInfo_Text"].setForegroundColorNum(0)
1226                 self["shortcutsgreen_restart"].setEnabled(False)
1227                 self["shortcutsgreen"].setEnabled(False)
1228                 self["shortcutsyellow"].setEnabled(True)
1229                 self["updown_actions"].setEnabled(False)
1230                 self["key_yellow"].setText("")
1231                 self["key_green"].setText("")
1232                 self.steptimer = True
1233                 self.nextStepTimer.start(1000)
1234
1235         def KeyOK(self):
1236                 self["infoshortcuts"].setEnabled(True)
1237                 self["shortcuts"].setEnabled(False)
1238                 if self.activebutton == 1: # Adapter Check
1239                         self["InfoText"].setText(_("This test detects your configured LAN-Adapter."))
1240                         self["InfoTextBorder"].show()
1241                         self["InfoText"].show()
1242                         self["key_red"].setText(_("Back"))
1243                 if self.activebutton == 2: #LAN Check
1244                         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"))
1245                         self["InfoTextBorder"].show()
1246                         self["InfoText"].show()
1247                         self["key_red"].setText(_("Back"))
1248                 if self.activebutton == 3: #DHCP Check
1249                         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."))
1250                         self["InfoTextBorder"].show()
1251                         self["InfoText"].show()
1252                         self["key_red"].setText(_("Back"))
1253                 if self.activebutton == 4: # IP Check
1254                         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"))
1255                         self["InfoTextBorder"].show()
1256                         self["InfoText"].show()
1257                         self["key_red"].setText(_("Back"))
1258                 if self.activebutton == 5: # DNS Check
1259                         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"))
1260                         self["InfoTextBorder"].show()
1261                         self["InfoText"].show()
1262                         self["key_red"].setText(_("Back"))
1263                 if self.activebutton == 6: # Edit Settings
1264                         self.session.open(AdapterSetup,self.iface)
1265
1266         def KeyYellow(self):
1267                 self.nextstep = 0
1268                 self["shortcutsgreen_restart"].setEnabled(True)
1269                 self["shortcutsgreen"].setEnabled(False)
1270                 self["shortcutsyellow"].setEnabled(False)
1271                 self["key_green"].setText(_("Restart test"))
1272                 self["key_yellow"].setText("")
1273                 self.steptimer = False
1274                 self.nextStepTimer.stop()
1275
1276         def layoutFinished(self):
1277                 self.setTitle(_("Network test: ") + iNetwork.getFriendlyAdapterName(self.iface) )
1278                 self["shortcutsyellow"].setEnabled(False)
1279                 self["AdapterInfo_OK"].hide()
1280                 self["NetworkInfo_Check"].hide()
1281                 self["DhcpInfo_Check"].hide()
1282                 self["IPInfo_Check"].hide()
1283                 self["DNSInfo_Check"].hide()
1284                 self["EditSettings_Text"].hide()
1285                 self["EditSettingsButton"].hide()
1286                 self["InfoText"].hide()
1287                 self["InfoTextBorder"].hide()
1288                 self["key_yellow"].setText("")
1289
1290         def setLabels(self):
1291                 self["Adaptertext"] = MultiColorLabel(_("LAN Adapter"))
1292                 self["Adapter"] = MultiColorLabel()
1293                 self["AdapterInfo"] = MultiPixmap()
1294                 self["AdapterInfo_Text"] = MultiColorLabel(_("Show Info"))
1295                 self["AdapterInfo_OK"] = Pixmap()
1296                 
1297                 if self.iface in iNetwork.wlan_interfaces:
1298                         self["Networktext"] = MultiColorLabel(_("Wireless Network"))
1299                 else:
1300                         self["Networktext"] = MultiColorLabel(_("Local Network"))
1301                 
1302                 self["Network"] = MultiColorLabel()
1303                 self["NetworkInfo"] = MultiPixmap()
1304                 self["NetworkInfo_Text"] = MultiColorLabel(_("Show Info"))
1305                 self["NetworkInfo_Check"] = MultiPixmap()
1306                 
1307                 self["Dhcptext"] = MultiColorLabel(_("DHCP"))
1308                 self["Dhcp"] = MultiColorLabel()
1309                 self["DhcpInfo"] = MultiPixmap()
1310                 self["DhcpInfo_Text"] = MultiColorLabel(_("Show Info"))
1311                 self["DhcpInfo_Check"] = MultiPixmap()
1312                 
1313                 self["IPtext"] = MultiColorLabel(_("IP Address"))
1314                 self["IP"] = MultiColorLabel()
1315                 self["IPInfo"] = MultiPixmap()
1316                 self["IPInfo_Text"] = MultiColorLabel(_("Show Info"))
1317                 self["IPInfo_Check"] = MultiPixmap()
1318                 
1319                 self["DNStext"] = MultiColorLabel(_("Nameserver"))
1320                 self["DNS"] = MultiColorLabel()
1321                 self["DNSInfo"] = MultiPixmap()
1322                 self["DNSInfo_Text"] = MultiColorLabel(_("Show Info"))
1323                 self["DNSInfo_Check"] = MultiPixmap()
1324                 
1325                 self["EditSettings_Text"] = MultiColorLabel(_("Edit settings"))
1326                 self["EditSettingsButton"] = MultiPixmap()
1327                 
1328                 self["key_red"] = StaticText(_("Close"))
1329                 self["key_green"] = StaticText(_("Start test"))
1330                 self["key_yellow"] = StaticText(_("Stop test"))
1331                 
1332                 self["InfoTextBorder"] = Pixmap()
1333                 self["InfoText"] = Label()
1334
1335         def getLinkState(self,iface):
1336                 if iface in iNetwork.wlan_interfaces:
1337                         try:
1338                                 from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
1339                         except:
1340                                         self["Network"].setForegroundColorNum(1)
1341                                         self["Network"].setText(_("disconnected"))
1342                                         self["NetworkInfo_Check"].setPixmapNum(1)
1343                                         self["NetworkInfo_Check"].show()
1344                         else:
1345                                 iStatus.getDataForInterface(self.iface,self.getInfoCB)
1346                 else:
1347                         iNetwork.getLinkState(iface,self.LinkStatedataAvail)
1348
1349         def LinkStatedataAvail(self,data):
1350                 self.output = data.strip()
1351                 result = self.output.split('\n')
1352                 pattern = re_compile("Link detected: yes")
1353                 for item in result:
1354                         if re_search(pattern, item):
1355                                 self["Network"].setForegroundColorNum(2)
1356                                 self["Network"].setText(_("connected"))
1357                                 self["NetworkInfo_Check"].setPixmapNum(0)
1358                         else:
1359                                 self["Network"].setForegroundColorNum(1)
1360                                 self["Network"].setText(_("disconnected"))
1361                                 self["NetworkInfo_Check"].setPixmapNum(1)
1362                 self["NetworkInfo_Check"].show()
1363
1364         def NetworkStatedataAvail(self,data):
1365                 if data <= 2:
1366                         self["IP"].setForegroundColorNum(2)
1367                         self["IP"].setText(_("confirmed"))
1368                         self["IPInfo_Check"].setPixmapNum(0)
1369                 else:
1370                         self["IP"].setForegroundColorNum(1)
1371                         self["IP"].setText(_("unconfirmed"))
1372                         self["IPInfo_Check"].setPixmapNum(1)
1373                 self["IPInfo_Check"].show()
1374                 self["IPInfo_Text"].setForegroundColorNum(1)            
1375                 self.steptimer = True
1376                 self.nextStepTimer.start(3000)          
1377                 
1378         def DNSLookupdataAvail(self,data):
1379                 if data <= 2:
1380                         self["DNS"].setForegroundColorNum(2)
1381                         self["DNS"].setText(_("confirmed"))
1382                         self["DNSInfo_Check"].setPixmapNum(0)
1383                 else:
1384                         self["DNS"].setForegroundColorNum(1)
1385                         self["DNS"].setText(_("unconfirmed"))
1386                         self["DNSInfo_Check"].setPixmapNum(1)
1387                 self["DNSInfo_Check"].show()
1388                 self["DNSInfo_Text"].setForegroundColorNum(1)
1389                 self["EditSettings_Text"].show()
1390                 self["EditSettingsButton"].setPixmapNum(1)
1391                 self["EditSettings_Text"].setForegroundColorNum(2) # active
1392                 self["EditSettingsButton"].show()
1393                 self["key_yellow"].setText("")
1394                 self["key_green"].setText(_("Restart test"))
1395                 self["shortcutsgreen"].setEnabled(False)
1396                 self["shortcutsgreen_restart"].setEnabled(True)
1397                 self["shortcutsyellow"].setEnabled(False)
1398                 self["updown_actions"].setEnabled(True)
1399                 self.activebutton = 6
1400
1401         def getInfoCB(self,data,status):
1402                 if data is not None:
1403                         if data is True:
1404                                 if status is not None:
1405                                         if status[self.iface]["acesspoint"] == "No Connection" or status[self.iface]["acesspoint"] == "Not-Associated" or status[self.iface]["acesspoint"] == False:
1406                                                 self["Network"].setForegroundColorNum(1)
1407                                                 self["Network"].setText(_("disconnected"))
1408                                                 self["NetworkInfo_Check"].setPixmapNum(1)
1409                                                 self["NetworkInfo_Check"].show()
1410                                         else:
1411                                                 self["Network"].setForegroundColorNum(2)
1412                                                 self["Network"].setText(_("connected"))
1413                                                 self["NetworkInfo_Check"].setPixmapNum(0)
1414                                                 self["NetworkInfo_Check"].show()
1415                                                 
1416         def cleanup(self):
1417                 iNetwork.stopLinkStateConsole()
1418                 iNetwork.stopDNSConsole()
1419                 try:
1420                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus,Status
1421                 except ImportError:
1422                         pass
1423                 else:
1424                         iStatus.stopWlanConsole()
1425