Ejemplo n.º 1
0
    def run(self, initial_scene):
        logger.info('Director starting up.')
        self.push(initial_scene)
        self._set_scene()

        screen = self.screen = urwid.raw_display.Screen()
        screen.set_terminal_properties(colors=256)
        urwid.set_encoding("UTF-8")

        def unhandled(key):
            # logger.debug('Received key sequence: %s', key)
            signals.keyboard.send(key=key)

            # FIXME: This shouldn't be hard-coded here. Rely on scene popping.
            if key in 'qQxX' or key == 'esc':
                logger.info('Director quitting.')
                raise urwid.ExitMainLoop()

        self.loop = urwid.MainLoop(
            self.scene.main_frame, list(palette.entries), screen,
            unhandled_input=unhandled)

        self.iterator = iter(self)
        self.loop.set_alarm_in(0, self.schedule_agent)
        self.loop.run()
Ejemplo n.º 2
0
 def test_utf8_input(self):
     urwid.set_encoding("utf-8")
     self.t1.set_edit_text('')
     self.t1.keypress((12,), u'û')
     self.assertEqual(self.t1.edit_text, u'û'.encode('utf-8'))
     self.t4.keypress((12,), u'û')
     self.assertEqual(self.t4.edit_text, u'û')
Ejemplo n.º 3
0
 def sbgtest(self, desc, data, top, exp ):
     urwid.set_encoding('utf-8')
     g = urwid.BarGraph( ['black','red','blue'],
             None, {(1,0):'red/black', (2,1):'blue/red'})
     g.set_data( data, top )
     rval = g.calculate_display((5,3))
     assert rval == exp, "%s expected %r, got %r"%(desc,exp,rval)
Ejemplo n.º 4
0
 def __init__(self, path, application, with_menu=True):
     super(UrwidWindow, self).__init__(path, application)
     urwid.set_encoding("utf8")
     self._builder = UrwidUIBuilder(self.application)
     self.with_menu = with_menu
     self.logger.debug("Creating urwid tui for '%s'" % application)
     self.logger.debug("Detected encoding: %s" % urwid.get_encoding_mode())
Ejemplo n.º 5
0
    def render(self):
        urwid.set_encoding("UTF-8")
        self.registerSignals()

        workspace_menu = ui.WorkspaceMenu(self.myWorkspaces())
        urwid.connect_signal(workspace_menu, 'click', self.showProjectList)

        self.frame = urwid.Pile([
            ('pack', urwid.AttrMap(workspace_menu, 'workspace')),
            None
        ])
        if self.state['view'] == 'workspace':
            self.showProjectList(self.state['id'])
        elif self.state['view'] == 'project':
            self.showProject(self.state['id'])
        elif self.state['view'] == 'atm':
            self.showMyTasks(self.state['id'])
        elif self.state['view'] == 'details':
            self.showDetails(self.state['id'])
        else:
            raise KeyError

        self.loop = urwid.MainLoop(self.frame,
                              unhandled_input=self.handleInput,
                              palette=ui.palette
                             )
        self.loop.run()
Ejemplo n.º 6
0
    def run(self):
        size = self.ui.get_cols_rows()
        urwid.set_encoding("utf-8")
        self.body.set_focus(1)
        while 1:
            self.body.set_focus(1)
            canvas = self.body.render(size, focus=True)
            self.ui.draw_screen( size, canvas )
            keys = None
            while not keys: 
                keys = self.ui.get_input()
            for k in keys:
                if k == 'window resize':
                    size = self.ui.get_cols_rows()
                    canvas = self.body.render(size, focus=True)
                    self.ui.draw_screen( size, canvas )
                elif k == 'esc':
                    self.do_quit()    
                elif k == 'enter':
                    self.commitText()
                elif ("up" in k) or ("down" in k):
                    self.body.set_focus(0)
                else:
                    self.body.set_focus(1)
                    #self.text_edit_area.keypress((1,), k) 
                    self.updatePrompt()
                self.body.keypress(size, k)
                self.body.set_focus(1)

                d_keys =  self._cheap_queue.keys() #not smart to iterate a dict and delete elements on the process
                for cheap_thread_key in d_keys:
                    if not self._cheap_queue[cheap_thread_key].isAlive():
                        self._cheap_queue[cheap_thread_key].join()
                        del(self._cheap_queue[cheap_thread_key])
Ejemplo n.º 7
0
Archivo: cli.py Proyecto: 1reza/turses
def main():
    """
    Launch ``turses``.
    """
    set_title(__name__)
    set_encoding('utf8')

    args = parse_arguments()

    # check if stdout has to be restored after program exit
    if any([args.debug,
            args.offline,
            getattr(args, 'help', False),
            getattr(args, 'version', False)]):
        # we are going to print information to stdout
        save_and_restore_stdout = False
    else:
        save_and_restore_stdout = True

    if save_and_restore_stdout:
        save_stdout()

    # load configuration
    configuration = Configuration(args)
    configuration.load()

    # start logger
    logging.basicConfig(filename=LOG_FILE,
                        level=configuration.logging_level)

    # create view
    curses_interface = CursesInterface(configuration)

    # select API backend
    if args.offline:
        api_backend = MockApi
    else:
        api_backend = TweepyApi

    # create controller
    turses = Turses(configuration=configuration,
                    ui=curses_interface,
                    api_backend=api_backend)
    try:
        turses.start()
    except KeyboardInterrupt:
        pass
    except:
        # open the debugger
        if args.debug or args.offline:
            import pdb
            pdb.post_mortem()
    finally:
        if save_and_restore_stdout:
            restore_stdout()

        restore_title()

        exit(0)
Ejemplo n.º 8
0
 def __init__(self):
     super(GUIScreen, self).__init__()
     urwid.set_encoding('utf8')
     self.root = None
     self.size = (180, 60)
     self.title = "Taurus Status"
     self.text = None
     self.font = None
	def main(self):
		urwid.set_encoding("UTF-8")
		self.StartMenu = urwid.Padding(self.firstMenu(self.firstMenuChoices), left=5, right=5)
		top = urwid.Overlay(self.StartMenu, urwid.SolidFill(u'\N{MEDIUM SHADE}'),
							align='center', width=('relative', 60),
							valign='middle', height=('relative', 60),
							min_width=20, min_height=9)
		urwid.MainLoop(top, self.palette).run()
Ejemplo n.º 10
0
Archivo: cli.py Proyecto: Erik-k/turses
def main():
    """
    Launch ``turses``.
    """
    set_title(__name__)
    set_encoding('utf8')

    args = read_arguments()

    # check if stdout has to be restored after program exit
    if any([args.debug,
            args.offline,
            getattr(args, 'help', False),
            getattr(args, 'version', False)]):
        # we are going to print information to stdout
        save_and_restore_stdout = False
    else:
        save_and_restore_stdout = True

    if save_and_restore_stdout:
        save_stdout()

    # parse arguments and load configuration
    configuration.parse_args(args)
    configuration.load()

    # start logger
    logging.basicConfig(filename=LOG_FILE,
                        level=configuration.logging_level)

    # create view
    curses_interface = CursesInterface()

    # create model
    timeline_list = TimelineList()

    # create API
    api = create_async_api(MockApi if args.offline else TweepyApi)

    # create controller
    turses = Turses(ui=curses_interface,
                    api=api,
                    timelines=timeline_list,)

    try:
        turses.start()
    except:
        # A unexpected exception occurred, open the debugger in debug mode
        if args.debug or args.offline:
            import pdb
            pdb.post_mortem()
    finally:
        if save_and_restore_stdout:
            restore_stdout()

        restore_title()

        exit(0)
Ejemplo n.º 11
0
Archivo: core.py Proyecto: gefei/bbcli
 def run(self):
     self.make_screen()
     urwid.set_encoding("utf-8")
     self.set_keys()
     try:
         self.loop.run()
     except KeyboardInterrupt:
         print "Keyboard interrupt received, quitting gracefully"
         raise urwid.ExitMainLoop
Ejemplo n.º 12
0
 def test(self):
     urwid.set_encoding("euc-jp")
     self.assertRaises(text_layout.CanNotDisplayText,
         text_layout.default_layout.calculate_text_segments,
         B('\xA1\xA1'), 1, 'space' )
     urwid.set_encoding("utf-8")
     self.assertRaises(text_layout.CanNotDisplayText,
         text_layout.default_layout.calculate_text_segments,
         B('\xe9\xa2\x96'), 1, 'space' )
Ejemplo n.º 13
0
 def run(self):
     self.make_screen()
     urwid.set_encoding('utf-8')
     urwid.connect_signal(self.walker, 'modified', self.update_footer)
     self.set_keys()
     try:
         self.loop.run()
     except KeyboardInterrupt:
         print "Keyboard interrupt received, quitting gracefully"
         raise urwid.ExitMainLoop
Ejemplo n.º 14
0
Archivo: cli.py Proyecto: tazjel/turses
def main():
    """
    Launch ``turses``.
    """
    set_title(__name__)
    set_encoding('utf8')

    args = parse_arguments()

    # stdout
    if any([args.debug,
            args.offline,
            getattr(args, 'help', False),
            getattr(args, 'version', False)]):
        # we are going to print information to stdout
        save_and_restore_stdout = False
    else:
        save_and_restore_stdout = True

    if save_and_restore_stdout:
        save_stdout()

    # configuration
    configuration = Configuration(args)
    configuration.load()

    # view
    curses_interface = CursesInterface(configuration)

    # API
    if args.offline:
        api_backend = MockApi
    else:
        api_backend = TweepyApi

    # controller
    turses = Turses(configuration=configuration,
                    ui=curses_interface,
                    api_backend=api_backend)
    try:
        turses.start()
    except KeyboardInterrupt:
        pass
    except:
        if args.debug or args.offline:
            import pdb
            pdb.post_mortem()
    finally:
        if save_and_restore_stdout:
            restore_stdout()

        restore_title()

        exit(0)
Ejemplo n.º 15
0
 def test3(self):
     urwid.set_encoding("euc-jp")
     self.cotest("db0","\xA1\xA1\xA1\xA1\xA1\xA1",[],"HI",[],2,2,
         [[(None,None,B("\xA1\xA1")),(None,None,B("HI")),
         (None,None,B("\xA1\xA1"))]])
     self.cotest("db1","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHI",[],1,2,
         [[(None,None,B(" ")),(None,None,B("OHI")),
         (None,None,B("\xA1\xA1"))]])
     self.cotest("db2","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHI",[],2,1,
         [[(None,None,B("\xA1\xA1")),(None,None,B("OHI")),
         (None,None,B(" "))]])
     self.cotest("db3","\xA1\xA1\xA1\xA1\xA1\xA1",[],"OHIO",[],1,1,
         [[(None,None,B(" ")),(None,None,B("OHIO")),(None,None,B(" "))]])
Ejemplo n.º 16
0
def main():
    try:
        set_encoding('utf8')

        args = parse_arguments()
        configuration = Configuration(args)
        configuration.load()
        ui = CursesInterface(configuration)

        # start `turses`
        CursesController(configuration=configuration, 
                         ui=ui,
                         api_backend=TweepyApi)
    except KeyboardInterrupt:
        exit(0)
Ejemplo n.º 17
0
def _check_encoding():
    """Set the Urwid global byte encoding to utf-8.

    Exit the application if, for some reasons, the change does not have effect.
    """
    urwid.set_encoding('utf-8')
    if not urwid.supports_unicode():
        # Note: the following message must only include ASCII characters.
        msg = (
            'Error: your terminal does not seem to support UTF-8 encoding.\n'
            'Please check your locale settings.\n'
            'On Ubuntu, running the following might fix the problem:\n'
            '  sudo locale-gen en_US.UTF-8\n'
            '  sudo dpkg-reconfigure locales'
        )
        sys.exit(msg.encode('ascii'))
Ejemplo n.º 18
0
    def main(self):
        urwid.set_encoding('UTF-8')

        self.listbox = ViListBox(self.key_bindings, urwid.SimpleListWalker([]))
        self.refresh()
        self.header = self.create_header()
        self.footer = self.create_footer()

        self.frame = urwid.Frame(urwid.AttrMap(self.listbox, 'plain'), header=self.header, footer=self.footer)

        self.view = ViColumns(self.key_bindings, [
            ('weight', 2, self.frame)
        ])

        self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.keystroke)
        self.loop.screen.set_terminal_properties(colors=256)
        self.loop.run()
Ejemplo n.º 19
0
def main():
    """ Main function. """
    global ui, dlogger
    # We are not python.
    misc.RenameProcess("wicd-curses")

    ui = urwid.raw_display.Screen()

    # if options.debug:
    #    dlogger = logging.getLogger("Debug")
    #    dlogger.setLevel(logging.DEBUG)
    #    dlogger.debug("wicd-curses debug logging started")

    # Default Color scheme.
    # Other potential color schemes can be found at:
    # http://excess.org/urwid/wiki/RecommendedPalette

    # Thanks to nanotube on #wicd for helping with this
    ui.register_palette(
        [
            ("body", "default", "default"),
            ("focus", "black", "light gray"),
            ("header", "light blue", "default"),
            ("important", "light red", "default"),
            ("connected", "dark green", "default"),
            ("connected focus", "black", "dark green"),
            ("editcp", "default", "default", "standout"),
            ("editbx", "light gray", "dark blue"),
            ("editfc", "white", "dark blue", "bold"),
            ("editnfc", "brown", "default", "bold"),
            ("tab active", "dark green", "light gray"),
            ("infobar", "light gray", "dark blue"),
            ("listbar", "light blue", "default"),
            # Simple colors around text
            ("green", "dark green", "default"),
            ("blue", "light blue", "default"),
            ("red", "dark red", "default"),
            ("bold", "white", "black", "bold"),
        ]
    )
    # Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad state)
    signal.signal(signal.SIGQUIT, handle_sigquit)
    # This is a wrapper around a function that calls another a function that
    # is a wrapper around a infinite loop.  Fun.
    urwid.set_encoding("utf8")
    ui.run_wrapper(run)
Ejemplo n.º 20
0
Archivo: tui.py Proyecto: ztenma/Swap
	def buildUI(self):
		urwid.set_encoding("UTF-8")

		palette = [('title', 'white,bold', 'black'),('stats', 'white', 'white')]
		palette.extend((name, 'white', style) for name, style in TUI.COLORS)

		header = urwid.AttrMap(urwid.Text('Swap', align='center'), 'title')

		leftGrid = urwid.Text('')
		leftCont = urwid.LineBox(urwid.Filler(leftGrid, 'top'))

		rightGrid = urwid.Text('')
		rightCont = urwid.LineBox(urwid.Filler(rightGrid, 'top'))

		scoreTitle = urwid.AttrMap(urwid.Text('Score', align='center'), 'title')
		scoreCont = urwid.Filler(scoreTitle, 'top', top=2)
		scoreLabel = urwid.Text('_%s | %s_' % (self.game.players[0].score, self.game.players[1].score), align='center')

		multiplierTitle = urwid.AttrMap(urwid.Text('Multiplier', align='center'), 'title')
		multiplierCont = urwid.Filler(multiplierTitle, 'top', top=2)
		multiplierLabel = urwid.Text('%s | %s' % (self.game.players[0].scoreMultiplier, self.game.players[1].scoreMultiplier), align='center')

		stateTitle = urwid.AttrMap(urwid.Text('State', align='center'), 'title')
		stateCont = urwid.Filler(stateTitle, 'top', top=2)
		stateLabel = urwid.Text('%s\n%s' % (self.game.players[0].stateMachine.vcrepr(), self.game.players[1].stateMachine.vcrepr()), align='left')

		statsPile = urwid.Pile([scoreCont,
			urwid.Filler(urwid.AttrMap(scoreLabel, 'stats'), 'top', top=1),
			multiplierCont,
			urwid.Filler(urwid.AttrMap(multiplierLabel, 'stats'), 'top', top=1),
			stateCont,
			urwid.Filler(urwid.AttrMap(stateLabel, 'stats'), 'top', top=1)
			])

		columns = urwid.Columns([(12*2+2, leftCont), statsPile, (12*2+2, rightCont)])

		frame = urwid.Frame(header=header, body=columns)

		self.leftGrid, self.rightGrid = leftGrid, rightGrid
		self.scoreLabel = scoreLabel
		self.multiplierLabel = multiplierLabel
		self.stateLabel = stateLabel
		self.palette = palette
		self.frame = frame
		self.mainLoop = urwid.MainLoop(frame, palette, unhandled_input=self.handleInput)
Ejemplo n.º 21
0
    def test_linebox_border(self):
        urwid.set_encoding("utf-8")
        t = urwid.Text("")

        l = urwid.LineBox(t).render((3,)).text

        # default
        self.assertEqual(l,
            self.border(B("\xe2\x94\x8c"), B("\xe2\x94\x80"),
                B("\xe2\x94\x90"), B("\xe2\x94\x82"), B("\xe2\x94\x82"),
                B("\xe2\x94\x94"), B("\xe2\x94\x80"), B("\xe2\x94\x98")))

        nums = [B(str(n)) for n in range(8)]
        b = dict(list(zip(["tlcorner", "tline", "trcorner", "lline", "rline",
            "blcorner", "bline", "brcorner"], nums)))
        l = urwid.LineBox(t, **b).render((3,)).text

        self.assertEqual(l, self.border(*nums))
Ejemplo n.º 22
0
def main(args, config):
    prepare_environment(config)

    if args.list_shortcut_paths:
        store_filename = config["shortcuts_paths_file"]
        if os.path.exists(store_filename):
            with open(store_filename) as afile:
                paths = [line.strip() for line in afile.readlines()]
            while len(paths) < len(config["shortcuts"]["cd_to_shortcut_path"]):
                paths.append("")
            print("Shortcuts:")
            smax_len = len(max(config["shortcuts"]["cd_to_shortcut_path"], key=len)) + 1
            for shortcut, path in zip(config["shortcuts"]["cd_to_shortcut_path"], paths):
                print("{:>{}} - {}".format(shortcut, smax_len, util.replace_home_with_tilde(path)))
    elif args.add_path:
        for pattern in config["skip_list"]:
            if re.search(pattern, args.add_path):
                return

        history_filename = config["history_file"]
        lockfile = os.path.dirname(history_filename) + ".lock"
        with open(lockfile, "w+") as lock:
            util.obtain_lockfile(lock)
            path = args.add_path
            path = util.replace_home_with_tilde(path)
            path = re.sub(r"/{2,}", r"/", path)
            path = path_strip(path)
            update_path_list(history_filename, path, config["history_limit"], config["skip_list"])
    else:
        urwid.set_encoding("UTF-8")
        # interactive menu
        display = Display(config)
        display.run()

        selected_path = display.get_selected_path()
        if args.escape_special_symbols:
            symbols = [" ", "(", ")"]
            for symbol in symbols:
                selected_path = selected_path.replace(symbol, "\\" + symbol)
        if args.output:
            with open(args.output, "w") as afile:
                afile.write(selected_path)
        else:
            print(selected_path)
Ejemplo n.º 23
0
def main():
    """ Main function. """
    global ui, dlogger
    # We are not python.
    misc.RenameProcess('wicd-curses')

    ui = urwid.raw_display.Screen()

    #if options.debug:
    #    dlogger = logging.getLogger("Debug")
    #    dlogger.setLevel(logging.DEBUG)
    #    dlogger.debug("wicd-curses debug logging started")

    # Default Color scheme.
    # Other potential color schemes can be found at:
    # http://excess.org/urwid/wiki/RecommendedPalette

    # Thanks to nanotube on #wicd for helping with this
    ui.register_palette([
        ('body', 'default', 'default'),
        ('focus', 'black', 'light gray'),
        ('header', 'light blue', 'default'),
        ('important', 'light red', 'default'),
        ('connected', 'dark green', 'default'),
        ('connected focus', 'black', 'dark green'),
        ('editcp', 'default', 'default', 'standout'),
        ('editbx', 'light gray', 'dark blue'),
        ('editfc', 'white', 'dark blue', 'bold'),
        ('editnfc', 'brown', 'default', 'bold'),
        ('tab active', 'dark green', 'light gray'),
        ('infobar', 'light gray', 'dark blue'),
        ('listbar', 'light blue', 'default'),
        # Simple colors around text
        ('green', 'dark green', 'default'),
        ('blue', 'light blue', 'default'),
        ('red', 'dark red', 'default'),
        ('bold', 'white', 'black', 'bold')
    ])
    # Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad state)
    signal.signal(signal.SIGQUIT, handle_sigquit)
    # This is a wrapper around a function that calls another a function that
    # is a wrapper around a infinite loop.  Fun.
    urwid.set_encoding('utf8')
    ui.run_wrapper(run)
Ejemplo n.º 24
0
    def __init__(self, hive, *args, **kwargs):
        super(CLI, self).__init__(*args, **kwargs)
        self._hive = hive
        self._background = urwid.SolidFill()
        urwid.set_encoding("utf-8") 
        self._display = urwid.MainLoop(
                self._background,
                self._pallet,
                unhandled_input=self.input_handler
                )

        self._display.widget = urwid.AttrMap(
                self._background,
                "background"
                )

        self._stack = Messages()
        self._list = urwid.ListBox(self._stack)
        self._frame = urwid.Frame(urwid.AttrMap(self._list, "normal"))
        self._display.widget.original_widget = self._frame
Ejemplo n.º 25
0
    def create_urwid_mainloop(self):
        eventloop = urwid.TwistedEventLoop(manage_reactor=False)
        urwid.set_encoding("utf-8")
        t = nisk.TUI.tui(
            mainframe=self.toplevel, screen=self.screen, unhandled_input=self.unhandled_input, khdl_app=app.app.keyHandler,
            colors=self.palette, eventloop=eventloop
        )

        # if nisk.TUI.tui.mdi is None:
        nisk.TUI.tui.mdi = t

        app_ = controller.pyGestorFacade.getInstance()
        app_._widgetregistrapai(self.toplevel)
        self.toplevel._widgetfacade = app_
        # app_.sendNotification(conf.cmds.STARTUP, nisk.tui.mdi)

        loop = t.loop
        self.screen.loop = loop
        # loop.run()
        nisk.tui.mdi.run()
        return loop
Ejemplo n.º 26
0
    def __init__(self):
        urwid.set_encoding("UTF-8")
        self.POLL_INTERVAL = 10
        try:
            self.configuration = Configuration()
        except Exception as error:
            print(error)
            raise urwid.ExitMainLoop()
        self.apis = {}
        if 'groupme' in self.configuration.config['general']['interfaces']:
            self.apis['groupme'] = GroupMeAPI(self.configuration.config['groupme']['api_key'])
        self.header_area = HeaderArea()
        self.input_area = InputArea()
        self.conversation_area = ConversationArea(self.apis)
        self.main_screen = urwid.Frame(
            self.conversation_area,
            header=self.header_area,
            footer=self.input_area
        )
        self.palette = [
            ('statusbar', 'black', 'light gray'),
            ('input_mode', 'white', 'dark red'),
            ('normal_mode', 'black', 'dark green'),
            ('highlight', 'black', 'light gray'),
        ]

        self.register_signal_emitters()
        self.connect_signal_handlers()
        super().__init__(self.main_screen, self.palette, unhandled_input=self.navigation_handler)

        # Initialize the conversation list refresh loop.
        # This should be done before trying to refresh the message area to avoid
        # a wait between first render and messages showing up.
        self.conversation_list_refresh_handler(None, None)

        # Initialize the refresh message area refresh loop.
        self.conversation_messages_refresh_handler(None, None)
Ejemplo n.º 27
0
 def setUp(self):
     urwid.set_encoding('utf-8')
Ejemplo n.º 28
0
 def setUp(self):
     urwid.set_encoding("utf-8")
Ejemplo n.º 29
0
 def setUp(self):
     urwid.set_encoding("euc-jp")
Ejemplo n.º 30
0
    WORKFLOW_COLOURS,
)
from cylc.flow.tui.tree import (
    find_closest_focus,
    translate_collapsing
)
from cylc.flow.tui.util import (
    compute_tree,
    dummy_flow,
    get_task_status_summary,
    get_workflow_status_str,
    render_node
)


urwid.set_encoding('utf8')  # required for unicode task icons

TREE_EXPAND_DEPTH = [2]


class TuiWidget(urwid.TreeWidget):
    """Display widget for tree nodes.

    Arguments:
        node (TuiNode):
            The root tree node.
        max_depth (int):
            Determines which nodes are unfolded by default.
            The maximum tree depth to unfold.

    """
Ejemplo n.º 31
0
 def test5_encode_error(self):
     urwid.set_encoding("ascii")
     expected = [B("?  ")]
     got = urwid.Text(u'û').render((3, ))._text
     assert got == expected, "got: %r expected: %r" % (got, expected)
Ejemplo n.º 32
0
    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

        # force urwid to pass key events as unicode, independent of LANG
        urwid.set_encoding('utf-8')

        # 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(
            get_xdg_env('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)

        loop = asyncio.get_event_loop()
        # Create a task for the periodic hook
        loop_hook = settings.get_hook('loop_hook')
        if loop_hook:
            # In Python 3.7 a nice aliase `asyncio.create_task` was added
            loop.create_task(
                periodic(loop_hook,
                         settings.get('periodic_hook_frequency'),
                         ui=self))

        # 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')
        loop.create_task(self.apply_commandline(initialcmdline))

        # start urwids mainloop
        self.mainloop.run()
Ejemplo n.º 33
0
import sys

import urwid
from urwid import set_encoding

from zulipterminal.config import symbols

set_encoding('utf-8')

palette = [
    ('header', 'white, bold', 'dark blue'),
    ('footer', 'black', 'white'),
]

symbol_dict = {
    name: symbol
    for name, symbol in vars(symbols).items()
    if not name.startswith('__') and not name.endswith('__')
}
max_symbol_name_length = max([len(name) for name in symbol_dict.keys()])

symbol_names_list = [
    urwid.Text(name, align='center') for name in symbol_dict.keys()
]
symbols_list = [urwid.Text(symbol) for symbol in symbol_dict.values()]

symbols_display_box = urwid.Columns(
    [
        # Allot extra width to the symbol names list to create a neat layout.
        (max_symbol_name_length + 2, urwid.Pile(symbol_names_list)),
        # Allot 2 characters to the symbols list to accommodate symbols needing
Ejemplo n.º 34
0
from concurrent.futures import ThreadPoolExecutor

from toot import api, config, __version__

from .compose import StatusComposer
from .constants import PALETTE
from .entities import Status
from .overlays import ExceptionStackTrace, GotoMenu, Help, StatusSource, StatusLinks
from .overlays import StatusDeleteConfirmation
from .timeline import Timeline
from .utils import parse_content_links, show_media

logger = logging.getLogger(__name__)

urwid.set_encoding('UTF-8')


class Header(urwid.WidgetWrap):
    def __init__(self, app, user):
        self.app = app
        self.user = user

        self.text = urwid.Text("")
        self.cols = urwid.Columns([
            ("pack", urwid.Text(('header_bold', 'toot'))),
            ("pack", urwid.Text(('header', ' | {}@{}'.format(user.username, app.instance)))),
            ("pack", self.text),
        ])

        widget = urwid.AttrMap(self.cols, 'header')
Ejemplo n.º 35
0
        self.update_text_widget()

    def update_text_widget(self):
        self.text_widget.set_caption(str(self.total))

    async def simulation_handler(self):

        while True:

            if self.active:
                self.total += 1
                self.update_text_widget()
                self.update_simulation_speed()
            await asyncio.sleep(self.delay)


if __name__ == '__main__':

    urwid.set_encoding('utf8')

    mainframe = Mainframe()

    asyncio_loop = asyncio.get_event_loop()
    async_event_loop = urwid.AsyncioEventLoop(loop=asyncio_loop)
    loop = urwid.MainLoop(mainframe, event_loop=async_event_loop)

    asyncio.ensure_future(mainframe.simulation_viewer.simulation_handler())
    # asyncio.ensure_future(mainframe.simulation_viewer.output_info.write_handler())

    loop.run()
Ejemplo n.º 36
0
def main(options: Optional[List[str]] = None) -> None:
    """
    Launch Zulip Terminal.
    """

    argv = options if options is not None else sys.argv[1:]
    args = parse_args(argv)

    set_encoding("utf-8")

    if args.debug:
        debug_path: Optional[str] = "debug.log"
        assert isinstance(debug_path, str)
        print(
            "NOTE: Debug mode enabled:"
            f"\n  API calls will be logged to {in_color('blue', API_CALL_LOG_FILENAME)}"
            f"\n  Standard output being logged to {in_color('blue', debug_path)}"
        )
        requests_logfile_handler = logging.FileHandler(API_CALL_LOG_FILENAME)
        requests_logger.addHandler(requests_logfile_handler)
    else:
        debug_path = None
        requests_logger.addHandler(logging.NullHandler())

    if args.profile:
        import cProfile

        prof = cProfile.Profile()
        prof.enable()

    if args.version:
        print(f"Zulip Terminal {ZT_VERSION}")
        sys.exit(0)

    if args.list_themes:
        print(list_themes())
        sys.exit(0)

    if args.config_file:
        zuliprc_path = args.config_file
    else:
        zuliprc_path = "~/zuliprc"

    try:
        zterm = parse_zuliprc(zuliprc_path)

        if args.autohide:
            zterm["autohide"] = (args.autohide, "on command line")

        if args.theme:
            theme_to_use = (args.theme, "on command line")
        else:
            theme_to_use = zterm["theme"]

        if (zterm["footlinks"][1] == ZULIPRC_CONFIG
                and zterm["maximum-footlinks"][1] == ZULIPRC_CONFIG):
            exit_with_error(
                "Footlinks property is not allowed alongside maximum-footlinks"
            )

        if (zterm["maximum-footlinks"][1] == ZULIPRC_CONFIG
                and int(zterm["maximum-footlinks"][0]) < 0):
            exit_with_error("Minimum value allowed for maximum-footlinks is 0")

        if zterm["footlinks"][1] == ZULIPRC_CONFIG:
            if zterm["footlinks"][0] == DEFAULT_SETTINGS["footlinks"]:
                maximum_footlinks = 3
            else:
                maximum_footlinks = 0
        else:
            maximum_footlinks = int(zterm["maximum-footlinks"][0])

        available_themes = all_themes()
        theme_aliases = aliased_themes()
        is_valid_theme = (theme_to_use[0] in available_themes
                          or theme_to_use[0] in theme_aliases)
        if not is_valid_theme:
            exit_with_error(
                "Invalid theme '{}' was specified {}.".format(*theme_to_use),
                helper_text=list_themes(),
            )
        if theme_to_use[0] not in available_themes:
            # theme must be an alias, as it is valid
            real_theme_name = theme_aliases[theme_to_use[0]]
            theme_to_use = (
                real_theme_name,
                "{} (by alias '{}')".format(theme_to_use[1], theme_to_use[0]),
            )

        if args.color_depth:
            zterm["color-depth"] = (args.color_depth, "on command line")

        color_depth_str = zterm["color-depth"][0]
        if color_depth_str == "24bit":
            color_depth = 2**24
        else:
            color_depth = int(color_depth_str)

        if args.notify:
            zterm["notify"] = (args.notify, "on command line")

        print("Loading with:")
        print("   theme '{}' specified {}.".format(*theme_to_use))
        complete, incomplete = complete_and_incomplete_themes()
        if theme_to_use[0] in incomplete:
            if complete:
                incomplete_theme_warning = (
                    "   WARNING: Incomplete theme; results may vary!\n"
                    "      (you could try: {})".format(", ".join(complete)))
            else:
                incomplete_theme_warning = (
                    "   WARNING: Incomplete theme; results may vary!\n"
                    "      (all themes are incomplete)")
            print(in_color("yellow", incomplete_theme_warning))
        print("   autohide setting '{}' specified {}.".format(
            *zterm["autohide"]))
        if zterm["footlinks"][1] == ZULIPRC_CONFIG:
            print(
                "   maximum footlinks value '{}' specified {} from footlinks.".
                format(maximum_footlinks, zterm["footlinks"][1]))
        else:
            print("   maximum footlinks value '{}' specified {}.".format(
                *zterm["maximum-footlinks"]))
        print("   color depth setting '{}' specified {}.".format(
            *zterm["color-depth"]))
        print("   notify setting '{}' specified {}.".format(*zterm["notify"]))

        # For binary settings
        # Specify setting in order True, False
        valid_settings = {
            "autohide": ["autohide", "no_autohide"],
            "notify": ["enabled", "disabled"],
            "color-depth": ["1", "16", "256", "24bit"],
        }
        boolean_settings: Dict[str, bool] = dict()
        for setting, valid_values in valid_settings.items():
            if zterm[setting][0] not in valid_values:
                helper_text = (
                    ["Valid values are:"] +
                    [f"  {option}" for option in valid_values] +
                    [f"Specify the {setting} option in zuliprc file."])
                exit_with_error(
                    "Invalid {} setting '{}' was specified {}.".format(
                        setting, *zterm[setting]),
                    helper_text="\n".join(helper_text),
                )
            if setting == "color-depth":
                break
            boolean_settings[setting] = zterm[setting][0] == valid_values[0]

        theme_data = generate_theme(theme_to_use[0], color_depth)

        Controller(
            config_file=zuliprc_path,
            maximum_footlinks=maximum_footlinks,
            theme_name=theme_to_use[0],
            theme=theme_data,
            color_depth=color_depth,
            in_explore_mode=args.explore,
            **boolean_settings,
            debug_path=debug_path,
        ).main()
    except ServerConnectionFailure as e:
        # Acts as separator between logs
        zt_logger.info(f"\n\n{e}\n\n")
        zt_logger.exception(e)
        exit_with_error(f"\nError connecting to Zulip server: {e}.")
    except InvalidThemeColorCode as e:
        # Acts as separator between logs
        zt_logger.info(f"\n\n{e}\n\n")
        zt_logger.exception(e)
        exit_with_error(f"\n{e}")
    except (display_common.AttrSpecError, display_common.ScreenError) as e:
        # NOTE: Strictly this is not necessarily just a theme error
        # FIXME: Add test for this - once loading takes place after UI setup

        # Acts as separator between logs
        zt_logger.info(f"\n\n{e}\n\n")
        zt_logger.exception(e)
        exit_with_error(f"\nPossible theme error: {e}.")
    except Exception as e:
        zt_logger.info("\n\n{e}\n\n")
        zt_logger.exception(e)
        if args.debug:
            sys.stdout.flush()
            traceback.print_exc(file=sys.stderr)
            run_debugger = input("Run Debugger? (y/n): ")
            if run_debugger in ["y", "Y", "yes"]:
                # Open PUDB Debugger
                import pudb

                pudb.post_mortem()

        if hasattr(e, "extra_info"):
            print(in_color("red", f"\n{e.extra_info}"),
                  file=sys.stderr)  # type: ignore

        print(
            in_color(
                "red",
                "\nZulip Terminal has crashed!"
                f"\nPlease refer to {TRACEBACK_LOG_FILENAME}"
                " for full log of the error.",
            ),
            file=sys.stderr,
        )
        print(
            "You can ask for help at:"
            "\nhttps://chat.zulip.org/#narrow/stream/206-zulip-terminal",
            file=sys.stderr,
        )
        print("\nThanks for using the Zulip-Terminal interface.\n")
        sys.stderr.flush()

    finally:
        if args.profile:
            prof.disable()
            import tempfile

            with tempfile.NamedTemporaryFile(prefix="zulip_term_profile.",
                                             suffix=".dat",
                                             delete=False) as profile_file:
                profile_path = profile_file.name
            # Dump stats only after temporary file is closed (for Win NT+ case)
            prof.dump_stats(profile_path)
            print("Profile data saved to {0}.\n"
                  "You can visualize it using e.g. `snakeviz {0}`".format(
                      profile_path))

        sys.exit(1)
Ejemplo n.º 37
0
def main(options: Optional[List[str]] = None) -> None:
    """
    Launch Zulip Terminal.
    """

    argv = options if options is not None else sys.argv[1:]
    args = parse_args(argv)

    set_encoding('utf-8')

    if args.profile:
        import cProfile
        prof = cProfile.Profile()
        prof.enable()

    if args.version:
        print('Zulip Terminal ' + ZT_VERSION)
        sys.exit(0)

    if args.config_file:
        zuliprc_path = args.config_file
    else:
        zuliprc_path = '~/zuliprc'

    try:
        zterm = parse_zuliprc(zuliprc_path)

        if args.theme:
            theme_to_use = (args.theme, 'on command line')
        else:
            theme_to_use = zterm['theme']
        available_themes = all_themes()
        if theme_to_use[0] not in available_themes:
            print("Invalid theme '{}' was specified {}.".format(*theme_to_use))
            print("The following themes are available:")
            for theme in available_themes:
                print("  ", theme)
            print("Specify theme in zuliprc file or override "
                  "using -t/--theme options on command line.")
            sys.exit(1)

        print("Loading with:")
        print("   theme '{}' specified {}.".format(*theme_to_use))
        complete, incomplete = complete_and_incomplete_themes()
        if theme_to_use[0] in incomplete:
            print(
                in_color(
                    'yellow', "   WARNING: Incomplete theme; "
                    "results may vary!\n"
                    "      (you could try: {})".format(", ".join(complete))))
        print("   autohide setting '{}' specified {}.".format(
            *zterm['autohide']))
        # For binary settings
        # Specify setting in order True, False
        valid_settings = {
            'autohide': ['autohide', 'no_autohide'],
            'notify': ['enabled', 'disabled'],
        }
        boolean_settings = dict()  # type: Dict[str, bool]
        for setting, valid_values in valid_settings.items():
            if zterm[setting][0] not in valid_values:
                print("Invalid {} setting '{}' was specified {}.".format(
                    setting, *zterm[setting]))
                print("The following options are available:")
                for option in valid_values:
                    print("  ", option)
                print("Specify the {} option in zuliprc file.".format(setting))
                sys.exit(1)
            boolean_settings[setting] = (zterm[setting][0] == valid_values[0])
        Controller(zuliprc_path, THEMES[theme_to_use[0]],
                   **boolean_settings).main()
    except ServerConnectionFailure as e:
        print(
            in_color('red',
                     "\nError connecting to Zulip server: {}.".format(e)))
        # Acts as separator between logs
        logging.info("\n\n" + str(e) + "\n\n")
        logging.exception(e)
        sys.exit(1)
    except Exception as e:
        logging.info("\n\n" + str(e) + "\n\n")
        logging.exception(e)
        if args.debug:
            sys.stdout.flush()
            traceback.print_exc(file=sys.stderr)
            run_debugger = input("Run Debugger? (y/n): ")
            if run_debugger in ["y", "Y", "yes"]:
                # Open PUDB Debuuger
                import pudb
                pudb.post_mortem()

        if hasattr(e, 'extra_info'):
            print(
                "\n" + in_color("red", e.extra_info),  # type: ignore
                file=sys.stderr)

        print(in_color(
            "red", "\nZulip Terminal has crashed!"
            "\nPlease refer to " + LOG_FILENAME + " for full log of"
            " the error."),
              file=sys.stderr)
        print("You can ask for help at:", file=sys.stderr)
        print("https://chat.zulip.org/#narrow/stream/206-zulip-terminal",
              file=sys.stderr)
        print("\nThanks for using the Zulip-Terminal interface.\n")
        sys.stderr.flush()

    finally:
        if args.profile:
            prof.disable()
            prof.dump_stats("/tmp/profile.data")
            print("Profile data saved to /tmp/profile.data")
            print("You can visualize it using e.g."
                  "`snakeviz /tmp/profile.data`")

        sys.exit(1)
Ejemplo n.º 38
0
    theml.draw_screen()
    handle_loading=theml.set_alarm_in(0.5,loadingstatus,"")

def testpopup(data):
    logs.write("VSAUCE::"+data)
    cube.open_pop_up()


if len(sys.argv)!=2:
    valid=False
else:
    valid=True
    port=sys.argv[1]
    kellogs=serial.Serial(port=port,timeout=1)

if valid:
    thescreen = cube.draw_cube()
    #logicthread = threading.Thread(target=do_logic)
    urwid.connect_signal(cube.txt_scramble, 'change', set_scramble)
    urwid.connect_signal(cube.chk_scan, 'change', clear_scramble)
    urwid.connect_signal(cube.btn_quit, 'click', on_quit, "")
    urwid.connect_signal(cube.btn_submit, 'click', on_submit, cube.thescramble)
    #urwid.connect_signal(cube.gf1.contents[1][0],'',testpopup,"michael here")
    ml = urwid.MainLoop(thescreen, palette, unhandled_input=onclick,pop_ups=True)
    ml.screen.set_terminal_properties(colors=256)
    urwid.set_encoding("utf-8")
    ml.run()
else:
    print("::usage::\n"+sys.argv[0]+" [com device]\nWhere:\n[com device] -> Arduino Serial Communication Port\n\n")
    print("example:\n\n"+sys.argv[0]+" COM3\n"+sys.argv[0]+" /dev/ttyAM0")
Ejemplo n.º 39
0

class FakeClass:
    def __init__(*args, **keys):
        pass


URWID_PRE_9P9 = False

try:
    import urwid.curses_display
    import urwid.raw_display
    import urwid
    import urwutil
    import urwfiledlg
    urwid.set_encoding("ascii")  #  gives better performance than 'utf8'
    if 0 == urwid.__version__.find('0.9.8') or 0 == urwid.__version__.find(
            '0.9.7'):
        URWID_PRE_9P9 = True
except Exception, e:
    urwid = FakeModule()
    urwid.Edit = FakeClass()
    urwid.Columns = FakeClass()
    urwid.AttrWrap = FakeClass()
    urwid.Pile = FakeClass()
    urwid.the_error = str(e)

import cStringIO
# PyRAF modules
import iraf, irafpar, irafhelp, iraftask, iraffunctions
Ejemplo n.º 40
0
def main(options: Optional[List[str]] = None) -> None:
    """
    Launch Zulip Terminal.
    """

    argv = options if options is not None else sys.argv[1:]
    args = parse_args(argv)

    set_encoding('utf-8')

    if args.debug:
        print("NOTE: Debug mode enabled; API calls being logged to {}.".format(
            in_color("blue", API_CALL_LOG_FILENAME)))
        requests_logfile_handler = logging.FileHandler(API_CALL_LOG_FILENAME)
        requests_logger.addHandler(requests_logfile_handler)
    else:
        requests_logger.addHandler(logging.NullHandler())

    if args.profile:
        import cProfile
        prof = cProfile.Profile()
        prof.enable()

    if args.version:
        print('Zulip Terminal ' + ZT_VERSION)
        sys.exit(0)

    if args.config_file:
        zuliprc_path = args.config_file
    else:
        zuliprc_path = '~/zuliprc'

    try:
        zterm = parse_zuliprc(zuliprc_path)

        if args.autohide:
            zterm['autohide'] = (args.autohide, 'on command line')

        if args.theme:
            theme_to_use = (args.theme, 'on command line')
        else:
            theme_to_use = zterm['theme']

        available_themes = all_themes()
        theme_aliases = aliased_themes()
        is_valid_theme = (theme_to_use[0] in available_themes
                          or theme_to_use[0] in theme_aliases)
        if not is_valid_theme:
            print("Invalid theme '{}' was specified {}.".format(*theme_to_use))
            print("The following themes are available:")
            for theme in available_themes:
                print("  ", theme)
            print("Specify theme in zuliprc file or override "
                  "using -t/--theme options on command line.")
            sys.exit(1)
        if theme_to_use[0] not in available_themes:
            # theme must be an alias, as it is valid
            real_theme_name = theme_aliases[theme_to_use[0]]
            theme_to_use = (real_theme_name, "{} (by alias '{}')".format(
                theme_to_use[1], theme_to_use[0]))

        print("Loading with:")
        print("   theme '{}' specified {}.".format(*theme_to_use))
        complete, incomplete = complete_and_incomplete_themes()
        if theme_to_use[0] in incomplete:
            print(
                in_color(
                    'yellow', "   WARNING: Incomplete theme; "
                    "results may vary!\n"
                    "      (you could try: {})".format(", ".join(complete))))
        print("   autohide setting '{}' specified {}.".format(
            *zterm['autohide']))
        print("   footlinks setting '{}' specified {}.".format(
            *zterm['footlinks']))
        # For binary settings
        # Specify setting in order True, False
        valid_settings = {
            'autohide': ['autohide', 'no_autohide'],
            'notify': ['enabled', 'disabled'],
            'footlinks': ['enabled', 'disabled'],
        }
        boolean_settings = dict()  # type: Dict[str, bool]
        for setting, valid_values in valid_settings.items():
            if zterm[setting][0] not in valid_values:
                print("Invalid {} setting '{}' was specified {}.".format(
                    setting, *zterm[setting]))
                print("The following options are available:")
                for option in valid_values:
                    print("  ", option)
                print("Specify the {} option in zuliprc file.".format(setting))
                sys.exit(1)
            boolean_settings[setting] = (zterm[setting][0] == valid_values[0])

        color_depth = int(args.color_depth)
        if color_depth == 1:
            theme_data = theme_with_monochrome_added(THEMES[theme_to_use[0]])
        else:
            theme_data = THEMES[theme_to_use[0]]

        Controller(zuliprc_path, theme_data, int(args.color_depth),
                   **boolean_settings).main()
    except ServerConnectionFailure as e:
        print(
            in_color('red',
                     "\nError connecting to Zulip server: {}.".format(e)))
        # Acts as separator between logs
        zt_logger.info("\n\n" + str(e) + "\n\n")
        zt_logger.exception(e)
        sys.exit(1)
    except (display_common.AttrSpecError, display_common.ScreenError) as e:
        # NOTE: Strictly this is not necessarily just a theme error
        # FIXME: Add test for this - once loading takes place after UI setup
        print(in_color('red', "\nPossible theme error: {}.".format(e)))
        # Acts as separator between logs
        zt_logger.info("\n\n" + str(e) + "\n\n")
        zt_logger.exception(e)
        sys.exit(1)
    except Exception as e:
        zt_logger.info("\n\n" + str(e) + "\n\n")
        zt_logger.exception(e)
        if args.debug:
            sys.stdout.flush()
            traceback.print_exc(file=sys.stderr)
            run_debugger = input("Run Debugger? (y/n): ")
            if run_debugger in ["y", "Y", "yes"]:
                # Open PUDB Debuuger
                import pudb
                pudb.post_mortem()

        if hasattr(e, 'extra_info'):
            print(
                "\n" + in_color("red", e.extra_info),  # type: ignore
                file=sys.stderr)

        print(in_color(
            "red", "\nZulip Terminal has crashed!"
            "\nPlease refer to " + TRACEBACK_LOG_FILENAME +
            " for full log of the error."),
              file=sys.stderr)
        print("You can ask for help at:", file=sys.stderr)
        print("https://chat.zulip.org/#narrow/stream/206-zulip-terminal",
              file=sys.stderr)
        print("\nThanks for using the Zulip-Terminal interface.\n")
        sys.stderr.flush()

    finally:
        if args.profile:
            prof.disable()
            import tempfile
            with tempfile.NamedTemporaryFile(prefix="zulip_term_profile.",
                                             suffix=".dat",
                                             delete=False) as profile_file:
                profile_path = profile_file.name
            # Dump stats only after temporary file is closed (for Win NT+ case)
            prof.dump_stats(profile_path)
            print("Profile data saved to {0}.\n"
                  "You can visualize it using e.g. `snakeviz {0}`".format(
                      profile_path))

        sys.exit(1)
Ejemplo n.º 41
0
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# vim:fileencoding=utf8
# gflags is python 2.x only *sigh*
from Main import Main
import urwid
urwid.set_encoding("UTF-8")
welcome_message = urwid.Edit("Sikevux's awesome homework thingey stuff\n-> ")
def interface_add(luser_input):
	task_add_data = luser_input.split("::")
	task_add_notes = ""
	task_add_title = task_add_data[0]
	if len(task_add_data) >= 2:
		task_add_notes = task_add_data[1]
		Main().addTask(task_add_title, task_add_notes)

def interface_show(task_show_input):
#	return task_show_input
	return Main().showTask(task_show_input)

def interface_list():
	tasks = Main().listTasks()
	return_value = ""
	for task in tasks['items']:
		return_value += task['title']+"\n"
	return_value = return_value[:-1]
	return return_value

def new_command():
	return urwid.Edit(("-> "))
Ejemplo n.º 42
0
    def __init__(self, host='localhost', port=XPLODIFYD_PORT):
        self.logged = False
        self.spoticlient = spclient(host, port)

        self._playlists = None
        self._active_pl = None
        self._active_pl_button = None
        self._plwalker = urwid.SimpleFocusListWalker([])
        self._tracks = {}
        self._active_tr_button = None
        self._current_state = SpotifyCmd.PAUSE
        self._trwalker = urwid.SimpleFocusListWalker([])
        self.plpane = urwid.ListBox(self._plwalker)
        self.trackpane = urwid.ListBox(self._trwalker)
        self.logwid = urwid.AttrWrap(urwid.Text(u"Not Logged In."), "log")
        self.trackwid = urwid.AttrWrap(urwid.Text(u"Now playing: (none)"),
                                       "track")
        self.header = urwid.Pile([self.logwid, self.trackwid])
        self.footer = urwid.AttrWrap(urwid.Text(self.footer_text), "foot")

        self._poller = None
        self._state = 0
        self._sess_state = 0
        self._mutex = threading.Lock()
        self._stop = threading.Event()

        self.widgets = [self.plpane, self.trackpane]

        email = urwid.Edit(u'Username:  '******'Password:  '******'Login')
        urwid.connect_signal(logbutton, 'click', self.login)

        self.mainview = urwid.Columns(self.widgets,
                                      dividechars=1,
                                      focus_column=0)
        self.loginview = urwid.Filler(
            urwid.Pile([
                email, passwd,
                urwid.AttrMap(logbutton, None, focus_map='reversed')
            ]))
        self.overlay = urwid.Overlay(self.loginview,
                                     self.mainview,
                                     align='center',
                                     width=('relative', 30),
                                     valign='middle',
                                     height=('relative', 30),
                                     min_width=30,
                                     min_height=6)
        super(XplodifyApp,
              self).__init__(urwid.AttrWrap(self.mainview, 'body'),
                             footer=self.footer,
                             header=self.header)

        urwid.set_encoding("ISO-8859-*")
        self.loop = urwid.MainLoop(self,
                                   self.palette,
                                   unhandled_input=self.unhandled_keypress)
Ejemplo n.º 43
0
 def setUp(self):
     urwid.set_encoding('utf-8')
Ejemplo n.º 44
0
 def setUp(self):
     urwid.set_encoding("utf-8")
Ejemplo n.º 45
0
 def setUp(self):
     urwid.set_encoding("euc-jp")
Ejemplo n.º 46
0
#Console Notepad V.0.1

import sys

import urwid

urwid.set_encoding("UTF-8")

class LineNavigate(urwid.ListWalker):

    def __init__(self, name):
        self.file = open(name)
        self.lines = []
        self.focus = 0

    def get_focus(self):
        return self.change_position(self.focus)

    def set_focus(self, focus):
        self.focus = focus
        self._modified()

    def get_next(self, start_from):
        #return self.change_position(start_from + 1)
        return self.change_position(start_from + 1)

    def get_prev(self, start_from):
        return self.change_position(start_from - 1)

    def read_next_line(self):