def use_glib_event_loop(loop=None):
    """
    Use the asyncio event loop for prompt_toolkit applications.
    """
    # Don't create a new loop if the current one uses asyncio already.
    current_loop = get_event_loop()
    if current_loop and isinstance(current_loop, GLibEventLoop):
        return

    set_event_loop(GLibEventLoop(loop))
Esempio n. 2
0
def _run_coroutine(coroutine):
    """
    Takes a generator that can yield Future instances.

    Example:

        def gen():
            yield From(...)
            print('...')
            yield From(...)
        ensure_future(gen())

    The values which are yielded by the given coroutine are supposed to be
    `Future` objects.
    """
    assert isinstance(coroutine, types.GeneratorType)
    loop = get_event_loop()

    result_f = loop.create_future()

    # Loop through the generator.
    def step_next(f=None):
        " Execute next step of the coroutine."
        try:
            # Run until next yield.
            if f is None:
                new_f = coroutine.send(None)
            else:
                exc = f.exception()
                if exc:
                    new_f = coroutine.throw(exc)
                else:
                    new_f = coroutine.send(f.result())
        except StopIteration as e:
            # Stop coroutine. Make sure that a result has been set in the future,
            # this will call the callbacks. (Also, don't take any result from
            # StopIteration, it has already been set using `raise Return()`.
            if not result_f.done():
                result_f.set_result(None)
        except Return as e:
            result_f.set_result(e.value)
        except BaseException as e:
            result_f.set_exception(e)
        else:
            # Process yielded value from coroutine.
            assert isinstance(new_f, Future)

            @new_f.add_done_callback
            def continue_(_):
                step_next(new_f)

    # Start processing coroutine.
    step_next()

    return result_f
Esempio n. 3
0
    def __init__(self, loop=None, command=['/bin/bash']):
        self.loop = loop or get_event_loop()

        def done_callback(*a, **kw):
            sys.exit(0)  # TODO
            pass

        self.process = Process.from_command(
            self.loop,
            lambda: self.on_content_changed.fire(),
            command,
            done_callback,
            bell_func=None,
            before_exec_func=None,
            has_priority=None)
        self.process.start()

        self.on_content_changed = Event(self)
Esempio n. 4
0
    def _on_input_timeout(self, buff):
        """
        When there is no input activity,
        in another thread, get the signature of the current code.
        """
        assert isinstance(buff, Buffer)
        app = self.app

        # Never run multiple get-signature threads.
        if self._get_signatures_thread_running:
            return
        self._get_signatures_thread_running = True

        document = buff.document

        def run():
            script = get_jedi_script_from_document(document, self.get_locals(),
                                                   self.get_globals())

            # Show signatures in help text.
            if script:
                try:
                    signatures = script.call_signatures()
                except ValueError:
                    # e.g. in case of an invalid \\x escape.
                    signatures = []
                except Exception:
                    # Sometimes we still get an exception (TypeError), because
                    # of probably bugs in jedi. We can silence them.
                    # See: https://github.com/davidhalter/jedi/issues/492
                    signatures = []
                else:
                    # Try to access the params attribute just once. For Jedi
                    # signatures containing the keyword-only argument star,
                    # this will crash when retrieving it the first time with
                    # AttributeError. Every following time it works.
                    # See: https://github.com/jonathanslenders/ptpython/issues/47
                    #      https://github.com/davidhalter/jedi/issues/598
                    try:
                        if signatures:
                            signatures[0].params
                    except AttributeError:
                        pass
            else:
                signatures = []

            self._get_signatures_thread_running = False

            # Set signatures and redraw if the text didn't change in the
            # meantime. Otherwise request new signatures.
            if buff.text == document.text:
                self.signatures = signatures

                # Set docstring in docstring buffer.
                if signatures:
                    string = signatures[0].docstring()
                    if not isinstance(string, six.text_type):
                        string = string.decode('utf-8')
                    self.docstring_buffer.reset(
                        document=Document(string, cursor_position=0))
                else:
                    self.docstring_buffer.reset()

                app.invalidate()
            else:
                self._on_input_timeout(buff)

        get_event_loop().run_in_executor(run)
Esempio n. 5
0
def _run_coroutine(coroutine):
    """
    Takes a generator that can yield Future instances.

    Example:

        def gen():
            yield From(...)
            print('...')
            yield From(...)
        ensure_future(gen())

    The values which are yielded by the given coroutine are supposed to be
    `Future` objects.
    """
    assert isinstance(coroutine, types.GeneratorType)
    loop = get_event_loop()

    result_f = loop.create_future()

    # Wrap this future in a `_FutureRef`. We need this in order to be able to
    # break all its references when we're done. This is important
    # because in case of an exception, we want to be sure that
    # `result_f.__del__` is triggered as soon as possible, so that we see the
    # exception.

    # (If `step_next` had a direct reference to `result_f` and there is a
    # future that references `step_next`, then sometimes it won't be cleaned up
    # immediately. - I'm not sure how exactly, but in that case it requires the
    # garbage collector, because refcounting isn't sufficient.)
    ref = _FutureRef(result_f)

    # Loop through the generator.
    def step_next(f=None):
        " Execute next step of the coroutine."
        try:
            if f is None:
                new_f = coroutine.send(None)
            else:
                exc = f.exception()
                if exc:
                    new_f = coroutine.throw(exc)
                else:
                    new_f = coroutine.send(f.result())
        except StopIteration as e:
            # Stop coroutine. Make sure that a result has been set in the future,
            # this will call the callbacks. (Also, don't take any result from
            # StopIteration, it has already been set using `raise Return()`.
            if not ref.future.done():
                ref.future.set_result(None)
                ref.forget()
        except Return as e:
            ref.future.set_result(e.value)
            ref.forget()
        except BaseException as e:
            ref.future.set_exception(e)
            ref.forget()
        else:
            # Process yielded value from coroutine.
            assert isinstance(new_f, Future)

            @new_f.add_done_callback
            def continue_(_):
                step_next(new_f)

    # Start processing coroutine.
    step_next()

    return result_f
Esempio n. 6
0
    def _on_input_timeout(self, buff):
        """
        When there is no input activity,
        in another thread, get the signature of the current code.
        """
        assert isinstance(buff, Buffer)
        app = self.app

        # Never run multiple get-signature threads.
        if self._get_signatures_thread_running:
            return
        self._get_signatures_thread_running = True

        document = buff.document

        def run():
            script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())

            # Show signatures in help text.
            if script:
                try:
                    signatures = script.call_signatures()
                except ValueError:
                    # e.g. in case of an invalid \\x escape.
                    signatures = []
                except Exception:
                    # Sometimes we still get an exception (TypeError), because
                    # of probably bugs in jedi. We can silence them.
                    # See: https://github.com/davidhalter/jedi/issues/492
                    signatures = []
                else:
                    # Try to access the params attribute just once. For Jedi
                    # signatures containing the keyword-only argument star,
                    # this will crash when retrieving it the first time with
                    # AttributeError. Every following time it works.
                    # See: https://github.com/jonathanslenders/ptpython/issues/47
                    #      https://github.com/davidhalter/jedi/issues/598
                    try:
                        if signatures:
                            signatures[0].params
                    except AttributeError:
                        pass
            else:
                signatures = []

            self._get_signatures_thread_running = False

            # Set signatures and redraw if the text didn't change in the
            # meantime. Otherwise request new signatures.
            if buff.text == document.text:
                self.signatures = signatures

                # Set docstring in docstring buffer.
                if signatures:
                    string = signatures[0].docstring()
                    if not isinstance(string, six.text_type):
                        string = string.decode('utf-8')
                    self.docstring_buffer.reset(
                        document=Document(string, cursor_position=0))
                else:
                    self.docstring_buffer.reset()

                app.invalidate()
            else:
                self._on_input_timeout(buff)

        get_event_loop().run_in_executor(run)
def _run_coroutine(coroutine):
    """
    Takes a generator that can yield Future instances.

    Example:

        def gen():
            yield From(...)
            print('...')
            yield From(...)
        ensure_future(gen())

    The values which are yielded by the given coroutine are supposed to be
    `Future` objects.
    """
    assert isinstance(coroutine, types.GeneratorType)
    loop = get_event_loop()

    result_f = loop.create_future()

    # Wrap this future in a `_FutureRef`. We need this in order to be able to
    # break all its references when we're done. This is important
    # because in case of an exception, we want to be sure that
    # `result_f.__del__` is triggered as soon as possible, so that we see the
    # exception.

    # (If `step_next` had a direct reference to `result_f` and there is a
    # future that references `step_next`, then sometimes it won't be cleaned up
    # immediately. - I'm not sure how exactly, but in that case it requires the
    # garbage collector, because refcounting isn't sufficient.)
    ref = _FutureRef(result_f)

    # Loop through the generator.
    def step_next(f=None):
        " Execute next step of the coroutine."
        try:
            if f is None:
                new_f = coroutine.send(None)
            else:
                exc = f.exception()
                if exc:
                    new_f = coroutine.throw(exc)
                else:
                    new_f = coroutine.send(f.result())
        except StopIteration:
            # Stop coroutine. Make sure that a result has been set in the future,
            # this will call the callbacks. (Also, don't take any result from
            # StopIteration, it has already been set using `raise Return()`.
            if not ref.future.done():
                ref.future.set_result(None)
                ref.forget()
        except Return as e:
            ref.future.set_result(e.value)
            ref.forget()
        except BaseException as e:
            ref.future.set_exception(e)
            ref.forget()
        else:
            # Process yielded value from coroutine.
            assert isinstance(new_f, Future), 'got %r' % (new_f, )

            @new_f.add_done_callback
            def continue_(_):
                step_next(new_f)

    # Start processing coroutine.
    step_next()

    return result_f
Esempio n. 8
0
 def __init__(self, loop=None):
     self.loop = loop or get_event_loop()
     self.container = Window(content=TerminalControl(loop), wrap_lines=True)