nsRepeatService.cpp (2704B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 // 8 // Eric Vaughan 9 // Netscape Communications 10 // 11 // See documentation in associated header file 12 // 13 14 #include "nsRepeatService.h" 15 16 #include "mozilla/StaticPtr.h" 17 #include "mozilla/dom/Document.h" 18 19 using namespace mozilla; 20 21 static StaticAutoPtr<nsRepeatService> gRepeatService; 22 23 nsRepeatService::nsRepeatService() 24 : mCallback(nullptr), mCallbackData(nullptr) {} 25 26 nsRepeatService::~nsRepeatService() { 27 NS_ASSERTION(!mCallback && !mCallbackData, 28 "Callback was not removed before shutdown"); 29 } 30 31 /* static */ 32 nsRepeatService* nsRepeatService::GetInstance() { 33 if (!gRepeatService) { 34 gRepeatService = new nsRepeatService(); 35 } 36 return gRepeatService; 37 } 38 39 /*static*/ 40 void nsRepeatService::Shutdown() { gRepeatService = nullptr; } 41 42 void nsRepeatService::Start(Callback aCallback, void* aCallbackData, 43 dom::Document* aDocument, 44 const nsACString& aCallbackName, 45 uint32_t aInitialDelay) { 46 MOZ_ASSERT(aCallback != nullptr, "null ptr"); 47 48 mCallback = aCallback; 49 mCallbackData = aCallbackData; 50 mCallbackName = aCallbackName; 51 52 mRepeatTimer = NS_NewTimer(GetMainThreadSerialEventTarget()); 53 54 if (mRepeatTimer) { 55 InitTimerCallback(aInitialDelay); 56 } 57 } 58 59 void nsRepeatService::Stop(Callback aCallback, void* aCallbackData) { 60 if (mCallback != aCallback || mCallbackData != aCallbackData) { 61 return; 62 } 63 64 // printf("Stopping repeat timer\n"); 65 if (mRepeatTimer) { 66 mRepeatTimer->Cancel(); 67 mRepeatTimer = nullptr; 68 } 69 mCallback = nullptr; 70 mCallbackData = nullptr; 71 } 72 73 void nsRepeatService::InitTimerCallback(uint32_t aInitialDelay) { 74 if (!mRepeatTimer) { 75 return; 76 } 77 78 mRepeatTimer->InitWithNamedFuncCallback( 79 [](nsITimer* aTimer, void* aClosure) { 80 // Use gRepeatService instead of nsRepeatService::GetInstance() (because 81 // we don't want nsRepeatService::GetInstance() to re-create a new 82 // instance for us, if we happen to get invoked after 83 // nsRepeatService::Shutdown() has nulled out gRepeatService). 84 nsRepeatService* rs = gRepeatService; 85 if (!rs) { 86 return; 87 } 88 89 if (rs->mCallback) { 90 rs->mCallback(rs->mCallbackData); 91 } 92 93 rs->InitTimerCallback(REPEAT_DELAY); 94 }, 95 nullptr, aInitialDelay, nsITimer::TYPE_ONE_SHOT, mCallbackName); 96 }