Line data Source code
1 : /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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 : #include "WebGLContextLossHandler.h"
7 :
8 : #include "mozilla/DebugOnly.h"
9 : #include "nsISupportsImpl.h"
10 : #include "nsITimer.h"
11 : #include "nsThreadUtils.h"
12 : #include "WebGLContext.h"
13 :
14 : namespace mozilla {
15 :
16 : class WatchdogTimerEvent final : public nsITimerCallback
17 : {
18 : const WeakPtr<WebGLContextLossHandler> mHandler;
19 :
20 : public:
21 : NS_DECL_ISUPPORTS
22 :
23 0 : explicit WatchdogTimerEvent(WebGLContextLossHandler* handler)
24 0 : : mHandler(handler)
25 0 : { }
26 :
27 : private:
28 0 : virtual ~WatchdogTimerEvent() { }
29 :
30 0 : NS_IMETHOD Notify(nsITimer*) override {
31 0 : if (mHandler) {
32 0 : mHandler->TimerCallback();
33 : }
34 0 : return NS_OK;
35 : }
36 : };
37 :
38 0 : NS_IMPL_ISUPPORTS(WatchdogTimerEvent, nsITimerCallback, nsISupports)
39 :
40 : ////////////////////////////////////////
41 :
42 0 : WebGLContextLossHandler::WebGLContextLossHandler(WebGLContext* webgl)
43 : : mWebGL(webgl)
44 0 : , mTimer(do_CreateInstance(NS_TIMER_CONTRACTID))
45 : , mTimerPending(false)
46 : , mShouldRunTimerAgain(false)
47 : #ifdef DEBUG
48 0 : , mEventTarget(GetCurrentThreadSerialEventTarget())
49 : #endif
50 : {
51 0 : MOZ_ASSERT(mEventTarget);
52 0 : }
53 :
54 0 : WebGLContextLossHandler::~WebGLContextLossHandler()
55 : {
56 0 : const DebugOnly<nsISerialEventTarget*> callingThread = GetCurrentThreadSerialEventTarget();
57 0 : MOZ_ASSERT(!callingThread || mEventTarget->IsOnCurrentThread());
58 0 : }
59 :
60 : ////////////////////
61 :
62 : void
63 0 : WebGLContextLossHandler::RunTimer()
64 : {
65 0 : MOZ_ASSERT(mEventTarget->IsOnCurrentThread());
66 :
67 : // If the timer was already running, don't restart it here. Instead,
68 : // wait until the previous call is done, then fire it one more time.
69 : // This is also an optimization to prevent unnecessary
70 : // cross-communication between threads.
71 0 : if (mTimerPending) {
72 0 : mShouldRunTimerAgain = true;
73 0 : return;
74 : }
75 :
76 0 : const RefPtr<WatchdogTimerEvent> event = new WatchdogTimerEvent(this);
77 0 : const uint32_t kDelayMS = 1000;
78 0 : mTimer->InitWithCallback(event, kDelayMS, nsITimer::TYPE_ONE_SHOT);
79 :
80 0 : mTimerPending = true;
81 : }
82 :
83 : ////////////////////
84 :
85 : void
86 0 : WebGLContextLossHandler::TimerCallback()
87 : {
88 0 : MOZ_ASSERT(mEventTarget->IsOnCurrentThread());
89 :
90 0 : mTimerPending = false;
91 :
92 0 : const bool runOnceMore = mShouldRunTimerAgain;
93 0 : mShouldRunTimerAgain = false;
94 :
95 0 : mWebGL->UpdateContextLossStatus();
96 :
97 0 : if (runOnceMore && !mTimerPending) {
98 0 : RunTimer();
99 : }
100 0 : }
101 :
102 : } // namespace mozilla
|