summaryrefslogtreecommitdiffstats
path: root/gfx/layers/apz/util/ActiveElementManager.cpp
blob: c92fec783a35a984de71121173b9a5e07dc128b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "ActiveElementManager.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_ui.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Document.h"
#include "mozilla/layers/APZEventState.h"
#include "mozilla/layers/APZUtils.h"
#include "nsITimer.h"

static mozilla::LazyLogModule sApzAemLog("apz.activeelement");
#define AEM_LOG(...) MOZ_LOG(sApzAemLog, LogLevel::Debug, (__VA_ARGS__))

namespace mozilla {
namespace layers {

class DelayedClearElementActivation final : public nsITimerCallback,
                                            public nsINamed {
 private:
  explicit DelayedClearElementActivation(RefPtr<dom::Element>& aTarget,
                                         const nsCOMPtr<nsITimer>& aTimer)
      : mTarget(aTarget)
        // Hold the reference count until we are called back.
        ,
        mTimer(aTimer),
        mProcessedSingleTap(false) {}

 public:
  NS_DECL_ISUPPORTS

  static RefPtr<DelayedClearElementActivation> Create(
      RefPtr<dom::Element>& aTarget);

  NS_IMETHOD Notify(nsITimer*) override;

  NS_IMETHOD GetName(nsACString& aName) override;

  void MarkSingleTapProcessed();

  bool ProcessedSingleTap() const { return mProcessedSingleTap; }

  void StartTimer();

  /**
   * Clear the Event State Manager's global active content.
   */
  void ClearGlobalActiveContent();

  void ClearTimer() {
    if (mTimer) {
      mTimer->Cancel();
      mTimer = nullptr;
    }
  }
  dom::Element* GetTarget() const { return mTarget; }

 private:
  ~DelayedClearElementActivation() = default;

  RefPtr<dom::Element> mTarget;
  nsCOMPtr<nsITimer> mTimer;
  bool mProcessedSingleTap;
};

static nsPresContext* GetPresContextFor(nsIContent* aContent) {
  if (!aContent) {
    return nullptr;
  }
  PresShell* presShell = aContent->OwnerDoc()->GetPresShell();
  if (!presShell) {
    return nullptr;
  }
  return presShell->GetPresContext();
}

RefPtr<DelayedClearElementActivation> DelayedClearElementActivation::Create(
    RefPtr<dom::Element>& aTarget) {
  nsCOMPtr<nsITimer> timer = NS_NewTimer();
  if (!timer) {
    return nullptr;
  }
  RefPtr<DelayedClearElementActivation> event =
      new DelayedClearElementActivation(aTarget, timer);
  return event;
}

NS_IMETHODIMP DelayedClearElementActivation::Notify(nsITimer*) {
  AEM_LOG("DelayedClearElementActivation notification ready=%d",
          mProcessedSingleTap);
  // If the single tap has been processed and the timer has expired,
  // clear the active element state.
  if (mProcessedSingleTap) {
    AEM_LOG("DelayedClearElementActivation clearing active content\n");
    ClearGlobalActiveContent();
  }
  mTimer = nullptr;
  return NS_OK;
}

NS_IMETHODIMP DelayedClearElementActivation::GetName(nsACString& aName) {
  aName.AssignLiteral("DelayedClearElementActivation");
  return NS_OK;
}

void DelayedClearElementActivation::StartTimer() {
  MOZ_ASSERT(mTimer);
  // If the timer is null, active content state has already been cleared.
  if (!mTimer) {
    return;
  }
  nsresult rv = mTimer->InitWithCallback(
      this, StaticPrefs::ui_touch_activation_duration_ms(),
      nsITimer::TYPE_ONE_SHOT);
  if (NS_FAILED(rv)) {
    ClearTimer();
  }
}

void DelayedClearElementActivation::MarkSingleTapProcessed() {
  mProcessedSingleTap = true;
  if (!mTimer) {
    AEM_LOG("Clear activation immediate!");
    ClearGlobalActiveContent();
  }
}

void DelayedClearElementActivation::ClearGlobalActiveContent() {
  if (nsPresContext* pc = GetPresContextFor(mTarget)) {
    EventStateManager::ClearGlobalActiveContent(pc->EventStateManager());
  }
  mTarget = nullptr;
}

NS_IMPL_ISUPPORTS(DelayedClearElementActivation, nsITimerCallback, nsINamed)

ActiveElementManager::ActiveElementManager()
    : mCanBePanOrZoom(false),
      mCanBePanOrZoomSet(false),
      mSingleTapBeforeActivation(false),
      mSingleTapState(apz::SingleTapState::NotClick),
      mSetActiveTask(nullptr) {}

ActiveElementManager::~ActiveElementManager() = default;

void ActiveElementManager::SetTargetElement(dom::EventTarget* aTarget) {
  if (mTarget) {
    // Multiple fingers on screen (since HandleTouchEnd clears mTarget).
    AEM_LOG("Multiple fingers on-screen, clearing target element\n");
    CancelTask();
    ResetActive();
    ResetTouchBlockState();
    return;
  }

  mTarget = dom::Element::FromEventTargetOrNull(aTarget);
  AEM_LOG("Setting target element to %p\n", mTarget.get());
  TriggerElementActivation();
}

void ActiveElementManager::HandleTouchStart(bool aCanBePanOrZoom) {
  AEM_LOG("Touch start, aCanBePanOrZoom: %d\n", aCanBePanOrZoom);
  if (mCanBePanOrZoomSet) {
    // Multiple fingers on screen (since HandleTouchEnd clears mCanBePanSet).
    AEM_LOG("Multiple fingers on-screen, clearing touch block state\n");
    CancelTask();
    ResetActive();
    ResetTouchBlockState();
    return;
  }

  mCanBePanOrZoom = aCanBePanOrZoom;
  mCanBePanOrZoomSet = true;
  TriggerElementActivation();
}

void ActiveElementManager::TriggerElementActivation() {
  // Reset mSingleTapState here either when HandleTouchStart() or
  // SetTargetElement() gets called.
  // NOTE: It's possible that ProcessSingleTap() gets called in between
  // HandleTouchStart() and SetTargetElement() calls. I.e.,
  // mSingleTapBeforeActivation is true, in such cases it doesn't matter that
  // mSingleTapState was reset once and referred it in ProcessSingleTap() and
  // then reset here again because in ProcessSingleTap() `NotYetDetermined` is
  // the only one state we need to care, and it should NOT happen in the
  // scenario. In other words the case where we need to care `NotYetDetermined`
  // is when ProcessSingleTap() gets called later than any other events and
  // notifications.
  mSingleTapState = apz::SingleTapState::NotClick;

  // Both HandleTouchStart() and SetTargetElement() call this. They can be
  // called in either order. One will set mCanBePanOrZoomSet, and the other,
  // mTarget. We want to actually trigger the activation once both are set.
  if (!(mTarget && mCanBePanOrZoomSet)) {
    return;
  }

  RefPtr<DelayedClearElementActivation> delayedEvent =
      DelayedClearElementActivation::Create(mTarget);
  if (mDelayedClearElementActivation) {
    mDelayedClearElementActivation->ClearTimer();
    mDelayedClearElementActivation->ClearGlobalActiveContent();
  }
  mDelayedClearElementActivation = delayedEvent;

  // If the touch cannot be a pan, make mTarget :active right away.
  // Otherwise, wait a bit to see if the user will pan or not.
  if (!mCanBePanOrZoom) {
    SetActive(mTarget);

    if (mDelayedClearElementActivation) {
      if (mSingleTapBeforeActivation) {
        mDelayedClearElementActivation->MarkSingleTapProcessed();
      }
      mDelayedClearElementActivation->StartTimer();
    }
  } else {
    CancelTask();  // this is only needed because of bug 1169802. Fixing that
                   // bug properly should make this unnecessary.
    MOZ_ASSERT(mSetActiveTask == nullptr);

    RefPtr<CancelableRunnable> task =
        NewCancelableRunnableMethod<nsCOMPtr<dom::Element>>(
            "layers::ActiveElementManager::SetActiveTask", this,
            &ActiveElementManager::SetActiveTask, mTarget);
    mSetActiveTask = task;
    NS_GetCurrentThread()->DelayedDispatch(
        task.forget(), StaticPrefs::ui_touch_activation_delay_ms());
    AEM_LOG("Scheduling mSetActiveTask %p\n", mSetActiveTask.get());
  }
  AEM_LOG(
      "Got both touch-end event and end touch notiication, clearing pan "
      "state\n");
  mCanBePanOrZoomSet = false;
}

void ActiveElementManager::ClearActivation() {
  AEM_LOG("Clearing element activation\n");
  CancelTask();
  ResetActive();
}

bool ActiveElementManager::HandleTouchEndEvent(apz::SingleTapState aState) {
  AEM_LOG("Touch end event, state: %hhu\n", static_cast<uint8_t>(aState));

  mTouchEndState += TouchEndState::GotTouchEndEvent;
  return MaybeChangeActiveState(aState);
}

bool ActiveElementManager::HandleTouchEnd(apz::SingleTapState aState) {
  AEM_LOG("Touch end\n");

  mTouchEndState += TouchEndState::GotTouchEndNotification;
  return MaybeChangeActiveState(aState);
}

bool ActiveElementManager::MaybeChangeActiveState(apz::SingleTapState aState) {
  if (mTouchEndState !=
      TouchEndStates(TouchEndState::GotTouchEndEvent,
                     TouchEndState::GotTouchEndNotification)) {
    return false;
  }

  CancelTask();

  mSingleTapState = aState;

  if (aState == apz::SingleTapState::WasClick) {
    // Scrollbar thumbs use a different mechanism for their active
    // highlight (the "active" attribute), so don't set the active state
    // on them because nothing will clear it.
    if (mCanBePanOrZoom &&
        !(mTarget && mTarget->IsXULElement(nsGkAtoms::thumb))) {
      SetActive(mTarget);
    }
  } else {
    // We might reach here if mCanBePanOrZoom was false on touch-start and
    // so we set the element active right away. Now it turns out the
    // action was not a click so we need to reset the active element.
    ResetActive();
  }

  ResetTouchBlockState();
  return true;
}

void ActiveElementManager::ProcessSingleTap() {
  if (!mDelayedClearElementActivation) {
    // We have not received touch-start notification yet. We will have to run
    // MarkSingleTapProcessed() when we receive the touch-start notification.
    mSingleTapBeforeActivation = true;
    return;
  }

  if (mSingleTapState == apz::SingleTapState::NotYetDetermined) {
    // If we got `NotYetDetermined`, which means at the moment we don't know for
    // sure whether double-tapping will be incoming or not, but now we are sure
    // that no double-tapping will happen, thus it's time to activate the target
    // element.
    if (auto* target = mDelayedClearElementActivation->GetTarget()) {
      SetActive(target);
    }
  }
  mDelayedClearElementActivation->MarkSingleTapProcessed();

  if (mCanBePanOrZoom) {
    // In the case that we have not started the delayed reset of the element
    // activation state, start the timer now.
    mDelayedClearElementActivation->StartTimer();
  }

  // We don't need to keep a reference to the element activation
  // clearing, because the event and its timer keep each other alive
  // until the timer expires
  mDelayedClearElementActivation = nullptr;
}

void ActiveElementManager::Destroy() {
  if (mDelayedClearElementActivation) {
    mDelayedClearElementActivation->ClearTimer();
    mDelayedClearElementActivation = nullptr;
  }
}

void ActiveElementManager::SetActive(dom::Element* aTarget) {
  AEM_LOG("Setting active %p\n", aTarget);

  if (nsPresContext* pc = GetPresContextFor(aTarget)) {
    pc->EventStateManager()->SetContentState(aTarget,
                                             dom::ElementState::ACTIVE);
  }
}

void ActiveElementManager::ResetActive() {
  AEM_LOG("Resetting active from %p\n", mTarget.get());

  // Clear the :active flag from mTarget by setting it on the document root.
  if (mTarget) {
    dom::Element* root = mTarget->OwnerDoc()->GetDocumentElement();
    if (root) {
      AEM_LOG("Found root %p, making active\n", root);
      SetActive(root);
    }
  }
}

void ActiveElementManager::ResetTouchBlockState() {
  mTarget = nullptr;
  mCanBePanOrZoomSet = false;
  mTouchEndState.clear();
  mSingleTapBeforeActivation = false;
  // NOTE: Do not reset mSingleTapState here since it will be necessary in
  // ProcessSingleTap() to tell whether we need to activate the target element
  // because on environments where double-tap is enabled ProcessSingleTap()
  // gets called after both of touch-end event and end touch notiication
  // arrived.
}

void ActiveElementManager::SetActiveTask(
    const nsCOMPtr<dom::Element>& aTarget) {
  AEM_LOG("mSetActiveTask %p running\n", mSetActiveTask.get());

  // This gets called from mSetActiveTask's Run() method. The message loop
  // deletes the task right after running it, so we need to null out
  // mSetActiveTask to make sure we're not left with a dangling pointer.
  mSetActiveTask = nullptr;
  SetActive(aTarget);
}

void ActiveElementManager::CancelTask() {
  AEM_LOG("Cancelling task %p\n", mSetActiveTask.get());

  if (mSetActiveTask) {
    mSetActiveTask->Cancel();
    mSetActiveTask = nullptr;
  }
}

}  // namespace layers
}  // namespace mozilla