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