enigma2 20131118 (master) -> 20140214 (master)
[enigma2.git] / usr / lib / enigma2 / python / Screens / HarddiskSetup.py
1 from Screen import Screen
2 from Components.ActionMap import ActionMap, HelpableActionMap
3 from Components.Harddisk import harddiskmanager  #global harddiskmanager
4 from Components.Label import Label
5 from Components.Pixmap import Pixmap
6 from Components.FileList import FileList
7 from Components.Sources.List import List
8 from Components.Sources.StaticText import StaticText
9 from Components.Sources.Boolean import Boolean
10 from Components.ConfigList import ConfigListScreen
11 from Components.config import config, configfile, getConfigListEntry
12 from Components.UsageConfig import defaultStorageDevice
13 from Components.PluginComponent import plugins
14 from Plugins.Plugin import PluginDescriptor
15 from Screens.ChoiceBox import ChoiceBox
16 from Screens.MessageBox import MessageBox
17 from Screens.HelpMenu import HelpableScreen
18 from Screens.Setup import Setup
19 from Screens.VirtualKeyBoard import VirtualKeyBoard
20 from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
21 from Tools.LoadPixmap import LoadPixmap
22 from Tools.BoundFunction import boundFunction
23 from enigma import eTimer
24 from os import path, makedirs, listdir, access, F_OK, R_OK
25
26 HARDDISK_INITIALIZE = 1
27 HARDDISK_CHECK = 2
28
29 harddisk_description = {'desc': _("hard disk"),'Desc': _("Hard disk")}
30 storagedevice_description = {'desc': _("storage device"),'Desc': _("Storage device")}
31
32 def updateVideoDirs(uuid = None):
33         tmp = config.movielist.videodirs.value
34         mountpath = moviedir = ""
35         cfg = config.storage.get(uuid, None)
36         if cfg is not None:
37                 p = harddiskmanager.getPartitionbyUUID(uuid)
38                 if p is not None:
39                         mountpath = cfg['mountpoint'].value
40                         if cfg["enabled"].value:
41                                 if p.isInitialized and uuid == defaultStorageDevice():
42                                         moviedir = "/hdd/movie/"
43                                 elif p.isInitialized and uuid != defaultStorageDevice():
44                                         moviedir = mountpath + "/movie/"
45                                 else:
46                                         moviedir = mountpath + "/"
47                                 if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir not in tmp:
48                                         tmp.append(moviedir)
49                         else:
50                                 if p.isInitialized:
51                                         moviedir = mountpath + "/movie/"
52                                 else:
53                                         moviedir = mountpath + "/"
54                                 if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
55                                         tmp.remove(moviedir)
56                 else:
57                         mountpath = cfg['mountpoint'].value
58                         moviedir = mountpath + "/"
59                         if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
60                                 tmp.remove(moviedir)
61                         moviedir += "movie/"
62                         if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
63                                 tmp.remove(moviedir)
64
65         if "/hdd/movie/" not in tmp:
66                 tmp.append("/hdd/movie/")
67         config.movielist.videodirs.value = tmp
68         config.movielist.videodirs.save()
69         config.movielist.save()
70         configfile.save()
71         print "updateVideoDirs:",config.movielist.videodirs.value
72
73 def doFstabUpgrade(uuid, path, mp, callConfirmApply, applyCallback = None, answer = None, selection = None):
74         print "[doFstabUpgrade] - Removing hard mount entry from fstab.",path, mp, answer, selection
75         partitionPath = path
76         uuidpartitionPath = "/dev/disk/by-uuid/" + uuid
77         mountpath = mp
78         if harddiskmanager.isPartitionpathFsTabMount(uuid,mountpath):
79                 harddiskmanager.unmountPartitionbyMountpoint(mountpath)
80                 harddiskmanager.modifyFstabEntry(partitionPath, mountpath, mode = "remove")
81         if harddiskmanager.isUUIDpathFsTabMount(uuid,mountpath):
82                 harddiskmanager.unmountPartitionbyMountpoint(mountpath)
83                 harddiskmanager.modifyFstabEntry(uuidpartitionPath, mountpath, mode = "remove")
84         if mountpath != "/media/hdd":
85                 if harddiskmanager.isPartitionpathFsTabMount(uuid,"/media/hdd"):
86                         harddiskmanager.unmountPartitionbyMountpoint("/media/hdd")
87                         harddiskmanager.modifyFstabEntry(partitionPath, "/media/hdd", mode = "remove")
88                 if harddiskmanager.isUUIDpathFsTabMount(uuid,"/media/hdd"):
89                         harddiskmanager.unmountPartitionbyMountpoint("/media/hdd")
90                         harddiskmanager.modifyFstabEntry(uuidpartitionPath, "/media/hdd", mode = "remove")
91
92         if applyCallback is not None:
93                 if harddiskmanager.get_fstab_mountstate(partitionPath, mountpath) == 'auto' or harddiskmanager.get_fstab_mountstate(uuidpartitionPath, mountpath) == 'auto' \
94                         or harddiskmanager.get_fstab_mountstate(partitionPath, "/media/hdd") == 'auto' or harddiskmanager.get_fstab_mountstate(uuidpartitionPath, "/media/hdd") == 'auto':
95                         if answer is not None and selection is not None:
96                                 applyCallback(False, callConfirmApply, answer, selection)
97                         else:
98                                 applyCallback(False, callConfirmApply)
99                 else:
100                         if answer is not None and selection is not None:
101                                 applyCallback(True, callConfirmApply, answer, selection)
102                         else:
103                                 applyCallback(True, callConfirmApply)
104         else:
105                 print "error removing fstab entry!"
106
107 def hddConfirmed(confirmed, stype, hdd, partition = None, callback = None ):
108         if not confirmed:
109                 return
110         print "hddConfirmed: this will start either the initialize or the fsck now!"
111         UUIDPartitionList = [ ]
112         if stype == HARDDISK_INITIALIZE:
113                 print "hddConfirmed: start initialize for device:%s and partitions:%s" % (hdd.device, hdd.numPartitions())
114                 for p in harddiskmanager.partitions[:]:
115                         if p.device is not None:
116                                 if p.device.startswith(hdd.device):
117                                         if p.uuid is not None:
118                                                 UUIDPartitionList.append(p.uuid)
119                 if UUIDPartitionList:
120                         for uuid in UUIDPartitionList[:]:
121                                 cfg = config.storage.get(uuid, None)
122                                 if cfg is not None:
123                                         harddiskmanager.unmountPartitionbyUUID(uuid)
124                                         harddiskmanager.modifyFstabEntry("/dev/disk/by-uuid/" + uuid, cfg["mountpoint"].value, mode = "remove")
125                                         cfg["enabled"].value = False
126                                         updateVideoDirs(uuid)
127                                         del config.storage[uuid]
128                                         print "hddConfirmed: known device re-initialize, removed old uuid:",uuid
129                                 else:
130                                         harddiskmanager.unmountPartitionbyUUID(uuid)
131
132                                 dev = harddiskmanager.getDeviceNamebyUUID(uuid)
133                                 if dev is not None:
134                                         harddiskmanager.unmountPartitionbyMountpoint("/autofs/" + dev)
135
136                 if defaultStorageDevice() in UUIDPartitionList: # we initialized the 'current' default storage device
137                         config.storage_options.default_device.value = "<undefined>"
138                 config.storage.save()
139                 configfile.save()
140         elif stype == HARDDISK_CHECK:
141                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hdd,partition)
142                 harddiskmanager.unmountPartitionbyUUID(uuid)
143
144         if callback is not None:
145                 callback(stype, hdd, partition)
146
147
148 class HarddiskWait(Screen):
149         def doInit(self):
150                 self.timer.stop()
151                 result = self.hdd.initialize(self.isFstabMounted, self.numpart)
152                 if harddiskmanager.KernelVersion < "3.2":
153                         harddiskmanager.trigger_udev()
154                 self.close(result)
155
156         def doCheck(self):
157                 self.timer.stop()
158                 result = self.hdd.check( self.isFstabMounted, self.numpart )
159                 self.close(result)
160
161         def __init__(self, session, hdd, stype, numpart = None):
162                 Screen.__init__(self, session)
163                 self.hdd = hdd
164                 self.devicedescription = storagedevice_description
165                 if not self.hdd.isRemovable:
166                         self.devicedescription = harddisk_description
167                 self.isFstabMounted = False
168                 self.numpart = numpart
169                 uuid = partitionPath = None
170                 if not self.numpart:
171                         self.numpart = self.hdd.numPartitions()
172
173                 if self.numpart == 0:
174                         uuid = harddiskmanager.getPartitionUUID(hdd.device)
175                         partitionPath = hdd.dev_path
176                 if self.numpart >= 1:
177                         uuid = harddiskmanager.getPartitionUUID(hdd.device + str(self.numpart))
178                         partitionPath = hdd.partitionPath(str(self.numpart))
179
180                 if uuid is not None:
181                         mountpath = harddiskmanager.get_fstab_mountpoint(partitionPath)
182                         if harddiskmanager.isUUIDpathFsTabMount(uuid, mountpath) or harddiskmanager.isPartitionpathFsTabMount(uuid, mountpath):
183                                 self.isFstabMounted = True
184
185                 self.timer = eTimer()
186                 if stype == HARDDISK_INITIALIZE:
187                         text = _("Initializing %(desc)s...") % self.devicedescription
188                         self.timer.callback.append(self.doInit)
189                 elif stype == HARDDISK_CHECK:
190                         text = _("Checking Filesystem...")
191                         self.timer.callback.append(self.doCheck)
192                 self["wait"] = Label(text)
193                 self.timer.start(100)
194
195
196 class HarddiskDriveSetup(Screen, ConfigListScreen):
197
198         def __init__(self, session, device = None, partition = False):
199                 Screen.__init__(self, session)
200                 self.skinName = "HarddiskDriveSetup"
201                 self.hdd = device
202                 self.devicedescription = storagedevice_description
203                 if not self.hdd.isRemovable:
204                         self.devicedescription = harddisk_description
205
206                 self.oldMountpath = None
207                 self.oldEnabledState = None
208                 self.UUIDPartitionList = [ ]
209
210                 self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.uuidPath, self.partitionPath = harddiskmanager.getPartitionVars(self.hdd,partition)
211                 print "[HarddiskDriveSetup] - deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s' - partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
212                 % (self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
213
214                 self.setup_title = _("Partition") + " " + self.deviceName
215                 if config.storage.get(self.UUID, None) is not None:
216                         self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
217                         self.oldEnabledState = config.storage[self.UUID]["enabled"].value
218
219
220                 self.onChangedEntry = [ ]
221                 self.list = [ ]
222                 ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
223
224                 self["key_red"] = StaticText()
225                 self["key_green"] = StaticText()
226                 self["key_yellow"] = StaticText()
227                 self["key_blue"] = StaticText()
228                 self["introduction"] = StaticText()
229                 self["model"] = StaticText(_("Model") + ": " + self.hdd.model())
230                 self["capacity"] = StaticText(_("Capacity") + ": "  + self.hdd.capacity())
231                 self["bus"] = StaticText(self.hdd.bus_description() + " " + "%(Desc)s" % self.devicedescription)
232                 self["icon"] = StaticText()
233                 self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-open.png"))
234                 if self.hdd.isRemovable:
235                         self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-big.png"))
236                 self["HelpWindow"] = Pixmap()
237                 self["HelpWindow"].hide()
238
239                 self["OkCancelActions"] = ActionMap(["OkCancelActions"],
240                         {
241                         "cancel": self.keyCancel,
242                         "ok": self.ok,
243                         }, -2)
244
245                 self["mountshortcuts"] = ActionMap(["ShortcutActions"],
246                         {
247                         "green": self.apply
248                         }, -2)
249
250                 self["mountshortcuts"].setEnabled(False)
251
252                 self.createSetup()
253                 self.onLayoutFinish.append(self.layoutFinished)
254                 self.onShown.append(self.__onShown)
255
256         def layoutFinished(self):
257                 self.setTitle(self.setup_title)
258
259         def __onShown(self):
260                 self.selectionChanged()
261
262         def createSetup(self):
263                 self.list = [ ]
264                 if self.numPartitions >= 0:
265                         if self.UUID is not None and config.storage.get(self.UUID, None) is None:
266                                 harddiskmanager.setupConfigEntries(initial_call = False, dev = self.deviceName)
267                         uuid_cfg = config.storage.get(self.UUID, None)
268                         if uuid_cfg is not None:
269                                 self["mountshortcuts"].setEnabled(True)
270                                 self.list = [getConfigListEntry(_("Enable partition automount?"), uuid_cfg["enabled"])]
271                                 if uuid_cfg["enabled"].value:
272                                         if uuid_cfg["mountpoint"].value == "" or ( self.oldEnabledState is False and uuid_cfg["mountpoint"].value == "/media/hdd"):
273                                                 val = harddiskmanager.suggestDeviceMountpath(self.UUID)
274                                                 if self.UUID == defaultStorageDevice():
275                                                         val = "/media/hdd"
276                                                 uuid_cfg["mountpoint"].value = val
277                                         self.list.append(getConfigListEntry(_("Mountpoint:"), uuid_cfg["mountpoint"]))
278
279                 self["config"].list = self.list
280                 self["config"].l.setSeperation(400)
281                 self["config"].l.setList(self.list)
282                 if not self.selectionChanged in self["config"].onSelectionChanged:
283                         self["config"].onSelectionChanged.append(self.selectionChanged)
284
285         def selectionChanged(self):
286                 if self.numPartitions >= 0:
287                         uuid_cfg = config.storage.get(self.UUID, None)
288                         if uuid_cfg is not None:
289                                 if self["config"].isChanged():
290                                         self["key_green"].setText(_("Save"))
291                                 else:
292                                         self["key_green"].setText("")
293                                 if self["config"].getCurrent()[1] == uuid_cfg["enabled"]:
294                                         self["introduction"].setText(_("Enable automatic partition mounting?"))
295                                 elif self["config"].getCurrent()[1] == uuid_cfg["mountpoint"]:
296                                         self["introduction"].setText(_("Please enter the directory to use as mountpoint or select a directory by pressing OK."))
297                                 else:
298                                         self["introduction"].setText("")
299
300         def changedConfigList(self):
301                 if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
302                         if self["config"].getCurrent()[1] == config.storage[self.UUID]["enabled"]:
303                                 self.createSetup()
304
305         def keyLeft(self):
306                 if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
307                         ConfigListScreen.keyLeft(self)
308                         self.changedConfigList()
309
310         def keyRight(self):
311                 if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
312                         ConfigListScreen.keyRight(self)
313                         self.changedConfigList()
314
315         def ok(self):
316                 if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
317                         current = self["config"].getCurrent()
318                         if current is not None:
319                                 if current[1] == config.storage[self.UUID]["mountpoint"]:
320                                         self.hideHelpWindow()
321                                         self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
322                                         self.session.openWithCallback(self.MountpointBrowserClosed, HarddiskMountpointBrowser, self.hdd, self.UUID)
323
324         def hideHelpWindow(self):
325                 current = self["config"].getCurrent()
326                 if current and config.storage.get(self.UUID, None) is not None:
327                         if current[1] == config.storage[self.UUID]["mountpoint"]:
328                                 if current[1].help_window.instance is not None:
329                                         current[1].help_window.instance.hide()
330
331         def MountpointBrowserClosed(self, retval = None):
332                 if retval and retval is not None:
333                         mountpath = retval.strip().replace(' ','')
334                         if retval.endswith("/"):
335                                 mountpath = retval[:-1]
336                         print "MountpointBrowserClosed: with path: " + str(mountpath)
337                         try:
338                                 if mountpath != self.oldMountpath:
339                                         if not path.exists(mountpath):
340                                                 makedirs(mountpath)
341                         except OSError:
342                                 print "mountpoint directory could not be created."
343
344                         if not path.exists(mountpath):
345                                 self.session.open(MessageBox, _("Sorry, your directory is not writeable."), MessageBox.TYPE_INFO, timeout = 10)
346
347                         else:
348                                 self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
349                                 config.storage[self.UUID]["mountpoint"].setValue(str(mountpath))
350                                 self.selectionChanged()
351                                 if (harddiskmanager.is_hard_mounted(self.partitionPath) or harddiskmanager.is_hard_mounted(self.uuidPath)):
352                                         message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
353                                         if harddiskmanager.isUUIDpathFsTabMount(self.UUID, mountpath) or harddiskmanager.isPartitionpathFsTabMount(self.UUID, mountpath) \
354                                                 or harddiskmanager.isUUIDpathFsTabMount(self.UUID, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(self.UUID, "/media/hdd"):
355                                                 self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, self.UUID, self.partitionPath, mountpath, False), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
356
357         def confirmFstabUpgrade(self, result, uuid, partitionPath, mountpath, callConfirmApply = False):
358                 print "[HarddiskSetup] - confirmFstabUpgrade:",result, uuid, partitionPath, mountpath, callConfirmApply
359                 if not result:
360                         return
361                 doFstabUpgrade(uuid, partitionPath, mountpath, callConfirmApply, self.confirmFstabUpgradeCB)
362
363         def confirmFstabUpgradeCB(self, *val):
364                 answer, result = val
365                 if answer is not None:
366                         if answer:
367                                 if result:
368                                         self.session.openWithCallback(lambda x : self.confirmApply(True), MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
369                                 else:
370                                         self.session.open(MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
371                         else:
372                                 self.session.open(MessageBox, _("Sorry, could not remove mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
373
374         def confirmApply(self, confirmed):
375                 if not confirmed:
376                         print "not confirmed"
377                         return
378                 else:
379                         for x in self["config"].list:
380                                 x[1].save()
381                         print "confirmApply:",config.storage[self.UUID]['enabled'].value, config.storage[self.UUID]['mountpoint'].value
382                         successfully = False
383                         action = "mount_only"
384                         uuid_cfg = config.storage.get(self.UUID, None)
385                         if uuid_cfg is not None:
386                                 if not uuid_cfg['enabled'].value and self.oldEnabledState:
387                                         action = "unmount"
388                                 if uuid_cfg['enabled'].value and uuid_cfg['mountpoint'].value == "/media/hdd":
389                                         action = "mount_default"
390                                 if action == "unmount":
391                                         updateVideoDirs(self.UUID)
392                                 mountpoint = uuid_cfg['mountpoint'].value
393                                 newenable = uuid_cfg['enabled'].value
394                                 if self.oldMountpath is None:
395                                         self.oldMountpath = ""
396                                 if self.oldEnabledState is None:
397                                         self.oldEnabledState = False
398
399                                 successfully = harddiskmanager.changeStorageDevice(self.UUID, action, [self.oldMountpath, self.oldEnabledState, mountpoint, newenable]) #mountDATA
400                                 if successfully:
401                                         uuid_cfg = config.storage.get(self.UUID, None)
402                                         if uuid_cfg is not None:
403                                                 if action in ("mount_default", "mount_only"):
404                                                         if self.oldMountpath and self.oldMountpath != "":
405                                                                 harddiskmanager.modifyFstabEntry(self.uuidPath, self.oldMountpath, mode = "remove")
406                                                         harddiskmanager.modifyFstabEntry(self.uuidPath, uuid_cfg['mountpoint'].value, mode = "add_activated")
407                                                 updateVideoDirs(self.UUID)
408                                 else:
409                                         self.session.open(MessageBox, _("There was en error while configuring your %(desc)s.") % self.devicedescription, MessageBox.TYPE_ERROR)
410                                 self.close()
411
412         def apply(self):
413                 self.hideHelpWindow()
414                 if self["config"].isChanged():
415                         if config.storage[self.UUID]['mountpoint'].value == '' :
416                                         self.session.open(MessageBox, _("Please select a mountpoint for this partition."), MessageBox.TYPE_ERROR)
417                         else:
418                                 mountpath = config.storage[self.UUID]['mountpoint'].value
419                                 if (harddiskmanager.is_hard_mounted(self.partitionPath) or harddiskmanager.is_hard_mounted(self.uuidPath)):
420                                         message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
421                                         if harddiskmanager.isUUIDpathFsTabMount(self.UUID, mountpath) or harddiskmanager.isPartitionpathFsTabMount(self.UUID, mountpath) \
422                                                 or harddiskmanager.isUUIDpathFsTabMount(self.UUID, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(self.UUID, "/media/hdd"):
423                                                 self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, self.UUID, self.partitionPath, mountpath, True), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
424                                         else:
425                                                 self.session.openWithCallback(self.confirmApply, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
426                                 else:
427                                         self.session.openWithCallback(self.confirmApply, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
428
429         def confirmCancel(self, result):
430                 if not result:
431                         return
432                 for x in self["config"].list:
433                         x[1].cancel()
434                 self.close()
435
436         def keyCancel(self):
437                 self.hideHelpWindow()
438                 if self["config"].isChanged():
439                         self.session.openWithCallback(self.confirmCancel, MessageBox, _("Really close without saving settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
440                 else:
441                         self.close()
442
443         # for summary:
444         def changedEntry(self):
445                 for x in self.onChangedEntry:
446                         x()
447                 self.selectionChanged()
448
449         def getCurrentEntry(self):
450                 if self["config"].getCurrent():
451                         return self["config"].getCurrent()[0]
452
453         def getCurrentValue(self):
454                 if self["config"].getCurrent():
455                         return str(self["config"].getCurrent()[1].value)
456
457         def createSummary(self):
458                 from Screens.Setup import SetupSummary
459                 return SetupSummary
460
461
462 class HarddiskDriveSelection(Screen, HelpableScreen):
463         VIEW_HARDDISK = 1
464         VIEW_PARTITION = 2
465
466         def __init__(self, session):
467                 Screen.__init__(self, session)
468                 HelpableScreen.__init__(self)
469                 self.skinName = "HarddiskDriveSelection"
470
471                 self["key_red"] = StaticText()
472                 self["key_green"] = StaticText()
473                 self["key_yellow"] = StaticText()
474                 self["key_blue"] = StaticText()
475                 self["info"] = Boolean(True)
476                 self["introduction"] = StaticText()
477                 self.devicedescription = storagedevice_description
478
479
480                 self["CancelActions"] = HelpableActionMap(self, "OkCancelActions",
481                         {
482                         "cancel": (self.keyCancel, _("Exit storage device selection.")),
483                         }, -2)
484
485                 self["OkActions"] = HelpableActionMap(self, "OkCancelActions",
486                         {
487                         "ok": (self.okbuttonClick, _("Select storage device.")),
488                         }, -2)
489
490                 self["RedColorActions"] = HelpableActionMap(self, "ColorActions",
491                         {
492                         "red": (self.keyRed, _("Initialize selected storage device or remove offline storage device.")),
493                         }, -2)
494
495                 self["GreenColorActions"] = HelpableActionMap(self, "ColorActions",
496                         {
497                         "green": (self.keyGreen, _("Check selected storage device.")),
498                         }, -2)
499
500                 self["YellowColorActions"] = HelpableActionMap(self, "ColorActions",
501                         {
502                         "yellow": (self.keyYellow,  _("Start storage device plugin...")),
503                         }, -2)
504
505                 self["BlueColorActions"] = HelpableActionMap(self, "ColorActions",
506                         {
507                         "blue": (self.keyBlue, _("Advanced settings.")),
508                         }, -2)
509
510                 self["StorageInfoActions"] = HelpableActionMap(self, "EPGSelectActions",
511                         {
512                         "info": (self.keyInfo, _("Display storage device informations.")),
513                         }, -2)
514
515                 self["OkActions"].setEnabled(False)
516                 self["RedColorActions"].setEnabled(False)
517                 self["GreenColorActions"].setEnabled(False)
518                 self["YellowColorActions"].setEnabled(False)
519                 self["BlueColorActions"].setEnabled(False)
520                 self["StorageInfoActions"].setEnabled(False)
521
522                 self.view = self.VIEW_HARDDISK
523                 self.selectedHDD = None
524                 self.currentIndex = 0
525                 self.currentlyUpdating = False
526                 self.verifyInitOrCheck = False
527                 self.list = []
528                 self["hddlist"] = List(self.list)
529
530                 self.onLayoutFinish.append(self.layoutFinished)
531                 self.onClose.append(self.__onClose)
532                 self.onHide.append(self.__onHide)
533                 self.onShown.append(self.__onShown)
534
535         def layoutFinished(self):
536                 self.setTitle(_("Storage devices"))
537                 self.currentlyUpdating = True
538                 self.setButtons()
539                 self.updateList()
540
541         def __onShown(self):
542                 self.currentlyUpdating = False
543                 if not self.hotplugCB in harddiskmanager.delayed_device_Notifier:
544                         harddiskmanager.delayed_device_Notifier.append(self.hotplugCB)
545                 self["hddlist"].setIndex(self.currentIndex)
546                 self.selectionChanged()
547
548         def __onClose(self):
549                 self.currentIndex = 0
550                 self.currentlyUpdating = False
551                 if self.hotplugCB in harddiskmanager.delayed_device_Notifier:
552                         harddiskmanager.delayed_device_Notifier.remove(self.hotplugCB)
553
554         def __onHide(self):
555                 self.currentlyUpdating = True
556                 if self.hotplugCB in harddiskmanager.delayed_device_Notifier:
557                         harddiskmanager.delayed_device_Notifier.remove(self.hotplugCB)
558
559         def hotplugCB(self, dev, media_state):
560                 if media_state in ("add_delayed", "remove_delayed"):
561                         print "[HarddiskDriveSelection] - hotplugCB for dev:%s, media_state:%s" % (dev, media_state)
562                         if self.currentlyUpdating is False:
563                                 self.currentlyUpdating = True
564                                 self.setButtons()
565                                 self.updateList()
566
567         def buildHDDList(self, hd, isOfflineStorage = False, partNum = False):
568                 divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
569                 devicepng = onlinepng = None
570                 isOfflineStorageDevice = isOfflineStorage
571                 isMountedPartition = isReadable = False
572                 currentMountpoint = partitionType = selectedPart = partitionPath = deviceName = uuidPath =None
573                 hdd_description = device_info = capacity_info = ""
574                 numPartitions = 0
575                 partitionNum = False
576                 fstype = sys = size = sizeg = p = None
577                 devicedescription = storagedevice_description
578                 nomountpoint_msg = _("No mountpoint defined!")
579                 initialize_msg = _("Please initialize!")
580                 unsupportetpart_msg = _("Unsupported partition type!")
581                 multiplepartmsg = _("Multiple partitions found!")
582                 needsattention_msg = _("Needs attention!")
583                 systemountpoint_msg = _("Mounted by system!")
584                 notmounted_msg = _("Not mounted!")
585
586                 if isOfflineStorageDevice:
587                         uuid = hd
588                         print "[HarddiskDriveSelection] - buildHDDList for offline uuid: ",uuid
589                         hdd_description = config.storage[uuid]["device_description"].value
590                         if config.storage[uuid]["enabled"].value == True:
591                                 currentMountpoint = config.storage[uuid]["mountpoint"].value
592                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-unavailable.png"))
593                         onlinepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_green_off.png"))
594                         if config.storage[uuid]["isRemovable"].value == True:
595                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-unavailable.png"))
596                                 device_info += config.storage[uuid]["device_info"].value + " " + _("%(Desc)s") % devicedescription
597                         else:
598                                 devicedescription = harddisk_description
599                                 device_info += config.storage[uuid]["device_info"].value + " " + _("%(Desc)s") % devicedescription
600                         if currentMountpoint is not None:
601                                 device_info += " - " + "( " + currentMountpoint + " )"
602                 else:
603                         hdd_description = hd.model()
604                         deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
605                         print "[HarddiskDriveSelection] - buildHDDList for online device:",deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath
606                         if uuid is None and numPartitions == 2:
607                                 part2Type = harddiskmanager.getBlkidPartitionType(hd.partitionPath("2"))
608                                 if part2Type == "swap":
609                                         uid = harddiskmanager.getPartitionUUID(hd.device + "1")
610                                         if uid is not None:
611                                                 p = harddiskmanager.getPartitionbyUUID(uid)
612                                                 if p is not None and p.isInitialized: # Found HDD was initialized by Enigma2 with swap partition
613                                                         deviceName = hd.device + "1"
614                                                         uuid = uid
615                                                         numPartitions = 1
616                                                         uuidPath = "/dev/disk/by-uuid/" + uuid
617                                                         partitionPath = hd.partitionPath("1")
618                                                         print "[HarddiskDriveSelection] - RE-buildHDDList for online device:",deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath
619                         if partitionNum is False:
620                                 cap = hd.capacity()
621                                 if cap != "":
622                                         capacity_info = " (" + cap + ")"
623                         if uuid is not None:
624                                 p = harddiskmanager.getPartitionbyUUID(uuid)
625                                 if p is not None:
626                                         if capacity_info == "":
627                                                 if p.total() is not None:
628                                                         tmp = p.total()/1000/1000
629                                                         cap = "%d.%03d GB" % (tmp/1000, tmp%1000)
630                                                         if cap != "":
631                                                                 capacity_info = " (" + cap + ")"
632                                         selectedPart = p
633                                         if selectedPart is not None and selectedPart.fsType == None:
634                                                 partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)
635                         if capacity_info == "":
636                                 fstype, sys, size, sizeg, sectors = harddiskmanager.getFdiskInfo(hd.device + str(partitionNum))
637                                 if sizeg is not None:
638                                         capacity_info = " (" + sizeg + " GB)"
639                                 else:
640                                         if size is not None:
641                                                 tmp = int(size)/1000/1000
642                                                 cap = "%d.%03d GB" % (tmp/1000, tmp%1000)
643                                                 if cap != "":
644                                                         capacity_info = " (" + cap + ")"
645                         hdd_description += capacity_info
646
647                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk.png"))
648                         onlinepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_green.png"))
649                         hddname = hd.device
650                         if self.view != self.VIEW_HARDDISK:
651                                 hddname = deviceName
652                         if hd.isRemovable:
653                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable.png"))
654                                 device_info += hd.bus_description() + " " + _("%(Desc)s") % devicedescription + " (" + hddname + ")"
655                         else:
656                                 devicedescription = harddisk_description
657                                 device_info += hd.bus_description() + " " + _("%(Desc)s") % devicedescription + " (" + hddname + ")"
658
659                         if uuid is not None:
660                                 cfg_uuid = config.storage.get(uuid, None)
661                                 if cfg_uuid is not None:
662                                         if cfg_uuid["mountpoint"].value != "":
663                                                 currentMountpoint = cfg_uuid["mountpoint"].value
664                                         if cfg_uuid["enabled"].value:
665                                                 p = harddiskmanager.getPartitionbyMountpoint(currentMountpoint)
666                                                 if p is not None:
667                                                         if p.mounted():
668                                                                 isMountedPartition = True
669                                 if not isMountedPartition:
670                                         if currentMountpoint is None:
671                                                 currentMountpoint = harddiskmanager.get_fstab_mountpoint(partitionPath) or harddiskmanager.get_fstab_mountpoint(uuidPath)
672                                         if currentMountpoint is not None:
673                                                 if harddiskmanager.is_hard_mounted(partitionPath) or harddiskmanager.is_hard_mounted(uuidPath):
674                                                         if harddiskmanager.isPartitionpathFsTabMount(uuid,currentMountpoint) or harddiskmanager.isUUIDpathFsTabMount(uuid,currentMountpoint):
675                                                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-attention.png"))
676                                                                 if hd.isRemovable:
677                                                                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-attention.png"))
678                                                                 device_info += " - " + currentMountpoint
679                                                                 device_info += " - " + needsattention_msg
680                                                         else:
681                                                                 device_info += " - " + nomountpoint_msg
682                                                 else:
683                                                         if not isMountedPartition:
684                                                                 if selectedPart is not None and selectedPart.isMountable:
685                                                                         if selectedPart.isReadable:
686                                                                                 isReadable = True
687                                                                                 device_info += " - " + nomountpoint_msg
688                                                                         else:
689                                                                                 device_info += " - " + unsupportetpart_msg
690                                                                 elif selectedPart is not None and not selectedPart.isMountable:
691                                                                         if self.view == self.VIEW_HARDDISK:
692                                                                                 device_info += " - " + initialize_msg
693                                                                         else:
694                                                                                 device_info += " - " + unsupportetpart_msg
695                                                                 else:
696                                                                         if access("/autofs/" + deviceName, F_OK|R_OK):
697                                                                                 isReadable = True
698                                                                                 try:
699                                                                                         listdir("/autofs/" + deviceName)
700                                                                                 except OSError:
701                                                                                         isReadable = False
702                                                                                 if isReadable:
703                                                                                         if cfg_uuid is not None and cfg_uuid["enabled"].value:
704                                                                                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-attention.png"))
705                                                                                                 if hd.isRemovable:
706                                                                                                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-attention.png"))
707                                                                                                 device_info += " - " + currentMountpoint
708                                                                                                 device_info += " - " + notmounted_msg
709                                                                                         else:
710                                                                                                 device_info += " - " + nomountpoint_msg
711                                                                                 else:
712                                                                                         device_info += " - " + unsupportetpart_msg
713                                                                         else:
714                                                                                 if self.view == self.VIEW_HARDDISK:
715                                                                                         device_info += " - " + initialize_msg
716                                                                                 else:
717                                                                                         device_info += " - " + unsupportetpart_msg
718                                         if currentMountpoint is None and cfg_uuid is not None:
719                                                 currentMountpoint = cfg_uuid["mountpoint"].value
720                                                 if currentMountpoint == "":
721                                                         if selectedPart is not None and selectedPart.isMountable:
722                                                                 if selectedPart.isReadable:
723                                                                         isReadable = True
724                                                                         device_info += " - " + nomountpoint_msg
725                                                                 else:
726                                                                         device_info += " - " + unsupportetpart_msg
727                                                         elif selectedPart is not None and not selectedPart.isMountable:
728                                                                 if self.view == self.VIEW_HARDDISK:
729                                                                         if selectedPart.fsType is not None:
730                                                                                 if selectedPart.isReadable or selectedPart.fsType == "swap":
731                                                                                         device_info += " - " + selectedPart.fsType
732                                                                                 else:
733                                                                                         device_info += " - " + unsupportetpart_msg
734                                                                         else:
735                                                                                 device_info += " - " + initialize_msg
736                                                                 else:
737                                                                         if selectedPart.fsType is not None and selectedPart.fsType == "swap":
738                                                                                 device_info += " - " + selectedPart.fsType
739                                                                         else:
740                                                                                 device_info += " - " + unsupportetpart_msg
741                                                         else:
742                                                                 if access("/autofs/" + deviceName, F_OK|R_OK):
743                                                                         isReadable = True
744                                                                         try:
745                                                                                 listdir("/autofs/" + deviceName)
746                                                                         except OSError:
747                                                                                 isReadable = False
748                                                                         if isReadable:
749                                                                                 device_info += " - " + nomountpoint_msg
750                                                                         else:
751                                                                                 device_info += " - " + unsupportetpart_msg
752                                                                 else:
753                                                                         if self.view == self.VIEW_HARDDISK:
754                                                                                 device_info += " - " + initialize_msg
755                                                                         else:
756                                                                                 device_info += " - " + unsupportetpart_msg
757                                         if currentMountpoint is None and cfg_uuid is None:
758                                                 device_info += " - " + nomountpoint_msg
759                                 if isMountedPartition:
760                                         isReadable = True
761                                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-configured.png"))
762                                         if hd.isRemovable:
763                                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-configured.png"))
764                                         device_info += " - " + currentMountpoint
765                         else:
766                                 if numPartitions <=1:
767                                         device_info += " - " + initialize_msg
768                                 else:
769                                         if self.view == self.VIEW_HARDDISK:
770                                                 device_info += " - " + multiplepartmsg
771                                         else:
772                                                 device_info += " - " + unsupportetpart_msg
773
774                 return((hdd_description, hd, device_info, numPartitions, isOfflineStorageDevice, isMountedPartition, currentMountpoint, devicepng, onlinepng, divpng, partitionNum, isReadable, partitionPath, partitionType, deviceName))
775
776         def updateList(self):
777                 self.view = self.VIEW_HARDDISK
778                 self.selectedHDD = None
779                 self.list = []
780
781                 for hd in harddiskmanager.hdd:
782                         if not hd.isRemovable:
783                                 self.list.append(self.buildHDDList(hd, isOfflineStorage = False)) #online hard disk devices discovered
784                 for hd in harddiskmanager.hdd:
785                         if hd.isRemovable:
786                                 self.list.append(self.buildHDDList(hd, isOfflineStorage = False)) #online removable devices discovered
787                 if self.list:
788                         self.list.sort(key=lambda x: x[14][:3])
789
790                 for uuid in config.storage:
791                         dev = harddiskmanager.getDeviceNamebyUUID(uuid)
792                         if dev is None:
793                                 self.list.append(self.buildHDDList(uuid, isOfflineStorage = True)) #offline devices
794                 if not self.list:
795                         self["key_blue"].setText("")
796                         self["BlueColorActions"].setEnabled(False)
797                         self.list.append((_("no storage devices found"), 0, None, None, None, None, None, None, None, None, False, None, None, None, None))
798                         self["introduction"].setText(_("No installed or configured storage devices found!"))
799
800                 self["hddlist"].setList(self.list)
801                 if not self.selectionChanged in self["hddlist"].onSelectionChanged:
802                         self["hddlist"].onSelectionChanged.append(self.selectionChanged)
803                 self["hddlist"].setIndex(self.currentIndex)
804                 self.currentlyUpdating = False
805
806         def updatePartitionList(self, hdd):
807                 self.view = self.VIEW_PARTITION
808                 self.selectedHDD = hdd
809                 self.list = []
810                 for p in harddiskmanager.partitions[:]:
811                         if p.device is not None:
812                                 if p.device.startswith(hdd.device) and p.device[3:].isdigit():
813                                         self.list.append(self.buildHDDList(hdd, isOfflineStorage = False, partNum = p.device[3:])) #online devices partition discovered
814                 if self.list:
815                         self.list.sort(key=lambda x: x[14][3:])
816
817                 self["hddlist"].setList(self.list)
818                 self["hddlist"].setIndex(0)
819                 self.currentlyUpdating = False
820                 self.selectionChanged()
821
822         def setButtons(self):
823                 self["key_red"].setText("")
824                 self["key_green"].setText("")
825                 self["key_yellow"].setText("")
826                 self["key_blue"].setText("")
827                 self["OkActions"].setEnabled(False)
828                 self["RedColorActions"].setEnabled(False)
829                 self["GreenColorActions"].setEnabled(False)
830                 self["YellowColorActions"].setEnabled(False)
831                 self["BlueColorActions"].setEnabled(False)
832                 self["StorageInfoActions"].setEnabled(False)
833                 self["info"].boolean = False
834
835         def selectionChanged(self):
836                 #[HarddiskDriveSelection] - current: (0: hdd_description, 1:hd/uuid, 2;device_info, 3:numpart, 4:isOfflineStorageDevice, 5:isMountedPartition, 6:currentMountpoint, devicepng, onlinepng, divpng)
837                 initialize_btntxt = _("Initialize")
838                 check_btntxt = _("Check")
839                 remove_btntxt = _("Remove")
840                 settings_btntxt = _("Settings")
841                 plugins_btntxt  = _("Storage plugins")
842                 self.setButtons()
843                 current = self["hddlist"].getCurrent()
844                 introduction = ""
845                 selectedPart = None
846                 isInitializing = False
847                 isVerifying = False
848                 if current:
849                         self.currentIndex = self["hddlist"].getIndex()
850                         numpart = current[3]
851                         offline = current[4]
852                         if numpart >= 0 and not offline:
853                                 storage_plugins = plugins.getPlugins(PluginDescriptor.WHERE_STORAGEMANAGER)
854                                 if len(storage_plugins):
855                                         self["YellowColorActions"].setEnabled(True)
856                                         self["key_yellow"].setText(plugins_btntxt)
857                                 if config.usage.setup_level.index >= 1:
858                                         self["key_blue"].setText(settings_btntxt)
859                                         self["BlueColorActions"].setEnabled(True)
860                                 self["StorageInfoActions"].setEnabled(True)
861                                 self["info"].boolean = True
862                                 hd = current[1]
863                                 partNum = current[10]
864                                 isReadable = current[11]
865                                 selectedPart = None
866                                 partitionType = None
867                                 isInitializing = hd.isInitializing
868                                 isVerifying = hd.isVerifying
869                                 if not isInitializing and not isVerifying and not self.verifyInitOrCheck:
870                                         self["OkActions"].setEnabled(True)
871                                 self.devicedescription = storagedevice_description
872                                 if not hd.isRemovable:
873                                         self.devicedescription = harddisk_description
874                                 showpartitions_msg = _("Please press OK to see available partitions!")
875                                 mountpartition_msg = _("Please press OK to set up a mountpoint for this partition!")
876                                 unknownpartition_msg = _("Unknown or unsupported partition type found!")
877                                 mount_msg = _("Please press OK to set up a mountpoint for this %(desc)s!") % self.devicedescription
878                                 init_msg = _("Please initialize this %(desc)s!") % self.devicedescription
879                                 redinit_msg = _("Please press red to initialize this %(desc)s!") % self.devicedescription
880                                 introduction = mount_msg
881
882                                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
883                                 print "[HarddiskDriveSelection] - selectionChanged: deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s' - partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
884                                 % (deviceName, uuid, numPartitions, partitionNum, partitionPath, uuidPath, hd.device, hd.dev_path)
885
886                                 if numPartitions >= 2:
887                                         introduction = showpartitions_msg
888
889                                 if uuid is not None:
890                                         p = harddiskmanager.getPartitionbyUUID(uuid)
891                                         if p is not None:
892                                                 selectedPart = p
893                                                 if selectedPart is not None:
894                                                         print "[HarddiskDriveSelection] - selectionChanged: SelectedPart device:'%s'-uuid:'%s' isMountable:'%s'-isReadable:'%s'-isWriteable:'%s'-isInitialized:'%s'-fsType:'%s'" \
895                                                         % (selectedPart.device ,selectedPart.uuid ,selectedPart.isMountable, selectedPart.isReadable,selectedPart.isWriteable,selectedPart.isInitialized,selectedPart.fsType)
896                                                         isReadable = selectedPart.isReadable
897                                                         partitionType = selectedPart.fsType
898                                 if partitionType is None:
899                                         partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)
900
901
902
903                                 if self.view == self.VIEW_HARDDISK:
904                                         self["key_red"].setText(initialize_btntxt)
905                                         if not isInitializing and not isVerifying and not self.verifyInitOrCheck:
906                                                 self["RedColorActions"].setEnabled(True)
907                                         if uuid is not None:
908                                                 if numPartitions <= 1:
909                                                         introduction = mountpartition_msg
910                                                         if not isInitializing and not isVerifying and not self.verifyInitOrCheck:
911                                                                 if partitionType is not None and partitionType in ( "ext2", "ext3" ):
912                                                                         self["key_green"].setText(check_btntxt)
913                                                                         self["GreenColorActions"].setEnabled(True)
914                                                         if not isReadable and partitionType is None:
915                                                                 introduction = redinit_msg
916                                                         if not isReadable and partitionType is not None:
917                                                                 introduction = unknownpartition_msg
918                                         else:
919                                                 if numPartitions <= 1:
920                                                         introduction = redinit_msg
921                                 if self.view == self.VIEW_PARTITION:
922                                         self["key_red"].setText("")
923                                         self["RedColorActions"].setEnabled(False)
924                                         if uuid is not None:
925                                                 if partitionType is not None and partitionType in ( "ext2", "ext3" ):
926                                                         self["key_green"].setText(check_btntxt)
927                                                         self["GreenColorActions"].setEnabled(True)
928                                                 introduction = mountpartition_msg
929                                                 if not isReadable:
930                                                         self["OkActions"].setEnabled(False)
931                                                         introduction = unknownpartition_msg
932                                         else:
933                                                 self["OkActions"].setEnabled(False)
934                                                 introduction = init_msg
935                                                 if not isReadable:
936                                                         introduction = unknownpartition_msg
937                         if offline:
938                                 self["key_red"].setText(remove_btntxt)
939                                 self["RedColorActions"].setEnabled(True)
940                                 self["OkActions"].setEnabled(True)
941                                 if isinstance(current[1], (basestring, str)):
942                                         self.devicedescription = storagedevice_description
943                                         if not config.storage[current[1]]["isRemovable"].value:
944                                                 self.devicedescription = harddisk_description
945                                         introduction = _("Please press red to remove this %(desc)s configuration!") % self.devicedescription
946                         if not isInitializing and not self.verifyInitOrCheck:
947                                 self["introduction"].setText(introduction)
948
949         def keyCancel(self):
950                 if self.view == self.VIEW_PARTITION:
951                         self.view = self.VIEW_HARDDISK
952                         self.mainMenuClosed()
953                 else:
954                         self.close()
955
956         def handleAnswer(self, answer, selection):
957                 self.devicedescription = storagedevice_description
958                 answer = answer and answer[1]
959                 print "[HarddiskDriveSelection] - handleAnswer:",answer
960                 if answer == "mount_default":
961                         self.applyAnswer(answer, selection)
962                 elif answer == "mount_only":
963                         self.applyAnswer(answer, selection)
964                 elif answer == "adopt_mount":
965                         self.applyAnswer(answer, selection)
966                 elif answer == "mount_manually":
967                         hd = selection[1]
968                         numpart = selection[3]
969                         partNum = selection[10]
970                         if numpart >= 2 and partNum is not False:
971                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, device = hd, partition = partNum)
972                         else:
973                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, device = hd)
974                 elif answer in ("unmount", "eject"):
975                         self.confirmApplyAnswer(True, answer, selection)
976                 elif answer == "remove":
977                         if isinstance(selection[1], (basestring, str)):
978                                 if not config.storage[selection[1]]["isRemovable"].value:
979                                         self.devicedescription = harddisk_description
980                                 message = _("Really remove this %(desc)s entry?") % self.devicedescription
981                                 self.session.openWithCallback(lambda x : self.keyRedConfirm(x, selection[1]), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
982                 elif answer == "init":
983                         if not selection[1].isRemovable:
984                                 self.devicedescription = harddisk_description
985                         message = _("Do you really want to initialize this %(desc)s?\nAll data on this %(desc)s will be lost!") % self.devicedescription
986                         self.session.openWithCallback(lambda x : hddConfirmed(x, HARDDISK_INITIALIZE, selection[1], None, self.starthddInitCheck), MessageBox, message)
987                 elif answer in ( None, "nothing"):
988                         print "nothing to do"
989
990         def applyAnswer(self, answer, selection):
991                 print "[HarddiskDriveSelection] - applyAnswer:",answer,selection
992                 hd = selection[1]
993                 partNum = selection[10]
994                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
995
996                 uuid_cfg = config.storage.get(uuid, None)
997                 if uuid_cfg is not None:
998                         mountpath = ""
999                         checkFstabUpgrade = True
1000                         if answer == "adopt_mount":
1001                                 checkFstabUpgrade = False
1002                         if answer == "mount_default":
1003                                 mountpath = "/media/hdd"
1004                         else:
1005                                 if defaultStorageDevice() == "<undefined>" and answer != "adopt_mount":
1006                                         mountpath = "/media/hdd"
1007                                         answer = "mount_default"
1008                                 else:
1009                                         mountpath = harddiskmanager.suggestDeviceMountpath(uuid)
1010                         if checkFstabUpgrade:
1011                                 if harddiskmanager.isUUIDpathFsTabMount(uuid, mountpath) or harddiskmanager.isPartitionpathFsTabMount(uuid, mountpath) \
1012                                 or harddiskmanager.isUUIDpathFsTabMount(uuid, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(uuid, "/media/hdd"):
1013                                         message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
1014                                         self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, uuid, partitionPath, mountpath, answer, selection, True), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
1015                                 else:
1016                                         self.confirmApplyAnswer(True, answer, selection)
1017                         else:
1018                                 self.confirmApplyAnswer(True, answer, selection)
1019                 else:
1020                         print "[applyAnswer] - could not determine uuid"
1021
1022         def confirmFstabUpgrade(self, result, uuid, partitionPath, mountpath, answer, selection, callConfirmApply = False):
1023                 if not result:
1024                         self.confirmApplyAnswer(True, answer, selection)
1025                 else:
1026                         doFstabUpgrade(uuid, partitionPath, mountpath, callConfirmApply, self.confirmFstabUpgradeCB, answer, selection)
1027
1028         def confirmFstabUpgradeCB(self, *val):
1029                 result, callConfirmApply, answer, selection, = val
1030                 if result is not None:
1031                         if result:
1032                                 if callConfirmApply:
1033                                         self.session.openWithCallback(lambda x : self.confirmApplyAnswer(True, answer, selection), MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
1034                         else:
1035                                 self.session.open(MessageBox, _("Sorry, could not remove mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
1036
1037         def confirmApplyAnswer(self, confirmed, answer, selection):
1038                 if not confirmed:
1039                         print "not confirmed"
1040                         return
1041                 else:
1042                         self.devicedescription = storagedevice_description
1043                         hd = selection[1]
1044                         if not hd.isRemovable:
1045                                 self.devicedescription = harddisk_description
1046                         partNum = selection[10]
1047                         deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
1048
1049                         successfully = False
1050                         old_mountpoint = ""
1051                         uuid_cfg = config.storage.get(uuid, None)
1052                         if uuid_cfg is not None:
1053                                 mountpoint = ""
1054                                 if answer == "unmount":
1055                                         uuid_cfg['enabled'].value = False
1056                                         old_mountpoint = uuid_cfg['mountpoint'].value
1057                                         updateVideoDirs(uuid)
1058                                         uuid_cfg['enabled'].value = True
1059                                 if answer == "adopt_mount":
1060                                         mountpoint = selection[6]
1061                                         if mountpoint == "/media/hdd":
1062                                                 answer = "mount_default"
1063                                 if answer == "adopt_mount":
1064                                         uuid_cfg['mountpoint'].value = mountpoint
1065                                         uuid_cfg['enabled'].value = True
1066                                         successfully = harddiskmanager.changeStorageDevice(uuid, "mount_only", ["", False, mountpoint, True]) #mountDATA
1067                                 else:
1068                                         successfully = harddiskmanager.changeStorageDevice(uuid, answer, None)
1069                                 print "confirmApplyAnswer:",answer, uuid_cfg['enabled'].value, uuid_cfg['mountpoint'].value
1070                         if successfully:
1071                                 uuid_cfg = config.storage.get(uuid, None)
1072                                 if uuid_cfg is not None:
1073                                         if answer in ("mount_default", "mount_only"):
1074                                                 harddiskmanager.modifyFstabEntry(uuidPath, uuid_cfg['mountpoint'].value, mode = "add_activated")
1075                                         updateVideoDirs(uuid)
1076                                         if answer == "unmount":
1077                                                 harddiskmanager.modifyFstabEntry(uuidPath, old_mountpoint, mode = "remove")
1078                         else:
1079                                 self.session.open(MessageBox, _("There was en error while configuring your %(desc)s.") % self.devicedescription, MessageBox.TYPE_ERROR)
1080                         self.mainMenuClosed()
1081
1082         def okbuttonClick(self):
1083                 selection = self["hddlist"].getCurrent()
1084                 if selection[1] != 0:
1085                         print "[HarddiskDriveSelection] - okbuttonClick:",selection[0], selection[2], selection[3],selection[10]
1086                         hd = selection[1]
1087                         offline = selection[4]
1088                         partNum = selection[10]
1089                         isRemovable = False
1090                         selectedPart = None
1091                         if not offline:
1092                                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
1093                                 print "[HarddiskDriveSelection] - okbuttonClick: deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
1094                                 % (deviceName, uuid, numPartitions, partitionNum, partitionPath, uuidPath, hd.device, hd.dev_path)
1095                                 isRemovable = hd.isRemovable
1096                         else: #offline drive ?
1097                                 uuid = hd
1098                                 numPartitions = 1
1099                                 partNum = False
1100
1101                         if uuid is not None:
1102                                 p = harddiskmanager.getPartitionbyUUID(uuid)
1103                                 if p is not None:
1104                                         selectedPart = p
1105
1106                         uuid_cfg = config.storage.get(uuid, None)
1107                         if uuid is not None and uuid_cfg is None:
1108                                 harddiskmanager.setupConfigEntries(initial_call = False, dev = deviceName)
1109                         if uuid_cfg is not None and offline:
1110                                 isRemovable = uuid_cfg['isRemovable'].value
1111
1112                         self.devicedescription = storagedevice_description
1113                         if not isRemovable:
1114                                 self.devicedescription = harddisk_description
1115
1116                         mountmsg = (_("Automatically set up a mountpoint."), "mount_only")
1117                         manualmsg = (_("Manually select a mountpoint."), "mount_manually")
1118                         adoptmsg = (_("Adopt current configuration."), "adopt_mount")
1119                         defaultmsg = (_("Set up as default %(desc)s.") % self.devicedescription, "mount_default")
1120                         unmountmsg = (_("Unmount this %(desc)s.") % self.devicedescription, "unmount")
1121                         removemsg = (_("Remove this %(desc)s configuration.") % self.devicedescription, "remove")
1122                         initmsg = (_("Initialize this %(desc)s.") % self.devicedescription, "init")
1123                         ejectmsg = (_("Eject."), "eject")
1124
1125                         choices = [ ]
1126                         if uuid_cfg is None: # uninitialized drive
1127                                 choices.extend([initmsg])
1128                         elif uuid_cfg is not None and not uuid_cfg['enabled'].value: # unconfigured drive
1129                                 if selectedPart is not None and selectedPart.isInitialized:
1130                                         isManualMounted = False
1131                                         currentMountpoint = harddiskmanager.get_fstab_mountpoint(partitionPath) or harddiskmanager.get_fstab_mountpoint(uuidPath)
1132                                         if currentMountpoint is not None:
1133                                                 if harddiskmanager.is_hard_mounted(partitionPath) or harddiskmanager.is_hard_mounted(uuidPath):
1134                                                         if harddiskmanager.isPartitionpathFsTabMount(uuid,currentMountpoint) or harddiskmanager.isUUIDpathFsTabMount(uuid,currentMountpoint):
1135                                                                 isManualMounted = True
1136                                         if defaultStorageDevice() == "<undefined>":
1137                                                 if not isManualMounted:
1138                                                         choices.extend([defaultmsg, mountmsg, manualmsg])
1139                                                 else:
1140                                                         choices.extend([defaultmsg, adoptmsg, mountmsg, manualmsg])
1141                                         else:
1142                                                 if not isManualMounted:
1143                                                         choices.extend([mountmsg, manualmsg, defaultmsg])
1144                                                 else:
1145                                                         choices.extend([adoptmsg, defaultmsg, mountmsg, manualmsg])
1146                                 else:
1147                                         if selectedPart is not None and selectedPart.isWriteable and selectedPart.isMountable: #writeable device, but not initialized by Enigma2
1148                                                 choices.extend([defaultmsg, mountmsg, manualmsg])
1149                                         else:
1150                                                 choices.extend([mountmsg, manualmsg])
1151                         elif uuid_cfg is not None and uuid_cfg['enabled'].value: # configured drive
1152                                 if selectedPart is not None and selectedPart.isInitialized:
1153                                         if defaultStorageDevice() != uuid:
1154                                                 choices.extend([unmountmsg, defaultmsg, manualmsg, ejectmsg])
1155                                         elif defaultStorageDevice() == uuid:
1156                                                 choices.extend([unmountmsg, mountmsg, manualmsg, ejectmsg])
1157                                 else:
1158                                         if offline:
1159                                                 choices.extend([removemsg])
1160                                         else:
1161                                                 choices.extend([unmountmsg, manualmsg, ejectmsg])
1162                         choices.append((_("Do nothing."), "nothing"))
1163
1164                         if uuid_cfg is not None and not uuid_cfg['enabled'].value:
1165                                 titletext = _("Unconfigured %(desc)s found!") % self.devicedescription
1166                         elif uuid_cfg is not None and uuid_cfg['enabled'].value:
1167                                 titletext = _("%(Desc)s already configured!") % self.devicedescription
1168                         else:
1169                                 titletext = _("Uninitialized %(desc)s found!") % self.devicedescription
1170
1171                         if numPartitions >= 2 and partNum is False:
1172                                 self.updatePartitionList(hd)
1173                         else:
1174                                 self.session.openWithCallback(lambda x : self.handleAnswer(x, selection), ChoiceBox, title = titletext + "\n" , list = choices)
1175
1176         def mainMenuClosed(self, *val):
1177                 if self.currentlyUpdating is False:
1178                         self.currentlyUpdating = True
1179                         self.setButtons()
1180                         if self.view == self.VIEW_PARTITION:
1181                                 self.updatePartitionList(self.selectedHDD)
1182                         else:
1183                                 self.updateList()
1184
1185         def starthddInitCheck(self, stype, hdd, partition ):
1186                 if stype == HARDDISK_INITIALIZE:
1187                         print "[HarddiskDriveSelection]- starthddInit Initialize: ",stype, hdd
1188                         hdd.isInitializing = True
1189                         self.session.openWithCallback(lambda x : self.hddReady(x, stype, hdd), HarddiskWait, hdd, stype)
1190                 else:
1191                         print "[HarddiskDriveSelection]- starthddInit Check: ",stype, hdd, partition
1192                         hdd.isVerifying = True
1193                         self.session.openWithCallback(lambda x : self.hddReady(x, stype, hdd, partition), HarddiskWait, hdd, stype, partition)
1194
1195         def hddReady(self, result, stype, hdd, partition = None ):
1196                 if (result != 0):
1197                         self.devicedescription = storagedevice_description
1198                         if not hdd.isRemovable:
1199                                 self.devicedescription = harddisk_description
1200                         if stype == HARDDISK_INITIALIZE:
1201                                 hdd.isInitializing = False
1202                                 message = _("Unable to initialize %(desc)s.\nError: ") % self.devicedescription
1203                         else:
1204                                 hdd.isVerifying = False
1205                                 message = _("Unable to complete filesystem check.\nError: ")
1206                         self.session.open(MessageBox, message + str(hdd.errorList[0 - result]), MessageBox.TYPE_ERROR)
1207                 else:
1208                         if stype == HARDDISK_INITIALIZE:
1209                                 #we need to wait until udev has set up all new system links
1210                                 self.timer = eTimer()
1211                                 self.timer.callback.append(boundFunction(self.verifyInitialize, hdd))
1212                                 self["introduction"].setText(_("Verifying initialization. Please wait!"))
1213                                 self.timer.start(3000,True)
1214                         elif stype == HARDDISK_CHECK:
1215                                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hdd,partition)
1216                                 harddiskmanager.mountPartitionbyUUID(uuid)
1217                                 hdd.isVerifying = False
1218                                 self["introduction"].setText(_("Filesystem check completed without errors."))
1219
1220         def verifyInitialize(self, hdd):
1221                 self.timer.stop()
1222                 self.devicedescription = storagedevice_description
1223                 if not hdd.isRemovable:
1224                         self.devicedescription = harddisk_description
1225                 successfully = False
1226                 action = "mount_only"
1227                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hdd, "1")
1228                 #print "[HarddiskDriveSelection]-> deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
1229                 #% (deviceName, uuid, numPartitions, partitionNum, partitionPath, uuidPath, hdd.device, hdd.dev_path)
1230                 if uuid is not None:
1231                         print "[HarddiskDriveSelection]- verifyInitialize - got new uuid: ",uuid
1232                         uuid_cfg = config.storage.get(uuid, None)
1233                         if uuid_cfg is None:
1234                                 harddiskmanager.setupConfigEntries(initial_call = False, dev = deviceName)
1235                         print "[HarddiskDriveSelection]- verifyInitialize -defaultStorageDevice()",defaultStorageDevice()
1236                         print "[HarddiskDriveSelection]- verifyInitialize -HDDEnabledCount()",harddiskmanager.HDDEnabledCount()
1237                         if uuid_cfg is not None:
1238                                 if defaultStorageDevice() == "<undefined>" or not harddiskmanager.HDDEnabledCount(): # no configured default storage device found
1239                                         action = "mount_default"
1240                                 print "[HarddiskDriveSelection]- verifyInitialize -ACTION",action
1241                                 successfully = harddiskmanager.changeStorageDevice(uuid, action, None)
1242                         if successfully:
1243                                 uuid_cfg = config.storage.get(uuid, None)
1244                                 if uuid_cfg is not None:
1245                                         if action in ("mount_default", "mount_only"):
1246                                                 harddiskmanager.modifyFstabEntry(uuidPath, uuid_cfg['mountpoint'].value, mode = "add_activated")
1247                                         updateVideoDirs(uuid)
1248                         else:
1249                                 self.session.open(MessageBox, _("There was en error while configuring your %(desc)s.") % self.devicedescription, MessageBox.TYPE_ERROR)
1250                 else:
1251                         self["introduction"].setText(_("Unable to verify partition information. Please restart!"))
1252                 hdd.isInitializing = False
1253                 self.verifyInitOrCheck = True
1254                 self.timer = eTimer()
1255                 self.timer.callback.append(self.verifyInitializeOrCheck)
1256                 self.timer.start(3000,True)
1257
1258         def verifyInitializeOrCheck(self):
1259                 self.timer.stop()
1260                 self.verifyInitOrCheck = False
1261                 self.mainMenuClosed()
1262
1263         def keyRed(self):
1264                 selection = self["hddlist"].getCurrent()
1265                 print "[HarddiskDriveSelection] - keyRed:",selection[0], selection[1], selection[2], selection[3], selection[4], selection[10],selection[11]
1266                 if selection[1] != 0:
1267                         self.devicedescription = storagedevice_description
1268                         if isinstance(selection[1], (basestring, str)):
1269                                 if not config.storage[selection[1]]["isRemovable"].value:
1270                                         self.devicedescription = harddisk_description
1271                                 message = _("Really delete this %(desc)s entry?") % self.devicedescription
1272                                 self.session.openWithCallback(lambda x : self.keyRedConfirm(x, selection[1]), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
1273                         else:
1274                                 hd = selection[1]
1275                                 if not hd.isRemovable:
1276                                         self.devicedescription = harddisk_description
1277                                 message = _("Do you really want to initialize this %(desc)s?\nAll data on this %(desc)s will be lost!") % self.devicedescription
1278                                 self.session.openWithCallback(lambda x : hddConfirmed(x, HARDDISK_INITIALIZE, hd, None, self.starthddInitCheck), MessageBox, message)
1279
1280         def keyRedConfirm(self, result, uuid):
1281                 if not result:
1282                         return
1283                 uuid_cfg = config.storage.get(uuid, None)
1284                 if uuid_cfg is not None:
1285                         harddiskmanager.modifyFstabEntry("/dev/disk/by-uuid/" + uuid, uuid_cfg["mountpoint"].value, mode = "remove")
1286                         uuid_cfg["enabled"].value = False
1287                         updateVideoDirs(uuid)
1288                         del config.storage[uuid]
1289                         if uuid == defaultStorageDevice():
1290                                 config.storage_options.default_device.value = "<undefined>"
1291                                 config.storage_options.default_device.save()
1292                                 config.storage_options.save()
1293                         config.storage.save()
1294                         configfile.save()
1295                         self.setButtons()
1296                         self.updateList()
1297
1298         def keyGreen(self):
1299                 #[HarddiskDriveSelection] - current: (0: hdd_description, 1:hd/uuid, 2;device_info, 3:numpart, 4:isOfflineStorageDevice, 5:isMountedPartition, 6:currentMountpoint, 10:partNum, devicepng, onlinepng, divpng)
1300                 selection = self["hddlist"].getCurrent()
1301                 if selection[1] != 0:
1302                         print "[HarddiskDriveSelection] - keyGreen:",selection[0], selection[1], selection[2], selection[3], selection[10]
1303                         hd = selection[1]
1304                         message = _("Do you really want to check the filesystem?\nThis could take lots of time!")
1305                         if selection[3] >= 2 and selection[10] is not False:
1306                                 self.session.openWithCallback(lambda x : hddConfirmed(x, HARDDISK_CHECK, hd, selection[10], self.starthddInitCheck), MessageBox, message)
1307                         else:
1308                                 self.session.openWithCallback(lambda x : hddConfirmed(x, HARDDISK_CHECK, hd, selection[3], self.starthddInitCheck), MessageBox, message)
1309
1310         def keyYellow(self):
1311                 selection = self["hddlist"].getCurrent()
1312                 print "[HarddiskDriveSelection] - keyYellow:",selection[0], selection[1], selection[2], selection[3], selection[4], selection[10],selection[11]
1313                 if selection[1] != 0:
1314                         if not isinstance(selection[1], (basestring, str)):
1315                                 storage_plugins = plugins.getPlugins(PluginDescriptor.WHERE_STORAGEMANAGER)
1316                                 l = len(storage_plugins)
1317                                 if l == 1:
1318                                         storage_plugins[0](session=self.session, current=selection)
1319                                 elif l > 1:
1320                                         pluginlist = []
1321                                         for p in storage_plugins:
1322                                                 pluginlist.append( (p.name, p) )
1323                                         self.session.openWithCallback(lambda x : self.onStoragePluginSelected(x, selection),  ChoiceBox, title=_("Please select a storage device plugin"), list = pluginlist)
1324
1325         def onStoragePluginSelected(self, p, selection):
1326                 p = p and p[1]
1327                 if p is not None:
1328                         p(session=self.session, current=selection)
1329
1330         def keyBlue(self):
1331                 selection = self["hddlist"].getCurrent()
1332                 if selection[1] != 0:
1333                         self.session.openWithCallback(self.mainMenuClosed, Setup, "harddisk")
1334
1335         def keyInfo(self):
1336                 selection = self["hddlist"].getCurrent()
1337                 if selection[1] != 0:
1338                         #print "[HarddiskDriveSelection] - keyInfo:",selection[0], selection[1], selection[2], selection[3], selection[10]
1339                         hd = selection[1]
1340                         numpart = selection[3]
1341                         partNum = selection[10]
1342                         if numpart >= 2 and partNum is not False:
1343                                 self.session.openWithCallback(self.mainMenuClosed, StorageInformation, hdd = hd, partition = partNum)
1344                         else:
1345                                 self.session.openWithCallback(self.mainMenuClosed, StorageInformation, hdd = hd)
1346
1347
1348 class HarddiskMountpointBrowser(Screen, HelpableScreen):
1349
1350         def __init__(self, session, hdd, uuid):
1351                 Screen.__init__(self, session)
1352                 self.skinName = "HarddiskMountpointBrowser"
1353                 self.hdd = hdd
1354                 self.UUID = uuid
1355                 HelpableScreen.__init__(self)
1356
1357                 self["key_red"] = StaticText(_("Cancel"))
1358                 self["key_green"] = StaticText(_("Use"))
1359                 self["key_yellow"] = StaticText(_("Create directory"))
1360                 self["key_blue"] = StaticText()
1361
1362                 currdir = "/media/"
1363                 inhibitDirs = ["/autofs", "/mnt", "/hdd", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/proc", "/sbin", "/share", "/sys", "/tmp", "/usr", "/var", "/media/realroot", "/media/union"]
1364                 self.filelist = FileList(currdir, matchingPattern="", inhibitDirs = inhibitDirs)
1365                 self["filelist"] = self.filelist
1366
1367                 self["shortcuts"] = ActionMap(["ColorActions"],
1368                         {
1369                         "red": self.exit,
1370                         "green": self.use,
1371                         "yellow": self.createMountdir,
1372                         }, -2)
1373
1374                 self["OkCancelActions"] = ActionMap(["OkCancelActions"],
1375                         {
1376                         "cancel": self.exit,
1377                         "ok": self.ok,
1378                         }, -2)
1379
1380                 self.onLayoutFinish.append(self.layoutFinished)
1381
1382         def layoutFinished(self):
1383                 self.setTitle(_("Select mountpoint"))
1384
1385         def ok(self):
1386                 if self.filelist.canDescent():
1387                         self.filelist.descent()
1388
1389         def use(self):
1390                 if self["filelist"].getCurrentDirectory() is not None:
1391                         if self.filelist.canDescent() and self["filelist"].getFilename() and len(self["filelist"].getFilename()) > len(self["filelist"].getCurrentDirectory()):
1392                                 self.filelist.descent()
1393                                 self.close(self["filelist"].getCurrentDirectory())
1394                 else:
1395                         self.close(self["filelist"].getFilename())
1396
1397         def createMountdir(self):
1398                 cfg = config.storage.get(self.UUID, None)
1399                 if cfg is not None:
1400                         self.session.openWithCallback(self.createMountdirCB, VirtualKeyBoard, title = (_("Enter mountpoint path.")), text = cfg["mountpoint"].value)
1401
1402         def createMountdirCB(self, retval = None):
1403                 if retval is not None:
1404                         self.close(retval)
1405
1406         def exit(self):
1407                 self.close(False)
1408
1409
1410 class StorageInformation(Screen):
1411
1412         def __init__(self, session, hdd = None, partition = False):
1413                 Screen.__init__(self, session)
1414                 self.skinName = "StorageInformation"
1415
1416                 self.hdd = hdd
1417                 self.partition = partition
1418
1419                 self.devicedescription = storagedevice_description
1420                 if not self.hdd.isRemovable:
1421                         self.devicedescription = harddisk_description
1422                 self.setup_title = _("Storage device information")
1423
1424                 self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.uuidPath, self.partitionPath = harddiskmanager.getPartitionVars(self.hdd,self.partition)
1425                 print "[StorageInformation] - deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
1426                 % (self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
1427
1428                 self["key_red"] = StaticText()
1429                 self["key_green"] = StaticText()
1430                 self["key_yellow"] = StaticText()
1431                 self["key_blue"] = StaticText()
1432                 self["introduction"] = StaticText()
1433                 self["icon"] = StaticText()
1434                 self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-open.png"))
1435                 if self.hdd.isRemovable:
1436                         self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-big.png"))
1437                 self["model"] = StaticText(_("Model") + ": " + self.hdd.model())
1438                 self["device_capacity"] = StaticText(_("Capacity") + ": "  + self.hdd.capacity())
1439                 self["device_free"] = StaticText(_("Free") + ": %d MB"  % self.hdd.free())
1440                 self["bus"] = StaticText(_("Description") + ": "  + self.hdd.bus_description() + " " + _("%(Desc)s") % self.devicedescription + " (" + self.hdd.device + ")" )
1441                 self["num_partitions"] = StaticText(_("Partitions") + ": " + str(self.numPartitions))
1442                 self["partition"] = StaticText()
1443                 self["partition_capacity"] = StaticText()
1444                 self["filesystem"] = StaticText()
1445
1446                 self["actions"] = ActionMap(["WizardActions", "DirectionActions"],
1447                 {
1448                         "back": self.close,
1449                         "cancel": self.close,
1450                 }, -2)
1451
1452                 self.onLayoutFinish.append(self.layoutFinished)
1453
1454         def layoutFinished(self):
1455                 self.setTitle(self.setup_title)
1456                 self.updateInfo()
1457
1458         def updateInfo(self):
1459                 init_msg = _("Please initialize this %(desc)s!") % self.devicedescription
1460                 unknownpartition_msg = _("Unknown or unsupported partition type.")
1461                 selectedPart = None
1462                 partitionType = None
1463                 capacity_info = ""
1464
1465                 if self.UUID is not None:
1466                         p = harddiskmanager.getPartitionbyUUID(self.UUID)
1467                         if p is not None:
1468                                 selectedPart = p
1469                                 if selectedPart is not None:
1470                                         partitionType = selectedPart.fsType
1471                 if partitionType is None:
1472                         partitionType = harddiskmanager.getBlkidPartitionType(self.partitionPath)
1473
1474                 if self.UUID is None and self.numPartitions == 0:
1475                         self["introduction"].setText(init_msg)
1476
1477                 if self.UUID is not None:
1478                         self["partition"].setText(_("Partition") + ": " + self.deviceName)
1479                         if partitionType is None:
1480                                 self["filesystem"].setText(_("Filesystem") + ": " + unknownpartition_msg)
1481                         else:
1482                                 self["filesystem"].setText(_("Filesystem") + ": " + partitionType)
1483                         if self.partitionNum is False:
1484                                 cap = self.hdd.capacity()
1485                                 if cap != "":
1486                                         capacity_info = str(cap)
1487                         else:
1488                                 if selectedPart is not None:
1489                                         if capacity_info == "":
1490                                                 if selectedPart.total() is not None:
1491                                                         tmp = selectedPart.total()/1000/1000
1492                                                         cap = "%d.%03d GB" % (tmp/1000, tmp%1000)
1493                                                         if cap != "":
1494                                                                 capacity_info = str(cap)
1495                                 if capacity_info == "":
1496                                         fstype, sys, size, sizeg, sectors = harddiskmanager.getFdiskInfo(self.hdd.device + str(self.partitionNum))
1497                                         if sizeg is not None:
1498                                                 capacity_info = " " + sizeg + " GB"
1499                                         else:
1500                                                 if size is not None:
1501                                                         tmp = int(size)/1000/1000
1502                                                         cap = "%d.%03d GB" % (tmp/1000, tmp%1000)
1503                                                         capacity_info = str(cap)
1504                         self["partition_capacity"].setText(_("Partition capacity") + ": "  + capacity_info)