.
Working with the tools we have, here's a decorator using
ui.delay:
from ui import * from functools import partial def poll(interval): def interval_decorator(func): def func_wrapper(self, *args, **kwargs): with_args = partial(wrapped_func, self, *args, **kwargs) delay(with_args, interval) return func(self, *args, **kwargs) wrapped_func = func_wrapper return func_wrapper return interval_decorator
Which can be used like this:
class CustomView(View): @poll(1) def get_text(self, name): print("Hello " + name) def will_close(self): cancel_delays() if __name__ == '__main__': v = CustomView() v.background_color = 'white' v.present('sheet') v.get_text('John')
... but as with anything using ui.delay, this is unstable and keeps crashing my Pythonista.
@mikael , exactly my point. Not easy to do. Also cancel delays is global in that it cancels all the queue. @omz mentioned before it might be a good idea for him to add something like this to a view. He Did not talk about the implementation. But of course he is in the best position to implement this type of callback that does not break. I have my fingers crossed he will do something 🤑
@Phuket2 I still think it might be a good idea, but I haven't found the time to actually work on this yet.
While we are waiting, the version below:
- does not use cancel_delays
- does not keep crashing
- does not need the View to be the root view (i.e. the one that is presented)
- will go dormant when off screen
- can be turned on and off per view by setting
pollingattribute True or False
I think I will turn this into a Composite component, with the following planned features:
- can be applied to any view (not just ui.Views)
- usage is easier - just define the polling methods
- support UI thread or background execution
- support chaining of these methods, as many animations need something like that
Updated code, sorry for the dump, but it is not awfully long:
#coding: utf-8 from ui import * from functools import partial def poll(interval): def interval_decorator(func): def func_wrapper(self, *args, **kwargs): if self.polling and isinstance(self, View) and self.on_screen: with_args = partial(wrapped_func, self, *args, **kwargs) delay(with_args, interval) return func(self, *args, **kwargs) else: self._polling = False wrapped_func = func_wrapper return func_wrapper return interval_decorator class CustomView(View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._polling = False @poll(1) def get_text(self, name): print("Hello " + name) def will_close(self): self.polling = False @property def polling(self): return self._polling @polling.setter def polling(self, value): was_polling = self._polling self._polling = value if not was_polling and self._polling: self.get_text('John') if __name__ == '__main__': v = View() v.background_color = 'white' v.present('sheet') c = CustomView() v.add_subview(c) c.polling = True
May be just use scene timer.
import ui, scene class TimerView(ui.View): class TimerScene(scene.Scene): def update(self): self.view.superview.update() def create_sceneview(self): scene_view = scene.SceneView() scene_view.width = 0 scene_view.height = 0 scene_view.frame_interval = self.frame_interval scene_view.scene = TimerView.TimerScene() return scene_view def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.frame_interval = kwargs.get('frame_interval', 1) self.add_subview(self.create_sceneview()) @property def start_time(self): return self.subviews[0].scene.t def draw(self): pass def update(self): self.set_needs_display() if __name__ == '__main__': from time import localtime class DigitalClock(TimerView):) v = DigitalClock(frame=(0,0,300, 300)) v.present('sheet')
Guys,
thanks for your code posts. I will give both versions a try out a little later today. Also thanks for your reply @omz.
You can also use async module timer
import ui import asyncio from time import localtime class DigitalClock(ui.View):) def update(self, event_loop): self.set_needs_display() event_loop.call_later(.5, self.update, event_loop) v = DigitalClock(frame=(0,0,300, 300), frame_interval=10) v.present('sheet') event_loop = asyncio.get_event_loop() event_loop.call_soon(v.update, event_loop) event_loop.run_forever()
Stop watch example (use the stopwatch.pyui from gist link in previous post)
import ui import asyncio class StopWatch(ui.View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.value = 0 self.state = 'stop', event_loop): if self.state == 'run': self.value += 1 self.set_needs_display() event_loop.call_later(.1, self.update, event_loop) def button_action(sender): v1 = sender.superview['view1'] if sender.title == 'Reset': v1.value = 0 v1.state = 'stop' elif sender.title == 'Start': v1.value = 0 v1.state = 'run' elif sender.title == 'Stop': v1.state = 'stop' v = ui.load_view() v.present('sheet') event_loop = asyncio.get_event_loop() event_loop.call_soon(v['view1'].update, event_loop) event_loop.run_forever()
This post is deleted!last edited by
@enceladus , they thanks for your code samples also.
I modified your update method in the first example. Just quickly, so it would stop after closing the window. Guessing more checks should be done.
def update(self, event_loop): if not self.on_screen: event_loop.stop() return self.set_needs_display() event_loop.call_later(.5, self.update, event_loop)
According to the docs the BaseEventLoop class is not thread safe. I am not good enough to under the implications/restrictions of this both as a standalone as well how it would interact with Pythonista's Threads. Any insights would be appreciated.
Again, for me at least is just to have a reliable and controllable way to easily add a way to call a so called poll/update method on a class, including a ui.View async.
Out of the above implementations again I am not good enough to say which is the best implementation. Appears asyncio is py3+ only. Which is fine by me, other might be looking for a 2.7 solution also.
I think that calls in event loop are run on the same thread. Button action (in stop watch example) should be put in the same event loop so that there are no thread-safety issues. As you have mentioned there could be other issues. (My experience in asyncio module is very limited and I am in learning mode.)
def button_action(sender): event_loop.call_soon(button_action_event_loop, sender) def button_action_event_loop(sender): v1 = sender.superview['view1'] if sender.title == 'Reset': v1.value = 0 v1.state = 'stop' elif sender.title == 'Start': v1.value = 0 v1.state = 'run' elif sender.title == 'Stop': v1.state = 'stop'
@Phuket2 I've added something to the latest beta. From the release notes:
In custom
ui.Viewsubclasses, you can now implement an
updatemethod (no arguments, except for
self) that gets called automatically by an internal timer. To make this work, you also have to set the new
update_intervalattribute. It specifies how often the timer fires (e.g. set to 1.0, the timer fires every second). It defaults to 0.0 (disable update timer) because otherwise this new feature might break existing code that happens to implement a method called
update.
I hope this works for you.
@omz , yup pulled another rabbit out of the hat :) was so excited when I seen the email this morning for the new beta. You have seemed to have done a lot. Just did a quick test with the update method. Appears to work perfectly. Just had a button on a form to start and stop the updates by setting the update interval. Very nice. I will do some more tests with opening Dialogs over the top etc... but many thanks, I think this will make a lot of ppl happy. Ok, back to exploring the new features :)
Is the update_interval, and update, attributes in the latest pythonista?
If now, can I get the beta?
By the way, it would be nice if the update method was an empty method (just "pass") that already existed, so users could set the update_interval and update method in the subclassed view's init method.
And whatever already exists, or is done in the future, thank you for a truly great product!
@technoway It's currently only in the beta. With regards to an empty method in the base class, setting the method in
__init__etc., that's not really possible because the act of implementing the method is a signal to change the behavior (hope that makes sense). The entire update timer machinery isn't initialized at all if your View class doesn't implement
update.
Thank you for the quick reply.
Am I allowed to install the beta version, and if so, where is it?
I am running Pythonista on an iPhone (and iPad too, but I need this particular functionality on my iPhone).
I have purchased both the Python 2.x and the Python 3.x versions of Pythonista for my iPhone.
Ah, I found the message about sending my apple ID through the e-mail. I'll do that. Thanks again, and sorry for all the noise. (I did search before my last post, but missed the relevant post).
@technoway You should have a beta invite in your email (please check your spam folder if it isn't there).
@omz, arrgh, spam. I have been patiently waiting for my invite, so long that the spam folder has been purged already. Is it easy for you to resend my invite, or should I just send another request? Sorry.
@technoway I sent the invite to the Gmail address you sent me yesterday. Did you just purge your spam folder?
@omz, I am not technoway. Sorry for jumping in; I have been waiting for the beta invite in order to test the polling functionality.