def start(self, fileNames): """ Constructs my widgets and starts my event loop and main loop. """ def possiblyQuit(key): if key in ('q', 'Q'): if not hasattr(self, '_stopping'): self._stopping = None self.warning("Shutting down, please wait...") if reactor.running: # I trust the stopper function to call my stop # method at the appropriate time reactor.callFromThread(reactor.stop) # The top-level widgets self.m = Messages() self.f = Files(fileNames, self._dims()[0]) p = u.Pile([u.Divider("=", 1, 1), self.f, u.Divider(" ")]) main = u.WidgetWrap( u.LineBox( u.Padding( u.Frame(self.m, footer=p), left=1, right=1), title=self.title)) eventLoop = u.TwistedEventLoop(reactor, manage_reactor=False) self.formerDims = self._dims() self.loop = u.MainLoop( main, screen=self.screen, unhandled_input=possiblyQuit, event_loop=eventLoop) reactor.addSystemEventTrigger('after', 'shutdown', self.stop) #sys.stdout = StdSubstitute('STDOUT', self) sys.stderr = observer = StdSubstitute('STDERR', self) twisted.python.log.addObserver(observer) self.running = True self.loop.start()
def __init__(self, dbman, initialcmd): """ :param dbman: :class:`~alot.db.DBManager` :param initialcmd: commandline applied after setting up interface :type initialcmd: str :param colourmode: determines which theme to chose :type colourmode: int in [1,16,256] """ self.dbman = dbman colourmode = int(settings.get('colourmode')) logging.info('setup gui in %d colours' % colourmode) global_att = settings.get_theming_attribute('global', 'body') self.mainframe = urwid.Frame(urwid.SolidFill()) self.mainframe_themed = urwid.AttrMap(self.mainframe, global_att) self.inputwrap = InputWrap(self, self.mainframe_themed) self.mainloop = urwid.MainLoop(self.inputwrap, handle_mouse=False, event_loop=urwid.TwistedEventLoop(), unhandled_input=self.unhandeled_input) self.mainloop.screen.set_terminal_properties(colors=colourmode) self.show_statusbar = settings.get('show_statusbar') self.notificationbar = None self.mode = 'global' self.commandprompthistory = [] logging.debug('fire first command') self.apply_command(initialcmd) self.mainloop.run()
def run_twisted(self): from twisted.internet import reactor evloop = urwid.TwistedEventLoop(reactor, manage_reactor=False) self.screen = urwid.raw_display.Screen() self.screen.register_palette(self.palette) self.loop = MainLoop(self.frame_widget, unhandled_input=self.handle_input, screen=self.screen, event_loop=evloop) self.loop.set_alarm_in(0.1, lambda loop, _: loop.draw_screen()) self.loop.start() # The loggers get a Handler that writes to the screen. We want this to only # happen if the screen exists, so de-register them after the reactor stops. reactor.addSystemEventTrigger('after', 'startup', self.register_loggers) reactor.addSystemEventTrigger('before', 'shutdown', self.unregister_loggers) reactor.run() # We might have stopped the screen already, and the stop() method # doesn't check for stopping twice. if self.called_loop_stop: self.logger.warn('Internal error!') else: self.loop.stop() self.called_loop_stop = True
def run(self): self.loop = urwid.MainLoop(self.view.frame, palette, unhandled_input=self.handle_input, event_loop=urwid.TwistedEventLoop()) self.view.loop = self.loop self.loop.run()
def main(self): self.loop = urwid.MainLoop( self.g_frame, self.palette, input_filter=self.filter_input, event_loop=urwid.TwistedEventLoop() ) self.loop.run()
def __init__(self, editor=None): if editor is None: editor = Editor() self.editor = editor super(GE, self).__init__( widget=Tab(self.editor.active_tab), event_loop=urwid.TwistedEventLoop(), )
def create_urwid_mainloop(self): evl = urwid.TwistedEventLoop(manage_reactor=False) loop = urwid.MainLoop(self.toplevel, screen=self.screen, event_loop=evl, unhandled_input=self.mind.unhandled_key, palette=self.palette) self.screen.loop = loop loop.run() return loop
def _setup_loop_background(self, reactor): fill_widget = urwid.SolidFill() mapped_widget = urwid.AttrMap(fill_widget, 'background') event_loop = urwid.TwistedEventLoop(reactor=reactor) loop = urwid.MainLoop(mapped_widget, PALETTE, event_loop=event_loop, unhandled_input=self.exit_on_q) cols, rows = loop.screen.get_cols_rows() loop.screen.set_terminal_properties(colors=256) return loop
def init(self, options, root_cls): self.state = DockerState(options.host, '1.18', options.freq) self.client = docker.Client(base_url=options.host, version='1.18') self.options = options self.root = root_cls() event_loop = urwid.TwistedEventLoop(manage_reactor=True) loop = urwid.MainLoop( self.root, palette=palette, event_loop=event_loop, ) super(ConsoleApp, self).__init__(loop)
def main(): parser = argparse.ArgumentParser( description="watch multiple command outputs") parser.add_argument('--specfile', '-f', type=argparse.FileType('rb'), required=True, help='YAML file containing commands to run') parser.add_argument('--no-quit-key', action='store_true', help='disable quitting with the Q key') options = parser.parse_args() config = yaml.safe_load(options.specfile) watches = list(map(WatcherBlock, config['processes'])) pile = urwid.AttrWrap(urwid.Pile([('pack', w.widget) for w in watches]), 'body') text_header = urwid.Text("{} on {}".format(os.path.basename(sys.argv[0]), socket.gethostname())) copying_text = urwid.Text( "Copyright 2017 Nicholas Booker. License: GPLv3+") time_text = urwid.Text("") header = urwid.AttrWrap( urwid.Columns([text_header, time_text, copying_text]), 'header') main_frame = urwid.Frame(pile, header=header) palette = [ ('title', 'white,underline', 'black'), ('header', 'black', 'light gray'), ('body', 'light gray', 'black'), ('status_error', 'light red', 'black'), ('status_ok', 'light green', 'black'), ] urwid_loop = urwid.MainLoop(main_frame, palette=palette, handle_mouse=False, unhandled_input=UnhandledInputHandler(options), event_loop=urwid.TwistedEventLoop()) def refresh_time(*args, **kwargs): current_time = datetime.datetime.now() next_minute = current_time.replace(second=0) + datetime.timedelta( minutes=1) time_text.set_text(current_time.strftime("%Y-%m-%d %H:%M")) urwid_loop.set_alarm_at( next_minute.replace(tzinfo=datetime.timezone.utc).timestamp(), refresh_time) reactor.callWhenRunning(refresh_time) for watch in watches: watch.urwid_loop = urwid_loop watch.twisted_reactor = reactor reactor.callWhenRunning(watch.trigger) urwid_loop.run() # replaces reactor.run()
async def run(self): loop = urwid.MainLoop(self.widget, event_loop=urwid.TwistedEventLoop( reactor=self.reactor, manage_reactor=False), **self.loop_kwarg) loop.start() try: return await self.done finally: loop.stop() click.echo()
def __init__(self, title="plait"): self.tabs = VerticalTabs() self.root = ConsoleFrame(title) self.screen = urwid.raw_display.Screen(input=open('/dev/tty', 'r')) self.loop = urwid.MainLoop(self.root, self.default_palette, screen=self.screen, handle_mouse=False, unhandled_input=self.unhandled_input, event_loop=urwid.TwistedEventLoop()) self.loop.screen.set_terminal_properties(colors=256) self.show(self.tabs, "Remote task hosts") self.failed_workers = [] super(ConsoleApp, self).__init__()
def __init__(self, dbman, initialcmd): """ :param dbman: :class:`~alot.db.DBManager` :param initialcmd: commandline applied after setting up interface :type initialcmd: str :param colourmode: determines which theme to chose :type colourmode: int in [1,16,256] """ # store database manager self.dbman = dbman # 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_command(initialcmd) # start urwids mainloop self.mainloop.run()
def __init__(self, username): self.clientCert = Certificate.deserialize( open("%s.cert" % username).read()) self.signatureKey = RSA.importKey(open("%s.priv" % username).read()) self.factory = IRPClientFactory(self.clientCert, self.signatureKey) self.controller = Controller() self.view = View(self.factory.clientCert.username) self.controller.view = self.view self.controller.factory = self.factory self.view.controller = self.controller self.loop = urwid.MainLoop(self.view.window, self.view.palette, unhandled_input=self.view.unhandled_input, event_loop=urwid.TwistedEventLoop()) self.view.loop = self.loop
def run(self): """ Start the event loop. """ if self.executecmd != None: cmdline = self.executecmd.split(None, 1) self.command(cmdline[0], cmdline[1]) self._ui.set_body(self) ev = urwid.TwistedEventLoop(reactor=reactor) self._loop = urwid.MainLoop(self._ui, palette=self._palette, unhandled_input=self._unhandled_input, event_loop=ev) reactor.callLater(0, self.startService) self._loop.run() logger.debug("exited urwid main loop") if self.debug == True: startLogging(StdoutHandler(), DEBUG, self.logconfigfile) return 0
def setWidget(self, widget, useFiller=False): def possiblyQuit(key): if key in ('q', 'Q'): reactor.stop() # The widget under test is outline, possibly padded with filler outlined = u.LineBox(widget) if useFiller: height = 'flow' if hasattr(widget, 'rows') else 3 w = u.Filler(outlined, valign='top', height=height) else: w = outlined main = u.WidgetWrap(w) # The loops eventLoop = u.TwistedEventLoop(reactor, manage_reactor=False) self.loop = u.MainLoop( main, screen=self.screen, unhandled_input=possiblyQuit, event_loop=eventLoop) self.loop.start()
def __init__(self, maxwindow): self.maxwindow = maxwindow self.windows = [] self.widgets = [] numcolumns = min(maxwindow, 2) columns = [[] for i in range(numcolumns)] for i in range(maxwindow): window = MyTerminal() self.windows.append(window) widget = urwid.Frame(urwid.LineBox(window)) self.widgets.append(widget) columns[i % len(columns)].append(widget) columns = [urwid.Pile(x) for x in columns] self.top = urwid.Columns(columns) evl = urwid.TwistedEventLoop(manage_reactor=True) self.loop = urwid.MainLoop(self.top, event_loop=evl) # now that the loop is there, we inform the terminals for window in self.windows: window.loop = self.loop self.lock = Lock() self.curwindow = 0 self.redrawing = False
#message = {"msg": TURN AUDIO INTO BITS} #This call is what triggers Twisted to do stuff. Twisted should be able #to take in the bit conversion of the audio. any_mesh.request(target, message) msg_list_box.add_line('Sending request', message['msg']) def load_msg_frame(): global frame, entry_box, msg_list_box msg_list_box = MessageListBox() entry_box = MsgEntryListBox() frame.body = msg_list_box frame.footer = urwid.BoxAdapter(entry_box, 7) frame.focus_position = 'footer' entry_box.set_focus(0) def refresh_device_column(): options = ('pack', None) device_list = [(urwid.Text("Connected Devices"), options), (urwid.Divider(), options)] for device in any_mesh.get_connections(): device_list.append((urwid.Text(device.name), options)) device_pile.contents = device_list frame = urwid.Frame(SetupListBox()) device_pile = urwid.Pile([urwid.Text("Connected Devices")]) columns = urwid.Columns([('weight', 2, urwid.BoxAdapter(frame, 50)), ('weight', 1, device_pile)], 5) fill = urwid.Filler(columns, 'top') tLoop = urwid.TwistedEventLoop() loop = urwid.MainLoop(fill, event_loop=tLoop, unhandled_input=handle_input) loop.run()
def __init__(self): """Setup the UI with urwid.""" self.__main = urwid.WidgetWrap(None) self.__loop = urwid.MainLoop(self.__main, event_loop=urwid.TwistedEventLoop())
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 setUp(self): self.evl = urwid.TwistedEventLoop()
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()