def __init__(self, content, default, tooltip, left_margin, source=None):
        """
        General Checkbox Field

        Args:
            content: text of the checkbox
            default: default value of the checkbox
            tooltip: the tooltip of the checkbox
            left_margin: The left margin of the Checkbox
            source: there this item is from for value reference
        """
        self.core = CheckBox(content, state=default)
        self.source = source
        self.widget = Pile([self.core, Padding(Text(tooltip), left=4)])
        super().__init__(self.widget, left=2 + left_margin - 4, right=2)
Example #2
0
 def set_bound_form_field(self, bff):
     contents = []
     for d in bff.form.candidate_netdevs:
         box = CheckBox(d.name, on_state_change=self._state_change)
         self.box_to_device[box] = d
         contents.append((box, self.pile.options('pack')))
     self.pile.contents[:] = contents
Example #3
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)
Example #4
0
    def _build_iface_selection(self):
        log.debug('bond: _build_iface_selection')
        items = [Text("INTERFACE SELECTION")]
        all_iface_names = self.model.get_all_interface_names()
        avail_ifnames = [
            iface for iface in all_iface_names
            if not self.model.iface_is_bonded(iface)
        ]
        log.debug('available for bonding: {}'.format(avail_ifnames))

        if len(avail_ifnames) == 0:
            log.debug('Nothing available...')
            return Pile([Color.info_minor(Text("No available interfaces."))])

        for ifname in avail_ifnames:
            device = self.model.get_interface(ifname)
            device_speed = self.model.iface_get_speed(ifname)
            iface_string = "{}     {},     {}".format(device.ifname,
                                                      device.ip4, device_speed)
            log.debug('bond: iface_string={}'.format(iface_string))
            self.selected_ifaces.append(CheckBox(iface_string))

        items += self.selected_ifaces
        log.debug('iface_select: items: {}'.format(items))
        return Pile(items)
Example #5
0
    def build_widgets(self):
        title_text = Text([("body", self.name)],
                          align="center")

        desc_text = Text(["\n", strip_solo_dots(self.description)])

        self.reset_button = PlainButton("Reset to Default", self.do_reset)
        if self.optype == OptionType.BOOLEAN:
            self.control = CheckBox(self.name, state=bool(self.current_value))

        elif self.optype == OptionType.INT:
            self.control = IntEdit(caption="{}: ".format(self.name),
                                   default=self.current_value)
        elif self.optype == OptionType.STRING:
            edit_text = self.current_value or ""
            self.control = StringEditor(
                caption="{}: ".format(self.name),
                edit_text=edit_text)
        else:
            raise Exception("Unknown option type")

        if self.optype == OptionType.STRING:
            connect_signal(self.control._edit, 'change',
                           self.handle_value_changed)
        else:
            connect_signal(self.control, 'change',
                           self.handle_value_changed)

        button_grid = GridFlow([self.reset_button],
                               36, 1, 0, 'right')

        return Pile([Divider(), title_text, desc_text, self.control,
                     button_grid])
Example #6
0
 def get_widget(self):
     if isinstance(self.value, str):
         return AttrMap(Edit('', self.value), 'editable')
     elif isinstance(self.value, bool):
         return CheckBox('', self.value)
     else:
         return Text("Unknown field for {}".format(str(type(self.value))))
Example #7
0
    def __init__(self,
                 height,
                 directory=".",
                 file="",
                 attr=(None, None),
                 show_hidden=False):
        """
        height -- height of the directory list and the file list
        directory, file -- default selection
        attr -- (inner selectable widgets, selected widgets)
        show_hidden -- If True, hidden files are shown by default.
        """

        self.directory = abspath(directory)
        self.file = ""
        self.attr = attr
        self.height = height
        self.show_hidden = show_hidden

        # Create dummy widgets for directory and file display:
        self.dir_widget = AttrWrap(
            BoxAdapter(ListBox([self._blank]), self.height), self.attr[0])
        self.file_widget = AttrWrap(
            BoxAdapter(ListBox([self._blank]), self.height), self.attr[0])

        columns = Columns([self.dir_widget, self.file_widget], 1)

        # Selection widget:
        self.select_widget = AttrWrap(Edit("", ""), self.attr[0], self.attr[1])

        # Buttons and checkbox:
        button_widgets = [
            AttrWrap(Button(button, self._action), attr[0], attr[1])
            for button in ["OK", "Cancel"]
        ]
        button_grid = GridFlow(button_widgets, 12, 2, 1, 'center')

        button_cols = Columns([
            CheckBox(self.SHOW_HIDDEN_TEXT, self.show_hidden, False,
                     self._toggle_hidden), button_grid
        ])

        self.outer_widget = Pile([
            columns, self._blank,
            Text(self.SELECTION_TEXT), self.select_widget, self._blank,
            button_cols
        ])

        self.update_widgets()

        WidgetWrap.__init__(self, self.outer_widget)
Example #8
0
    def __init__(self, underlying, juju_state, on_success, on_cancel):
        import cloudinstall.charms
        charm_modules = [import_module('cloudinstall.charms.' + mname)
                         for (_, mname, _) in
                         pkgutil.iter_modules(cloudinstall.charms.__path__)]
        charm_classes = sorted([m.__charm_class__ for m in charm_modules],
                               key=attrgetter('deploy_priority'))

        self.boxes = []
        first_index = 0
        for i, charm_class in enumerate(charm_classes):
            charm = charm_class(juju_state=juju_state)
            if charm.name() and not first_index:
                first_index = i
            r = CheckBox(charm.name())
            r.text_label = charm.name()
            self.boxes.append(r)
        wrapped_boxes = _wrap_focus(self.boxes)

        def ok(button):
            selected = filter(lambda r: r.get_state(), self.boxes)
            on_success([s.text_label for s in selected])

        def cancel(button):
            on_cancel()

        bs = [Button("Ok", ok), Button("Cancel", cancel)]
        wrapped_buttons = _wrap_focus(bs)
        self.buttons = Columns(wrapped_buttons)
        self.items = ListBox(wrapped_boxes)
        self.items.set_focus(first_index)
        ba = BoxAdapter(self.items, height=len(wrapped_boxes))
        self.lb = ListBox([ba, self.count_editor, self.buttons])
        root = LineBox(self.lb, title="Select new charm")
        root = AttrMap(root, "dialog")

        Overlay.__init__(self, root, underlying, 'center', 30, 'middle',
                         len(wrapped_boxes) + 4)
Example #9
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)
Example #10
0
    def build_widgets(self):
        desc_text = Text(["\n", strip_solo_dots(self.description)])

        self.reset_button = PlainButton("Reset to Default", self.do_reset)
        if self.optype == OptionType.BOOLEAN:
            self.control = CheckBox('', state=bool(self.current_value))
            self.wrapped_control = self.control
        elif self.optype == OptionType.INT:
            self.control = IntEdit(default=self.current_value)
            self.wrapped_control = Color.string_input(
                self.control, focus_map='string_input focus')
        elif self.optype == OptionType.STRING:
            edit_text = self.current_value or ""
            self.control = StringEditor(edit_text=edit_text)
            self.wrapped_control = Color.string_input(
                self.control, focus_map='string_input focus')
        elif self.optype == OptionType.FLOAT:
            edit_text = str(self.current_value)
            self.control = StringEditor(edit_text=edit_text)
            self.wrapped_control = Color.string_input(
                self.control, focus_map='string_input focus')
        else:
            raise Exception("Unknown option type")

        self.control_columns = Columns(
            [('pack', Text("{}:".format(self.name), align='right')),
             (80, self.wrapped_control)],
            dividechars=1)

        if self.optype in [OptionType.STRING, OptionType.FLOAT]:
            connect_signal(self.control._edit, 'change',
                           self.handle_value_changed)
        else:
            connect_signal(self.control, 'change', self.handle_value_changed)

        button_grid = GridFlow([
            Color.button_secondary(self.reset_button,
                                   focus_map='button_secondary focus')
        ], 36, 1, 0, 'right')

        return Pile([
            Padding.line_break(""),
            Padding.left(self.control_columns, left=1),
            Padding.left(desc_text, left=2), button_grid
        ])
Example #11
0
def parse_tag_from_node(node):
    label = node.attr.label or ''
    state = bool(node.attr.state or '')
    return CheckBox(label=label, state=state)
Example #12
0
    def __init__(self, title=None, cls=None):#{{{
        if cls is None:
            cls = type('Dummy', (object,), {'run': lambda *a: None})
        self.cls = cls

        self._desde_err = None
        self._hasta_err = None

        _edit_cancel = lambda *w: self.focus_button(1)
        _edit_ok = lambda *w: self.focus_button(0)
        def _focus_hasta(*w):
            self.content.set_focus(2)

        self.articulos = InputBox()
        self.articulos.filter_input = lambda t: t.upper()
        connect_signal(self.articulos, "edit-done", self.on_articulos_edit_done)
        connect_signal(self.articulos, "edit-cancel", _edit_cancel)

        self.desde = DateSelectorBox(out_fmt="%d/%m/%Y")
        err = ('desde_error', '_desde_err')
        connect_signal(self.desde, 'focus-in', self.on_fecha_focus_in, err)
        connect_signal(self.desde, 'focus-out', self.on_fecha_focus_out, err)
        connect_signal(self.desde, 'edit-cancel', _edit_cancel)
        connect_signal(self.desde, 'edit-done', self.on_fecha_edit_done, err+(_focus_hasta,))
        connect_signal(self.desde, 'bad-date-error', self.on_fecha_error, err)
        self.desde_error = Text("", wrap='clip')

        self.hasta = DateSelectorBox(out_fmt="%d/%m/%Y")
        err = ('hasta_error', '_hasta_err')
        connect_signal(self.hasta, 'focus-in', self.on_fecha_focus_in, err)
        connect_signal(self.hasta, 'focus-out', self.on_fecha_focus_out, err)
        connect_signal(self.hasta, 'edit-cancel', _edit_cancel)
        connect_signal(self.hasta, 'edit-done', self.on_fecha_edit_done, err+(_edit_ok,))
        connect_signal(self.hasta, 'bad-date-error', self.on_fecha_error, err)
        self.hasta_error = Text("", wrap='clip')

        articulos_row = Columns([
            ('fixed', 14, AttrMap(Text("Artículos", align='right'), 'dialog.selectdate.label')),
            AttrMap(self.articulos, 'dialog.selectdate.input', 'dialog.selectdate.input.focus'),
        ], dividechars=1)

        desde_row = Columns([
            ('fixed', 14, AttrMap(Text("Desde", align='right'), 'dialog.selectdate.label')),
            ('fixed', 11, AttrMap(self.desde, 'dialog.selectdate.input', 'dialog.selectdate.input.focus')),
            AttrMap(self.desde_error, 'dialog.selectdate.error'),
        ], dividechars=1)

        hasta_row = Columns([
            ('fixed', 14, AttrMap(Text("Hasta", align='right'), 'dialog.selectdate.label')),
            ('fixed', 11, AttrMap(self.hasta, 'dialog.selectdate.input', 'dialog.selectdate.input.focus')),
            AttrMap(self.hasta_error, 'dialog.selectdate.error'),
        ], dividechars=1)

        self.include_inactives = CheckBox(u"Incluir Desactivados", state=True)
        include_inactives_row = Columns([
            ('fixed', 14, Divider()),
            AttrMap(self.include_inactives, 'dialog.selectdate.label'),
        ], dividechars=1)

        self.content = Pile([
            articulos_row,
            desde_row,
            hasta_row,
            include_inactives_row,
            Divider(),
        ])

        t = u"Artículos y Rango de Fechas"
        if title:
            t += u" - %s" % title

        # Set initial dates
        self.desde.set_value(date(2001, 01, 01)) # FIXME: hardcoded > Principio de actividad
        self.hasta.set_value(date.today()+relativedelta(day=31)) # Fin de mes

        buttons = [("Continuar", self.run_list), ("Cancelar", self._quit)]

        Dialog.__init__(self, self.content, buttons,
                title=t,
                height=None,
                width=60,
                attr_style='dialog.selectdate',
                title_attr_style='dialog.selectdate.title')
Example #13
0
class SelectArticlesDateRange(SelectDateRange):#{{{

    def __init__(self, title=None, cls=None):#{{{
        if cls is None:
            cls = type('Dummy', (object,), {'run': lambda *a: None})
        self.cls = cls

        self._desde_err = None
        self._hasta_err = None

        _edit_cancel = lambda *w: self.focus_button(1)
        _edit_ok = lambda *w: self.focus_button(0)
        def _focus_hasta(*w):
            self.content.set_focus(2)

        self.articulos = InputBox()
        self.articulos.filter_input = lambda t: t.upper()
        connect_signal(self.articulos, "edit-done", self.on_articulos_edit_done)
        connect_signal(self.articulos, "edit-cancel", _edit_cancel)

        self.desde = DateSelectorBox(out_fmt="%d/%m/%Y")
        err = ('desde_error', '_desde_err')
        connect_signal(self.desde, 'focus-in', self.on_fecha_focus_in, err)
        connect_signal(self.desde, 'focus-out', self.on_fecha_focus_out, err)
        connect_signal(self.desde, 'edit-cancel', _edit_cancel)
        connect_signal(self.desde, 'edit-done', self.on_fecha_edit_done, err+(_focus_hasta,))
        connect_signal(self.desde, 'bad-date-error', self.on_fecha_error, err)
        self.desde_error = Text("", wrap='clip')

        self.hasta = DateSelectorBox(out_fmt="%d/%m/%Y")
        err = ('hasta_error', '_hasta_err')
        connect_signal(self.hasta, 'focus-in', self.on_fecha_focus_in, err)
        connect_signal(self.hasta, 'focus-out', self.on_fecha_focus_out, err)
        connect_signal(self.hasta, 'edit-cancel', _edit_cancel)
        connect_signal(self.hasta, 'edit-done', self.on_fecha_edit_done, err+(_edit_ok,))
        connect_signal(self.hasta, 'bad-date-error', self.on_fecha_error, err)
        self.hasta_error = Text("", wrap='clip')

        articulos_row = Columns([
            ('fixed', 14, AttrMap(Text("Artículos", align='right'), 'dialog.selectdate.label')),
            AttrMap(self.articulos, 'dialog.selectdate.input', 'dialog.selectdate.input.focus'),
        ], dividechars=1)

        desde_row = Columns([
            ('fixed', 14, AttrMap(Text("Desde", align='right'), 'dialog.selectdate.label')),
            ('fixed', 11, AttrMap(self.desde, 'dialog.selectdate.input', 'dialog.selectdate.input.focus')),
            AttrMap(self.desde_error, 'dialog.selectdate.error'),
        ], dividechars=1)

        hasta_row = Columns([
            ('fixed', 14, AttrMap(Text("Hasta", align='right'), 'dialog.selectdate.label')),
            ('fixed', 11, AttrMap(self.hasta, 'dialog.selectdate.input', 'dialog.selectdate.input.focus')),
            AttrMap(self.hasta_error, 'dialog.selectdate.error'),
        ], dividechars=1)

        self.include_inactives = CheckBox(u"Incluir Desactivados", state=True)
        include_inactives_row = Columns([
            ('fixed', 14, Divider()),
            AttrMap(self.include_inactives, 'dialog.selectdate.label'),
        ], dividechars=1)

        self.content = Pile([
            articulos_row,
            desde_row,
            hasta_row,
            include_inactives_row,
            Divider(),
        ])

        t = u"Artículos y Rango de Fechas"
        if title:
            t += u" - %s" % title

        # Set initial dates
        self.desde.set_value(date(2001, 01, 01)) # FIXME: hardcoded > Principio de actividad
        self.hasta.set_value(date.today()+relativedelta(day=31)) # Fin de mes

        buttons = [("Continuar", self.run_list), ("Cancelar", self._quit)]

        Dialog.__init__(self, self.content, buttons,
                title=t,
                height=None,
                width=60,
                attr_style='dialog.selectdate',
                title_attr_style='dialog.selectdate.title')
#}}}
    def run_list(self, *args):
        art_list = self.get_articles()
        if not art_list:
            show_error([u"Los artículos ingresados no producen ningún resultado válido, ",
                        u"ingrese ", ('dialog.warning.important', u"artículos"), " o ",
                        ('dialog.warning.important', "grupos"), " correctos."])
            self._pile.set_focus(0)
            self.content.set_focus(0)
            return
        subdialog = self.cls(start_date=self.desde.get_value(),
                             end_date=self.hasta.get_value(),
                             articles=art_list)
        self.dialog_result = subdialog.run()
        self.quit()

    def get_articles(self):
        arts = []
        code_list = set([c.strip() for c in self.articulos.get_edit_text().split(",")])
        agrup_list = [c[1:] for c in code_list if c.startswith('@')]
        code_list = code_list.difference(agrup_list)
        query = session.query(Articulo)
        if self.include_inactives.get_state() is False:
            query = query.filter(Articulo.es_activo==True)
        if code_list:
            art = query.filter(Articulo.codigo.in_(code_list)).all()
            order = dict([(v, i) for i, v in enumerate(code_list)])
            art.sort(cmp=lambda a, b: cmp(order[a.codigo], order[b.codigo]))
            arts.extend(art)
        if agrup_list:
            art = query.filter(Articulo.agrupacion.in_(agrup_list)).order_by(Articulo.codigo).all()
            order = dict([(v, i) for i, v in enumerate(agrup_list)])
            art.sort(cmp=lambda a, b: cmp(order[a.agrupacion], order[b.agrupacion]))
            arts.extend(art)
        return arts

    def on_articulos_edit_done(self, widget, text):
        self.content.set_focus(1)