How to use the udiskie.async_.Future function in udiskie

To help you get started, we’ve selected a few udiskie examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github coldfix / udiskie / udiskie / prompt.py View on Github external
except ImportError:  # for Python<3.7
    from importlib_resources import read_text

from .async_ import exec_subprocess, run_bg, Future
from .locale import _
from .config import DeviceFilter

Gtk = None

__all__ = ['password', 'browser']


dialog_definition = read_text(__package__, 'password_dialog.ui')


class Dialog(Future):

    def __init__(self, window):
        self._enter_count = 0
        self.window = window
        self.window.connect("response", self._result_handler)

    def _result_handler(self, window, response):
        self.set_result(response)

    def __enter__(self):
        self._enter_count += 1
        self._awaken()
        return self

    def __exit__(self, *exc_info):
        self._enter_count -= 1
github coldfix / udiskie / udiskie / async_.py View on Github external
async def exec_subprocess(argv):
    """
    An Future task that represents a subprocess. If successful, the task's
    result is set to the collected STDOUT of the subprocess.

    :raises subprocess.CalledProcessError: if the subprocess returns a non-zero
                                           exit code
    """
    future = Future()
    process = Gio.Subprocess.new(
        argv,
        Gio.SubprocessFlags.STDOUT_PIPE |
        Gio.SubprocessFlags.STDIN_INHERIT)
    stdin_buf = None
    cancellable = None
    process.communicate_async(
        stdin_buf, cancellable, gio_callback, future)
    result = await future
    success, stdout, stderr = process.communicate_finish(result)
    stdout = stdout.get_data()      # GLib.Bytes -> bytes
    if not success:
        raise RuntimeError("Subprocess did not exit normally!")
    exit_code = process.get_exit_status()
    if exit_code != 0:
        raise CalledProcessError(
github coldfix / udiskie / udiskie / async_.py View on Github external
GLib.idle_add(call_func, fn, *args)


def sleep(seconds):
    future = Future()
    GLib.timeout_add(int(seconds*1000), future.set_result, True)
    return future


def ensure_future(awaitable):
    if isinstance(awaitable, Future):
        return awaitable
    return Task(iter(awaitable.__await__()))


class Task(Future):

    """Turns a generator into a Future."""

    def __init__(self, generator):
        """Create and start a ``Task`` from the specified generator."""
        self._generator = generator
        run_soon(self._resume, next, self._generator)

    def _resume(self, func, *args):
        """Resume the coroutine by throwing a value or returning a value from
        the ``await`` and handle further awaits."""
        try:
            value = func(*args)
        except StopIteration:
            self._generator.close()
            self.set_result(None)
github coldfix / udiskie / udiskie / cli.py View on Github external
self.notify = Component(self._load_notify)
        self.statusicon = Component(self._load_statusicon)
        self.automounter = self._load_automounter(options['automount'])
        self.automounter.activate()

        if options['notify']:
            self.notify.activate()
        if options['notify_command']:
            # is currently enabled/disabled statically only once:
            self.notify_command()
        if show_tray:
            self.statusicon.activate()
            tasks.append(self.statusicon.instance._icon.task)
        else:
            tasks.append(Future())
        if options['automount']:
            tasks.append(self.mounter.add_all())

        return gather(*tasks)
github coldfix / udiskie / udiskie / async_.py View on Github external
def ensure_future(awaitable):
    if isinstance(awaitable, Future):
        return awaitable
    return Task(iter(awaitable.__await__()))
github coldfix / udiskie / udiskie / async_.py View on Github external
def sleep(seconds):
    future = Future()
    GLib.timeout_add(int(seconds*1000), future.set_result, True)
    return future
github coldfix / udiskie / udiskie / tray.py View on Github external
Create an object managing a tray icon.

        The actual Gtk.StatusIcon is only created as soon as you call show()
        for the first time. The reason to delay its creation is that the GTK
        icon will be initially visible, which results in a perceptable
        flickering.

        :param UdiskieMenu menumaker: menu factory
        :param Gtk.StatusIcon statusicon: status icon
        """
        self._icons = icons
        self._icon = statusicon
        self._menu = menumaker
        self._conn_left = None
        self._conn_right = None
        self.task = Future()
        menumaker._quit_action = self.destroy
github coldfix / udiskie / udiskie / async_.py View on Github external
def to_coro(func):
    @wraps(func)
    async def coro(*args, **kwargs):
        return func(*args, **kwargs)
    return coro


def run_bg(func):
    @wraps(func)
    def runner(*args, **kwargs):
        return ensure_future(func(*args, **kwargs))
    return runner


class gather(Future):

    """
    Manages a collection of asynchronous tasks.

    The callbacks are executed when all of the subtasks have completed.
    """

    def __init__(self, *tasks):
        """Create from a list of `Future`-s."""
        tasks = list(tasks)
        self._done = False
        self._results = {}
        self._num_tasks = len(tasks)
        if not tasks:
            run_soon(self.set_result, [])
        for idx, task in enumerate(tasks):