Bug 1200063 - Add a generic implementation of nsITimerCallback that's usable with a lambda or other function object. r=kats

We can consider moving this to xpcom in the future.
This commit is contained in:
Botond Ballo 2015-09-16 20:29:41 -04:00
parent d7d2955d42
commit add8d8267f
2 changed files with 43 additions and 0 deletions

View File

@ -81,5 +81,7 @@ APZThreadUtils::RunOnControllerThread(Task* aTask)
#endif
}
NS_IMPL_ISUPPORTS(GenericTimerCallbackBase, nsITimerCallback)
} // namespace layers
} // namespace mozilla

View File

@ -7,6 +7,7 @@
#define mozilla_layers_APZThreadUtils_h
#include "base/message_loop.h"
#include "nsITimer.h"
class Task;
@ -51,6 +52,46 @@ public:
static void RunOnControllerThread(Task* aTask);
};
// A base class for GenericTimerCallback<Function>.
// This is necessary because NS_IMPL_ISUPPORTS doesn't work for a class
// template.
class GenericTimerCallbackBase : public nsITimerCallback
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
protected:
virtual ~GenericTimerCallbackBase() {}
};
// An nsITimerCallback implementation that can be used with any function
// object that's callable with no arguments.
template <typename Function>
class GenericTimerCallback final : public GenericTimerCallbackBase
{
public:
explicit GenericTimerCallback(const Function& aFunction) : mFunction(aFunction) {}
NS_IMETHODIMP Notify(nsITimer*) override
{
mFunction();
return NS_OK;
}
private:
Function mFunction;
};
// Convenience function for constructing a GenericTimerCallback.
// Returns a raw pointer, suitable for passing directly as an argument to
// nsITimer::InitWithCallback(). The intention is to enable the following
// terse inline usage:
// timer->InitWithCallback(NewTimerCallback([](){ ... }), delay);
template <typename Function>
GenericTimerCallback<Function>* NewTimerCallback(const Function& aFunction)
{
return new GenericTimerCallback<Function>(aFunction);
}
} // namespace layers
} // namespace mozilla