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