Bug 1893067 - Add actions key to glean urlbar metrics. r=mak,urlbar-reviewers
[gecko.git] / editor / libeditor / DeleteRangeTransaction.cpp
blob6262f31fd031a46a70ab32e5a8735b1993bbb7d1
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
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/. */
6 #include "DeleteRangeTransaction.h"
8 #include "DeleteContentTransactionBase.h"
9 #include "DeleteNodeTransaction.h"
10 #include "DeleteTextTransaction.h"
11 #include "EditTransactionBase.h"
12 #include "EditorBase.h"
13 #include "EditorDOMPoint.h"
14 #include "EditorUtils.h"
15 #include "HTMLEditUtils.h"
17 #include "mozilla/Assertions.h"
18 #include "mozilla/ContentIterator.h"
19 #include "mozilla/Logging.h"
20 #include "mozilla/mozalloc.h"
21 #include "mozilla/RangeBoundary.h"
22 #include "mozilla/StaticPrefs_editor.h"
23 #include "mozilla/ToString.h"
24 #include "mozilla/dom/Selection.h"
26 #include "nsAtom.h"
27 #include "nsCOMPtr.h"
28 #include "nsDebug.h"
29 #include "nsError.h"
30 #include "nsGkAtoms.h"
31 #include "nsIContent.h"
32 #include "nsINode.h"
33 #include "nsAString.h"
35 namespace mozilla {
37 using namespace dom;
39 using EditorType = EditorUtils::EditorType;
41 DeleteRangeTransaction::DeleteRangeTransaction(EditorBase& aEditorBase,
42 const nsRange& aRangeToDelete)
43 : mEditorBase(&aEditorBase), mRangeToDelete(aRangeToDelete.CloneRange()) {}
45 NS_IMPL_CYCLE_COLLECTION_INHERITED(DeleteRangeTransaction,
46 EditAggregateTransaction, mEditorBase,
47 mRangeToDelete, mPointToPutCaret)
49 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DeleteRangeTransaction)
50 NS_INTERFACE_MAP_END_INHERITING(EditAggregateTransaction)
52 void DeleteRangeTransaction::AppendChild(
53 DeleteContentTransactionBase& aTransaction) {
54 mChildren.AppendElement(aTransaction);
57 nsresult
58 DeleteRangeTransaction::MaybeExtendDeletingRangeWithSurroundingWhitespace(
59 nsRange& aRange) const {
60 if (!mEditorBase->mEditActionData->SelectionCreatedByDoubleclick() ||
61 !StaticPrefs::
62 editor_word_select_delete_space_after_doubleclick_selection()) {
63 return NS_OK;
65 EditorRawDOMPoint startPoint(aRange.StartRef());
66 EditorRawDOMPoint endPoint(aRange.EndRef());
67 const bool maybeRangeStartsAfterWhiteSpace =
68 startPoint.IsInTextNode() && !startPoint.IsStartOfContainer();
69 const bool maybeRangeEndsAtWhiteSpace =
70 endPoint.IsInTextNode() && !endPoint.IsEndOfContainer();
72 if (!maybeRangeStartsAfterWhiteSpace && !maybeRangeEndsAtWhiteSpace) {
73 // no whitespace before or after word => nothing to do here.
74 return NS_OK;
77 const bool precedingCharIsWhitespace =
78 maybeRangeStartsAfterWhiteSpace
79 ? startPoint.IsPreviousCharASCIISpaceOrNBSP()
80 : false;
81 const bool trailingCharIsWhitespace =
82 maybeRangeEndsAtWhiteSpace ? endPoint.IsCharASCIISpaceOrNBSP() : false;
84 // if possible, try to remove the preceding whitespace
85 // so the caret is at the end of the previous word.
86 if (precedingCharIsWhitespace) {
87 // "one [two]", "one [two] three" or "one [two], three"
88 ErrorResult err;
89 aRange.SetStart(startPoint.PreviousPoint(), err);
90 if (auto rv = err.StealNSResult(); NS_FAILED(rv)) {
91 NS_WARNING(
92 "DeleteRangeTransaction::"
93 "MaybeExtendDeletingRangeWithSurroundingWhitespace"
94 " failed to update the start of the deleting range");
95 return rv;
97 } else if (trailingCharIsWhitespace) {
98 // "[one] two"
99 ErrorResult err;
100 aRange.SetEnd(endPoint.NextPoint(), err);
101 if (auto rv = err.StealNSResult(); NS_FAILED(rv)) {
102 NS_WARNING(
103 "DeleteRangeTransaction::"
104 "MaybeExtendDeletingRangeWithSurroundingWhitespace"
105 " failed to update the end of the deleting range");
106 return rv;
110 return NS_OK;
113 NS_IMETHODIMP DeleteRangeTransaction::DoTransaction() {
114 MOZ_LOG(GetLogModule(), LogLevel::Info,
115 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
116 "Start==============================",
117 this, __FUNCTION__,
118 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
120 if (NS_WARN_IF(!mEditorBase) || NS_WARN_IF(!mRangeToDelete)) {
121 return NS_ERROR_NOT_AVAILABLE;
124 // Swap mRangeToDelete out into a stack variable, so we make sure to null it
125 // out on return from this function. Once this function returns, we no longer
126 // need mRangeToDelete, and keeping it alive in the long term slows down all
127 // DOM mutations because it's observing them.
128 RefPtr<nsRange> rangeToDelete;
129 rangeToDelete.swap(mRangeToDelete);
131 MaybeExtendDeletingRangeWithSurroundingWhitespace(*rangeToDelete);
133 // build the child transactions
134 // XXX We should move this to the constructor. Then, we don't need to make
135 // this class has mRangeToDelete with nullptr since transaction instances
136 // may be created a lot and live long.
138 EditorRawDOMRange extendedRange(*rangeToDelete);
139 MOZ_ASSERT(extendedRange.IsPositionedAndValid());
141 if (extendedRange.InSameContainer()) {
142 // the selection begins and ends in the same node
143 nsresult rv = AppendTransactionsToDeleteIn(extendedRange);
144 if (NS_FAILED(rv)) {
145 NS_WARNING(
146 "DeleteRangeTransaction::AppendTransactionsToDeleteIn() failed");
147 return rv;
149 } else {
150 // If the range ends at end of a node, we may need to extend the range to
151 // make ContentSubtreeIterator iterates close tag of the unnecessary nodes
152 // in AppendTransactionsToDeleteNodesEntirelyIn.
153 for (EditorRawDOMPoint endOfRange = extendedRange.EndRef();
154 endOfRange.IsInContentNode() && endOfRange.IsEndOfContainer() &&
155 endOfRange.GetContainer() != extendedRange.StartRef().GetContainer();
156 endOfRange = extendedRange.EndRef()) {
157 extendedRange.SetEnd(
158 EditorRawDOMPoint::After(*endOfRange.ContainerAs<nsIContent>()));
161 // the selection ends in a different node from where it started. delete
162 // the relevant content in the start node
163 nsresult rv = AppendTransactionToDeleteText(extendedRange.StartRef(),
164 nsIEditor::eNext);
165 if (NS_FAILED(rv)) {
166 NS_WARNING(
167 "DeleteRangeTransaction::AppendTransactionToDeleteText() failed");
168 return rv;
170 // delete the intervening nodes
171 rv = AppendTransactionsToDeleteNodesWhoseEndBoundaryIn(extendedRange);
172 if (NS_FAILED(rv)) {
173 NS_WARNING(
174 "DeleteRangeTransaction::"
175 "AppendTransactionsToDeleteNodesWhoseEndBoundaryIn() failed");
176 return rv;
178 // delete the relevant content in the end node
179 rv = AppendTransactionToDeleteText(extendedRange.EndRef(),
180 nsIEditor::ePrevious);
181 if (NS_FAILED(rv)) {
182 NS_WARNING(
183 "DeleteRangeTransaction::AppendTransactionToDeleteText() failed");
184 return rv;
189 // if we've successfully built this aggregate transaction, then do it.
190 nsresult rv = EditAggregateTransaction::DoTransaction();
191 if (NS_FAILED(rv)) {
192 NS_WARNING("EditAggregateTransaction::DoTransaction() failed");
193 return rv;
196 MOZ_LOG(GetLogModule(), LogLevel::Info,
197 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
198 "End==============================",
199 this, __FUNCTION__,
200 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
202 mPointToPutCaret = rangeToDelete->StartRef();
203 if (MOZ_UNLIKELY(!mPointToPutCaret.IsSetAndValid())) {
204 for (const OwningNonNull<EditTransactionBase>& transaction :
205 Reversed(mChildren)) {
206 if (const DeleteContentTransactionBase* deleteContentTransaction =
207 transaction->GetAsDeleteContentTransactionBase()) {
208 mPointToPutCaret = deleteContentTransaction->SuggestPointToPutCaret();
209 if (mPointToPutCaret.IsSetAndValid()) {
210 break;
212 continue;
214 MOZ_ASSERT_UNREACHABLE(
215 "Child transactions must be DeleteContentTransactionBase");
218 return NS_OK;
221 NS_IMETHODIMP DeleteRangeTransaction::UndoTransaction() {
222 MOZ_LOG(GetLogModule(), LogLevel::Info,
223 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
224 "Start==============================",
225 this, __FUNCTION__,
226 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
228 nsresult rv = EditAggregateTransaction::UndoTransaction();
229 NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
230 "EditAggregateTransaction::UndoTransaction() failed");
232 MOZ_LOG(GetLogModule(), LogLevel::Info,
233 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
234 "End==============================",
235 this, __FUNCTION__,
236 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
237 return rv;
240 NS_IMETHODIMP DeleteRangeTransaction::RedoTransaction() {
241 MOZ_LOG(GetLogModule(), LogLevel::Info,
242 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
243 "Start==============================",
244 this, __FUNCTION__,
245 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
247 nsresult rv = EditAggregateTransaction::RedoTransaction();
248 NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
249 "EditAggregateTransaction::RedoTransaction() failed");
251 MOZ_LOG(GetLogModule(), LogLevel::Info,
252 ("%p DeleteRangeTransaction::%s this={ mName=%s } "
253 "End==============================",
254 this, __FUNCTION__,
255 nsAtomCString(mName ? mName.get() : nsGkAtoms::_empty).get()));
256 return rv;
259 nsresult DeleteRangeTransaction::AppendTransactionsToDeleteIn(
260 const EditorRawDOMRange& aRangeToDelete) {
261 if (NS_WARN_IF(!aRangeToDelete.IsPositionedAndValid())) {
262 return NS_ERROR_INVALID_ARG;
264 MOZ_ASSERT(aRangeToDelete.InSameContainer());
266 if (NS_WARN_IF(!mEditorBase)) {
267 return NS_ERROR_NOT_AVAILABLE;
270 // see what kind of node we have
271 if (Text* textNode = aRangeToDelete.StartRef().GetContainerAs<Text>()) {
272 if (mEditorBase->IsHTMLEditor() &&
273 NS_WARN_IF(
274 !EditorUtils::IsEditableContent(*textNode, EditorType::HTML))) {
275 // Just ignore to append the transaction for non-editable node.
276 return NS_OK;
278 // if the node is a chardata node, then delete chardata content
279 uint32_t textLengthToDelete;
280 if (aRangeToDelete.Collapsed()) {
281 textLengthToDelete = 1;
282 } else {
283 textLengthToDelete =
284 aRangeToDelete.EndRef().Offset() - aRangeToDelete.StartRef().Offset();
285 MOZ_DIAGNOSTIC_ASSERT(textLengthToDelete > 0);
288 RefPtr<DeleteTextTransaction> deleteTextTransaction =
289 DeleteTextTransaction::MaybeCreate(*mEditorBase, *textNode,
290 aRangeToDelete.StartRef().Offset(),
291 textLengthToDelete);
292 // If the text node isn't editable, it should be never undone/redone.
293 // So, the transaction shouldn't be recorded.
294 if (!deleteTextTransaction) {
295 NS_WARNING("DeleteTextTransaction::MaybeCreate() failed");
296 return NS_ERROR_FAILURE;
298 AppendChild(*deleteTextTransaction);
299 return NS_OK;
302 MOZ_ASSERT(mEditorBase->IsHTMLEditor());
304 // Even if we detect invalid range, we should ignore it for removing
305 // specified range's nodes as far as possible.
306 // XXX This is super expensive. Probably, we should make
307 // DeleteNodeTransaction() can treat multiple siblings.
308 for (nsIContent* child = aRangeToDelete.StartRef().GetChild();
309 child && child != aRangeToDelete.EndRef().GetChild();
310 child = child->GetNextSibling()) {
311 if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*child))) {
312 continue; // Should we abort?
314 RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
315 DeleteNodeTransaction::MaybeCreate(*mEditorBase, *child);
316 if (deleteNodeTransaction) {
317 AppendChild(*deleteNodeTransaction);
321 return NS_OK;
324 nsresult DeleteRangeTransaction::AppendTransactionToDeleteText(
325 const EditorRawDOMPoint& aMaybePointInText, nsIEditor::EDirection aAction) {
326 if (NS_WARN_IF(!aMaybePointInText.IsSetAndValid())) {
327 return NS_ERROR_INVALID_ARG;
330 if (NS_WARN_IF(!mEditorBase)) {
331 return NS_ERROR_NOT_AVAILABLE;
334 if (!aMaybePointInText.IsInTextNode()) {
335 return NS_OK;
338 // If the node is a text node, then delete text before or after the point.
339 Text& textNode = *aMaybePointInText.ContainerAs<Text>();
340 uint32_t startOffset, numToDelete;
341 if (nsIEditor::eNext == aAction) {
342 startOffset = aMaybePointInText.Offset();
343 numToDelete = textNode.TextDataLength() - startOffset;
344 } else {
345 startOffset = 0;
346 numToDelete = aMaybePointInText.Offset();
349 if (!numToDelete) {
350 return NS_OK;
353 RefPtr<DeleteTextTransaction> deleteTextTransaction =
354 DeleteTextTransaction::MaybeCreate(*mEditorBase, textNode, startOffset,
355 numToDelete);
356 // If the text node isn't editable, it should be never undone/redone.
357 // So, the transaction shouldn't be recorded.
358 if (MOZ_UNLIKELY(!deleteTextTransaction)) {
359 NS_WARNING("DeleteTextTransaction::MaybeCreate() failed");
360 return NS_ERROR_FAILURE;
362 AppendChild(*deleteTextTransaction);
363 return NS_OK;
366 nsresult
367 DeleteRangeTransaction::AppendTransactionsToDeleteNodesWhoseEndBoundaryIn(
368 const EditorRawDOMRange& aRangeToDelete) {
369 if (NS_WARN_IF(!mEditorBase)) {
370 return NS_ERROR_NOT_AVAILABLE;
373 ContentSubtreeIterator subtreeIter;
374 nsresult rv = subtreeIter.Init(aRangeToDelete.StartRef().ToRawRangeBoundary(),
375 aRangeToDelete.EndRef().ToRawRangeBoundary());
376 if (NS_FAILED(rv)) {
377 NS_WARNING("ContentSubtreeIterator::Init() failed");
378 return rv;
381 for (; !subtreeIter.IsDone(); subtreeIter.Next()) {
382 nsINode* node = subtreeIter.GetCurrentNode();
383 if (NS_WARN_IF(!node) || NS_WARN_IF(!node->IsContent())) {
384 return NS_ERROR_FAILURE;
387 if (NS_WARN_IF(!HTMLEditUtils::IsRemovableNode(*node->AsContent()))) {
388 continue;
390 RefPtr<DeleteNodeTransaction> deleteNodeTransaction =
391 DeleteNodeTransaction::MaybeCreate(*mEditorBase, *node->AsContent());
392 if (deleteNodeTransaction) {
393 AppendChild(*deleteNodeTransaction);
396 return NS_OK;
399 } // namespace mozilla