nsRepeatService.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. //
  6. // Eric Vaughan
  7. // Netscape Communications
  8. //
  9. // See documentation in associated header file
  10. //
  11. #include "nsRepeatService.h"
  12. #include "nsIServiceManager.h"
  13. nsRepeatService* nsRepeatService::gInstance = nullptr;
  14. nsRepeatService::nsRepeatService()
  15. : mCallback(nullptr), mCallbackData(nullptr)
  16. {
  17. }
  18. nsRepeatService::~nsRepeatService()
  19. {
  20. NS_ASSERTION(!mCallback && !mCallbackData, "Callback was not removed before shutdown");
  21. }
  22. nsRepeatService*
  23. nsRepeatService::GetInstance()
  24. {
  25. if (!gInstance) {
  26. gInstance = new nsRepeatService();
  27. NS_IF_ADDREF(gInstance);
  28. }
  29. return gInstance;
  30. }
  31. /*static*/ void
  32. nsRepeatService::Shutdown()
  33. {
  34. NS_IF_RELEASE(gInstance);
  35. }
  36. void nsRepeatService::Start(Callback aCallback, void* aCallbackData,
  37. uint32_t aInitialDelay)
  38. {
  39. NS_PRECONDITION(aCallback != nullptr, "null ptr");
  40. mCallback = aCallback;
  41. mCallbackData = aCallbackData;
  42. nsresult rv;
  43. mRepeatTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
  44. if (NS_SUCCEEDED(rv)) {
  45. mRepeatTimer->InitWithCallback(this, aInitialDelay, nsITimer::TYPE_ONE_SHOT);
  46. }
  47. }
  48. void nsRepeatService::Stop(Callback aCallback, void* aCallbackData)
  49. {
  50. if (mCallback != aCallback || mCallbackData != aCallbackData)
  51. return;
  52. //printf("Stopping repeat timer\n");
  53. if (mRepeatTimer) {
  54. mRepeatTimer->Cancel();
  55. mRepeatTimer = nullptr;
  56. }
  57. mCallback = nullptr;
  58. mCallbackData = nullptr;
  59. }
  60. NS_IMETHODIMP nsRepeatService::Notify(nsITimer *timer)
  61. {
  62. // do callback
  63. if (mCallback)
  64. mCallback(mCallbackData);
  65. // start timer again.
  66. if (mRepeatTimer) {
  67. mRepeatTimer->InitWithCallback(this, REPEAT_DELAY, nsITimer::TYPE_ONE_SHOT);
  68. }
  69. return NS_OK;
  70. }
  71. NS_IMPL_ISUPPORTS(nsRepeatService, nsITimerCallback)