Triggering code on Pythonista focus lost
nfmusician last edited by nfmusician
I've got an app using a TextView for editing plaintext files that has a save button. In the case that focus is lost from the Pythonista app as a whole (not just the TextView itself) while the file is unsaved, is there a way to catch this and trigger an automatic save before the app sleeps?
stephen last edited by
Here u go!
Disable or enable the idle timer (which puts the device to sleep after a certain period of inactivity).
Return True if the app is currently running in the background, False otherwise.
JonB last edited by
The method using a timer to periodically check whether the app is in the background ought to work. Check once every 30 seconds, perhaps. It might not be a bad idea to just perpetually save to a file after certain periods of inactivity -- at least to a temporary file. In your delegate method, you could first call the ui.cancel_delays(), then call ui.delay(your_save_func, 30).
That way everytime you edit, after you stop typing, 30 seconds later the file gets saved. That should work in the background as well, I think (but test it).
As an alternative, you can register a callback for notifications when the app is sent to the background -- so that you call for function immediately.
mikael last edited by
from functools import partial import ui class Delegate: save_delay = 1 def textview_did_change(self, textview): ui.cancel_delays() ui.delay( partial(self.save, textview), self.save_delay) def save(self, textview): print('Saving', textview) tv = ui.TextView(delegate=Delegate()) tv.present('fullscreen')
cvp last edited by
from functools import partial
Didn't know this partial. I often have searched a way with ui.delay calling a function with arguments, without using globals. Thanks to remember me that I don't know a lot about Python 😢