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