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