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