enigma2 (20120309 rel32 -> 20120321 rel32)
[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.ConfigList import ConfigListScreen
10 from Components.config import config, configfile, ConfigYesNo, ConfigText, getConfigListEntry, ConfigNothing, NoSave
11 from Components.UsageConfig import defaultStorageDevice
12 from Screens.ChoiceBox import ChoiceBox
13 from Screens.MessageBox import MessageBox
14 from Screens.HelpMenu import HelpableScreen
15 from Screens.Setup import Setup, getSetupTitle
16 from Screens.VirtualKeyBoard import VirtualKeyBoard
17 from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
18 from Tools.LoadPixmap import LoadPixmap
19 from enigma import eTimer
20 from os import path, makedirs, listdir, access, F_OK, R_OK
21
22 def updateVideoDirs(uuid = None):
23         tmp = config.movielist.videodirs.value
24         mountpath = moviedir = ""
25         cfg = config.storage.get(uuid, None)
26         if cfg is not None:
27                 p = harddiskmanager.getPartitionbyUUID(uuid)
28                 if p is not None:
29                         mountpath = cfg['mountpoint'].value
30                         if cfg["enabled"].value:
31                                 if p.isInitialized and uuid == defaultStorageDevice():
32                                         moviedir = "/hdd/movie/"
33                                 elif p.isInitialized and uuid != defaultStorageDevice():
34                                         moviedir = mountpath + "/movie/"
35                                 else:
36                                         moviedir = mountpath + "/"
37                                 if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir not in tmp:
38                                         tmp.append(moviedir)
39                         else:
40                                 if p.isInitialized:
41                                         moviedir = mountpath + "/movie/"
42                                 else:
43                                         moviedir = mountpath + "/"
44                                 if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
45                                         tmp.remove(moviedir)
46                 else:
47                         mountpath = cfg['mountpoint'].value
48                         moviedir = mountpath + "/"
49                         if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
50                                 tmp.remove(moviedir)
51                         moviedir += "movie/"
52                         if moviedir not in ("/hdd/movie/", "/media/hdd/movie/") and moviedir in tmp:
53                                 tmp.remove(moviedir)
54
55         if "/hdd/movie/" not in tmp:
56                 tmp.append("/hdd/movie/")
57         config.movielist.videodirs.value = tmp
58         config.movielist.videodirs.save()
59         config.movielist.save()
60         config.save()
61         configfile.save()
62         print "updateVideoDirs:",config.movielist.videodirs.value
63
64 def doFstabUpgrade(uuid, path, mp, callConfirmApply, applyCallback = None, answer = None, selection = None):
65         print "[doFstabUpgrade] - Removing hard mount entry from fstab.",path, mp
66         partitionPath = path
67         uuidpartitionPath = "/dev/disk/by-uuid/" + uuid
68         mountpath = mp
69         if harddiskmanager.isPartitionpathFsTabMount(uuid,mountpath):
70                 harddiskmanager.unmountPartitionbyMountpoint(mountpath)
71                 harddiskmanager.modifyFstabEntry(partitionPath, mountpath, mode = "add_deactivated")
72         if harddiskmanager.isUUIDpathFsTabMount(uuid,mountpath):
73                 harddiskmanager.unmountPartitionbyMountpoint(mountpath)
74                 harddiskmanager.modifyFstabEntry(uuidpartitionPath, mountpath, mode = "add_deactivated")
75         if mountpath != "/media/hdd":
76                 if harddiskmanager.isPartitionpathFsTabMount(uuid,"/media/hdd"):
77                         harddiskmanager.unmountPartitionbyMountpoint("/media/hdd")
78                         harddiskmanager.modifyFstabEntry(partitionPath, "/media/hdd", mode = "add_deactivated")
79                 if harddiskmanager.isUUIDpathFsTabMount(uuid,"/media/hdd"):
80                         harddiskmanager.unmountPartitionbyMountpoint("/media/hdd")
81                         harddiskmanager.modifyFstabEntry(uuidpartitionPath, "/media/hdd", mode = "add_deactivated")
82
83         if applyCallback is not None:
84                 if harddiskmanager.get_fstab_mountstate(partitionPath, mountpath) == 'auto' or harddiskmanager.get_fstab_mountstate(uuidpartitionPath, mountpath) == 'auto' \
85                         or harddiskmanager.get_fstab_mountstate(partitionPath, "/media/hdd") == 'auto' or harddiskmanager.get_fstab_mountstate(uuidpartitionPath, "/media/hdd") == 'auto':
86                         if answer is not None and selection is not None:
87                                 applyCallback(False, callConfirmApply, answer, selection)
88                         else:
89                                 applyCallback(False, callConfirmApply)
90                 else:
91                         if answer is not None and selection is not None:
92                                 applyCallback(True, callConfirmApply, answer, selection)
93                         else:
94                                 applyCallback(True, callConfirmApply)
95         else:
96                 print "error removing fstab entry!"
97
98 class HarddiskWait(Screen):
99         def doInit(self):
100                 self.timer.stop()
101                 result = self.hdd.initialize(self.isFstabMounted, self.numpart)
102                 harddiskmanager.trigger_udev()
103                 self.close(result)
104
105         def doCheck(self):
106                 self.timer.stop()
107                 result = self.hdd.check( self.isFstabMounted, self.numpart )
108                 self.close(result)
109
110         def __init__(self, session, hdd, stype, numpart = None):
111                 Screen.__init__(self, session)
112                 self.hdd = hdd
113                 self.isFstabMounted = False
114                 self.numpart = numpart
115                 uuid = partitionPath = None
116                 if not self.numpart:
117                         self.numpart = self.hdd.numPartitions()
118
119                 if self.numpart == 0:
120                         uuid = harddiskmanager.getPartitionUUID(hdd.device)
121                         partitionPath = hdd.dev_path
122                 if self.numpart >= 1:
123                         uuid = harddiskmanager.getPartitionUUID(hdd.device + str(self.numpart))
124                         partitionPath = hdd.partitionPath(str(self.numpart))
125
126                 if uuid is not None:
127                         mountpath = harddiskmanager.get_fstab_mountpoint(partitionPath)
128                         if harddiskmanager.isUUIDpathFsTabMount(uuid, mountpath) or harddiskmanager.isPartitionpathFsTabMount(uuid, mountpath):
129                                 self.isFstabMounted = True
130
131                 self.timer = eTimer()
132                 if stype == HarddiskDriveSetup.HARDDISK_INITIALIZE:
133                         text = _("Initializing hard disk...")
134                         if self.hdd.isRemovable:
135                                 text = _("Initializing storage device...")
136                         self.timer.callback.append(self.doInit)
137                 elif stype == HarddiskDriveSetup.HARDDISK_CHECK:
138                         text = _("Checking Filesystem...")
139                         self.timer.callback.append(self.doCheck)
140                 self["wait"] = Label(text)
141                 self.timer.start(100)
142
143
144 class HarddiskDriveSetup(Screen, ConfigListScreen):
145         HARDDISK_INITIALIZE = 1
146         HARDDISK_CHECK = 2
147         HARDDISK_SETUP = 3
148
149         def __init__(self, session, stype = None, device = None, partition = False):
150                 Screen.__init__(self, session)
151                 self.skinName = "HarddiskDriveSetup"
152                 self.hdd = device
153                 self.setup_title = _("Hard disk")
154                 if self.hdd.isRemovable:
155                         self.setup_title = _("Storage device")
156                 self.oldMountpath = None
157                 self.oldEnabledState = None
158                 self.UUIDPartitionList = [ ]
159
160                 if stype not in (self.HARDDISK_INITIALIZE, self.HARDDISK_CHECK, self.HARDDISK_SETUP):
161                         self.type = self.HARDDISK_INITIALIZE
162                 else:
163                         self.type = stype
164
165                 self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.uuidPath, self.partitionPath = harddiskmanager.getPartitionVars(self.hdd,partition)
166                 if config.storage.get(self.UUID, None) is not None:
167                         self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
168                         self.oldEnabledState = config.storage[self.UUID]["enabled"].value
169
170                 print "[HarddiskDriveSetup]-> deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
171                 % (self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
172
173                 self.onChangedEntry = [ ]
174                 self.list = [ ]
175                 ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
176
177                 self["key_red"] = StaticText()
178                 self["key_green"] = StaticText()
179                 self["key_yellow"] = StaticText()
180                 self["key_blue"] = StaticText()
181                 self["introduction"] = StaticText()
182                 self["model"] = StaticText(_("Model: ") + self.hdd.model())
183                 self["capacity"] = StaticText(_("Capacity: ") + self.hdd.capacity())
184                 self["bus"] = StaticText()
185                 self["icon"] = StaticText()
186                 self["bus"].setText(self.hdd.bus_description() + " " + _("Hard disk"))
187                 self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-open.png"))
188                 if self.hdd.isRemovable:
189                         self["bus"].setText(self.hdd.bus_description() + " " + _("Storage device"))
190                         self["icon"].setText(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-big.png"))
191                 self["HelpWindow"] = Pixmap()
192                 self["HelpWindow"].hide()
193
194                 self["OkCancelActions"] = ActionMap(["OkCancelActions"],
195                         {
196                         "cancel": self.keyCancel,
197                         "ok": self.ok,
198                         }, -2)
199
200                 self["shortcuts"] = ActionMap(["ColorActions"],
201                         {
202                         "red": self.hddQuestion
203                         }, -2)
204
205                 self["mountshortcuts"] = ActionMap(["ShortcutActions"],
206                         {
207                         "green": self.apply
208                         }, -2)
209
210                 self["mountshortcuts"].setEnabled(False)
211                 if self.type == self.HARDDISK_SETUP:
212                         self["shortcuts"].setEnabled(False)
213
214                 self.createSetup()
215                 self.onLayoutFinish.append(self.layoutFinished)
216                 self.onShown.append(self.__onShown)
217
218         def layoutFinished(self):
219                 self.setTitle(self.setup_title)
220
221         def __onShown(self):
222                 self.selectionChanged()
223
224         def createSetup(self):
225                 self.list = [ ]
226                 if self.type == self.HARDDISK_SETUP:
227                         if self.numPartitions >= 0:
228                                 if self.UUID is not None and config.storage.get(self.UUID, None) is None:
229                                         harddiskmanager.setupConfigEntries(initial_call = False, dev = self.deviceName)
230                                 uuid_cfg = config.storage.get(self.UUID, None)
231                                 if uuid_cfg is not None:
232                                         self["mountshortcuts"].setEnabled(True)
233                                         self.list = [getConfigListEntry(_("Enable partition automount?"), uuid_cfg["enabled"])]
234                                         if uuid_cfg["enabled"].value:
235                                                 if uuid_cfg["mountpoint"].value == "" or ( self.oldEnabledState is False and uuid_cfg["mountpoint"].value == "/media/hdd"):
236                                                         val = harddiskmanager.suggestDeviceMountpath(self.UUID)
237                                                         uuid_cfg["mountpoint"].value = val
238                                                 self.list.append(getConfigListEntry(_("Mountpoint:"), uuid_cfg["mountpoint"]))
239
240                 self["config"].list = self.list
241                 self["config"].l.setSeperation(400)
242                 self["config"].l.setList(self.list)
243                 if not self.selectionChanged in self["config"].onSelectionChanged:
244                         self["config"].onSelectionChanged.append(self.selectionChanged)
245
246         def selectionChanged(self):
247                 self["key_red"].setText(_("Initialize"))
248                 if self.type == self.HARDDISK_SETUP:
249                         self["shortcuts"].setEnabled(False)
250                         self["key_red"].setText("")
251                         if self.numPartitions >= 0:
252                                 uuid_cfg = config.storage.get(self.UUID, None)
253                                 if uuid_cfg is not None:
254                                         if self["config"].isChanged():
255                                                 self["key_green"].setText(_("Save"))
256                                         else:
257                                                 self["key_green"].setText("")
258                                         if self["config"].getCurrent()[1] == uuid_cfg["enabled"]:
259                                                 self["introduction"].setText(_("Enable automatic partition mounting?"))
260                                         elif self["config"].getCurrent()[1] == uuid_cfg["mountpoint"]:
261                                                 self["introduction"].setText(_("Please enter the directory to use as mountpoint or select a directory by pressing OK."))
262                                         else:
263                                                 self["introduction"].setText("")
264                 elif self.type == self.HARDDISK_INITIALIZE:
265                         self["shortcuts"].setEnabled(True)
266                         self["key_red"].setText(_("Initialize"))
267                         if self.numPartitions >= 0:
268                                 uuid_cfg = config.storage.get(self.UUID, None)
269                                 if uuid_cfg is not None:
270                                         self["introduction"].setText(_("Press Red to initialize this hard disk!"))
271                                         if self.hdd.isRemovable:
272                                                 self["introduction"].setText(_("Press Red to initialize this storage device!"))
273                                 partitionType = harddiskmanager.getBlkidPartitionType(self.partitionPath)
274                                 if self.UUID is None and partitionType is None:
275                                         self["introduction"].setText(_("New uninitialized hard disk found. Please initialize!"))
276                                         if self.hdd.isRemovable:
277                                                 self["introduction"].setText(_("New uninitialized storage device found. Please initialize!"))
278                                 if self.UUID is None and partitionType is not None:
279                                         self["introduction"].setText(_("Unknown partition layout or new uninitialized hard disk found. Please initialize!"))
280                                         if self.hdd.isRemovable:
281                                                 self["introduction"].setText(_("Unknown partition layout or new uninitialized storage device found. Please initialize!"))
282                                 if self.UUID is not None and partitionType is None:
283                                         self["introduction"].setText(_("Unknown partition layout or new uninitialized hard disk found. Please initialize!"))
284                                         if self.hdd.isRemovable:
285                                                 self["introduction"].setText(_("Unknown partition layout or new uninitialized storage device found. Please initialize!"))
286                 elif self.type == self.HARDDISK_CHECK:
287                         self["shortcuts"].setEnabled(True)
288                         self["key_red"].setText(_("Check"))
289                         self["introduction"].setText(_("Press Red to start the filesystem check."))
290
291         def hddReady(self, result):
292                 print "hddReady result: " + str(result)
293                 if (result != 0):
294                         if self.type == self.HARDDISK_INITIALIZE:
295                                 message = _("Unable to initialize hard disk.\nError: ")
296                                 if self.hdd.isRemovable:
297                                         message = _("Unable to initialize storage device.\nError: ")
298                         else:
299                                 message = _("Unable to complete filesystem check.\nError: ")
300                         self.session.open(MessageBox, message + str(self.hdd.errorList[0 - result]), MessageBox.TYPE_ERROR)
301                 else:
302                         if self.type == self.HARDDISK_INITIALIZE:
303                                 #we need to wait until udev has set up all new system links
304                                 self.timer = eTimer()
305                                 self.timer.callback.append(self.verifyInitialize)
306                                 self["introduction"].setText(_("Verifying initialization. Please wait!"))
307                                 self.timer.start(3000,True)
308                         elif self.type == self.HARDDISK_CHECK:
309                                 harddiskmanager.mountPartitionbyUUID(self.UUID)
310                                 self["introduction"].setText(_("Filesystem check completed without errors."))
311
312         def verifyInitialize(self):
313                 self.timer.stop()
314                 self.deviceName, tmpid, self.numPartitions, self.partitionNum, self.uuidPath, self.partitionPath = harddiskmanager.getPartitionVars(self.hdd)
315                 #print "[HarddiskDriveSetup]-> deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
316                 #% (self.deviceName, tmpid, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
317
318                 if tmpid is not None and tmpid != self.UUID:
319                         if self.UUID == defaultStorageDevice() or (self.UUID is None and not harddiskmanager.HDDEnabledCount()): #we initialized the default storage device
320                                 print "[HarddiskDriveSetup] - verifyInitialize - set up device %s as default." % tmpid
321                                 config.storage_options.default_device.value = tmpid
322                                 config.storage_options.default_device.save()
323                                 config.storage_options.save()
324                         if config.storage.get(self.UUID, None) is not None:
325                                 del config.storage[self.UUID] #delete old uuid reference entries
326                         self.UUID = harddiskmanager.getPartitionUUID(self.deviceName)
327                         print "[HarddiskDriveSetup] - verifyInitialize - got new uuid: ",self.UUID
328
329                 if self.UUID is not None:
330                         if config.storage.get(self.UUID, None) is None:
331                                 harddiskmanager.setupConfigEntries(initial_call = False, dev = self.deviceName)
332                         if config.storage.get(self.UUID, None) is not None:
333                                 if self.UUID == defaultStorageDevice():
334                                         config.storage[self.UUID]["enabled"].value = True
335                                         config.storage[self.UUID]["mountpoint"].value = "/media/hdd"
336                                 self.type = self.HARDDISK_SETUP
337                                 self["shortcuts"].setEnabled(True)
338                                 self.createSetup()
339                                 self.selectionChanged()
340                         else:
341                                 self["introduction"].setText(_("Unable to verify partition information. Please restart!"))
342
343         def hddQuestion(self):
344                 if self.type == self.HARDDISK_INITIALIZE:
345                         message = _("Do you really want to initialize this hard disk?\nAll data on this disk will be lost!")
346                         if self.hdd.isRemovable:
347                                 message = _("Do you really want to initialize this storage device?\nAll data on this device will be lost!")
348
349                 elif self.type == self.HARDDISK_CHECK:
350                         message = _("Do you really want to check the filesystem?\nThis could take lots of time!")
351                 self.session.openWithCallback(self.hddConfirmed, MessageBox, message)
352
353         def hddConfirmed(self, confirmed):
354                 if not confirmed:
355                         return
356                 print "hddConfirmed: this will start either the initialize or the fsck now!"
357                 if self.type == self.HARDDISK_INITIALIZE:
358                         print "hddConfirmed: start initialize for uuid:%s and device:%s and partitions:%s" % (self.UUID, self.hdd.device, self.numPartitions)
359                         if self.hdd.numPartitions() >=2:
360                                 for p in harddiskmanager.partitions[:]:
361                                         if p.device is not None:
362                                                 if p.device.startswith(self.hdd.device) and p.device[3:].isdigit():
363                                                         if p.uuid is not None:
364                                                                 self.UUIDPartitionList.append(p.uuid)
365                         if self.UUIDPartitionList:
366                                 for uuid in self.UUIDPartitionList[:]:
367                                         if config.storage.get(uuid, None) is not None:
368                                                 harddiskmanager.unmountPartitionbyUUID(uuid)
369                                                 del config.storage[uuid]
370                                                 print "hddConfirmed: known device re-initialize, removed old uuid:",uuid
371                                                 config.storage.save()
372                                                 config.save()
373                                                 configfile.save()
374
375                         if config.storage.get(self.UUID, None) is not None:
376                                 harddiskmanager.unmountPartitionbyUUID(self.UUID)
377                                 del config.storage[self.UUID]
378                                 print "hddConfirmed: known device re-initialize"
379                                 config.storage.save()
380                                 config.save()
381                                 configfile.save()
382                 self.session.openWithCallback(self.hddReady, HarddiskWait, self.hdd, self.type, self.numPartitions)
383
384         def changedConfigList(self):
385                 if self.type == self.HARDDISK_SETUP:
386                         if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
387                                 if self["config"].getCurrent()[1] == config.storage[self.UUID]["enabled"]:
388                                         self.createSetup()
389
390         def keyLeft(self):
391                 if self.type == self.HARDDISK_SETUP:
392                         if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
393                                 ConfigListScreen.keyLeft(self)
394                                 self.changedConfigList()
395
396         def keyRight(self):
397                 if self.type == self.HARDDISK_SETUP:
398                         if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
399                                 ConfigListScreen.keyRight(self)
400                                 self.changedConfigList()
401
402         def ok(self):
403                 if self.type == self.HARDDISK_SETUP:
404                         if self.numPartitions >= 0 and config.storage.get(self.UUID, None) is not None:
405                                 current = self["config"].getCurrent()
406                                 if current is not None:
407                                         if current[1] == config.storage[self.UUID]["mountpoint"]:
408                                                 self.hideHelpWindow()
409                                                 self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
410                                                 self.session.openWithCallback(self.MountpointBrowserClosed, HarddiskMountpointBrowser, self.hdd, self.UUID)
411
412         def hideHelpWindow(self):
413                 if self.type == self.HARDDISK_SETUP:
414                         current = self["config"].getCurrent()
415                         if current and config.storage.get(self.UUID, None) is not None:
416                                 if current[1] == config.storage[self.UUID]["mountpoint"]:
417                                         if current[1].help_window.instance is not None:
418                                                 current[1].help_window.instance.hide()
419
420         def MountpointBrowserClosed(self, retval = None):
421                 if retval and retval is not None:
422                         mountpath = retval.strip().replace(' ','')
423                         if retval.endswith("/"):
424                                 mountpath = retval[:-1]
425                         print "MountpointBrowserClosed: with path: " + str(mountpath)
426                         try:
427                                 if mountpath != self.oldMountpath:
428                                         if not path.exists(mountpath):
429                                                 makedirs(mountpath)
430                         except OSError:
431                                 print "mountpoint directory could not be created."
432
433                         if not path.exists(mountpath):
434                                 self.session.open(MessageBox, _("Sorry, your directory is not writeable."), MessageBox.TYPE_INFO, timeout = 10)
435
436                         else:
437                                 self.oldMountpath = config.storage[self.UUID]["mountpoint"].value
438                                 config.storage[self.UUID]["mountpoint"].setValue(str(mountpath))
439                                 self.selectionChanged()
440                                 if (harddiskmanager.is_hard_mounted(self.partitionPath) or harddiskmanager.is_hard_mounted(self.uuidPath)):
441                                         message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
442                                         if harddiskmanager.isUUIDpathFsTabMount(self.UUID, mountpath) or harddiskmanager.isPartitionpathFsTabMount(self.UUID, mountpath) \
443                                                 or harddiskmanager.isUUIDpathFsTabMount(self.UUID, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(self.UUID, "/media/hdd"):
444                                                 self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, self.UUID, self.partitionPath, mountpath, False), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
445
446         def confirmFstabUpgrade(self, result, uuid, partitionPath, mountpath, callConfirmApply = False):
447                 print "[HarddiskSetup]confirmFstabUpgrade:",result, uuid, partitionPath, mountpath, callConfirmApply
448                 if not result:
449                         return
450                 doFstabUpgrade(uuid, partitionPath, mountpath, callConfirmApply, self.confirmFstabUpgradeCB)
451
452         def confirmFstabUpgradeCB(self, *val):
453                 answer, result = val
454                 if answer is not None:
455                         if answer:
456                                 if result:
457                                         self.session.openWithCallback(lambda x : self.confirmApply(True), MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
458                                 else:
459                                         self.session.open(MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
460                         else:
461                                 self.session.open(MessageBox, _("Sorry, could not remove mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
462
463         def confirmApply(self, confirmed):
464                 if not confirmed:
465                         print "not confirmed"
466                         return
467                 else:
468                         for x in self["config"].list:
469                                 x[1].save()
470                         print "confirmApply:",config.storage[self.UUID]['enabled'].value, config.storage[self.UUID]['mountpoint'].value
471                         successfully = False
472                         action = "mount_only"
473                         uuid_cfg = config.storage.get(self.UUID, None)
474                         if uuid_cfg is not None:
475                                 if not uuid_cfg['enabled'].value and self.oldEnabledState:
476                                         action = "unmount"
477                                 if uuid_cfg['enabled'].value and uuid_cfg['mountpoint'].value == "/media/hdd":
478                                         action = "mount_default"
479                                 if action == "unmount":
480                                         updateVideoDirs(self.UUID)
481                                 mountpoint = uuid_cfg['mountpoint'].value
482                                 newenable = uuid_cfg['enabled'].value
483                                 if self.oldMountpath is None:
484                                         self.oldMountpath = ""
485                                 if self.oldEnabledState is None:
486                                         self.oldEnabledState = False
487
488                                 successfully = harddiskmanager.changeStorageDevice(self.UUID, action, [self.oldMountpath, self.oldEnabledState, mountpoint, newenable]) #mountDATA
489                                 if successfully:
490                                         uuid_cfg = config.storage.get(self.UUID, None)
491                                         if uuid_cfg is not None:
492                                                 if action in ("mount_default", "mount_only"):
493                                                         harddiskmanager.modifyFstabEntry(self.uuidPath, uuid_cfg['mountpoint'].value, mode = "add_deactivated")
494                                                 updateVideoDirs(self.UUID)
495                                 else:
496                                         self.session.open(MessageBox, _("There was en error while configuring your storage device."), MessageBox.TYPE_ERROR)
497
498                                 #print "[HarddiskDriveSetup confirmApply]-> deviceName:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
499                                 #% (self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
500                                 self.close()
501
502         def apply(self):
503                 self.hideHelpWindow()
504                 if self["config"].isChanged():
505                         if config.storage[self.UUID]['mountpoint'].value == '' :
506                                         self.session.open(MessageBox, _("Please select a mountpoint for this partition."), MessageBox.TYPE_ERROR)
507                         else:
508                                 mountpath = config.storage[self.UUID]['mountpoint'].value
509                                 #print "[HarddiskDriveSetup]-> Apply:'%s' - uuid:'%s' - numPart:'%s' - partNum:'%s'\n- partPath:'%s' - uuidPath:'%s' - hdd.device:'%s' - hdd.dev_path:'%s'" \
510                                 #% (self.deviceName, self.UUID, self.numPartitions, self.partitionNum, self.partitionPath, self.uuidPath, self.hdd.device,self.hdd.dev_path)
511
512                                 if (harddiskmanager.is_hard_mounted(self.partitionPath) or harddiskmanager.is_hard_mounted(self.uuidPath)):
513                                         message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
514                                         if harddiskmanager.isUUIDpathFsTabMount(self.UUID, mountpath) or harddiskmanager.isPartitionpathFsTabMount(self.UUID, mountpath) \
515                                                 or harddiskmanager.isUUIDpathFsTabMount(self.UUID, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(self.UUID, "/media/hdd"):
516                                                 self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, self.UUID, self.partitionPath, mountpath, True), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
517                                         else:
518                                                 self.session.openWithCallback(self.confirmApply, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
519                                 else:
520                                         self.session.openWithCallback(self.confirmApply, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
521
522         def confirmCancel(self, result):
523                 if not result:
524                         return
525                 for x in self["config"].list:
526                         x[1].cancel()
527                 self.close()
528
529         def keyCancel(self):
530                 self.hideHelpWindow()
531                 if self["config"].isChanged():
532                         self.session.openWithCallback(self.confirmCancel, MessageBox, _("Really close without saving settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
533                 else:
534                         self.close()
535
536         # for summary:
537         def changedEntry(self):
538                 for x in self.onChangedEntry:
539                         x()
540                 self.selectionChanged()
541
542         def getCurrentEntry(self):
543                 if self["config"].getCurrent():
544                         return self["config"].getCurrent()[0]
545
546         def getCurrentValue(self):
547                 if self["config"].getCurrent():
548                         return str(self["config"].getCurrent()[1].value)
549
550         def createSummary(self):
551                 from Screens.Setup import SetupSummary
552                 return SetupSummary
553
554
555 class HarddiskDriveSelection(Screen, HelpableScreen):
556         VIEW_HARDDISK = 1
557         VIEW_PARTITION = 2
558
559         def __init__(self, session):
560                 Screen.__init__(self, session)
561                 HelpableScreen.__init__(self)
562                 self.skinName = "HarddiskDriveSelection"
563
564                 self["key_red"] = StaticText()
565                 self["key_green"] = StaticText()
566                 self["key_yellow"] = StaticText()
567                 self["key_blue"] = StaticText()
568                 self["introduction"] = StaticText()
569
570                 self["CancelActions"] = HelpableActionMap(self, "OkCancelActions",
571                         {
572                         "cancel": (self.keyCancel, _("Exit storage device selection.")),
573                         }, -2)
574
575                 self["OkActions"] = HelpableActionMap(self, "OkCancelActions",
576                         {
577                         "ok": (self.okbuttonClick, _("Select storage device.")),
578                         }, -2)
579
580                 self["RedColorActions"] = HelpableActionMap(self, "ColorActions",
581                         {
582                         "red": (self.keyRed, _("Remove offline storage device.")),
583                         }, -2)
584
585                 self["GreenColorActions"] = HelpableActionMap(self, "ColorActions",
586                         {
587                         "green": (self.keyGreen, _("Initialize selected storage device.")),
588                         }, -2)
589
590                 self["YellowColorActions"] = HelpableActionMap(self, "ColorActions",
591                         {
592                         "yellow": (self.keyYellow, _("Check selected storage device.")),
593                         }, -2)
594
595                 self["BlueColorActions"] = HelpableActionMap(self, "ColorActions",
596                         {
597                         "blue": (self.keyBlue, _("Advanced settings.")),
598                         }, -2)
599
600                 self["OkActions"].setEnabled(False)
601                 self["RedColorActions"].setEnabled(False)
602                 self["GreenColorActions"].setEnabled(False)
603                 self["YellowColorActions"].setEnabled(False)
604                 self["BlueColorActions"].setEnabled(False)
605
606                 self.view = self.VIEW_HARDDISK
607                 self.selectedHDD = None
608                 self.currentIndex = 0
609                 self.currentlyUpdating = False
610                 self.list = []
611                 self["hddlist"] = List(self.list)
612
613                 self.onLayoutFinish.append(self.layoutFinished)
614                 self.onClose.append(self.__onClose)
615                 self.onHide.append(self.__onHide)
616                 self.onShown.append(self.__onShown)
617
618         def layoutFinished(self):
619                 self.setTitle(_("Storage devices"))
620                 self.currentlyUpdating = True
621                 self.setButtons()
622                 self.updateList()
623
624         def __onShown(self):
625                 self.currentlyUpdating = False
626                 if not self.hotplugCB in harddiskmanager.delayed_device_Notifier:
627                         harddiskmanager.delayed_device_Notifier.append(self.hotplugCB)
628                 self["hddlist"].setIndex(self.currentIndex)
629                 self.selectionChanged()
630
631         def __onClose(self):
632                 self.currentIndex = 0
633                 self.currentlyUpdating = False
634                 if self.hotplugCB in harddiskmanager.delayed_device_Notifier:
635                         harddiskmanager.delayed_device_Notifier.remove(self.hotplugCB)
636
637         def __onHide(self):
638                 self.currentlyUpdating = True
639                 if self.hotplugCB in harddiskmanager.delayed_device_Notifier:
640                         harddiskmanager.delayed_device_Notifier.remove(self.hotplugCB)
641
642         def hotplugCB(self, dev, media_state):
643                 if media_state in ("add_delayed", "remove_delayed"):
644                         print "[HarddiskDriveSelection] - hotplugCB for dev:%s, media_state:%s" % (dev, media_state)
645                         if self.currentlyUpdating is False and self.view == self.VIEW_HARDDISK:
646                                 self.currentlyUpdating = True
647                                 self.setButtons()
648                                 self.updateList()
649
650         def buildHDDList(self, hd, isOfflineStorage = False, partNum = False):
651                 divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
652                 devicepng = onlinepng = None
653                 isOfflineStorageDevice = isOfflineStorage
654                 isConfiguredStorageDevice = isMountedPartition = isReadable = False
655                 currentMountpoint = partitionType = selectedPart = partitionPath = deviceName = uuidPath =None
656                 hdd_description = device_info = ""
657                 numPartitions = 0
658                 partitionNum = False
659                 fstype = sys = size = sizeg = None
660
661                 if isOfflineStorageDevice:
662                         uuid = hd
663                         print "[HarddiskDriveSelection] - buildHDDList for offline uuid: ",uuid
664                         hdd_description = config.storage[uuid]["device_description"].value
665                         if config.storage[uuid]["enabled"].value == True:
666                                 isConfiguredStorageDevice = True
667                                 currentMountpoint = config.storage[uuid]["mountpoint"].value
668                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-unavailable.png"))
669                         onlinepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_green_off.png"))
670                         if config.storage[uuid]["isRemovable"].value == True:
671                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-unavailable.png"))
672                                 device_info += config.storage[uuid]["device_info"].value + " " + _("Storage device")
673                         else:
674                                 device_info += config.storage[uuid]["device_info"].value + " " + _("Hard disk")
675                         if currentMountpoint is not None:
676                                 device_info += " - " + "( " + currentMountpoint + " )"
677                 else:
678                         hdd_description = hd.model()
679                         deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
680                         print "[HarddiskDriveSelection] - buildHDDList for online device:",deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath
681                         if partitionNum is False:
682                                 cap = hd.capacity()
683                                 if cap != "":
684                                         hdd_description += " (" + cap + ")"
685                         else:
686                                 fstype, sys, size, sizeg = harddiskmanager.getFdiskInfo(hd.device + str(partitionNum))
687                                 if sizeg is not None:
688                                         hdd_description += " (" + sizeg + " GB)"
689
690                         if uuid is not None:
691                                 p = harddiskmanager.getPartitionbyUUID(uuid)
692                                 if p is not None:
693                                         selectedPart = p
694                                         if selectedPart.fsType == None:
695                                                 partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)
696
697                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk.png"))
698                         onlinepng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/buttons/button_green.png"))
699                         if hd.isRemovable:
700                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable.png"))
701                                 device_info += hd.bus_description() + " " + _("Storage device")
702                         else:
703                                 device_info += hd.bus_description() + " " + _("Hard disk")
704
705                         if uuid is not None:
706                                 cfg_uuid = config.storage.get(uuid, None)
707                                 if cfg_uuid is not None:
708                                         if cfg_uuid["mountpoint"].value != "":
709                                                 currentMountpoint = cfg_uuid["mountpoint"].value
710                                         if cfg_uuid["enabled"].value:
711                                                 isConfiguredStorageDevice = True
712                                                 p = harddiskmanager.getPartitionbyMountpoint(currentMountpoint)
713                                                 if p is not None:
714                                                         if p.mounted():
715                                                                 isMountedPartition = True
716                                 if not isMountedPartition:
717                                         if currentMountpoint is None:
718                                                 currentMountpoint = harddiskmanager.get_fstab_mountpoint(partitionPath) or harddiskmanager.get_fstab_mountpoint(uuidPath)
719                                         if currentMountpoint is not None:
720                                                 if harddiskmanager.is_hard_mounted(partitionPath) or harddiskmanager.is_hard_mounted(uuidPath):
721                                                         if harddiskmanager.isPartitionpathFsTabMount(uuid,currentMountpoint) or harddiskmanager.isUUIDpathFsTabMount(uuid,currentMountpoint):
722                                                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-attention.png"))
723                                                                 if hd.isRemovable:
724                                                                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-attention.png"))
725                                                                 device_info += " - " + _("Needs attention!")
726                                                         else:
727                                                                 device_info += " - " + _("No mountpoint defined!")
728                                                 else:
729                                                         if not isMountedPartition:
730                                                                 if selectedPart is not None and selectedPart.isMountable:
731                                                                         if selectedPart.isReadable:
732                                                                                 isReadable = True
733                                                                                 device_info += " - " + _("No mountpoint defined!")
734                                                                         else:
735                                                                                 device_info += " - " + _("Unsupported partition type!")
736                                                                 elif selectedPart is not None and not selectedPart.isMountable:
737                                                                         if self.view == self.VIEW_HARDDISK:
738                                                                                 device_info += " - " + _("Please initialize!")
739                                                                         else:
740                                                                                 device_info += " - " + _("Unsupported partition type!")
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 += " - " + _("No mountpoint defined!")
750                                                                                 else:
751                                                                                         device_info += " - " + _("Unsupported partition type!")
752                                                                         else:
753                                                                                 if self.view == self.VIEW_HARDDISK:
754                                                                                         device_info += " - " + _("Please initialize!")
755                                                                                 else:
756                                                                                         device_info += " - " + _("Unsupported partition type!")
757                                         if currentMountpoint is None and cfg_uuid is not None:
758                                                 currentMountpoint = cfg_uuid["mountpoint"].value
759                                                 if currentMountpoint == "":
760                                                         if selectedPart is not None and selectedPart.isMountable:
761                                                                 if selectedPart.isReadable:
762                                                                         isReadable = True
763                                                                         device_info += " - " + _("No mountpoint defined!")
764                                                                 else:
765                                                                         device_info += " - " + _("Unsupported partition type!")
766                                                         elif selectedPart is not None and not selectedPart.isMountable:
767                                                                 if self.view == self.VIEW_HARDDISK:
768                                                                         device_info += " - " + _("Please initialize!")
769                                                                 else:
770                                                                         device_info += " - " + _("Unsupported partition type!")
771                                                         else:
772                                                                 if access("/autofs/" + deviceName, F_OK|R_OK):
773                                                                         isReadable = True
774                                                                         try:
775                                                                                 listdir("/autofs/" + deviceName)
776                                                                         except OSError:
777                                                                                 isReadable = False
778                                                                         if isReadable:
779                                                                                 device_info += " - " + _("No mountpoint defined!")
780                                                                         else:
781                                                                                 device_info += " - " + _("Unsupported partition type!")
782                                                                 else:
783                                                                         if self.view == self.VIEW_HARDDISK:
784                                                                                 device_info += " - " + _("Please initialize!")
785                                                                         else:
786                                                                                 device_info += " - " + _("Unsupported partition type!")
787                                         if (currentMountpoint is None and cfg_uuid is None):
788                                                 device_info += " - " + _("No mountpoint defined!")
789                                 if isMountedPartition:
790                                         isReadable = True
791                                         devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_harddisk-configured.png"))
792                                         if hd.isRemovable:
793                                                 devicepng = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/device_removable-configured.png"))
794                                         device_info += " - " + currentMountpoint
795                         else:
796                                 if numPartitions <=1:
797                                         device_info += " - " + _("Please initialize!")
798                                 else:
799                                         if self.view == self.VIEW_HARDDISK:
800                                                 device_info += " - " + _("Multiple partitions found!")
801                                         else:
802                                                 device_info += " - " + _("Unsupported partition type!")
803
804                 #print "BuildHDDLIST",hdd_description, device_info, numPartitions, isOfflineStorageDevice, isMountedPartition, currentMountpoint, partitionPath, partitionType, partitionNum, isReadable
805                 return((hdd_description, hd, device_info, numPartitions, isOfflineStorageDevice, isMountedPartition, currentMountpoint, devicepng, onlinepng, divpng, partitionNum, isReadable, partitionPath, partitionType, deviceName))
806
807         def updateList(self):
808                 self.view = self.VIEW_HARDDISK
809                 self.selectedHDD = None
810                 self.list = []
811
812                 for hd in harddiskmanager.hdd:
813                         if not hd.isRemovable:
814                                 numPart = hd.numPartitions()
815                                 self.list.append(self.buildHDDList(hd, isOfflineStorage = False)) #online hard disk devices discovered
816                 for hd in harddiskmanager.hdd:
817                         if hd.isRemovable:
818                                 numPart = hd.numPartitions()
819                                 self.list.append(self.buildHDDList(hd, isOfflineStorage = False)) #online removable devices discovered
820                 if self.list:
821                         self.list.sort(key=lambda x: x[14][:3])
822                 for uuid in config.storage:
823                         dev = harddiskmanager.getDeviceNamebyUUID(uuid)
824                         if dev is None:
825                                 self.list.append(self.buildHDDList(uuid, isOfflineStorage = True)) #offline devices
826                 if not self.list:
827                         self.list.append((_("no storage devices found"), 0, None, None, None, None, None, None, None, None, False))
828                         self["introduction"].setText(_("No installed or configured storage devices found!"))
829
830                 self["hddlist"].setList(self.list)
831                 if not self.selectionChanged in self["hddlist"].onSelectionChanged:
832                         self["hddlist"].onSelectionChanged.append(self.selectionChanged)
833                 self["hddlist"].setIndex(self.currentIndex)
834                 self.currentlyUpdating = False
835
836         def updatePartitionList(self, hdd):
837                 self.view = self.VIEW_PARTITION
838                 self.selectedHDD = hdd
839                 numpart = hdd.numPartitions()
840                 self.list = []
841                 for p in harddiskmanager.partitions[:]:
842                         if p.device is not None:
843                                 if p.device.startswith(hdd.device) and p.device[3:].isdigit():
844                                         #print "add partition",p.device[3:],p.device
845                                         self.list.append(self.buildHDDList(hdd, isOfflineStorage = False, partNum = p.device[3:])) #online devices partition discovered
846                 if self.list:
847                         self.list.sort(key=lambda x: x[14][3:])
848                 self["hddlist"].setList(self.list)
849                 if not self.selectionChanged in self["hddlist"].onSelectionChanged:
850                         self["hddlist"].onSelectionChanged.append(self.selectionChanged)
851                 self["hddlist"].setIndex(0)
852                 self.currentlyUpdating = False
853
854         def setButtons(self):
855                 self["key_red"].setText("")
856                 self["key_green"].setText("")
857                 self["key_yellow"].setText("")
858                 self["key_blue"].setText("")
859                 self["OkActions"].setEnabled(False)
860                 self["RedColorActions"].setEnabled(False)
861                 self["GreenColorActions"].setEnabled(False)
862                 self["YellowColorActions"].setEnabled(False)
863                 self["BlueColorActions"].setEnabled(False)
864                 if config.usage.setup_level.index >= 1:
865                         if self.list:
866                                 self["key_blue"].setText(_("Settings"))
867                                 self["BlueColorActions"].setEnabled(True)
868
869         def selectionChanged(self):
870                 #[HarddiskDriveSelection] - current: (0: hdd_description, 1:hd/uuid, 2;device_info, 3:numpart, 4:isOfflineStorageDevice, 5:isMountedPartition, 6:currentMountpoint, devicepng, onlinepng, divpng)
871                 self.setButtons()
872                 current = self["hddlist"].getCurrent()
873                 introduction = ""
874                 selectedPart = None
875                 if current:
876                         self.currentIndex = self["hddlist"].getIndex()
877                         numpart = current[3]
878                         offline = current[4]
879                         partNum = current[10]
880                         if numpart >= 0 and not offline:
881                                 self["key_green"].setText(_("Initialize"))
882                                 self["GreenColorActions"].setEnabled(True)
883                                 self["OkActions"].setEnabled(True)
884                                 introduction = _("Please press OK to set up a mountpoint for this hard disk!")
885                                 hd = current[1]
886                                 isReadable = current[11]
887                                 selectedPart = None
888                                 partitionType = None
889                                 if hd.isRemovable:
890                                         introduction = _("Please press OK to set up a mountpoint for this storage device!")
891                                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
892                                 if partitionNum is False and numPartitions >= 2:
893                                                 self["key_green"].setText("")
894                                                 self["GreenColorActions"].setEnabled(False)
895                                                 introduction = _("Please press OK to see available partitions!")
896                                 if partitionNum is not False and numPartitions >= 2:
897                                         self["key_green"].setText("")
898                                         self["GreenColorActions"].setEnabled(False)
899
900                                 if uuid is not None:
901                                         p = harddiskmanager.getPartitionbyUUID(uuid)
902                                         if p is not None:
903                                                 selectedPart = p
904                                                 partitionType = selectedPart.fsType
905                                                 if partitionType is None:
906                                                         partitionType = harddiskmanager.getBlkidPartitionType(partitionPath)
907                                 if self.view == self.VIEW_HARDDISK:
908                                         if uuid is not None:
909                                                 if numPartitions <= 1:
910                                                         if partitionType is not None and partitionType in ( "ext2", "ext3" ):
911                                                                 self["key_yellow"].setText(_("Check"))
912                                                                 self["YellowColorActions"].setEnabled(True)
913                                                         else:
914                                                                 if not isReadable:
915                                                                         self["OkActions"].setEnabled(False)
916                                                                         introduction = _("Please press green to initialize this hard disk!")
917                                                                         if hd.isRemovable:
918                                                                                 introduction = _("Please press green to initialize this storage device!")
919                                         else:
920                                                 if numPartitions <= 1:
921                                                         self["OkActions"].setEnabled(False)
922                                                         introduction = _("Please press green to initialize this hard disk!")
923                                                         if hd.isRemovable:
924                                                                 introduction = _("Please press green to initialize this storage device!")
925                                 if self.view == self.VIEW_PARTITION:
926                                         if uuid is not None:
927                                                 if partitionType is not None and partitionType in ( "ext2", "ext3" ):
928                                                         self["key_yellow"].setText(_("Check"))
929                                                         self["YellowColorActions"].setEnabled(True)
930                                                 else:
931                                                         introduction = _("Please press OK to set up a mountpoint for this partition!")
932                                                         if not isReadable:
933                                                                 self["OkActions"].setEnabled(False)
934                                                                 introduction = _("Unknown or unsupported partition type found!")
935                                         else:
936                                                 self["OkActions"].setEnabled(False)
937                                                 introduction = _("Please initialize this hard disk!")
938                                                 if hd.isRemovable:
939                                                         introduction = _("Please initialize this storage device!")
940                                                 if not isReadable:
941                                                                 introduction = _("Unknown or unsupported partition type found!")
942                         if offline:
943                                 self["key_red"].setText(_("Remove"))
944                                 self["RedColorActions"].setEnabled(True)
945                                 introduction = _("Please press red to remove this hard disk configuration!")
946                                 if isinstance(current[1], (basestring, str)):
947                                         if config.storage[current[1]]["isRemovable"].value == True:
948                                                 introduction = _("Please press red to remove this storage device configuration!")
949
950                         self["introduction"].setText(introduction)
951
952         def keyCancel(self):
953                 if self.view == self.VIEW_PARTITION:
954                         self.view = self.VIEW_HARDDISK
955                         self.mainMenuClosed()
956                 else:
957                         self.close()
958
959         def handleAnswer(self, answer, selection):
960                 answer = answer and answer[1]
961                 if answer == "mount_default":
962                         self.applyAnswer(answer, selection)
963                 elif answer == "mount_only":
964                         self.applyAnswer(answer, selection)
965                 elif answer == "mount_manually":
966                         hd = selection[1]
967                         numpart = selection[3]
968                         partNum = selection[10]
969                         if numpart >= 2 and partNum is not False:
970                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, HarddiskDriveSetup.HARDDISK_SETUP, device = hd, partition = partNum)
971                         else:
972                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, HarddiskDriveSetup.HARDDISK_SETUP, device = hd)
973                 elif answer == "unmount":
974                         self.confirmApplyAnswer(True, answer, selection)
975                 elif answer in ( None, "nothing"):
976                         print "nothing to do"
977
978         def applyAnswer(self, answer, selection):
979                 print "[HarddiskDriveSelection] - applyAnswer:",answer,selection
980                 hd = selection[1]
981                 partNum = selection[10]
982                 deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
983
984                 uuid_cfg = config.storage.get(uuid, None)
985                 if uuid_cfg is not None:
986                         mountpath = ""
987                         if answer == "mount_default":
988                                 mountpath = "/media/hdd"
989                         else:
990                                 mountpath = harddiskmanager.suggestDeviceMountpath(uuid)
991
992                         if harddiskmanager.isUUIDpathFsTabMount(uuid, mountpath) or harddiskmanager.isPartitionpathFsTabMount(uuid, mountpath) \
993                                 or harddiskmanager.isUUIDpathFsTabMount(uuid, "/media/hdd") or harddiskmanager.isPartitionpathFsTabMount(uuid, "/media/hdd"):
994                                 message = _("Device already hard mounted over filesystem table. Remove fstab entry?")
995                                 self.session.openWithCallback(lambda x : self.confirmFstabUpgrade(x, uuid, partitionPath, mountpath, answer, selection, True), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
996                         else:
997                                 self.confirmApplyAnswer(True, answer, selection)
998                 else:
999                         print "[applyAnswer] - could not determine uuid"
1000
1001         def confirmFstabUpgrade(self, result, uuid, partitionPath, mountpath, answer, selection, callConfirmApply = False):
1002                 if not result:
1003                         return
1004                 doFstabUpgrade(uuid, partitionPath, mountpath, callConfirmApply, self.confirmFstabUpgradeCB, answer, selection)
1005
1006         def confirmFstabUpgradeCB(self, *val):
1007                 result, callConfirmApply, answer, selection, = val
1008                 if result is not None:
1009                         if result:
1010                                 if callConfirmApply:
1011                                         self.session.openWithCallback(lambda x : self.confirmApplyAnswer(True, answer, selection), MessageBox, _("Successfully, deactivated mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
1012                         else:
1013                                 self.session.open(MessageBox, _("Sorry, could not remove mount entry from fstab."), MessageBox.TYPE_INFO, timeout = 10)
1014
1015         def confirmApplyAnswer(self, confirmed, answer, selection):
1016                 if not confirmed:
1017                         print "not confirmed"
1018                         return
1019                 else:
1020                         hd = selection[1]
1021                         partNum = selection[10]
1022                         deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
1023
1024                         successfully = False
1025                         uuid_cfg = config.storage.get(uuid, None)
1026                         if uuid_cfg is not None:
1027                                 if answer == "unmount":
1028                                         updateVideoDirs(uuid)
1029                                 successfully = harddiskmanager.changeStorageDevice(uuid, answer, None)
1030                                 print "confirmApplyAnswer:",uuid_cfg['enabled'].value, uuid_cfg['mountpoint'].value
1031                         if successfully:
1032                                 uuid_cfg = config.storage.get(uuid, None)
1033                                 if uuid_cfg is not None:
1034                                         if answer in ("mount_default", "mount_only"):
1035                                                 harddiskmanager.modifyFstabEntry(uuidPath, uuid_cfg['mountpoint'].value, mode = "add_deactivated")
1036                                         updateVideoDirs(uuid)
1037                         else:
1038                                 self.session.open(MessageBox, _("There was en error while configuring your storage device."), MessageBox.TYPE_ERROR)
1039                         self.mainMenuClosed()
1040
1041         def okbuttonClick(self):
1042                 selection = self["hddlist"].getCurrent()
1043                 if selection[1] != 0:
1044                         print "[HarddiskDriveSelection] - okbuttonClick:",selection[0], selection[2], selection[3],selection[10]
1045                         hd = selection[1]
1046                         partNum = selection[10]
1047                         isReadable = selection[11]
1048                         selectedPart = None
1049                         deviceName, uuid, numPartitions, partitionNum, uuidPath, partitionPath = harddiskmanager.getPartitionVars(hd,partNum)
1050
1051                         if uuid is not None:
1052                                 p = harddiskmanager.getPartitionbyUUID(uuid)
1053                                 if p is not None:
1054                                         selectedPart = p
1055
1056                         uuid_cfg = config.storage.get(uuid, None)
1057                         if uuid is not None and uuid_cfg is None:
1058                                 harddiskmanager.setupConfigEntries(initial_call = False, dev = deviceName)
1059
1060                         defaultmsg = (_("Set up as default storage device now."), "mount_default")
1061                         mountmsg = (_("Automatically set up a mountpoint now."), "mount_only")
1062                         manualmsg = (_("Manually select a mountpoint now."), "mount_manually")
1063                         unmountmsg = (_("Unmount now."), "unmount")
1064
1065                         choices = [ ]
1066                         if uuid_cfg is not None and not uuid_cfg['enabled'].value: # unconfigured drive
1067                                 if selectedPart is not None and selectedPart.isInitialized:
1068                                         choices.extend([defaultmsg, mountmsg, manualmsg])
1069                                 else:
1070                                         choices.extend([mountmsg, manualmsg])
1071                         elif uuid_cfg is not None and uuid_cfg['enabled'].value: # configured drive
1072                                 if selectedPart is not None and selectedPart.isInitialized:
1073                                         if defaultStorageDevice() != uuid:
1074                                                 choices.extend([unmountmsg, defaultmsg, manualmsg])
1075                                         elif defaultStorageDevice() == uuid:
1076                                                 choices.extend([unmountmsg, mountmsg, manualmsg])
1077                                 else:
1078                                         choices.extend([unmountmsg, manualmsg])
1079                         choices.append((_("Do nothing."), "nothing"))
1080
1081                         titletext = _("Unconfigured hard disk found!")
1082                         if hd.isRemovable:
1083                                 titletext = _("Unconfigured storage device found!")
1084
1085                         if uuid_cfg is not None and uuid_cfg['enabled'].value:
1086                                 titletext = _("Hard disk already configured!")
1087                                 if hd.isRemovable:
1088                                         titletext = _("Storage device already configured!")
1089
1090                         if numPartitions >= 2 and partNum is False:
1091                                 self.updatePartitionList(hd)
1092                         else:
1093                                 self.session.openWithCallback(lambda x : self.handleAnswer(x, selection), ChoiceBox, title = titletext + "\n" , list = choices)
1094
1095         def mainMenuClosed(self, *val):
1096                 if self.currentlyUpdating is False:
1097                         self.currentlyUpdating = True
1098                         self.setButtons()
1099                         if self.view == self.VIEW_PARTITION:
1100                                 self.updatePartitionList(self.selectedHDD)
1101                         else:
1102                                 self.updateList()
1103
1104         def keyRed(self):
1105                 selection = self["hddlist"].getCurrent()
1106                 if isinstance(selection[1], (basestring, str)):
1107                         print "[HarddiskDriveSelection] - keyRed:",selection[0], selection[1]
1108                         message = _("Really delete this hard disk entry?")
1109                         if config.storage[selection[1]]["isRemovable"].value:
1110                                 message = _("Really delete this storage device entry?")
1111                         self.session.openWithCallback(lambda x : self.keyRedConfirm(x, selection[1]), MessageBox, message, MessageBox.TYPE_YESNO, timeout = 20, default = True)
1112
1113         def keyRedConfirm(self, result, uuid):
1114                 if not result:
1115                         return
1116                 if config.storage.get(uuid, None) is not None:
1117                         updateVideoDirs(uuid)
1118                         del config.storage[uuid]
1119                         config.storage.save()
1120                         config.save()
1121                         configfile.save()
1122                         if self.currentlyUpdating is False:
1123                                 self.currentlyUpdating = True
1124                                 self.setButtons()
1125                                 self.updateList()
1126
1127         def keyGreen(self):
1128                 #[HarddiskDriveSelection] - current: (0: hdd_description, 1:hd/uuid, 2;device_info, 3:numpart, 4:isOfflineStorageDevice, 5:isMountedPartition, 6:currentMountpoint, devicepng, onlinepng, divpng)
1129                 selection = self["hddlist"].getCurrent()
1130                 if selection[1] != 0:
1131                         print "[HarddiskDriveSelection] - keyGreen:",selection[0], selection[2], selection[3]
1132                         self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, HarddiskDriveSetup.HARDDISK_INITIALIZE, device = selection[1])
1133
1134         def keyYellow(self):
1135                 selection = self["hddlist"].getCurrent()
1136                 if selection[1] != 0:
1137                         print "[HarddiskDriveSelection] - keyYellow:",selection[0], selection[2], selection[3], selection[10]
1138                         if selection[3] >= 2 and selection[10] is not False:
1139                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, HarddiskDriveSetup.HARDDISK_CHECK, device = selection[1], partition = selection[10])
1140                         else:
1141                                 self.session.openWithCallback(self.mainMenuClosed, HarddiskDriveSetup, HarddiskDriveSetup.HARDDISK_CHECK, device = selection[1], partition = selection[3])
1142
1143         def keyBlue(self):
1144                 selection = self["hddlist"].getCurrent()
1145                 if selection[1] != 0:
1146                         self.session.openWithCallback(self.mainMenuClosed, Setup, "harddisk")
1147
1148
1149 class HarddiskMountpointBrowser(Screen, HelpableScreen):
1150
1151         def __init__(self, session, hdd, uuid):
1152                 Screen.__init__(self, session)
1153                 self.skinName = "HarddiskMountpointBrowser"
1154                 self.hdd = hdd
1155                 self.UUID = uuid
1156                 HelpableScreen.__init__(self)
1157
1158                 self["key_red"] = StaticText(_("Cancel"))
1159                 self["key_green"] = StaticText(_("Use"))
1160                 self["key_yellow"] = StaticText(_("Create directory"))
1161                 self["key_blue"] = StaticText()
1162
1163                 currdir = "/media/"
1164                 inhibitDirs = ["/autofs", "/mnt", "/hdd", "/bin", "/boot", "/dev", "/etc", "/home", "/lib", "/proc", "/sbin", "/share", "/sys", "/tmp", "/usr", "/var", "/media/realroot", "/media/union"]
1165                 self.filelist = FileList(currdir, matchingPattern="", inhibitDirs = inhibitDirs)
1166                 self["filelist"] = self.filelist
1167
1168                 self["shortcuts"] = ActionMap(["ColorActions"],
1169                         {
1170                         "red": self.exit,
1171                         "green": self.use,
1172                         "yellow": self.createMountdir,
1173                         }, -2)
1174
1175                 self["OkCancelActions"] = ActionMap(["OkCancelActions"],
1176                         {
1177                         "cancel": self.exit,
1178                         "ok": self.ok,
1179                         }, -2)
1180
1181                 self.onLayoutFinish.append(self.layoutFinished)
1182
1183         def layoutFinished(self):
1184                 self.setTitle(_("Select mountpoint"))
1185
1186         def ok(self):
1187                 if self.filelist.canDescent():
1188                         self.filelist.descent()
1189
1190         def use(self):
1191                 if self["filelist"].getCurrentDirectory() is not None:
1192                         if self.filelist.canDescent() and self["filelist"].getFilename() and len(self["filelist"].getFilename()) > len(self["filelist"].getCurrentDirectory()):
1193                                 self.filelist.descent()
1194                                 self.close(self["filelist"].getCurrentDirectory())
1195                 else:
1196                         self.close(self["filelist"].getFilename())
1197
1198         def createMountdir(self):
1199                 cfg = config.storage.get(self.UUID, None)
1200                 if cfg is not None:
1201                         self.session.openWithCallback(self.createMountdirCB, VirtualKeyBoard, title = (_("Enter mountpoint path.")), text = cfg["mountpoint"].value)
1202
1203         def createMountdirCB(self, retval = None):
1204                 if retval is not None:
1205                         self.close(retval)
1206
1207         def exit(self):
1208                 self.close(False)