Exemplo n.º 1
0
    def interactive_config_bootstrap(self,
                                     path,
                                     config_title,
                                     source_config="",
                                     edit_message="",
                                     post_message=""):
        # Initialize the config system (copy any example configs to their final directories)
        self.init_config_system(path, source_config)
        # Strip the original title and replace it with the one we're being fed
        self.add_title_to_file(path, config_title)

        # Ask the user to configure the program
        if len(edit_message) > 0:
            print(edit_message)
            # Wait for them to press a key
            blessed.Terminal().inkey()

        # Drop them into editing
        self.edit_file(path, False)

        if len(post_message) > 0:
            print(post_message)
            blessed.Terminal().inkey()

        print(blessed.Terminal().clear_eos() + "")
        exit(self.EXIT_CODE_CONFIG)
Exemplo n.º 2
0
    def __init__(
        self,
        loop: AbstractEventLoop,
        protocol: Protocol,
        input_handler,
        output_handler,
    ) -> None:

        super().__init__()

        self._loop = loop
        self._protocol = protocol

        import sys
        self._input = _File(sys.__stdin__, mode='r', non_blocking=True)
        self._output = _File(sys.__stdout__, mode='w')

        self._input_decoder = codecs.getincrementaldecoder(
            self._input.encoding)(errors='ignore')
        self._input_buf = []

        self._output_encoder = codecs.getincrementalencoder(
            self._output.encoding)(errors='ignore')
        self._output_buf = deque()

        self._saved_attr = None
        self._terminal = None
        self._shared = False
        self._echo = None

        if self._input.isatty:
            self._saved_attr = termios.tcgetattr(self._input.fd)
            attr = termios.tcgetattr(self._input.fd)
            attr[3] &= ~termios.ICANON
            attr[6][termios.VMIN] = 1
            attr[6][termios.VTIME] = 0
            termios.tcsetattr(self._input.fd, termios.TCSADRAIN, attr)

            if self._input == self._output:
                self._terminal = blessed.Terminal()
                self._shared = True

            else:
                self._terminal = blessed.Terminal(
                    stream=self._input.tty_file(mode='w'), )

            self._echo = _File(self._terminal.stream, mode='w')

        self._loop.call_soon(self._protocol.connection_made, self)
        self._loop.call_soon(self._add_reader)
Exemplo n.º 3
0
def main(transport_logical_preset, application_preset):
    """Run echo test."""
    connection = connect_serial_retry(baudrate=115200, timeout=None)
    if connection is None:
        logger.fatal('Failed to establish serial connection!')
        return

    handlers = {
        'echo': LoggingHandler(b'echo', name='Echo'),
        'copy': LoggingHandler(b'copy', name='Copy'),
        'reply': LoggingHandler(b'reply', name='Reply'),
        'prefix': LoggingHandler(b'prefix', name='Prefix'),
        'blink': LoggingHandler(b'blink', name='Blink'),
        'ping-pong': PingPongHandler()
    }

    term = blessed.Terminal()
    protocol = AutomaticStack(
        make_preset_stack(transport_logical=transport_logical_preset,
                          application=application_preset),
        list(handlers.values()), ReceiveLoggerLink())
    stack = ThreadedSerialAdapter(
        connection, make_threading_stack(protocol_stack=protocol))
    logger.info(stack)

    time.sleep(1.0)
    run_once(run_console, stack, handlers, term)
    logger.info('Quitting!')
Exemplo n.º 4
0
    def __init__(self, _address=None, cols=20, rows=2, backlight_enabled=True):
        import blessed

        self.term = blessed.Terminal()
        self.backlt = backlight_enabled

        super(_TerminalLCD, self).__init__(cols=cols, rows=rows)
Exemplo n.º 5
0
def dprint(text):
    """ Function for printing debug information """
    if (not SHOW_DEBUG):
        return

    t = blessed.Terminal()
    print(t.red_bold("@DEBUG: {t}".format(t=text)))
Exemplo n.º 6
0
    def __init__(self):

        # Parse command line arguments
        # (also loads the configuration file)
        self.parse_args()

        self.connector = JiraConnector(self.config)

        self.issues = self.get_responses()
        self.sorted_issues = self.issues.copy()

        result_tuple = Selector.select_item(self.sorted_issues,
                                            self.NUM_RESULTS, self.QUERY_TEXT)

        term = blessed.Terminal()
        # User cancelled the select
        if result_tuple is None:
            print(term.clear_eos() + "")
            exit(self.EXIT_CODE_CANCEL)

        selected_issue = result_tuple[0]
        self.sorted_issues = result_tuple[1]

        if selected_issue is not None:
            self.save_issue(selected_issue)
            self.write_to_cache(self.cache_file_path)
            self.selected_issue = selected_issue

        print(term.clear_eos() + "")
        exit(self.normal_exit_code)
Exemplo n.º 7
0
    def __init__(self):
        self.cursed = Cursed()
        self.t = blessed.Terminal()

        prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei']
        self.sizes = list(
            reversed([(1024**i, name) for i, name in enumerate(prefixes)]))
Exemplo n.º 8
0
def main():
    term = blessed.Terminal()
    with term.cbreak(), term.hidden_cursor(), term.fullscreen():
        idx = len(HSV_SORTED_COLORS) // 2
        dirty = True
        while True:
            if dirty:
                outp = render(term, idx)
                print(outp, end='', flush=True)
            with term.hidden_cursor():
                inp = term.inkey()
            dirty = True
            if inp.code == term.KEY_LEFT or inp == 'h':
                idx -= 1
            elif inp.code == term.KEY_DOWN or inp == 'j':
                idx += term.width
            elif inp.code == term.KEY_UP or inp == 'k':
                idx -= term.width
            elif inp.code == term.KEY_RIGHT or inp == 'l':
                idx += 1
            elif inp.code in (term.KEY_TAB, term.KEY_BTAB):
                term.number_of_colors = next_color(
                    term.number_of_colors, inp.code == term.KEY_TAB)
            elif inp in ('[', ']'):
                term.color_distance_algorithm = next_algo(
                    term.color_distance_algorithm, inp == '[')
            elif inp == '\x0c':
                pass
            else:
                dirty = False

            while idx < 0:
                idx += len(HSV_SORTED_COLORS)
            while idx >= len(HSV_SORTED_COLORS):
                idx -= len(HSV_SORTED_COLORS)
Exemplo n.º 9
0
def main():

    # Initalize blessed - the curses wrapper.
    t = blessed.Terminal()
    globals()["t"] = t

    # Print the introduction method and alike things.
    print(t.bold_red(Client.conf.intro_banner))
    print("Welcome to Latharia.")
    print("This is the main console, where you can do various things!")

    print(options_menu)

    # Interpret and execute options
    while True:
        command = input("Option: ")

        if (command == "0"):
            func.client_menu()
            break
        elif (command == "1"):
            func.server_menu()
            break
        else:
            print("Invalid option")
            continue
Exemplo n.º 10
0
    def __init__(self, script, shell):
        self.script = Script(script)
        self.shell = shell
        self.STDINFD = sys.stdin.fileno()
        self.exit_flag = False
        self.statusline_flag = False
        self.terminal = TerminalSession(self.shell)
        self.terminal.add_output_callback( lambda c: self.update_statusline() )
        self.saved_terminal_settings = None
        self.command_parser = CommandParser()

        self.command_parser.add_command("passthrough", ['pass-through','pass'])
        self.command_parser.add_command("temporary passthrough",['temporary pass-through', 'temp pass'])
        self.command_parser.add_command("line")
        self.command_parser.add_command("mode")
        self.command_parser.add_command("statusline")
        self.command_parser.add_command("stdout")
        self.command_parser.add_command("pause")
        self.command_parser.add_command("comment")
        self.command_parser.add_command("display")

        if have_blessed:
          self.bterm = blessed.Terminal()
          self.detected_term_escape_sequences = list(blessed.keyboard.get_keyboard_sequences(self.bterm).keys())
        else:
          self.detected_term_escape_sequences = []
          if have_blessings:
            self.bterm = blessings.Terminal()
          else:
            self.bterm = None

        try:
          self.saved_terminal_settings = termios.tcgetattr(self.STDINFD)
          tty.setraw(self.STDINFD)
        except:
          logging.warning("Could not save terminal state for stdin. This likely means that no terminal is in control.")

        self.input_handler = UserInputHandler(self.STDINFD)

        self.mode = self.Modes.Insert
        self.mode_handlers = {self.Modes.Insert:self.InsertMode(self),
                              self.Modes.Line:self.LineMode(self),
                              self.Modes.Command:self.CommandMode(self),
                              self.Modes.Passthrough:self.PassthroughMode(self),
                              self.Modes.TemporaryPassthrough:self.TemporaryPassthroughMode(self),
                              }
        self.mode_status_abbrvs = {self.Modes.Insert:"I",
                                   self.Modes.Command:"C",
                                   self.Modes.Passthrough:"P",
                                   self.Modes.TemporaryPassthrough:"T",
                                   self.Modes.Line:"L"}


        self.monitor_server = None
        self.monitor_server_flag = False
        self.monitor_server_hostname = "localhost"
        self.monitor_server_port = 3000

        self.message_display = None
Exemplo n.º 11
0
 def disable_styling(self):
     # The `does_styling` attr is read-only, so in order to actually change
     # it we do a small hack: create a new Terminal object which has styling
     # disabled, and then replace the "guts" of the current object with those
     # of the newly created object.
     tt = blessed.Terminal(force_styling=None)
     tt.override_width = self.override_width
     self.__dict__, tt.__dict__ = tt.__dict__, self.__dict__
Exemplo n.º 12
0
 def __lldb_init_module(debugger, env_dict):
     """
     Called by LLDB when the module is loaded
     """
     if not 'cmd' in env_dict:
         log.debug("Initialising LLDB command")
         env_dict['cmd'] = VoltronLLDBCommand(debugger, env_dict)
         print(blessed.Terminal().bold_red("Voltron loaded."))
         print("Run `voltron init` after you load a target.")
Exemplo n.º 13
0
 def invoke(self, *args):
     regs = voltron.debugger.registers()
     reg_list = [
         'rax', 'rbx', 'rcx', 'rdx', 'rbp', 'rsp', 'rdi', 'rsi', 'rip',
         'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15'
     ]
     for name in reg_list:
         print("{t.bold}{:3} {t.normal}{:0=16X}".format(
             name, regs[name], t=blessed.Terminal()))
Exemplo n.º 14
0
def _main():
    s.log.setup()
    assert s.net.port_free(
        _port), 'something already running on port: {}'.format(_port)
    s.thread.new(_server)
    terminal = blessed.Terminal()
    with terminal.fullscreen():
        with terminal.hidden_cursor():
            _app(terminal)
Exemplo n.º 15
0
def convert(ctx):
    """Convert video file(s)"""

    containers = build_containers(ctx.obj['FILES'])
    running = main_menu(containers)
    terminal = blessed.Terminal()
    err = ErrorWriter(terminal)

    padding = max([len(container.file_name) for container in running])
    for line_number, container in enumerate(running):
        container.add_progress(terminal, line_number + 2, padding)

    writer = Writer(0, terminal, 'bold_blue_on_black')
    total_ms = sum([container.microseconds for container in running])
    widgets = [
        progressbar.Percentage(), ' ',
        progressbar.Bar(), ' ',
        progressbar.Timer(), ' | ',
        progressbar.ETA()
    ]
    pr_bar = progressbar.ProgressBar(max_value=total_ms,
                                     widgets=widgets,
                                     fd=writer)

    with terminal.fullscreen():
        while running:
            total_progress = 0
            for container in running:
                try:
                    progress = container.progress
                    container.pr_bar.update(progress)
                except (ProgressFinishedError) as _e:
                    if container.process.returncode:
                        err.write('Warning: ffmpeg error while converting '
                                  '{}'.format(container.file_name))
                        err.write(container.process.communicate()[1].strip(
                            os.linesep))

                    running.remove(container)
                    progress = container.microseconds
                    container.pr_bar.finish()

                total_progress += progress

            pr_bar.update(total_progress)
            time.sleep(0.2)

    pr_bar.finish()
    click.clear()
    for message in err.messages:
        click.secho(
            message,
            fg='red',
            bg='black',
        )
Exemplo n.º 16
0
 def __lldb_init_module(debugger, env_dict):
     """
     Called by LLDB when the module is loaded
     """
     if 'cmd' not in env_dict:
         log.debug("Initialising LLDB command")
         env_dict['cmd'] = VoltronLLDBCommand(debugger, env_dict)
         voltron.cmd = env_dict['cmd']
         print(blessed.Terminal().bold_red("Voltron loaded."))
         print("Run `voltron init` after you load a target.")
         env_dict['cmd'].adaptor.host.HandleCommand("script import voltron")
Exemplo n.º 17
0
def main():
    term = blessed.Terminal()
    print(term.clear)
    start_ts = time.time()
    try:
        command_line(term)
    except Exception:
        log.exception("Exception")
        return 1
    finally:
        print(f"Total processing time: {format_sec_to_hms(time.time() - start_ts)}")
    return 0
Exemplo n.º 18
0
    def start_config_copy(self):

        print("Starting interactive copy dialogue for local configuration...")

        try:
            git_root = self.get_git_root_dir()
            git_branch = self.get_git_branch()

            current_local_config_path = self.local_configuration_path(
                git_root, git_branch)
        except git.exc.InvalidGitRepositoryError:
            # If we have no git repo, we have no local config, which means what the hell are we doing in this function
            print(
                "[WARNING] No GIT repo detected, can't edit local configurations."
            )
            exit(1)

        local_configs_root = self.local_configs_dir()
        paths = [
            path for path in self.get_directory_contents(local_configs_root)
            if path != current_local_config_path
        ]
        items = [path.relative_to(local_configs_root) for path in paths]

        selected_item_tuple = Selector.select_item(
            items, 15, "Search for local config: ")

        if selected_item_tuple is not None:

            selected_item = selected_item_tuple[0]

            print(
                "Replace current local config for {1}{2} with config from: {0}? (y/n) "
                .format(selected_item, git_root, git_branch),
                end="",
                flush=True)
            term = blessed.Terminal()
            key = term.inkey()

            if key == "y":
                match = [
                    path for path in paths if path.match(str(selected_item))
                ]
                selected_path = match[0]

                print("Replacing {0} with {1}...".format(
                    current_local_config_path, selected_path))
                if not self.dry_run:
                    shutil.copyfile(str(selected_path),
                                    str(current_local_config_path))

        exit(self.normal_exit_code)
Exemplo n.º 19
0
Arquivo: test_sui.py Projeto: pji/life
 def test_init_with_parameters(self):
     """Start.__init__() should set the given parameters, as
     the initial attribute values.
     """
     exp = {
         'data': grid.Grid(3, 3),
         'term': blessed.Terminal(),
     }
     state = sui.Start(**exp)
     act = {
         'data': state.data,
         'term': state.term,
     }
     self._dicteq(exp, act)
Exemplo n.º 20
0
Arquivo: test_sui.py Projeto: pji/life
 def test__init__with_parameters(self):
     """Save.__init__() should accept given parameters and use them
     as the initial values for the relevant attributes.
     """
     exp = {
         'data': grid.Grid(3, 3),
         'term': blessed.Terminal(),
     }
     state = sui.Save(**exp)
     act = {
         'data': state.data,
         'term': state.term,
     }
     self.assertDictEqual(exp, act)
Exemplo n.º 21
0
Arquivo: test_sui.py Projeto: pji/life
 def test_init_with_parameters(self):
     """Given grid and term, Load.__init__() will set the Load
     objects attributes with the given values.
     """
     exp = {
         'data': grid.Grid(3, 3),
         'term': blessed.Terminal(),
     }
     state = sui.Load(**exp)
     act = {
         'data': state.data,
         'term': state.term,
     }
     self.assertDictEqual(exp, act)
Exemplo n.º 22
0
def _print_lines_not_matching_pattern(errors, pattern, decorate=True):
    term = blessed.Terminal()
    msg_start = ''
    msg_prepend_lines = ''
    msg_end = ''
    if decorate:
        msg_start = term.darkorange(f'WARNING: following lines do not match '
                                    f'the pattern "{pattern}" and have been '
                                    f'ignored:\n')
        msg_prepend_lines = term.darkorange('✘ ')
        msg_end = term.darkorange('End of ignored lines list\n')
    msg_content = '\n'.join(msg_prepend_lines + line for line in errors)
    message = f'{msg_start}{msg_content}\n{msg_end}'
    sys.stderr.write(message)
Exemplo n.º 23
0
def main():
    """Program entry point."""
    term = blessed.Terminal(stream=sys.__stderr__)
    # This table was generated with the aide of bin/new-wide-by-version.py in
    # the wcwidth repository, note that 4.1.0 and 5.0.0 have identical wide
    # characters.
    previous_version = '4.1.0'
    wide_by_version = [
        ('5.1.0', '龼'),
        ('5.2.0', '🈯'),
        ('6.0.0', '🈁'),
        ('8.0.0', '🉐'),
        ('9.0.0', '🐹'),
        ('10.0.0', '🦖'),
        ('11.0.0', '🧪'),
        ('12.0.0', '🪐'),
        ('12.1.0', '㋿'),
        ('13.0.0', '🫕'),
    ]

    try:
        echo = functools.partial(print, end='', flush=True, file=sys.stderr)
        echo()
    except TypeError:
        def echo(string):
            print(string, end='', file=sys.stderr)
            sys.stderr.flush()

    def get_xpos():
        ypos, xpos = term.get_location(timeout=3.0)
        if -1 in (ypos, xpos):
            echo(term.normal + term.move_x(0) + term.clear_eol)
            echo('ucs-detect: Unicode Version could not be determined!\n')
            sys.exit(1)
        return xpos

    with term.hidden_cursor():
        for version, wchar in wide_by_version:
            start_x = get_xpos()
            echo(wchar)
            end_x = get_xpos()
            echo(term.move_x(0) + term.clear_eol)
            if end_x - start_x != 2:
                break
            previous_version = version
        echo(term.normal)
        print('UNICODE_VERSION={0}; export UNICODE_VERSION'
              .format(previous_version))
    return 0
Exemplo n.º 24
0
    def __init__(self, args):
        self.args = args

        self.imgterm = None

        if self.args['--sixel']:
            self.imgterm = 'sixel'
        elif 'TERM_PROGRAM' in os.environ:
            if os.environ['TERM_PROGRAM'] == 'WezTerm':
                self.imgterm = 'WezTerm'
            elif os.environ['TERM_PROGRAM'] == 'iTerm.app':
                self.imgterm = 'iTerm2'
        elif os.environ['TERM'] == 'xterm-kitty':
            self.imgterm = 'kitty'

        if self.imgterm is None:
            print("Error: Unable to detect your terminal program.")
            sys.exit(1)

        self.args = args
        self.term = blessed.Terminal()
        if self.term.number_of_colors < 256:
            print("Got just %d colors" % self.term.number_of_colors)
            sys.exit(1)
        self.starty = None
        self.startx = None
        osver, _, arch =platform.mac_ver()
        self.is_macos = osver is not None and osver != ''
        if self.args['-g'] is not None:
            if 'x' not in self.args['-g']:
                print("[Error] The geometry must be specified in the form wxh  - example:  640x480")
                sys.exit(1)

            self.scwid, self.scht = [ int(sci, 10) for sci in self.args['-g'].lower().split('x') ]
        elif self.is_macos:
            self.scwid, self.scht = self.macos_get_pixwidth()
            self.scht -= 35
        else:
            print("[Error] The window geometry must be specified in order to display a cover.")
            sys.exit(1)

        print(self.term.clear)
        ts = get_terminal_size()
# Get how many pixels per character
        self.ppc_w = self.scwid / ts.columns
        self.ppc_h = self.scht / (ts.lines + 1)
        print(f'scwid: {self.scwid} pixels/w: {self.ppc_w}  scht: {self.scht} pixels/h: {self.ppc_h}')
        print(self.term.move_yx(ts.lines-1, 0))
Exemplo n.º 25
0
 def __init__(self,
              data=None,
              options=None,
              prefix=__file__,
              name=None,
              version=None):
     if options is not None:
         self.options = options
     if version is not None:
         self.version = version
     if data is not None:
         self.data = data
     self.name = name
     self.prefix = prefix
     self.init()
     self.term = blessed.Terminal()
Exemplo n.º 26
0
def parse(filename, pattern, errors_only=False):
    """
    Parse file using provided pattern and output the result. Do not store
    anything.
    """
    _, titles = parser.parse_pattern(pattern)
    parsed, errors = parser.parse_file(filename, pattern)
    if not errors_only:
        print(terminal.tabulate([titles] + parsed))
    if errors:
        _print_lines_not_matching_pattern(errors,
                                          pattern,
                                          decorate=not errors_only)
    elif errors_only:
        term = blessed.Terminal()
        sys.stderr.write(term.chartreuse3('No parsing errors ☺\n'))
Exemplo n.º 27
0
Arquivo: test_sui.py Projeto: pji/life
    def test_update_ui(self, mock_print):
        """Start.update_ui() should draw the initial UI."""
        data = grid.Grid(3, 3)
        term = blessed.Terminal()
        state = sui.Start(data, term)
        exp = [
            call(loc.format(1, 1) + '   '),
            call(loc.format(2, 1) + '   '),
            call(loc.format(3, 1) + '\u2500' * data.width),
            call(loc.format(4, 1) + state.menu + clr_eol, end='', flush=True),
        ]

        state.update_ui()
        act = mock_print.mock_calls

        self._listeq(exp, act)
Exemplo n.º 28
0
Arquivo: test_sui.py Projeto: pji/life
    def test_input(self, mock_print, _, __):
        """Start.input() should return the run command if any key is
        pressed."""
        term = blessed.Terminal()
        exp = ('run', )
        exp_calls = [
            call(loc.format(term.height, 1) + 'Press any key to continue.' +
                 clr_eol,
                 end='',
                 flush=True),
        ]

        state = sui.Start()
        act = state.input()
        act_calls = mock_print.mock_calls

        self.assertTupleEqual(exp, act)
        self.assertListEqual(exp_calls, act_calls)
Exemplo n.º 29
0
    def __init__(self):
        self.jupyter = False
        self.ipython = False
        if sys.__stdin__ and sys.__stdout__:
            import blessed
            import _locale

            # Save current locale settings
            try:
                _lls = []
                for i in range(100):
                    ll = _locale.setlocale(i)
                    _lls.append(ll)
            except _locale.Error:
                pass

            self._blessed_term = blessed.Terminal()

            # Restore previous locale settings
            for i, ll in enumerate(_lls):
                _locale.setlocale(i, ll)

            self._allow_unicode = False
            self._enable_keyboard = True
            self._enable_colors = True
            self._enable_terminal_codes = True
            self._encoding = self._blessed_term._encoding
            enc = self._encoding.upper()
            if enc == "UTF8" or enc == "UTF-8":
                self._allow_unicode = True
            self.is_a_tty = sys.__stdin__.isatty() and sys.__stdout__.isatty()
            self._width = 0
            self._height = 0
            self._check_ipython()
        else:
            self._enable_keyboard = False
            self._enable_colors = False
            self._enable_terminal_codes = False
            self._encoding = "UTF8"
            self._allow_unicode = True
            self.is_a_tty = False
            self._width = 80
            self._height = 25
Exemplo n.º 30
0
async def gui_main(gh: GitHub, cmd_options: CommandOptions):
    try:
        term = blessed.Terminal()

        def get_key():
            with term.raw():
                return term.inkey()

        with term.fullscreen(), term.hidden_cursor():
            main = MainWindow(term, gh, cmd_options)
            await main.init()

            while True:
                main.on_paint()
                with concurrent.futures.ThreadPoolExecutor() as pool:
                    key = await asyncio.get_event_loop().run_in_executor(pool, get_key)
                await main.on_input(key)
    except ExitApp:
        pass