Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add asyncio call from gui #1576

Open
atitoff opened this issue Jan 12, 2025 · 0 comments
Open

Add asyncio call from gui #1576

atitoff opened this issue Jan 12, 2025 · 0 comments

Comments

@atitoff
Copy link

atitoff commented Jan 12, 2025

I wrote a simple library.
Asynchrony is launched in a separate thread.

import webview
import asyncio

from lib.wv_async import WVAsync, JsApi

# add user function
class Js(JsApi):
    def call23(self, d):
        print('call23', d)

html = """<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8"></head><body>

<button onClick="pywebview.api.call('random', {a: 'ss', b: 25})">Test</button><br><br>
<button onClick="pywebview.api.call23({a: 'ss', b: 25})">Test2</button>

</body></html>"""

async def random(d):
    print('def random:', d)
    i = 0
    while True:
        await asyncio.sleep(1)
        print('random', i)
        i += 1


wv_app = WVAsync()
js_api = Js(wv_app.jq)

wv_app.registry('random', random)

window = webview.create_window('JS API example', html=html, js_api=js_api)
wv_app.start(window)
webview.start()

lib wv_async.py

import asyncio
from threading import Thread

import janus


class WVAsync:
    def __init__(self):
        self.jq = janus.Queue()
        self.js_api = JsApi(self.jq)
        self.window = None
        self._t = Thread(target=self._main)
        self._reg = {}  # {fn_name: fn}

    def registry(self, name, fn):
        self._reg[name] = fn

    def _on_closing(self):
        print('closing')
        self.jq.sync_q.put_nowait({'closing': True})

    def start(self, window):
        self.window = window
        self.window.events.closing += self._on_closing
        self._t.start()

    def _main(self):
        asyncio.run(self._main_loop())

    async def _main_loop(self):
        while True:  # ret = {name: {value}}
            ret = await self.jq.async_q.get()
            print(ret)
            for fn_name in ret:
                if fn_name in self._reg:
                    asyncio.create_task(self._reg[fn_name](ret[fn_name]))
                    await asyncio.sleep(0)
            if 'closing' in ret:
                break


class JsApi:
    def __init__(self, jq):
        self.jq = jq

    def call(self, rpc_name, d=None):
        print(rpc_name, d)
        self.jq.sync_q.put_nowait({rpc_name: d})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant