4.2.1r16
[enigma2.git] / usr / lib / enigma2 / python / Plugins / SystemPlugins / NetworkManager / NetworkConfig.py
1 # -*- coding: utf-8 -*-
2 from enigma import eNetworkManager, eNetworkService, eNetworkServicePtr, StringList, StringMap
3
4 from Components.Label import Label
5 from Components.ActionMap import ActionMap
6 from Components.config import getConfigListEntry, ConfigIP, ConfigOnOff, ConfigIP6, ConfigSelection, ConfigInteger
7 from Components.ConfigList import ConfigListScreen
8 from Components.Sources.List import List
9 from Components.Sources.StaticText import StaticText
10 from Components.Network import NetworkInterface
11 from Screens.Screen import Screen
12
13 from Tools.BoundFunction import boundFunction
14 from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
15 from Tools.Log import Log
16 from Tools.LoadPixmap import LoadPixmap
17
18 from netaddr import IPAddress
19
20 def toIP4List(value):
21         return [ int(v) for v in str(value).split(".") ]
22
23 def toIP4String(cfg):
24         return cfg.tostring(cfg.value)
25
26 class NetworkConfigGeneral(object):
27         @staticmethod
28         def translateSecurity(security):
29                 security_map = {
30                         "none" : _("None"),
31                         "wep"  : "WEP",
32                         "psk"  : "WPA/WPA2",
33                         "wps"  : "WPS",
34                         "ieee8021x" : "ieee8021x",
35                 }
36                 return security_map.get(security, security.upper())
37
38         @staticmethod
39         def translateState(state):
40                 state_map = {
41                         "idle" : _("Idle"),
42                         "failure" : _("Failure"),
43                         "association" : _("Association"),
44                         "configuration" : _("Configuration"),
45                         "disconnect" : _("Disconnect"),
46                         "online" : _("Connected"),
47                 }
48                 return state_map.get(state, state)
49
50         def __init__(self):
51                 self._nm = eNetworkManager.getInstance()
52                 self._nm_conn = [
53                                 self._nm.technologiesChanged.connect(self._technologiesChanged),
54                                 self._nm.stateChanged.connect(self._servicesChanged),
55                                 self._nm.servicesChanged.connect(self._servicesChanged),
56                         ]
57                 self._tech_conn = []
58                 self._services = List([], enableWrapAround = True)
59                 self._services.buildfunc = self._buildServiceListEntry
60
61         def _getCurrentService(self):
62                 service = self._services.getCurrent()
63                 if service:
64                         return service[1]
65                 return None
66         _currentService = property(_getCurrentService)
67
68         def _technologiesChanged(self):
69                 pass
70
71         def _techPoweredChanged(self, powered):
72                 if powered:
73                         self._rescan()
74
75         def _setTechPowered(self, cfg):
76                 tech = cfg.tech
77                 powered = not tech.powered()
78                 tech.setPowered(powered)
79
80         def _scanFinished(self, tech):
81                 pass
82
83         def _rescan(self, tech=None):
84                 if tech is not None and tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
85                         Log.i("Triggering rescan for '%s'" %tech.name())
86                         tech.scan()
87                         return True
88
89                 res = False
90                 for tech in self._nm.getTechnologies():
91                         if tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
92                                 Log.i("Triggering rescan for '%s'" %tech.name())
93                                 tech.scan()
94                                 res = True
95                 return res
96
97         def _removeService(self):
98                 service = self._currentService
99                 if isinstance(service, eNetworkServicePtr):
100                         Log.i("Removing %s" %service.name())
101                         service.setAutoConnect(False)
102                         service.remove()
103
104         def getTechnologyConfig(self):
105                 l = []
106                 techs = self._nm.getTechnologies()
107                 self._tech_conn = []
108                 for tech in techs:
109                         cfg = ConfigOnOff(default=tech.powered())
110                         cfg.tech = tech
111                         cfg.addNotifier(self._setTechPowered, initial_call=False)
112                         self._tech_conn.append(tech.poweredChanged.connect(self._techPoweredChanged))
113                         self._tech_conn.append(tech.scanFinished.connect(boundFunction(self._scanFinished, tech)))
114                         title = "%s (%s)" %(tech.name(), tech.type())
115                         l.append(getConfigListEntry(title, cfg))
116                 Log.w(l)
117                 return l
118
119         def _servicesChanged(self, *args):
120                 pass
121
122         def getServiceList(self, unified=False):
123                 l = []
124                 services = self._nm.getServices()
125                 techs = self._nm.getTechnologies()
126                 self._tech_conn = []
127                 if unified:
128                         for tech in techs:
129                                 self._tech_conn.append(tech.poweredChanged.connect(self._techPoweredChanged))
130                                 self._tech_conn.append(tech.scanFinished.connect(boundFunction(self._scanFinished, tech)))
131                                 l.append( (tech.path(), tech,) )
132                                 for service in services:
133                                         if service.type() == tech.type():
134                                                 l.append( (service.path(), service,) )
135                 else:
136                         for service in services:
137                                 l.append( (service.path(), service,) )
138                 return l
139
140         def _buildListEntry(self, path, instance):
141                 if isinstance(instance, eNetworkServicePtr):
142                         return self._buildServiceListEntry(path, instance)
143                 else:
144                         return self._buildTechnologyListEntry(path, instance)
145
146         def _buildTechnologyListEntry(self, techpath, tech):
147                 #Log.i("technology: %s/%s" %(tech.name(), tech.type()))
148                 enabled = _("on") if tech.powered() else _("off")
149                 name = tech.name()
150                 if tech.isScanning():
151                         name = _("%s - scanning...") %name
152                 return (tech.path(), None, enabled, None, None, None, name, "")
153
154         def _buildServiceListEntry(self, svcpath, service):
155                 #Log.i("service: %s/%s/%s" %(service.name(), service.type(), service.strength()))
156                 strength = ""
157                 security = ""
158                 if service.type() == eNetworkService.TYPE_ETHERNET:
159                         if service.connected():
160                                 interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-active.png"))
161                         else:
162                                 if service.state() != eNetworkManager.STATE_IDLE:
163                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired.png"))
164                                 else:
165                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wired-inactive.png"))
166                 elif service.type() == eNetworkService.TYPE_WIFI:
167                         strength = "%s%s" %(service.strength(), "%")
168                         for sec in service.security():
169                                 if not security:
170                                         security = NetworkConfigGeneral.translateSecurity(sec)
171                                 else:
172                                         security = "%s, %s" %(security, NetworkConfigGeneral.translateSecurity(sec))
173                         if service.connected():
174                                 interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-active.png"))
175                         else:
176                                 if service.state() != eNetworkManager.STATE_IDLE:
177                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless.png"))
178                                 else:
179                                         interfacepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/network_wireless-inactive.png"))
180                 ip = ""
181
182                 if service.connected():
183                         ip = service.ipv4().get(eNetworkService.KEY_ADDRESS, "")
184                         if not ip:
185                                 ip = service.ipv6().get(eNetworkService.KEY_ADDRESS, "")
186
187
188                 return (service.path(), interfacepng, strength, service.name(), ip, NetworkConfigGeneral.translateState(service.state()), None, security)
189
190 class NetworkServiceConfig(Screen, NetworkConfigGeneral):
191         skin = """
192                 <screen name="NetworkServiceConfig" position="center,center" size="1020,500" title="Network Configuration" zPosition="0">
193                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
194                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
195                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
196                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
197
198                         <widget name="key_red" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
199                         <widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
200                         <widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
201                         <widget name="key_blue" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
202
203                         <widget source="list" render="Listbox" position="5,50" size="550,400" scrollbarMode="showOnDemand" zPosition="1">
204                                 <convert type="TemplatedMultiContent">
205                                         {"template":[
206                                                         MultiContentEntryPixmapAlphaTest(pos = (0, 0), size = (50, 50), png = 1), #type icon
207                                                         MultiContentEntryText(pos = (55, 0), size = (300, 24), font=0, flags = RT_HALIGN_LEFT, text = 3), #service name
208                                                         MultiContentEntryText(pos = (360, 0), size = (180, 18), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_BOTTOM, text = 7), #security
209                                                         MultiContentEntryText(pos = (430, 30), size = (110, 18), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_TOP, text = 2), #signal strength
210                                                         MultiContentEntryText(pos = (55, 30), size = (220, 18), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), #ip
211                                                         MultiContentEntryText(pos = (280, 30), size = (145, 18), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 5), #state
212                                                         MultiContentEntryText(pos = (5, 0), size = (490, 50), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 6), #technology name
213                                                 ],
214                                         "itemHeight": 50,
215                                         "fonts": [gFont("Regular", 22), gFont("Regular", 16)]
216                                         }
217                                 </convert>
218                         </widget>
219
220                         <widget name="hint" position="5,470" zPosition="1" size="555,25" font="Regular;20" halign="center" valign="center" transparent="1" />
221
222                         <eLabel position="570,10" size="440,480" zPosition="0" backgroundColor="#0E3B62" />
223                         <widget name="details_label" position="580,20" zPosition="1" size="420,25" font="Regular;22" backgroundColor="#0E3B62" transparent="1" />
224                         <widget name="details" position="580,55" zPosition="1" size="420,430" font="Regular;16" backgroundColor="#0E3B62" transparent="1" />
225                 </screen>"""
226
227         def __init__(self, session):
228                 Screen.__init__(self, session)
229                 NetworkConfigGeneral.__init__(self)
230
231                 self["key_red"] = Label(_("Reset"))
232                 self["key_green"] = Label(_("Scan"))
233                 self["key_yellow"] = Label(_("IP"))
234                 self["key_blue"] = Label(_("DNS"))
235                 self["hint"] = Label(_("Press OK to connect"))
236                 self["details_label"] = Label(_("Active Connection"))
237                 self["details"] = Label("")
238                 self["OkCancelActions"] = ActionMap(["OkCancelActions", "ColorActions"],
239                 {
240                         "cancel": self.close,
241                         "ok" : self._ok,
242                         "green": self._rescan,
243                         "red": self._removeService
244                 }, -3)
245                 self["ServiceActions"] = ActionMap(["ColorActions"],
246                 {
247                         "yellow": self._configIP,
248                         "blue": self._configDNS,
249                 }, -2)
250
251                 self["list"] = self._services
252                 self._hasWireless = False
253
254                 self._services.buildfunc = self._buildListEntry
255                 self._services.onSelectionChanged.append(self._selectionChanged)
256
257                 self._addNotifiers()
258                 self._createSetup()
259
260                 self.onClose.append(self._onClose)
261                 self.onLayoutFinish.append(self.layoutFinished)
262
263         def _rescan(self):
264                 if not self._currentService or isinstance(self._currentService, eNetworkServicePtr):
265                         return
266                 if self._currentService.type() != eNetworkService.TYPE_WIFI:
267                         return
268                 if NetworkConfigGeneral._rescan(self, self._currentService):
269                         self._createSetup()
270
271         def _scanFinished(self, tech):
272                 Log.i("finished!")
273                 self._createSetup()
274
275         def _removeService(self):
276                 NetworkConfigGeneral._removeService(self)
277                 self._createSetup()
278
279         def _selectionChanged(self):
280                 self._checkButtons()
281
282         def _checkButtons(self):
283                 self["hint"].setText("")
284                 if isinstance(self._currentService, eNetworkServicePtr): #a service
285                         self["key_green"].hide()
286                         if self._currentService.connected():
287                                 self["hint"].setText(_("Press OK to disconnect"))
288                         else:
289                                 self["hint"].setText(_("Press OK to connect"))
290                         if self._currentService.favorite():
291                                 self["key_red"].show()
292                         else:
293                                 self["key_red"].hide()
294                         self["key_yellow"].show()
295                         self["key_blue"].show()
296                         self["ServiceActions"].setEnabled(True)
297                 else: #a technology
298                         if self._currentService and self._currentService.type() == eNetworkService.TYPE_WIFI:
299                                 self["key_green"].show()
300                         else:
301                                 self["key_green"].hide()
302                         self["key_red"].hide()
303                         if self._currentService:
304                                 if self._currentService.powered():
305                                         self["hint"].setText(_("Press OK to disable"))
306                                 else:
307                                         self["hint"].setText(_("Press OK to enable"))
308                         else:
309                                 self["hint"].setText("")
310                         self["key_yellow"].hide()
311                         self["key_blue"].hide()
312                         self["ServiceActions"].setEnabled(False)
313
314         def _configChanged(self, *args, **kwargs):
315                 self._createSetup()
316
317         def _configIP(self):
318                 service = self._currentService
319                 if service:
320                         self.session.open(NetworkServiceIPConfig, service)
321
322         def _configDNS(self):
323                 service = self._currentService
324                 if service:
325                         self.session.open(NetworkServiceNSConfig, service)
326
327         def _technologiesChanged(self):
328                 self._createSetup()
329
330         def _servicesChanged(self, *args):
331                 self._createSetup()
332
333         def _addNotifiers(self):
334                 pass
335
336         def _removeNotifiers(self):
337                 pass
338
339         def _onClose(self):
340                 self._removeNotifiers()
341
342         def keyLeft(self):
343                 ConfigListScreen.keyLeft(self)
344
345         def keyRight(self):
346                 ConfigListScreen.keyRight(self)
347
348         def _ok(self):
349                 item = self._currentService
350                 if not item:
351                         return
352                 if isinstance(item, eNetworkServicePtr):
353                         state = item.state()
354                         Log.i(state)
355                         if state == eNetworkManager.STATE_IDLE or state == eNetworkManager.STATE_FAILURE:
356                                 item.requestDisconnect()
357                                 item.requestConnect()
358                                 item.setAutoConnect(True)
359                         else:
360                                 item.requestDisconnect()
361                 else:
362                         item.setPowered(not item.powered())
363
364         def _createSetup(self):
365                 self._hasWireless = False
366                 for tech in self._nm.getTechnologies():
367                         if tech.type() == eNetworkService.TYPE_WIFI and tech.powered():
368                                 self._hasWireless = True
369                 self._services.updateList(self.getServiceList(unified=True))
370                 self._checkButtons()
371                 self._setDetailText()
372
373         def _setDetailText(self):
374                 text = ""
375                 for service in self._nm.getServices():
376                         if service.connected():
377                                 if text:
378                                         text = "\n\n%s" %(text)
379
380                                 text = "%s\n\n" %(service.name())
381                                 ni = NetworkInterface(service)
382                                 ip4 = ni.getIpv4()
383                                 ip6 = ni.getIpv6()
384                                 iptext = _("%s IPv%s\n  Address: %s\n  %s: %s\n  Gateway: %s\n\n")
385                                 #IPv4
386                                 if ip4.method != eNetworkService.METHOD_OFF:
387                                         addr = ip4.address
388                                         mask = ip4.netmask
389                                         gw = ip4.gateway
390                                         text = iptext %(
391                                                         text,
392                                                         4,
393                                                         addr,
394                                                         _("Netmask"),
395                                                         mask,
396                                                         gw,
397                                                 )
398                                 #IPv6
399                                 if ip6.method != eNetworkService.METHOD_OFF:
400                                         addr = ip6.address
401                                         mask = ip6.netmask
402                                         gw = ip6.gateway
403                                         text = iptext %(
404                                                         text,
405                                                         6,
406                                                         addr,
407                                                         _("Prefix length"),
408                                                         mask,
409                                                         gw,
410                                                 )
411                                 ns = self._textFormatIpList( service.nameservers() )
412                                 text = _("%sNameserver\n%s\n") %(text, ns) or _("n/a")
413                                 ts = self._textFormatIpList( service.timeservers() )
414                                 text = _("%s\nTimeserver\n%s\n") %(text, ts)
415                                 break
416                 self["details"].setText(text)
417
418         def _textFormatIpList(self, iplist):
419                 if not iplist:
420                         return "  %s" %(_("n/a"))
421                 iplist = "  %s" %("\n  ".join(iplist))
422                 return iplist
423
424         def _techPoweredChanged(self, powered):
425                 if powered:
426                         self._rescan()
427                 self._createSetup()
428
429         def layoutFinished(self):
430                 self.setTitle(_("Network Config"))
431                 self._checkButtons()
432
433 class ServiceBoundConfiguration(object):
434         def __init__(self, service):
435                 self._service = service
436                 nm = eNetworkManager.getInstance()
437                 self._svcRemovedConn = nm.serviceRemoved.connect(self.__onServiceRemoved)
438                 self._isServiceRemoved = False
439
440         def __onServiceRemoved(self, svcpath):
441                 if svcpath == self._service.path():
442                         Log.i("Service '%s' removed. Closing..." %svcpath)
443                         self._isServiceRemoved = True
444                         #TODO show a messagebox! The user will be VERY confused otherwise!
445                         self.close()
446
447 class ServiceIPConfiguration(object):
448         def __init__(self, service):
449                 self._service = service
450                 self.onChanged = []
451                 self.onMethodChanged = []
452                 method_choices_ip4 = {eNetworkService.METHOD_DHCP : "dhcp", eNetworkService.METHOD_MANUAL : _("manual"), eNetworkService.METHOD_OFF : _("off")}
453                 #IPv4
454                 self._config_ip4_method = ConfigSelection(method_choices_ip4, default=eNetworkService.METHOD_DHCP)
455                 self._config_ip4_address = ConfigIP(default=[0,0,0,0])
456                 self._config_ip4_mask = ConfigIP(default=[0,0,0,0])
457                 self._config_ip4_gw = ConfigIP(default=[0,0,0,0])
458                 #IPv6
459                 method_choices_ip6 = {eNetworkService.METHOD_AUTO : _("auto"), eNetworkService.METHOD_6TO4 : "6to4", eNetworkService.METHOD_MANUAL : _("manual"), eNetworkService.METHOD_OFF : _("off")}
460                 choices_privacy_ip6 = {eNetworkService.IPV6_PRIVACY_DISABLED : _("Disabled"), eNetworkService.IPV6_PRIVACY_ENABLED : _("Enabled"), eNetworkService.IPV6_PRIVACY_PREFERRED : _("Preferred")}
461                 self._config_ip6_method = ConfigSelection(method_choices_ip6, default=eNetworkService.METHOD_DHCP)
462                 self._config_ip6_address = ConfigIP6()
463                 self._config_ip6_prefix_length = ConfigInteger(0, limits=(1, 128))
464                 self._config_ip6_gw = ConfigIP6()
465                 self._config_ip6_privacy = ConfigSelection(choices_privacy_ip6, default="disabled")
466
467                 self._isReloading = False
468                 self._ipv4Changed = False
469                 self._ipv6Changed = False
470                 self._addNotifiers()
471                 self._service_conn = [
472                         self._service.ipv4Changed.connect(self._serviceChanged),
473                         self._service.ipv6Changed.connect(self._serviceChanged),
474                         self._service.ipv4ConfigChanged.connect(self._serviceChanged),
475                         self._service.ipv6ConfigChanged.connect(self._serviceChanged),
476                 ]
477
478         def _serviceChanged(self, *args):
479                 self.reload(force=False)
480
481         def _addNotifiers(self):
482                 #Setup refresh
483                 self._config_ip4_method.addNotifier(self._methodChanged, initial_call=False)
484                 self._config_ip6_method.addNotifier(self._methodChanged, initial_call=False)
485
486                 #change tracking
487                 #ipv4
488                 self._config_ip4_method.addNotifier(self._changedIP4, initial_call=False)
489                 self._config_ip4_address.addNotifier(self._changedIP4, initial_call=False)
490                 self._config_ip4_mask.addNotifier(self._changedIP4, initial_call=False)
491                 self._config_ip4_gw.addNotifier(self._changedIP4, initial_call=False)
492                 #ipv6
493                 self._config_ip6_method.addNotifier(self._changedIP6, initial_call=False)
494                 self._config_ip6_address.addNotifier(self._changedIP6, initial_call=False)
495                 self._config_ip6_prefix_length.addNotifier(self._changedIP6, initial_call=False)
496                 self._config_ip6_gw.addNotifier(self._changedIP6, initial_call=False)
497                 self._config_ip6_privacy.addNotifier(self._changedIP6, initial_call=False)
498
499         def _changedIP4(self, element):
500                 if not self._isReloading:
501                         self._ipv4Changed = True
502                 self._changed(element)
503
504         def _changedIP6(self, element):
505                 if not self._isReloading:
506                         self._ipv6Changed = True
507                 self._changed(element)
508
509         def _changed(self, element):
510                 if not self._isReloading:
511                         Log.i()
512                         for fnc in self.onChanged:
513                                 fnc()
514
515         def _methodChanged(self, element):
516                 if not self._isReloading:
517                         Log.i()
518                         for fnc in self.onMethodChanged:
519                                 fnc()
520
521         def reload(self, force=True):
522                 self._isReloading = True
523                 if force:
524                         self._ipv4Changed = False
525                         self._ipv6Changed = False
526                 if not self._ipv6Changed:
527                         ip4 = self._service.ipv4()
528                         if not dict(ip4):
529                                 ip6 = self._service.ipv4Config()
530                         self._config_ip4_method.value = ip4.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
531                         self._config_ip4_address.value = toIP4List( ip4.get("Address", "0.0.0.0") )
532                         self._config_ip4_mask.value = toIP4List( ip4.get(eNetworkService.KEY_NETMASK, "0.0.0.0") )
533                         self._config_ip4_gw.value = toIP4List( ip4.get(eNetworkService.KEY_GATEWAY, "0.0.0.0") )
534                 if not self._ipv6Changed:
535                         ip6 = self._service.ipv6()
536                         Log.i("%s / %s" %(dict(ip6), dict(self._service.ipv6Config())) )
537                         if not dict(ip6):
538                                 ip6 = self._service.ipv6Config()
539                         self._config_ip6_method.value = ip6.get(eNetworkService.KEY_METHOD, eNetworkService.METHOD_OFF)
540                         self._config_ip6_address.value = ip6.get(eNetworkService.KEY_ADDRESS, "::")
541                         self._config_ip6_prefix_length.value = ord( ip6.get(eNetworkService.KEY_PREFIX_LENGTH, chr(1)) )
542                         self._config_ip6_gw.value = ip6.get(eNetworkService.KEY_GATEWAY, "::")
543                         self._config_ip6_privacy.value = ip6.get(eNetworkService.KEY_PRIVACY, eNetworkService.IPV6_PRIVACY_DISABLED)
544                 self._isReloading = False
545                 self._changed(None)
546
547         def getList(self):
548                 if self._config_ip4_method.value == eNetworkService.METHOD_MANUAL:
549                         self._config_ip4_address.enabled = True
550                         self._config_ip4_mask.enabled = True
551                         self._config_ip4_gw.enabled = True
552                 else:
553                         self._config_ip4_address.enabled = False
554                         self._config_ip4_mask.enabled = False
555                         self._config_ip4_gw.enabled = False
556                 if self._config_ip6_method.value == eNetworkService.METHOD_MANUAL:
557                         self._config_ip6_address.enabled = True
558                         self._config_ip6_prefix_length.enabled = True
559                         self._config_ip6_gw.enabled = True
560                 else:
561                         self._config_ip6_address.enabled = False
562                         self._config_ip6_prefix_length.enabled = False
563                         self._config_ip6_gw.enabled = False
564
565                 l = [ getConfigListEntry(_("Method (IPv4)"), self._config_ip4_method), ]
566                 if self._config_ip4_method.value != eNetworkService.METHOD_OFF:
567                         l.extend([
568                                 getConfigListEntry(_("Address (IPv4)"), self._config_ip4_address),
569                                 getConfigListEntry(_("Mask (IPv4)"), self._config_ip4_mask),
570                                 getConfigListEntry(_("Gateway (IPv4)"), self._config_ip4_gw),
571                         ])
572                 l.append( getConfigListEntry(_("Method (IPv6)"), self._config_ip6_method))
573                 if self._config_ip6_method.value != eNetworkService.METHOD_OFF:
574                         l.extend([
575                                 getConfigListEntry(_("Address (IPv6)"), self._config_ip6_address),
576                                 getConfigListEntry(_("Prefix length (IPv6)"), self._config_ip6_prefix_length),
577                                 getConfigListEntry(_("Gateway (IPv6)"), self._config_ip6_gw),
578                         ])
579                 if self._config_ip6_method.value in (eNetworkService.METHOD_AUTO, eNetworkService.METHOD_6TO4):
580                         l.append( getConfigListEntry(_("Privacy (IPv6)"), self._config_ip6_privacy) )
581                 return l
582
583         def save(self):
584                 if self._ipv4Changed:
585                         Log.i("IPv4 Changed, saving!")
586                         if self._config_ip4_method.value == eNetworkService.METHOD_MANUAL:
587                                 ip4_config = {
588                                                 eNetworkService.KEY_METHOD : self._config_ip4_method.value,
589                                                 eNetworkService.KEY_ADDRESS : toIP4String(self._config_ip4_address),
590                                                 eNetworkService.KEY_NETMASK : toIP4String(self._config_ip4_mask),
591                                                 eNetworkService.KEY_GATEWAY : toIP4String(self._config_ip4_gw),
592                                         }
593                         else:
594                                 ip4_config = { eNetworkService.KEY_METHOD : self._config_ip4_method.value }
595                         Log.i(ip4_config)
596                         self._service.setIpv4Config(StringMap(ip4_config))
597
598                 if self._ipv6Changed:
599                         Log.i("IPv6 Changed, saving!")
600                         if self._config_ip6_method.value == eNetworkService.METHOD_MANUAL:
601                                 ip6_config = {
602                                                 eNetworkService.KEY_METHOD : self._config_ip6_method.value,
603                                                 eNetworkService.KEY_ADDRESS : self._config_ip6_address.value,
604                                                 eNetworkService.KEY_PREFIX_LENGTH : self._config_ip6_prefix_length.value,
605                                                 eNetworkService.KEY_GATEWAY : self._config_ip6_gw.value,
606                                                 eNetworkService.KEY_PRIVACY : self._config_ip6_privacy.value,
607                                         }
608                         else:
609                                 val = self._config_ip6_method.value #avoid config element overhead here
610                                 #one can not configure 6to4, it will automatically be applied by connman if applicable -> change it to auto
611                                 if val == eNetworkService.METHOD_6TO4:
612                                         val = eNetworkService.METHOD_AUTO
613
614                                 ip6_config = { eNetworkService.KEY_METHOD : val }
615                                 if val != eNetworkService.METHOD_OFF:
616                                         ip6_config[eNetworkService.KEY_PRIVACY] = self._config_ip6_privacy.value
617                         Log.i(ip6_config)
618                         self._service.setIpv6Config(StringMap(ip6_config))
619
620 class NetworkServiceIPConfig(ConfigListScreen, Screen, ServiceBoundConfiguration):
621         skin = """
622                 <screen name="NetworkServiceIPConfig" position="center,center" size="560,400" title="Network: Service configuration">
623                         <!--
624                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
625                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
626                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
627                         -->
628                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
629                         <!--
630                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
631                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
632                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
633                         -->
634                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
635                         <widget name="config" position="5,50" size="550,360" scrollbarMode="showOnDemand" zPosition="1"/>
636                 </screen>"""
637
638         def __init__(self, session, service):
639                 Screen.__init__(self, session)
640                 ConfigListScreen.__init__(self, [], session=session)
641                 ServiceBoundConfiguration.__init__(self, service)
642
643                 self["key_blue"] = StaticText(_("Reset"))
644                 self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
645                 {
646                         "blue": self._reload,
647                         "save": self.close,
648                         "cancel": self.close,
649                         "ok" : self.close,
650                 }, -2)
651
652                 self._ipconfig = ServiceIPConfiguration(self._service)
653                 self._ipconfig.onMethodChanged.append(self._createSetup)
654                 self._noSave = False
655
656                 self._reload()
657                 self.onClose.append(self.__onClose)
658
659         def __onClose(self):
660                 self._ipconfig.onMethodChanged.remove(self._createSetup)
661                 self._apply()
662                 del self._ipconfig
663
664         def _apply(self):
665                 if self._isServiceRemoved:
666                         return
667                 self._ipconfig.save()
668
669         def _reload(self):
670                 self._ipconfig.reload()
671                 self._createSetup()
672
673         def _createSetup(self):
674                 self["config"].list = self._ipconfig.getList()
675
676 class ServiceNSConfiguration(object):
677         def __init__(self, service):
678                 self._service = service
679                 self.onChanged = []
680                 self._nameservers = []
681
682         def reload(self):
683                 self._nameservers = []
684                 ns = self._service.nameserversConfig()
685                 for n in ns:
686                         ip = IPAddress(n)
687                         if ip.version == 4:
688                                 cfg = ConfigIP( default=toIP4List(ip.format()))
689                                 self._nameservers.append(cfg)
690                         elif ip.version == 6:
691                                 cfg = ConfigIP6(default=ip.format())
692                                 self._nameservers.append(cfg)
693
694         def getList(self):
695                 return [ getConfigListEntry("Nameserver", ns) for ns in self._nameservers ]
696
697         def add4(self):
698                 self._nameservers.append(ConfigIP([0,0,0,0]))
699
700         def add6(self):
701                 self._nameservers.append(ConfigIP6())
702
703         def remove(self, cfg):
704                 self._nameservers.remove(cfg)
705
706         def save(self):
707                 servers = []
708                 for nscfg in self._nameservers:
709                         if isinstance(nscfg, ConfigIP):
710                                 servers.append(toIP4String(nscfg))
711                         elif isinstance(nscfg, ConfigIP6):
712                                 servers.append(nscfg.value)
713                 self._service.setNameserversConfig(StringList(servers))
714
715 class NetworkServiceNSConfig(ConfigListScreen, Screen, ServiceBoundConfiguration):
716         skin = """
717                 <screen name="NetworkServiceNSConfig" position="center,center" size="560,400" title="Service: Nameserver configuration">
718                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
719                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
720                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
721                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
722                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
723                         <widget source="key_green"
724                          render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
725                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
726                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
727                         <widget name="config" position="5,50" size="550,260" scrollbarMode="showOnDemand" zPosition="1"/>
728                         <widget source="activedns" position="5,320" size="550,80" render="Label" font="Regular;20" valign="bottom" backgroundColor="background" transparent="1" zPosition="1" />
729                 </screen>"""
730
731         def __init__(self, session, service):
732                 Screen.__init__(self, session)
733                 ConfigListScreen.__init__(self, [], session=session)
734                 ServiceBoundConfiguration.__init__(self, service)
735
736                 self["key_red"] = StaticText(_("Delete"))
737                 self["key_green"] = StaticText(_("New (IPv4)"))
738                 self["key_yellow"] = StaticText(_("New (IPv6)"))
739                 self["key_blue"] = StaticText(_("Reset"))
740                 self["activedns"] = StaticText(self.getActiveDnsText())
741                 self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
742                 {
743                         "red": self._remove,
744                         "green": self._add4,
745                         "yellow": self._add6,
746                         "blue": self._reload,
747                         "save": self.close,
748                         "cancel": self.close,
749                         "ok" : self.close,
750                 }, -2)
751
752                 self._nsconfig = ServiceNSConfiguration(self._service)
753                 self._reload()
754                 self.onClose.append(self.__onClose)
755                 self.onLayoutFinish.append(self._layoutFinished)
756
757         def getActiveDnsText(self):
758                 nameservers = list(self._service.nameservers())
759                 text = ""
760                 if nameservers:
761                         text = _("Active Nameservers:\n%s") %(", ".join(nameservers))
762                         Log.i(text)
763                 return text
764
765         def _layoutFinished(self):
766                 self.setTitle(_("%s Network - Nameservers" %self._service.name()))
767
768         def _remove(self):
769                 cfg = self["config"].getCurrent()
770                 if cfg:
771                         self._nsconfig.remove(cfg[1])
772                         self._createSetup()
773
774         def _add4(self):
775                 self._nsconfig.add4()
776                 self._createSetup()
777
778         def _add6(self):
779                 self._nsconfig.add6()
780                 self._createSetup()
781
782         def __onClose(self):
783                 if self._isServiceRemoved:
784                         return
785                 self._nsconfig.save()
786
787         def _reload(self):
788                 self._nsconfig.reload()
789                 self._createSetup()
790
791         def _createSetup(self):
792                 self["config"].setList( self._nsconfig.getList() )