Ejemplo n.º 1
0
    def run(self) -> None:
        """
        Run the REPL loop.
        """
        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                # Pull text from the user.
                try:
                    text = self.read()
                except EOFError:
                    return
                except BaseException as e:
                    # Something went wrong while reading input.
                    # (E.g., a bug in the completer that propagates. Don't
                    # crash the REPL.)
                    traceback.print_exc()
                    continue

                # Run it; display the result (or errors if applicable).
                self.run_and_show_expression(text)
        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 2
0
    async def run_async(self) -> None:
        if self.terminal_title:
            set_title(self.terminal_title)

        while True:
            # Capture the current input_mode in order to restore it after reset,
            # for ViState.reset() sets it to InputMode.INSERT unconditionally and
            # doesn't accept any arguments.
            def pre_run(
                last_input_mode: InputMode = self.app.vi_state.input_mode,
            ) -> None:
                if self.vi_keep_last_used_mode:
                    self.app.vi_state.input_mode = last_input_mode

                if not self.vi_keep_last_used_mode and self.vi_start_in_navigation_mode:
                    self.app.vi_state.input_mode = InputMode.NAVIGATION

            # Run the UI.
            try:
                text = await self.app.run_async(pre_run=pre_run)
            except EOFError:
                return
            except KeyboardInterrupt:
                # Abort - try again.
                self.default_buffer.document = Document()
            else:
                self._process_text(text)

        if self.terminal_title:
            clear_title()
Ejemplo n.º 3
0
    def __init__(self, arguments: dict) -> None:
        try:
            self.path, self.revision, self.files = parse_args(**arguments)
            repo = Repo(path=self.path)

            path = repo.working_dir.replace(os.path.expanduser('~'), '~', 1)
            self.working_dir = repo.working_dir
            revision = self.revision[0]
            if self.revision == 'HEAD':
                revision = repo._nrepo.head.ref.name
            title = '%s \uf418 %s' % (path.rstrip('/'), revision)

            shortcuts.set_title('%s - Git Log Viewer' % title)
        except NoRevisionMatches:
            print('No revisions match the given arguments.', file=sys.stderr)
            sys.exit(1)
        except NoPathMatches:
            print("No paths match the given arguments.", file=sys.stderr)
            sys.exit(1)

        self.date_max_len = 0
        self.name_max_len = 0
        self._repo = repo
        self.line_count = self._repo.count_commits(self.revision[0])
        self.commit_list: List[Commit] = []
        self.log_entry_list: List[Commit] = []
        self.search_state: Optional[SearchState] = None
        self._search_thread: Optional[Thread] = None
        super().__init__(line_count=self.line_count,
                         get_line=self.get_line,
                         show_cursor=False)
        self.fill_up(utils.screen_height())
Ejemplo n.º 4
0
    async def run_async(self) -> None:
        """
        Run the REPL loop, but run the blocking parts in an executor, so that
        we don't block the event loop. Both the input and output (which can
        display a pager) will run in a separate thread with their own event
        loop, this way ptpython's own event loop won't interfere with the
        asyncio event loop from where this is called.

        The "eval" however happens in the current thread, which is important.
        (Both for control-C to work, as well as for the code to see the right
        thread in which it was embedded).
        """
        loop = asyncio.get_event_loop()

        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                try:
                    # Read.
                    try:
                        text = await loop.run_in_executor(None, self.read)
                    except EOFError:
                        return

                    # Eval.
                    try:
                        result = await self.eval_async(text)
                    except KeyboardInterrupt as e:  # KeyboardInterrupt doesn't inherit from Exception.
                        raise
                    except SystemExit:
                        return
                    except BaseException as e:
                        self._handle_exception(e)
                    else:
                        # Print.
                        if result is not None:
                            await loop.run_in_executor(
                                None, lambda: self.show_result(result))

                        # Loop.
                        self.current_statement_index += 1
                        self.signatures = []

                except KeyboardInterrupt as e:
                    # XXX: This does not yet work properly. In some situations,
                    # `KeyboardInterrupt` exceptions can end up in the event
                    # loop selector.
                    self._handle_keyboard_interrupt(e)
        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 5
0
    def _init_window(self):
        clear()
        set_title("Test Infra CLI")

        if not self._global_variables.pull_secret:
            message_dialog(
                title="Pull Secret",
                text=
                "Cant find PULL_SECRET, some functionality might not work as expected"
            ).run()
Ejemplo n.º 6
0
    def run(self) -> None:
        """
        Run the REPL loop.
        """
        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                try:
                    # Read.
                    try:
                        text = self.read()
                    except EOFError:
                        return

                    # Eval.
                    try:
                        result = self.eval(text)
                    except KeyboardInterrupt as e:  # KeyboardInterrupt doesn't inherit from Exception.
                        raise
                    except SystemExit:
                        return
                    except BaseException as e:
                        self._handle_exception(e)
                    else:
                        # Print.
                        if result is not None:
                            self.show_result(result)

                        # Loop.
                        self.current_statement_index += 1
                        self.signatures = []

                except KeyboardInterrupt as e:
                    # Handle all possible `KeyboardInterrupt` errors. This can
                    # happen during the `eval`, but also during the
                    # `show_result` if something takes too long.
                    # (Try/catch is around the whole block, because we want to
                    # prevent that a Control-C keypress terminates the REPL in
                    # any case.)
                    self._handle_keyboard_interrupt(e)
        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 7
0
    async def run_async(self) -> None:
        """
        Run the REPL loop, but run the blocking parts in an executor, so that
        we don't block the event loop. Both the input and output (which can
        display a pager) will run in a separate thread with their own event
        loop, this way ptpython's own event loop won't interfere with the
        asyncio event loop from where this is called.

        The "eval" however happens in the current thread, which is important.
        (Both for control-C to work, as well as for the code to see the right
        thread in which it was embedded).
        """
        loop = asyncio.get_event_loop()

        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                try:
                    # Read.
                    try:
                        text = await loop.run_in_executor(None, self.read)
                    except EOFError:
                        return
                    except BaseException:
                        # Something went wrong while reading input.
                        # (E.g., a bug in the completer that propagates. Don't
                        # crash the REPL.)
                        traceback.print_exc()
                        continue

                    # Eval.
                    await self.run_and_show_expression_async(text)

                except KeyboardInterrupt as e:
                    # XXX: This does not yet work properly. In some situations,
                    # `KeyboardInterrupt` exceptions can end up in the event
                    # loop selector.
                    self._handle_keyboard_interrupt(e)
        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 8
0
    async def run_async(self) -> None:
        if self.terminal_title:
            set_title(self.terminal_title)

        while True:
            # Run the UI.
            try:
                text = await self.app.run_async()
            except EOFError:
                return
            except KeyboardInterrupt:
                # Abort - try again.
                self.default_buffer.document = Document()
            else:
                self._process_text(text)

        if self.terminal_title:
            clear_title()
Ejemplo n.º 9
0
    def run(self):
        if self.terminal_title:
            set_title(self.terminal_title)

        while True:
            # Run the UI.
            try:
                text = self.app.run(inputhook=inputhook)
            except EOFError:
                return
            except KeyboardInterrupt:
                # Abort - try again.
                self.default_buffer.document = Document()
            else:
                self._process_text(text)

        if self.terminal_title:
            clear_title()
Ejemplo n.º 10
0
 def __init__(self):
     self.sc = SC()
     self.mwapi = MWapi()
     self.temp_file = "temp.wav"
     self.session = PromptSession(PygmentsLexer(SqlLexer),
                                  completer=sql_completer,
                                  style=style,
                                  color_depth=ColorDepth.TRUE_COLOR)
     set_title("voc 1.0")
     print_f([(
         'class:comp',
         '::::::::::::::::::::::Welcome to use xiaoda dictionary voc 1.0.:::::::::::::::::::::'
     )])
     for each in logo_arr:
         print_f([each])
     print_f([(
         'class:comp',
         ':::::::::::::::::::::::::::::Type a word to look up now!::::::::::::::::::::::::::::'
     )])
Ejemplo n.º 11
0
    def run(self) -> None:
        """
        Run the REPL loop.
        """
        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                # Read.
                try:
                    text = self.read()
                except EOFError:
                    return

                # Eval.
                try:
                    result = self.eval(text)
                except KeyboardInterrupt as e:  # KeyboardInterrupt doesn't inherit from Exception.
                    self._handle_keyboard_interrupt(e)
                except SystemExit:
                    return
                except BaseException as e:
                    self._handle_exception(e)
                else:
                    # Print.
                    if result is not None:
                        self.show_result(result)

                    # Loop.
                    self.current_statement_index += 1
                    self.signatures = []

        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        self._current_menu: menus.Menu = None
        self._float_message_layout = None

        self.set_menu(menus.SplashScreen)
        set_title(self.version_string)

        super().__init__(*args, **kwargs,
                         layout=Layout(DynamicContainer(self._get_layout)),
                         full_screen=True)

        self.token: oauth2.OAuth2Token = None
        self.user: user.User = None

        self.preferences = preferences.Preferences.load('cache/prefs.json')
        self.oauth_client = oauth2.OAuth2Client(CONFIG.get('oauth2'))
        self.rpc_handler = presence.RPCHandler(
            CONFIG.get('rpc', {}).get('client_id')
        )
        self.riitag_watcher: watcher.RiitagWatcher = None

        self.oauth_client.start_server(CONFIG.get('port', 4000))
Ejemplo n.º 13
0
    def run(self) -> None:
        if self.terminal_title:
            set_title(self.terminal_title)

        def prompt() -> str:
            # In order to make sure that asyncio code written in the
            # interactive shell doesn't interfere with the prompt, we run the
            # prompt in a different event loop.
            # If we don't do this, people could spawn coroutine with a
            # while/true inside which will freeze the prompt.

            try:
                old_loop: Optional[
                    asyncio.AbstractEventLoop] = asyncio.get_event_loop()
            except RuntimeError:
                # This happens when the user used `asyncio.run()`.
                old_loop = None

            asyncio.set_event_loop(self.pt_loop)
            try:
                return self.app.run()  # inputhook=inputhook)
            finally:
                # Restore the original event loop.
                asyncio.set_event_loop(old_loop)

        while True:
            # Run the UI.
            try:
                text = prompt()
            except EOFError:
                return
            except KeyboardInterrupt:
                # Abort - try again.
                self.default_buffer.document = Document()
            else:
                self._process_text(text)

        if self.terminal_title:
            clear_title()
Ejemplo n.º 14
0
    def run(self) -> None:
        """
        Run the REPL loop.
        """
        if self.terminal_title:
            set_title(self.terminal_title)

        self._add_to_namespace()

        try:
            while True:
                # Pull text from the user.
                try:
                    text = self.read()
                except EOFError:
                    return

                # Run it; display the result (or errors if applicable).
                self.run_and_show_expression(text)
        finally:
            if self.terminal_title:
                clear_title()
            self._remove_from_namespace()
Ejemplo n.º 15
0
#!/usr/bin/env python
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.shortcuts import set_title

if __name__ == '__main__':
    set_title('This is the terminal title')
    answer = prompt('Give me some input: ')
    set_title('')

    print('You said: %s' % answer)
Ejemplo n.º 16
0
        if arg in _FLAGS[key]:
            return True
    return False


if __name__ == "__main__":
    init()
    if has_flag("debug"):
        _DEBUG = True
    if has_flag("help"):
        print(Fore.LIGHTBLUE_EX + "Available options:" + Fore.LIGHTYELLOW_EX)
        for f in _FLAGS.values():
            print("\t%s" % str(f))
        exit()
    print(Fore.LIGHTYELLOW_EX + "Loading..." + Fore.RESET)
    set_title("DarkShell")
    try:
        if _DEBUG:
            raise MetaError(reason="Skipping the update check", message="Debug State")
        is_latest, version = check_for_updates()
    except MetaError as ex:
        if _DEBUG:
            print(Fore.LIGHTYELLOW_EX + str(ex) + Fore.RESET)
        is_latest, version = True, __version__
    if not _DEBUG:
        DarkShell.do_clear(args=[])
    print(Fore.LIGHTBLUE_EX + "Welcome to DarkShell %s%s" % (
        "v" + __version__, (" (v%s is available)" % version) if not is_latest else "" + Fore.RESET))
    try:
        DarkShell().cmd_loop()
    except Exception as ex:
Ejemplo n.º 17
0
            return True
    return False


if __name__ == "__main__":
    init()
    if len(argv) > 1:
        if has_flag("debug"):
            _DEBUG = True
        if has_flag("help"):
            print(Fore.LIGHTBLUE_EX + "Available options:" + Fore.LIGHTYELLOW_EX)
            for f in _FLAGS.values():
                print("\t%s" % str(f))
            exit()
    print(Fore.LIGHTYELLOW_EX + "Loading..." + Fore.RESET)
    set_title("DarkShell-R")
    try:
        if _DEBUG:
            raise MetaError(reason="Skipping the update check", message="Debug State")
        is_latest, version = check_for_updates()
    except MetaError as ex:
        if _DEBUG:
            print(Fore.LIGHTYELLOW_EX + str(ex) + Fore.RESET)
        is_latest, version = True, __version__
    if not _DEBUG:
        DarkSouls.warn_anti_cheat()
        DarkShell.do_clear(args=[])
    print(Fore.LIGHTBLUE_EX + "Welcome to DarkShell %s%s" % (
        "v" + __version__, (" (v%s is available)" % version) if not is_latest else "" + Fore.RESET))
    try:
        DarkShell().cmd_loop()
Ejemplo n.º 18
0
def set_console_title():
    if APP_PACKAGE_NAME:
        set_title('ADK      %s    SN: %s   APP:%s' %
                  (DEVICE_NAME, DEVICE_UDID, APP_PACKAGE_NAME))
    else:
        set_title('ADK      %s    SN: %s' % (DEVICE_NAME, DEVICE_UDID))
Ejemplo n.º 19
0
 def update_version(self):
     set_title("DarkShell-R — Game Version: %s" % self.get_version())
#!/usr/bin/env python
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.shortcuts import set_title


if __name__ == '__main__':
    set_title('This is the terminal title')
    answer = prompt('Give me some input: ')
    set_title('')

    print('You said: %s' % answer)
Ejemplo n.º 21
0
#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.shortcuts import set_title

if __name__ == "__main__":
    set_title("This is the terminal title")
    answer = prompt("Give me some input: ")
    set_title("")

    print("You said: %s" % answer)
Ejemplo n.º 22
0
        curr = load_json('%s/meta.json' % module_folder)
        curr['lessons'] = [load_json(lesson_json) for lesson_json in sorted(glob('%s/lesson*.json' % module_folder))]
        LESSON_DATA.append(curr)

    # load save data
    if exists(SAVE_FILE_PATH):
        f = open(SAVE_FILE_PATH,'rb'); SAVE_DATA = pload(f); f.close(); APP_STYLE = SAVE_DATA['style']
    else:
        SAVE_DATA = blank_save()
        makedirs(dirname(SAVE_FILE_PATH), exist_ok=True); save_game()

    # maximize terminal if possible (only supports Windows)
    maximize_console()

    # prep
    set_title(TITLE_STR)
    run_app('welcome')
    curr_app = 'main_menu'

    # game loop
    while curr_app is not None:
        # Main Menu (pick next app)
        if curr_app == 'main_menu':
            curr_app = run_app(curr_app)

        # Styles Menu (pick style, set next app to Main Menu)
        elif curr_app == 'styles':
            tmp_style = run_app(curr_app)
            if tmp_style is not None:
                APP_STYLE = STYLES[tmp_style]; SAVE_DATA['style'] = APP_STYLE; save_game()
            curr_app = 'main_menu'