Source code

Revision control

Other Tools

/* -*- 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/. */
/*
* Implementation of nsFrameSelection
*/
#include "nsFrameSelection.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/EventStates.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/Logging.h"
#include "mozilla/PresShell.h"
#include "mozilla/ScrollTypes.h"
#include "mozilla/StaticAnalysisFunctions.h"
#include "mozilla/StaticPrefs_bidi.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/Unused.h"
#include "nsCOMPtr.h"
#include "nsDebug.h"
#include "nsString.h"
#include "nsISelectionListener.h"
#include "nsContentCID.h"
#include "nsDeviceContext.h"
#include "nsIContent.h"
#include "nsRange.h"
#include "nsITableCellLayout.h"
#include "nsTArray.h"
#include "nsTableWrapperFrame.h"
#include "nsTableCellFrame.h"
#include "nsIScrollableFrame.h"
#include "nsCCUncollectableMarker.h"
#include "nsTextFragment.h"
#include <algorithm>
#include "nsContentUtils.h"
#include "nsCSSFrameConstructor.h"
#include "nsGkAtoms.h"
#include "nsIFrameTraversal.h"
#include "nsLayoutUtils.h"
#include "nsLayoutCID.h"
#include "nsBidiPresUtils.h"
static NS_DEFINE_CID(kFrameTraversalCID, NS_FRAMETRAVERSAL_CID);
#include "nsTextFrame.h"
#include "nsThreadUtils.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "nsPresContext.h"
#include "nsCaret.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/TextEvents.h"
// notifications
#include "mozilla/dom/Document.h"
#include "nsISelectionController.h" //for the enums
#include "nsCopySupport.h"
#include "nsIClipboard.h"
#include "nsIFrameInlines.h"
#include "nsError.h"
#include "mozilla/AutoCopyListener.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/StaticRange.h"
#include "mozilla/dom/Text.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/SelectionBinding.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Telemetry.h"
#include "mozilla/layers/ScrollInputMethods.h"
#include "nsFocusManager.h"
#include "nsPIDOMWindow.h"
using namespace mozilla;
using namespace mozilla::dom;
using mozilla::layers::ScrollInputMethod;
static LazyLogModule sFrameSelectionLog("FrameSelection");
//#define DEBUG_TABLE 1
/**
* Add cells to the selection inside of the given cells range.
*
* @param aTable [in] HTML table element
* @param aStartRowIndex [in] row index where the cells range starts
* @param aStartColumnIndex [in] column index where the cells range starts
* @param aEndRowIndex [in] row index where the cells range ends
* @param aEndColumnIndex [in] column index where the cells range ends
*/
static nsresult AddCellsToSelection(const nsIContent* aTableContent,
int32_t aStartRowIndex,
int32_t aStartColumnIndex,
int32_t aEndRowIndex,
int32_t aEndColumnIndex,
Selection& aNormalSelection);
static nsAtom* GetTag(nsINode* aNode);
static nsINode* GetClosestInclusiveTableCellAncestor(nsINode* aDomNode);
MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult CreateAndAddRange(
nsINode* aContainer, int32_t aOffset, Selection& aNormalSelection);
static nsresult SelectCellElement(nsIContent* aCellElement,
Selection& aNormalSelection);
#ifdef XP_MACOSX
static nsresult UpdateSelectionCacheOnRepaintSelection(Selection* aSel);
#endif // XP_MACOSX
#ifdef PRINT_RANGE
static void printRange(nsRange* aDomRange);
# define DEBUG_OUT_RANGE(x) printRange(x)
#else
# define DEBUG_OUT_RANGE(x)
#endif // PRINT_RANGE
/******************************************************************************
* nsPeekOffsetStruct
******************************************************************************/
//#define DEBUG_SELECTION // uncomment for printf describing every collapse and
// extend. #define DEBUG_NAVIGATION
//#define DEBUG_TABLE_SELECTION 1
nsPeekOffsetStruct::nsPeekOffsetStruct(
nsSelectionAmount aAmount, nsDirection aDirection, int32_t aStartOffset,
nsPoint aDesiredCaretPos, bool aJumpLines, bool aScrollViewStop,
bool aIsKeyboardSelect, bool aVisual, bool aExtend,
ForceEditableRegion aForceEditableRegion,
EWordMovementType aWordMovementType, bool aTrimSpaces)
: mAmount(aAmount),
mDirection(aDirection),
mStartOffset(aStartOffset),
mDesiredCaretPos(aDesiredCaretPos),
mWordMovementType(aWordMovementType),
mJumpLines(aJumpLines),
mTrimSpaces(aTrimSpaces),
mScrollViewStop(aScrollViewStop),
mIsKeyboardSelect(aIsKeyboardSelect),
mVisual(aVisual),
mExtend(aExtend),
mForceEditableRegion(aForceEditableRegion == ForceEditableRegion::Yes),
mResultContent(),
mResultFrame(nullptr),
mContentOffset(0),
mAttach(CARET_ASSOCIATE_BEFORE) {}
// Array which contains index of each SelecionType in Selection::mDOMSelections.
// For avoiding using if nor switch to retrieve the index, this needs to have
// -1 for SelectionTypes which won't be created its Selection instance.
static const int8_t kIndexOfSelections[] = {
-1, // SelectionType::eInvalid
-1, // SelectionType::eNone
0, // SelectionType::eNormal
1, // SelectionType::eSpellCheck
2, // SelectionType::eIMERawClause
3, // SelectionType::eIMESelectedRawClause
4, // SelectionType::eIMEConvertedClause
5, // SelectionType::eIMESelectedClause
6, // SelectionType::eAccessibility
7, // SelectionType::eFind
8, // SelectionType::eURLSecondary
9, // SelectionType::eURLStrikeout
};
inline int8_t GetIndexFromSelectionType(SelectionType aSelectionType) {
// The enum value of eInvalid is -1 and the others are sequential value
// starting from 0. Therefore, |SelectionType + 1| is the index of
// kIndexOfSelections.
return kIndexOfSelections[static_cast<int8_t>(aSelectionType) + 1];
}
/*
The limiter is used specifically for the text areas and textfields
In that case it is the DIV tag that is anonymously created for the text
areas/fields. Text nodes and BR nodes fall beneath it. In the case of a
BR node the limiter will be the parent and the offset will point before or
after the BR node. In the case of the text node the parent content is
the text node itself and the offset will be the exact character position.
The offset is not important to check for validity. Simply look at the
passed in content. If it equals the limiter then the selection point is valid.
If its parent it the limiter then the point is also valid. In the case of
NO limiter all points are valid since you are in a topmost iframe. (browser
or composer)
*/
bool nsFrameSelection::IsValidSelectionPoint(nsINode* aNode) const {
if (!aNode) {
return false;
}
nsIContent* limiter = GetLimiter();
if (limiter && limiter != aNode && limiter != aNode->GetParent()) {
// if newfocus == the limiter. that's ok. but if not there and not parent
// bad
return false; // not in the right content. tLimiter said so
}
limiter = GetAncestorLimiter();
return !limiter || aNode->IsInclusiveDescendantOf(limiter);
}
namespace mozilla {
struct MOZ_RAII AutoPrepareFocusRange {
AutoPrepareFocusRange(Selection* aSelection,
const bool aMultiRangeSelection) {
MOZ_ASSERT(aSelection);
MOZ_ASSERT(aSelection->GetType() == SelectionType::eNormal);
if (aSelection->mStyledRanges.mRanges.Length() <= 1) {
return;
}
if (aSelection->mFrameSelection->IsUserSelectionReason()) {
mUserSelect.emplace(aSelection);
}
nsTArray<StyledRange>& ranges = aSelection->mStyledRanges.mRanges;
if (!aSelection->mUserInitiated || aMultiRangeSelection) {
// Scripted command or the user is starting a new explicit multi-range
// selection.
for (StyledRange& entry : ranges) {
entry.mRange->SetIsGenerated(false);
}
return;
}
if (!IsAnchorRelativeOperation(
aSelection->mFrameSelection->mSelectionChangeReasons)) {
return;
}
// This operation is against the anchor but our current mAnchorFocusRange
// represents the focus in a multi-range selection. The anchor from a user
// perspective is the most distant generated range on the opposite side.
// Find that range and make it the mAnchorFocusRange.
nsRange* const newAnchorFocusRange =
FindGeneratedRangeMostDistantFromAnchor(*aSelection);
if (!newAnchorFocusRange) {
// There are no generated ranges - that's fine.
return;
}
// Setup the new mAnchorFocusRange and mark the old one as generated.
if (aSelection->mAnchorFocusRange) {
aSelection->mAnchorFocusRange->SetIsGenerated(true);
}
newAnchorFocusRange->SetIsGenerated(false);
aSelection->mAnchorFocusRange = newAnchorFocusRange;
RemoveGeneratedRanges(*aSelection);
if (aSelection->mFrameSelection) {
aSelection->mFrameSelection->InvalidateDesiredCaretPos();
}
}
private:
static nsRange* FindGeneratedRangeMostDistantFromAnchor(
const Selection& aSelection) {
const nsTArray<StyledRange>& ranges = aSelection.mStyledRanges.mRanges;
const size_t len = ranges.Length();
nsRange* result{nullptr};
if (aSelection.GetDirection() == eDirNext) {
for (size_t i = 0; i < len; ++i) {
if (ranges[i].mRange->IsGenerated()) {
result = ranges[i].mRange;
break;
}
}
} else {
size_t i = len;
while (i--) {
if (ranges[i].mRange->IsGenerated()) {
result = ranges[i].mRange;
break;
}
}
}
return result;
}
static void RemoveGeneratedRanges(Selection& aSelection) {
RefPtr<nsPresContext> presContext = aSelection.GetPresContext();
nsTArray<StyledRange>& ranges = aSelection.mStyledRanges.mRanges;
size_t i = ranges.Length();
while (i--) {
nsRange* range = ranges[i].mRange;
if (range->IsGenerated()) {
range->UnregisterSelection();
aSelection.SelectFrames(presContext, range, false);
ranges.RemoveElementAt(i);
}
}
}
/**
* @aParam aSelectionChangeReasons can be multiple of the reasons defined in
nsISelectionListener.idl.
*/
static bool IsAnchorRelativeOperation(const int16_t aSelectionChangeReasons) {
return aSelectionChangeReasons &
(nsISelectionListener::DRAG_REASON |
nsISelectionListener::MOUSEDOWN_REASON |
nsISelectionListener::MOUSEUP_REASON |
nsISelectionListener::COLLAPSETOSTART_REASON);
}
Maybe<Selection::AutoUserInitiated> mUserSelect;
};
} // namespace mozilla
////////////BEGIN nsFrameSelection methods
template Result<RefPtr<nsRange>, nsresult>
nsFrameSelection::CreateRangeExtendedToSomewhere(
nsDirection aDirection, const nsSelectionAmount aAmount,
CaretMovementStyle aMovementStyle);
template Result<RefPtr<StaticRange>, nsresult>
nsFrameSelection::CreateRangeExtendedToSomewhere(
nsDirection aDirection, const nsSelectionAmount aAmount,
CaretMovementStyle aMovementStyle);
nsFrameSelection::nsFrameSelection(PresShell* aPresShell, nsIContent* aLimiter,
const bool aAccessibleCaretEnabled) {
for (size_t i = 0; i < ArrayLength(mDomSelections); i++) {
mDomSelections[i] = new Selection(kPresentSelectionTypes[i], this);
}
#ifdef XP_MACOSX
// On macOS, cache the current selection to send to service menu of macOS.
bool enableAutoCopy = true;
AutoCopyListener::Init(nsIClipboard::kSelectionCache);
#else // #ifdef XP_MACOSX
// Check to see if the auto-copy pref is enabled and make the normal
// Selection notifies auto-copy listener of its changes.
bool enableAutoCopy = AutoCopyListener::IsPrefEnabled();
if (enableAutoCopy) {
AutoCopyListener::Init(nsIClipboard::kSelectionClipboard);
}
#endif // #ifdef XP_MACOSX #else
if (enableAutoCopy) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (mDomSelections[index]) {
mDomSelections[index]->NotifyAutoCopy();
}
}
mPresShell = aPresShell;
mDragState = false;
mLimiters.mLimiter = aLimiter;
// This should only ever be initialized on the main thread, so we are OK here.
MOZ_ASSERT(NS_IsMainThread());
mAccessibleCaretEnabled = aAccessibleCaretEnabled;
if (mAccessibleCaretEnabled) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
mDomSelections[index]->MaybeNotifyAccessibleCaretEventHub(aPresShell);
}
bool plaintextControl = (aLimiter != nullptr);
bool initSelectEvents =
plaintextControl ? StaticPrefs::dom_select_events_textcontrols_enabled()
: StaticPrefs::dom_select_events_enabled();
Document* doc = aPresShell->GetDocument();
if (initSelectEvents || (doc && doc->NodePrincipal()->IsSystemPrincipal())) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (mDomSelections[index]) {
mDomSelections[index]->EnableSelectionChangeEvent();
}
}
}
nsFrameSelection::~nsFrameSelection() = default;
NS_IMPL_CYCLE_COLLECTION_CLASS(nsFrameSelection)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsFrameSelection)
for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) {
tmp->mDomSelections[i] = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(
mTableSelection.mClosestInclusiveTableCellAncestor)
tmp->mTableSelection.mMode = TableSelectionMode::None;
tmp->mTableSelection.mDragSelectingCells = false;
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTableSelection.mStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTableSelection.mEndSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTableSelection.mAppendStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTableSelection.mUnselectCellOnMouseUp)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMaintainedRange.mRange)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLimiters.mLimiter)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLimiters.mAncestorLimiter)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsFrameSelection)
if (tmp->mPresShell && tmp->mPresShell->GetDocument() &&
nsCCUncollectableMarker::InGeneration(
cb, tmp->mPresShell->GetDocument()->GetMarkedCCGeneration())) {
return NS_SUCCESS_INTERRUPTED_TRAVERSE;
}
for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDomSelections[i])
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(
mTableSelection.mClosestInclusiveTableCellAncestor)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTableSelection.mStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTableSelection.mEndSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTableSelection.mAppendStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTableSelection.mUnselectCellOnMouseUp)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMaintainedRange.mRange)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLimiters.mLimiter)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLimiters.mAncestorLimiter)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(nsFrameSelection, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(nsFrameSelection, Release)
bool nsFrameSelection::Caret::IsVisualMovement(
bool aContinueSelection, CaretMovementStyle aMovementStyle) const {
int32_t movementFlag = StaticPrefs::bidi_edit_caret_movement_style();
return aMovementStyle == eVisual ||
(aMovementStyle == eUsePrefStyle &&
(movementFlag == 1 || (movementFlag == 2 && !aContinueSelection)));
}
// Get the x (or y, in vertical writing mode) position requested
// by the Key Handling for line-up/down
nsresult nsFrameSelection::DesiredCaretPos::FetchPos(
nsPoint& aDesiredCaretPos, const PresShell& aPresShell,
Selection& aNormalSelection) const {
MOZ_ASSERT(aNormalSelection.GetType() == SelectionType::eNormal);
if (mIsSet) {
aDesiredCaretPos = mValue;
return NS_OK;
}
RefPtr<nsCaret> caret = aPresShell.GetCaret();
if (!caret) {
return NS_ERROR_NULL_POINTER;
}
caret->SetSelection(&aNormalSelection);
nsRect coord;
nsIFrame* caretFrame = caret->GetGeometry(&coord);
if (!caretFrame) {
return NS_ERROR_FAILURE;
}
nsPoint viewOffset(0, 0);
nsView* view = nullptr;
caretFrame->GetOffsetFromView(viewOffset, &view);
if (view) {
coord += viewOffset;
}
aDesiredCaretPos = coord.TopLeft();
return NS_OK;
}
void nsFrameSelection::InvalidateDesiredCaretPos() // do not listen to
// mDesiredCaretPos.mValue;
// you must get another.
{
mDesiredCaretPos.Invalidate();
}
void nsFrameSelection::DesiredCaretPos::Invalidate() { mIsSet = false; }
void nsFrameSelection::DesiredCaretPos::Set(const nsPoint& aPos) {
mValue = aPos;
mIsSet = true;
}
nsresult nsFrameSelection::ConstrainFrameAndPointToAnchorSubtree(
nsIFrame* aFrame, const nsPoint& aPoint, nsIFrame** aRetFrame,
nsPoint& aRetPoint) const {
//
// The whole point of this method is to return a frame and point that
// that lie within the same valid subtree as the anchor node's frame,
// for use with the method GetContentAndOffsetsFromPoint().
//
// A valid subtree is defined to be one where all the content nodes in
// the tree have a valid parent-child relationship.
//
// If the anchor frame and aFrame are in the same subtree, aFrame will
// be returned in aRetFrame. If they are in different subtrees, we
// return the frame for the root of the subtree.
//
if (!aFrame || !aRetFrame) {
return NS_ERROR_NULL_POINTER;
}
*aRetFrame = aFrame;
aRetPoint = aPoint;
//
// Get the frame and content for the selection's anchor point!
//
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) {
return NS_ERROR_NULL_POINTER;
}
nsCOMPtr<nsIContent> anchorContent =
do_QueryInterface(mDomSelections[index]->GetAnchorNode());
if (!anchorContent) {
return NS_ERROR_FAILURE;
}
//
// Now find the root of the subtree containing the anchor's content.
//
NS_ENSURE_STATE(mPresShell);
RefPtr<PresShell> presShell = mPresShell;
nsIContent* anchorRoot = anchorContent->GetSelectionRootContent(presShell);
NS_ENSURE_TRUE(anchorRoot, NS_ERROR_UNEXPECTED);
//
// Now find the root of the subtree containing aFrame's content.
//
nsCOMPtr<nsIContent> content = aFrame->GetContent();
if (content) {
nsIContent* contentRoot = content->GetSelectionRootContent(presShell);
NS_ENSURE_TRUE(contentRoot, NS_ERROR_UNEXPECTED);
if (anchorRoot == contentRoot) {
// If the aFrame's content isn't the capturing content, it should be
// a descendant. At this time, we can return simply.
nsIContent* capturedContent = PresShell::GetCapturingContent();
if (capturedContent != content) {
return NS_OK;
}
// Find the frame under the mouse cursor with the root frame.
// At this time, don't use the anchor's frame because it may not have
// fixed positioned frames.
nsIFrame* rootFrame = presShell->GetRootFrame();
nsPoint ptInRoot = aPoint + aFrame->GetOffsetTo(rootFrame);
nsIFrame* cursorFrame =
nsLayoutUtils::GetFrameForPoint(RelativeTo{rootFrame}, ptInRoot);
// If the mouse cursor in on a frame which is descendant of same
// selection root, we can expand the selection to the frame.
if (cursorFrame && cursorFrame->PresShell() == presShell) {
nsCOMPtr<nsIContent> cursorContent = cursorFrame->GetContent();
NS_ENSURE_TRUE(cursorContent, NS_ERROR_FAILURE);
nsIContent* cursorContentRoot =
cursorContent->GetSelectionRootContent(presShell);
NS_ENSURE_TRUE(cursorContentRoot, NS_ERROR_UNEXPECTED);
if (cursorContentRoot == anchorRoot) {
*aRetFrame = cursorFrame;
aRetPoint = aPoint + aFrame->GetOffsetTo(cursorFrame);
return NS_OK;
}
}
// Otherwise, e.g., the cursor isn't on any frames (e.g., the mouse
// cursor is out of the window), we should use the frame of the anchor
// root.
}
}
//
// When we can't find a frame which is under the mouse cursor and has a same
// selection root as the anchor node's, we should return the selection root
// frame.
//
*aRetFrame = anchorRoot->GetPrimaryFrame();
if (!*aRetFrame) {
return NS_ERROR_FAILURE;
}
//
// Now make sure that aRetPoint is converted to the same coordinate
// system used by aRetFrame.
//
aRetPoint = aPoint + aFrame->GetOffsetTo(*aRetFrame);
return NS_OK;
}
void nsFrameSelection::SetCaretBidiLevelAndMaybeSchedulePaint(
nsBidiLevel aLevel) {
// If the current level is undefined, we have just inserted new text.
// In this case, we don't want to reset the keyboard language
mCaret.mBidiLevel = aLevel;
RefPtr<nsCaret> caret;
if (mPresShell && (caret = mPresShell->GetCaret())) {
caret->SchedulePaint();
}
}
nsBidiLevel nsFrameSelection::GetCaretBidiLevel() const {
return mCaret.mBidiLevel;
}
void nsFrameSelection::UndefineCaretBidiLevel() {
mCaret.mBidiLevel |= BIDI_LEVEL_UNDEFINED;
}
#ifdef PRINT_RANGE
void printRange(nsRange* aDomRange) {
if (!aDomRange) {
printf("NULL Range\n");
}
nsINode* startNode = aDomRange->GetStartContainer();
nsINode* endNode = aDomRange->GetEndContainer();
int32_t startOffset = aDomRange->StartOffset();
int32_t endOffset = aDomRange->EndOffset();
printf("range: 0x%lx\t start: 0x%lx %ld, \t end: 0x%lx,%ld\n",
(unsigned long)aDomRange, (unsigned long)startNode, (long)startOffset,
(unsigned long)endNode, (long)endOffset);
}
#endif /* PRINT_RANGE */
static nsAtom* GetTag(nsINode* aNode) {
nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
if (!content) {
MOZ_ASSERT_UNREACHABLE("bad node passed to GetTag()");
return nullptr;
}
return content->NodeInfo()->NameAtom();
}
/**
*/
static nsINode* GetClosestInclusiveTableCellAncestor(nsINode* aDomNode) {
if (!aDomNode) return nullptr;
nsINode* current = aDomNode;
// Start with current node and look for a table cell
while (current) {
nsAtom* tag = GetTag(current);
if (tag == nsGkAtoms::td || tag == nsGkAtoms::th) return current;
current = current->GetParent();
}
return nullptr;
}
static nsDirection GetCaretDirection(const nsIFrame& aFrame,
nsDirection aDirection,
bool aVisualMovement) {
const nsBidiDirection paragraphDirection =
nsBidiPresUtils::ParagraphDirection(&aFrame);
return (aVisualMovement && paragraphDirection == NSBIDI_RTL)
? nsDirection(1 - aDirection)
: aDirection;
}
nsresult nsFrameSelection::MoveCaret(nsDirection aDirection,
bool aContinueSelection,
const nsSelectionAmount aAmount,
CaretMovementStyle aMovementStyle) {
NS_ENSURE_STATE(mPresShell);
// Flush out layout, since we need it to be up to date to do caret
// positioning.
OwningNonNull<PresShell> presShell(*mPresShell);
presShell->FlushPendingNotifications(FlushType::Layout);
if (!mPresShell) {
return NS_OK;
}
nsPresContext* context = mPresShell->GetPresContext();
if (!context) {
return NS_ERROR_FAILURE;
}
const int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
const RefPtr<Selection> sel = mDomSelections[index];
if (!sel) {
return NS_ERROR_NULL_POINTER;
}
int32_t scrollFlags = Selection::SCROLL_FOR_CARET_MOVE;
if (sel->IsEditorSelection()) {
// If caret moves in editor, it should cause scrolling even if it's in
// overflow: hidden;.
scrollFlags |= Selection::SCROLL_OVERFLOW_HIDDEN;
}
int32_t caretStyle = StaticPrefs::layout_selection_caret_style();
if (caretStyle == 0
#ifdef XP_WIN
&& aAmount != eSelectLine
#endif
) {
// Put caret at the selection edge in the |aDirection| direction.
caretStyle = 2;
}
const bool doCollapse = !sel->IsCollapsed() && !aContinueSelection &&
caretStyle == 2 && aAmount <= eSelectLine;
if (doCollapse) {
if (aDirection == eDirPrevious) {
SetChangeReasons(nsISelectionListener::COLLAPSETOSTART_REASON);
mCaret.mHint = CARET_ASSOCIATE_AFTER;
} else {
SetChangeReasons(nsISelectionListener::COLLAPSETOEND_REASON);
mCaret.mHint = CARET_ASSOCIATE_BEFORE;
}
} else {
SetChangeReasons(nsISelectionListener::KEYPRESS_REASON);
}
AutoPrepareFocusRange prep(sel, false);
// we must keep this around and revalidate it when its just UP/DOWN
nsPoint desiredPos(0, 0);
if (aAmount == eSelectLine) {
nsresult result = mDesiredCaretPos.FetchPos(desiredPos, *mPresShell, *sel);
if (NS_FAILED(result)) {
return result;
}
mDesiredCaretPos.Set(desiredPos);
}
bool visualMovement =
mCaret.IsVisualMovement(aContinueSelection, aMovementStyle);
nsIFrame* frame = sel->GetPrimaryFrameForFocusNode(visualMovement);
if (!frame) {
return NS_ERROR_FAILURE;
}
Result<bool, nsresult> isIntraLineCaretMove = IsIntraLineCaretMove(aAmount);
nsDirection direction{aDirection};
if (isIntraLineCaretMove.isErr()) {
return isIntraLineCaretMove.unwrapErr();
}
if (isIntraLineCaretMove.inspect()) {
// Forget old caret position for moving caret to different line since
// caret position may be changed.
mDesiredCaretPos.Invalidate();
direction = GetCaretDirection(*frame, aDirection, visualMovement);
}
if (doCollapse) {
const nsRange* anchorFocusRange = sel->GetAnchorFocusRange();
if (anchorFocusRange) {
RefPtr<nsINode> node;
int32_t offset;
if (visualMovement && nsBidiPresUtils::IsReversedDirectionFrame(frame)) {
direction = nsDirection(1 - direction);
}
if (direction == eDirPrevious) {
node = anchorFocusRange->GetStartContainer();
offset = anchorFocusRange->StartOffset();
} else {
node = anchorFocusRange->GetEndContainer();
offset = anchorFocusRange->EndOffset();
}
sel->CollapseInLimiter(node, offset);
}
sel->ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION,
ScrollAxis(), ScrollAxis(), scrollFlags);
return NS_OK;
}
CaretAssociateHint tHint(mCaret.mHint); // temporary variable so we dont set
// mCaret.mHint until it is necessary
Result<nsPeekOffsetStruct, nsresult> result = PeekOffsetForCaretMove(
direction, aContinueSelection, aAmount, aMovementStyle, desiredPos);
nsresult rv;
if (result.isOk() && result.inspect().mResultContent) {
const nsPeekOffsetStruct& pos = result.inspect();
nsIFrame* theFrame;
int32_t currentOffset, frameStart, frameEnd;
if (aAmount <= eSelectWordNoSpace) {
// For left/right, PeekOffset() sets pos.mResultFrame correctly, but does
// not set pos.mAttachForward, so determine the hint here based on the
// result frame and offset: If we're at the end of a text frame, set the
// hint to ASSOCIATE_BEFORE to indicate that we want the caret displayed
// at the end of this frame, not at the beginning of the next one.
theFrame = pos.mResultFrame;
theFrame->GetOffsets(frameStart, frameEnd);
currentOffset = pos.mContentOffset;
if (frameEnd == currentOffset && !(frameStart == 0 && frameEnd == 0))
tHint = CARET_ASSOCIATE_BEFORE;
else
tHint = CARET_ASSOCIATE_AFTER;
} else {
// For up/down and home/end, pos.mResultFrame might not be set correctly,
// or not at all. In these cases, get the frame based on the content and
// hint returned by PeekOffset().
tHint = pos.mAttach;
theFrame = GetFrameForNodeOffset(pos.mResultContent, pos.mContentOffset,
tHint, &currentOffset);
if (!theFrame) return NS_ERROR_FAILURE;
theFrame->GetOffsets(frameStart, frameEnd);
}
if (context->BidiEnabled()) {
switch (aAmount) {
case eSelectBeginLine:
case eSelectEndLine: {
// In Bidi contexts, PeekOffset calculates pos.mContentOffset
// differently depending on whether the movement is visual or logical.
// For visual movement, pos.mContentOffset depends on the direction-
// ality of the first/last frame on the line (theFrame), and the caret
// directionality must correspond.
FrameBidiData bidiData = theFrame->GetBidiData();
SetCaretBidiLevelAndMaybeSchedulePaint(
visualMovement ? bidiData.embeddingLevel : bidiData.baseLevel);
break;
}
default:
// If the current position is not a frame boundary, it's enough just
// to take the Bidi level of the current frame
if ((pos.mContentOffset != frameStart &&
pos.mContentOffset != frameEnd) ||
eSelectLine == aAmount) {
SetCaretBidiLevelAndMaybeSchedulePaint(
theFrame->GetEmbeddingLevel());
} else {
BidiLevelFromMove(mPresShell, pos.mResultContent,
pos.mContentOffset, aAmount, tHint);
}
}
}
// "pos" is on the stack, so pos.mResultContent has stack lifetime, so using
// MOZ_KnownLive is ok.
const FocusMode focusMode = aContinueSelection
? FocusMode::kExtendSelection
: FocusMode::kCollapseToNewPoint;
rv = TakeFocus(MOZ_KnownLive(*pos.mResultContent), pos.mContentOffset,
pos.mContentOffset, tHint, focusMode);
} else if (aAmount <= eSelectWordNoSpace && direction == eDirNext &&
!aContinueSelection) {
// Collapse selection if PeekOffset failed, we either
// 1. bumped into the BRFrame, bug 207623
// 2. had select-all in a text input (DIV range), bug 352759.
bool isBRFrame = frame->IsBrFrame();
RefPtr<nsINode> node = sel->GetFocusNode();
sel->CollapseInLimiter(node, sel->FocusOffset());
// Note: 'frame' might be dead here.
if (!isBRFrame) {
mCaret.mHint = CARET_ASSOCIATE_BEFORE; // We're now at the end of the
// frame to the left.
}
rv = NS_OK;
} else {
rv = result.isErr() ? result.unwrapErr() : NS_OK;
}
if (NS_SUCCEEDED(rv)) {
rv = sel->ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION,
ScrollAxis(), ScrollAxis(), scrollFlags);
}
return rv;
}
Result<nsPeekOffsetStruct, nsresult> nsFrameSelection::PeekOffsetForCaretMove(
nsDirection aDirection, bool aContinueSelection,
const nsSelectionAmount aAmount, CaretMovementStyle aMovementStyle,
const nsPoint& aDesiredCaretPos) const {
Selection* selection =
mDomSelections[GetIndexFromSelectionType(SelectionType::eNormal)];
if (!selection) {
return Err(NS_ERROR_NULL_POINTER);
}
const bool visualMovement =
mCaret.IsVisualMovement(aContinueSelection, aMovementStyle);
int32_t offsetused = 0;
nsIFrame* frame =
selection->GetPrimaryFrameForFocusNode(visualMovement, &offsetused);
if (!frame) {
return Err(NS_ERROR_FAILURE);
}
const auto kForceEditableRegion =
selection->IsEditorSelection()
? nsPeekOffsetStruct::ForceEditableRegion::Yes
: nsPeekOffsetStruct::ForceEditableRegion::No;
// set data using mLimiters.mLimiter to stop on scroll views. If we have a
// limiter then we stop peeking when we hit scrollable views. If no limiter
// then just let it go ahead
nsPeekOffsetStruct pos(aAmount, aDirection, offsetused, aDesiredCaretPos,
true, !!mLimiters.mLimiter, true, visualMovement,
aContinueSelection, kForceEditableRegion);
nsresult rv = frame->PeekOffset(&pos);
if (NS_FAILED(rv)) {
return Err(rv);
}
return pos;
}
nsPrevNextBidiLevels nsFrameSelection::GetPrevNextBidiLevels(
nsIContent* aNode, uint32_t aContentOffset, bool aJumpLines) const {
return GetPrevNextBidiLevels(aNode, aContentOffset, mCaret.mHint, aJumpLines);
}
// static
nsPrevNextBidiLevels nsFrameSelection::GetPrevNextBidiLevels(
nsIContent* aNode, uint32_t aContentOffset, CaretAssociateHint aHint,
bool aJumpLines) {
// Get the level of the frames on each side
nsIFrame* currentFrame;
int32_t currentOffset;
int32_t frameStart, frameEnd;
nsDirection direction;
nsPrevNextBidiLevels levels;
levels.SetData(nullptr, nullptr, 0, 0);
currentFrame =
GetFrameForNodeOffset(aNode, aContentOffset, aHint, &currentOffset);
if (!currentFrame) return levels;
currentFrame->GetOffsets(frameStart, frameEnd);
if (0 == frameStart && 0 == frameEnd)
direction = eDirPrevious;
else if (frameStart == currentOffset)
direction = eDirPrevious;
else if (frameEnd == currentOffset)
direction = eDirNext;
else {
// we are neither at the beginning nor at the end of the frame, so we have
// no worries
nsBidiLevel currentLevel = currentFrame->GetEmbeddingLevel();
levels.SetData(currentFrame, currentFrame, currentLevel, currentLevel);
return levels;
}
nsIFrame* newFrame =
currentFrame
->GetFrameFromDirection(direction, false, aJumpLines, true, false)
.mFrame;
FrameBidiData currentBidi = currentFrame->GetBidiData();
nsBidiLevel currentLevel = currentBidi.embeddingLevel;
nsBidiLevel newLevel =
newFrame ? newFrame->GetEmbeddingLevel() : currentBidi.baseLevel;
// If not jumping lines, disregard br frames, since they might be positioned
// incorrectly.
// XXX This could be removed once bug 339786 is fixed.
if (!aJumpLines) {
if (currentFrame->IsBrFrame()) {
currentFrame = nullptr;
currentLevel = currentBidi.baseLevel;
}
if (newFrame && newFrame->IsBrFrame()) {
newFrame = nullptr;
newLevel = currentBidi.baseLevel;
}
}
if (direction == eDirNext)
levels.SetData(currentFrame, newFrame, currentLevel, newLevel);
else
levels.SetData(newFrame, currentFrame, newLevel, currentLevel);
return levels;
}
nsresult nsFrameSelection::GetFrameFromLevel(nsIFrame* aFrameIn,
nsDirection aDirection,
nsBidiLevel aBidiLevel,
nsIFrame** aFrameOut) const {
NS_ENSURE_STATE(mPresShell);
nsBidiLevel foundLevel = 0;
nsIFrame* foundFrame = aFrameIn;
nsCOMPtr<nsIFrameEnumerator> frameTraversal;
nsresult result;
nsCOMPtr<nsIFrameTraversal> trav(
do_CreateInstance(kFrameTraversalCID, &result));
if (NS_FAILED(result)) return result;
result =
trav->NewFrameTraversal(getter_AddRefs(frameTraversal),
mPresShell->GetPresContext(), aFrameIn, eLeaf,
false, // aVisual
false, // aLockInScrollView
false, // aFollowOOFs
false // aSkipPopupChecks
);
if (NS_FAILED(result)) return result;
do {
*aFrameOut = foundFrame;
foundFrame = frameTraversal->Traverse(aDirection == eDirNext);
if (!foundFrame) return NS_ERROR_FAILURE;
foundLevel = foundFrame->GetEmbeddingLevel();
} while (foundLevel > aBidiLevel);
return NS_OK;
}
nsresult nsFrameSelection::MaintainSelection(nsSelectionAmount aAmount) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) {
return NS_ERROR_NULL_POINTER;
}
mMaintainedRange.MaintainAnchorFocusRange(*mDomSelections[index], aAmount);
return NS_OK;
}
void nsFrameSelection::BidiLevelFromMove(PresShell* aPresShell,
nsIContent* aNode,
uint32_t aContentOffset,
nsSelectionAmount aAmount,
CaretAssociateHint aHint) {
switch (aAmount) {
// Movement within the line: the new cursor Bidi level is the level of the
// last character moved over
case eSelectCharacter:
case eSelectCluster:
case eSelectWord:
case eSelectWordNoSpace:
case eSelectBeginLine:
case eSelectEndLine:
case eSelectNoAmount: {
nsPrevNextBidiLevels levels =
GetPrevNextBidiLevels(aNode, aContentOffset, aHint, false);
SetCaretBidiLevelAndMaybeSchedulePaint(aHint == CARET_ASSOCIATE_BEFORE
? levels.mLevelBefore
: levels.mLevelAfter);
break;
}
/*
// Up and Down: the new cursor Bidi level is the smaller of the two
surrounding characters case eSelectLine: case eSelectParagraph:
GetPrevNextBidiLevels(aContext, aNode, aContentOffset, &firstFrame,
&secondFrame, &firstLevel, &secondLevel);
aPresShell->SetCaretBidiLevelAndMaybeSchedulePaint(std::min(firstLevel,
secondLevel)); break;
*/
default:
UndefineCaretBidiLevel();
}
}
void nsFrameSelection::BidiLevelFromClick(nsIContent* aNode,
uint32_t aContentOffset) {
nsIFrame* clickInFrame = nullptr;
int32_t OffsetNotUsed;
clickInFrame = GetFrameForNodeOffset(aNode, aContentOffset, mCaret.mHint,
&OffsetNotUsed);
if (!clickInFrame) return;
SetCaretBidiLevelAndMaybeSchedulePaint(clickInFrame->GetEmbeddingLevel());
}
void nsFrameSelection::MaintainedRange::AdjustNormalSelection(
const nsIContent* aContent, const int32_t aOffset,
Selection& aNormalSelection) const {
MOZ_ASSERT(aNormalSelection.Type() == SelectionType::eNormal);
if (!mRange || !aContent) {
return;
}
nsINode* rangeStartNode = mRange->GetStartContainer();
nsINode* rangeEndNode = mRange->GetEndContainer();
int32_t rangeStartOffset = mRange->StartOffset();
int32_t rangeEndOffset = mRange->EndOffset();
const Maybe<int32_t> relToStart = nsContentUtils::ComparePoints(
rangeStartNode, rangeStartOffset, aContent, aOffset);
if (NS_WARN_IF(!relToStart)) {
// Potentially handle this properly when Selection across Shadow DOM
// boundary is implemented
return;
}
const Maybe<int32_t> relToEnd = nsContentUtils::ComparePoints(
rangeEndNode, rangeEndOffset, aContent, aOffset);
if (NS_WARN_IF(!relToEnd)) {
// Potentially handle this properly when Selection across Shadow DOM
// boundary is implemented
return;
}
// If aContent/aOffset is inside (or at the edge of) the maintained
// selection, or if it is on the "anchor" side of the maintained selection,
// we need to do something.
if ((*relToStart <= 0 && *relToEnd >= 0) ||
(*relToStart > 0 && aNormalSelection.GetDirection() == eDirNext) ||
(*relToEnd < 0 && aNormalSelection.GetDirection() == eDirPrevious)) {
// Set the current range to the maintained range.
aNormalSelection.ReplaceAnchorFocusRange(mRange);
// Set the direction of the selection so that the anchor will be on the
// far side of the maintained selection, relative to aContent/aOffset.
aNormalSelection.SetDirection(*relToStart > 0 ? eDirPrevious : eDirNext);
}
}
void nsFrameSelection::MaintainedRange::AdjustContentOffsets(
nsIFrame::ContentOffsets& aOffsets, const bool aScrollViewStop) const {
// Adjust offsets according to maintained amount
if (mRange && mAmount != eSelectNoAmount) {
nsINode* rangenode = mRange->GetStartContainer();
int32_t rangeOffset = mRange->StartOffset();
const Maybe<int32_t> relativePosition = nsContentUtils::ComparePoints(
rangenode, rangeOffset, aOffsets.content, aOffsets.offset);
if (NS_WARN_IF(!relativePosition)) {
// Potentially handle this properly when Selection across Shadow DOM
// boundary is implemented
return;
}
nsDirection direction = *relativePosition > 0 ? eDirPrevious : eDirNext;
nsSelectionAmount amount = mAmount;
if (amount == eSelectBeginLine && direction == eDirNext) {
amount = eSelectEndLine;
}
int32_t offset;
nsIFrame* frame = GetFrameForNodeOffset(aOffsets.content, aOffsets.offset,
CARET_ASSOCIATE_AFTER, &offset);
if (frame && amount == eSelectWord && direction == eDirPrevious) {
// To avoid selecting the previous word when at start of word,
// first move one character forward.
nsPeekOffsetStruct charPos(eSelectCharacter, eDirNext, offset,
nsPoint(0, 0), false, aScrollViewStop, false,
false, false);
if (NS_SUCCEEDED(frame->PeekOffset(&charPos))) {
frame = charPos.mResultFrame;
offset = charPos.mContentOffset;
}
}
nsPeekOffsetStruct pos(amount, direction, offset, nsPoint(0, 0), false,
aScrollViewStop, false, false, false);
if (frame && NS_SUCCEEDED(frame->PeekOffset(&pos)) && pos.mResultContent) {
aOffsets.content = pos.mResultContent;
aOffsets.offset = pos.mContentOffset;
}
}
}
void nsFrameSelection::MaintainedRange::MaintainAnchorFocusRange(
const Selection& aNormalSelection, const nsSelectionAmount aAmount) {
MOZ_ASSERT(aNormalSelection.Type() == SelectionType::eNormal);
mAmount = aAmount;
const nsRange* anchorFocusRange = aNormalSelection.GetAnchorFocusRange();
if (anchorFocusRange && aAmount != eSelectNoAmount) {
mRange = anchorFocusRange->CloneRange();
return;
}
mRange = nullptr;
}
nsresult nsFrameSelection::HandleClick(nsIContent* aNewFocus,
uint32_t aContentOffset,
uint32_t aContentEndOffset,
const FocusMode aFocusMode,
CaretAssociateHint aHint) {
if (!aNewFocus) return NS_ERROR_INVALID_ARG;
if (MOZ_LOG_TEST(sFrameSelectionLog, LogLevel::Debug)) {
const int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
MOZ_LOG(sFrameSelectionLog, LogLevel::Debug,
("%s: selection=%p, new focus=%p, offsets=(%u,%u), focus mode=%i",
__FUNCTION__,
mDomSelections[index] ? mDomSelections[index].get() : nullptr,
aNewFocus, aContentOffset, aContentEndOffset,
static_cast<int>(aFocusMode)));
}
mDesiredCaretPos.Invalidate();
if (aFocusMode != FocusMode::kExtendSelection) {
mMaintainedRange.mRange = nullptr;
if (!IsValidSelectionPoint(aNewFocus)) {
mLimiters.mAncestorLimiter = nullptr;
}
}
// Don't take focus when dragging off of a table
if (!mTableSelection.mDragSelectingCells) {
BidiLevelFromClick(aNewFocus, aContentOffset);
SetChangeReasons(nsISelectionListener::MOUSEDOWN_REASON +
nsISelectionListener::DRAG_REASON);
const int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
RefPtr<Selection> selection = mDomSelections[index];
MOZ_ASSERT(selection);
if (aFocusMode == FocusMode::kExtendSelection) {
mMaintainedRange.AdjustNormalSelection(aNewFocus, aContentOffset,
*selection);
}
AutoPrepareFocusRange prep(selection,
aFocusMode == FocusMode::kMultiRangeSelection);
return TakeFocus(*aNewFocus, aContentOffset, aContentEndOffset, aHint,
aFocusMode);
}
return NS_OK;
}
void nsFrameSelection::HandleDrag(nsIFrame* aFrame, const nsPoint& aPoint) {
if (!aFrame || !mPresShell) {
return;
}
nsresult result;
nsIFrame* newFrame = 0;
nsPoint newPoint;
result = ConstrainFrameAndPointToAnchorSubtree(aFrame, aPoint, &newFrame,
newPoint);
if (NS_FAILED(result)) return;
if (!newFrame) return;
nsIFrame::ContentOffsets offsets =
newFrame->GetContentOffsetsFromPoint(newPoint);
if (!offsets.content) return;
const int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
RefPtr<Selection> selection = mDomSelections[index];
if (newFrame->IsSelected() && selection) {
// `MOZ_KnownLive` required because of
mMaintainedRange.AdjustNormalSelection(MOZ_KnownLive(offsets.content),
offsets.offset, *selection);
}
const bool scrollViewStop = mLimiters.mLimiter != nullptr;
mMaintainedRange.AdjustContentOffsets(offsets, scrollViewStop);
// TODO: no click has happened, rename `HandleClick`.
HandleClick(MOZ_KnownLive(offsets.content) /* bug 1636889 */, offsets.offset,
offsets.offset, FocusMode::kExtendSelection, offsets.associate);
}
nsresult nsFrameSelection::StartAutoScrollTimer(nsIFrame* aFrame,
const nsPoint& aPoint,
uint32_t aDelay) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) {
return NS_ERROR_NULL_POINTER;
}
RefPtr<Selection> selection = mDomSelections[index];
return selection->StartAutoScrollTimer(aFrame, aPoint, aDelay);
}
void nsFrameSelection::StopAutoScrollTimer() {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) {
return;
}
mDomSelections[index]->StopAutoScrollTimer();
}
// static
nsINode* nsFrameSelection::TableSelection::IsContentInActivelyEditableTableCell(
nsPresContext* aContext, nsIContent* aContent) {
if (!aContext) {
return nullptr;
}
RefPtr<HTMLEditor> htmlEditor = nsContentUtils::GetHTMLEditor(aContext);
if (!htmlEditor) {
return nullptr;
}
nsINode* inclusiveTableCellAncestor =
GetClosestInclusiveTableCellAncestor(aContent);
if (!inclusiveTableCellAncestor) {
return nullptr;
}
const Element* editorHostNode = htmlEditor->GetActiveEditingHost();
if (!editorHostNode) {
return nullptr;
}
const bool editableCell =
inclusiveTableCellAncestor->IsInclusiveDescendantOf(editorHostNode);
return editableCell ? inclusiveTableCellAncestor : nullptr;
}
namespace {
struct ParentAndOffset {
explicit ParentAndOffset(const nsINode& aNode)
: mParent{aNode.GetParent()},
mOffset{mParent ? mParent->ComputeIndexOf(&aNode) : 0} {}
nsINode* mParent;
// 0, if there's no parent.
int32_t mOffset;
};
} // namespace
/**
hard to go from nodes to frames, easy the other way!
*/
nsresult nsFrameSelection::TakeFocus(nsIContent& aNewFocus,
uint32_t aContentOffset,
uint32_t aContentEndOffset,
CaretAssociateHint aHint,
const FocusMode aFocusMode) {
NS_ENSURE_STATE(mPresShell);
if (!IsValidSelectionPoint(&aNewFocus)) {
return NS_ERROR_FAILURE;
}
MOZ_LOG(sFrameSelectionLog, LogLevel::Verbose,
("%s: new focus=%p, offsets=(%u, %u), hint=%i, focusMode=%i",
__FUNCTION__, &aNewFocus, aContentOffset, aContentEndOffset,
static_cast<int>(aHint), static_cast<int>(aFocusMode)));
mPresShell->FrameSelectionWillTakeFocus(*this);
// Clear all table selection data
mTableSelection.mMode = TableSelectionMode::None;
mTableSelection.mDragSelectingCells = false;
mTableSelection.mStartSelectedCell = nullptr;
mTableSelection.mEndSelectedCell = nullptr;
mTableSelection.mAppendStartSelectedCell = nullptr;
mCaret.mHint = aHint;
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) return NS_ERROR_NULL_POINTER;
Maybe<Selection::AutoUserInitiated> userSelect;
if (IsUserSelectionReason()) {
userSelect.emplace(mDomSelections[index]);
}
// traverse through document and unselect crap here
switch (aFocusMode) {
case FocusMode::kCollapseToNewPoint:
[[fallthrough]];
case FocusMode::kMultiRangeSelection: {
// single click? setting cursor down
const Batching saveBatching =
mBatching; // hack to use the collapse code.
mBatching.mCounter = 1;
RefPtr<Selection> selection = mDomSelections[index];
if (aFocusMode == FocusMode::kMultiRangeSelection) {
// Remove existing collapsed ranges as there's no point in having
// non-anchor/focus collapsed ranges.
selection->RemoveCollapsedRanges();
ErrorResult error;
RefPtr<nsRange> newRange = nsRange::Create(
&aNewFocus, aContentOffset, &aNewFocus, aContentOffset, error);
if (NS_WARN_IF(error.Failed())) {
return error.StealNSResult();
}
MOZ_ASSERT(newRange);
selection->AddRangeAndSelectFramesAndNotifyListeners(*newRange,
IgnoreErrors());
} else {
bool oldDesiredPosSet =
mDesiredCaretPos.mIsSet; // need to keep old desired
// position if it was set.
selection->CollapseInLimiter(&aNewFocus, aContentOffset);
mDesiredCaretPos.mIsSet =
oldDesiredPosSet; // now reset desired pos back.
}
mBatching = saveBatching;
if (aContentEndOffset != aContentOffset) {
selection->Extend(&aNewFocus, aContentEndOffset);
}
// find out if we are inside a table. if so, find out which one and which
// cell once we do that, the next time we get a takefocus, check the
// parent tree. if we are no longer inside same table ,cell then switch to
// table selection mode. BUT only do this in an editor
NS_ENSURE_STATE(mPresShell);
RefPtr<nsPresContext> context = mPresShell->GetPresContext();
mTableSelection.mClosestInclusiveTableCellAncestor = nullptr;
if (nsINode* inclusiveTableCellAncestor =
TableSelection::IsContentInActivelyEditableTableCell(
context, &aNewFocus)) {
mTableSelection.mClosestInclusiveTableCellAncestor =
inclusiveTableCellAncestor;
MOZ_LOG(sFrameSelectionLog, LogLevel::Debug,
("%s: Collapsing into new cell", __FUNCTION__));
}
break;
}
case FocusMode::kExtendSelection: {
// Now update the range list:
nsINode* inclusiveTableCellAncestor =
GetClosestInclusiveTableCellAncestor(&aNewFocus);
if (mTableSelection.mClosestInclusiveTableCellAncestor &&
inclusiveTableCellAncestor &&
inclusiveTableCellAncestor !=
mTableSelection
.mClosestInclusiveTableCellAncestor) // switch to cell
// selection mode
{
MOZ_LOG(sFrameSelectionLog, LogLevel::Debug,
("%s: moving into new cell", __FUNCTION__));
WidgetMouseEvent event(false, eVoidEvent, nullptr,
WidgetMouseEvent::eReal);
// Start selecting in the cell we were in before
ParentAndOffset parentAndOffset{
*mTableSelection.mClosestInclusiveTableCellAncestor};
if (parentAndOffset.mParent) {
const nsresult result = HandleTableSelection(
parentAndOffset.mParent, parentAndOffset.mOffset,
TableSelectionMode::Cell, &event);
if (NS_WARN_IF(NS_FAILED(result))) {
return result;
}
}
// Find the parent of this new cell and extend selection to it
parentAndOffset = ParentAndOffset{*inclusiveTableCellAncestor};
// XXXX We need to REALLY get the current key shift state
// (we'd need to add event listener -- let's not bother for now)
event.mModifiers &= ~MODIFIER_SHIFT; // aContinueSelection;
if (parentAndOffset.mParent) {
mTableSelection.mClosestInclusiveTableCellAncestor =
inclusiveTableCellAncestor;
// Continue selection into next cell
const nsresult result = HandleTableSelection(
parentAndOffset.mParent, parentAndOffset.mOffset,
TableSelectionMode::Cell, &event);
if (NS_WARN_IF(NS_FAILED(result))) {
return result;
}
}
} else {
RefPtr<Selection> selection = mDomSelections[index];
// XXXX Problem: Shift+click in browser is appending text selection to
// selected table!!!
// is this the place to erase selected cells ?????
uint32_t offset =
(selection->GetDirection() == eDirNext &&
aContentEndOffset > aContentOffset) // didn't go far enough
? aContentEndOffset // this will only redraw the diff
: aContentOffset;
selection->Extend(&aNewFocus, offset);
}
break;
}
}
// Don't notify selection listeners if batching is on:
if (IsBatching()) {
return NS_OK;
}
// Be aware, the Selection instance may be destroyed after this call.
return NotifySelectionListeners(SelectionType::eNormal);
}
UniquePtr<SelectionDetails> nsFrameSelection::LookUpSelection(
nsIContent* aContent, int32_t aContentOffset, int32_t aContentLength,
bool aSlowCheck) const {
if (!aContent || !mPresShell) {
return nullptr;
}
UniquePtr<SelectionDetails> details;
for (size_t j = 0; j < ArrayLength(mDomSelections); j++) {
if (mDomSelections[j]) {
details = mDomSelections[j]->LookUpSelection(
aContent, aContentOffset, aContentLength, std::move(details),
kPresentSelectionTypes[j], aSlowCheck);
}
}
return details;
}
void nsFrameSelection::SetDragState(bool aState) {
if (mDragState == aState) return;
mDragState = aState;
if (!mDragState) {
mTableSelection.mDragSelectingCells = false;
// Notify that reason is mouse up.
SetChangeReasons(nsISelectionListener::MOUSEUP_REASON);
// Be aware, the Selection instance may be destroyed after this call.
NotifySelectionListeners(SelectionType::eNormal);
}
}
Selection* nsFrameSelection::GetSelection(SelectionType aSelectionType) const {
int8_t index = GetIndexFromSelectionType(aSelectionType);
if (index < 0) return