summaryrefslogtreecommitdiffstats
path: root/pyanaconda/ui/gui/spokes/custom.py
blob: ee7c204b0faf1d58dae834ad39022bf52663b872 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# Custom partitioning classes.
#
# Copyright (C) 2012  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Chris Lumens <clumens@redhat.com>
#

# TODO:
# - Add button doesn't do anything.  It may need to ask for what kind of thing is being
#   added, too.
# - Clicking on a MountpointSelector does not cause it to be highlighted in blue.
# - Deleting an LV is not reflected in available space in the bottom left.
# - Device descriptions, suggested sizes, etc. should be moved out into a support file.
# - Removing a device is not very smart.  It needs to take into account LUKS, LVM, RAID,
#   all that kind of stuff.  If this is the last device in one of those containers, all
#   the containers should be deleted too.
# - Tabbing behavior in the accordion is weird.
# - When all members of a page are removed, the page should be removed from the
#   accordion and the RHS should be updated to display something else.

import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
N_ = lambda x: x
P_ = lambda x, y, z: gettext.ldngettext("anaconda", x, y, z)

from pyanaconda.product import productName, productVersion
from pyanaconda.storage.formats import device_formats
from pyanaconda.storage.size import Size

from pyanaconda.ui.gui import UIObject
from pyanaconda.ui.gui.spokes import NormalSpoke
from pyanaconda.ui.gui.spokes.lib.cart import SelectedDisksDialog
from pyanaconda.ui.gui.spokes.lib.accordion import *
from pyanaconda.ui.gui.utils import enlightbox, setViewportBackground
from pyanaconda.ui.gui.categories.storage import StorageCategory

from gi.repository import Gtk

__all__ = ["CustomPartitioningSpoke"]

class AddDialog(UIObject):
    builderObjects = ["addDialog"]
    mainWidgetName = "addDialog"
    uiFile = "spokes/custom.ui"

    def on_add_cancel_clicked(self, button, *args):
        self.window.destroy()

    def on_add_confirm_clicked(self, button, *args):
        self.window.destroy()

    def refresh(self):
        UIObject.refresh(self)

    def run(self):
        return self.window.run()

class ConfirmDeleteDialog(UIObject):
    builderObjects = ["confirmDeleteDialog"]
    mainWidgetName = "confirmDeleteDialog"
    uiFile = "spokes/custom.ui"

    def on_delete_cancel_clicked(self, button, *args):
        self.window.destroy()

    def on_delete_confirm_clicked(self, button, *args):
        self.window.destroy()

    def refresh(self, mountpoint, device):
        UIObject.refresh(self)
        label = self.builder.get_object("confirmLabel")

        if mountpoint:
            txt = "%s (%s)" % (mountpoint, device)
        else:
            txt = device

        label.set_text(label.get_text() % txt)

    def run(self):
        return self.window.run()

class CustomPartitioningSpoke(NormalSpoke):
    builderObjects = ["customStorageWindow", "sizeAdjustment",
                      "partitionStore",
                      "addImage", "removeImage", "settingsImage"]
    mainWidgetName = "customStorageWindow"
    uiFile = "spokes/custom.ui"

    category = StorageCategory
    title = N_("MANUAL PARTITIONING")

    def __init__(self, data, storage, payload, instclass):
        NormalSpoke.__init__(self, data, storage, payload, instclass)

        self._current_selector = None
        self._ran_autopart = False

    def apply(self):
        pass

    @property
    def indirect(self):
        return True

    def _grabObjects(self):
        self._configureBox = self.builder.get_object("configureBox")

        self._viewport = self.builder.get_object("partitionsViewport")
        self._partitionsNotebook = self.builder.get_object("partitionsNotebook")

        self._addButton = self.builder.get_object("addButton")
        self._removeButton = self.builder.get_object("removeButton")
        self._configButton = self.builder.get_object("configureButton")

    def initialize(self):
        from pyanaconda.storage.devices import DiskDevice
        from pyanaconda.storage.formats.fs import FS

        NormalSpoke.initialize(self)

        self._grabObjects()
        setViewportBackground(self.builder.get_object("availableSpaceViewport"), "#db3279")
        setViewportBackground(self.builder.get_object("totalSpaceViewport"), "#60605b")
        setViewportBackground(self._viewport)

        self._accordion = Accordion()
        self._viewport.add(self._accordion)

        # Populate the list of valid filesystem types from the format classes.
        # Unfortunately, we have to narrow them down a little bit more because
        # this list will include things like PVs and RAID members.
        combo = self.builder.get_object("fileSystemTypeCombo")
        for cls in device_formats.itervalues():
            obj = cls()
            if obj.supported and obj.formattable and \
               (isinstance(obj, FS) or obj.type in ["biosboot", "prepboot", "swap"]):
                combo.append_text(obj.name)

    def _mountpointName(self, mountpoint):
        # If there's a mount point, apply a kind of lame scheme to it to figure
        # out what the name should be.  Basically, just look for the last directory
        # in the mount point's path and capitalize the first letter.  So "/boot"
        # becomes "Boot", and "/usr/local" becomes "Local".
        if mountpoint == "/":
            return "Root"
        elif mountpoint != None:
            try:
                lastSlash = mountpoint.rindex("/")
            except ValueError:
                # No slash in the mount point?  I suppose that's possible.
                return None

            return mountpoint[lastSlash+1:].capitalize()
        else:
            return None

    def _clearpartDevices(self):
        return [d for d in self.storage.devicetree.devices if d.name in self.data.clearpart.drives]

    def _unusedDevices(self):
        from pyanaconda.storage.devices import DiskDevice
        return [d for d in self.storage.unusedDevices if d.disks and not isinstance(d, DiskDevice)]

    def _currentFreeSpace(self):
        """Add up all the free space on selected disks and return it as a Size."""
        totalFree = 0

        freeDisks = self.storage.getFreeSpace(disks=self._clearpartDevices())
        for tup in freeDisks.values():
            for chunk in tup:
                totalFree += chunk

        return Size(totalFree)

    def _currentTotalSpace(self):
        """Add up the sizes of all selected disks and return it as a Size."""
        totalSpace = 0

        for disk in self._clearpartDevices():
            totalSpace += disk.size

        return Size(spec="%s MB" % totalSpace)

    def _updateSpaceDisplay(self):
        # Set up the free space/available space displays in the bottom left.
        self._availableSpaceLabel = self.builder.get_object("availableSpaceLabel")
        self._totalSpaceLabel = self.builder.get_object("totalSpaceLabel")
        self._summaryButton = self.builder.get_object("summary_button")

        self._availableSpaceLabel.set_text(str(self._currentFreeSpace()))
        self._totalSpaceLabel.set_text(str(self._currentTotalSpace()))

        summaryLabel = self._summaryButton.get_children()[0]
        count = len(self.data.clearpart.drives)
        summary = P_("%d storage device selected",
                     "%d storage devices selected",
                     count) % count

        summaryLabel.set_use_markup(True)
        summaryLabel.set_markup("<span foreground='blue'><u>%s</u></span>" % summary)

    def refresh(self):
        NormalSpoke.refresh(self)
        self._do_refresh()
        self._updateSpaceDisplay()

    def _do_refresh(self):
        # Make sure we start with a clean slate.
        self._accordion.removeAllPages()

        # Start with buttons disabled, since no filesystem is selected.
        self._removeButton.set_sensitive(False)
        self._configButton.set_sensitive(False)

        # Now it's time to populate the accordion.

        # We can only have one page expanded at a time.
        did_expand = False

        # If we've not yet run autopart, add an instance of CreateNewPage.  This
        # ensures it's only added once.
        if not self._ran_autopart:
            page = CreateNewPage(self.on_create_clicked)
            title = _("New %s %s Installation") % (productName, productVersion)
            self._accordion.addPage(title, page)
            self._accordion.expandPage(title)
            did_expand = True

            self._partitionsNotebook.set_current_page(0)
            label = self.builder.get_object("whenCreateLabel")
            label.set_text(label.get_text() % (productName, productVersion))

        # Add in all the existing (or autopart-created) operating systems.
        for root in self.storage.roots:
            page = Page()

            for swap in root.swaps:
                selector = page.addDevice("Swap", swap.size, None, self.on_selector_clicked)
                selector._device = swap
                selector._root = root

            for (mountpoint, device) in root.mounts.iteritems():
                selector = page.addDevice(self._mountpointName(mountpoint) or device.format.name, device.size, mountpoint, self.on_selector_clicked)
                selector._device = device
                selector._root = root

            page.show_all()
            self._accordion.addPage(root.name, page)

            if not did_expand and self._current_selector and root == self._current_selector._root:
                did_expand = True
                self._accordion.expandPage(root.name)

        # Anything that doesn't go with an OS we understand?  Put it in the Other box.
        unused = self._unusedDevices()
        if unused:
            page = UnknownPage()

            for u in unused:
                selector = page.addDevice(u.format.name, u.size, None, self.on_selector_clicked)
                selector._device = u
                selector._root = unused

            page.show_all()
            self._accordion.addPage(_("Unknown"), page)

            if not did_expand and self._current_selector and unused == self._current_selector._root:
                did_expand = True
                self._accordion.expandPage(_("Unknown"))

    ###
    ### RIGHT HAND SIDE METHODS
    ###

    def _description(self, name):
        if name == "Swap":
            return _("The 'swap' area on your computer is used by the operating\n" \
                     "system when running low on memory.")
        elif name == "Boot":
            return _("The 'boot' area on your computer is where files needed\n" \
                     "to start the operating system are stored.")
        elif name == "Root":
            return _("The 'root' area on your computer is where core system\n" \
                     "files and applications are stored.")
        elif name == "Home":
            return _("The 'home' area on your computer is where all your personal\n" \
                     "data is stored.")
        elif name == "BIOS Boot":
            return _("No one knows what this could possibly be for.")
        else:
            return ""

    def _save_right_side(self, selector):
        if not selector:
            return

        labelEntry = self.builder.get_object("labelEntry")

        device = selector._device

        if hasattr(device.format, "label") and labelEntry.get_text():
            device.format.label = labelEntry.get_text()

    def _populate_right_side(self, selector):
        encryptCheckbox = self.builder.get_object("encryptCheckbox")
        labelEntry = self.builder.get_object("labelEntry")
        selectedDeviceLabel = self.builder.get_object("selectedDeviceLabel")
        selectedDeviceDescLabel = self.builder.get_object("selectedDeviceDescLabel")
        sizeSpinner = self.builder.get_object("sizeSpinner")
        typeCombo = self.builder.get_object("deviceTypeCombo")
        fsCombo = self.builder.get_object("fileSystemTypeCombo")

        device = selector._device

        selectedDeviceLabel.set_text(selector.props.name)
        selectedDeviceDescLabel.set_text(self._description(selector.props.name))

        labelEntry.set_text(getattr(device.format, "label", "") or "")
        labelEntry.set_sensitive(getattr(device.format, "labelfsProg", "") != "")

        if labelEntry.get_sensitive():
            labelEntry.props.has_tooltip = False
        else:
            labelEntry.set_tooltip_text(_("This file system does not support labels."))

        sizeSpinner.set_range(device.minSize, device.maxSize)
        sizeSpinner.set_value(device.size)
        sizeSpinner.set_sensitive(device.resizable)

        if sizeSpinner.get_sensitive():
            sizeSpinner.props.has_tooltip = False
        else:
            sizeSpinner.set_tooltip_text(_("This file system may not be resized."))

        encryptCheckbox.set_active(device.encrypted)

        # FIXME:  What do we do if we can't figure it out?
        if device.type == "lvmlv":
            typeCombo.set_active(1)
        elif device.type in ["dm-raid array", "mdarray"]:
            typeCombo.set_active(2)
        elif device.type == "partition":
            typeCombo.set_active(3)

        # FIXME:  What do we do if we can't figure it out?
        model = fsCombo.get_model()
        for i in range(0, len(model)):
            if model[i][0] == device.format.name:
                fsCombo.set_active(i)
                break

        self._current_selector = selector

    ###
    ### SIGNAL HANDLERS
    ###

    def on_back_clicked(self, button):
        self.skipTo = "StorageSpoke"
        NormalSpoke.on_back_clicked(self, button)

    # Use the default back action here, since the finish button takes the user
    # to the install summary screen.
    def on_finish_clicked(self, button):
        self._save_right_side(self._current_selector)
        NormalSpoke.on_back_clicked(self, button)

    def on_add_clicked(self, button):
        dialog = AddDialog(self.data)
        with enlightbox(self.window, dialog.window):
            dialog.refresh()
            rc = dialog.run()

            if rc == 1:
                # FIXME:  Do creation.
                pass

    def _remove_from_ui(self, root, device, cb):
        if device in root.swaps:
            root.swaps.remove(device)
        elif hasattr(device.format, "mountpoint") and device.format.mountpoint in root.mounts:
            root.mounts.pop(device.format.mountpoint)
        else:
            # Can this ever happen?
            return

        # Now that it's removed from the installation root, refreshing the
        # display will have the effect of making it disappear.  It's like
        # it never existed.
        self._do_refresh()

        # Make sure there's something displayed on the RHS.  Just default to
        # the first mountpoint in the page.
        page = self._accordion.currentPage()
        if not page or not page._members:
            return

        self._populate_right_side(page._members[0])

        # Finally, do the remove actions.  This has to come after updating the
        # display or device.format.mountpoint will disappear and the code at the
        # top of this method won't work.
        cb(device)
        self._updateSpaceDisplay()

    def _remove_existing_cb(self, device):
        self.storage.devicetree.registerAction(ActionDestroyFormat(device))
        self.storage.devicetree.registerAction(ActionDestroyDevice(device))

    def _remove_created_cb(self, device):
        actions = self.storage.devicetree.findActions(device=device)
        map(self.storage.devicetree.cancelAction, reversed(actions))

    def on_remove_clicked(self, button):
        from pyanaconda.storage.deviceaction import ActionDestroyFormat, ActionDestroyDevice

        if not self._current_selector:
            return

        device = self._current_selector._device
        if device.exists:
            # This is a device that exists on disk and most likely has data
            # on it.  Thus, we first need to confirm with the user and then
            # schedule actions to delete the thing.
            dialog = ConfirmDeleteDialog(self.data)
            with enlightbox(self.window, dialog.window):
                dialog.refresh(getattr(device.format, "mountpoint", None), device.name)
                rc = dialog.run()

                if rc == 1:
                    self._remove_from_ui(self._current_selector._root, device,
                                         self._remove_existing_cb)
        else:
            # This is a device we just created during custom partitioning so
            # it's never existed on disk and there's no data on it.  Thus, we
            # don't need to ask before deleting.  Remove it from the UI first
            # and then cancel the actions that would create it.
            self._remove_from_ui(self._current_selector._root, device,
                                 self._remove_created_cb)

    def on_summary_clicked(self, button):
        dialog = SelectedDisksDialog(self.data)

        with enlightbox(self.window, dialog.window):
            dialog.refresh(self._clearpartDevices(), showRemove=False)
            dialog.run()

    def on_configure_clicked(self, button):
        pass

    def on_selector_clicked(self, selector):
        # Make sure we're showing details instead of the "here's how you create
        # a new OS" label.
        self._partitionsNotebook.set_current_page(1)

        self._save_right_side(self._current_selector)
        self._populate_right_side(selector)

        self._removeButton.set_sensitive(True)
        self._configButton.set_sensitive(True)

    def on_create_clicked(self, button):
        from pyanaconda.storage import Root
        from pyanaconda.storage.devices import DiskDevice
        from pyanaconda.storage.partitioning import doAutoPartition

        # Pick the first disk to be the destination device for the bootloader.
        # This appears to be the minimum amount of configuration required to
        # make autopart happy with the bootloader settings.
        if not self.data.bootloader.bootDrive:
            self.data.bootloader.bootDrive = self.storage.bootloader.disks[0].name

        # Then do autopartitioning.  We do not do any clearpart first.  This is
        # custom partitioning, so you have to make your own room.
        # FIXME:  Handle all the autopart exns here.
        self.data.autopart.autopart = True
        self.data.autopart.execute(self.storage, self.data, self.instclass)

        # Create a new Root object for the new installation and put it into
        # the storage object.  This means any boot-related devices we make for
        # this new install (biosboot, etc.) will show up as unused and therefore
        # be put into the Unknown page.
        mounts = {}
        swaps = []

        # Devices just created by autopartitioning will be listed as unused
        # since they are not yet a part of any known Root.
        for device in self._unusedDevices():
            if device.format.type == "swap":
                swaps.append(device)

            if hasattr(device.format, "mountpoint"):
                mounts[device.format.mountpoint] = device

        newName = _("New %s %s Installation") % (productName, productVersion)
        root = Root(mounts=mounts, swaps=swaps, name=newName)
        self.storage.roots.append(root)

        # Setting this ensures the CreateNewPage instance does not reappear when
        # refresh is called.
        self._ran_autopart = True

        # And refresh the spoke to make the new partitions appear.
        self.refresh()
        self._accordion.expandPage(newName)