Exemplo n.º 1
0
    def _build_filesystem_list(self):
        log.debug('FileSystemView: building part list')
        cols = []
        longest_path = len("MOUNT POINT")
        for m in sorted(self.model._mounts, key=lambda m:m.path):
            path = m.path
            longest_path = max(longest_path, len(path))
            for p, *_ in reversed(cols):
                if path.startswith(p):
                    path = [('info_minor', p), path[len(p):]]
                    break
            cols.append((m.path, path, humanize_size(m.device.volume.size), m.device.fstype, m.device.volume.desc()))
        for fs in self.model._filesystems:
            if fs.fstype == 'swap':
                cols.append((None, 'SWAP', humanize_size(fs.volume.size), fs.fstype, fs.volume.desc()))

        if len(cols) == 0:
            return Pile([Color.info_minor(
                Text("No disks or partitions mounted."))])
        cols.insert(0, (None, "MOUNT POINT", "SIZE", "TYPE", "DEVICE TYPE"))
        pl = []
        for _, a, b, c, d in cols:
            if b == "SIZE":
                b = Text(b, align='center')
            else:
                b = Text(b, align='right')
            pl.append(Columns([(longest_path, Text(a)), (9, b), (self.model.longest_fs_name, Text(c)), Text(d)], 4))
        return Pile(pl)
Exemplo n.º 2
0
def verify_size_ok(level, sizes):
    r = False
    try:
        devs = create_devices_for_sizes(sizes)
        raid = create_raid(level, devs)
        devs = [FakeDev(size) for size in sizes]
        calc_size = get_raid_size(level, devs)
        real_size = get_real_raid_size(raid)
        if len(set(sizes)) == 1:
            sz = '[{}]*{}'.format(humanize_size(sizes[0]), len(sizes))
        else:
            sz = str([humanize_size(s) for s in sizes])
        print("level {} sizes {} -> calc_size {} real_size {}".format(
            level, sz, calc_size, real_size),
              end=' ')
        if calc_size > real_size:
            print("BAAAAAAAAAAAD", real_size - calc_size)
            if os.environ.get('DEBUG'):
                print(raid)
                input('waiting: ')
        elif calc_size == real_size:
            print("exactly right!")
            r = True
        else:
            print("subiquity wasted space", real_size - calc_size)
            r = True
    finally:
        cleanup()
    return r
Exemplo n.º 3
0
 def lost_focus(self):
     val = self.value
     if not val:
         return
     suffixes = ''.join(HUMAN_UNITS) + ''.join(HUMAN_UNITS).lower()
     if val[-1] not in suffixes:
         unit = self.form.size_str[-1]
         val += unit
         self.value = val
     try:
         sz = self.form.size.value
     except ValueError:
         return
     if sz > self.form.max_size:
         self.value = self.form.size_str
         self.form.size.show_extra(
             ('info_minor', _("Capped partition size at {size}").format(
                 size=self.form.size_str)))
     elif (align_up(sz) != sz
           and humanize_size(align_up(sz)) != self.form.size.value):
         sz_str = humanize_size(align_up(sz))
         self.value = sz_str
         self.form.size.show_extra(
             ('info_minor',
              _("Rounded size up to {size}").format(size=sz_str)))
Exemplo n.º 4
0
def summarize_device(device, part_filter=lambda p: True):
    """Return content for a table summarizing device.

    This (obj, cells) where obj is either device itself, a partition of
    device or None and cells is part of an argument to TableRow that
    will span 4 columns that describes device or a partition of
    device. This sounds a bit strange but hopefully you can figure it
    out by looking at the uses of this function.
    """
    label = labels.label(device)
    anns = labels.annotations(device)
    if anns:
        label = "{} ({})".format(label, ", ".join(anns))
    rows = [(device, [
        (2, Text(label)),
        Text(labels.desc(device)),
        Text(humanize_size(device.size), align="right"),
    ])]
    partitions = device.partitions()
    if partitions:
        for part in device.partitions():
            if not part_filter(part):
                continue
            details = ", ".join(
                labels.annotations(part) + labels.usage_labels(part))
            rows.append((part, [
                Text(labels.label(part, short=True)),
                (2, Text(details)),
                Text(humanize_size(part.size), align="right"),
            ]))
    else:
        rows.append((None, [
            (4, Color.info_minor(Text(", ".join(labels.usage_labels(device)))))
        ]))
    return rows
Exemplo n.º 5
0
    def __init__(self, parent, snap, cur_channel):
        self.parent = parent
        self.snap = snap
        self.channels = []
        self.needs_focus = True

        channel_width = (max(len(csi.channel_name) for csi in snap.channels) +
                         StarRadioButton.reserve_columns + 1)
        max_version = max(len(csi.version) for csi in snap.channels)
        max_revision = max(len(str(csi.revision)) for csi in snap.channels) + 2
        max_size = max(len(humanize_size(csi.size)) for csi in snap.channels)

        self.description = Text(snap.description.replace('\r', '').strip())
        self.lb_description = ListBox([self.description])

        radio_group = []
        for csi in snap.channels:
            notes = '-'
            if csi.confinement != "strict":
                notes = csi.confinement
            btn = StarRadioButton(radio_group,
                                  "{}:".format(csi.channel_name),
                                  state=csi.channel_name == cur_channel,
                                  on_state_change=self.state_change,
                                  user_data=SnapSelection(
                                      channel=csi.channel_name,
                                      is_classic=csi.confinement == "classic"))
            self.channels.append(
                Color.menu_button(
                    Columns([
                        (channel_width, btn),
                        (max_version, Text(csi.version)),
                        (max_revision, Text("({})".format(csi.revision))),
                        (max_size, Text(humanize_size(csi.size))),
                        ('pack', Text(notes)),
                    ],
                            dividechars=1)))

        self.lb_channels = NoTabCyclingListBox(self.channels)

        title = Columns([
            Text(snap.name),
            ('pack',
             Text(_("Publisher: {}").format(snap.publisher), align='right')),
        ],
                        dividechars=1)

        contents = [
            ('pack', title),
            ('pack', Text("")),
            ('pack', Text(snap.summary)),
            ('pack', Text("")),
            self.lb_description,  # overwritten in render()
            ('pack', Text("")),
            ('weight', 1, self.lb_channels),
        ]
        self.description_index = contents.index(self.lb_description)
        self.pile = Pile(contents)
        super().__init__(self.pile)
Exemplo n.º 6
0
    def __init__(self, model, controller, disk, partition=None):
        log.debug('PartitionView: selected_disk=[{}]'.format(disk.path))
        self.model = model
        self.controller = controller
        self.disk = disk
        self.partition = partition

        max_size = disk.free
        if partition is None:
            initial = {'partnum': disk.next_partnum}
            label = _("Create")
        else:
            max_size += partition.size
            initial = {
                'partnum': partition.number,
                'size': humanize_size(partition.size),
            }
            label = _("Save")
        super().__init__(max_size, partition, initial,
                         lambda: self.controller.partition_disk(disk))
        self.form.buttons.base_widget[0].set_label(label)
        if partition is not None and partition.flag == "boot":
            opts = [Option(("fat32", True, self.model.fs_by_name["fat32"]))]
            self.form.fstype.widget._options = opts
            self.form.fstype.widget.index = 0
            self.form.mount.enabled = False
            self.form.fstype.enabled = False
Exemplo n.º 7
0
 def __init__(self, model, max_size, initial, lvm_names, device):
     self.model = model
     self.device = device
     self.existing_fs_type = None
     if device:
         ofstype = device.original_fstype()
         if ofstype:
             self.existing_fs_type = ofstype
     initial_path = initial.get('mount')
     self.mountpoints = {
         m.path: m.device.volume
         for m in self.model.all_mounts() if m.path != initial_path
     }
     self.max_size = max_size
     if max_size is not None:
         self.size_str = humanize_size(max_size)
         self.size.caption = _("Size (max {size}):").format(
             size=self.size_str)
     self.lvm_names = lvm_names
     super().__init__(initial)
     if max_size is None:
         self.remove_field('size')
     connect_signal(self.fstype.widget, 'select', self.select_fstype)
     self.form_pile = None
     self.select_fstype(None, self.fstype.widget.value)
Exemplo n.º 8
0
    def _build_disk_selection(self):
        log.debug('lvm: _build_disk_selection')
        items = [Text("DISK SELECTION")]

        # lvm can use empty whole disks, or empty partitions
        avail_disks = self.model.get_empty_disk_names()
        avail_parts = self.model.get_empty_partition_names()
        avail_devs = sorted(avail_disks + avail_parts)
        if len(avail_devs) == 0:
            return items.append(
                [Color.info_minor(Text("No available disks."))])

        for dname in avail_devs:
            device = self.model.get_disk(dname)
            if device.path != dname:
                # we've got a partition
                lvmdev = device.get_partition(dname)
            else:
                lvmdev = device

            disk_sz = humanize_size(lvmdev.size)
            disk_string = "{}     {},     {}".format(dname, disk_sz,
                                                     device.model)
            log.debug('lvm: disk_string={}'.format(disk_string))
            self.selected_disks.append(CheckBox(disk_string))

        items += self.selected_disks

        return Pile(items)
Exemplo n.º 9
0
 def __init__(self, model, controller):
     self.model = model
     self.controller = controller
     cancel = cancel_btn(_("Cancel"), on_press=self.cancel)
     disks = []
     for disk in self.model.all_disks():
         label = "%-42s %s" % (disk.label, humanize_size(
             disk.size).rjust(9))
         if disk.size >= model.lower_size_limit:
             disk_btn = forward_btn(label,
                                    on_press=self.choose_disk,
                                    user_arg=disk)
         else:
             disk_btn = Color.info_minor(Text("  " + label))
         disks.append(disk_btn)
     body = Pile([
         ('pack', Text("")),
         ('pack',
          Padding.center_70(Text(_("Choose the disk to install to:")))),
         ('pack', Text("")),
         Padding.center_70(ListBox(disks)),
         ('pack', Text("")),
         ('pack', button_pile([cancel])),
         ('pack', Text("")),
     ])
     super().__init__(body)
Exemplo n.º 10
0
 def __init__(self, model, controller, method):
     self.model = model
     self.controller = controller
     self.method = method
     cancel = cancel_btn(_("Cancel"), on_press=self.cancel)
     rows = []
     for disk in self.model.all_disks():
         if disk.size >= dehumanize_size("6G"):
             disk_btn = ClickableIcon(disk.label)
             connect_signal(
                 disk_btn, 'click', self.choose_disk, disk)
             attr = Color.done_button
         else:
             disk_btn = Text("  "+disk.label)
             attr = Color.info_minor
         rows.append(attr(TableRow([
             Text('['),
             disk_btn,
             Text(humanize_size(disk.size), align='right'),
             Text('\N{BLACK RIGHT-POINTING SMALL TRIANGLE}'),
             Text(']'),
             ])))
     super().__init__(screen(
         TableListBox(rows, spacing=1, colspecs={
             1: ColSpec(can_shrink=True, min_width=20, rpad=2),
             2: ColSpec(min_width=9),
             }),
         button_pile([cancel]),
         focus_buttons=False,
         excerpt=(
             excerpts[method]
             + "\n\n"
             + _("Choose the disk to install to:"))))
Exemplo n.º 11
0
    def _get_available_devs(self, section):
        devs = []

        # bcache can use empty whole disks, or empty partitions
        avail_disks = self.model.get_empty_disk_names()
        avail_parts = self.model.get_empty_partition_names()
        input_disks = avail_disks + avail_parts
        if section == 'CACHE':
            input_disks += self.model.get_bcache_cachedevs()

        # filter out:
        #  currently selected cache or backing disk
        #  any bcache devices
        bcache_names = list(self.model.bcache_devices.keys())
        selected_disks = [self.backing_disk, self.cache_disk]
        filter_disks = bcache_names + selected_disks

        avail_devs = sorted(
            [dev for dev in input_disks if dev not in filter_disks])

        for dname in avail_devs:
            device = self.model.get_disk(dname)
            if device.path != dname:
                # we've got a partition
                bcachedev = device.get_partition(dname)
            else:
                bcachedev = device

            disk_sz = humanize_size(bcachedev.size)
            disk_string = "{}     {},     {}".format(dname, disk_sz,
                                                     device.model)
            log.debug('bcache: disk_string={}'.format(disk_string))
            devs.append(disk_string)

        return devs
Exemplo n.º 12
0
 def set_bound_form_field(self, bff):
     super().set_bound_form_field(bff)
     self.all_rows = []
     for kind, device in bff.form.all_devices:
         if kind == LABEL:
             self.all_rows.append(TableRow([
                 Text("    " + device.label),
                 Text(humanize_size(device.size), align='right')
             ]))
             self.no_selector_rows.append(self.all_rows[-1])
             self.all_rows.append(TableRow([
                 (2, Color.info_minor(Text("      " + device.desc())))
             ]))
             self.no_selector_rows.append(self.all_rows[-1])
         else:
             if kind == DEVICE:
                 label = device.label
                 prefix = "    "
             elif kind == PART:
                 label = _("  partition {}").format(device._number)
                 prefix = "      "
             else:
                 raise Exception("unexpected kind {}".format(kind))
             box = CheckBox(
                 label,
                 on_state_change=self._state_change_device,
                 user_data=device)
             self.device_to_checkbox[device] = box
             size = Text(humanize_size(device.size), align='right')
             self.all_rows.append(Color.menu_button(TableRow([box, size])))
             self.no_selector_rows.append(self.all_rows[-1])
             selector = Selector(['active', 'spare'])
             connect_signal(
                 selector, 'select', self._select_active_spare, device)
             selector = Toggleable(
                 UrwidPadding(
                     Color.menu_button(selector),
                     left=len(prefix)))
             selector.disable()
             self.device_to_selector[device] = selector
             self.all_rows.append(TableRow([(2, selector)]))
             # Do not append that one to no_selector_rows!
             self.all_rows.append(self._summarize(prefix, device))
             self.no_selector_rows.append(self.all_rows[-1])
     self.table.set_contents(self.all_rows)
     log.debug("%s", self.table._w.focus_position)
Exemplo n.º 13
0
    def refresh_model_inputs(self):
        devices = [
            d for d in self.parent.model.all_devices()
            if (d.available() == self.show_available or (
                not self.show_available and d.has_unavailable_partition()))
        ]
        if len(devices) == 0:
            self._w = Padding.push_2(self._no_devices_content)
            self.table.table_rows = []
            return
        self._w = self.table
        log.debug('FileSystemView: building device list')
        rows = []

        rows.append(
            Color.info_minor(
                TableRow([
                    Text(""),
                    (2, Text(_("DEVICE"))),
                    Text(_("TYPE")),
                    Text(_("SIZE"), align="center"),
                    Text(""),
                    Text(""),
                ])))
        for device in devices:
            for obj, cells in summarize_device(
                    device,
                    lambda part: part.available() == self.show_available):
                if obj is not None:
                    menu = self._action_menu_for_device(obj)
                else:
                    menu = Text("")
                if obj is device:
                    start, end = '[', ']'
                else:
                    start, end = '', ''
                cells = [Text(start)] + cells + [menu, Text(end)]
                if obj is not None:
                    rows.append(make_action_menu_row(cells, menu))
                else:
                    rows.append(TableRow(cells))
            if (self.show_available and device.used > 0
                    and device.free_for_partitions > 0):
                free = humanize_size(device.free_for_partitions)
                rows.append(
                    TableRow([
                        Text(""),
                        (3, Color.info_minor(Text(_("free space")))),
                        Text(free, align="right"),
                        Text(""),
                        Text(""),
                    ]))
            rows.append(TableRow([Text("")]))
        self.table.set_contents(rows[:-1])
        if self.table._w.focus_position >= len(rows):
            self.table._w.focus_position = len(rows) - 1
        while not self.table._w.focus.selectable():
            self.table._w.focus_position -= 1
Exemplo n.º 14
0
    def _build_model_inputs(self):
        partitioned_disks = []

        def format_volume(label, part):
            size = humanize_size(part.size)
            if part.fs() is None:
                fstype = '-'
                mountpoint = '-'
            elif part.fs().mount() is None:
                fstype = part.fs().fstype
                mountpoint = '-'
            else:
                fstype = part.fs().fstype
                mountpoint = part.fs().mount().path
            if part.type == 'disk':
                part_btn = menu_btn(label, on_press=self._click_disk)
            else:
                part_btn = menu_btn(label,
                                    on_press=self._click_part,
                                    user_arg=part)
            return Columns([
                (25, part_btn),
                (9, Text(size, align="right")),
                Text(fstype),
                Text(mountpoint),
            ], 2)

        if self.disk.fs() is not None:
            partitioned_disks.append(format_volume("entire disk", self.disk))
        else:
            for part in self.disk.partitions():
                partitioned_disks.append(
                    format_volume("Partition {}".format(part.number), part))
        if self.disk.free > 0:
            free_space = humanize_size(self.disk.free)
            if len(self.disk.partitions()) > 0:
                label = "Add another partition"
            else:
                label = "Add first partition"
            add_btn = menu_btn(label, on_press=self.add_partition)
            partitioned_disks.append(
                Columns([
                    (25, add_btn),
                    (9, Text(free_space, align="right")),
                    Text("free space"),
                ], 2))
        if len(self.disk.partitions()) == 0 and \
           self.disk.available:
            text = ("Format or create swap on entire "
                    "device (unusual, advanced)")
            partitioned_disks.append(Text(""))
            partitioned_disks.append(
                menu_btn(label=text, on_press=self.format_entire))

        return partitioned_disks
Exemplo n.º 15
0
 def __init__(self, mountpoint_to_devpath_mapping, max_size, initial={}):
     self.mountpoint_to_devpath_mapping = mountpoint_to_devpath_mapping
     self.max_size = max_size
     if max_size is not None:
         self.size_str = humanize_size(max_size)
         self.size.caption = _("Size (max {})").format(self.size_str)
     super().__init__(initial)
     if max_size is None:
         self.remove_field('size')
     connect_signal(self.fstype.widget, 'select', self.select_fstype)
     self.select_fstype(None, self.fstype.widget.value)
Exemplo n.º 16
0
def summarize_device(disk):
    label = disk.label
    rows = [(disk, [
        (2, Text(label)),
        Text(disk.type),
        Text(humanize_size(disk.size), align="right"),
    ])]
    if disk.partitions:
        for part in disk.partitions:
            details = ", ".join(part.annotations)
            rows.append((part, [
                Text(_("partition {number}").format(number=part.number)),
                (2, Text(details)),
                Text(humanize_size(part.size), align="right"),
            ]))
    else:
        rows.append((None, [
            (4, Color.info_minor(Text(", ".join(disk.usage_labels))))
        ]))
    return rows
Exemplo n.º 17
0
 def _select_level(self, sender, new_level):
     active_device_count = len(self.form.devices.widget.active_devices)
     if active_device_count >= new_level.min_devices:
         self.form.size.value = humanize_size(
             get_raid_size(new_level.value, self.form.devices.value))
     else:
         self.form.size.value = '-'
     self.form.devices.widget.set_supports_spares(new_level.supports_spares)
     self.form.level.value = new_level
     self.form.devices.showing_extra = False
     self.form.devices.validate()
Exemplo n.º 18
0
    def show_disk_information(self, disk):
        """ Show disk information, requires sudo/root
        """
        bus = disk._info.raw.get('ID_BUS', None)
        major = disk._info.raw.get('MAJOR', None)
        if bus is None and major == '253':
            bus = 'virtio'

        devpath = disk._info.raw.get('DEVPATH', disk.path)
        rotational = '1'
        try:
            dev = os.path.basename(devpath)
            rfile = '/sys/class/block/{}/queue/rotational'.format(dev)
            rotational = open(rfile, 'r').read().strip()
        except (PermissionError, FileNotFoundError, IOError):
            log.exception('WARNING: Failed to read file {}'.format(rfile))
            pass

        dinfo = {
            'bus': bus,
            'devname': disk.path,
            'devpath': devpath,
            'model': disk.model,
            'serial': disk.serial,
            'size': disk.size,
            'humansize': humanize_size(disk.size),
            'vendor': disk._info.vendor,
            'rotational': 'true' if rotational == '1' else 'false',
        }
        if dinfo['serial'] is None:
            dinfo['serial'] = 'unknown'
        if dinfo['model'] is None:
            dinfo['model'] = 'unknown'
        if dinfo['vendor'] is None:
            dinfo['vendor'] = 'unknown'

        template = """\n
{devname}:\n
 Vendor: {vendor}
 Model: {model}
 SerialNo: {serial}
 Size: {humansize} ({size}B)
 Bus: {bus}
 Rotational: {rotational}
 Path: {devpath}
"""
        result = template.format(**dinfo)
        log.debug('calling DiskInfoView()')
        disk_info_view = DiskInfoView(self.model, self, disk, result)
        footer = _('Select next or previous disks with n and p')
        self.ui.set_footer(footer)
        self.ui.set_body(disk_info_view)
Exemplo n.º 19
0
 def __init__(self, mountpoints, max_size, initial, ok_for_slash_boot,
              lvm_names):
     self.mountpoints = mountpoints
     self.ok_for_slash_boot = ok_for_slash_boot
     self.max_size = max_size
     if max_size is not None:
         self.size_str = humanize_size(max_size)
         self.size.caption = _("Size (max {}):").format(self.size_str)
     self.lvm_names = lvm_names
     super().__init__(initial)
     if max_size is None:
         self.remove_field('size')
     connect_signal(self.fstype.widget, 'select', self.select_fstype)
     self.select_fstype(None, self.fstype.widget.value)
Exemplo n.º 20
0
    def __init__(self, model, controller, disk, partition=None):
        log.debug('PartitionView: selected_disk=[{}]'.format(disk.path))
        self.model = model
        self.controller = controller
        self.disk = disk
        self.partition = partition
        self.title = _("Partition, format, and mount {}").format(disk.label)

        max_size = disk.free
        initial = {}
        if partition is None:
            label = _("Create")
            self.footer = _("Enter partition details, format and mount.")
        else:
            max_size += partition.size
            initial['size'] = humanize_size(partition.size)
            if partition.flag == "bios_grub":
                label = None
                initial['mount'] = None
            else:
                self.footer = _("Edit partition details, format and mount.")
                label = _("Save")
        super().__init__(max_size,
                         partition,
                         initial,
                         lambda: self.controller.partition_disk(disk),
                         focus_buttons=label is None)
        if label is not None:
            self.form.buttons.base_widget[0].set_label(label)
        else:
            del self.form.buttons.base_widget.contents[0]
            self.form.buttons.base_widget[0].set_label(_("OK"))
        if partition is not None:
            if partition.flag == "boot":
                opts = [
                    Option(("fat32", True, self.model.fs_by_name["fat32"]))
                ]
                self.form.fstype.widget._options = opts
                self.form.fstype.widget.index = 0
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
            elif partition.flag == "bios_grub":
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
                self.form.size.enabled = False
Exemplo n.º 21
0
 def __init__(self, model, controller):
     self.model = model
     self.controller = controller
     cancel = cancel_btn("Cancel", on_press=self.cancel)
     disks = []
     for disk in self.model.all_disks():
         disk_btn = forward_btn(
             "%-40s %s" % (disk.serial, humanize_size(disk.size).rjust(9)),
             on_press=self.choose_disk,
             user_arg=disk)
         disks.append(disk_btn)
     lb = ListBox([
         Padding.center_70(Text("")),
         Padding.center_70(Text(_("Choose the disk to install to:"))),
         Padding.center_70(Text("")),
         Padding.center_70(Pile(disks)),
         Padding.center_70(Text("")),
         button_pile([cancel]),
     ])
     super().__init__(lb)
Exemplo n.º 22
0
 def format_volume(label, part):
     size = humanize_size(part.size)
     if part.fs() is None:
          fstype = '-'
          mountpoint = '-'
     elif part.fs().mount() is None:
         fstype = part.fs().fstype
         mountpoint = '-'
     else:
         fstype = part.fs().fstype
         mountpoint = part.fs().mount().path
     if part.type == 'disk':
         part_btn = menu_btn(label, on_press=self._click_disk)
     else:
         part_btn = menu_btn(label, on_press=self._click_part, user_arg=part)
     return Columns([
         (label_width, part_btn),
         (9, Text(size, align="right")),
         Text(fstype),
         Text(mountpoint),
     ], 2)
Exemplo n.º 23
0
 def _change_devices(self, sender, new_devices):
     if len(sender.active_devices) >= self.form.level.value.min_devices:
         self.form.size.value = humanize_size(
             get_raid_size(self.form.level.value.value, new_devices))
     else:
         self.form.size.value = '-'
Exemplo n.º 24
0
    def refresh_model_inputs(self):
        devices = [
            d for d in self.parent.model.all_devices()
            if (d.available() == self.show_available or (
                not self.show_available and d.has_unavailable_partition()))
        ]
        if len(devices) == 0:
            self._w = self._no_devices_content
            self.table.table_rows = []
            return
        self._w = self.table
        log.debug('FileSystemView: building device list')
        rows = []

        def _fmt_fs(label, fs):
            r = _("{} {}").format(label, fs.fstype)
            if not self.parent.model.fs_by_name[fs.fstype].is_mounted:
                return r
            m = fs.mount()
            if m:
                r += _(", {}").format(m.path)
            else:
                r += _(", not mounted")
            return r

        def _fmt_constructed(label, device):
            return _("{} part of {} ({})").format(label, device.label,
                                                  device.desc())

        rows.append(
            TableRow([
                Text(_("DEVICE")),
                Text(_("SIZE"), align="center"),
                Text(_("TYPE")),
            ]))
        for device in devices:
            menu = self._action_menu_for_device(device)
            row = TableRow([
                Text(device.label),
                Text("{:>9}".format(humanize_size(device.size))),
                Text(device.desc()),
                menu,
            ])
            row = add_menu_row_focus_behaviour(menu, row, 'menu_button',
                                               'menu_button focus')
            rows.append(row)

            entire_label = None
            if device.fs():
                entire_label = _fmt_fs(_("  entire device formatted as"),
                                       device.fs())
            elif device.constructed_device():
                entire_label = _fmt_constructed(_("  entire device"),
                                                device.constructed_device())
            if entire_label is not None:
                rows.append(TableRow([
                    Text(entire_label),
                ]))
            else:
                for part in device.partitions():
                    if part.available() != self.show_available:
                        continue
                    prefix = _("  partition {},").format(part._number)
                    if part.flag == "bios_grub":
                        label = prefix + " bios_grub"
                    elif part.fs():
                        label = _fmt_fs(prefix, part.fs())
                    elif part.constructed_device():
                        label = _fmt_constructed(prefix,
                                                 part.constructed_device())
                    else:
                        label = _("{} not formatted").format(prefix)
                    part_size = "{:>9} ({}%)".format(
                        humanize_size(part.size),
                        int(100 * part.size / device.size))
                    menu = self._action_menu_for_device(part)
                    row = TableRow([
                        Text(label),
                        (2, Text(part_size)),
                        menu,
                    ])
                    row = add_menu_row_focus_behaviour(menu,
                                                       row,
                                                       'menu_button',
                                                       'menu_button focus',
                                                       cursor_x=2)
                    rows.append(row)
                if self.show_available and 0 < device.used < device.size:
                    size = device.size
                    free = device.free_for_partitions
                    percent = str(int(100 * free / size))
                    if percent == "0":
                        percent = "%.2f" % (100 * free / size, )
                    size_text = "{:>9} ({}%)".format(humanize_size(free),
                                                     percent)
                    rows.append(
                        TableRow(
                            [Text(_("  free space")), (2, Text(size_text))]))
        self.table.set_contents(rows)
        if self.table._w.focus_position >= len(rows):
            self.table._w.focus_position = len(rows) - 1
        while not self.table._w.focus.selectable():
            self.table._w.focus_position -= 1
Exemplo n.º 25
0
 def size(self):
     return humanize_size(self.mount.device.volume.size)
Exemplo n.º 26
0
 def _change_devices(self, sender, new_devices):
     if len(sender.active_devices) >= 1:
         self.form.size.value = humanize_size(get_lvm_size(new_devices))
     else:
         self.form.size.value = '-'
Exemplo n.º 27
0
 def test_basics(self):
     for string, integer in self.basics:
         with self.subTest(input=string):
             self.assertEqual(string, humanize_size(integer))
Exemplo n.º 28
0
    def __init__(self, parent, disk, partition=None):

        self.disk = disk
        self.partition = partition
        self.model = parent.model
        self.controller = parent.controller
        self.parent = parent
        max_size = disk.free_for_partitions
        mountpoints = {
            m.path: m.device.volume for m in self.model.all_mounts()}

        initial = {}
        label = _("Create")
        if isinstance(disk, LVM_VolGroup):
            lvm_names = {p.name for p in disk.partitions()}
        else:
            lvm_names = set()
        if self.partition:
            if self.partition.flag == "bios_grub":
                label = None
                initial['mount'] = None
            else:
                label = _("Save")
            initial['size'] = humanize_size(self.partition.size)
            max_size += self.partition.size
            fs = self.partition.fs()
            if fs is not None:
                if partition.flag != "boot":
                    initial['fstype'] = self.model.fs_by_name[fs.fstype]
                mount = fs.mount()
                if mount is not None:
                    initial['mount'] = mount.path
                    del mountpoints[mount.path]
            else:
                initial['fstype'] = self.model.fs_by_name[None]
            if isinstance(disk, LVM_VolGroup):
                initial['name'] = partition.name
                lvm_names.remove(partition.name)
        elif isinstance(disk, LVM_VolGroup):
            x = 0
            while True:
                name = 'lv-{}'.format(x)
                if name not in lvm_names:
                    break
                x += 1
            initial['name'] = name

        self.form = PartitionForm(
            mountpoints, max_size, initial, isinstance(disk, Disk), lvm_names)

        if not isinstance(disk, LVM_VolGroup):
            self.form.remove_field('name')

        if label is not None:
            self.form.buttons.base_widget[0].set_label(label)
        else:
            del self.form.buttons.base_widget.contents[0]
            self.form.buttons.base_widget[0].set_label(_("OK"))

        if partition is not None:
            if partition.flag == "boot":
                opts = [
                    Option(("fat32", True, self.model.fs_by_name["fat32"])),
                ]
                self.form.fstype.widget.options = opts
                self.form.fstype.widget.index = 0
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
            elif partition.flag == "bios_grub":
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
                self.form.size.enabled = False

        connect_signal(self.form, 'submit', self.done)
        connect_signal(self.form, 'cancel', self.cancel)

        rows = []
        focus_index = 0
        if partition is not None:
            if self.partition.flag == "boot":
                rows.extend([
                    Text(_(boot_partition_description)),
                    Text(""),
                ])
            elif self.partition.flag == "bios_grub":
                rows.extend([
                    Text(_(bios_grub_partition_description)),
                    Text(""),
                ])
                focus_index = 2
        rows.extend(self.form.as_rows())
        widgets = [
            Pile(rows),
            Text(""),
            self.form.buttons,
        ]

        if partition is None:
            if isinstance(disk, LVM_VolGroup):
                add_name = _("logical volume")
            else:
                add_name = _("partition")
            title = _("Adding {} to {}").format(add_name, disk.label)
        else:
            if isinstance(disk, LVM_VolGroup):
                desc = _("logical volume {}").format(partition.name)
            else:
                desc = partition.short_label
            title = _("Editing {} of {}").format(desc, disk.label)

        super().__init__(title, widgets, 0, focus_index)
Exemplo n.º 29
0
    def refresh_model_inputs(self):
        devices = [
            d for d in self.parent.model.all_devices()
            if (d.available() == self.show_available
                or (not self.show_available and d.has_unavailable_partition()))
        ]
        if len(devices) == 0:
            self._w = self._no_devices_content
            self.table.table_rows = []
            return
        self._w = self.table
        log.debug('FileSystemView: building device list')
        rows = []

        def _usage_label(obj):
            cd = obj.constructed_device()
            if cd is not None:
                return _("{component_name} of {name}").format(
                    component_name=cd.component_name, name=cd.name)
            fs = obj.fs()
            if fs is not None:
                m = fs.mount()
                if m:
                    return _(
                        "formatted as {fstype}, mounted at {path}").format(
                            fstype=fs.fstype, path=m.path)
                else:
                    return _("formatted as {fstype}, not mounted").format(
                        fstype=fs.fstype)
            else:
                return _("unused")

        rows.append(TableRow([Color.info_minor(heading) for heading in [
            Text(" "),
            Text(_("DEVICE")),
            Text(_("SIZE"), align="center"),
            Text(_("TYPE")),
            Text(" "),
            Text(" "),
        ]]))
        for device in devices:
            menu = self._action_menu_for_device(device)
            cells = [
                Text("["),
                Text(device.label),
                Text("{:>9}".format(humanize_size(device.size))),
                Text(device.desc()),
                menu,
                Text("]"),
            ]
            row = make_action_menu_row(cells, menu)
            rows.append(row)

            if not device.partitions():
                rows.append(TableRow([
                    Text(""),
                    (3, Text("  " + _usage_label(device))),
                    Text(""),
                    Text(""),
                ]))
            else:
                for part in device.partitions():
                    if part.available() != self.show_available:
                        continue
                    menu = self._action_menu_for_device(part)
                    part_size = "{:>9} ({}%)".format(
                        humanize_size(part.size),
                        int(100 * part.size / device.size))
                    cells = [
                        Text("["),
                        Text("  " + part.short_label),
                        (2, Text(part_size)),
                        menu,
                        Text("]"),
                    ]
                    row = make_action_menu_row(cells, menu, cursor_x=4)
                    rows.append(row)
                    if part.flag == "bios_grub":
                        label = "bios_grub"
                    else:
                        label = _usage_label(part)
                    rows.append(TableRow([
                        Text(""),
                        (3, Text("    " + label)),
                        Text(""),
                        Text(""),
                    ]))
                if (self.show_available
                        and device.used > 0
                        and device.free_for_partitions > 0):
                    size = device.size
                    free = device.free_for_partitions
                    percent = str(int(100 * free / size))
                    if percent == "0":
                        percent = "%.2f" % (100 * free / size,)
                    size_text = "{:>9} ({}%)".format(
                        humanize_size(free), percent)
                    rows.append(TableRow([
                        Text(""),
                        Text("  " + _("free space")),
                        (2, Text(size_text)),
                        Text(""),
                        Text(""),
                    ]))
        self.table.set_contents(rows)
        if self.table._w.focus_position >= len(rows):
            self.table._w.focus_position = len(rows) - 1
        while not self.table._w.focus.selectable():
            self.table._w.focus_position -= 1
Exemplo n.º 30
0
    def __init__(self, parent, disk, partition=None):
        self.disk = disk
        self.partition = partition
        self.model = parent.model
        self.controller = parent.controller
        self.parent = parent
        max_size = disk.free_for_partitions

        initial = {}
        label = _("Create")
        if isinstance(disk, LVM_VolGroup):
            lvm_names = {p.name for p in disk.partitions()}
        else:
            lvm_names = None
        if self.partition:
            if self.partition.flag in ["bios_grub", "prep"]:
                label = None
                initial['mount'] = None
            else:
                label = _("Save")
            initial['size'] = humanize_size(self.partition.size)
            max_size += self.partition.size

            if partition.flag != "boot":
                initial.update(initial_data_for_fs(self.partition.fs()))
            else:
                if partition.fs() and partition.fs().mount():
                    initial['mount'] = '/boot/efi'
                else:
                    initial['mount'] = None
            if isinstance(disk, LVM_VolGroup):
                initial['name'] = partition.name
                lvm_names.remove(partition.name)
        else:
            initial['fstype'] = 'ext4'
            if isinstance(disk, LVM_VolGroup):
                x = 0
                while True:
                    name = 'lv-{}'.format(x)
                    if name not in lvm_names:
                        break
                    x += 1
                initial['name'] = name

        self.form = PartitionForm(
            self.model, max_size, initial, lvm_names, partition)

        if not isinstance(disk, LVM_VolGroup):
            self.form.remove_field('name')

        if label is not None:
            self.form.buttons.base_widget[0].set_label(label)
        else:
            del self.form.buttons.base_widget.contents[0]
            self.form.buttons.base_widget[0].set_label(_("OK"))

        if partition is not None:
            if partition.flag == "boot":
                if partition.original_fstype():
                    opts = [
                        Option((
                            _("Use existing fat32 filesystem"),
                            True,
                            None
                            )),
                        Option(("---", False)),
                        Option((
                                _("Reformat as fresh fat32 filesystem"),
                                True,
                                "fat32"
                            )),
                        ]
                    self.form.fstype.widget.options = opts
                    if partition.fs().preserve:
                        self.form.fstype.widget.index = 0
                    else:
                        self.form.fstype.widget.index = 2
                    self.form.mount.enabled = False
                else:
                    opts = [Option(("fat32", True))]
                    self.form.fstype.widget.options = opts
                    self.form.fstype.widget.index = 0
                    self.form.mount.enabled = False
                    self.form.fstype.enabled = False
            elif partition.flag in ["bios_grub", "prep"]:
                self.form.mount.enabled = False
                self.form.fstype.enabled = False
                self.form.size.enabled = False
            if partition.preserve:
                self.form.name.enabled = False
                self.form.size.enabled = False

        connect_signal(self.form, 'submit', self.done)
        connect_signal(self.form, 'cancel', self.cancel)

        rows = []
        focus_index = 0
        if partition is not None:
            if self.partition.flag == "boot":
                desc = boot_partition_description
                if self.partition.preserve:
                    desc += boot_partition_description_reformat
                else:
                    desc += boot_partition_description_size
                rows.extend([
                    Text(_(desc)),
                    Text(""),
                ])
            elif self.partition.flag == "bios_grub":
                rows.extend([
                    Text(_(bios_grub_partition_description)),
                    Text(""),
                ])
                focus_index = 2
            elif self.partition.flag == "prep":
                rows.extend([
                    Text(_(prep_partition_description)),
                    Text(""),
                ])
                focus_index = 2
        rows.extend(self.form.as_rows())
        self.form.form_pile = Pile(rows)
        widgets = [
            self.form.form_pile,
            Text(""),
            self.form.buttons,
        ]

        if partition is None:
            if isinstance(disk, LVM_VolGroup):
                add_name = _("logical volume")
            else:
                add_name = _("partition")
            title = _("Adding {} to {}").format(add_name, disk.label)
        else:
            if isinstance(disk, LVM_VolGroup):
                desc = _("logical volume {}").format(partition.name)
            else:
                desc = partition.short_label
            title = _("Editing {} of {}").format(desc, disk.label)

        super().__init__(title, widgets, 0, focus_index)