+_wxCallAfterId = None
+
+def wxCallAfter(callable, *args, **kw):
+ """
+ Call the specified function after the current and pending event
+ handlers have been completed. This is also good for making GUI
+ method calls from non-GUI threads.
+ """
+ app = wxGetApp()
+ assert app, 'No wxApp created yet'
+
+ global _wxCallAfterId
+ if _wxCallAfterId is None:
+ _wxCallAfterId = wxNewEventType()
+ app.Connect(-1, -1, _wxCallAfterId,
+ lambda event: event.callable(*event.args, **event.kw) )
+ evt = wxPyEvent()
+ evt.SetEventType(_wxCallAfterId)
+ evt.callable = callable
+ evt.args = args
+ evt.kw = kw
+ wxPostEvent(app, evt)
+
+
+#----------------------------------------------------------------------
+
+
+class wxFutureCall:
+ """
+ A convenience class for wxTimer, that calls the given callable
+ object once after the given amount of milliseconds, passing any
+ positional or keyword args. The return value of the callable is
+ availbale after it has been run with the GetResult method.
+
+ If you don't need to get the return value or restart the timer
+ then there is no need to hold a reference to this object. It will
+ hold a reference to itself while the timer is running (the timer
+ has a reference to self.Notify) but the cycle will be broken when
+ the timer completes, automatically cleaning up the wxFutureCall
+ object.
+ """
+ def __init__(self, millis, callable, *args, **kwargs):
+ self.millis = millis
+ self.callable = callable
+ self.SetArgs(*args, **kwargs)
+ self.runCount = 0
+ self.hasRun = False
+ self.result = None
+ self.timer = None
+ self.Start()
+
+ def __del__(self):
+ self.Stop()
+
+
+ def Start(self, millis=None):
+ """
+ (Re)start the timer
+ """
+ self.hasRun = False
+ if millis is not None:
+ self.millis = millis
+ self.Stop()
+ self.timer = wxPyTimer(self.Notify)
+ self.timer.Start(self.millis, wxTIMER_ONE_SHOT)
+ Restart = Start
+
+
+ def Stop(self):
+ """
+ Stop and destroy the timer.
+ """
+ if self.timer is not None:
+ self.timer.Stop()
+ self.timer = None
+
+
+ def GetInterval(self):
+ if self.timer is not None:
+ return self.timer.GetInterval()
+ else:
+ return 0
+
+
+ def IsRunning(self):
+ return self.timer is not None and self.timer.IsRunning()
+
+
+ def SetArgs(self, *args, **kwargs):
+ """
+ (Re)set the args passed to the callable object. This is
+ useful in conjunction with Restart if you want to schedule a
+ new call to the same callable object but with different
+ parameters.
+ """
+ self.args = args
+ self.kwargs = kwargs
+
+ def HasRun(self):
+ return self.hasRun
+
+ def GetResult(self):
+ return self.result
+
+ def Notify(self):
+ """
+ The timer has expired so call the callable.
+ """
+ if self.callable and getattr(self.callable, 'im_self', True):
+ self.runCount += 1
+ self.result = self.callable(*self.args, **self.kwargs)
+ self.hasRun = True
+ wxCallAfter(self.Stop)
+
+
+#----------------------------------------------------------------------