def read(filename, align='left'):
def line_process(line):
return urwid.AttrMap(urwid.Text(map(pixel_process, line), wrap='clip', align=align), 'pic')
path = getattr(sys, '_MEIPASS', None)
if path:
path = os.path.join(path, 'data/%s' % filename)
else:
path = pkg_resources.resource_filename(__name__, 'data/%s' % filename)
with open(path, 'r') as file_to_read:
bytes_read = file_to_read.read()
img_size = {"width":ord(bytes_read[18]), "height":ord(bytes_read[22])}
bmp = {"complete": len(bytes_read),
"content": img_size["width"] * img_size["height"] * 3,
"line_size": img_size["width"] * 3}
pic = []
for i in range(bmp["complete"] - bmp["content"], bmp["complete"], bmp["line_size"]):
raw_line = bytes_read[i:i + bmp["line_size"]]
row = []
for j in range(0, bmp["line_size"], 3):
raw_pixel = raw_line[j:j + 3][::-1]
color = '#' + ''.join(map(round_compo, raw_pixel))
row.append(color)
pic.append(row)
return urwid.Pile(map(line_process, pic[::-1]))
python类Pile()的实例源码
def __init__(self, cards, onclick=None, index=0, on_double_click=None):
self.cards = cards
self.onclick = onclick
self.on_double_click = on_double_click
self.pile = urwid.Pile([])
self._update_pile()
self.index = index
super(CardPileWidget, self).__init__(self.pile)
def __init__(self):
self.top_string = urwid.Text('')
self.bottom_string = urwid.Text('')
self.small_blinks = urwid.Filler(self.top_string, 'top')
self.large_blinks = ('weight', 10, urwid.Filler(self.bottom_string, 'top'))
self.default_widget = urwid.LineBox(
urwid.Pile([
self.large_blinks
]),
title='Websockets'
)
def __init__(self, *args, **kwargs):
self.start = urwid.Edit('Start: ')
self.end = urwid.Edit('End: ')
self.server = kwargs["server"]
self.calendar = kwargs["calendar"]
del(kwargs['server'])
del(kwargs["calendar"])
print (self.server, self.calendar)
div = urwid.Divider()
self.msg = urwid.Edit(caption="Event message: ", edit_text='', multiline=True)
button_save = urwid.Button('save')
urwid.connect_signal(button_save, 'click', self.on_save)
self.pile = urwid.Pile([self.start,
self.end,
div,
self.msg,
div,
button_save])
super(EventWidget, self).__init__(self.pile, *args, **kwargs)
def __init__(self):
close_button = urwid.Button("that's pretty cool")
urwid.connect_signal(close_button, 'click',
lambda button:self._emit("close"))
pile = urwid.Pile([urwid.Text(
"^^ I'm attached to the widget that opened me. "
"Try resizing the window!\n"), close_button])
fill = urwid.Filler(pile)
self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))
def __init__(self, pubpen):
self.pubpen = pubpen
username_label = urwid.Text('Username: ', align='right')
password_label = urwid.Text('Password: ', align='right')
self.username = urwid.Edit()
self.password = urwid.Edit()
login_button = urwid.Button('Login')
decorated_login_button = urwid.AttrMap(login_button, None, focus_map='reversed')
quit_button = urwid.Button('Quit')
decorated_quit_button = urwid.AttrMap(quit_button, None, focus_map='reversed')
buttons = urwid.Columns((
(len('Login') + 4, decorated_login_button),
(len('Quit') + 4, decorated_quit_button),
), focus_column=1)
labels = urwid.Pile([username_label, password_label])
self.fields = urwid.Pile([self.username, self.password, buttons],
focus_item=0)
entry_box = urwid.Columns([labels, self.fields])
self.status_message = urwid.Text(' ', align='center')
entry_with_status = urwid.Pile([entry_box, self.status_message])
padded_entry_with_status = urwid.Padding(entry_with_status, align='center')
self.display = urwid.Filler(padded_entry_with_status, valign='middle')
decorate = urwid.LineBox(self.display)
super().__init__(decorate)
self.focusable_widgets = (w for w in itertools.cycle((
((self.fields, 1),),
((self.fields, 2), (buttons, 0)),
((self.fields, 2), (buttons, 1)),
((self.fields, 0),)
)))
urwid.connect_signal(login_button, 'click', self.attempt_login)
urwid.connect_signal(quit_button, 'click', self.quit)
self.pubpen.subscribe('user.login_success', self.handle_login_success)
self.pubpen.subscribe('user.login_failure', self.handle_login_failure)
def __init__(self, pubpen):
self.pubpen = pubpen
#
# Always displayed widgets
#
self.menu_bar_window = MenuBarWindow(self.pubpen)
self.info_window = InfoWindow(self.pubpen)
self.main_window = MainWindow(self.pubpen)
self.msg_window = MessageWindow(self.pubpen)
pile = urwid.Pile((self.main_window,
(self.msg_window.height, self.msg_window),
))
cols = urwid.Columns((pile, (15, self.info_window)))
layout = urwid.Pile((
('pack', self.menu_bar_window),
('weight', 1, cols),
))
self.top = urwid.Frame(layout)
super().__init__(self.top)
tline = self.tline_widget[0]
self.status_bar = StatusBar(self.pubpen, spacer=tline.div_char)
self.tline_widget.contents.clear()
self.tline_widget.contents.extend((
(tline, self.tline_widget.options('given', 1, False)),
(self.status_bar, self.tline_widget.options('weight', 1, False)),
(tline, self.tline_widget.options('given', 1, False)),
))
def __init__(self, app, title, current_key, values):
self.app = app
rows = []
self.key = None
self.value = None
for key, value in values():
button = SearchSelectInnerButton(key, value)
urwid.connect_signal(button, 'click',
lambda b:self.onSelected(b))
rows.append(button)
pile = urwid.Pile(rows)
fill = urwid.Filler(pile, valign='top')
super(SearchSelectDialog, self).__init__(urwid.LineBox(fill, title))
def __init__(self, app):
self.app = app
save_button = mywid.FixedButton(u'Save')
cancel_button = mywid.FixedButton(u'Cancel')
urwid.connect_signal(save_button, 'click',
lambda button:self._emit('save'))
urwid.connect_signal(cancel_button, 'click',
lambda button:self._emit('cancel'))
rows = []
buttons = [('pack', save_button),
('pack', cancel_button)]
buttons = urwid.Columns(buttons, dividechars=2)
self.project_button = ProjectButton(self.app)
self.status_button = StatusButton(self.app)
self.assignee_button = AssigneeButton(self.app)
self.title_field = mywid.MyEdit(u'', edit_text=u'', ring=app.ring)
for (label, w) in [
(u'Project:', ('pack', self.project_button)),
(u'Title:', self.title_field),
(u'Status:', ('pack', self.status_button)),
(u'Assignee:', ('pack', self.assignee_button)),
]:
row = urwid.Columns([(12, urwid.Text(label)), w])
rows.append(row)
rows.append(urwid.Divider())
rows.append(buttons)
pile = urwid.Pile(rows)
fill = urwid.Filler(pile, valign='top')
super(NewTaskDialog, self).__init__(urwid.LineBox(fill, 'New Task'))
def __init__(self, app, query, query_desc=None, project_key=None,
active=False, sort_by=None, reverse=None):
super(StoryListView, self).__init__(urwid.Pile([]))
self.log = logging.getLogger('boartty.view.story_list')
self.searchInit()
self.app = app
self.query = query
self.query_desc = query_desc or query
self.active = active
self.story_rows = {}
self.enabled_columns = set()
for colinfo in COLUMNS:
if (colinfo.name in self.required_columns or
colinfo.name not in self.optional_columns):
self.enabled_columns.add(colinfo.name)
self.disabled_columns = set()
self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([]))
self.project_key = project_key
if 'Project' not in self.required_columns and project_key is not None:
self.enabled_columns.discard('Project')
self.disabled_columns.add('Project')
#storyboard: creator
if 'Owner' not in self.required_columns and 'owner:' in query:
# This could be or'd with something else, but probably
# not.
self.enabled_columns.discard('Owner')
self.disabled_columns.add('Owner')
self.sort_by = sort_by or app.config.story_list_options['sort-by']
if reverse is not None:
self.reverse = reverse
else:
self.reverse = app.config.story_list_options['reverse']
self.header = StoryListHeader(self.enabled_columns)
self.refresh()
self._w.contents.append((app.header, ('pack', 1)))
self._w.contents.append((urwid.Divider(), ('pack', 1)))
self._w.contents.append((urwid.AttrWrap(self.header, 'table-header'), ('pack', 1)))
self._w.contents.append((self.listbox, ('weight', 1)))
self._w.set_focus(3)
def __init__(self, app, board_key):
super(BoardView, self).__init__(urwid.Pile([]))
self.log = logging.getLogger('boartty.view.board')
self.searchInit()
self.app = app
self.board_key = board_key
self.worklist_keys = set()
self.title_label = urwid.Text(u'', wrap='clip')
self.description_label = urwid.Text(u'')
board_info = []
board_info_map={'story-data': 'focused-story-data'}
for l, v in [("Title", self.title_label),
("Description", self.description_label),
]:
row = urwid.Columns([(12, urwid.Text(('story-header', l), wrap='clip')), v])
board_info.append(row)
board_info = urwid.Pile(board_info)
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(board_info)
self.listbox.body.append(urwid.Divider())
self.listbox_board_start = len(self.listbox.body)
lane_columns = urwid.Columns([], dividechars=1)
self.listbox.body.append(lane_columns)
self.lane_manager = mywid.ListUpdateManager(lane_columns)
self.refresh()
self.listbox.set_focus(1)
def makeFrame(self, data):
"""
Returns a new frame that is formatted correctly with respect to the window's dimensions.
:param data: tuple of (answers, question_title, question_desc, question_stats, question_url)
:return: a new urwid.Frame object
"""
answers, question_title, question_desc, question_stats, question_url = data
self.data = data
self.question_desc = question_desc
self.url = question_url
self.answer_text = AnswerText(answers)
self.screenHeight, screenWidth = subprocess.check_output(['stty', 'size']).split()
self.question_text = urwid.BoxAdapter(QuestionDescription(question_desc), int(max(1, (int(self.screenHeight) - 9) / 2)))
answer_frame = urwid.Frame(
header= urwid.Pile( [
header_for_display,
QuestionTitle(question_title),
self.question_text,
QuestionStats(question_stats),
urwid.Divider('-')
]),
body=self.answer_text,
footer= urwid.Pile([
QuestionURL(question_url),
UnicodeText(u'\u2191: previous answer, \u2193: next answer, o: open in browser, \u2190: back')
])
)
return answer_frame
def set_answer(self):
"""
We must use a box adapter to get the text to scroll when this widget is already in
a Pile from the main question page. Scrolling is necessary for long answers which are longer
than the length of the terminal.
"""
self.content = [('less-important', 'Answer: ')] + self.answers[self.index].split("\n")
self._w = ScrollableTextBox(self.content)
def set_description(self):
"""
We must use a box adapter to get the text to scroll when this widget is already in
a Pile from the main question page. Scrolling is necessary for long questions which are longer
than the length of the terminal.
"""
self.content = self.description.strip("\n").split("\n")
self._w = ScrollableTextBox(self.content)
def __init__(self, discord_client, chat_widget):
self.discord = discord_client
self.ui = self.discord.ui
self.chat_widget = chat_widget
self.editing = None
self.edit = urwid.Edit(multiline=True, allow_tab=True)
self.edit.keypress = self._edit_keypress
self.w_lb = urwid.LineBox(urwid.Padding(self.edit, left=1, right=1))
self.w_text = urwid.Text("")
self.w_typing = TypingList(self)
self.pile = urwid.Pile([])
self.hide_channel_selector()
self.__super.__init__(self.pile)
def __init__(self, content, header=None, footer=None):
wlist = []
if header:
wlist.append(header)
wlist.extend([DIV, pad(content)])
if footer:
wlist.extend([HR, DIV, pad(footer)])
wlist.append(DIV)
card = urwid.AttrMap(urwid.Pile(wlist), 'card')
urwid.WidgetWrap.__init__(self, card)
def get_content(text):
return urwid.Pile([urwid.SelectableIcon(
s, 0) if i == 0 else urwid.Text(s) for i, s in enumerate(text)])
def __init__(self, text, vertical_padding=True):
content = [urwid.Padding(self.get_content(text), left=3, right=3)]
if vertical_padding:
content = [DIV] + content + [DIV]
lbox = urwid.LineBox(urwid.Pile(content))
self.__super.__init__(urwid.AttrMap(urwid.Pile(
[lbox]), 'image button', 'image button focus'))
def __init__(self, pic, text):
content = self.get_content(text)
lbox = urwid.LineBox(urwid.Pile([DIV, urwid.Padding(
urwid.Columns([(8, pic), content], 4), left=3, right=3), DIV]))
self.__super.__init__(urwid.AttrMap(urwid.Pile(
[lbox]), 'image button', 'image button focus'))
def uri_prompt(self, title, label, uri_example, tests):
"""
Args:
title (str): Title for the test page
label (str): label for the input field
uri_example (str): example of a valid URI
tests (Test[]): test to pass as argument to run_test
"""
intro = urwid.Pile([
urwid.Text(('text bold', title + ' test suite')),
DIV,
urwid.Text([label + ' (', ('text italic', uri_example), ')'])
])
def _next(form, uri):
form.set_message("validating URI")
cred = validate_uri(uri)
if cred:
form.set_message("Checking MongoDB connection...")
tester = Tester(cred, tests)
if tester.info:
self.run_test(cred, title, tester, tests)
else:
form.set_message("Couldn't find a MongoDB server", True)
else:
form.set_message("Invalid domain", True)
form = FormCard(
{"content": intro, "app": self.app}, ['URI'],
'Run ' + title.lower() + ' test suite',
{'next': _next, 'back': self.choose_test})
self.app.render(form)