Created
February 23, 2021 16:08
-
-
Save om2c0de/3e02fdebb59a5853a24604fb56016615 to your computer and use it in GitHub Desktop.
Imitating 'async_bind'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# imitating 'async_bind' | |
from kivy.config import Config | |
Config.set('input', 'mouse', 'mouse,disable_multitouch') | |
import kivy | |
kivy.require('2.0.0') | |
import trio | |
from kivy.app import App | |
from kivy.uix.widget import Widget | |
async def async_bind(ed, name, *, filter=None): | |
def _callback(*args): | |
nonlocal parameter | |
if (filter is not None) and not filter(*args): | |
return | |
parameter = args | |
event.set() | |
parameter = None | |
bind_id = ed.fbind(name, _callback) | |
assert bind_id > 0 # check if binding succeeded | |
try: | |
while True: | |
event = trio.Event() | |
await event.wait() | |
yield parameter | |
finally: | |
ed.unbind_uid(name, bind_id) | |
class Paint(Widget): | |
def on_touch_down(self, touch): | |
if not self.collide_point(*touch.opos): | |
return | |
nursery = App.get_running_app().nursery | |
nursery.start_soon(self.draw_polyline, touch) | |
async def draw_polyline(self, touch): | |
from kivy.graphics import Line | |
def hide_touch(*args): | |
return True | |
try: | |
self.bind( | |
on_touch_down=hide_touch, | |
on_touch_move=hide_touch, | |
on_touch_up=hide_touch, | |
) | |
to_widget = self.to_widget | |
line = Line( | |
width=2, | |
points=[*to_widget(*touch.opos), *to_widget(*touch.pos)] | |
) | |
self.canvas.add(line) | |
async for widet, touch in async_bind(self, 'on_touch_down'): | |
if touch.button == 'left': | |
p = line.points | |
p.extend(to_widget(*touch.opos)) | |
line.points = p | |
elif touch.button == 'right': | |
break | |
finally: | |
self.unbind( | |
on_touch_down=hide_touch, | |
on_touch_move=hide_touch, | |
on_touch_up=hide_touch, | |
) | |
class SampleApp(App): | |
nursery = None | |
def build(self): | |
return Paint() | |
async def root_task(self): | |
async with trio.open_nursery() as nursery: | |
self.nursery = nursery | |
async def app_task(): | |
await self.async_run(async_lib='trio') | |
nursery.cancel_scope.cancel() | |
nursery.start_soon(app_task) | |
trio.run(SampleApp().root_task) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment