Ejemplo n.º 1
0
tl_txtbox1 = urwid.Text(tl_txt1)
tr_txtbox1 = urwid.Text(tr_txt1)
bl_txtbox1 = urwid.Text(bl_txt1)
br_txtbox1 = urwid.Text(br_txt1)

tl_txtmap1 = urwid.AttrMap(tl_txtbox1, 'tl_txt_pal')
tr_txtmap1 = urwid.AttrMap(tr_txtbox1, 'tr_txt_pal')
bl_txtmap1 = urwid.AttrMap(bl_txtbox1, 'bl_txt_pal')
br_txtmap1 = urwid.AttrMap(br_txtbox1, 'br_txt_pal')

right_pile1 = urwid.Pile([tl_txtmap1, bl_txtmap1])
left_pile1 = urwid.Pile([tr_txtmap1, br_txtmap1])

column1 = urwid.Columns([right_pile1, left_pile1])

padding1 = urwid.Padding(column1, left=10, right=3)

tl_txt2 = 'Top Left 2'
tr_txt2 = 'Top Right 2'
bl_txt2 = 'Bottom Left 2'
br_txt2 = 'Bottom Right 2'

tl_txtbox2 = urwid.Text(tl_txt2)
tr_txtbox2 = urwid.Text(tr_txt2)
bl_txtbox2 = urwid.Text(bl_txt2)
br_txtbox2 = urwid.Text(br_txt2)

tl_txtmap2 = urwid.AttrMap(tl_txtbox2, 'tl_txt_pal')
tr_txtmap2 = urwid.AttrMap(tr_txtbox2, 'tr_txt_pal')
bl_txtmap2 = urwid.AttrMap(bl_txtbox2, 'bl_txt_pal')
br_txtmap2 = urwid.AttrMap(br_txtbox2, 'br_txt_pal')
Ejemplo n.º 2
0
                    urwid.AttrMap(done, None, focus_map='reversed')]))


def generate_gif(button):
    raise urwid.ExitMainLoop()


def generate_gif_with_subtitle(button, edit):
    global subtitle
    subtitle = edit.edit_text
    raise urwid.ExitMainLoop()


def exit(button):
    index = None
    raise urwid.ExitMainLoop()


main = urwid.Padding(menu(u'Movie choice', choices), left=2, right=2)
top = urwid.Overlay(main,
                    urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                    align='center',
                    width=('relative', 60),
                    valign='middle',
                    height=('relative', 60),
                    min_width=20,
                    min_height=9)
urwid.MainLoop(top, palette=[('reversed', 'standout', '')]).run()
if index:
    makeGif(source, index, custom_subtitle=subtitle)
Ejemplo n.º 3
0
def logInformation(button):
    log = '[INFO] ' + datetime.datetime.now().strftime(
        "%Y-%m-%d %H:%M:%S") + ' Log: ' + askLog.get_edit_text() + '\n'
    with open(str(pid) + '.out', 'a+') as outFile:
        outFile.write(log)
    main.original_widget = urwid.Padding(menu(), left=0, right=0)
Ejemplo n.º 4
0
    def _show_confirmation(self, items, payment, address, scheduled=False):
        widgets = []
        widgets += [urwid.Divider()]

        # Add total as a line item
        total = LineItem({})
        total.price = sum(x.price * x.quantity for x in items)
        total.title = "Total"
        items.append(total)

        # Order Items
        for item in filter(lambda x: x.type == LineItem.TYPE_DISH, items):
            price = "%.2f" % (item.price / 100.0)
            columns = urwid.Columns([
                ("fixed", 2, urwid.Text(str(item.quantity), align="right")),
                ("fixed", 1, urwid.Divider()),
                ("weight", 1, ColoredText(item.title, colors.ITEM_MEAL)),
                ("fixed", 6, ColoredText(price, colors.PRICE, align="right")),
            ])
            widgets += [columns]

        # Total & Taxes
        widgets += [urwid.Divider()]
        for item in filter(lambda x: x.type != LineItem.TYPE_DISH, items):
            price = "%.2f" % (item.price / 100.0)
            title = item.title
            columns = urwid.Columns([
                ("weight", 1, ColoredText(title, colors.TAX, align="right")),
                ("fixed", 10, ColoredText(price, colors.PRICE, align="right")),
            ])
            widgets += [columns]

        # Payment method
        columns = urwid.Columns([
            ("weight", 0.5, ColoredText("Payment method", colors.LOW)),
            ("weight", 0.5, ColoredText(payment, colors.LOW, align="right")),
        ])
        widgets += [urwid.Divider()]
        widgets += [columns]

        # Address
        columns = urwid.Columns([
            ("weight", 0.5, ColoredText("Deliver to", colors.LOW)),
            ("weight", 0.5, ColoredText(address, colors.LOW, align="right")),
        ])
        widgets += [columns]

        # Delay warning
        if scheduled:
            warning_label = urwid.Text(WARNING_TEXT, align="center")
            widgets += [urwid.Divider()]
            widgets += [colors.wrap(warning_label, colors.WARNING)]

        # Order button
        text = "Order when ready" if scheduled else "Order"
        buttons = urwid.Columns([
            ("weight", 0.4, Button("Cancel", "cancel", delegate=self)),
            ("weight", 0.2, urwid.Divider()),
            ("weight", 0.4, Button(text, "order", delegate=self)),
        ],
                                focus_column=2)
        widgets += [urwid.Divider()]
        widgets += [buttons]

        pile = urwid.Pile(widgets)
        pile = urwid.Padding(pile, left=2, right=2)
        pile = urwid.Columns([
            ("weight", 0.2, urwid.Divider()),
            ("weight", 0.6, ColoredLineBox(pile, title="Confirmation")),
            ("weight", 0.2, urwid.Divider()),
        ])

        self.body = pile
Ejemplo n.º 5
0
    parser.write(cfgfile)
    cfgfile.close()

    index = 0
else:
    print("Config file found")
    print("Decoding wallet seed with your password")
    mnemonic = read_encrypted(password, 'seed.txt', string=True)

account = parser.get('wallet', 'account')
index = int(parser.get('wallet', 'index'))
representative = parser.get('wallet', 'representative')
pow_source = parser.get('wallet', 'pow_source')
node_server = parser.get('wallet', 'server')
ws = create_connection(node_server)

main = urwid.Padding(menu(u'RetroXRBWallet', choices), left=2, right=2)
top = urwid.Overlay(main,
                    urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                    align='center',
                    width=('relative', 90),
                    valign='middle',
                    height=('relative', 80),
                    min_width=20,
                    min_height=9)

main_loop = urwid.MainLoop(top, palette=[('reversed', 'standout', '')])
main_loop.set_alarm_in(10, receive_xrb)
main_loop.run()
Ejemplo n.º 6
0
    def update_info(self, *args, **kwargs):
        """
        Update the job information text.
        Called by the job
        """
        # Create the layout with the information
        self.info_widgets_list = [
            urwid.Text('ID: {}'.format(self.job.id)),
            urwid.Divider('='),
            urwid.Text('Command: {}'.format(self.job.command)),
            urwid.Text('Status: {}'.format(self.job.status))
        ]

        if self.job.status == JobStatus.FAILED:  # If job has failed add error reason (if available)
            if 'Error reason' in self.job.metadata:
                self.info_widgets_list.append(
                    urwid.Text('Possible error reason: {}'.format(
                        self.job.metadata['Error reason'])))

        # Add button with the option available depending on the job status
        if self.job.status in [JobStatus.DONE, JobStatus.FAILED]:
            self.info_widgets_list.append(
                urwid.Padding(JobResubmitWidget(self.job,
                                                callback=self.resubmit),
                              align='center',
                              left=4,
                              right=2))
            self.info_widgets_list.append(urwid.Divider('-'))
        elif self.job.status != JobStatus.UNSUBMITTED:
            self.info_widgets_list.append(create_button(
                'Kill', self.terminate))
            self.info_widgets_list.append(urwid.Divider('-'))

        self.metadata_widgets_list = []
        self.metadata_widgets_list.append(
            urwid.Text('Retries: {}'.format(self.job.retries)))
        self.metadata_widgets_list.append(urwid.Divider())
        # Add resources requested by the job
        requested_resources = 'Specific requested resources:\n'
        requested_resources += '  ' + str(self.job.params).replace(
            '\n', '\n  ')
        self.metadata_widgets_list.append(urwid.Text(requested_resources))

        # If usage information is available, display it
        if 'usage' in self.job.metadata:
            self.metadata_widgets_list.append(urwid.Divider())
            used_resources = 'Used resources:\n'
            used_resources += "\n".join([
                "  {} = {}".format(k, v)
                for k, v in self.job.metadata['usage'].items()
            ])
            self.metadata_widgets_list.append(urwid.Text(used_resources))

        self.file_widgets_list = []  # Reset files widget
        # Create widget with the files if the job has failed
        if self.job.status == JobStatus.FAILED:
            # Generate wigets with stdout and stderr if available. Done here because Failed state is "absolute"=
            stdout_widget = self._load_file_as_widget(self.job.f_stdout,
                                                      'stdout')
            if stdout_widget is not None:
                self.file_widgets_list.append(stdout_widget)
                self.file_widgets_list.append(urwid.Divider('*'))
            stderr_widget = self._load_file_as_widget(self.job.f_stderr,
                                                      'stderr')
            if stderr_widget is not None:
                self.file_widgets_list.append(stderr_widget)
                self.file_widgets_list.append(urwid.Divider('*'))
    def __init__(self):

        # Variables used to build status line
        self.batteryVoltage = 0.00
        self.mqttHost = mqtt_server

        # Data list where points are put for bar graph plotting
        self.plotData = []

        # name,          foreground,    background,  mono         , foreground_high, background_high
        palette = [('body', 'black', 'light gray', 'standout'),
                   ('header', 'white', 'dark red', 'bold'),
                   ('screen edge', 'light blue', 'dark cyan'),
                   ('main shadow', 'dark gray', 'black'),
                   ('line', 'black', 'light gray', 'standout'),
                   ('bg background', 'light gray', 'black'),
                   ('bg 1', 'black', 'dark blue', 'standout'),
                   ('bg 1 smooth', 'dark blue', 'black'),
                   ('bg 2', 'black', 'dark cyan', 'standout'),
                   ('bg 2 smooth', 'dark cyan', 'black'),
                   ('button normal', 'light gray', 'dark blue', 'standout'),
                   ('button select', 'white', 'dark green'),
                   ('line', 'black', 'light gray', 'standout'),
                   ('pg normal', 'white', 'black', 'standout'),
                   ('pg complete', 'white', 'dark magenta'),
                   ('pg smooth', 'dark magenta', 'black'),
                   ('bigtext', 'dark green', 'dark red')]

        # Title
        txtTitle = urwid.BigText(("bigtext", "@alexmaswarrior fridge"),
                                 urwid.font.Thin6x6Font())
        txtTitleBox = urwid.Padding(txtTitle, "center", width="clip")
        txtTitleBox = urwid.Filler(txtTitleBox, "bottom")
        txtTitleBox = urwid.BoxAdapter(txtTitleBox, 7)
        titlePile = urwid.Pile([txtTitleBox])

        # Big temperature numerals
        self.txtTemperature = urwid.BigText("", urwid.font.HalfBlock7x7Font())
        txtTemperatureBox = urwid.Padding(self.txtTemperature,
                                          "center",
                                          width="clip")
        txtTemperatureBox = urwid.Filler(txtTemperatureBox, "bottom")
        txtTemperatureBox = urwid.BoxAdapter(txtTemperatureBox, 7)

        # Footer
        self.txtFooter = urwid.Text("MQTT Host:     Battery Voltage:")

        # History graph
        self.BarGraph = urwid.BarGraph(['bg background', 'bg 1', 'bg 2'])
        self.BarGraph.set_data([(0, ), (1, ), (2, )], 8)
        self.BarGraph.set_bar_width(1)
        BarGraphBox = urwid.Columns([("weight", 2, self.BarGraph)])
        BarGraphBox = urwid.Padding(self.BarGraph, ("fixed left", 1))
        BarGraphBox = urwid.BoxAdapter(BarGraphBox, 25)

        # put it together
        cols = urwid.Columns([txtTemperatureBox, BarGraphBox])
        fill = urwid.Filler(cols, "middle")

        frame = urwid.Frame(fill, header=titlePile, footer=self.txtFooter)
        frameLineBox = urwid.LineBox(frame,
                                     title="Refrigerator Display Thing",
                                     tlcorner="\u2554",
                                     tline="\u2550",
                                     lline="\u2551",
                                     trcorner="\u2557",
                                     blcorner="\u255A",
                                     rline="\u2551",
                                     bline="\u2550",
                                     brcorner="\u255d")

        screen = urwid.raw_display.Screen()
        screen.register_palette(palette)
        self.loop = urwid.MainLoop(frameLineBox, palette, screen=screen)

        # Gets the writing end of pipes to the UI event loop
        self.temperature_write_pipe = self.loop.watch_pipe(
            self.temperature_pipe_event)
        self.voltage_write_pipe = self.loop.watch_pipe(self.voltage_pipe_event)
Ejemplo n.º 8
0
    body = [urwid.Text(title), urwid.Divider()]
    for c in choices:
        button = urwid.Button(c)
        urwid.connect_signal(button, 'click', item_chosen, c)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))
    return urwid.ListBox(urwid.SimpleFocusListWalker(body))


def item_chosen(button, choice):
    response = urwid.Text([u'You chose ', choice, u'\n'])
    done = urwid.Button(u'Ok')
    urwid.connect_signal(done, 'click', exit_program)
    main.original_widget = urwid.Filler(
        urwid.Pile([response,
                    urwid.AttrMap(done, None, focus_map='reversed')]))


def exit_program(button):
    raise urwid.ExitMainLoop()


main = urwid.Padding(menu(u'Pythons', choices), left=2, right=2)
top = urwid.Overlay(main,
                    urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                    align='center',
                    width=('relative', 60),
                    valign='middle',
                    height=('relative', 60),
                    min_width=20,
                    min_height=9)
urwid.MainLoop(top, palette=[('reversed', 'standout', '')]).run()
Ejemplo n.º 9
0
def BigTxt(TXT):
    txt = urwid.BigText(TXT, urwid.font.HalfBlock5x4Font())
    view = urwid.Padding(txt, 'center', width='clip')
    view = urwid.AttrMap(view, 'body')
    return urwid.Columns([view])
Ejemplo n.º 10
0
    def refresh(self):
        with self.app.db.getSession() as session:
            change = session.getChange(self.change_key)
            # When we first open the change, update its last_seen
            # time.
            if not self.marked_seen:
                change.last_seen = datetime.datetime.utcnow()
                self.marked_seen = True
            self.topic = change.topic or ''
            self.pending_status_message = change.pending_status_message or ''
            reviewed = hidden = starred = held = ''
            if change.reviewed:
                reviewed = ' (reviewed)'
            if change.hidden:
                hidden = ' (hidden)'
            if change.starred:
                starred = '* '
            if change.held:
                held = ' (held)'
            self.title = '%sChange %s%s%s%s' % (starred, change.number,
                                                reviewed, hidden, held)
            self.app.status.update(title=self.title)
            self.project_key = change.project.key
            self.project_name = change.project.name
            self.change_rest_id = change.id
            self.change_id = change.change_id
            if change.owner:
                self.owner_email = change.owner.email
            else:
                self.owner_email = None

            self.change_id_label.text.set_text(
                ('change-data', change.change_id))
            self.owner_label.text.set_text(('change-data', change.owner_name))
            self.project_label.text.set_text(
                ('change-data', change.project.name))
            self.branch_label.set_text(('change-data', change.branch))
            self.topic_label.text.set_text(('change-data', self.topic))
            self.created_label.set_text(
                ('change-data', str(self.app.time(change.created))))
            self.updated_label.set_text(
                ('change-data', str(self.app.time(change.updated))))
            self.status_label.set_text(('change-data', change.status))
            self.permalink_url = urlparse.urljoin(self.app.config.url,
                                                  str(change.number))
            self.permalink_label.text.set_text(
                ('change-data', self.permalink_url))
            self.commit_message.set_text(change.revisions[-1].message)

            categories = []
            approval_headers = [urwid.Text(('table-header', 'Name'))]
            for label in change.labels:
                if label.category in categories:
                    continue
                approval_headers.append(
                    urwid.Text(('table-header', label.category)))
                categories.append(label.category)
            votes = mywid.Table(approval_headers)
            approvals_for_name = {}
            pending_message = change.revisions[-1].getPendingMessage()
            for approval in change.approvals:
                # Don't display draft approvals unless they are pending-upload
                if approval.draft and not pending_message:
                    continue
                approvals = approvals_for_name.get(approval.reviewer.name)
                if not approvals:
                    approvals = {}
                    row = []
                    if approval.reviewer.username == self.app.config.username:
                        style = 'reviewer-own-name'
                    else:
                        style = 'reviewer-name'
                    row.append(urwid.Text((style, approval.reviewer.name)))
                    for i, category in enumerate(categories):
                        w = urwid.Text(u'', align=urwid.CENTER)
                        approvals[category] = w
                        row.append(w)
                    approvals_for_name[approval.reviewer.name] = approvals
                    votes.addRow(row)
                if str(approval.value) != '0':
                    cat_min, cat_max = change.getMinMaxPermittedForCategory(
                        approval.category)
                    if approval.value > 0:
                        val = '+%i' % approval.value
                        if approval.value == cat_max:
                            val = ('max-label', val)
                        else:
                            val = ('positive-label', val)
                    else:
                        val = '%i' % approval.value
                        if approval.value == cat_min:
                            val = ('min-label', val)
                        else:
                            val = ('negative-label', val)
                    approvals[approval.category].set_text(val)
            votes = urwid.Padding(votes, width='pack')

            # TODO: update the existing table rather than replacing it
            # wholesale.  It will become more important if the table
            # gets selectable items (like clickable names).
            self.grid.contents[2] = (votes, ('given', 80))

            self.refreshDependencies(session, change)

            repo = gitrepo.get_repo(change.project.name, self.app.config)
            # The listbox has both revisions and messages in it (and
            # may later contain the vote table and change header), so
            # keep track of the index separate from the loop.
            listbox_index = self.listbox_patchset_start
            for revno, revision in enumerate(change.revisions):
                self.last_revision_key = revision.key
                row = self.revision_rows.get(revision.key)
                if not row:
                    row = RevisionRow(
                        self.app,
                        self,
                        repo,
                        revision,
                        expanded=(revno == len(change.revisions) - 1))
                    self.listbox.body.insert(listbox_index, row)
                    self.revision_rows[revision.key] = row
                row.update(revision)
                # Revisions are extremely unlikely to be deleted, skip
                # that case.
                listbox_index += 1
            if len(self.listbox.body) == listbox_index:
                self.listbox.body.insert(listbox_index, urwid.Divider())
            listbox_index += 1
            # Get the set of messages that should be displayed
            display_messages = []
            result_systems = {}
            for message in change.messages:
                if (message.revision == change.revisions[-1] and message.author
                        and message.author.name):
                    for commentlink in self.app.config.commentlinks:
                        results = commentlink.getTestResults(
                            self.app, message.message)
                        if results:
                            result_system = result_systems.get(
                                message.author.name, {})
                            result_systems[message.author.name] = result_system
                            result_system.update(results)
                skip = False
                if self.hide_comments and message.author and message.author.name:
                    for regex in self.app.config.hide_comments:
                        if regex.match(message.author.name):
                            skip = True
                            break
                if not skip:
                    display_messages.append(message)
            # The set of message keys currently displayed
            unseen_keys = set(self.message_rows.keys())
            # Make sure all of the messages that should be displayed are
            for message in display_messages:
                row = self.message_rows.get(message.key)
                if not row:
                    box = ChangeMessageBox(self.app, message)
                    row = urwid.Padding(box, width=80)
                    self.listbox.body.insert(listbox_index, row)
                    self.message_rows[message.key] = row
                else:
                    unseen_keys.remove(message.key)
                    if message.created != row.original_widget.message_created:
                        row.original_widget.refresh(message)
                listbox_index += 1
            # Remove any messages that should not be displayed
            for key in unseen_keys:
                row = self.message_rows.get(key)
                self.listbox.body.remove(row)
                del self.message_rows[key]
                listbox_index -= 1
        self._updateTestResults(result_systems)
Ejemplo n.º 11
0
 def __init__(self):
     self.table = StatisticsTable()
     self.widget = urwid.Padding(self.table, right=1)
Ejemplo n.º 12
0
    def __init__(self, app, change_key):
        super(ChangeView, self).__init__(urwid.Pile([]))
        self.log = logging.getLogger('gertty.view.change')
        self.app = app
        self.change_key = change_key
        self.revision_rows = {}
        self.message_rows = {}
        self.last_revision_key = None
        self.hide_comments = True
        self.marked_seen = False
        self.change_id_label = mywid.TextButton(u'',
                                                on_press=self.searchChangeId)
        self.owner_label = mywid.TextButton(u'', on_press=self.searchOwner)
        self.project_label = mywid.TextButton(u'', on_press=self.searchProject)
        self.branch_label = urwid.Text(u'', wrap='clip')
        self.topic_label = mywid.TextButton(u'', on_press=self.searchTopic)
        self.created_label = urwid.Text(u'', wrap='clip')
        self.updated_label = urwid.Text(u'', wrap='clip')
        self.status_label = urwid.Text(u'', wrap='clip')
        self.permalink_label = mywid.TextButton(u'',
                                                on_press=self.openPermalink)
        change_info = []
        change_info_map = {'change-data': 'focused-change-data'}
        for l, v in [
            ("Change-Id",
             urwid.Padding(urwid.AttrMap(self.change_id_label,
                                         None,
                                         focus_map=change_info_map),
                           width='pack')),
            ("Owner",
             urwid.Padding(urwid.AttrMap(self.owner_label,
                                         None,
                                         focus_map=change_info_map),
                           width='pack')),
            ("Project",
             urwid.Padding(urwid.AttrMap(self.project_label,
                                         None,
                                         focus_map=change_info_map),
                           width='pack')),
            ("Branch", self.branch_label),
            ("Topic",
             urwid.Padding(urwid.AttrMap(self.topic_label,
                                         None,
                                         focus_map=change_info_map),
                           width='pack')),
            ("Created", self.created_label),
            ("Updated", self.updated_label),
            ("Status", self.status_label),
            ("Permalink",
             urwid.Padding(urwid.AttrMap(self.permalink_label,
                                         None,
                                         focus_map=change_info_map),
                           width='pack')),
        ]:
            row = urwid.Columns([(12,
                                  urwid.Text(('change-header', l),
                                             wrap='clip')), v])
            change_info.append(row)
        change_info = urwid.Pile(change_info)
        self.commit_message = CommitMessageBox(app, u'')
        votes = mywid.Table([])
        self.depends_on = urwid.Pile([])
        self.depends_on_rows = {}
        self.needed_by = urwid.Pile([])
        self.needed_by_rows = {}
        self.conflicts_with = urwid.Pile([])
        self.conflicts_with_rows = {}
        self.related_changes = urwid.Pile(
            [self.depends_on, self.needed_by, self.conflicts_with])
        self.results = mywid.HyperText(
            u'')  # because it scrolls better than a table
        self.grid = mywid.MyGridFlow(
            [change_info, self.commit_message, votes, self.results],
            cell_width=80,
            h_sep=2,
            v_sep=1,
            align='left')
        self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([]))
        self._w.contents.append((self.app.header, ('pack', 1)))
        self._w.contents.append((urwid.Divider(), ('pack', 1)))
        self._w.contents.append((self.listbox, ('weight', 1)))
        self._w.set_focus(2)

        self.listbox.body.append(self.grid)
        self.listbox.body.append(urwid.Divider())
        self.listbox.body.append(self.related_changes)
        self.listbox.body.append(urwid.Divider())
        self.listbox_patchset_start = len(self.listbox.body)

        self.checkGitRepo()
        self.refresh()
        self.listbox.set_focus(3)
        self.grid.set_focus(1)
Ejemplo n.º 13
0
    def __init__(self, app, change_view, repo, revision, expanded=False):
        super(RevisionRow, self).__init__(urwid.Pile([]))
        self.app = app
        self.change_view = change_view
        self.revision_key = revision.key
        self.project_name = revision.change.project.name
        self.commit_sha = revision.commit
        self.can_submit = revision.can_submit
        self.title = mywid.TextButton(u'', on_press=self.expandContract)
        table = mywid.Table(columns=3)
        total_added = 0
        total_removed = 0
        for rfile in revision.files:
            if rfile.status is None:
                continue
            added = rfile.inserted or 0
            removed = rfile.deleted or 0
            total_added += added
            total_removed += removed
            table.addRow([
                urwid.Text(('filename', rfile.display_path), wrap='clip'),
                urwid.Text([('lines-added', '+%i' % (added, )), ', '],
                           align=urwid.RIGHT),
                urwid.Text(('lines-removed', '-%i' % (removed, )))
            ])
        table.addRow([
            urwid.Text(''),
            urwid.Text([('lines-added', '+%i' % (total_added, )), ', '],
                       align=urwid.RIGHT),
            urwid.Text(('lines-removed', '-%i' % (total_removed, )))
        ])
        table = urwid.Padding(table, width='pack')

        focus_map = {'revision-button': 'focused-revision-button'}
        self.review_button = ReviewButton(self)
        buttons = [
            self.review_button,
            mywid.FixedButton(('revision-button', "Diff"), on_press=self.diff),
            mywid.FixedButton(('revision-button', "Local Checkout"),
                              on_press=self.checkout),
            mywid.FixedButton(('revision-button', "Local Cherry-Pick"),
                              on_press=self.cherryPick)
        ]
        if self.can_submit:
            buttons.append(
                mywid.FixedButton(
                    ('revision-button', "Submit"),
                    on_press=lambda x: self.change_view.doSubmitChange()))

        buttons = [('pack', urwid.AttrMap(b, None, focus_map=focus_map))
                   for b in buttons]
        buttons = urwid.Columns(buttons + [urwid.Text('')], dividechars=2)
        buttons = urwid.AttrMap(buttons, 'revision-button')
        self.more = urwid.Pile([table, buttons])
        padded_title = urwid.Padding(self.title, width='pack')
        self.pile = urwid.Pile([padded_title])
        self._w = urwid.AttrMap(self.pile,
                                None,
                                focus_map=self.revision_focus_map)
        self.expanded = False
        self.update(revision)
        if expanded:
            self.expandContract(None)
Ejemplo n.º 14
0
symbols_display_box = urwid.Columns(
    [
        # Allot extra width to the symbol names list to create a neat layout.
        (max_symbol_name_length + 2, urwid.Pile(symbol_names_list)),
        # Allot 2 characters to the symbols list to accommodate symbols needing
        # double character-width to render.
        (2, urwid.Pile(symbols_list))
    ],
    dividechars=5)
columns_length = max_symbol_name_length + 10

line_box = urwid.LineBox(symbols_display_box,
                         title="Render Symbols",
                         title_attr='header')
info_box = urwid.Text(('footer', u" Exit: ^C (ctrl c)"), align='center')
display_box = urwid.Pile([line_box, info_box])

# Allot extra width to the display_box to render a neat layout.
body = urwid.Filler(urwid.Padding(display_box,
                                  width=columns_length + 5,
                                  align='center'),
                    valign='middle')


def main() -> None:
    try:
        loop = urwid.MainLoop(body, palette)
        loop.run()
    finally:
        sys.exit(0)
Ejemplo n.º 15
0
 def render(self, focus):
     opt = urwid.Text("\n" + self.text, align="left")
     opt = urwid.AttrWrap(opt, "title")
     opt = urwid.Padding(opt, align="center", width=40)
     return opt
Ejemplo n.º 16
0
    def __init__(self,
                 json_object,
                 preview_keys=['_t', 'severity', 'event_name', '__time__'],
                 print_key=None,
                 hidden=False,
                 meta=None):
        """
        :param json_object: object to display
        :param preview_keys: keys to show when object is collasped
        :param print_key: when nesting, print a key before this object
        :param hidden: true if object is collapsed by default
        :param meta: arbitrary data to store in this object
        """
        super(JsonObject, self).__init__([])
        self.meta = meta
        self.json = json_object
        self.print_key = print_key

        preview_text = "{ ... }"
        if type(self.json) is dict:
            preview_text = "{ "
            for key in preview_keys:
                if key in self.json:
                    preview_text += "{}: {}, ".format(key, self.json[key])
            preview_text += '... }'
        elif type(self.json) is list:
            preview_text = "[ ... ]"

        if print_key:
            preview_text = '{}: {}'.format(print_key, preview_text)

        self.hidden_item = urwid.Padding(urwid.Pile([JsonBox(preview_text)]),
                                         left=5)

        #self.json_item = walk_json(json_object, parent=urwid.Pile([]))
        widgets = []
        if type(self.json) is dict:
            widgets.append(
                urwid.AttrMap(
                    JsonBox((print_key + ": {") if print_key else '{'),
                    'json_row', 'json_row_h'))

        elif type(self.json) is list:
            widgets.append(
                urwid.AttrMap(
                    JsonBox((print_key + ": [") if print_key else '['),
                    'json_row', 'json_row_h'))

        if type(self.json) in [list, dict]:
            if type(self.json) is list:
                for item in self.json:
                    widgets.append(JsonObject(item))
            elif type(self.json) is dict:
                for key in sorted(self.json.keys()):
                    widgets.append(
                        JsonObject(self.json[key],
                                   hidden=type(self.json[key]) in [list, dict],
                                   print_key=key))

        else:  # plain value
            if type(self.json) == type(None):
                str_value = 'null'
            elif type(self.json) not in [int, float]:
                str_value = '"{}"'.format(self.json)
            else:
                str_value = self.json
            widgets.append(
                JsonBox('{}: {},'.format(print_key, str_value)
                        if print_key else '{},'.format(str(str_value))))

        if type(self.json) is dict:
            widgets.append(
                urwid.AttrMap(JsonBox('}'), 'json_row', 'json_row_h'))
        elif type(self.json) is list:
            widgets.append(
                urwid.AttrMap(JsonBox("]"), 'json_row', 'json_row_h'))
        self.json_item = urwid.Padding(urwid.Pile(widgets), left=5)

        self.is_hidden = hidden

        self.contents.append(
            ((self.hidden_item if hidden else self.json_item), ('weight', 1)))
Ejemplo n.º 17
0
    def __init__(self, callback=None, width=None, height=None, is_root=False):
        self.setup() # hook
        callback = callback or self._process

        self.is_root = is_root
        self.parent = application.app.get_widget()

        self.width = width or self.outer_width
        self.height = height or self.outer_height

        # I guess we want two containers - one for the widgets that contain
        # actual data, and a second one that holds wrapped widgets for insertion
        # into the dialog's listbox.
        self._display_widgets = []
        self._data_widgets = {}

        self.make_widgets()
        self.listbox = self.make_body_listbox()

        self.frame = TabFrame(self.listbox, focus_part=self.focus_part)

        header_items = [urwid.Text(self.title), urwid.Divider('\u2550')]
        self.title_widget = header_items[0]

        if self.messages:
            for i, msg in enumerate(self.messages):
                header_items.append(urwid.AttrWrap(urwid.Text(msg), self.message_style))
                if i+1 < len(self.messages):
                    header_items.append(urwid.Divider())

        self.frame.header = urwid.Pile(header_items)
        w = self.frame

        # pad area around listbox
        w = urwid.Padding(w, ('fixed left',2), ('fixed right',2))
        w = urwid.Filler(w, ('fixed top',1), ('fixed bottom',1))
        w = urwid.AttrWrap(w, 'body')

        w = urwid.LineBox(w)

        # "shadow" effect
        w = urwid.Columns( [w,('fixed', 1, urwid.AttrWrap(
            urwid.Filler(urwid.Text(('border',' ')), "top") ,'shadow'))])
        w = urwid.Frame( w, footer =
            urwid.AttrWrap(urwid.Text(('border',' ')),'shadow'))

        self.view = w

        if self.is_root:
            # this dialog is the main window
            # create outermost border area
            w = urwid.Padding(w, 'center', self.width )
            w = urwid.Filler(w, 'middle', self.height )
            w = urwid.AttrWrap( w, 'border' )
        else:
            # this dialog is a child window
            # overlay it over the parent window
            # I guess here he we need to fix up the use of the palette
            w = urwid.Overlay(w, self.parent, 'center', self.width+2, 'middle', self.height+2)
            w = urwid.AttrWrap(w, 'border')

        self.view = w

        self.add_exit_buttons()

        # Call WidgetWrap.__init__ to correctly initialize ourselves
        urwid.WidgetWrap.__init__(self, self.view)
        urwid.connect_signal(self, 'exit', callback)

        # set a flag that prevents closing twice
        self._dismissed = False
Ejemplo n.º 18
0
    def __init__(self, controller, num_files, total_size, q, ev_skip,
                 ev_suspend, ev_abort, ev_nodb, on_complete):
        self.controller = controller
        self.num_files = num_files
        self.total_size = total_size
        self.q = q
        self.ev_skip = ev_skip
        self.ev_suspend = ev_suspend
        self.ev_abort = ev_abort
        self.ev_nodb = ev_nodb
        self.on_complete = on_complete

        self.aborted = False

        self.current = urwid.Text(' ', layout=TildeLayout)
        w = urwid.Filler(self.current)
        w = urwid.LineBox(urwid.Padding(w, left=1, right=1),
                          'Delete',
                          title_attr='dialog_title',
                          bline='')
        top = urwid.Padding(w, left=1, right=1)

        self.files = urwid.Text(f'Files processed: 0/{self.num_files}',
                                layout=TildeLayout)
        self.time = urwid.Text(
            f'Time: {format_seconds(0)} ETA {format_seconds(0)}',
            layout=TildeLayout)
        self.progress = urwid.ProgressBar('dialog', 'progress', 0,
                                          (num_files or 1))
        w = urwid.Columns([(1, urwid.Text('[')), self.progress,
                           (1, urwid.Text(']'))])
        w = urwid.Pile([
            (1, urwid.Filler(w)),
            (1, urwid.Filler(self.files)),
            (1, urwid.Filler(self.time)),
        ])
        self.divider = urwid.LineBox(
            urwid.Padding(w, left=1, right=1),
            f'Total: {human_readable_size(0)}/{human_readable_size(self.total_size)}',
            tlcorner='├',
            trcorner='┤',
            bline='')
        middle = urwid.Padding(self.divider, left=1, right=1)

        self.btn_skip = urwid.Button('Skip', lambda x: self.on_skip())
        attr_btn_skip = urwid.AttrMap(self.btn_skip, 'dialog', 'dialog_focus')
        self.btn_suspend = urwid.Button('Suspend', lambda x: self.on_suspend())
        attr_btn_suspend = urwid.AttrMap(self.btn_suspend, 'dialog',
                                         'dialog_focus')
        self.btn_abort = urwid.Button('Abort', lambda x: self.on_abort())
        attr_btn_abort = urwid.AttrMap(self.btn_abort, 'dialog',
                                       'dialog_focus')
        self.btn_nodb = urwid.Button('No DB', lambda x: self.on_nodb())
        attr_btn_nodb = urwid.AttrMap(self.btn_nodb, 'dialog', 'dialog_focus')
        w = urwid.Columns([
            urwid.Divider(' '), (8, attr_btn_skip), (1, urwid.Text(' ')),
            (12, attr_btn_suspend), (1, urwid.Text(' ')), (9, attr_btn_abort),
            (1, urwid.Text(' ')), (9, attr_btn_nodb),
            urwid.Divider(' ')
        ])
        w = urwid.LineBox(urwid.Filler(w), tlcorner='├', trcorner='┤')
        bottom = urwid.Padding(w, left=1, right=1)

        w = urwid.Pile([
            (1, urwid.Filler(urwid.Text(' '))),
            (2, top),
            (4, middle),
            (3, bottom),
            (1, urwid.Filler(urwid.Text(' '))),
        ])
        w = urwid.AttrMap(w, 'dialog')

        super().__init__(w)
Ejemplo n.º 19
0
    def __init__(self, execution_manager):
        self.execution_manager = execution_manager

        # Create layout

        # Menu layout
        self.menu = urwid.BoxAdapter(None, 20)
        # Menu structure
        self.menu_structure = {
            'main':
            (None, [('Jobs', self.show_menu, 'jobs'),
                    ('Change max running', self.change_max_running),
                    ('Stop/continue submission', self.show_menu, 'terminate'),
                    ('Resubmit failed', self.resubmit_failed),
                    ('Update metadata files', self.metadata_update),
                    ('Exit', self.show_menu, 'exit')]),
            'jobs': ('main', []),
            'terminate':
            ('main', [('Stop submission', self.halt),
                      ('Cancel running and stop submission', self.terminate)]),
            'exit': ('main', [('Submit & exit', self.submit_and_exit),
                              ('Exit', self.exit)])
        }
        # Add the groups
        job_groups = JOB_STATUS_VALUES
        for group in job_groups:
            self.menu_structure['jobs'][1].append(
                (group.title(), self.show_group, group))

        self.previous_menu = None

        # Manager status (progress bar and group counts)
        self.execution_status_widget = ExecutionStatusWidget(
            self.execution_manager.status)
        # Extra info for the run (max running, running/halted ...)
        self.execution_info_widget = ExecutionInfoWidget(
            self.execution_manager)

        # Widget that wraps the "changeable" data. Moves from cluster info to job info
        self.details = urwid.Padding(None, align='center', left=2,
                                     right=2)  # workaround

        # The cluster widget is only one. The jobs we create them on demand
        self.cluster_widget = ClusterWidget()

        # Initialize empty widgets
        self.show_menu(None, 'main')
        self.details.original_widget = UpdatablePile(
            [self.cluster_widget,
             ExecutionParameters(self.execution_manager)])

        output_path = urwid.AttrMap(
            urwid.Text('Out: ' +
                       path.abspath(self.execution_manager.out_folder)),
            'folder')

        self.widget = urwid.Filler(
            urwid.Columns([("fixed", 50, self.menu),
                           ("weight", 0.6,
                            urwid.Padding(urwid.Pile([
                                output_path,
                                urwid.Divider(), self.execution_status_widget,
                                self.execution_info_widget,
                                urwid.Divider(), self.details
                            ]),
                                          align='center',
                                          left=2,
                                          right=2))]))

        BaseTimedWidgetWrap.__init__(self, self.widget)

        # If the execution is halted (due to reattach) update the corresponding widget
        if not self.execution_manager.is_submission_enabled:
            self.halt(None)
Ejemplo n.º 20
0
    def main_view(self) -> List[Any]:

        # Recipient Header
        if self.need_recipient_header():
            if self.message['type'] == 'stream':
                recipient_header = self.stream_header()
            else:
                recipient_header = self.private_header()
        else:
            recipient_header = None

        # Content Header
        message = {
            key: {
                'is_starred':
                'starred' in msg['flags'],
                'author': (msg['sender_full_name']
                           if 'sender_full_name' in msg else None),
                'time':
                (self._time_for_message(msg) if 'timestamp' in msg else None),
                'datetime': (datetime.fromtimestamp(msg['timestamp'])
                             if 'timestamp' in msg else None),
            }
            for key, msg in dict(this=self.message,
                                 last=self.last_message).items()
        }
        different = {  # How this message differs from the previous one
            'recipients': recipient_header is not None,
            'author': message['this']['author'] != message['last']['author'],
            '24h': (message['last']['datetime'] is not None
                    and ((message['this']['datetime']
                          - message['last']['datetime'])
                         .days)),
            'timestamp': (
                message['last']['time'] is not None
                and message['this']['time'] != message['last']['time']
            ),
            'star_status': (
                message['this']['is_starred'] != message['last']['is_starred']
            ),
        }
        any_differences = any(different.values())

        if any_differences:  # Construct content_header, if needed
            TextType = Dict[str, Tuple[Optional[str], str]]
            text_keys = ('author', 'star', 'time')
            text = {key: (None, ' ') for key in text_keys}  # type: TextType

            if any(different[key] for key in ('recipients', 'author', '24h')):
                text['author'] = ('name', message['this']['author'])
            if message['this']['is_starred']:
                text['star'] = ('starred', "*")
            if any(different[key]
                   for key in ('recipients', 'author', 'timestamp')):
                this_year = date.today().year
                msg_year = message['this']['datetime'].year
                if this_year != msg_year:
                    text['time'] = ('time',
                                    '{} - {}'.format(msg_year,
                                                     message['this']['time']))
                else:
                    text['time'] = ('time', message['this']['time'])

            content_header = urwid.Columns([
                ('weight', 10, urwid.Text(text['author'])),
                (23, urwid.Text(text['time'], align='right')),
                (1, urwid.Text(text['star'], align='right')),
            ],
                                           dividechars=1)
        else:
            content_header = None

        # If the message contains '/me' emote then replace it with
        # sender's full name and show it in bold.
        if self.message['is_me_message']:
            self.message['content'] = self.message['content'].replace(
                '/me',
                '<strong>' + self.message['sender_full_name'] + '</strong>', 1)

        # Transform raw message content into markup (As needed by urwid.Text)
        active_char = '▒'  # Options are '█', '▓', '▒', '░'
        content = self.transform_content()

        if self.message['id'] in self.model.index['edited_messages']:
            edited_label_size = 7
            left_padding = 1
        else:
            edited_label_size = 0
            left_padding = 8

        content = urwid.Padding(urwid.Columns([
            (edited_label_size, urwid.Text('EDITED')),
            urwid.LineBox(urwid.Columns([
                (1, urwid.Text('')),
                urwid.Text(content),
            ]),
                          tline='',
                          bline='',
                          rline='',
                          lline=active_char)
        ]),
                                align='left',
                                left=left_padding,
                                width=('relative', 100),
                                min_width=10,
                                right=5)

        # Reactions
        reactions = self.reactions_view(self.message['reactions'])

        # Build parts together and return
        parts = [
            (recipient_header, recipient_header is not None),
            (content_header, any_differences),
            (content, True),
            (reactions, reactions != ''),
        ]
        return [part for part, condition in parts if condition]
Ejemplo n.º 21
0
 def __init__(self, conversation_list, on_select, keybindings):
     list_walker = ConversationListWalker(conversation_list, on_select)
     list_box = ListBox(keybindings, list_walker)
     widget = urwid.Padding(list_box, left=2, right=2)
     super().__init__(widget)
Ejemplo n.º 22
0
# ALL                                                                        #
##############################################################################

# pile = urwid.Pile([
#   ('pack', top_grid),
#   ('weight',12, urwid.LineBox(mid_pile)),
#   ('weight',12, urwid.LineBox(msg_widget)),
#   ('pack', bot_field)
# ])

div = urwid.Divider(u'\N{BOX DRAWINGS LIGHT HORIZONTAL}')
div = urwid.AttrMap(div, 'div')
blankdiv = urwid.Divider(u' ')
bpile = urwid.Pile([])
pile = urwid.AttrMap(bpile, 'body')
msg_header = urwid.Padding(text('...', 'dark_gray_on_black'))
msg_container = urwid.Padding(msg_widget, left=1, right=1)

# pile.contents.append((urwid.Padding(div, left=20, right=20), ('pack', None)))
bpile.contents.append((blankdiv, ('pack', None)))
bpile.contents.append((top_line1, ('pack', None)))
bpile.contents.append((blankdiv, ('pack', None)))
bpile.contents.append((top_line2, ('pack', None)))
bpile.contents.append((div, ('pack', None)))
bpile.contents.append((mid_table, ('pack', None)))
bpile.contents.append((div, ('pack', None)))
bpile.contents.append((msg_header, ('pack', None)))
bpile.contents.append((msg_container, ('weight', 1)))
bpile.contents.append((div, ('pack', None)))
# bpile.contents.append((input_field, ('pack', None)))
Ejemplo n.º 23
0
#import urwid.curses_display
import urwid as u

from urwid import MainLoop, SolidFill

caption = u.Text(('caption', 'Enter some words:'), align='center')
input = u.Edit(multiline=False)
# Will be set from the code
scratchpad = u.Text('')
button = u.Button('Push me')
button_wrap = u.Padding(u.AttrMap(button, 'button.normal', 'button.focus'),
                        align='center',
                        width=15)
interior = u.Filler(u.Pile())

window = u.LineBox(interior)
single_color = [('basic', 'yellow', 'dark blue')]

topw = u.Overlay(window, background, 'center', 30, 'middle', 10)
main_loop = MainLoop(topw, palette=single_color)
main_loop.run()

#def callback(key):
#    raise ExitMainLoop()
#

#mainloop = MainLoop(u.AttrMap(SolidFill('#'),
#'basic'), palette=single_color).run()

#b = u.Button(u"cancel")
#b.render((15,), focus = True).text
Ejemplo n.º 24
0
    def __init__(self,
                 items=None,
                 default=None,
                 label=None,
                 border=False,
                 scrollbar=False,
                 margin=None,
                 left_chars=None,
                 right_chars=None,
                 left_chars_top=None,
                 right_chars_top=None,
                 auto_complete=False,
                 keymap={}):

        # raise Exception(self.KEYMAP_SCOPE)
        if items is not None:
            self._items = items

        self.default = default
        self.label = label
        self.border = border
        self.scrollbar = scrollbar
        self.auto_complete = auto_complete
        # self.keymap = keymap

        if margin:
            self.margin = margin

        if isinstance(self.items, list):
            if len(self.items):
                if isinstance(self.items[0], tuple):
                    self._items = AttrDict(self.items)
                else:
                    logger.debug(self.items)
                    self._items = AttrDict(
                        ((item, n) for n, item in enumerate(self.items)))
            else:
                self._items = AttrDict()

        self.button = DropdownItem(
            u"",
            None,
            margin=self.margin,
            left_chars=left_chars_top if left_chars_top else left_chars,
            right_chars=right_chars_top if right_chars_top else right_chars)

        self.pop_up = DropdownDialog(
            self,
            self._items,
            self.default,
            label=self.label,
            border=self.border,
            margin=self.margin,
            left_chars=left_chars,
            right_chars=right_chars,
            auto_complete=self.auto_complete,
            scrollbar=scrollbar,
            # keymap = self.KEYMAP
        )

        urwid.connect_signal(self.pop_up, "select",
                             lambda souce, selection: self.select(selection))

        urwid.connect_signal(self.pop_up, "close",
                             lambda button: self.close_pop_up())

        if self.default:
            try:
                self.select_value(self.default)
            except StopIteration:
                self.focus_position = 0

        if len(self):
            self.select(self.selection)
        else:
            self.button.set_label(("dropdown_text", self.empty_label))

        cols = [(self.button_width, self.button)]

        if self.label:
            cols[0:0] = [
                ("pack", urwid.Text([("dropdown_label", "%s: " % (self.label))
                                     ])),
            ]
        self.columns = urwid.Columns(cols, dividechars=0)

        w = self.columns
        if self.border:
            w = urwid.LineBox(self.columns)
        w = urwid.Padding(w, width=self.width)

        super(Dropdown, self).__init__(w)
        urwid.connect_signal(self.button, 'click',
                             lambda button: self.open_pop_up())
Ejemplo n.º 25
0
def return_to_main(button):
    main.original_widget = urwid.Padding(menu(u'RetroXRBWallet', choices),
                                         left=2,
                                         right=2)
Ejemplo n.º 26
0
    def build(self, ui):
        self.ui = ui

        track = self.ui.player.getTrack()

        trackName = ''
        if (track != None):
            trackName = '{name} ({artists})'.format(
                name=track.title,
                artists=','.join(map(lambda a: a.name, track._artists)))

        statusText = 'Онлайн'
        if (not self.ui.repository.online):
            statusText = 'Оффлайн'

        loopText = ''
        if (self.ui.player.loop):
            loopText = '🔁  On (F7)'
        else:
            loopText = '🔁  (F7)'

        return urwid.LineBox(
            urwid.Pile([
                urwid.Columns([
                    urwid.Padding(urwid.AttrMap(urwid.Text(trackName),
                                                'greenColor'),
                                  right=3),
                    urwid.ProgressBar('progressbar.b', 'progressbar.a',
                                      self.ui.player.currentPosition * 100)
                ]),
                urwid.Columns([
                    urwid.Pile([
                        UiButton('Сейчас играет', self.on_playlist),
                        UiButton(statusText, on_press=self.toggle_offline),
                        urwid.Text('DL: ' +
                                   str(len(self.ui.downloader.queue))),
                    ]),
                    urwid.Text(' '),
                    urwid.Pile([
                        urwid.AttrMap(UiButton('▶  (F1)', on_press=self.play),
                                      'greenColor'),
                        urwid.AttrMap(UiButton('⏸  (F2)', on_press=self.pause),
                                      'yellowColor'),
                        urwid.AttrMap(UiButton('⏹  (F3)', on_press=self.stop),
                                      'redColor'),
                    ]),
                    urwid.Text(' '),
                    urwid.Pile([
                        UiButton('⏮  (F4)', on_press=self.prevTrack),
                        UiButton('⏭  (F5)', on_press=self.nextTrack),
                        UiButton('🔀 (F6)', on_press=self.shuffle)
                    ]),
                    urwid.Text(' '),
                    urwid.Pile([
                        UiButton(loopText, on_press=self.loop),
                        UiButton(self.getLikeDislikeText(track),
                                 on_press=self.on_like_press,
                                 user_data=track),
                        UiButton(self.getLikeDislikeText(track, True),
                                 on_press=self.on_dislike_press,
                                 user_data=track),
                    ])

                    #UiButton('Like'),
                    #UiButton('Dislike'),
                ])
            ]),
            title='Player')
Ejemplo n.º 27
0
                            datetime.datetime.now().strftime("%H:%M:%S") +
                            '\n')
    totalErrorStatus = urwid.Text("Total validation errors: -1\n")
    usbErrorStatus = urwid.Text("Total USB errors: -1\n")
    applications = []
    applicationStatus = urwid.Text("No application is running\n")
    #pid = os.getpid()
    pid = getNewLogName()
    stopNext = urwid.Button('Stop')
    currentDataFile = urwid.Text('data/counter.dat')
    outputMessage = urwid.Text('\n----Application Output----\n')
    usbStatus = urwid.Text("USB controller status (Should be 2): Unknown\n")
    promStatus = urwid.Text("Prom status: Unknown\n")
    askLog = urwid.Edit(("Enter text\n"))

    main = urwid.Padding(menu(), left=2, right=2)

    top = urwid.Overlay(main,
                        urwid.SolidFill(u'\N{MEDIUM SHADE}'),
                        align='center',
                        width=('relative', 80),
                        valign='middle',
                        height=('relative', 90),
                        min_width=20,
                        min_height=9)

    topFocus = top.get_focus_path()
    main_loop = urwid.MainLoop(top, palette=[('reversed', 'standout', '')])
    main_loop.set_alarm_in(1, refresh)
    main_loop.run()
Ejemplo n.º 28
0
    def __init__(self, master):
        self.master = master
        self.lb = select.Select([
            select.Heading("Traffic Manipulation"),
            select.Option("Header Set Patterns", "H",
                          checker("setheaders", master.options),
                          self.setheaders),
            select.Option("Ignore Patterns", "I",
                          checker("ignore_hosts", master.options),
                          self.ignore_hosts),
            select.Option("Replacement Patterns", "R",
                          checker("replacements", master.options),
                          self.replacepatterns),
            select.Option("Scripts", "S", checker("scripts", master.options),
                          self.scripts),
            select.Heading("Interface"),
            select.Option("Default Display Mode", "M",
                          checker("default_contentview", master.options),
                          self.default_displaymode),
            select.Option("Palette", "P", checker("palette", master.options),
                          self.palette),
            select.Option("Show Host", "w", checker("showhost",
                                                    master.options),
                          master.options.toggler("showhost")),
            select.Heading("Network"),
            select.Option("No Upstream Certs", "U",
                          checker("no_upstream_cert", master.options),
                          master.options.toggler("no_upstream_cert")),
            select.Option("TCP Proxying", "T",
                          checker("tcp_hosts", master.options),
                          self.tcp_hosts),
            select.Option("Don't Verify SSL/TLS Certificates", "V",
                          checker("ssl_insecure", master.options),
                          master.options.toggler("ssl_insecure")),
            select.Heading("Utility"),
            select.Option("Anti-Cache", "a",
                          checker("anticache", master.options),
                          master.options.toggler("anticache")),
            select.Option("Anti-Compression", "o",
                          checker("anticomp", master.options),
                          master.options.toggler("anticomp")),
            select.Option("Kill Extra", "x",
                          checker("replay_kill_extra", master.options),
                          master.options.toggler("replay_kill_extra")),
            select.Option("No Refresh", "f",
                          checker("refresh_server_playback", master.options),
                          master.options.toggler("refresh_server_playback")),
            select.Option("Sticky Auth", "A",
                          checker("stickyauth", master.options),
                          self.sticky_auth),
            select.Option("Sticky Cookies", "t",
                          checker("stickycookie", master.options),
                          self.sticky_cookie),
        ])
        title = urwid.Text("Options")
        title = urwid.Padding(title, align="left", width=("relative", 100))
        title = urwid.AttrWrap(title, "heading")
        w = urwid.Frame(self.lb, header=title)
        super().__init__(w)

        self.master.loop.widget.footer.update("")
        signals.update_settings.connect(self.sig_update_settings)
        master.options.changed.connect(self.sig_update_settings)
Ejemplo n.º 29
0
def goto_menu(button):
    main.original_widget = urwid.Padding(menu(), left=0, right=0)
Ejemplo n.º 30
0
    def create_view(self) -> urwid.Widget:
        p2 = lambda w: urwid.Padding(w, left=2)

        self.class_widget = CompetitionClassSelectorWidget(self, self.competition)
        urwid.connect_signal(self.class_widget, "change", self._on_class_changed)

        self.task_widget = TaskDownloadWidget(self, self.competition)
        urwid.connect_signal(self.task_widget, "download", self._on_download_task)

        self.airspace_group: List[urwid.Widget] = []
        self.airspace_pile = urwid.Pile(
            [
                self._make_file_radio(
                    sf,
                    self.airspace_group,
                    sf.name == self.competition.airspace,
                    self._on_airspace_changed,
                )
                for sf in self.airspaces
            ]
        )

        self.waypoint_group: List[urwid.Widget] = []
        self.waypoint_pile = urwid.Pile(
            [
                self._make_file_radio(
                    sf,
                    self.waypoint_group,
                    sf.name == self.competition.waypoints,
                    self._on_waypoint_changed,
                )
                for sf in self.waypoints
            ]
        )

        self.profile_pile = urwid.Pile(
            [self._make_profile_checkbox(prf) for prf in self.profiles]
        )

        self.download_status = urwid.Text("")

        form = urwid.Pile(
            [
                self.class_widget,
                urwid.Divider(),
                self.task_widget,
                urwid.Divider(),
                self.download_status,
                urwid.Divider(),
                urwid.Text("Airspace files"),
                p2(self.airspace_pile),
                urwid.Divider(),
                urwid.Text("Waypoint files"),
                p2(self.waypoint_pile),
                urwid.Divider(),
                urwid.Text("XCSoar profiles"),
                p2(self.profile_pile),
                urwid.Divider(),
                self._create_buttons(),
                urwid.Divider(),
                self._create_credits(),
            ]
        )

        filler = urwid.Filler(form, valign=urwid.TOP)

        self.status = widget.CMFlashMessage(self)

        return urwid.Frame(
            widget.CMScreenPadding(filler),
            header=widget.CMScreenHeader(self.competition.title),
            footer=widget.CMScreenPadding(self.status),
        )