def main(): palette = [ ('proj', '', '', ''), ('proj_include', 'light gray', 'dark gray', ''), ('proj_focus', '', 'dark blue', ''), ('proj_selected', 'light magenta', '', ''), ('proj_focus_selected', 'light magenta', 'dark blue', ''), ('body', '', '', ''), ('body_focus', '', 'dark gray', ''), ('head', 'light red', 'black'), ] COMMAND_LINE_ARGS = sys.argv for arg in COMMAND_LINE_ARGS: if ".yml" in arg: playbook_filename = arg break try: with open(playbook_filename, 'r') as f: doc = yaml.load(f) except IOError: print "Error: " + playbook_filename + " not exists!" sys.exit(1) except UnboundLocalError: print "Error: playbook filename not found!" sys.exit(2) tasks = doc[0]['tasks'] for task in tasks: task['selected'] = '0' def keystroke(input): if input in ('r', 'R'): raise urwid.ExitMainLoop() if input in ('enter', 's', 'S'): item_focused = listbox.get_focus() focus = item_focused[0].content try: if tasks[item_focused[1]]['name'] != "": if tasks[item_focused[1]]['selected'] == '0': tasks[item_focused[1]]['selected'] = '1' else: tasks[item_focused[1]]['selected'] = '0' except KeyError: focus = "" view.set_header( urwid.AttrWrap(urwid.Text('selected: %s' % str(focus)), 'head')) refresh() def refresh(): walker[:] = map(ItemWidget, tasks) def tag_playbook(tag): print 'Custom tag: ' + tag with open(playbook_filename) as f2: list_task = yaml.load(f2) for task in tasks: if task["selected"] == "1": for task_play in list_task[0]['tasks']: try: if task_play['name'] == task['name']: if 'tags' in task_play.keys(): task_play[ 'tags'] = task_play['tags'] + ',' + tag else: task_play['tags'] = tag except KeyError: continue #print(list_task) with open(playbook_filename, "w") as f2: yaml.dump(list_task, f2, default_flow_style=False) def run_playbook(tag): print 'Running playbook:' my_command = 'ansible-playbook --tags ' + tag + ' ' + ' '.join( COMMAND_LINE_ARGS[1:]) print 'CMD: ' + my_command sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while sub_process.poll() is None: out = sub_process.stdout.read(1) sys.stdout.write(out) sys.stdout.flush() def remove_tag(tag): with open(playbook_filename) as f2: list_task = yaml.load(f2) for task_play in list_task[0]['tasks']: try: if task_play['tags'].find(tag) != -1: task_play['tags'] = task_play['tags'].replace( ',' + tag, '') task_play['tags'] = task_play['tags'].replace(tag, '') if task_play['tags'] == '': del task_play['tags'] except: continue with open(playbook_filename, "w") as f2: yaml.dump(list_task, f2, default_flow_style=False) #print(list_task) header = urwid.AttrMap(urwid.Text('selected:'), 'head') walker = urwid.SimpleListWalker([]) listbox = urwid.ListBox(walker) refresh() view = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header) loop = urwid.MainLoop(view, palette, unhandled_input=keystroke) loop.run() tag = ''.join( random.sample(map(chr, range(48, 57) + range(65, 90) + range(97, 122)), 32)) tag_playbook(tag) run_playbook(tag) remove_tag(tag)
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)
def main(self): global DATA text_header = (u"OpenChronos config \u2503 " u"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 aborts.") self.list_content = list_content = [] for key, field in DATA.iteritems(): # generate gui forms depending on type self.generate_widget(key, field) # rescan widgets and disable/enable them based on their dependencies for key, wid in WIDMAP.iteritems(): if not hasattr(wid, '_widget'): continue wid = wid._widget if isinstance(wid, urwid.Edit): val = wid.get_edit_text() elif isinstance(wid, urwid.CheckBox): val = wid.get_state() else: continue widget_changed_callback(wid, val) def ok_pressed(*args, **kwargs): raise urwid.ExitMainLoop() def abort_pressed(*args, **kwargs): sys.exit(0) list_content.append(urwid.Divider(div_char=u"\u2550", top=1, bottom=1)) list_content.append( urwid.Padding( urwid.GridFlow([ urwid.AttrWrap(urwid.Button("Save", ok_pressed), 'opt', 'optsel'), urwid.AttrWrap(urwid.Button("Abort", abort_pressed), 'opt', 'optsel') ], 15, 4, 4, 'center'), ('fixed left', 4), ('fixed right', 3))) header = urwid.AttrWrap(urwid.Text(text_header), 'header') walker = HelpListWalker(self, list_content) listbox = urwid.ListBox(walker) self.help_widget = urwid.Text("") footer = urwid.AttrWrap(self.help_widget, 'footer') frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header, footer=footer) screen = urwid.raw_display.Screen() palette = [ ('header', 'white', 'dark red', 'bold'), ('info', 'black', 'dark cyan'), ('body', 'black', 'dark gray'), ('optsel', 'white', 'dark blue'), ('opt', 'black', 'light gray'), ('optd', 'black', 'dark gray'), ] def unhandled(key): if key == 'f8': #raise urwid.ExitMainLoop() sys.exit(0) urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
if self.mainFrame.body == self : self.body.append(question()) set_last_position(self) palette = [('input', 'white,bold', 'black'), ('head','light gray','black'), ('error','light red','black'), ('multiple_cmd','light magenta','black'), ('choice','light magenta','dark blue'), ('title_choice','white,bold','dark blue'), ('background_choice','default','dark blue'), ('out','light blue','black'), ('info','dark green','black'),] en_tete = urwid.Text(time.strftime('%d/%m/%y %H:%M',time.localtime()), align='right') filler_en_tete = urwid.AttrMap(en_tete, 'head') pied = urwid.Text("----------------------",align='center') filler_pied = urwid.AttrMap(pied, 'head') maConversation = ConversationListBox() mainFrame = urwid.Frame(maConversation,filler_en_tete) maConversation.mainFrame=mainFrame mainLoop = urwid.MainLoop(mainFrame, palette) maConversation.mainLoop = mainLoop maConversation.en_tete = en_tete mainLoop.set_alarm_in(0, update_hour, en_tete) mainLoop.run()
def startConsole(self): # generate widget to show the status of the alert system for option in self.options: if option.type == "alertSystemActive": if option.value == 0: self.alertSystemActive = \ StatusUrwid("alert system status", "Status", "Deactivated") self.alertSystemActive.turnRed() else: self.alertSystemActive = \ StatusUrwid("alert system status", "Status", "Activated") self.alertSystemActive.turnGreen() if self.alertSystemActive == None: logging.error("[%s]: No alert system status option." % self.fileName) return # generate widget to show the status of the connection self.connectionStatus = StatusUrwid("connection status", "Status", "Online") self.connectionStatus.turnNeutral() # generate pin field self.pinEdit = PinUrwid("Enter PIN:\n", multiline=False, mask="*") self.pinEdit.registerConsoleInstance(self) # generate menu option1 = urwid.Text("1. Activate alert system") option2 = urwid.Text("2. Deactivate alert system") option3 = urwid.Text("3. Activate alert system in %d seconds" % self.timeDelayedActivation) separator = urwid.Text("") instruction = urwid.Text("Please, choose an option.") self.menuPile = urwid.Pile([option1, option2, option3, separator, instruction]) # generate edit/menu part of the screen self.editPartScreen = urwid.Pile([self.pinEdit]) boxedEditPartScreen = urwid.LineBox(self.editPartScreen, title="menu") # initialize warning view urwid self.warningView = WarningUrwid() # generate final body object self.finalBody = urwid.Pile([self.alertSystemActive.get(), self.connectionStatus.get(), boxedEditPartScreen]) fillerBody = urwid.Filler(self.finalBody, "top") # generate header header = urwid.Text("alertR keypad manager", align="center") # build frame for final rendering self.mainFrame = urwid.Frame(fillerBody, header=header) # color palette palette = [ ('redColor', 'black', 'dark red'), ('greenColor', 'black', 'dark green'), ('grayColor', 'black', 'light gray'), ('connected', 'black', 'dark green'), ('disconnected', 'black', 'dark red'), ('sensoralert', 'black', 'yellow'), ('connectionfail', 'black', 'light gray'), ('timedout', 'black', 'dark red'), ('neutral', '', ''), ] # create urwid main loop for the rendering self.mainLoop = urwid.MainLoop(self.mainFrame, palette=palette, unhandled_input=self.handleKeypress) # create a file descriptor callback to give other # threads the ability to communicate with the urwid thread self.screenFd = self.mainLoop.watch_pipe(self.screenCallback) # set the correct view in which we are self.inPinView = True self.inMenuView = False self.inWarningView = False # run urwid loop self.mainLoop.run()
def main(): global header, viewer, panes, footer, frame, searchterm searchterm = '' palette = [(None, 'light gray', 'black'), ('viewer', 'black', 'light gray'), ('focus', 'white', 'black', 'standout'), ('header', 'yellow', 'black', 'standout'), ('footer', 'light gray', 'black'), ('key', 'light cyan', 'black', 'underline'), ('error', 'dark red', 'light gray'), ('good', 'dark green', 'black', 'standout'), ('search', 'dark red', 'yellow')] def button_press(button, user_data=None): """Action when another file is selected, display its content in viewer""" global viewer, panes, footer, frame, term index = choice_path.index(user_data) thetitle = choice_text[index] frame.footer = urwid.Text('loading {}'.format(thetitle)) try: lines = file_contents(user_data).replace( '\r', '').expandtabs().split('\n') contents = [urwid.Text(x) for x in lines] viewer = urwid.AttrWrap( WheelableListBox(urwid.SimpleListWalker(contents)), 'viewer') viewer = urwid.LineBox(viewer, title=thetitle) frame.body = urwid.Columns([(choice_width, choice_list), ('weight', 1, viewer)], focus_column=1, dividechars=1) search(searchterm) frame.footer = urwid.AttrWrap( urwid.Text('loaded {}'.format(thetitle)), 'good') except: text = 'Could not read {}: {}' frame.footer = urwid.AttrWrap( urwid.Text(text.format(thetitle, sys.exc_info()[0])), 'error') choice_text = [] choice_path = [] if (args.directory is None and args.files is None and args.title is None): # No arguments supplied, use current directory. listing = sorted(os.listdir('.')) choice_text = [x for x in listing if os.path.isfile(x)] choice_path = choice_text elif args.directory: # User supplid a directory dir = args.directory files = sorted(os.listdir(dir)) isfile = os.path.isfile choice_text = [x for x in files if isfile(os.path.join(dir, x))] choice_path = [ os.path.join(dir, x) for x in files if isfile(os.path.join(dir, x)) ] elif args.files: # A list of files files = sorted(args.files) choice_text = [os.path.basename(x) for x in files if os.path.isfile(x)] choice_path = [x for x in files if os.path.isfile(x)] elif args.title: # Pairs of titles and files choice_text = [x[0] for x in args.title] choice_path = [x[1] for x in args.title] else: quit() # Create buttons choices = [] for index in range(len(choice_text)): choice = urwid.Button(choice_text[index], on_press=button_press, user_data=choice_path[index]) choices.append(choice) header = urwid.AttrWrap(urwid.Text(args.banner), 'header') choice_list = WheelableListBox(urwid.SimpleListWalker([header] + choices)) choice_width = min(max(len(x) for x in choice_text) + 4, 24) viewer = urwid.AttrWrap(WheelableListBox(urwid.SimpleListWalker([])), 'viewer') viewerr = urwid.LineBox(viewer, title=choice_text[0]) panes = urwid.Columns([(choice_width, choice_list), ('weight', 1, viewer)], focus_column=1, dividechars=1) footer = urwid.AttrWrap(urwid.Text(''), 'footer') frame = urwid.Frame(panes, footer=footer) button_press(None, choice_path[0]) loop = urwid.MainLoop(frame, palette=palette, unhandled_input=handle_key) loop.run()
def __init__(self, dbman, initialcmdline): """ :param dbman: :class:`~alot.db.DBManager` :param initialcmdline: commandline applied after setting up interface :type initialcmdline: str :param colourmode: determines which theme to chose :type colourmode: int in [1,16,256] """ self.dbman = dbman """Database Manager (:class:`~alot.db.manager.DBManager`)""" self.buffers = [] """list of active buffers""" self.current_buffer = None """points to currently active :class:`~alot.buffers.Buffer`""" self.db_was_locked = False """flag used to prevent multiple 'index locked' notifications""" self.mode = 'global' """interface mode identifier - type of current buffer""" self.commandprompthistory = [] """history of the command line prompt""" self.senderhistory = [] """history of the sender prompt""" self.recipienthistory = [] """history of the recipients prompt""" self.input_queue = [] """stores partial keyboard input""" self.last_commandline = None """saves the last executed commandline""" # define empty notification pile self._notificationbar = None # should we show a status bar? self._show_statusbar = settings.get('show_statusbar') # pass keypresses to the root widget and never interpret bindings self._passall = False # indicates "input lock": only focus move commands are interpreted self._locked = False self._unlock_callback = None # will be called after input lock ended self._unlock_key = None # key that ends input lock # alarm handle for callback that clears input queue (to cancel alarm) self._alarm = None # create root widget global_att = settings.get_theming_attribute('global', 'body') mainframe = urwid.Frame(urwid.SolidFill()) self.root_widget = urwid.AttrMap(mainframe, global_att) signal.signal(signal.SIGINT, self.handle_signal) signal.signal(signal.SIGUSR1, self.handle_signal) # load histories self._cache = os.path.join( os.environ.get('XDG_CACHE_HOME', os.path.expanduser('~/.cache')), 'alot', 'history') self._cmd_hist_file = os.path.join(self._cache, 'commands') self._sender_hist_file = os.path.join(self._cache, 'senders') self._recipients_hist_file = os.path.join(self._cache, 'recipients') size = settings.get('history_size') self.commandprompthistory = self._load_history_from_file( self._cmd_hist_file, size=size) self.senderhistory = self._load_history_from_file( self._sender_hist_file, size=size) self.recipienthistory = self._load_history_from_file( self._recipients_hist_file, size=size) # set up main loop self.mainloop = urwid.MainLoop( self.root_widget, handle_mouse=settings.get('handle_mouse'), event_loop=urwid.TwistedEventLoop(), unhandled_input=self._unhandled_input, input_filter=self._input_filter) # Create a defered that calls the loop_hook loop_hook = settings.get_hook('loop_hook') if loop_hook: loop = task.LoopingCall(loop_hook, ui=self) loop_defered = loop.start(settings.get('periodic_hook_frequency')) loop_defered.addErrback(lambda e: logging.error( 'error in loop hook %s', e.getErrorMessage())) # set up colours colourmode = int(settings.get('colourmode')) logging.info('setup gui in %d colours', colourmode) self.mainloop.screen.set_terminal_properties(colors=colourmode) logging.debug('fire first command') self.apply_commandline(initialcmdline) # start urwids mainloop self.mainloop.run()
def main(): text_header = (u"Amazon Product Review Summarization & Analysis - F8 exits.") text_intro = [ u"Hi! This tool will helps customer summarize and analyze reviews from Amazon product page," u"including review text summarization, sentiment analysis, key feature extraction. Finally, it will generate a markdown format report.", ('important', u"\nHow to use"), ('important', u"\nInput: "), u"Amazon product url copied from browser.", ('important', u"\nOutput: "), u"A markdown format report under path: /output/product_asin (Asin is the id of an amazon product)"] input_box_intro = u"Input / Paste Amazon Product URL:" text_edit_alignments = input_box_intro text_edit_left = u"" blank = urwid.Divider() def button_press(button): cur_text = text_edit_left frame.footer = urwid.Text(cur_text) input_box = urwid.Edit("", text_edit_left, align='left') listbox_content = [ blank, urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20), urwid.Text(text_edit_alignments), urwid.AttrWrap(input_box,'editbx', 'editfc'), ] header = urwid.AttrWrap(urwid.Text(text_header, align='center'), 'header') listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) palette = [ ('body','black','light gray', 'standout'), ('reverse','light gray','black'), ('header','white','dark red', 'bold'), ('important','dark blue','light gray',('standout','underline')), ('editfc','white', 'dark blue', 'bold'), ('editbx','light gray', 'dark blue'), ('editcp','black','light gray', 'standout'), ('bright','dark gray','light gray', ('bold','standout')), ('buttn','black','dark cyan'), ('buttnf','white','dark blue','bold'), ] output_widget = urwid.Text("Current Status:\n" ) frame = urwid.Frame(body = urwid.AttrWrap(listbox, 'body'), header=header, footer=output_widget) screen = urwid.raw_display.Screen() def received_output(data): output_widget.set_text(output_widget.text + data.decode('utf8')) proc = None def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() elif key == 'enter': url = input_box.get_edit_text() global proc proc = subprocess.Popen(['python', '-u', run_me, url], stdout=write_fd, close_fds=True) loop = urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled) run_me = os.path.join(os.path.dirname(sys.argv[0]), 'Main.py') write_fd = loop.watch_pipe(received_output) loop.run() proc.kill()
def ue_view_rrh3(self): """ RRH3 state window content Input : None Output : frame : urwid Frame object - showing content of RRH3 state window """ # State of screen self.state = 'log_rrh3' # Title denote server rrh3Title = [] rrh3Title.append(urwid.Divider('-')) rrh3Title.append( urwid.AttrWrap(urwid.Text("RRH 3", 'center'), 'button select')) rrh3Title.append(urwid.Divider('-')) rrh3TitleGrid = urwid.GridFlow(rrh3Title, 16, 0, 1, 'left') statusTable = [rrh3TitleGrid] # Column title title = [] title.append(urwid.AttrWrap(urwid.Text("UEID", 'center'), 'menuf')) title.append(urwid.AttrWrap(urwid.Text("IMSI", 'center'), 'menuf')) title.append(urwid.AttrWrap(urwid.Text("STATUS", 'center'), 'menuf')) titleGrid = urwid.GridFlow(title, 16, 0, 1, 'left') statusTable.append(titleGrid) # Lines separate rows in table border = [] border.append(urwid.Divider('-')) border.append(urwid.Divider('.')) border.append(urwid.Divider('-')) borderGrid = urwid.GridFlow(border, 16, 0, 1, 'left') if (self.rrh3SocketExist): # Each element in 'content' list is a row's content. content3 = [None] * len(self.rrh3Specific[0]) gridContent3 = [None] * len(self.rrh3Specific[0]) # Decorate each row in table for index in range(0, len(self.rrh3Specific[0])): content3[index] = [ urwid.AttrWrap( urwid.Text(self.rrh3Specific[0][index], 'center'), 'bg'), urwid.AttrWrap( urwid.Text(self.rrh3Specific[1][index], 'center'), 'bg'), urwid.AttrWrap( urwid.Text(self.rrh3Specific[2][index], 'center'), 'bg') ] gridContent3[index] = urwid.GridFlow(content3[index], 16, 0, 1, 'left') # Add detail to screen table content statusTable.append(gridContent3[index]) statusTable.append(borderGrid) # Build a rrh_status_window # Create table of content # for index in range(0, len(self.rrh3Specific[0])): # statusTable.append(gridContent3[index]) # statusTable.append(borderGrid) statusTable.append(borderGrid) rrhWindow = urwid.SimpleListWalker(statusTable) # Frame for RRH status window return urwid.AttrMap( urwid.Frame(urwid.ListBox(rrhWindow), self.menubar(), self.statusbar()), 'bg')
def make_player_ui(self): #Draws the main player UI #Header vol = self.player_object.volume // 10 self.txt2_1 = urwid.Text("--/--", align='left') self.txt2_2 = urwid.Text("Playing: None", align='center') self.txt2_3 = urwid.Text(u"Mode: Repeat off", align='right') self.txt2_4 = urwid.Text(f"Volume: {(vol-1)*'█'}{(9-vol)*'░'}", align='right') cols = urwid.Columns( [self.txt2_1, self.txt2_2, self.txt2_3, self.txt2_4], dividechars=0, focus_column=None, min_width=1, box_columns=None) head_widget = urwid.Pile([cols], focus_item=None) head_final_widget = self.body = urwid.LineBox( head_widget, title='Terminal Youtube Player', title_align='center', tlcorner='┌', tline='─', lline='│', trcorner='┐', blcorner='└', rline='│', bline='─', brcorner='┘') #body self.list = urwid.SimpleFocusListWalker([]) heading = urwid.Columns([(6, urwid.Text(u"Track", align='left')), (15, urwid.Text(u"Duration", align='left')), urwid.Text(u"Title", align='left'), urwid.Text(u"Artist", align='left')], dividechars=0, focus_column=None, min_width=1, box_columns=None) self.playlistbox = urwid.ListBox(self.list) self.body_pile = urwid.Pile( [(1, urwid.Filler(heading, valign='top', height='pack', min_height=None, top=0, bottom=0)), (1, urwid.Filler(urwid.Divider())), self.playlistbox], focus_item=2) self.body = urwid.LineBox(self.body_pile, title="", title_align='center', tlcorner='┌', tline='─', lline='│', trcorner='┐', blcorner='└', rline='│', bline='─', brcorner='┘') #Footer Progress bar self.pb = my_bar("reversed", "highlight") self.pb.set_completion(0) self.pb_text = urwid.Text("", align='right') footer_widget = urwid.Columns([self.pb, (14, self.pb_text)], dividechars=0, focus_column=None, min_width=1, box_columns=None) #Final player_ui object player_ui_object = urwid.Frame(self.body, header=head_final_widget, footer=footer_widget, focus_part='body') return urwid.Padding(player_ui_object, right=0, left=0)
def startConsole(self): # Generate widget to show the profile which is currently used by the system. option = self.system_data.get_option_by_type("profile") if option is None: logging.error("[%s]: No profile option." % self.fileName) return profile = self.system_data.get_profile_by_id(option.value) if profile is None: logging.error("[%s]: Profile with id %d does not exist." % (self.fileName, option.value)) return self._profile_urwid = StatusUrwid("Active System Profile", "Profile", profile.name) self._profile_urwid.set_color( self._profile_colors[profile.profileId % len(self._profile_colors)]) # generate widget to show the status of the connection self._connection_status = StatusUrwid("Connection Status", "Status", "Online") self._connection_status.set_color("neutral") # generate pin field self.pinEdit = PinUrwid("Enter PIN:\n", False, "*", self) # Generate menu. option1 = urwid.Text("1. Change system profile") option2 = urwid.Text("2. Change system profile in %d seconds" % self._time_delayed_profile_change) separator = urwid.Text("") instruction = urwid.Text("Please, choose an option.") self.menuPile = urwid.Pile([option1, option2, separator, instruction]) # generate edit/menu part of the screen self.editPartScreen = urwid.Pile([self.pinEdit]) boxedEditPartScreen = urwid.LineBox(self.editPartScreen, title="Menu") # initialize warning view urwid self._warning_view = WarningUrwid() # generate final body object self.finalBody = urwid.Pile([ self._profile_urwid.get(), self._connection_status.get(), boxedEditPartScreen ]) fillerBody = urwid.Filler(self.finalBody, "top") # generate header header = urwid.Text("AlertR Keypad Manager", align="center") # build frame for final rendering self.mainFrame = urwid.Frame(fillerBody, header=header) # color palette palette = [ ('redColor', 'black', 'dark red'), ('greenColor', 'black', 'dark green'), ('grayColor', 'black', 'light gray'), ('connected', 'black', 'dark green'), ('disconnected', 'black', 'dark red'), ('sensoralert', 'black', 'yellow'), ('connectionfail', 'black', 'light gray'), ('timedout', 'black', 'dark red'), ('neutral', '', ''), ('profile_0', 'black', 'dark green'), ('profile_1', 'black', 'dark red'), ('profile_2', 'black', 'dark cyan'), ('profile_3', 'black', 'dark magenta'), ('profile_4', 'black', 'yellow'), ] # create urwid main loop for the rendering self.mainLoop = urwid.MainLoop(self.mainFrame, palette=palette, unhandled_input=self.handleKeypress) # create a file descriptor callback to give other # threads the ability to communicate with the urwid thread self.screenFd = self.mainLoop.watch_pipe(self.screenCallback) # set the correct view in which we are self.inPinView = True self.inMenuView = False self._in_warning_view = False self._in_profile_choice_view = False # Start unlock checker thread. thread = threading.Thread(target=self._thread_screen_unlock_checker) thread.daemon = True thread.start() # run urwid loop self.mainLoop.run()
def cli(): global inp, err_bar, orig_stdin, orig_stdout, body, loop, jq_man if sys.stdin.isatty(): sys.stderr.write( 'error: jqed requires some data piped on standard input, for example try: `ip --json link | jqed`\n' ) exit(1) if len(sys.argv) > 2: sys.stderr.write('usage: jqed [initial expression]\n') exit(1) # Preserve original stdio, and replace stdio with /dev/tty orig_stdin = os.fdopen(os.dup(sys.stdin.fileno())) orig_stdout = os.fdopen(os.dup(sys.stdout.fileno()), mode='wb', buffering=0) os.close(0) os.close(1) sys.stdin = open('/dev/tty', 'rb') sys.stdout = open('/dev/tty', 'wb') # Apparently urwid has some artifacts with WSL, see issue #6 # Hopefully this won't break WSL2 if IS_WSL: urwid_screen = WSLScreen() else: urwid_screen = urwid.raw_display.Screen() # Create gui inp = BetterEdit(('prompt_ok', PROMPT)) if len(sys.argv) == 2: # If the user specified an argument, use it as an initial expression inp.set_edit_text(sys.argv[1]) inp.set_edit_pos(len(sys.argv[1])) body = urwid.Text('') body_filler = urwid.AttrMap(urwid.Filler(body, 'top'), 'body_plain') err_bar = urwid.Text(( 'inp_plain', 'HELP: ^C: Exit, ^P: Pause, jq manual: https://stedolan.github.io/jq/manual' )) frame = urwid.Frame(body_filler, header=urwid.AttrMap(inp, 'inp_plain'), footer=urwid.AttrMap(err_bar, 'err_bar'), focus_part='header') loop = urwid.MainLoop(frame, palette, handle_mouse=False, screen=urwid_screen) try: jq_man = JqManager(orig_stdin, loop) loop.run() except KeyboardInterrupt: line = shlex.quote(inp.edit_text.strip()) if line.startswith("''"): line = line[2:] if line.endswith("''"): line = line[:-2] try: orig_stdout.write( ('{}\njqed: jq editor ' + VERSION + ' https://github.com/wazzaps/jqed\n' + 'jqed: | jq {}\n').format(jq_man.out_data, line).encode()) except BrokenPipeError: sys.stderr.write('jq {}\n'.format(line)) exit(0)
urwid.Button (u"Button 3", click_handler) ] # We'll combine the Button objects in a Column object, stacking the buttons # horizontally. Previously this was a Pile to stack vertically, but then the # buttons would expand to the full width of the window. body_columns = urwid.Columns ( BUTTON_LIST, dividechars=8 ) # The frame we use later must have a box object for its body. body_filled = urwid.Filler( body_columns, height='pack', valign='top' ) layout = urwid.Frame( body_filled, header=text_header ) loop = urwid.MainLoop(layout, palette) loop.run()
def f_wrap(*args, **kwargs): footer = urwid.AttrWrap(urwid.Text(ViewUtil.FOOTER_TEXT), "background") return urwid.Frame(urwid.AttrWrap(func(*args, **kwargs), "background"), footer=footer)
def __init__(self): # craete interface with Frame and the body is made of 3 columns and wrap the columns in lineBoxes to have borders self.walker1 = urwid.SimpleFocusListWalker([]) self.walker3 = urwid.SimpleFocusListWalker([]) self.walker2 = urwid.SimpleFocusListWalker([]) self.div = urwid.Divider() self.box = urwid.ListBox(self.walker1) self.line = urwid.LineBox(self.box, title='SSID', tlcorner=u'\u250c', tline=u'\u2500', lline=u'\u2502', trcorner=u'\u2510', blcorner=u'\u2514', rline=u'\u2502', bline=u'\u2500', brcorner=u'\u2518') self.box2 = urwid.ListBox(self.walker2) self.line2 = urwid.LineBox(self.box2, title='Client', tlcorner=u'\u250c', tline=u'\u2500', lline=u'\u2502', trcorner=u'\u2510', blcorner=u'\u2514', rline=u'\u2502', bline=u'\u2500', brcorner=u'\u2518') self.box3 = urwid.ListBox(self.walker3) self.line3 = urwid.LineBox(self.box3, title='BSSID', tlcorner=u'\u250c', tline=u'\u2500', lline=u'\u2502', trcorner=u'\u2510', blcorner=u'\u2514', rline=u'\u2502', bline=u'\u2500', brcorner=u'\u2518') self.pile = urwid.Columns([('weight', 2, self.line), ('weight', 2, self.line2)]) self.con = urwid.Text([u'Console']) self.lineCon = urwid.LineBox(self.con, title='', tlcorner=u'\u250c', tline=u'\u2500', lline=u'\u2502', trcorner=u'\u2510', blcorner=u'\u2514', rline=u'\u2502', bline=u'\u2500', brcorner=u'\u2518') self.title = urwid.Text([u'Wireless De-atuth PeW PeW !!!']) self.lineTitle = urwid.LineBox(self.title, title='', tlcorner=u'\u250c', tline=u'\u2500', lline=u'\u2502', trcorner=u'\u2510', blcorner=u'\u2514', rline=u'\u2502', bline=u'\u2500', brcorner=u'\u2518') self.top = urwid.Frame(self.pile, footer=self.lineCon, header=self.lineTitle) self.editing = False self.main() self.index = 0
def status_view(self): """ RRH state window content Input : None Output : frame : urwid Frame object - showing content of RRH state window """ # State of screen self.state = 'info' self.isConfiguring = False # Titles of statistic table bodyTitle = [] bodyTitle.append(urwid.AttrWrap(urwid.Text("RRH"), 'menuf')) bodyTitle.append(urwid.AttrWrap(urwid.Text("Attached"), 'menuf')) bodyTitle.append(urwid.AttrWrap(urwid.Text("Detached"), 'menuf')) bodyTitle.append(urwid.AttrWrap(urwid.Text("Attaching"), 'menuf')) titleGrid = urwid.GridFlow(bodyTitle, 10, 0, 1, 'left') # Statistic table content attributes = [titleGrid] # Brief statistic content of RRH 1 if (self.rrh1SocketExist): rrh1 = [] rrh1Button = self.button("RRH 1") rrh1.append(rrh1Button) rrh1.append( urwid.AttrWrap(urwid.Text(self.rrh1Overview[0], 'center'), 'menuh')) rrh1.append( urwid.AttrWrap(urwid.Text(self.rrh1Overview[1], 'center'), 'menuh')) rrh1.append( urwid.AttrWrap(urwid.Text(self.rrh1Overview[2], 'center'), 'menuh')) rrh1Grid = urwid.GridFlow(rrh1, 10, 0, 1, 'left') attributes.append(rrh1Grid) # Brief statistic content of RRH 2 if (self.rrh2SocketExist): rrh2 = [] rrh2Button = self.button("RRH 2") rrh2.append(rrh2Button) rrh2.append( urwid.AttrWrap(urwid.Text(self.rrh2Overview[0], 'center'), 'menuh')) rrh2.append( urwid.AttrWrap(urwid.Text(self.rrh2Overview[1], 'center'), 'menuh')) rrh2.append( urwid.AttrWrap(urwid.Text(self.rrh2Overview[2], 'center'), 'menuh')) rrh2Grid = urwid.GridFlow(rrh2, 10, 0, 1, 'left') attributes.append(rrh2Grid) # Brief statistic content of RRH 3 if (self.rrh3SocketExist): rrh3 = [] rrh3Button = self.button("RRH 3") rrh3.append(rrh3Button) rrh3.append( urwid.AttrWrap(urwid.Text(self.rrh3Overview[0], 'center'), 'menuh')) rrh3.append( urwid.AttrWrap(urwid.Text(self.rrh3Overview[1], 'center'), 'menuh')) rrh3.append( urwid.AttrWrap(urwid.Text(self.rrh3Overview[2], 'center'), 'menuh')) rrh3Grid = urwid.GridFlow(rrh3, 10, 0, 1, 'left') attributes.append(rrh3Grid) # Create frame for Info window self.nattributes = urwid.SimpleListWalker(attributes) self.body = urwid.ListBox(self.nattributes) frame = urwid.AttrMap( urwid.Frame(self.body, self.menubar(), self.statusbar()), 'bg') return frame
def __init__(self): """Creates main widgets and creates mainloop""" self.config = utils.parse_config(utils.to_config_path('ui-curses.json'), utils.curses_defaults) keymap = utils.curses_defaults['keymap'] keymap.update(self.config['keymap']) self.keymap_str = self.get_keymap_str(keymap) self.keymapping = self.map_key_to_func(keymap) palette = [] for k, color in self.config['palette'].items(): palette.append( (k, color[0], color[1]) ) # Prepare header sys.stdout.write("\x1b]0;Trackma-curses "+utils.VERSION+"\x07"); self.header_title = urwid.Text('Trackma-curses ' + utils.VERSION) self.header_api = urwid.Text('API:') self.header_filter = urwid.Text('Filter:') self.header_sort = urwid.Text('Sort:title') self.header_order = urwid.Text('Order:d') self.header = urwid.AttrMap(urwid.Columns([ self.header_title, ('fixed', 30, self.header_filter), ('fixed', 17, self.header_sort), ('fixed', 16, self.header_api)]), 'status') top_pile = [self.header] if self.config['show_help']: top_text = "{help}:Help {sort}:Sort " + \ "{update}:Update {play}:Play " + \ "{status}:Status {score}:Score " + \ "{quit}:Quit" top_text = top_text.format(**self.keymap_str) top_pile.append(urwid.AttrMap(urwid.Text(top_text), 'status')) self.top_pile = urwid.Pile(top_pile) # Prepare status bar self.status_text = urwid.Text('Trackma-curses '+utils.VERSION) self.status_queue = urwid.Text('Q:N/A') self.status_tracker = urwid.Text('T:N/A') self.statusbar = urwid.AttrMap(urwid.Columns([ self.status_text, ('fixed', 10, self.status_tracker), ('fixed', 6, self.status_queue), ]), 'status') self.listheader = urwid.AttrMap( urwid.Columns([ ('weight', 1, urwid.Text('Title')), ('fixed', 10, urwid.Text('Progress')), ('fixed', 7, urwid.Text('Score')), ]), 'header') self.listwalker = ShowWalker([]) self.listbox = urwid.ListBox(self.listwalker) self.listframe = urwid.Frame(self.listbox, header=self.listheader) self.viewing_info = False self.view = urwid.Frame(self.listframe, header=self.top_pile, footer=self.statusbar) self.mainloop = urwid.MainLoop(self.view, palette, unhandled_input=self.keystroke, screen=urwid.raw_display.Screen())
def show_popup(self, target): """Show the popup.""" if self.stack_main_loop is None: raise Exception("Please set StackMainLoop for this widget.") self.stack_main_loop.push_widget( urwid.Frame(self.pile, self.search, None, 'header'))
def main(self): #Disable kernel print messages. They make our UI ugly noout = open('/dev/null', 'w') subprocess.call(["sysctl", "-w", "kernel.printk=4 1 1 7"], stdout=noout, stderr=noout) text_header = (u"Fuel %s setup " u"Use Up/Down/Left/Right to navigate. F8 exits." % self.version) text_footer = (u"Status messages go here.") #Top and bottom lines of frame self.header = urwid.AttrWrap(urwid.Text(text_header), 'header') self.footer = urwid.AttrWrap(urwid.Text(text_footer), 'footer') #Prepare submodules loader = Loader(self) moduledir = "%s/modules" % (os.path.dirname(__file__)) self.children, self.choices = loader.load_modules(module_dir=moduledir) if len(self.children) == 0: import sys sys.exit(1) self.menuitems = self.menu(u'Menu', self.choices) menufill = urwid.Filler(self.menuitems, 'top', 40) self.menubox = urwid.BoxAdapter(menufill, 40) self.child = self.children[0] self.childpage = self.child.screenUI() self.childfill = urwid.Filler(self.childpage, 'top', 22) self.childbox = urwid.BoxAdapter(self.childfill, 22) self.cols = urwid.Columns( [('fixed', 20, urwid.Pile( [urwid.AttrMap(self.menubox, 'bright'), urwid.Divider(" ")])), ('weight', 3, urwid.Pile( [urwid.Divider(" "), self.childbox, urwid.Divider(" ")]))], 1) self.listwalker = urwid.SimpleListWalker([self.cols]) #self.listwalker = urwid.TreeWalker([self.cols]) self.listbox = urwid.ListBox(self.listwalker) #listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) self.frame = urwid.Frame(urwid.AttrWrap(self.listbox, 'body'), header=self.header, footer=self.footer) palette = \ [ ('body', 'black', 'light gray', 'standout'), ('reverse', 'light gray', 'black'), ('header', 'white', 'dark red', 'bold'), ('important', 'dark blue', 'light gray', ('standout', 'underline')), ('editfc', 'white', 'dark blue', 'bold'), ('editbx', 'light gray', 'dark blue'), ('editcp', 'black', 'light gray', 'standout'), ('bright', 'dark gray', 'light gray', ('bold', 'standout')), ('buttn', 'black', 'dark cyan'), ('buttnf', 'white', 'dark blue', 'bold'), ('light gray', 'white', 'light gray', 'bold'), ('red', 'dark red', 'light gray', 'bold'), ('black', 'black', 'black', 'bold'), ] # use appropriate Screen class if urwid.web_display.is_web_request(): self.screen = urwid.web_display.Screen() else: self.screen = urwid.raw_display.Screen() def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() if key == 'shift tab': self.child.walker.tab_prev() if key == 'tab': self.child.walker.tab_next() self.mainloop = urwid.MainLoop(self.frame, palette, self.screen, unhandled_input=unhandled) #Initialize each module completely before any events are handled for child in reversed(self.choices): self.setChildScreen(name=child) #Prepare DNS for resolution dnsobj = self.children[int(self.choices.index("DNS & Hostname"))] dnsobj.setEtcResolv() self.mainloop.run()
def __init__(self, master): self.master = master self.lb = select.Select( [ select.Heading("Traffic Manipulation"), select.Option( "Header Set Patterns", "H", lambda: master.setheaders.count(), self.setheaders ), select.Option( "Ignore Patterns", "I", lambda: master.server.config.check_ignore, self.ignorepatterns ), select.Option( "Replacement Patterns", "R", lambda: master.replacehooks.count(), self.replacepatterns ), select.Option( "Scripts", "S", lambda: master.scripts, self.scripts ), select.Heading("Interface"), select.Option( "Default Display Mode", "M", self.has_default_displaymode, self.default_displaymode ), select.Option( "Palette", "P", lambda: self.master.palette != palettes.DEFAULT, self.palette ), select.Option( "Show Host", "w", lambda: master.showhost, self.toggle_showhost ), select.Heading("Network"), select.Option( "No Upstream Certs", "U", lambda: master.server.config.no_upstream_cert, self.toggle_upstream_cert ), select.Option( "TCP Proxying", "T", lambda: master.server.config.check_tcp, self.tcp_proxy ), select.Heading("Utility"), select.Option( "Anti-Cache", "a", lambda: master.anticache, self.toggle_anticache ), select.Option( "Anti-Compression", "o", lambda: master.anticomp, self.toggle_anticomp ), select.Option( "Kill Extra", "x", lambda: master.killextra, self.toggle_killextra ), select.Option( "No Refresh", "f", lambda: not master.refresh_server_playback, self.toggle_refresh_server_playback ), select.Option( "Sticky Auth", "A", lambda: master.stickyauth_txt, self.sticky_auth ), select.Option( "Sticky Cookies", "t", lambda: master.stickycookie_txt, self.sticky_cookie ), ] ) title = urwid.Text("Options") title = urwid.Padding(title, align="left", width=("relative", 100)) title = urwid.AttrWrap(title, "heading") self._w = urwid.Frame( self.lb, header = title ) self.master.loop.widget.footer.update("") signals.update_settings.connect(self.sig_update_settings)
def __init__(self, parname, theta, initsize=None): """Parameters ---------- parname : str Name of the list in ``theta``. It we be displayed to the user in the selection dialog. theta : 1-d array Sequence of values. If not an array, will be turned into an array. The values in this sequence will be presented to the user for interactive selection. Every value will have a checkbox. initsize : float | None If not None, it is the size (e.g. in GB, or simply in counts) associated with the full size of 'something', pre-selection. This size will be numerically reduced for every element removed during the selection. If None, no size computation will be performed. Returns ------- Nothing. But after running the interactive selection, see member self.idxes, it contains the selected indices. """ self.theta = theta if not isinstance(self.theta, N.ndarray): self.theta = N.array(self.theta) self.parname = parname self.initsize = initsize # set colors for bg, fg, and other elements # self.palette = [ ('header', 'white,bold', 'dark red'), # ('body', 'white,bold', 'light gray'), # ('buttn', 'black', 'light gray'), # ('buttnf', 'light green,bold', 'light gray'), # ('selected', 'white', 'dark blue') ] self.palette = [('header', 'white,bold', 'dark blue'), ('body', 'white,bold', 'dark cyan'), ('buttn', 'black', 'dark cyan'), ('buttnf', 'white,bold', 'dark cyan'), ('selected', 'white', 'dark blue')] self.ui = urwid.curses_display.Screen() self.HEADER = urwid.AttrWrap( urwid.Text("Use the keyboard arrows to move between checkboxes.\n" +\ "Hit SPACE to select/deselect. Hit ENTER when done.\n\n" +\ "Select values for parameter %s" % parname), 'header') strings = [str(e) for e in self.theta] len_ = int(N.max([len(e) for e in strings])) self.cells = [ urwid.AttrWrap(urwid.CheckBox(e, state=True), 'buttn', 'buttnf') for e in strings ] self.pad = urwid.Padding( urwid.GridFlow(self.cells, 4 + int(len_), 2, 0, 'left'), ('fixed left', 4), ('fixed right', 3)) self.listbox = urwid.ListBox([self.pad]) self.view = urwid.Frame(urwid.AttrWrap(self.listbox, 'body'), header=self.HEADER) self.update_footer() self.ui.register_palette(self.palette) self.ui.run_wrapper(self.run)
def gui(self, key): self.do_gui = True self.last_view = [] self.status_bar = self.config.get_config('status_bar') self.log_alarms = 0 self.log_lock = threading.Lock() self.thread_sync = threading.Thread(target=self.ndb.sync_worker, args=[self.do_server_sync]) self.thread_sync.setDaemon(True) self.view_titles = \ view_titles.ViewTitles(self.config, { 'ndb' : self.ndb, 'search_string' : None, 'log' : self.log }) self.view_note = \ view_note.ViewNote(self.config, { 'ndb' : self.ndb, 'key' : key, # initial key to view or None 'log' : self.log }) self.view_log = view_log.ViewLog(self.config) self.view_help = view_help.ViewHelp(self.config) palette = \ [ ('default', self.config.get_color('default_fg'), self.config.get_color('default_bg') ), ('status_bar', self.config.get_color('status_bar_fg'), self.config.get_color('status_bar_bg') ), ('log', self.config.get_color('log_fg'), self.config.get_color('log_bg') ), ('user_input_bar', self.config.get_color('user_input_bar_fg'), self.config.get_color('user_input_bar_bg') ), ('note_focus', self.config.get_color('note_focus_fg'), self.config.get_color('note_focus_bg') ), ('note_title_day', self.config.get_color('note_title_day_fg'), self.config.get_color('note_title_day_bg') ), ('note_title_week', self.config.get_color('note_title_week_fg'), self.config.get_color('note_title_week_bg') ), ('note_title_month', self.config.get_color('note_title_month_fg'), self.config.get_color('note_title_month_bg') ), ('note_title_year', self.config.get_color('note_title_year_fg'), self.config.get_color('note_title_year_bg') ), ('note_title_ancient', self.config.get_color('note_title_ancient_fg'), self.config.get_color('note_title_ancient_bg') ), ('note_date', self.config.get_color('note_date_fg'), self.config.get_color('note_date_bg') ), ('note_flags', self.config.get_color('note_flags_fg'), self.config.get_color('note_flags_bg') ), ('note_tags', self.config.get_color('note_tags_fg'), self.config.get_color('note_tags_bg') ), ('note_content', self.config.get_color('note_content_fg'), self.config.get_color('note_content_bg') ), ('note_content_focus', self.config.get_color('note_content_focus_fg'), self.config.get_color('note_content_focus_bg') ), ('note_content_old', self.config.get_color('note_content_old_fg'), self.config.get_color('note_content_old_bg') ), ('note_content_old_focus', self.config.get_color('note_content_old_focus_fg'), self.config.get_color('note_content_old_focus_bg') ), ('help_focus', self.config.get_color('help_focus_fg'), self.config.get_color('help_focus_bg') ), ('help_header', self.config.get_color('help_header_fg'), self.config.get_color('help_header_bg') ), ('help_config', self.config.get_color('help_config_fg'), self.config.get_color('help_config_bg') ), ('help_value', self.config.get_color('help_value_fg'), self.config.get_color('help_value_bg') ), ('help_descr', self.config.get_color('help_descr_fg'), self.config.get_color('help_descr_bg') ) ] self.master_frame = urwid.Frame(body=urwid.Filler(urwid.Text(u'')), header=None, footer=urwid.Pile( [urwid.Pile([]), urwid.Pile([])]), focus_part='body') self.sncli_loop = urwid.MainLoop(self.master_frame, palette, handle_mouse=False) self.sncli_loop.set_alarm_in(0, self.gui_init_view, True if key else False) self.sncli_loop.run()
def __init__(self, exception): self._text = urwid.Text([('bold',str(exception)), '\nPress any key to continue']) self._frame = urwid.Frame(urwid.SolidFill(), footer=self._text) self._frame.set_focus('footer') urwid.WidgetWrap.__init__(self, self._frame)
#!/usr/bin/python import subprocess import urwid import os import sys factor_me = 362923067964327863989661926737477737673859044111968554257667 run_me = os.path.join(os.path.dirname(sys.argv[0]), 'subproc2.py') output_widget = urwid.Text("Factors of %d:\n" % factor_me) edit_widget = urwid.Edit("Type anything or press enter to exit:") frame_widget = urwid.Frame(header=edit_widget, body=urwid.Filler(output_widget, valign='bottom'), focus_part='header') def exit_on_enter(key): if key == 'enter': raise urwid.ExitMainLoop() loop = urwid.MainLoop(frame_widget, unhandled_input=exit_on_enter) def received_output(data): output_widget.set_text(output_widget.text + data.decode('utf8')) write_fd = loop.watch_pipe(received_output) proc = subprocess.Popen( ['python', '-u', run_me, str(factor_me)], stdout=write_fd, close_fds=True)
def view_log(self): header = urwid.AttrMap(urwid.Text(self.header_text), 'header') footer = urwid.AttrMap(urwid.Text(self.footer_log_text), 'foot') frame = urwid.Frame(self.log, header=header, footer=footer) self.push_view(self, frame)
def main(): parser = OptionParser() parser.add_option("-v", "--verbose", action="count", default=0), (options, args) = parser.parse_args() if options.verbose: formatter = logging.Formatter( "%(asctime)s [%(levelname)8s] %(message)s", datefmt='%Y-%m-%d %H:%M:%S') fh = logging.FileHandler("datatable.log") # fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) if options.verbose > 1: logger.setLevel(logging.DEBUG) logging.getLogger("panwid.datatable").setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) logging.getLogger("panwid.datatable").setLevel(logging.INFO) logger.addHandler(fh) logging.getLogger("panwid.datatable").addHandler(fh) # logging.getLogger("raccoon.dataframe").setLevel(logging.DEBUG) # logging.getLogger("raccoon.dataframe").addHandler(fh) attr_entries = {} for attr in ["dark red", "dark green", "dark blue"]: attr_entries[attr.split()[1]] = PaletteEntry(mono="white", foreground=attr, background="black") entries = ScrollingListBox.get_palette_entries() entries.update(DataTable.get_palette_entries(user_entries=attr_entries)) palette = Palette("default", **entries) COLUMNS = [ # DataTableColumn("uniqueid", width=10, align="right", padding=1), DataTableColumn( "foo", label="Foo", width=5, align="right", sort_key=lambda v: (v is None, v), attr="color", padding=0, footer_fn=lambda column, values: sum(v for v in values if v is not None)), DataTableColumn("bar", label="Bar", width=10, align="right", sort_reverse=True, sort_icon=False, padding=1), # margin=5), DataTableColumn("baz", label="Baz!", width=("weight", 1)), DataTableColumn("qux", label=urwid.Text([("red", "q"), ("green", "u"), ("blue", "x")]), width=5, hide=True), # DataTableColumn("empty", label="empty", width=5), ] class ExampleDataTable(DataTable): columns = COLUMNS[:] index = "index" def __init__(self, num_rows=10, *args, **kwargs): self.num_rows = num_rows # indexes = random.sample(range(self.num_rows*2), num_rows) self.randomize_query_data() self.last_rec = len(self.query_data) super(ExampleDataTable, self).__init__(*args, **kwargs) def randomize_query_data(self): indexes = list(range(self.num_rows)) self.query_data = [ self.random_row(indexes[i]) for i in range(self.num_rows) # self.random_row(i) for i in range(self.num_rows) ] random.shuffle(self.query_data) def random_row(self, uniqueid): return dict( uniqueid=uniqueid, foo=random.choice(list(range(100)) + [None] * 20), bar=(random.uniform(0, 1000) if random.randint(0, 5) else None), baz=(''.join( random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + ' ' * 10) for _ in range(random.randint(5, 20))) if random.randint( 0, 5) else None), qux=urwid.Text([("red", "1"), ("green", "2"), ("blue", "3")]), xyzzy=("%0.1f" % (random.uniform(0, 100)) if random.randint( 0, 5) else None), baz_len=lambda r: len(r["baz"]) if r.get("baz") else 0, # xyzzy = random.randint(10, 100), empty=None, a=dict(b=dict(c=random.randint(0, 100))), d=dict(e=dict(f=random.randint(0, 100))), color=["red", "green", "blue"][random.randrange(3)], ) def query(self, sort=(None, None), offset=None, limit=None, load_all=False): logger.info("query: offset=%s, limit=%s, sort=%s" % (offset, limit, sort)) try: sort_field, sort_reverse = sort except: sort_field = sort sort_reverse = None if sort_field: kwargs = {} kwargs["key"] = lambda x: (x.get( sort_field) is None, x.get(sort_field), x.get(self.index)) if sort_reverse: kwargs["reverse"] = sort_reverse self.query_data.sort(**kwargs) if offset is not None: if not load_all: start = offset end = offset + limit r = self.query_data[start:end] logger.debug("%s:%s (%s)" % (start, end, len(r))) else: r = self.query_data[offset:] else: r = self.query_data for d in r: yield d def query_result_count(self): return self.num_rows def keypress(self, size, key): if key == "meta r": self.randomize_query_data() self.reset(reset_sort=True) if key == "ctrl r": self.reset(reset_sort=True) if key == "ctrl d": self.log_dump(20) if key == "meta d": self.log_dump(20, columns=["foo", "baz"]) if key == "ctrl f": self.focus_position = 0 elif key == "ctrl t": # logger.info(self.get_row(0)[0]) logger.info(self.selection.data["bar"]) elif key == "meta i": logger.info( "foo %s, baz: %s" % (self.selection.get("foo"), self.selection.get("baz"))) elif self.ui_sort and key.isdigit() and int(key) - 1 in range( len(self.columns)): col = int(key) - 1 self.sort_by_column(col, toggle=True) elif key == "ctrl l": self.load("test.json") elif key == "ctrl s": self.save("test.json") elif key == "0": # self.sort_by_column(self.index, toggle=True) self.sort_index() elif key == "a": self.add_row(self.random_row(self.last_rec)) self.last_rec += 1 elif key == "A": self.add_row(self.random_row(self.last_rec), sort=False) self.last_rec += 1 elif key == "d": if len(self): self.delete_rows(self.df.index[self.focus_position]) elif key == "meta a": name = "".join( random.choice(string.ascii_uppercase + string.lowercase + string.digits) for _ in range(5)) data = [ "".join( random.choice(string.ascii_uppercase + string.lowercase + string.digits) for _ in range(5)) for _ in range(len(self)) ] col = DataTableColumn(name, label=name, width=6, padding=0) self.add_columns(col, data=data) elif key == "r": self.set_columns(COLUMNS) elif key == "t": self.toggle_columns("qux") elif key == "T": self.toggle_columns(["foo", "baz"]) elif key == "D": self.remove_columns(len(self.columns) - 1) elif key == "f": self.apply_filters( [lambda x: x["foo"] > 20, lambda x: x["bar"] < 800]) elif key == "F": self.clear_filters() elif key == ".": self.toggle_details() elif key == "s": self.selection.set_attr("red") elif key == "S": self.selection.clear_attr("red") elif key == "k": self.selection[2].set_attr("red") elif key == "K": self.selection[2].clear_attr("red") elif key == "u": logger.info(self.footer.values) elif key == "c": self.toggle_cell_selection() elif key == "shift left": self.cycle_sort_column(-1) elif key == "shift right": self.cycle_sort_column(1) elif self.ui_sort and key == "shift up": self.sort_by_column(reverse=True) elif self.ui_sort and key == "shift down": self.sort_by_column(reverse=False) elif key == "shift end": self.load_all() # self.listbox.focus_position = len(self) -1 elif key == "ctrl up": if self.focus_position > 0: self.swap_rows(self.focus_position, self.focus_position - 1, "foo") self.focus_position -= 1 elif key == "ctrl down": if self.focus_position < len(self) - 1: self.swap_rows(self.focus_position, self.focus_position + 1, "foo") self.focus_position += 1 else: return super(ExampleDataTable, self).keypress(size, key) class ExampleDataTableBox(urwid.WidgetWrap): def __init__(self, *args, **kwargs): self.table = ExampleDataTable(*args, **kwargs) urwid.connect_signal( self.table, "select", lambda source, selection: logger.info("selection: %s" % (selection))) label = "sz:%d pgsz:%s sort:%s%s hdr:%s ftr:%s ui_sort:%s cell_sel:%s" % ( self.table.query_result_count(), self.table.limit if self.table.limit else "-", "-" if self.table.sort_by[1] else "+" if self.table.sort_by[0] else "n", self.table.sort_by[0] or " ", "y" if self.table.with_header else "n", "y" if self.table.with_footer else "n", "y" if self.table.ui_sort else "n", "y" if self.table.cell_selection else "n", ) self.pile = urwid.Pile([("pack", urwid.Text(label)), ("pack", urwid.Divider(u"\N{HORIZONTAL BAR}")), ("weight", 1, self.table)]) self.box = urwid.BoxAdapter(urwid.LineBox(self.pile), 25) super(ExampleDataTableBox, self).__init__(self.box) def detail_fn(data): return urwid.Padding( urwid.Columns([ ("weight", 1, data.get("qux")), ("weight", 1, urwid.Text(str(data.get("baz_len")))), ("weight", 2, urwid.Text(str(data.get("xyzzy")))), ])) boxes = [ ExampleDataTableBox(10, index="uniqueid", detail_fn=detail_fn, detail_column="bar", cell_selection=True, sort_refocus=True), ExampleDataTableBox( 1000, index="uniqueid", sort_by="foo", query_sort=False, ui_sort=False, with_footer=True, with_scrollbar=True, ), ExampleDataTableBox( 500, columns=[ DataTableColumn("row", width=7, value="{row}/{rows_total}") ] + ExampleDataTable.columns, limit=25, index="uniqueid", sort_by=("bar", True), sort_icons=False, query_sort=True, with_footer=True, with_scrollbar=True, cell_selection=True, border=(1, u"\N{VERTICAL LINE}", "blue"), padding=3, ), ExampleDataTableBox( 5000, limit=500, index="uniqueid", sort_by=("foo", True), border=3, query_sort=True, with_scrollbar=True, with_header=False, with_footer=False, ), ] grid_flow = urwid.GridFlow(boxes, 60, 1, 1, "left") def global_input(key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() else: return False old_signal_keys = screen.tty_signal_keys() l = list(old_signal_keys) l[0] = 'undefined' l[3] = 'undefined' l[4] = 'undefined' screen.tty_signal_keys(*l) main = urwid.MainLoop(urwid.Frame( urwid.Filler(urwid.LineBox(grid_flow), valign="top")), palette=palette, screen=screen, unhandled_input=global_input) try: main.run() finally: screen.tty_signal_keys(*old_signal_keys)
if __name__ == "__main__": cwd = os.getcwd() # get current working directory dtree = DirectoryTree() # get a directory walker # Use CollapsibleArrowTree for decoration. # define initial collapse: as_deep_as_cwd = lambda pos: dtree.depth(pos) >= dtree.depth(cwd) # We hide the usual arrow tip and use a customized collapse-icon. decorated_tree = CollapsibleArrowTree( dtree, is_collapsed=as_deep_as_cwd, arrow_tip_char=None, icon_frame_left_char=None, icon_frame_right_char=None, icon_collapsed_char=u'\u25B6', icon_expanded_char=u'\u25B7', ) # stick it into a TreeBox and use 'body' color attribute for gaps tb = TreeBox(decorated_tree, focus=cwd) root_widget = urwid.AttrMap(tb, 'body') #add a text footer footer = urwid.AttrMap(urwid.Text('Q to quit'), 'focus') #enclose all in a frame urwid.MainLoop(urwid.Frame(root_widget, footer=footer), palette, unhandled_input=unhandled_input).run() # go
def __init__(self, dbman, initialcmdline): """ :param dbman: :class:`~alot.db.DBManager` :param initialcmdline: commandline applied after setting up interface :type initialcmdline: str :param colourmode: determines which theme to chose :type colourmode: int in [1,16,256] """ self.dbman = dbman """Database Manager (:class:`~alot.db.manager.DBManager`)""" self.buffers = [] """list of active buffers""" self.current_buffer = None """points to currently active :class:`~alot.buffers.Buffer`""" self.db_was_locked = False """flag used to prevent multiple 'index locked' notifications""" self.mode = 'global' """interface mode identifier - type of current buffer""" self.commandprompthistory = [] """history of the command line prompt""" self.input_queue = [] """stores partial keyboard input""" self.last_commandline = None """saves the last executed commandline""" # define empty notification pile self._notificationbar = None # should we show a status bar? self._show_statusbar = settings.get('show_statusbar') # pass keypresses to the root widget and never interpret bindings self._passall = False # indicates "input lock": only focus move commands are interpreted self._locked = False self._unlock_callback = None # will be called after input lock ended self._unlock_key = None # key that ends input lock # alarm handle for callback that clears input queue (to cancel alarm) self._alarm = None # create root widget global_att = settings.get_theming_attribute('global', 'body') mainframe = urwid.Frame(urwid.SolidFill()) self.root_widget = urwid.AttrMap(mainframe, global_att) # set up main loop self.mainloop = urwid.MainLoop(self.root_widget, handle_mouse=False, event_loop=urwid.TwistedEventLoop(), unhandled_input=self._unhandeled_input, input_filter=self._input_filter) # set up colours colourmode = int(settings.get('colourmode')) logging.info('setup gui in %d colours' % colourmode) self.mainloop.screen.set_terminal_properties(colors=colourmode) logging.debug('fire first command') self.apply_commandline(initialcmdline) # start urwids mainloop self.mainloop.run()
def main(): text_header = (u"hi! " u"UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits.") Radio_Text = [ u"Select ", ('important', u"one"), ] Multiselect_Text = [ u"Select ", ('important', u"many"), ] MultiSelect_Options = [ u"Wax", u"Wash", u"Buff", u"Clear Coat", u"Dry", u"Racing Stripe" ] Radio_Options = [u"opt1", u"opt2", u"opt3"] def button_press(button): frame.footer = urwid.AttrWrap( urwid.Text([u"Pressed: ", button.get_label()]), 'header') radio_button_group = [] AttrWraps_list = [ urwid.AttrWrap(urwid.CheckBox(txt), 'buttn', 'buttnf') for txt in MultiSelect_Options ] blank = urwid.Divider() listbox_content = [ blank, urwid.Padding(urwid.Text(Radio_Text), left=2, right=2, min_width=20), blank, urwid.Padding(urwid.GridFlow([ urwid.AttrWrap(urwid.RadioButton(radio_button_group, txt), 'buttn', 'buttnf') for txt in Radio_Options ], 23, 7, 1, 'left'), left=3, right=3, min_width=20), blank, urwid.Padding(urwid.Text(Multiselect_Text), left=2, right=2, min_width=20), blank, urwid.Padding(urwid.GridFlow([ urwid.AttrWrap(urwid.CheckBox(txt), 'buttn', 'buttnf') for txt in MultiSelect_Options ], 10, 3, 1, 'left'), left=4, right=3, min_width=10), blank, blank, ] header = urwid.AttrWrap(urwid.Text(text_header), 'header') listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content)) frame = urwid.Frame(urwid.AttrWrap(listbox, 'body'), header=header) palette = [ ('body', 'black', 'light gray', 'standout'), ('reverse', 'light gray', 'black'), ('header', 'white', 'dark red', 'bold'), ('important', 'dark blue', 'light gray', ('standout', 'underline')), ('editfc', 'white', 'dark blue', 'bold'), ('editbx', 'light gray', 'dark blue'), ('editcp', 'black', 'light gray', 'standout'), ('bright', 'dark gray', 'light gray', ('bold', 'standout')), ('buttn', 'black', 'dark cyan'), ('buttnf', 'white', 'dark blue', 'bold'), ] # use appropriate Screen class if urwid.web_display.is_web_request(): screen = urwid.web_display.Screen() else: screen = urwid.raw_display.Screen() def unhandled(key): if key == 'f8': raise urwid.ExitMainLoop() if key == 'f5': txt = urwid.Text( str({x.get_label(): x.get_state() for x in AttrWraps_list})) fill = urwid.Filler(txt, 'top') loop = urwid.MainLoop(fill) loop.run() urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
# Create input buttons manual_clock = urwid.CheckBox( "manual_clock", on_state_change=lambda x, newstate: mark_1.output_by_name("CLK", newstate)) typewriter = Keyboard() # Create input footer test_text = urwid.Text("This is the footer") footer_widgets = [test_text, manual_clock, typewriter] footer = urwid.ListBox(urwid.SimpleFocusListWalker(footer_widgets)) # Render main screen #fill = urwid.Frame(urwid.Filler(display_tubes_pile, 'top'), footer=footer) fill = urwid.Frame(footer, header=display, focus_part='body') loop = urwid.MainLoop(fill) update_display_tubes() mark_1.disp_callback = update_display_tubes mark_1.sl_callback = update_stop_lamp loop.run() # Tests #b = False #mark_1.update_DISP() #mark_1.update_SL() #for i in range (11):