def conn_text(self, conn): if conn: hdrs = [] for k, v in conn.headers.fields: # This will always force an ascii representation of headers. For example, if the server sends a # # X-Authors: Made with ❤ in Hamburg # # header, mitmproxy will display the following: # # X-Authors: Made with \xe2\x9d\xa4 in Hamburg. # # The alternative would be to just use the header's UTF-8 representation and maybe # do `str.replace("\t", "\\t")` to exempt tabs from urwid's special characters escaping [1]. # That would in some terminals allow rendering UTF-8 characters, but the mapping # wouldn't be bijective, i.e. a user couldn't distinguish "\\t" and "\t". # Also, from a security perspective, a mitmproxy user couldn't be fooled by homoglyphs. # # 1) https://github.com/mitmproxy/mitmproxy/issues/1833 # https://github.com/urwid/urwid/blob/6608ee2c9932d264abd1171468d833b7a4082e13/urwid/display_common.py#L35-L36, k = strutils.bytes_to_escaped_str(k) + ":" v = strutils.bytes_to_escaped_str(v) hdrs.append((k, v)) txt = common.format_keyvals( hdrs, key_format="header" ) viewmode = self.master.commands.call("console.flowview.mode") msg, body = self.content_view(viewmode, conn) cols = [ urwid.Text( [ ("heading", msg), ] ), urwid.Text( [ " ", ('heading', "["), ('heading_key', "m"), ('heading', (":%s]" % viewmode)), ], align="right" ) ] title = urwid.AttrWrap(urwid.Columns(cols), "heading") txt.append(title) txt.extend(body) else: txt = [ urwid.Text(""), urwid.Text( [ ("highlight", "No response. Press "), ("key", "e"), ("highlight", " and edit any aspect to add one."), ] ) ] return searchable.Searchable(txt)
def refresh2(loop=None, data=None): loop.set_alarm_in(2, refresh) Ing, Msg = Bili_msg() Head.contents[3] = (urwid.Text(Ing), Head.options()) Head.contents[2] = (urwid.Text(Msg), Head.options())
def new_conversation(self): self.dialog_open = True source_hash = "" display_name = "" e_id = urwid.Edit(caption="Addr : ", edit_text=source_hash) e_name = urwid.Edit(caption="Name : ", edit_text=display_name) trust_button_group = [] r_untrusted = urwid.RadioButton(trust_button_group, "Untrusted") r_unknown = urwid.RadioButton(trust_button_group, "Unknown", state=True) r_trusted = urwid.RadioButton(trust_button_group, "Trusted") def dismiss_dialog(sender): self.update_conversation_list() self.dialog_open = False def confirmed(sender): try: existing_conversations = nomadnet.Conversation.conversation_list( self.app) display_name = e_name.get_edit_text() source_hash_text = e_id.get_edit_text() source_hash = bytes.fromhex(source_hash_text) trust_level = DirectoryEntry.UNTRUSTED if r_unknown.state == True: trust_level = DirectoryEntry.UNKNOWN elif r_trusted.state == True: trust_level = DirectoryEntry.TRUSTED if not source_hash in [c[0] for c in existing_conversations]: entry = DirectoryEntry(source_hash, display_name, trust_level) self.app.directory.remember(entry) new_conversation = nomadnet.Conversation( source_hash_text, nomadnet.NomadNetworkApp.get_shared_instance(), initiator=True) self.update_conversation_list() self.display_conversation(source_hash_text) self.dialog_open = False except Exception as e: RNS.log( "Could not start conversation. The contained exception was: " + str(e), RNS.LOG_VERBOSE) if not dialog_pile.error_display: dialog_pile.error_display = True options = dialog_pile.options(height_type="pack") dialog_pile.contents.append((urwid.Text(""), options)) dialog_pile.contents.append((urwid.Text( ("error_text", "Could not start conversation. Check your input."), align="center"), options)) dialog_pile = urwid.Pile([ e_id, e_name, urwid.Text(""), r_untrusted, r_unknown, r_trusted, urwid.Text(""), urwid.Columns([ ("weight", 0.45, urwid.Button("Create", on_press=confirmed)), ("weight", 0.1, urwid.Text("")), ("weight", 0.45, urwid.Button("Back", on_press=dismiss_dialog)) ]) ]) dialog_pile.error_display = False dialog = DialogLineBox(dialog_pile, title="New Conversation") dialog.delegate = self bottom = self.listbox overlay = urwid.Overlay(dialog, bottom, align="center", width=("relative", 100), valign="middle", height="pack", left=2, right=2) options = self.columns_widget.options("weight", ConversationsDisplay.list_width) self.columns_widget.contents[0] = (overlay, options)
def onUpdate(self, data): # If we lose the connection to the remote system close the console. if data.startswith(b'### closed ###'): self.proc = False self.getProcess() lostprocess_message = 'reconnecting to server . . .' self.walker.append( urwid.Text(('logged_response', lostprocess_message))) self.widget.set_focus(len(self.walker) - 1) return if data[-1:] != b'\n': self.buffer += data.decode("utf-8") return if len(self.buffer) > 0: data = (self.buffer + data.decode("utf-8")).encode("utf-8") self.buffer = '' data_lines = data.decode("utf-8").rstrip().split('\n') for line_json in data_lines: try: if len(line_json) <= 0: continue try: line_data = json.loads(line_json.strip()) line = line_data['line'] shard = line_data['shard'] if self.focus and self.focus != line_data['shard']: continue except: print(line_json) logging.exception('error processing data: ' + line_json) continue log_type = outputparser.getType(line) if self.quiet and log_type != 'result': return if log_type == 'result': formatting = 'logged_response' elif log_type == 'highlight': formatting = 'highlight' elif log_type == 'error': formatting = 'error' else: severity = outputparser.getSeverity(line) if not severity or severity > 5 or severity < 0: severity = 2 formatting = 'severity' + str(severity) line = line.replace('	', " ") line = outputparser.clearTags(line) if line.startswith('ScreepStats: Processed'): return if line.startswith('STATS'): return if log_type == 'log' and len(self.filters) > 0: has_match = False for pattern in self.filters: try: match = re.search(pattern, line) except: e = sys.exc_info()[0] logging.exception('dammit') if match is not None: has_match = True break if not has_match: continue self.walker.append( urwid.Text((formatting, '%s: %s' % (shard, line)))) self.widget.autoscroll() except: logging.exception('error processing data')
def getWelcomeMessage(self): return urwid.Text( ('default', 'Welcome to the Screeps Interactive Console'))
def load_inner_widget(self): return urwid.Text(self.get_display_text())
# Color schemes that specify the appearance off focus and on focus. PALETTE = [("reveal_focus", "black", "white"), ("dp_barActive_focus", "light gray", ""), ("dp_barActive_offFocus", "black", ""), ("dp_barInactive_focus", "dark gray", ""), ("dp_barInactive_offFocus", "black", ""), ("dp_highlight_focus", "black", "brown", "standout"), ("dp_highlight_offFocus", "white", "black"), ("text_highlight", "yellow,bold", ""), ("text_bold", "bold", ""), ("text_esc", "light red,bold", "")] date = datetime.date(2018, 11, 15) # Navigation instructions text_arrow_keys = urwid.Text([("text_highlight", "ctrl"), " + (", ("text_highlight", "↑"), " or ", ("text_highlight", "↓"), ") to move one step_length."]) text_pages = urwid.Text([("text_highlight", "ctrl"), " + (", ("text_highlight", "page up"), " or ", ("text_highlight", "page down"), ") to move one jump_length."]) text_home_end = urwid.Text([("text_highlight", "ctrl"), " + (", ("text_highlight", "home"), " or ", ("text_highlight", "end"), ") to jump to the corresponding end."]) pickers = {"left": [], "right": []} # Left column
def __init__(self): # show message in the center of the screen super().__init__(urwid.Filler( urwid.Text('Connecting...', align='center') ))
def __init__(self, default_provider): def format_provider(n, p): return p.NAME if p.config_is_valid else f"* {p.NAME}" def providers_sort_key(p): k, v = p # providers = list(config.settings.profile.providers.keys()) # if k in providers: # raise Exception(v) if v.config_is_valid: return (0, str(v.NAME)) else: return (1, str(v.NAME)) self.provider_dropdown = BaseDropdown(AttrDict([ (format_provider(n, p), n) for n, p in sorted(providers.PROVIDERS.items(), key=providers_sort_key) ]), label="Provider", default=default_provider, margin=1) urwid.connect_signal(self.provider_dropdown, "change", lambda w, b, v: self._emit("provider_change", v)) self.profile_dropdown = BaseDropdown( AttrDict([(k, k) for k in config.settings.profiles.keys()]), label="Profile", default=config.settings.profile_name, margin=1) urwid.connect_signal(self.profile_dropdown, "change", lambda w, b, v: self._emit("profile_change", v)) self.max_concurrent_tasks_widget = providers.filters.IntegerTextFilterWidget( default=config.settings.tasks.max, minimum=1) def set_max_concurrent_tasks(v): config.settings.tasks.max = int(v) self.max_concurrent_tasks_widget.connect("changed", set_max_concurrent_tasks) # urwid.connect_signal( # self.max_concurrent_tasks_widget, # "change", # set_max_concurrent_tasks # ) self.columns = urwid.Columns( [ # ('weight', 1, urwid.Padding(urwid.Edit("foo"))), (self.provider_dropdown.width, self.provider_dropdown), ("pack", urwid.Text(("Downloads"))), (5, self.max_concurrent_tasks_widget), ("weight", 1, urwid.Padding(urwid.Text(""))), # (1, urwid.Divider(u"\N{BOX DRAWINGS LIGHT VERTICAL}")), (self.profile_dropdown.width, self.profile_dropdown), ], dividechars=3) # self.filler = urwid.Filler(self.columns) super(MainToolbar, self).__init__(urwid.Filler(self.columns))
import urwid palette = [ ('banner', 'white', 'light red'), ('streak', 'white', 'light blue'), ('bg', '', ''), ] main = urwid.Padding(urwid.Text("Loading")) def quit(btn): raise urwid.ExitMainLoop() def submit(button, choice): response = urwid.Text([u'You chose ', choice, u'\n']) done = urwid.Button(u'Ok') urwid.connect_signal(done, 'click', quit) main.original_widget = urwid.Filler(urwid.Pile([response, urwid.AttrMap(done, None, focus_map='banner')])) def menu(title, choices): body = [urwid.Text(title), urwid.Divider()] for c in choices: button = urwid.Button(c) urwid.connect_signal(button, 'click', submit, c) body.append(urwid.AttrMap(button, None, focus_map='streak')) return urwid.ListBox(urwid.SimpleFocusListWalker(body)) choices = ["2.x", "3.x"]
def submit(button, choice): response = urwid.Text([u'You chose ', choice, u'\n']) done = urwid.Button(u'Ok') urwid.connect_signal(done, 'click', quit) main.original_widget = urwid.Filler(urwid.Pile([response, urwid.AttrMap(done, None, focus_map='banner')]))
def __init__(self): text_header = (u"Helm charts installer - " u"UP / DOWN / PAGE UP / PAGE DOWN scroll. ctrl+e exits.") text_footer = remove_ansi_color_from_string(get_cluster_info().split("\n")[0]) text_intro = [('important', u"Helm charts installer "), u"installs kubernetes helm charts on a configured cluster, " u"by default its intended to work on a cluster on the local host. " u"For more details execute 'helm_charts -h'"] config_context_info = [u"Current config file: ", ('important', config_file), u"\nCurrent context used: ", ('important', cluster_context)] self.helm_repo_installed_repositories_text = urwid.Text( identify_installed_helm_repos()['value'].replace("\t", " ")) self.text_helm_charts_installation_result = urwid.Text(u"", align='left') self.helm_repo_change_result = urwid.Text('') self.text_helm_charts_installed = urwid.Text( identify_installed_helm_charts()['value'].replace("\t", " ") ) self.cluster_namespaces_text = urwid.Text( identify_cluster_namespaces()['value'].replace("\t", " ")) self.namespaces_change_result = urwid.Text('') blank = urwid.Divider() equal_divider = urwid.WidgetWrap(urwid.Divider("=", 1)) asterisk_divider = urwid.WidgetWrap(urwid.Divider("*", 0, 1)) listbox_content = [ # Show into text blank, urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20), # Show current config file, and context used blank, urwid.Padding(urwid.Text(config_context_info), left=2, right=2, min_width=20), # Helm charts display equal_divider, urwid.Padding(urwid.Text([u"Installed ", ('important', u"Helm charts:")]), left=2, right=2, min_width=20), asterisk_divider, urwid.Padding(self.text_helm_charts_installed, left=2, right=2, min_width=20), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.Button("Install Charts", self.on_chart_install_open), 'buttn', 'buttnf')], 18, 3, 1, 'left'), left=2, right=2, min_width=13), blank, urwid.Padding(urwid.GridFlow( [urwid.AttrWrap(urwid.Button("Delete Charts", self.on_chart_delete_open), 'buttn', 'buttnf')], 18, 3, 1, 'left'), left=2, right=2, min_width=13), blank, # Print results of charts installations urwid.Padding(self.text_helm_charts_installation_result, left=2, right=2, min_width=20), urwid.Columns([ urwid.Pile([ # Helm repositories display equal_divider, urwid.Padding( urwid.Text([u"Installed ", ('important', u"Helm repositories:")]), left=2, right=2, min_width=20), asterisk_divider, urwid.Padding(self.helm_repo_installed_repositories_text, left=2, right=2, min_width=20), blank, urwid.Padding( urwid.AttrWrap( urwid.Button("Add repository", self.on_repo_add_menu_open), 'buttn', 'buttnf'), left=2, right=2, width=25), blank, urwid.Padding( urwid.AttrWrap( urwid.Button("Delete repositories", self.on_repo_delete_menu_open), 'buttn', 'buttnf'), left=2, right=2, width=25), blank, # Print result from helm repo add urwid.Padding(self.helm_repo_change_result, left=2, right=2, min_width=20), ]), urwid.Pile([ # Helm repositories display equal_divider, urwid.Padding( urwid.Text([u"Available ", ('important', u"Namespaces:")]), left=2, right=2, min_width=20), asterisk_divider, urwid.Padding(self.cluster_namespaces_text, left=2, right=2, min_width=20), blank, urwid.Padding( urwid.AttrWrap( urwid.Button("Create Namespace", self.on_create_namespace_menu_open), 'buttn', 'buttnf'), left=2, right=2, width=25), blank, urwid.Padding( urwid.AttrWrap( urwid.Button("Delete Namespace", self.on_delete_namespace_menu_open), 'buttn', 'buttnf'), left=2, right=2, width=25), blank, # Print result from namespaces change urwid.Padding(self.namespaces_change_result, left=2, right=2, min_width=20), ]) ], 3), ] header = urwid.AttrWrap(urwid.Text(text_header), 'header') footer = urwid.AttrWrap(urwid.Text(text_footer), 'footer') listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) # Frame widget is used to keep the instructions at the top of the screen self.frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header, footer=footer) urwid.WidgetPlaceholder.__init__(self, self.frame)
def button_press(self, button): self.frame.footer = urwid.AttrWrap(urwid.Text( [u"Pressed: ", button.get_label()]), 'header')
def __init__(self): close_button = urwid.Button("close") urwid.connect_signal(close_button, 'click', self.reenter_username) pile = urwid.Pile([urwid.Text(ErrorMessages.default), close_button]) fill = urwid.Filler(pile) self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))
'complete', label='Current File', label_width=15, units='MB', done=10) bar2 = TimedProgressBar('normal', 'complete', label='Overall', label_width=15, units='MB', done=100) # Advance the second bar bar2.add_progress(40) footer = uw.Text('q to exit, any other key adds to progress') progress = uw.Frame(uw.ListBox([bar1, uw.Divider(), bar2]), footer=footer) # Pressing a key other that 'q' advances the progress bars by 1 # Calling add_progress() also updates the displayed rate and time # remaining. def keypress(key): if key in ('q', 'Q'): raise uw.ExitMainLoop() else: bar2.add_progress(1) if bar1.add_progress(1) and bar2.current < bar2.done: bar1.reset() loop = uw.MainLoop(progress, palette, unhandled_input=keypress) loop.run()
def update_content(self, page_number, title_markup='Front Page'): self.header_content = [ urwid.Text(title_markup), urwid.Divider(), self.tab_menu, urwid.Text('Page {}'.format(page_number), align='right') ]
def format_row(self, icon, text): return urwid.Text([' ', ('profile_icon', get_icon(icon)), ' ', text])
def has_symbols(password): return any(not letter.isalpha() and not letter.isdigit() for letter in password) def doesnt_consist_of_symbols(password): return any(letter.isalpha() or letter.isdigit() for letter in password) def on_ask_change(edit, new_edit_text): score = 0 password_checks = [ is_very_long, has_digit, has_letters, has_upper_letters, has_lower_letters, has_symbols ] for password_check in password_checks: if password_check(new_edit_text): score += 2 print('Рейтинг этого пароля:', score) if __name__ == '__main__': ask = urwid.Edit('Введите пароль: ', mask='*') reply = urwid.Text("") menu = urwid.Pile([ask, reply]) menu = urwid.Filler(menu, valign='top') urwid.connect_signal(ask, 'change', on_ask_change) urwid.MainLoop(menu).run()
def __init__(self, ebuild): title = urwid.Text(('blue-bold', ebuild.get_cp())) row_titles = ['Description', 'Homepage', 'SLOT(S)', 'License', 'IUSE'] title_keys = ['DESCRIPTION', 'HOMEPAGE', 'SLOT', 'LICENSE', 'IUSE'] ebuild_vd = ebuild.getVariablesDict() row_dict = {} self.title = ebuild.get_cp() # Detecting the available variables for j, i in enumerate(title_keys): if i in ebuild_vd: row_dict[row_titles[j]] = ebuild_vd[i] else: row_dict[row_titles[j]] = 'None' # PKG INFO pkg_table = urwidtable.Table(row_dict) divider = urwid.Divider('-') # AVAILABLE INFO versions_title = urwid.Text(('bold', 'Available Versions')) versions = [urwid.Text(i) for i in ebuild.get_versions()] # MERGED INFO emerge_title = urwid.Text(('bold', 'Emerge History')) emerged_tables = [] if ebuild.get_cp() in vardb.cp_list: db_dir = portage_env.VARDBPKG + '/' + ebuild.get_cat() list_dir = os.listdir(db_dir) package_name = re.search('(.*/)(.*)', ebuild.get_cp()).group(2) merged_list = [ i for i in list_dir if i.find(package_name, 0) != -1 ] for k in merged_list: curEbuild = vardb.MergedEbuild(ebuild.get_cat() + '/' + k) curEbuild_dict = curEbuild.get_var_dict() ebuild_row_titles = [ 'BUILD_TIME', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS', 'CHOST', 'IUSE_EFFECTIVE', 'IUSE', 'SLOT', 'USE', 'DEPEND', 'FEATURES', 'LICENSE', 'repository' ] merged_dict = {} for t in ebuild_row_titles: try: merged_dict[t] = curEbuild_dict[t] except: pass ebuild_table = urwidtable.Table(merged_dict, title=k) emerged_tables.append(ebuild_table) else: emerged_tables.append(urwid.Text('No past merges')) widget_list = [ title, pkg_table, divider, versions_title, *versions, divider, emerge_title, *emerged_tables ] super(Package_Pane, self).__init__(urwid.SimpleFocusListWalker(widget_list))
new_item = VariableWidget(parent, var_label, value_str, id_path, attr_prefix, iinfo=iinfo) self.main_widget_list.append(new_item) return new_item # }}} # {{{ top level SEPARATOR = urwid.AttrMap(urwid.Text(""), "variable separator") def make_var_view(frame_var_info, locals, globals): vars = list(locals.keys()) vars.sort(key=str.lower) tmv_walker = TopAndMainVariableWalker(frame_var_info) ret_walker = BasicValueWalker(frame_var_info) watch_widget_list = [] for watch_expr in frame_var_info.watches: try: value = eval(watch_expr.expression, globals, locals) except Exception: value = WatchEvalError()
def appendText(self, message, format='logged_response'): self.append(urwid.Text((format, message)))
def _tab(self, content, attr): p = urwid.Text(content, align="center") p = urwid.Padding(p, align="center", width=("relative", 100)) p = urwid.AttrWrap(p, attr) return p
def getHeader(self): return urwid.AttrMap( urwid.Text("%s - Screeps Interactive Console" % (self.connection_name, ), align='center'), 'header')
def _handle_input(self, input): if input == "enter" or ( input[0] == 'meta mouse press' and input[1] == 1 ): # View answers Either press Enter or "ALT + Left Click" url = self._get_selected_link() focus_widget, idx = self.content_container.get_focus( ) # Gets selected item search_results = self.search_results if url != None: self.viewing_answers = True question_title, question_desc, question_stats, answers = get_question_and_answers( url, search_results, idx) pile = urwid.Pile( self._stylize_question(question_title, question_desc, question_stats) + [urwid.Divider('*')] + interleave(answers, [urwid.Divider('-')] * (len(answers) - 1))) padding = ScrollBar( Scrollable(urwid.Padding(pile, left=2, right=2))) #filler = urwid.Filler(padding, valign="top") linebox = urwid.LineBox(padding) menu = urwid.Text([ u'\n', ("menu", u" ESC "), ("light gray", u" Go back "), ("menu", u" B "), ("light gray", u" Open browser "), ("menu", u" Q "), ("light gray", u" Quit"), ]) # highlight the selected answer _, idx = self.content_container.get_focus() txt = self.content[idx].original_widget.text self.content[idx] = urwid.AttrMap(SelectableText(txt), 'viewed', 'reveal viewed focus') self.main_loop.widget = urwid.Frame(body=urwid.Overlay( linebox, self.content_container, "center", ("relative", 60), "middle", 23), footer=menu) elif input in ('b', 'B') or ( input[0] == 'ctrl mouse press' and input[1] == 1 ): # Open link Either press (B or b) or "CTRL + Left Click" url = self._get_selected_link() if url != None: webbrowser.open(url) elif input == "esc": # Close window if self.viewing_answers: self.main_loop.widget = self.original_widget self.viewing_answers = False else: raise urwid.ExitMainLoop() elif input in ('q', 'Q'): # Quit raise urwid.ExitMainLoop()
palette = [('body', 'black', 'light gray', 'standout'), ('streak', 'black', 'dark red'), ('banner', 'black', 'light gray'), ('header', 'white', 'dark red', 'bold'), ('button normal', 'light gray', 'dark blue', 'standout'), ('button select', 'white', 'dark green'), ('button disabled', 'dark gray', 'dark blue'), ('edit', 'light gray', 'dark blue'), ('bigtext', 'white', 'black'), ('chars', 'light gray', 'black'), ('exit', 'white', 'dark cyan'), ('Red_Text', 'dark red', '', 'bold'), ('Yellow_Text', 'yellow', '', 'bold'), ('Blue_Text', 'dark blue', "")] #Self infor mid = 393056819 AA = bili.get_member_info(mid) Up_inf = urwid.Text("\n\n\n\n\n" + Bili_UPinf(393056819)) 粉丝 = urwid.Text(str(bili.get_stat_info(mid)['data']['follower'])) 粉丝 = urwid.AttrWrap(粉丝, 'Red_Text') Up_inf = urwid.Pile([Up_inf, 粉丝]) Logo = urwid.Text(Logo) Ing, Msg = Bili_msg() Ing = urwid.Text(Ing) Msg = urwid.Text("\n".join(Msg.split("\n")[-15:])) Msg = urwid.AttrWrap(Msg, 'Blue_Text') Head = urwid.Columns([('fixed', 16, Up_inf), ('fixed', 30, Logo), ('fixed', 10, Ing), ('fixed', 36, Msg)]) #Veido Infor Title = urwid.Text("\n".join(["", "點擊:", "點贊:", "回覆:", "投幣:"])) Bv1_N = Bili_v("Python色差", 86328254) Bv2_N = Bili_v("汪汪洗澡", 89026731)
def _stylize_question(self, title, desc, stats): new_title = urwid.Text(("title", u"%s" % title)) new_stats = urwid.Text(("stats", u"%s\n" % stats)) return [new_title, desc, new_stats]
def edit_selected_in_directory(self): g = self.app.ui.glyphs self.dialog_open = True source_hash_text = self.ilb.get_selected_item().source_hash display_name = self.ilb.get_selected_item().display_name if display_name == None: display_name = "" e_id = urwid.Edit(caption="Addr : ", edit_text=source_hash_text) t_id = urwid.Text("Addr : " + source_hash_text) e_name = urwid.Edit(caption="Name : ", edit_text=display_name) selected_id_widget = t_id untrusted_selected = False unknown_selected = True trusted_selected = False direct_selected = True propagated_selected = False try: if self.app.directory.find(bytes.fromhex(source_hash_text)): trust_level = self.app.directory.trust_level( bytes.fromhex(source_hash_text)) if trust_level == DirectoryEntry.UNTRUSTED: untrusted_selected = True unknown_selected = False trusted_selected = False elif trust_level == DirectoryEntry.UNKNOWN: untrusted_selected = False unknown_selected = True trusted_selected = False elif trust_level == DirectoryEntry.TRUSTED: untrusted_selected = False unknown_selected = False trusted_selected = True if self.app.directory.preferred_delivery( bytes.fromhex( source_hash_text)) == DirectoryEntry.PROPAGATED: direct_selected = False propagated_selected = True except Exception as e: pass trust_button_group = [] r_untrusted = urwid.RadioButton(trust_button_group, "Untrusted", state=untrusted_selected) r_unknown = urwid.RadioButton(trust_button_group, "Unknown", state=unknown_selected) r_trusted = urwid.RadioButton(trust_button_group, "Trusted", state=trusted_selected) method_button_group = [] r_direct = urwid.RadioButton(method_button_group, "Deliver directly", state=direct_selected) r_propagated = urwid.RadioButton(method_button_group, "Use propagation nodes", state=propagated_selected) def dismiss_dialog(sender): self.update_conversation_list() self.dialog_open = False def confirmed(sender): try: display_name = e_name.get_edit_text() source_hash = bytes.fromhex(e_id.get_edit_text()) trust_level = DirectoryEntry.UNTRUSTED if r_unknown.state == True: trust_level = DirectoryEntry.UNKNOWN elif r_trusted.state == True: trust_level = DirectoryEntry.TRUSTED delivery = DirectoryEntry.DIRECT if r_propagated.state == True: delivery = DirectoryEntry.PROPAGATED entry = DirectoryEntry(source_hash, display_name, trust_level, preferred_delivery=delivery) self.app.directory.remember(entry) self.update_conversation_list() self.dialog_open = False self.app.ui.main_display.sub_displays.network_display.directory_change_callback( ) except Exception as e: RNS.log( "Could not save directory entry. The contained exception was: " + str(e), RNS.LOG_VERBOSE) if not dialog_pile.error_display: dialog_pile.error_display = True options = dialog_pile.options(height_type="pack") dialog_pile.contents.append((urwid.Text(""), options)) dialog_pile.contents.append((urwid.Text( ("error_text", "Could not save entry. Check your input."), align="center"), options)) source_is_known = self.app.directory.is_known( bytes.fromhex(source_hash_text)) if source_is_known: known_section = urwid.Divider(g["divider1"]) else: def query_action(sender, user_data): self.close_conversation_by_hash(user_data) nomadnet.Conversation.query_for_peer(user_data) options = dialog_pile.options(height_type="pack") dialog_pile.contents = [(urwid.Text("Query sent"), options), (urwid.Button("OK", on_press=dismiss_dialog), options)] query_button = urwid.Button("Query network for keys", on_press=query_action, user_data=source_hash_text) known_section = urwid.Pile([ urwid.Divider(g["divider1"]), urwid.Text(g["info"] + "\n", align="center"), urwid.Text( "The identity of this peer is not known, and you cannot currently communicate.\n", align="center"), query_button, urwid.Divider(g["divider1"]) ]) dialog_pile = urwid.Pile([ selected_id_widget, e_name, urwid.Divider(g["divider1"]), r_untrusted, r_unknown, r_trusted, urwid.Divider(g["divider1"]), r_direct, r_propagated, known_section, urwid.Columns([ ("weight", 0.45, urwid.Button("Save", on_press=confirmed)), ("weight", 0.1, urwid.Text("")), ("weight", 0.45, urwid.Button("Back", on_press=dismiss_dialog)) ]) ]) dialog_pile.error_display = False dialog = DialogLineBox(dialog_pile, title="Peer Info") dialog.delegate = self bottom = self.listbox overlay = urwid.Overlay(dialog, bottom, align="center", width=("relative", 100), valign="middle", height="pack", left=2, right=2) options = self.columns_widget.options("weight", ConversationsDisplay.list_width) self.columns_widget.contents[0] = (overlay, options)
def get_question_and_answers(url, search_results, idx): return search_results[idx]["Title"], urwid.Text( ""), search_results[idx]["index"], [ urwid.Text(search_results[idx]["Answer"]) ]
def sync_conversations(self): g = self.app.ui.glyphs self.dialog_open = True def dismiss_dialog(sender): self.dialog_open = False self.sync_dialog = None self.update_conversation_list() if self.app.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_COMPLETE: self.app.cancel_lxmf_sync() max_messages_group = [] r_mall = urwid.RadioButton(max_messages_group, "Download all", state=True) r_mlim = urwid.RadioButton(max_messages_group, "Limit to", state=False) ie_lim = urwid.IntEdit("", 5) rbs = urwid.GridFlow([r_mlim, ie_lim], 12, 1, 0, align="left") def sync_now(sender): limit = None if r_mlim.get_state(): limit = ie_lim.value() self.app.request_lxmf_sync(limit) self.update_sync_dialog() def cancel_sync(sender): self.app.cancel_lxmf_sync() self.update_sync_dialog() cancel_button = urwid.Button("Close", on_press=dismiss_dialog) sync_progress = SyncProgressBar("progress_empty", "progress_full", current=self.app.get_sync_progress(), done=1.0, satt=None) real_sync_button = urwid.Button("Sync Now", on_press=sync_now) hidden_sync_button = urwid.Button("Cancel Sync", on_press=cancel_sync) if self.app.get_sync_status( ) == "Idle" or self.app.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_COMPLETE: sync_button = real_sync_button else: sync_button = hidden_sync_button button_columns = urwid.Columns([("weight", 0.45, sync_button), ("weight", 0.1, urwid.Text("")), ("weight", 0.45, cancel_button)]) real_sync_button.bc = button_columns pn_ident = None if self.app.get_default_propagation_node() != None: pn_hash = self.app.get_default_propagation_node() pn_ident = RNS.Identity.recall(pn_hash) if pn_ident == None: RNS.log( "Propagation node identity is unknown, requesting from network...", RNS.LOG_DEBUG) RNS.Transport.request_path(pn_hash) if pn_ident != None: node_hash = RNS.Destination.hash_from_name_and_identity( "nomadnetwork.node", pn_ident) pn_entry = self.app.directory.find(node_hash) dialog = DialogLineBox(urwid.Pile([ urwid.Text("" + g["node"] + " " + str(pn_entry.display_name), align="center"), urwid.Divider(g["divider1"]), sync_progress, urwid.Divider(g["divider1"]), r_mall, rbs, urwid.Text(""), button_columns ]), title="Message Sync") else: button_columns = urwid.Columns([("weight", 0.45, urwid.Text("")), ("weight", 0.1, urwid.Text("")), ("weight", 0.45, cancel_button)]) dialog = DialogLineBox(urwid.Pile([ urwid.Text(""), urwid.Text("No trusted nodes found, cannot sync", align="center"), urwid.Text(""), button_columns ]), title="Message Sync") dialog.delegate = self dialog.sync_progress = sync_progress dialog.cancel_button = cancel_button dialog.real_sync_button = real_sync_button dialog.hidden_sync_button = hidden_sync_button dialog.bc = button_columns self.sync_dialog = dialog bottom = self.listbox overlay = urwid.Overlay(dialog, bottom, align="center", width=("relative", 100), valign="middle", height="pack", left=2, right=2) options = self.columns_widget.options("weight", ConversationsDisplay.list_width) self.columns_widget.contents[0] = (overlay, options)
def labelled_value(label, value): return urwid.AttrMap(urwid.Text([("label", label), str(value)]), "fixed value", "fixed value")