def __init__(self, initial_buttons):
self.list_stack = [initial_buttons]
self.all_styled_buttons = [urwid.AttrMap(b, None, 'reveal focus')
for b in initial_buttons.items]
self.list_walker = ChooseFromListWalker(self.all_styled_buttons, self)
list_box = ChooseFromListBox(self.list_walker)
column_array = convert_details_to_columns(
initial_buttons.items[0].retrieve_important_details())
self.cols = urwid.Columns(
[('weight', 1, column_array[0]), ('weight', 4, column_array[1])], )
self.detail_view = False
self.base_title_text = self.list_stack[-1].items_title
self.title = urwid.AttrMap(urwid.Text(self.base_title_text + " " + self.EMPTY_FILTER_TEXT), 'title')
self.cols_title = urwid.AttrMap(urwid.Text(u'Attributes'), 'title')
self.body = urwid.Pile([(2, urwid.Filler(self.title, valign='top')), list_box, (
2, urwid.Filler(self.cols_title, valign='top')), self.cols])
self.before_detail = None
self.filter_string = ""
python类Text()的实例源码
def __init__(self, data, field_labels, btn_label, callbacks):
self.app = data["app"]
self.error = False
self.fields, self.callbacks = [], callbacks
for label in field_labels:
self.fields.append(InputField(label, next_callback=self.next))
input_fields = urwid.Pile(self.fields)
self.message_field = urwid.Text('')
error_row = urwid.Columns([(17, urwid.Text('')), self.message_field])
buttons = [TextButton(btn_label, on_press=self.next)]
if callbacks['back']:
buttons.insert(0, TextButton('< Back', align='left', on_press=callbacks['back']))
footer = urwid.AttrMap(urwid.Columns(buttons), 'button')
card = Card(urwid.Pile(
[data["content"], input_fields, error_row]), footer=footer)
urwid.WidgetWrap.__init__(self, card)
def __init__(self, title, cred, tests, data):
self.app = None
self.tester = data["tester"]
urn = cred["nodelist"][0][0] + ":" + str(cred["nodelist"][0][1]) + (
"/" + (cred["database"]) if bool(cred["database"]) else "")
self.data = {"title": title, "callback": data["callback"],
"urn": urn, "num_tests": len(tests)}
self.progress_text = urwid.Text(
('progress', '0/' + str(self.data["num_tests"])))
running_display = urwid.Columns(
[(14, urwid.Text(('text', 'Running test'))), self.progress_text])
self.progress_bar = CustomProgressBar(
'progress', 'remaining', 0, self.data["num_tests"])
self.text_running = urwid.Text(('text', ''))
box = urwid.BoxAdapter(urwid.Filler(
self.text_running, valign='top'), 2)
pile = urwid.Pile([running_display, self.progress_bar, DIV, box])
urwid.WidgetWrap.__init__(self, pile)
def get_top_row(self, current, options):
def get_button(sign, text):
return urwid.AttrMap(TextButton(sign, on_press=(
lambda _: self.update_view(text))), 'button')
next_btn = get_button('>', 'next_callback')
prev_btn = get_button('<', 'prev')
top_row = []
if current > 1:
top_row.append((prev_btn, options('weight', 0)))
top_row.append((urwid.Padding(urwid.Text(self.get_top_text()),
left=25), options('weight', 1)))
if current < len(self.result):
top_row.append((next_btn, options('weight', 0.2)))
return top_row
def welcome(self):
pic = picRead('welcome.bmp', align='right')
text = urwid.Text([
('text bold', self.app.name),
('text', ' is a CLI tool for auditing MongoDB servers, detecting poor security '
'settings and performing automated penetration testing.\n\n'),
('text italic', "\"With great power comes great responsibility\". Unauthorized "
"access to strangers' computer systems is a crime "
"in many countries. Take care.")
])
button = urwid.AttrMap(
TextButton(
"Ok, I'll be careful!", on_press=self.choose_test), 'button')
card = Card(text, header=pic, footer=button)
self.app.render(card)
def __init__(self):
self.game = Game()
self._statusbar = urwid.Text(u'Ready')
self.current_selection = Selection(None, None)
self._tableau_columns = urwid.Columns([EmptyCardWidget() for _ in range(7)])
self._top_columns = urwid.Columns([
EmptyCardWidget(),
EmptyCardWidget(),
SpacerWidget(),
EmptyCardWidget(),
EmptyCardWidget(),
EmptyCardWidget(),
EmptyCardWidget(),
])
self._update_stock_and_waste()
self._update_foundations()
self._update_tableaus()
self.main_layout = urwid.Pile([
self._top_columns,
urwid.Divider(),
self._tableau_columns,
urwid.Divider(),
self._statusbar,
])
def __init__(self, client):
self.client = client
self.screen = urwid.raw_display.Screen()
# self.screen = self.DummyScreen()
self.frame = urwid.Frame(
client.default_view,
footer=urwid.Text("", align='center'),
)
self.client.frame = self.frame
self.urwid_loop = urwid.MainLoop(
self.frame,
screen=self.screen,
palette=palette,
event_loop=self.FixedAsyncLoop(loop=client.loop),
unhandled_input=client.handle_keypresses,
pop_ups=True
)
def quit_prompt(self):
"""Pop-up window that appears when you try to quit."""
# Nothing fancy here.
question = ur.Text(("bold", "Really quit?"), "center")
yes_btn = ur.AttrMap(ur.Button(
"Yes", self.button_press, "quit"), "red", None)
no_btn = ur.AttrMap(ur.Button(
"No", self.button_press, "back"), "green", None)
prompt = ur.LineBox(ur.ListBox(ur.SimpleFocusListWalker(
[question, self.div, self.div, no_btn, yes_btn])))
# The only interesting thing in this method is this Overlay widget.
overlay = MyOverlay(
prompt, self.loop.baseWidget,
"center", 20, "middle", 8,
16, 8,
parent=self)
self.loop.Widget = overlay
def parse_post(self, post):
"""Read post JSON and return values in easily-readable dictionary."""
# Old json - without name field
if len(post) == 3:
parsed_post = {
"name": "Anonymous",
"stamp": self.convert_time(post[0]),
"id": str(post[1]),
"text": ur.Text(post[2])
}
else:
parsed_post = {
"name": post[0],
"stamp": self.convert_time(post[1]),
"id": str(post[2]),
"text": ur.Text(post[3])
}
return parsed_post
def init_main_screen(self):
self.w_filter_edit = urwid.Edit('Filter ')
aw_filter_edit = urwid.AttrMap(self.w_filter_edit, 'edit', 'edit_focus')
self.w_status_line = urwid.AttrMap(StatusLine(self.store.get_test_stats), 'statusline', '')
urwid.connect_signal(self.w_filter_edit, 'change', self.on_filter_change)
self.init_test_listbox()
self.w_main = urwid.Padding(
urwid.Pile([
('pack', urwid.Text(u'Python Urwid Test Runner', align='center')),
('pack', urwid.Divider()),
('pack', aw_filter_edit),
('pack', urwid.Divider()),
self.w_test_listbox,
('pack', urwid.Divider()),
('pack', self.w_status_line),
]),
left=2, right=2
)
def __init__(self, pubpen):
self.pubpen = pubpen
self.exchange_entry = urwid.Text('(C)ommodity Exchange')
self.port_entry = urwid.Text('(P)ort District')
self.financial_entry = urwid.Text('(F)inancial')
self.travel_entry = urwid.Text('(T)ravel')
self.game_menu_entry = urwid.Text('(M)enu')
self.menu_entries = urwid.Columns((
('weight', 1, urwid.Divider(' ')),
(len('(C)ommodity Exchange') + 4, self.exchange_entry),
(len('(P)ort District') + 4, self.port_entry),
(len('(F)inancial') + 4, self.financial_entry),
(len('(T)ravel') + 4, self.travel_entry),
(len('(M)enu') + 4, self.game_menu_entry),
('weight', 1, urwid.Divider(' ')),
), dividechars=1)
super().__init__(self.menu_entries)
def add_message(self, msg, severity=MsgType.info):
"""
Add a message to the MessageWindow.
Reap older messages if there are too many
"""
if not self._can_print_message:
self.loop.call_later(self._MIN_TIME_BETWEEN_MESSAGES, self.add_message, msg, severity)
return
if severity is MsgType.error:
msg = urwid.Text(('reversed', msg))
else:
msg = urwid.Text(msg)
self.message_list.append(msg)
while len(self.message_list) > self._MAX_MESSAGES:
self.message_list.pop(0)
self._can_print_message = False
self.loop.call_later(self._MIN_TIME_BETWEEN_MESSAGES,
partial(setattr, self, '_can_print_message', True))
def __init__(self, pubpen, spacer=u'u2500'):
self.pubpen = pubpen
self.who = urwid.Text(u'\u2524 Name: \u251C')
self.where = urwid.Text(u'\u2524 Location: \u251C')
self.left = urwid.Columns([self.who])
self.right = urwid.Columns([self.where])
super().__init__((('pack', self.who),
('weight', 1, urwid.Divider(spacer)),
('pack', self.where),
))
# Connect to backend events
self.pubpen.subscribe('user.info', self.handle_user_info)
self.pubpen.subscribe('user.login_success', self.handle_login)
self.pubpen.subscribe('ship.moved', self.handle_ship_moved)
#
# Widget methods
#
def __init__(self, Telegram_ui):
self.Telegram_ui = Telegram_ui
self.updateLockedauto = False
self.username_list = []
self.buffer_writing_text = {}
# handeling navigation in history
self.history_own_message = {}
self.history_pos = 0
self.cur_text = ""
self.status_bar = urwid.Text(('status_bar', ' '), align='left')
self.attr = urwid.AttrMap(self.status_bar, 'status_bar')
self.widgetEdit = urwid.Edit(TEXT_CAPTION, "", multiline=False)
self.pile = urwid.Pile([self.attr, self.widgetEdit])
super().__init__(self.pile)
self.update_send_widget()
def __init__(self, title, message, entry_prompt=None,
entry_text='', buttons=[], ring=None):
button_widgets = []
for button in buttons:
button_widgets.append(('pack', button))
button_columns = urwid.Columns(button_widgets, dividechars=2)
rows = []
rows.append(urwid.Text(message))
if entry_prompt:
self.entry = MyEdit(entry_prompt, edit_text=entry_text, ring=ring)
rows.append(self.entry)
else:
self.entry = None
rows.append(urwid.Divider())
rows.append(button_columns)
listbox = urwid.ListBox(rows)
super(ButtonDialog, self).__init__(urwid.LineBox(listbox, title))
def __init__(self, app, board, topic, callback=None):
super(BoardRow, self).__init__('', on_press=callback,
user_data=(board.key, board.title))
self.app = app
self.mark = False
self._style = None
self.board_key = board.key
if topic:
self.topic_key = topic.key
self.indent = ' '
else:
self.topic_key = None
self.indent = ''
self.board_title = board.title
self.title = mywid.SearchableText('')
self._setTitle(board.title, self.indent)
self.title.set_wrap_mode('clip')
self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
col = urwid.Columns([
self.title,
('fixed', ACTIVE_COL_WIDTH, self.active_stories),
])
self.row_style = urwid.AttrMap(col, '')
self._w = urwid.AttrMap(self.row_style, None, focus_map=self.board_focus_map)
self.update(board)
def __init__(self, app, project, topic, callback=None):
super(ProjectRow, self).__init__('', on_press=callback,
user_data=(project.key, project.name))
self.app = app
self.mark = False
self._style = None
self.project_key = project.key
if topic:
self.topic_key = topic.key
self.indent = ' '
else:
self.topic_key = None
self.indent = ''
self.project_name = project.name
self.name = mywid.SearchableText('')
self._setName(project.name, self.indent)
self.name.set_wrap_mode('clip')
self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
col = urwid.Columns([
self.name,
('fixed', ACTIVE_COL_WIDTH, self.active_stories),
])
self.row_style = urwid.AttrMap(col, '')
self._w = urwid.AttrMap(self.row_style, None, focus_map=self.project_focus_map)
self.update(project)
def __init__(self, topic, callback=None):
super(TopicRow, self).__init__('', on_press=callback,
user_data=(topic.key, topic.name))
self.mark = False
self._style = None
self.topic_key = topic.key
self.name = urwid.Text('')
self._setName(topic.name)
self.name.set_wrap_mode('clip')
self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
col = urwid.Columns([
self.name,
('fixed', ACTIVE_COL_WIDTH, self.active_stories),
])
self.row_style = urwid.AttrMap(col, '')
self._w = urwid.AttrMap(self.row_style, None, focus_map=self.project_focus_map)
self._style = 'subscribed-project'
self.row_style.set_attr_map({None: self._style})
self.update(topic)
def open_confirm_prompt(self, callback, title="", content="",
yestxt="Yes", notxt="No", align="center"):
def create_cb(bool):
def res(*k, **a):
callback(bool)
self.close_pop_up()
return res
self.open_pop_up(
urwid.Filler(urwid.Text(content, align=align)),
header=urwid.Text(
title, align='center'),
footer=urwid.Columns([
(urwid.Button(yestxt, create_cb(True))),
(urwid.Button(notxt, create_cb(False))),
]),
height=6,
width=50)
self.pop_up.set_focus("footer")
logger.debug("Confirm prompt text: " + str(content))
def update_columns(self):
cols = []
names = discurses.processing.shorten_channel_names(
self.chat_widget.channels, 100)
for ch in self.chat_widget.channels:
if ch == self.chat_widget.send_channel:
cols.append((urwid.AttrMap(
urwid.Text(
names[ch], align="center"),
"send_channel_selector_sel",
"send_channel_selector_sel_f"),
self.w_cols.options('weight', 1)))
else:
cols.append((urwid.AttrMap(
urwid.Text(
names[ch], align="center"),
"send_channel_selector",
"send_channel_selector_f"),
self.w_cols.options('weight', 1)))
self.w_cols.contents = cols
def __init__(self, chat_widget):
self.chat_widget = chat_widget
self.message = FakeMessage(datetime.datetime.min)
self._selectable = False
txt = urwid.Text(
" \n"
" \n"
" \n"
" \n"
"< moo > \n"
" ----- \n"
" \ ^__^ \n"
" \ (oo)\_______ \n"
" (__)\ )\/\ \n"
" ||----w | \n"
" || || \n"
" \n"
" \n"
"Congratulations! You have reached the top, Thats awesome! Unless "
"the channel is empty, in which case, meh... big deal.\n\n",
align=urwid.CENTER)
w = urwid.Padding(txt, left=5, right=5)
self.__super.__init__(w)
def __init__(self, data, field_labels, btn_label, callbacks):
self.app = data["app"]
self.error = False
self.fields, self.callbacks = [], callbacks
for label in field_labels:
self.fields.append(InputField(label, next_callback=self.next))
input_fields = urwid.Pile(self.fields)
self.message_field = urwid.Text('')
error_row = urwid.Columns([(17, urwid.Text('')), self.message_field])
buttons = [TextButton(btn_label, on_press=self.next)]
if callbacks['back']:
buttons.insert(0, TextButton('< Back', align='left', on_press=callbacks['back']))
footer = urwid.AttrMap(urwid.Columns(buttons), 'button')
card = Card(urwid.Pile(
[data["content"], input_fields, error_row]), footer=footer)
urwid.WidgetWrap.__init__(self, card)
def __init__(self, title, cred, tests, data):
self.app = None
self.tester = data["tester"]
urn = cred["nodelist"][0][0] + ":" + str(cred["nodelist"][0][1]) + (
"/" + (cred["database"]) if bool(cred["database"]) else "")
self.data = {"title": title, "callback": data["callback"],
"urn": urn, "num_tests": len(tests)}
self.progress_text = urwid.Text(
('progress', '0/' + str(self.data["num_tests"])))
running_display = urwid.Columns(
[(14, urwid.Text(('text', 'Running test'))), self.progress_text])
self.progress_bar = CustomProgressBar(
'progress', 'remaining', 0, self.data["num_tests"])
self.text_running = urwid.Text(('text', ''))
box = urwid.BoxAdapter(urwid.Filler(
self.text_running, valign='top'), 2)
pile = urwid.Pile([running_display, self.progress_bar, DIV, box])
urwid.WidgetWrap.__init__(self, pile)
def get_top_row(self, current, options):
def get_button(sign, text):
return urwid.AttrMap(TextButton(sign, on_press=(
lambda _: self.update_view(text))), 'button')
next_btn = get_button('>', 'next_callback')
prev_btn = get_button('<', 'prev')
top_row = []
if current > 1:
top_row.append((prev_btn, options('weight', 0)))
top_row.append((urwid.Padding(urwid.Text(self.get_top_text()),
left=25), options('weight', 1)))
if current < len(self.result):
top_row.append((next_btn, options('weight', 0.2)))
return top_row
def welcome(self):
pic = picRead('welcome.bmp', align='right')
text = urwid.Text([
('text bold', self.app.name),
('text', ' is a CLI tool for auditing MongoDB servers, detecting poor security '
'settings and performing automated penetration testing.\n\n'),
('text italic', "\"With great power comes great responsibility\". Unauthorized "
"access to strangers' computer systems is a crime "
"in many countries. Take care.")
])
button = urwid.AttrMap(
TextButton(
"Ok, I'll be careful!", on_press=self.choose_test), 'button')
card = Card(text, header=pic, footer=button)
self.app.render(card)
def test_remove(self):
self.tabs.insert(urwid.Text('Tab3'), urwid.Text('Tab three'))
self.assertEqual(tuple(t.text for t in self.tabs.titles),
('Tab1', 'Tab2', 'Tab3'))
self.assertEqual(tuple(t.text for t in self.tabs.contents),
('Tab one', 'Tab two', 'Tab three'))
self.tabs.remove(self.tabs.get_id(2))
self.assertEqual(tuple(t.text for t in self.tabs.titles),
('Tab1', 'Tab2'))
self.assertEqual(tuple(t.text for t in self.tabs.contents),
('Tab one', 'Tab two'))
self.tabs.remove(1)
self.assertEqual(tuple(t.text for t in self.tabs.titles),
('Tab1',))
self.assertEqual(tuple(t.text for t in self.tabs.contents),
('Tab one',))
self.tabs.remove()
self.assertEqual(tuple(self.tabs.titles), ())
self.assertEqual(tuple(self.tabs.contents), ())
with self.assertRaises(IndexError):
self.tabs.remove(0)
def setUp(self):
self.size = (80, 20)
self.content = [
urwid.ListBox(urwid.SimpleFocusListWalker([
urwid.Edit('Field 1'),
urwid.Edit('Field 2'),
])),
urwid.ListBox(urwid.SimpleFocusListWalker([
SelectableText('Row 1'),
urwid.Edit('', 'Edit field 2'),
SelectableText('Row 3'),
]))
]
self.editbox = self.content[1].body[1]
self.editbox.edit_pos = 0
self.tabs = Tabs((urwid.Text('Edit fields'), self.content[0]),
(urwid.Text('empty'),),
(urwid.Text('Text rows'), self.content[1]))
def test_focusable_widget_gets_keypress_only_if_visible(self):
w = Scrollable(
urwid.Pile([urwid.Text('t1'),
urwid.Text('t2'),
urwid.Edit('', 'e3')])
)
size = (5, 2)
def press_keys():
for key in ('backspace', 'backspace', 'f', 'o', 'o'):
w.keypress(size, key)
self.check(w, size, text=('t1'.ljust(size[0]),
't2'.ljust(size[0])))
press_keys()
self.check(w, size, text=('t1'.ljust(size[0]),
't2'.ljust(size[0])))
w.set_scrollpos(1)
self.check(w, size, text=('t2'.ljust(size[0]),
'e3'.ljust(size[0])))
press_keys()
self.check(w, size, text=('t2'.ljust(size[0]),
'foo'.ljust(size[0])))
def test_evaluated_key_does_not_replace_original_key(self):
# Create a list of widgets that translate 'j' to 'down' in their
# keypress() methods.
lst_contents = [self.mk_widget(urwid.Text, str(i), context='item')
for i in range(1, 10)]
self.keymap.bind('j', context='item', action=Key('down'))
# Create ListBox with separate key context. If the ListBox gets to
# handle 'j', it just checks a mark we can look for.
lst_widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(lst_contents), context='list')
lst_got_j = FakeAction()
self.keymap.bind('j', context='list', action=lst_got_j)
# Make sure everything works regularly
size = (3, 3)
self.assert_lines(lst_widget, size, exp_lines=('1 ', '2 ', '3 '), exp_focus_pos=0)
lst_widget.keypress(size, 'down')
self.assert_lines(lst_widget, size, exp_lines=('1 ', '2 ', '3 '), exp_focus_pos=1)
# Do the actual test: Pressing 'j' should pass 'j' to the focused item,
# which evaluates it to 'down'. But the list widget must get 'j'.
lst_widget.keypress(size, 'j')
self.assert_lines(lst_widget, size, exp_lines=('1 ', '2 ', '3 '), exp_focus_pos=1)
self.assertEqual(lst_got_j.callnum, 1)
def test_complete_chain(self):
self.km.bind('alt-1 alt-2 alt-3', 'foo')
self.widget.keypress((80,), 'alt-1')
self.assert_status(keys_given=('alt-1',),
widget_text='Original Text',
active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))
self.widget.keypress((80,), 'alt-2')
self.assert_status(keys_given=('alt-1', 'alt-2'),
widget_text='Original Text',
active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))
self.widget.keypress((80,), 'alt-3')
self.assert_status(keys_given=(),
widget_text='foo1',
active_keychains=())