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/. */
7 #ifndef AccessibleCaretManager_h
8 #define AccessibleCaretManager_h
10 #include "AccessibleCaret.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/dom/CaretStateChangedEvent.h"
14 #include "mozilla/dom/MouseEventBinding.h"
15 #include "mozilla/EnumSet.h"
16 #include "mozilla/EventForwards.h"
17 #include "mozilla/RefPtr.h"
18 #include "mozilla/UniquePtr.h"
22 #include "nsISelectionListener.h"
24 class nsFrameSelection
;
36 // -----------------------------------------------------------------------------
37 // AccessibleCaretManager does not deal with events or callbacks directly. It
38 // relies on AccessibleCaretEventHub to call its public methods to do the work.
39 // All codes needed to interact with PresShell, Selection, and AccessibleCaret
40 // should be written in AccessibleCaretManager.
42 // None the public methods in AccessibleCaretManager will flush layout or style
43 // prior to performing its task. The caller must ensure the layout is up to
45 // TODO: it's unclear, whether that's true. `OnSelectionChanged` calls
46 // `UpdateCarets`, which may flush layout.
48 // Please see the wiki page for more information.
49 // https://wiki.mozilla.org/AccessibleCaret
51 class AccessibleCaretManager
{
53 // @param aPresShell may be nullptr for testing.
54 explicit AccessibleCaretManager(PresShell
* aPresShell
);
55 virtual ~AccessibleCaretManager() = default;
57 // Called by AccessibleCaretEventHub to inform us that PresShell is destroyed.
60 // The aPoint in the following public methods should be relative to root
63 // Press caret on the given point. Return NS_OK if the point is actually on
66 virtual nsresult
PressCaret(const nsPoint
& aPoint
, EventClassID aEventClass
);
68 // Drag caret to the given point. It's required to call PressCaret()
71 virtual nsresult
DragCaret(const nsPoint
& aPoint
);
73 // Release caret from he previous press action. It's required to call
74 // PressCaret() beforehand.
76 virtual nsresult
ReleaseCaret();
78 // A quick single tap on caret on given point without dragging.
80 virtual nsresult
TapCaret(const nsPoint
& aPoint
);
82 // Select a word or bring up paste shortcut (if Gaia is listening) under the
85 virtual nsresult
SelectWordOrShortcut(const nsPoint
& aPoint
);
87 // Handle scroll-start event.
89 virtual void OnScrollStart();
91 // Handle scroll-end event.
93 virtual void OnScrollEnd();
95 // Handle ScrollPositionChanged from nsIScrollObserver. This might be called
96 // at anytime, not necessary between OnScrollStart and OnScrollEnd.
98 virtual void OnScrollPositionChanged();
100 // Handle reflow event from nsIReflowObserver.
102 virtual void OnReflow();
104 // Handle blur event from nsFocusManager.
106 virtual void OnBlur();
108 // Handle NotifySelectionChanged event from nsISelectionListener.
109 // @param aReason potentially multiple of the reasons defined in
110 // nsISelectionListener.idl.
112 virtual nsresult
OnSelectionChanged(dom::Document
* aDoc
, dom::Selection
* aSel
,
116 virtual void OnKeyboardEvent();
118 // Update the manager with the last input source that was observed. This
119 // is used in part to determine if the carets should be shown or hidden.
120 void SetLastInputSource(uint16_t aInputSource
);
122 // Returns True indicating that we should disable APZ to avoid jumpy carets.
123 bool ShouldDisableApz() const;
128 // @param aPresShell may be nullptr for testing.
129 AccessibleCaretManager(PresShell
* aPresShell
, Carets aCarets
);
131 // This enum representing the number of AccessibleCarets on the screen.
132 enum class CaretMode
: uint8_t {
133 // No caret on the screen.
136 // One caret, i.e. the selection is collapsed.
139 // Two carets, i.e. the selection is not collapsed.
143 friend std::ostream
& operator<<(std::ostream
& aStream
,
144 const CaretMode
& aCaretMode
);
146 enum class UpdateCaretsHint
: uint8_t {
147 // Update everything including appearance and position.
150 // Update everything while respecting the old appearance. For example, if
151 // the caret in cursor mode is hidden due to blur, do not change its
152 // appearance to Normal.
153 RespectOldAppearance
,
155 // No CaretStateChangedEvent will be dispatched in the end of
160 using UpdateCaretsHintSet
= mozilla::EnumSet
<UpdateCaretsHint
>;
162 friend std::ostream
& operator<<(std::ostream
& aStream
,
163 const UpdateCaretsHint
& aResult
);
165 enum class Terminated
: bool { No
, Yes
};
167 // This method could kill the shell, so callers to methods that call
168 // MaybeFlushLayout should ensure the event hub that owns us is still alive.
170 // See the mRefCnt assertions in AccessibleCaretEventHub.
172 [[nodiscard
]] MOZ_CAN_RUN_SCRIPT
virtual Terminated
MaybeFlushLayout();
174 // Update carets based on current selection status. This function will flush
175 // layout, so caller must ensure the PresShell is still valid after calling
179 const UpdateCaretsHintSet
& aHints
= UpdateCaretsHint::Default
);
181 // Force hiding all carets regardless of the current selection status, and
182 // dispatch CaretStateChangedEvent if one of the carets is logically-visible.
184 void HideCaretsAndDispatchCaretStateChangedEvent();
187 void UpdateCaretsForCursorMode(const UpdateCaretsHintSet
& aHints
);
190 void UpdateCaretsForSelectionMode(const UpdateCaretsHintSet
& aHints
);
192 // A helper function to update mShouldDisableApz.
193 void UpdateShouldDisableApz();
195 // Provide haptic / touch feedback, primarily for select on longpress.
196 void ProvideHapticFeedback();
198 // Get the nearest enclosing focusable frame of aFrame.
199 // @return focusable frame if there is any; nullptr otherwise.
200 nsIFrame
* GetFocusableFrame(nsIFrame
* aFrame
) const;
202 // Change focus to aFrame if it isn't nullptr. Otherwise, clear the old focus
203 // then re-focus the window.
204 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void ChangeFocusToOrClearOldFocus(
205 nsIFrame
* aFrame
) const;
208 nsresult
SelectWord(nsIFrame
* aFrame
, const nsPoint
& aPoint
) const;
209 MOZ_CAN_RUN_SCRIPT
void SetSelectionDragState(bool aState
) const;
211 // Return true if the candidate string is a phone number.
212 bool IsPhoneNumber(const nsAString
& aCandidate
) const;
214 // Extend the current selection forwards and backwards if it's already a
217 void SelectMoreIfPhoneNumber() const;
219 // Extend the current phone number selection in the requested direction.
221 void ExtendPhoneNumberSelection(const nsAString
& aDirection
) const;
223 void SetSelectionDirection(nsDirection aDir
) const;
225 // If aDirection is eDirNext, get the frame for the range start in the first
226 // range from the current selection, and return the offset into that frame as
227 // well as the range start content and the content offset. Otherwise, get the
228 // frame and the offset for the range end in the last range instead.
229 nsIFrame
* GetFrameForFirstRangeStartOrLastRangeEnd(
230 nsDirection aDirection
, int32_t* aOutOffset
,
231 nsIContent
** aOutContent
= nullptr,
232 int32_t* aOutContentOffset
= nullptr) const;
234 MOZ_CAN_RUN_SCRIPT nsresult
DragCaretInternal(const nsPoint
& aPoint
);
235 nsPoint
AdjustDragBoundary(const nsPoint
& aPoint
) const;
237 // Start the selection scroll timer if the caret is being dragged out of
240 void StartSelectionAutoScrollTimer(const nsPoint
& aPoint
) const;
241 void StopSelectionAutoScrollTimer() const;
243 void ClearMaintainedSelection() const;
245 static dom::Element
* GetEditingHostForFrame(const nsIFrame
* aFrame
);
246 dom::Selection
* GetSelection() const;
247 already_AddRefed
<nsFrameSelection
> GetFrameSelection() const;
250 nsAutoString
StringifiedSelection() const;
252 // Get the union of all the child frame scrollable overflow rects for aFrame,
253 // which is used as a helper function to restrict the area where the caret can
254 // be dragged. Returns the rect relative to aFrame.
255 static nsRect
GetAllChildFrameRectsUnion(nsIFrame
* aFrame
);
257 // Restrict the active caret's dragging position based on
258 // sCaretsAllowDraggingAcrossOtherCaret. If the active caret is the first
259 // caret, the `limit` will be the previous character of the second caret.
260 // Otherwise, the `limit` will be the next character of the first caret.
262 // @param aOffsets is the new position of the active caret, and it will be set
263 // to the `limit` when 1) sCaretsAllowDraggingAcrossOtherCaret is false and
264 // it's being dragged past the limit. 2) sCaretsAllowDraggingAcrossOtherCaret
265 // is true and the active caret's position is the same as the inactive's
267 // @return true if the aOffsets is suitable for changing the selection.
268 bool RestrictCaretDraggingOffsets(nsIFrame::ContentOffsets
& aOffsets
);
270 // ---------------------------------------------------------------------------
271 // The following functions are made virtual for stubbing or mocking in gtest.
273 // @return Yes if Terminate() had been called.
274 virtual Terminated
IsTerminated() const {
275 return mPresShell
? Terminated::No
: Terminated::Yes
;
278 // Get caret mode based on current selection.
279 virtual CaretMode
GetCaretMode() const;
281 // @return true if aStartFrame comes before aEndFrame.
282 virtual bool CompareTreePosition(nsIFrame
* aStartFrame
,
283 nsIFrame
* aEndFrame
) const;
285 // Check if the two carets is overlapping to become tilt.
286 // @return true if the two carets become tilt; false, otherwise.
287 virtual bool UpdateCaretsForOverlappingTilt();
289 // Make the two carets always tilt.
290 virtual void UpdateCaretsForAlwaysTilt(const nsIFrame
* aStartFrame
,
291 const nsIFrame
* aEndFrame
);
293 // Check whether AccessibleCaret is displayable in cursor mode or not.
294 // @param aOutFrame returns frame of the cursor if it's displayable.
295 // @param aOutOffset returns frame offset as well.
296 virtual bool IsCaretDisplayableInCursorMode(
297 nsIFrame
** aOutFrame
= nullptr, int32_t* aOutOffset
= nullptr) const;
299 virtual bool HasNonEmptyTextContent(nsINode
* aNode
) const;
301 // This function will flush layout, so caller must ensure the PresShell is
302 // still valid after calling this method.
303 // @param aPoint The event point when the user is pressing or dragging a
304 // caret, which is relative to the root frame.
306 virtual void DispatchCaretStateChangedEvent(dom::CaretChangedReason aReason
,
307 const nsPoint
* aPoint
= nullptr);
309 // ---------------------------------------------------------------------------
312 nscoord mOffsetYToCaretLogicalPosition
= NS_UNCONSTRAINEDSIZE
;
314 // AccessibleCaretEventHub owns us by a UniquePtr. When it's destroyed, we'll
315 // also be destroyed. No need to worry if we outlive mPresShell.
317 // mPresShell will be set to nullptr in Terminate(). Therefore mPresShell is
318 // nullptr either we are in gtest or PresShell::IsDestroying() is true.
319 PresShell
* MOZ_NON_OWNING_REF mPresShell
= nullptr;
323 Carets(UniquePtr
<AccessibleCaret
> aFirst
,
324 UniquePtr
<AccessibleCaret
> aSecond
);
326 Carets(Carets
&&) = default;
327 Carets(const Carets
&) = delete;
328 Carets
& operator=(const Carets
&) = delete;
330 AccessibleCaret
* GetFirst() const { return mFirst
.get(); }
332 AccessibleCaret
* GetSecond() const { return mSecond
.get(); }
334 bool HasLogicallyVisibleCaret() const {
335 return mFirst
->IsLogicallyVisible() || mSecond
->IsLogicallyVisible();
338 bool HasVisuallyVisibleCaret() const {
339 return mFirst
->IsVisuallyVisible() || mSecond
->IsVisuallyVisible();
348 // First caret is attached to nsCaret in cursor mode, and is attached to
349 // selection highlight as the left caret in selection mode.
350 UniquePtr
<AccessibleCaret
> mFirst
;
352 // Second caret is used solely in selection mode, and is attached to
353 // selection highlight as the right caret.
354 UniquePtr
<AccessibleCaret
> mSecond
;
359 // The caret being pressed or dragged.
360 AccessibleCaret
* mActiveCaret
= nullptr;
362 // The caret mode since last update carets.
363 CaretMode mLastUpdateCaretMode
= CaretMode::None
;
365 // The last input source that the event hub saw. We use this to decide whether
366 // or not show the carets when the selection is updated, as we want to hide
367 // the carets for mouse-triggered selection changes but show them for other
368 // input types such as touch.
369 uint16_t mLastInputSource
= dom::MouseEvent_Binding::MOZ_SOURCE_UNKNOWN
;
371 // Set to true in OnScrollStart() and set to false in OnScrollEnd().
372 bool mIsScrollStarted
= false;
374 class LayoutFlusher final
{
376 LayoutFlusher() = default;
380 LayoutFlusher(const LayoutFlusher
&) = delete;
381 LayoutFlusher
& operator=(const LayoutFlusher
&) = delete;
383 MOZ_CAN_RUN_SCRIPT
void MaybeFlush(const PresShell
& aPresShell
);
385 // Set to false to disallow flushing layout in some callbacks such as
386 // OnReflow(), OnScrollStart(), OnScrollStart(), or
387 // OnScrollPositionChanged().
388 bool mAllowFlushing
= true;
391 // Whether we're flushing layout, used for sanity-checking.
392 bool mFlushing
= false;
395 LayoutFlusher mLayoutFlusher
;
397 // Set to True if one of the caret's position is changed in last update.
398 bool mIsCaretPositionChanged
= false;
400 class DesiredAsyncPanZoomState final
{
402 void Update(const AccessibleCaretManager
& aAccessibleCaretManager
);
404 enum class Value
: bool { Disabled
, Enabled
};
406 Value
Get() const { return mValue
; }
409 Value mValue
= Value::Enabled
;
412 DesiredAsyncPanZoomState mDesiredAsyncPanZoomState
;
414 static const int32_t kAutoScrollTimerDelay
= 30;
416 // Clicking on the boundary of input or textarea will move the caret to the
417 // front or end of the content. To avoid this, we need to deflate the content
418 // boundary by 61 app units, which is 1 pixel + 1 app unit as defined in
420 static const int32_t kBoundaryAppUnits
= 61;
422 enum ScriptUpdateMode
: int32_t {
423 // By default, always hide carets for selection changes due to JS calls.
425 // Update any visible carets for selection changes due to JS calls,
426 // but don't show carets if carets are hidden.
427 kScriptUpdateVisible
,
428 // Always show carets for selection changes due to JS calls.
433 std::ostream
& operator<<(std::ostream
& aStream
,
434 const AccessibleCaretManager::CaretMode
& aCaretMode
);
436 std::ostream
& operator<<(
437 std::ostream
& aStream
,
438 const AccessibleCaretManager::UpdateCaretsHint
& aResult
);
440 } // namespace mozilla
442 #endif // AccessibleCaretManager_h