Пример #1
0
    def render(self, size, focus=False):
        """
        Render edit widget and return canvas.  Include cursor when in
        focus.

        >>> c = Edit("? ","yes").render((10,), focus=True)
        >>> c.text # ... = b in Python 3
        [...'? yes     ']
        >>> c.cursor
        (5, 0)
        """
        if self.has_focus and not focus:
            self.has_focus = False
            self.on_blur()
        self.has_focus = focus

        (maxcol,) = size
        self._shift_view_to_cursor = bool(focus)

        canv = Text.render(self,(maxcol,))
        if focus:
            canv = CompositeCanvas(canv)
            canv.cursor = self.get_cursor_coords((maxcol,))

        # .. will need to FIXME if I want highlight to work again
        #if self.highlight:
        #    hstart, hstop = self.highlight_coords()
        #    d.coords['highlight'] = [ hstart, hstop ]
        return canv
Пример #2
0
 def build_menuable_items(self):
     """ Builds a list of bundles available to install
     """
     cols = []
     for bundle in app.bundles:
         bundle_metadata = bundle['Meta']['bundle-metadata']
         try:
             conjure_data = bundle['Meta']['extra-info/conjure-up']
             name = conjure_data.get('friendly-name',
                                     bundle['Meta']['id']['Name'])
         except KeyError:
             name = bundle['Meta']['id']['Name']
         self.fname_id_map[name] = bundle
         cols.append(
             Columns([("weight", 0.2,
                       Color.body(menu_btn(label=name, on_press=self.done),
                                  focus_map="menu_button focus")),
                      ("weight", 0.3,
                       Text(bundle_metadata.get('Description',
                                                'Needs a description'),
                            align="left"))],
                     dividechars=1))
         cols.append(Padding.line_break(""))
     return Pile(cols)
Пример #3
0
    def __init__(self):
        self.keybind = {}

        self.main_helper_text = self.generate_helper_text([
            ("F10", "Quit", "helper_text_red"),
        ])

        self.subview_helper_text = self.generate_helper_text([
            ("F1", "Confirm", "helper_text_green"),
            ("F5", "Abort", "helper_text_brown"),
            ("F10", "Quit", "helper_text_red"),
            ("TAB", "Next", "helper_text_light"),
            ("S-TAB", "Previous", "helper_text_light")
        ])

        self.root = Frame(self.generate_main_view(),
                          Text(("header", ""), "center"),
                          self.main_helper_text)
        self.loop = MainLoop(self.root,
                             palette,
                             unhandled_input=self.unhandled_input)

        self.bind_global("f10", self.quit)
        self.handle_os_signals()
Пример #4
0
 def _journal_date(self, s, f, ajournal, date):
     zones = build_zones(s, ajournal, HRZ_WIDTH)
     active_date = self.__active_date(s, ajournal, date)
     climbs = self.__climbs(s, ajournal, date)
     details = Pile(([] if climbs else [Divider()]) + active_date + climbs)
     yield Pile([
         Text(f'{ajournal.name} ({ajournal.activity_group.name})'),
         Indent(Columns([details, (HRZ_WIDTH + 2, zones)])),
         Divider(),
         Indent(
             Columns([
                 Pile(
                     self.__template(s, ajournal, MIN_KM_TIME_ANY,
                                     'Min Time', r'(\d+km)', date) +
                     self.__template(s, ajournal, MED_KM_TIME_ANY,
                                     'Med Time', r'(\d+km)', date)),
                 Pile(
                     self.__template(s, ajournal, MAX_MED_HR_M_ANY,
                                     'Max Med Heart Rate', r'(\d+m)', date)
                     + self.__template(s, ajournal, MAX_MEAN_PE_M_ANY,
                                       'Max Mean Power Estimate', r'(\d+m)',
                                       date))
             ]))
     ])
Пример #5
0
    def __init__(self, user, last_statuses):
        """
        Receive a ``user`` and its ``last_statuses`` to render the widget.
        """
        whitespace = Divider(' ')
        widgets = [Text(u"{0}".format(user.name)), whitespace]

        # bio
        if user.description:
            description = Text(parse_attributes(user.description))
            widgets.extend([description, whitespace])

        # URL
        if user.url:
            url_text_with_attr = ('url', user.url)
            url = Text(url_text_with_attr)

            widgets.extend([url, whitespace])

        # statistics: following, followers and favorites
        # TODO: tweet count
        following = Text(_('following:\n{0}'.format(user.friends_count)))
        followers = Text(_('followers:\n{0}'.format(user.followers_count)))
        favorites = Text(_('favorites:\n{0}'.format(user.favorites_count)))
        stats = Columns([following, followers, favorites])

        widgets.extend([stats, whitespace])

        # Last n statuses
        # TODO: make it configurable
        statuses_to_show = configuration.styles['statuses_in_user_info']
        status_widgets = [
            StatusWidget(status) for status in last_statuses[:statuses_to_show]
        ]
        widgets.extend(status_widgets)

        pile = Pile(widgets)

        WidgetWrap.__init__(
            self,
            LineBox(title='@{0}'.format(user.screen_name),
                    original_widget=pile))
Пример #6
0
    def _build_filesystem_list(self):
        log.debug('FileSystemView: building part list')
        cols = []
        mount_point_text = _("MOUNT POINT")
        longest_path = len(mount_point_text)
        for m in sorted(self.model._mounts, key=lambda m: m.path):
            path = m.path
            longest_path = max(longest_path, len(path))
            for p, *dummy 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.")))])
        size_text = _("SIZE")
        type_text = _("TYPE")
        size_width = max(len(size_text), 9)
        type_width = max(len(type_text), self.model.longest_fs_name)
        cols.insert(
            0,
            (None, mount_point_text, size_text, type_text, _("DEVICE TYPE")))
        pl = []
        for dummy, 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)), (size_width, b),
                         (type_width, Text(c)),
                         Text(d)], 4))
        return Pile(pl)
Пример #7
0
    def __init__(self, app, step_model, cb):
        """
        Arguments:
        step_model: step model
        step_model_widget: step model widget
        cb: callback
        """
        self.app = app
        self.model = step_model

        self.title = Text(('info_minor', step_model.title))
        self.description = Text(('info_minor', step_model.description))
        self.result = Text(step_model.result)
        self.output = Text(('info_minor', ''))
        self.icon = Text(("info_minor", "\N{BALLOT BOX}"))

        self.additional_input = []
        if len(step_model.additional_input) > 0:
            for i in step_model.additional_input:
                widget = {
                    "label": Text(('body', i['label'])),
                    "key": i['key'],
                    "input": self.INPUT_TYPES.get(i['type'])
                }
                if 'default' in i:
                    widget['input'] = StringEditor(default=i['default'])

                self.additional_input.append(widget)
        else:
            widget = {"label": Text(""), "key": "submit", "input": None}
            self.additional_input.append(widget)

        self.cb = cb
        self.step_pile = self.build_widget()
        self.show_output = True
        super().__init__(self.step_pile)
Пример #8
0
    def __init__(self, user):
        """
        """
        whitespace = Divider(' ')
        widgets = []

        # name
        name = Text('%s' % user.name)
        widgets.extend([name, whitespace])

        # bio
        if user.description:
            description = Text(parse_attributes(user.description))
            widgets.extend([description, whitespace])

        # URL
        if user.url:
            url_text_with_attr = ('url', user.url)
            url = Text(url_text_with_attr)

            widgets.extend([url, whitespace])

        # statistics: following, followers and favorites
        following = Text(_('following:\n%s' % user.friends_count))
        followers = Text(_('followers:\n%s' % user.followers_count))
        favorites = Text(_('favorites:\n%s' % user.favorites_count))
        stats = Columns([following, followers, favorites])

        widgets.extend([stats, whitespace])

        # last status
        if user.status:
            status = StatusWidget(user.status)
            widgets.append(status)

        pile = Pile(widgets)

        WidgetWrap.__init__(self, LineBox(title='@%s' % user.screen_name,
                                          original_widget=pile))
 def _build_iface_inputs(self):
     col1 = [
         Columns([("weight", 0.2, Text("Subnet")),
                  ("weight", 0.3,
                   Color.string_input(self.subnet_input,
                                      focus_map="string_input focus")),
                  ("weight", 0.5, Text("CIDR e.g. 192.168.9.0/24"))],
                 dividechars=2),
         Columns([("weight", 0.2, Text("Address")),
                  ("weight", 0.3,
                   Color.string_input(self.address_input,
                                      focus_map="string_input focus")),
                  ("weight", 0.5, Text(""))],
                 dividechars=2),
         Columns([("weight", 0.2, Text("Gateway")),
                  ("weight", 0.3,
                   Color.string_input(self.gateway_input,
                                      focus_map="string_input focus")),
                  ("weight", 0.5, Text(""))],
                 dividechars=2)
     ]
     return Pile(col1)
Пример #10
0
 def __init__(self, model, controller):
     self.model = model
     self.controller = controller
     self.items = []
     self.error = Text("", align='center')
     self.additional_options = Pile(self._build_additional_options())
     self.listbox = ListBox(self._build_model_inputs() + [
         Padding.center_79(self.additional_options),
         Padding.line_break(""),
     ])
     self.bottom = Pile([
         Text(""),
         self._build_buttons(),
         Text(""),
     ])
     self.error_showing = False
     self.frame = Pile([('pack', Text("")),
                        ('pack', Padding.center_79(Text(_(self.excerpt)))),
                        ('pack', Text("")),
                        Padding.center_90(self.listbox),
                        ('pack', self.bottom)])
     self.frame.focus_position = 4
     super().__init__(self.frame)
Пример #11
0
 def add_log_line(self, text):
     self._add_line(self.log_listbox, Text(text))
Пример #12
0
 def render_component(self, props):
     if props['completed']:
         return Text('[X] --' + props['text'] + '--')
     else:
         return Text('[ ]   ' + props['text'])
Пример #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 = 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
Пример #14
0
    def __init__(self, model, controller):
        log.debug('FileSystemView init start()')
        self.model = model
        self.controller = controller

        self.mount_list = MountList(self)
        self.avail_list = DeviceList(self, True)
        self.used_list = DeviceList(self, False)
        self.avail_list.table.bind(self.used_list.table)

        body = [
            Text(_("FILE SYSTEM SUMMARY")),
            Text(""),
            Padding.push_2(self.mount_list),
            Text(""),
            Text(""),
            Text(_("AVAILABLE DEVICES")),
            Text(""),
            Padding.push_2(self.avail_list),
            Text(""),
            Text(""),
            Text(_("USED DEVICES")),
            Text(""),
            Padding.push_2(self.used_list),
            Text(""),
        ]

        self.lb = ListBox(body)
        frame = screen(self.lb,
                       self._build_buttons(),
                       focus_buttons=self.model.can_install())
        frame.width = ('relative', 95)
        super().__init__(frame)
        log.debug('FileSystemView init complete()')
Пример #15
0
    def __init__(self, label, on_press=None, user_data=None):
        self.widget = Text(label)
        self.widget = AttrMap(self.widget, 'footer')
        self._hidden_btn = Button(label, on_press, user_data)

        super().__init__(self.widget)
Пример #16
0
    def __init__(self, parent, existing=None):
        self.parent = parent
        self.existing = existing
        all_netdev_names = {
            device.name
            for device in parent.model.get_all_netdevs()
        }
        if existing is None:
            title = _('Create bond')
            label = _("Create")
            x = 0
            while True:
                name = 'bond{}'.format(x)
                if name not in all_netdev_names:
                    break
                x += 1
            initial = {
                'devices': set(),
                'name': name,
            }
        else:
            title = _('Edit bond')
            label = _("Save")
            all_netdev_names.remove(existing.name)
            params = existing.config['parameters']
            mode = params['mode']
            initial = {
                'devices':
                set([
                    parent.model.get_netdev_by_name(name)
                    for name in existing.config['interfaces']
                ]),
                'name':
                existing.name,
                'mode':
                mode,
            }
            if mode in BondParameters.supports_xmit_hash_policy:
                initial['xmit_hash_policy'] = params['transmit-hash-policy']
            if mode in BondParameters.supports_lacp_rate:
                initial['lacp_rate'] = params['lacp-rate']

        def device_ok(device):
            if device is existing:
                return False
            if device in initial['devices']:
                return True
            if device.type in ("vlan", "bond"):
                return False
            return not device.is_bond_slave

        candidate_netdevs = [
            device for device in parent.model.get_all_netdevs()
            if device_ok(device)
        ]

        self.form = BondForm(initial, candidate_netdevs, all_netdev_names)
        self.form.buttons.base_widget[0].set_label(label)
        connect_signal(self.form, 'submit', self.done)
        connect_signal(self.form, 'cancel', self.cancel)
        super().__init__(
            title, [Pile(self.form.as_rows()),
                    Text(""), self.form.buttons], 0, 0)
Пример #17
0
 def add_log_line(self, text):
     at_end = len(self.log_listwalker) == 0 or self.log_listbox.focus_position == len(self.log_listwalker) - 1
     self.log_listwalker.append(Text(text))
     if at_end:
         self.log_listbox.set_focus(len(self.log_listwalker) - 1)
         self.log_listbox.set_focus_valign('bottom')
Пример #18
0
        self.info.set_text(self.format % args)

    def cols(self, maxcol):
        l = len(self.get_text()[0])
        r = len(self.info.get_text()[0])
        lr = l + r
        mc = maxcol - 2
        if lr <= mc:
            return l, r
        return l * mc // lr, r * mc // lr

    if urwid_ver < '0.9.8':
        def render(self, (maxcol,), focus=False):
            l, r = self.cols(maxcol)
            return CanvasJoin([
                Text.render(self, (l,), focus),
                maxcol - r, self.info.render((r,)),
            ])
    else:
        def render(self, (maxcol,), focus=False):
            l, r = self.cols(maxcol)
            return CanvasJoin([
                (Text.render(self, (l,), focus), None, True, maxcol - r),
                (self.info.render((r,)), None, False, r),
            ])

    def rows(self, (maxcol,), focus=False):
        l, r = self.cols(maxcol)
        return max(Text.rows(self, (l,), focus), self.info.rows((r,)))

Пример #19
0
 def make_body(self):
     return Pile([
         Text(_("Keyboard auto detection failed, sorry")),
         Text(""),
         button_pile([ok_btn(label="OK", on_press=self.ok)]),
     ])
Пример #20
0
 def __init__(self):
     super(SampleLabelsAvgRT, self).__init__(SimpleListWalker([]))
     self.header = Text(("stat-hdr", " Avg Time "), align=RIGHT)
     self.body.append(self.header)
Пример #21
0
 def add_data(self, data):
     """
     add label name
     """
     data_widget = Text(("stat-txt", "%s" % data), wrap=CLIP)
     self.body.append(data_widget)
Пример #22
0
    def __init__(self, parent, existing=None):
        self.parent = parent
        mountpoint_to_devpath_mapping = (
            self.parent.model.get_mountpoint_to_devpath_mapping())
        self.existing = existing
        raid_names = {raid.name for raid in parent.model.all_raids()}
        if existing is None:
            title = _('Create software RAID ("MD") disk')
            x = 0
            while True:
                name = 'md{}'.format(x)
                if name not in raid_names:
                    break
                x += 1
            initial = {
                'devices': {},
                'name': name,
                'level': raidlevels_by_value[1],
                'size': '-',
                }
        else:
            raid_names.remove(existing.name)
            title = _('Edit software RAID disk "{}"').format(existing.name)
            f = existing.fs()
            if f is None:
                fs = parent.model.fs_by_name[None]
                m = None
            else:
                fs = parent.model.fs_by_name[f.fstype]
                m = f.mount()
                if m:
                    m = m.path
                    if m in mountpoint_to_devpath_mapping:
                        del mountpoint_to_devpath_mapping[m]
            name = existing.name
            if name.startswith('md/'):
                name = name[3:]
            devices = {}
            for d in existing.devices:
                devices[d] = 'active'
            for d in existing.spare_devices:
                devices[d] = 'spare'
            initial = {
                'devices': devices,
                'fstype': fs,
                'mount': m,
                'name': name,
                'level': raidlevels_by_value[existing.raidlevel]
                }

        all_devices = []

        # We mustn't allow the user to add a device to this raid if it
        # is built out of this raid!
        omits = set()

        def _walk_down(o):
            if o is None:
                return
            if o in omits:
                raise Exception(
                    "block device cycle detected involving {}".format(o))
            omits.add(o)
            _walk_down(o.constructed_device())
            for p in o.partitions():
                _walk_down(p)

        _walk_down(existing)

        cur_devices = set()
        if existing:
            cur_devices = existing.devices | existing.spare_devices

        def device_ok(dev):
            return (dev not in omits
                    and (dev.supports_action(DeviceAction.FORMAT)
                         or dev in cur_devices))

        for dev in self.parent.model.all_devices():
            if device_ok(dev):
                all_devices.append((DEVICE, dev))
            else:
                ok_parts = []
                for part in dev.partitions():
                    if device_ok(part):
                        ok_parts.append((PART, part))
                if len(ok_parts) > 0:
                    all_devices.append((LABEL, dev))
                    all_devices.extend(ok_parts)

        form = self.form = RaidForm(
            mountpoint_to_devpath_mapping, all_devices, initial, raid_names)

        self.form.devices.widget.set_supports_spares(
            initial['level'].supports_spares)

        connect_signal(form.level.widget, 'select', self._select_level)
        connect_signal(form.devices.widget, 'change', self._change_devices)
        connect_signal(form, 'submit', self.done)
        connect_signal(form, 'cancel', self.cancel)

        rows = form.as_rows()

        if existing is not None:
            rows[0:0] = [
                Text("You cannot save edit to RAIDs just yet."),
                Text(""),
                ]
            self.form.validated = lambda *args: self.form.done_btn.disable()
            self.form.validated()

        super().__init__(
            title,
            [Pile(rows), Text(""), self.form.buttons],
            0, 0)
Пример #23
0
 def __init__(self, format):
     Text.__init__(self, '')
     self.format = format
     self.info = Text('')
Пример #24
0
 def __init__(self):
     super(SampleLabelsNames, self).__init__(SimpleListWalker([]))
     self.header = Text(("stat-hdr", " Labels "))
     self.body.append(self.header)
Пример #25
0
 def __init__(self, format):
     Text.__init__(self, '')
     self.format = format
     self.info = Text('')
Пример #26
0
 def __init__(self):
     super(SampleLabelsFailed, self).__init__(SimpleListWalker([]))
     self.header = Text(("stat-hdr", " Failures "), align=CENTER)
     self.body.append(self.header)
Пример #27
0
 def rows(self, xxx_todo_changeme3, focus=False):
     (maxcol, ) = xxx_todo_changeme3
     lines, r = self.cols(maxcol)
     return max(Text.rows(self, (lines, ), focus), self.info.rows((r, )))
Пример #28
0
 def add_data(self, data):
     """
     add new avg rt value to column
     """
     data_widget = Text(("stat-txt", "%.3f" % data), align=RIGHT)
     self.body.append(data_widget)
Пример #29
0
 def __init__(self, text):
     AttrWrap.__init__(self, Text(text, wrap='clip'), None, 'focus')
Пример #30
0
    def _pile_elements(self):
        btns = self.btns.copy()

        widgets = [
            Text(rewrap(_(error_report_intros[self.report.kind]))),
            Text(""),
            ]

        self.spinner.stop()

        if self.report.state == ErrorReportState.DONE:
            widgets.append(btns['view'])
            widgets.append(Text(""))
            widgets.append(Text(rewrap(_(submit_text))))
            widgets.append(Text(""))

            if self.report.uploader:
                if self.upload_pb is None:
                    self.upload_pb = self.pb(self.report.uploader)
                widgets.append(self.upload_pb)
            else:
                if self.report.oops_id:
                    widgets.append(btns['submitted'])
                else:
                    widgets.append(btns['submit'])
                self.upload_pb = None

            fs_label, fs_loc = self.report.persistent_details
            if fs_label is not None:
                location_text = _(
                    "The error report has been saved to\n\n  {loc}\n\non the "
                    "filesystem with label {label!r}.").format(
                        loc=fs_loc, label=fs_label)
                widgets.extend([
                    Text(""),
                    Text(location_text),
                    ])
        else:
            text, spin = error_report_state_descriptions[self.report.state]
            widgets.append(Text(rewrap(_(text))))
            if spin:
                self.spinner.start()
                widgets.extend([
                    Text(""),
                    self.spinner])

        if self.report.uploader:
            widgets.extend([Text(""), btns['cancel']])
        elif self.interrupting:
            if self.report.state != ErrorReportState.INCOMPLETE:
                text, btn_names = error_report_options[self.report.kind]
                if text:
                    widgets.extend([Text(""), Text(rewrap(_(text)))])
                for b in btn_names:
                    widgets.extend([Text(""), btns[b]])
        else:
            widgets.extend([
                Text(""),
                btns['close'],
                ])

        return widgets
Пример #31
0
def exploreFieldSet(field_set, args, options={}):
    charset = getTerminalCharset()

    ui = urwid.curses_display.Screen()
    ui.register_palette((
        ('focus', 'white', 'dark blue'),
        ('sep', 'white', 'dark red'),
        ('input', 'black', 'light gray'),
    ))

    msgs = [[], [], 0]
    hachoir_log.use_print = False

    def logger(level, prefix, text, ctxt):
        if ctxt is not None:
            c = []
            if hasattr(ctxt, "_logger"):
                c[:0] = [ctxt._logger()]
            if issubclass(ctxt.__class__, Field):
                ctxt = ctxt["/"]
            name = logger.objects.get(ctxt)
            if name:
                c[:0] = [name]
            if c:
                text = "[%s] %s" % ('|'.join(c), text)
        if not isinstance(text, str):
            text = str(text, charset)
        msgs[0].append((level, prefix, text))

    logger.objects = WeakKeyDictionary()
    hachoir_log.on_new_message = logger

    preload_fields = 1 + max(0, args.preload)

    log_count = [0, 0, 0]
    sep = Separator("log: %%u/%%u/%%u  |  %s  " % "F1: help")
    sep.set_info(*tuple(log_count))
    body = Tabbed(sep)
    help = ('help', ListBox([Text(getHelpMessage())]))
    logger.objects[field_set] = logger.objects[
        field_set.stream] = name = 'root'
    body.append((name,
                 TreeBox(charset, Node(field_set, None), preload_fields,
                         args.path, options)))

    log = BoxAdapter(ListBox(msgs[1]), 0)
    log.selectable = lambda: False
    wrapped_sep = AttrWrap(sep, 'sep')
    footer = Pile([('flow', wrapped_sep), log])

    # awful way to allow the user to hide the log widget
    log.render = lambda size, focus=False: BoxAdapter.render(
        log, size[:1], focus)
    footer.render = lambda arg, focus=False: Pile.render(
        footer, (arg[0], sep.rows(arg) + log.height), focus)

    top = Frame(body, None, footer)

    def input_enter(w):
        footer.widget_list[0] = w
        footer.set_focus(0)
        top.set_focus('footer')

    def input_leave():
        footer.widget_list[0] = wrapped_sep
        footer.set_focus(0)
        top.set_focus('body')

    input = Input(input_enter, input_leave)

    def run():
        msg = _resize = retry = 0
        events = ("window resize", )
        profile_display = args.profile_display
        while True:
            for e in events:
                try:
                    if e == "window resize":
                        size = ui.get_cols_rows()
                        resize = log.height
                    else:
                        e = top.keypress(size, e)
                        if e is None:
                            pass
                        elif e in ('f1', '?'):
                            try:
                                body.select(body.tabs.index(help))
                            except ValueError:
                                body.append(help)
                                resize = log.height
                        elif e in ('esc', 'ctrl w'):
                            body.close()
                            if body.original_widget is None:
                                return
                            resize = log.height
                        elif e == '+':
                            if log.height:
                                resize = log.height - 1
                        elif e == '-':
                            resize = log.height + 1
                        elif e == 'q':
                            return
                # except AssertionError:
                #     hachoir_log.error(getBacktrace())
                except NewTab_Stream as e:
                    stream = e.field.getSubIStream()
                    logger.objects[stream] = e = "%u/%s" % (
                        body.active, e.field.absolute_address)
                    parser = guessParser(stream)
                    if not parser:
                        hachoir_log.error("No parser found for %s" %
                                          stream.source)
                    else:
                        logger.objects[parser] = e
                        body.append((e,
                                     TreeBox(charset, Node(parser, None),
                                             preload_fields, None, options)))
                        resize = log.height
                except NeedInput as e:
                    input.do(*e.args)
                if profile_display:
                    events = events[1:]
                    break
            while True:
                if msgs[0]:
                    for level, prefix, text in msgs[0]:
                        log_count[level] += 1
                        txt = Text("[%u]%s %s" % (msg, prefix, text))
                        msg += 1
                        msgs[1].append(txt)
                        _resize += txt.rows(size[:1])
                    if log.height < _resize and (resize is None
                                                 or resize < _resize):
                        resize = _resize
                    try:
                        log.set_focus(len(msgs[1]) - 1)
                    except IndexError:
                        pass
                    sep.set_info(*tuple(log_count))
                    msgs[0] = []
                if resize is not None:
                    body.height = size[1] - sep.rows(size[:1]) - resize
                    if body.height <= 0:
                        resize += body.height - 1
                        body.height = 1
                    log.height = resize
                    resize = None
                canvas = top.render(size, focus=True)
                if not msgs[0]:
                    _resize = retry = 0
                    break
                assert not retry
                retry += 1
            ui.draw_screen(size, canvas)
            msgs[2] = len(msgs[1])
            if profile_display and events:
                continue
            while True:
                events = ui.get_input()
                if events:
                    break

    try:
        ui.run_wrapper(run)
    except Exception:
        pending = [msg.get_text()[0] for msg in msgs[1][msgs[2]:]] + \
                  ["[*]%s %s" % (prefix, text)
                   for level, prefix, text in msgs[0]]
        if pending:
            print("\nPending messages:\n" + '\n'.join(pending))
        raise
Пример #32
0
 def __init__(self, app, message):
     self.message = Text(message, align="center")
     self.output = Text("", align="left")
     self.loading_boxes = [Text(x) for x in self.load_attributes]
     super().__init__(self._build_node_waiting())
Пример #33
0
 def run():
     msg = _resize = retry = 0
     events = ("window resize", )
     profile_display = args.profile_display
     while True:
         for e in events:
             try:
                 if e == "window resize":
                     size = ui.get_cols_rows()
                     resize = log.height
                 else:
                     e = top.keypress(size, e)
                     if e is None:
                         pass
                     elif e in ('f1', '?'):
                         try:
                             body.select(body.tabs.index(help))
                         except ValueError:
                             body.append(help)
                             resize = log.height
                     elif e in ('esc', 'ctrl w'):
                         body.close()
                         if body.original_widget is None:
                             return
                         resize = log.height
                     elif e == '+':
                         if log.height:
                             resize = log.height - 1
                     elif e == '-':
                         resize = log.height + 1
                     elif e == 'q':
                         return
             # except AssertionError:
             #     hachoir_log.error(getBacktrace())
             except NewTab_Stream as e:
                 stream = e.field.getSubIStream()
                 logger.objects[stream] = e = "%u/%s" % (
                     body.active, e.field.absolute_address)
                 parser = guessParser(stream)
                 if not parser:
                     hachoir_log.error("No parser found for %s" %
                                       stream.source)
                 else:
                     logger.objects[parser] = e
                     body.append((e,
                                  TreeBox(charset, Node(parser, None),
                                          preload_fields, None, options)))
                     resize = log.height
             except NeedInput as e:
                 input.do(*e.args)
             if profile_display:
                 events = events[1:]
                 break
         while True:
             if msgs[0]:
                 for level, prefix, text in msgs[0]:
                     log_count[level] += 1
                     txt = Text("[%u]%s %s" % (msg, prefix, text))
                     msg += 1
                     msgs[1].append(txt)
                     _resize += txt.rows(size[:1])
                 if log.height < _resize and (resize is None
                                              or resize < _resize):
                     resize = _resize
                 try:
                     log.set_focus(len(msgs[1]) - 1)
                 except IndexError:
                     pass
                 sep.set_info(*tuple(log_count))
                 msgs[0] = []
             if resize is not None:
                 body.height = size[1] - sep.rows(size[:1]) - resize
                 if body.height <= 0:
                     resize += body.height - 1
                     body.height = 1
                 log.height = resize
                 resize = None
             canvas = top.render(size, focus=True)
             if not msgs[0]:
                 _resize = retry = 0
                 break
             assert not retry
             retry += 1
         ui.draw_screen(size, canvas)
         msgs[2] = len(msgs[1])
         if profile_display and events:
             continue
         while True:
             events = ui.get_input()
             if events:
                 break