Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=78: */
/* 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 "mozilla/HTMLEditor.h"
#include <string.h>
#include "HTMLEditUtils.h"
#include "InternetCiter.h"
#include "WSRunObject.h"
#include "mozilla/dom/Comment.h"
#include "mozilla/dom/DataTransfer.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/FileReader.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/Base64.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/EditAction.h"
#include "mozilla/EditorDOMPoint.h"
#include "mozilla/EditorUtils.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/Preferences.h"
#include "mozilla/Result.h"
#include "mozilla/SelectionState.h"
#include "mozilla/TypeInState.h"
#include "nsAString.h"
#include "nsCOMPtr.h"
#include "nsCRTGlue.h" // for CRLF
#include "nsComponentManagerUtils.h"
#include "nsIScriptError.h"
#include "nsContentUtils.h"
#include "nsDebug.h"
#include "nsDependentSubstring.h"
#include "nsError.h"
#include "nsGkAtoms.h"
#include "nsIClipboard.h"
#include "nsIContent.h"
#include "mozilla/dom/Document.h"
#include "nsIDocumentEncoder.h"
#include "nsIFile.h"
#include "nsIInputStream.h"
#include "nsNameSpaceManager.h"
#include "nsINode.h"
#include "nsIParserUtils.h"
#include "nsIPrincipal.h"
#include "nsISupportsImpl.h"
#include "nsISupportsPrimitives.h"
#include "nsISupportsUtils.h"
#include "nsITransferable.h"
#include "nsIVariant.h"
#include "nsLinebreakConverter.h"
#include "nsLiteralString.h"
#include "nsNetUtil.h"
#include "nsRange.h"
#include "nsReadableUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsStreamUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsStringIterator.h"
#include "nsTreeSanitizer.h"
#include "nsXPCOM.h"
#include "nscore.h"
#include "nsContentUtils.h"
#include "nsQueryObject.h"
class nsAtom;
class nsILoadContext;
class nsISupports;
namespace mozilla {
using namespace dom;
#define kInsertCookie "_moz_Insert Here_moz_"
// some little helpers
static bool FindIntegerAfterString(const char* aLeadingString,
const nsCString& aCStr,
int32_t& foundNumber);
static void RemoveFragComments(nsCString& aStr);
nsresult HTMLEditor::LoadHTML(const nsAString& aInputString) {
MOZ_ASSERT(IsEditActionDataAvailable());
if (NS_WARN_IF(!mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
// force IME commit; set up rules sniffing and batching
DebugOnly<nsresult> rvIgnored = CommitComposition();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"EditorBase::CommitComposition() failed, but ignored");
if (NS_WARN_IF(Destroyed())) {
return NS_ERROR_EDITOR_DESTROYED;
}
AutoPlaceholderBatch treatAsOneTransaction(*this,
ScrollSelectionIntoView::Yes);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
*this, EditSubAction::eInsertHTMLSource, nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::EnsureNoPaddingBRElementForEmptyEditor() failed");
return rv;
}
// Delete Selection, but only if it isn't collapsed, see bug #106269
if (!SelectionRef().IsCollapsed()) {
nsresult rv = DeleteSelectionAsSubAction(eNone, eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return rv;
}
}
// Get the first range in the selection, for context:
RefPtr<const nsRange> range = SelectionRef().GetRangeAt(0);
if (NS_WARN_IF(!range)) {
return NS_ERROR_FAILURE;
}
// Create fragment for pasted HTML.
ErrorResult error;
RefPtr<DocumentFragment> documentFragment =
range->CreateContextualFragment(aInputString, error);
if (error.Failed()) {
NS_WARNING("nsRange::CreateContextualFragment() failed");
return error.StealNSResult();
}
// Put the fragment into the document at start of selection.
EditorDOMPoint pointToInsert(range->StartRef());
// XXX We need to make pointToInsert store offset for keeping traditional
// behavior since using only child node to pointing insertion point
// changes the behavior when inserted child is moved by mutation
// observer. We need to investigate what we should do here.
Unused << pointToInsert.Offset();
for (nsCOMPtr<nsIContent> contentToInsert = documentFragment->GetFirstChild();
contentToInsert; contentToInsert = documentFragment->GetFirstChild()) {
rv = InsertNodeWithTransaction(*contentToInsert, pointToInsert);
if (NS_FAILED(rv)) {
NS_WARNING("EditorBase::InsertNodeWithTransaction() failed");
return rv;
}
// XXX If the inserted node has been moved by mutation observer,
// incrementing offset will cause odd result. Next new node
// will be inserted after existing node and the offset will be
// overflown from the container node.
pointToInsert.Set(pointToInsert.GetContainer(), pointToInsert.Offset() + 1);
if (NS_WARN_IF(!pointToInsert.Offset())) {
// Append the remaining children to the container if offset is
// overflown.
pointToInsert.SetToEndOf(pointToInsert.GetContainer());
}
}
return NS_OK;
}
NS_IMETHODIMP HTMLEditor::InsertHTML(const nsAString& aInString) {
nsresult rv = InsertHTMLAsAction(aInString);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::InsertHTMLAsAction() failed");
return rv;
}
nsresult HTMLEditor::InsertHTMLAsAction(const nsAString& aInString,
nsIPrincipal* aPrincipal) {
AutoEditActionDataSetter editActionData(*this, EditAction::eInsertHTML,
aPrincipal);
nsresult rv = editActionData.CanHandleAndMaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"CanHandleAndMaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
rv = DoInsertHTMLWithContext(aInString, u""_ns, u""_ns, u""_ns, nullptr,
EditorDOMPoint(), true, true, false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::DoInsertHTMLWithContext() failed");
return EditorBase::ToGenericNSResult(rv);
}
class MOZ_STACK_CLASS HTMLEditor::HTMLWithContextInserter final {
public:
MOZ_CAN_RUN_SCRIPT explicit HTMLWithContextInserter(HTMLEditor& aHTMLEditor)
: mHTMLEditor(aHTMLEditor) {}
HTMLWithContextInserter() = delete;
HTMLWithContextInserter(const HTMLWithContextInserter&) = delete;
HTMLWithContextInserter(HTMLWithContextInserter&&) = delete;
MOZ_CAN_RUN_SCRIPT nsresult Run(const nsAString& aInputString,
const nsAString& aContextStr,
const nsAString& aInfoStr,
const EditorDOMPoint& aPointToInsert,
bool aDoDeleteSelection, bool aTrustedInput,
bool aClearStyle);
private:
class FragmentFromPasteCreator;
class FragmentParser;
/**
* CollectTopMostChildContentsCompletelyInRange() collects topmost child
* contents which are completely in the given range.
* For example, if the range points a node with its container node, the
* result is only the node (meaning does not include its descendants).
* If the range starts start of a node and ends end of it, and if the node
* does not have children, returns no nodes, otherwise, if the node has
* some children, the result includes its all children (not including their
* descendants).
*
* @param aStartPoint Start point of the range.
* @param aEndPoint End point of the range.
* @param aOutArrayOfContents [Out] Topmost children which are completely in
* the range.
*/
static void CollectTopMostChildContentsCompletelyInRange(
const EditorRawDOMPoint& aStartPoint, const EditorRawDOMPoint& aEndPoint,
nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents);
/**
* @return nullptr, if there's no invisible `<br>`.
*/
HTMLBRElement* GetInvisibleBRElementAtPoint(
const EditorDOMPoint& aPointToInsert) const;
EditorDOMPoint GetNewCaretPointAfterInsertingHTML(
const EditorDOMPoint& aLastInsertedPoint) const;
/**
* @return error result or the last inserted point. The latter is only set, if
* content was inserted.
*/
[[nodiscard]] MOZ_CAN_RUN_SCRIPT Result<EditorDOMPoint, nsresult>
InsertContents(
const EditorDOMPoint& aPointToInsert,
nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents,
const nsINode* aFragmentAsNode);
/**
* @param aContextStr as indicated by nsITransferable's kHTMLContext.
* @param aInfoStr as indicated by nsITransferable's kHTMLInfo.
*/
nsresult CreateDOMFragmentFromPaste(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, nsCOMPtr<nsINode>* aOutFragNode,
nsCOMPtr<nsINode>* aOutStartNode, nsCOMPtr<nsINode>* aOutEndNode,
int32_t* aOutStartOffset, int32_t* aOutEndOffset,
bool aTrustedInput) const;
[[nodiscard]] MOZ_CAN_RUN_SCRIPT nsresult MoveCaretOutsideOfLink(
Element& aLinkElement, const EditorDOMPoint& aPointToPutCaret);
HTMLEditor& mHTMLEditor;
};
class MOZ_STACK_CLASS
HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator final {
public:
nsresult Run(const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, const nsAString& aInfoStr,
nsCOMPtr<nsINode>* aOutFragNode,
nsCOMPtr<nsINode>* aOutStartNode, nsCOMPtr<nsINode>* aOutEndNode,
bool aTrustedInput) const;
private:
nsresult CreateDocumentFragmentAndGetParentOfPastedHTMLInContext(
const Document& aDocument, const nsAString& aInputString,
const nsAString& aContextStr, bool aTrustedInput,
nsCOMPtr<nsINode>& aParentNodeOfPastedHTMLInContext,
RefPtr<DocumentFragment>& aDocumentFragmentToInsert) const;
static nsAtom* DetermineContextLocalNameForParsingPastedHTML(
const nsIContent* aParentContentOfPastedHTMLInContext);
static bool FindTargetNodeOfContextForPastedHTMLAndRemoveInsertionCookie(
nsINode& aStart, nsCOMPtr<nsINode>& aResult);
static bool IsInsertionCookie(const nsIContent& aContent);
/**
* @param aDocumentFragmentForContext contains the merged result.
*/
static nsresult MergeAndPostProcessFragmentsForPastedHTMLAndContext(
DocumentFragment& aDocumentFragmentForPastedHTML,
DocumentFragment& aDocumentFragmentForContext,
nsIContent& aTargetContentOfContextForPastedHTML);
/**
* @param aInfoStr as indicated by nsITransferable's kHTMLInfo.
*/
[[nodiscard]] static nsresult MoveStartAndEndAccordingToHTMLInfo(
const nsAString& aInfoStr, nsCOMPtr<nsINode>* aOutStartNode,
nsCOMPtr<nsINode>* aOutEndNode);
static nsresult PostProcessFragmentForPastedHTMLWithoutContext(
DocumentFragment& aDocumentFragmentForPastedHTML);
static nsresult PreProcessContextDocumentFragmentForMerging(
DocumentFragment& aDocumentFragmentForContext);
static void RemoveHeadChildAndStealBodyChildsChildren(nsINode& aNode);
enum class NodesToRemove {
eAll,
eOnlyListItems /*!< List items are always block-level elements, hence such
whitespace-only nodes are always invisible. */
};
static nsresult
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
nsIContent& aNode, NodesToRemove aNodesToRemove);
};
HTMLBRElement*
HTMLEditor::HTMLWithContextInserter::GetInvisibleBRElementAtPoint(
const EditorDOMPoint& aPointToInsert) const {
WSRunScanner wsRunScannerAtInsertionPoint(mHTMLEditor, aPointToInsert);
if (wsRunScannerAtInsertionPoint.GetEndReasonContent() &&
wsRunScannerAtInsertionPoint.GetEndReasonContent()->IsHTMLElement(
nsGkAtoms::br) &&
!mHTMLEditor.IsVisibleBRElement(
wsRunScannerAtInsertionPoint.EndReasonBRElementPtr())) {
return wsRunScannerAtInsertionPoint.EndReasonBRElementPtr();
}
return nullptr;
}
EditorDOMPoint
HTMLEditor::HTMLWithContextInserter::GetNewCaretPointAfterInsertingHTML(
const EditorDOMPoint& aLastInsertedPoint) const {
EditorDOMPoint pointToPutCaret;
// but don't cross tables
nsIContent* containerContent = nullptr;
if (!HTMLEditUtils::IsTable(aLastInsertedPoint.GetChild())) {
containerContent =
mHTMLEditor.GetLastEditableLeaf(*aLastInsertedPoint.GetChild());
if (containerContent) {
Element* mostDistantInclusiveAncestorTableElement = nullptr;
for (Element* maybeTableElement =
containerContent->GetAsElementOrParentElement();
maybeTableElement &&
maybeTableElement != aLastInsertedPoint.GetChild();
maybeTableElement = maybeTableElement->GetParentElement()) {
if (HTMLEditUtils::IsTable(maybeTableElement)) {
mostDistantInclusiveAncestorTableElement = maybeTableElement;
}
}
// If we're in table elements, we should put caret into the most ancestor
// table element.
if (mostDistantInclusiveAncestorTableElement) {
containerContent = mostDistantInclusiveAncestorTableElement;
}
}
}
// If we are not in table elements, we should put caret in the last inserted
// node.
if (!containerContent) {
containerContent = aLastInsertedPoint.GetChild();
}
// If the container is a text node or a container element except `<table>`
// element, put caret a end of it.
if (containerContent->IsText() ||
(HTMLEditUtils::IsContainerNode(*containerContent) &&
!HTMLEditUtils::IsTable(containerContent))) {
pointToPutCaret.SetToEndOf(containerContent);
}
// Otherwise, i.e., it's an atomic element, `<table>` element or data node,
// put caret after it.
else {
pointToPutCaret.Set(containerContent);
DebugOnly<bool> advanced = pointToPutCaret.AdvanceOffset();
NS_WARNING_ASSERTION(advanced, "Failed to advance offset from found node");
}
// Make sure we don't end up with selection collapsed after an invisible
// `<br>` element.
WSRunScanner wsRunScannerAtCaret(mHTMLEditor, pointToPutCaret);
if (wsRunScannerAtCaret
.ScanPreviousVisibleNodeOrBlockBoundaryFrom(pointToPutCaret)
.ReachedBRElement() &&
!mHTMLEditor.IsVisibleBRElement(
wsRunScannerAtCaret.GetStartReasonContent())) {
WSRunScanner wsRunScannerAtStartReason(
mHTMLEditor,
EditorDOMPoint(wsRunScannerAtCaret.GetStartReasonContent()));
WSScanResult backwardScanFromPointToCaretResult =
wsRunScannerAtStartReason.ScanPreviousVisibleNodeOrBlockBoundaryFrom(
pointToPutCaret);
if (backwardScanFromPointToCaretResult.InNormalWhiteSpacesOrText()) {
pointToPutCaret = backwardScanFromPointToCaretResult.Point();
} else if (backwardScanFromPointToCaretResult.ReachedSpecialContent()) {
// XXX In my understanding, this is odd. The end reason may not be
// same as the reached special content because the equality is
// guaranteed only when ReachedCurrentBlockBoundary() returns true.
// However, looks like that this code assumes that
// GetStartReasonContent() returns the content.
NS_ASSERTION(wsRunScannerAtStartReason.GetStartReasonContent() ==
backwardScanFromPointToCaretResult.GetContent(),
"Start reason is not the reached special content");
pointToPutCaret.SetAfter(
wsRunScannerAtStartReason.GetStartReasonContent());
}
}
return pointToPutCaret;
}
nsresult HTMLEditor::DoInsertHTMLWithContext(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, const nsAString& aFlavor, Document* aSourceDoc,
const EditorDOMPoint& aPointToInsert, bool aDoDeleteSelection,
bool aTrustedInput, bool aClearStyle) {
HTMLWithContextInserter htmlWithContextInserter(*this);
return htmlWithContextInserter.Run(aInputString, aContextStr, aInfoStr,
aPointToInsert, aDoDeleteSelection,
aTrustedInput, aClearStyle);
}
nsresult HTMLEditor::HTMLWithContextInserter::Run(
const nsAString& aInputString, const nsAString& aContextStr,
const nsAString& aInfoStr, const EditorDOMPoint& aPointToInsert,
bool aDoDeleteSelection, bool aTrustedInput, bool aClearStyle) {
MOZ_ASSERT(mHTMLEditor.IsEditActionDataAvailable());
if (NS_WARN_IF(!mHTMLEditor.mInitSucceeded)) {
return NS_ERROR_NOT_INITIALIZED;
}
// force IME commit; set up rules sniffing and batching
mHTMLEditor.CommitComposition();
AutoPlaceholderBatch treatAsOneTransaction(mHTMLEditor,
ScrollSelectionIntoView::Yes);
IgnoredErrorResult ignoredError;
AutoEditSubActionNotifier startToHandleEditSubAction(
MOZ_KnownLive(mHTMLEditor), EditSubAction::ePasteHTMLContent,
nsIEditor::eNext, ignoredError);
if (NS_WARN_IF(ignoredError.ErrorCodeIs(NS_ERROR_EDITOR_DESTROYED))) {
return ignoredError.StealNSResult();
}
NS_WARNING_ASSERTION(
!ignoredError.Failed(),
"HTMLEditor::OnStartToHandleTopLevelEditSubAction() failed, but ignored");
ignoredError.SuppressException();
// create a dom document fragment that represents the structure to paste
nsCOMPtr<nsINode> fragmentAsNode, streamStartParent, streamEndParent;
int32_t streamStartOffset = 0, streamEndOffset = 0;
nsresult rv = CreateDOMFragmentFromPaste(
aInputString, aContextStr, aInfoStr, address_of(fragmentAsNode),
address_of(streamStartParent), address_of(streamEndParent),
&streamStartOffset, &streamEndOffset, aTrustedInput);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::CreateDOMFragmentFromPaste() "
"failed");
return rv;
}
// if we have a destination / target node, we want to insert there
// rather than in place of the selection
// ignore aDoDeleteSelection here if aPointToInsert is not set since deletion
// will also occur later; this block is intended to cover the various
// scenarios where we are dropping in an editor (and may want to delete
// the selection before collapsing the selection in the new destination)
if (aPointToInsert.IsSet()) {
rv = MOZ_KnownLive(mHTMLEditor)
.PrepareToInsertContent(aPointToInsert, aDoDeleteSelection);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::PrepareToInsertContent() failed");
return rv;
}
}
// we need to recalculate various things based on potentially new offsets
// this is work to be completed at a later date (probably by jfrancis)
AutoTArray<OwningNonNull<nsIContent>, 64> arrayOfTopMostChildContents;
// If we have stream start point information, lets use it and end point.
// Otherwise, we should make a range all over the document fragment.
EditorRawDOMPoint streamStartPoint =
streamStartParent
? EditorRawDOMPoint(streamStartParent, streamStartOffset)
: EditorRawDOMPoint(fragmentAsNode, 0);
EditorRawDOMPoint streamEndPoint =
streamStartParent ? EditorRawDOMPoint(streamEndParent, streamEndOffset)
: EditorRawDOMPoint::AtEndOf(fragmentAsNode);
Unused << streamStartPoint;
Unused << streamEndPoint;
HTMLWithContextInserter::CollectTopMostChildContentsCompletelyInRange(
EditorRawDOMPoint(streamStartParent, streamStartOffset),
EditorRawDOMPoint(streamEndParent, streamEndOffset),
arrayOfTopMostChildContents);
if (arrayOfTopMostChildContents.IsEmpty()) {
// We aren't inserting anything, but if aDoDeleteSelection is set, we do
// want to delete everything.
// XXX What will this do? We've already called DeleteSelectionAsSubAtion()
// above if insertion point is specified.
if (aDoDeleteSelection) {
nsresult rv =
MOZ_KnownLive(mHTMLEditor).DeleteSelectionAsSubAction(eNone, eStrip);
if (NS_FAILED(rv)) {
NS_WARNING(
"EditorBase::DeleteSelectionAsSubAction(eNone, eStrip) failed");
return rv;
}
}
return NS_OK;
}
// Are there any table elements in the list?
// check for table cell selection mode
bool cellSelectionMode =
HTMLEditUtils::IsInTableCellSelectionMode(mHTMLEditor.SelectionRef());
if (cellSelectionMode) {
// do we have table content to paste? If so, we want to delete
// the selected table cells and replace with new table elements;
// but if not we want to delete _contents_ of cells and replace
// with non-table elements. Use cellSelectionMode bool to
// indicate results.
if (!HTMLEditUtils::IsAnyTableElement(arrayOfTopMostChildContents[0])) {
cellSelectionMode = false;
}
}
if (!cellSelectionMode) {
rv = MOZ_KnownLive(mHTMLEditor).DeleteSelectionAndPrepareToCreateNode();
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteSelectionAndPrepareToCreateNode() failed");
return rv;
}
if (aClearStyle) {
// pasting does not inherit local inline styles
EditResult result =
MOZ_KnownLive(mHTMLEditor)
.ClearStyleAt(
EditorDOMPoint(mHTMLEditor.SelectionRef().AnchorRef()),
nullptr, nullptr, SpecifiedStyle::Preserve);
if (result.Failed()) {
NS_WARNING("HTMLEditor::ClearStyleAt() failed");
return result.Rv();
}
}
} else {
// Delete whole cells: we will replace with new table content.
// Braces for artificial block to scope AutoSelectionRestorer.
// Save current selection since DeleteTableCellWithTransaction() perturbs
// it.
{
AutoSelectionRestorer restoreSelectionLater(mHTMLEditor);
rv = MOZ_KnownLive(mHTMLEditor).DeleteTableCellWithTransaction(1);
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteTableCellWithTransaction(1) failed");
return rv;
}
}
// collapse selection to beginning of deleted table content
IgnoredErrorResult ignoredError;
mHTMLEditor.SelectionRef().CollapseToStart(ignoredError);
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"Selection::Collapse() failed, but ignored");
}
// XXX Why don't we test this first?
if (mHTMLEditor.IsReadonly()) {
return NS_OK;
}
EditActionResult result = mHTMLEditor.CanHandleHTMLEditSubAction();
if (result.Failed() || result.Canceled()) {
NS_WARNING_ASSERTION(result.Succeeded(),
"HTMLEditor::CanHandleHTMLEditSubAction() failed");
return result.Rv();
}
mHTMLEditor.UndefineCaretBidiLevel();
rv = MOZ_KnownLive(mHTMLEditor).EnsureNoPaddingBRElementForEmptyEditor();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
"failed, but ignored");
if (NS_SUCCEEDED(rv) && mHTMLEditor.SelectionRef().IsCollapsed()) {
nsresult rv =
MOZ_KnownLive(mHTMLEditor).EnsureCaretNotAfterPaddingBRElement();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::EnsureCaretNotAfterPaddingBRElement() "
"failed, but ignored");
if (NS_SUCCEEDED(rv)) {
nsresult rv = MOZ_KnownLive(mHTMLEditor).PrepareInlineStylesForCaret();
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::PrepareInlineStylesForCaret() failed, but ignored");
}
}
// Adjust position based on the first node we are going to insert.
EditorDOMPoint pointToInsert = mHTMLEditor.GetBetterInsertionPointFor(
arrayOfTopMostChildContents[0],
EditorBase::GetStartPoint(mHTMLEditor.SelectionRef()));
if (!pointToInsert.IsSet()) {
NS_WARNING("HTMLEditor::GetBetterInsertionPointFor() failed");
return NS_ERROR_FAILURE;
}
// Remove invisible `<br>` element at the point because if there is a `<br>`
// element at end of what we paste, it will make the existing invisible
// `<br>` element visible.
if (HTMLBRElement* invisibleBRElement =
GetInvisibleBRElementAtPoint(pointToInsert)) {
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsert);
nsresult rv =
MOZ_KnownLive(mHTMLEditor)
.DeleteNodeWithTransaction(MOZ_KnownLive(*invisibleBRElement));
if (NS_FAILED(rv)) {
NS_WARNING("HTMLEditor::DeleteNodeWithTransaction() failed.");
return rv;
}
}
const bool insertionPointWasInLink =
!!HTMLEditor::GetLinkElement(pointToInsert.GetContainer());
if (pointToInsert.IsInTextNode()) {
SplitNodeResult splitNodeResult =
MOZ_KnownLive(mHTMLEditor)
.SplitNodeDeepWithTransaction(
MOZ_KnownLive(*pointToInsert.GetContainerAsContent()),
pointToInsert, SplitAtEdges::eAllowToCreateEmptyContainer);
if (splitNodeResult.Failed()) {
NS_WARNING("HTMLEditor::SplitNodeDeepWithTransaction() failed");
return splitNodeResult.Rv();
}
pointToInsert = splitNodeResult.SplitPoint();
if (!pointToInsert.IsSet()) {
NS_WARNING(
"HTMLEditor::SplitNodeDeepWithTransaction() didn't return split "
"point");
return NS_ERROR_FAILURE;
}
}
{ // Block only for AutoHTMLFragmentBoundariesFixer to hide it from the
// following code. Note that it may modify arrayOfTopMostChildContents.
AutoHTMLFragmentBoundariesFixer fixPiecesOfTablesAndLists(
arrayOfTopMostChildContents);
}
MOZ_ASSERT(pointToInsert.GetContainer()->GetChildAt_Deprecated(
pointToInsert.Offset()) == pointToInsert.GetChild());
const Result<EditorDOMPoint, nsresult> lastInsertedPoint = InsertContents(
pointToInsert, arrayOfTopMostChildContents, fragmentAsNode);
if (lastInsertedPoint.isErr()) {
NS_WARNING("HTMLWithContextInserter::InsertContents() failed.");
return lastInsertedPoint.inspectErr();
}
if (!lastInsertedPoint.inspect().IsSet()) {
return NS_OK;
}
const EditorDOMPoint pointToPutCaret =
GetNewCaretPointAfterInsertingHTML(lastInsertedPoint.inspect());
// Now collapse the selection to the end of what we just inserted.
rv = MOZ_KnownLive(mHTMLEditor).CollapseSelectionTo(pointToPutCaret);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::CollapseSelectionTo() failed, but ignored");
// If we didn't start from an `<a href>` element, we should not keep
// caret in the link to make users type something outside the link.
if (insertionPointWasInLink) {
return NS_OK;
}
RefPtr<Element> linkElement = GetLinkElement(pointToPutCaret.GetContainer());
if (!linkElement) {
return NS_OK;
}
rv = MoveCaretOutsideOfLink(*linkElement, pointToPutCaret);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::MoveCaretOutsideOfLink "
"failed.");
return rv;
}
return NS_OK;
}
Result<EditorDOMPoint, nsresult>
HTMLEditor::HTMLWithContextInserter::InsertContents(
const EditorDOMPoint& aPointToInsert,
nsTArray<OwningNonNull<nsIContent>>& aArrayOfTopMostChildContents,
const nsINode* aFragmentAsNode) {
EditorDOMPoint pointToInsert{aPointToInsert};
// Loop over the node list and paste the nodes:
RefPtr<Element> blockElement =
pointToInsert.IsInContentNode()
? HTMLEditUtils::GetInclusiveAncestorBlockElement(
*pointToInsert.ContainerAsContent())
: nullptr;
EditorDOMPoint lastInsertedPoint;
nsCOMPtr<nsIContent> insertedContextParentContent;
for (OwningNonNull<nsIContent>& content : aArrayOfTopMostChildContents) {
if (NS_WARN_IF(content == aFragmentAsNode) ||
NS_WARN_IF(content->IsHTMLElement(nsGkAtoms::body))) {
return Err(NS_ERROR_FAILURE);
}
if (insertedContextParentContent) {
// If we had to insert something higher up in the paste hierarchy,
// we want to skip any further paste nodes that descend from that.
// Else we will paste twice.
// XXX This check may be really expensive. Cannot we check whether
// the node's `ownerDocument` is the `aFragmentAsNode` or not?
// XXX If content was moved to outside of insertedContextParentContent
// by mutation event listeners, we will anyway duplicate it.
if (EditorUtils::IsDescendantOf(*content,
*insertedContextParentContent)) {
continue;
}
}
// If a `<table>` or `<tr>` element on the clipboard, and pasting it into
// a `<table>` or `<tr>` element, insert only the appropriate children
// instead.
bool inserted = false;
if (HTMLEditUtils::IsTableRow(content) &&
HTMLEditUtils::IsTableRow(pointToInsert.GetContainer()) &&
(HTMLEditUtils::IsTable(content) ||
HTMLEditUtils::IsTable(pointToInsert.GetContainer()))) {
// Move children of current node to the insertion point.
for (nsCOMPtr<nsIContent> firstChild = content->GetFirstChild();
firstChild; firstChild = content->GetFirstChild()) {
EditorDOMPoint insertedPoint =
MOZ_KnownLive(mHTMLEditor)
.InsertNodeIntoProperAncestorWithTransaction(
*firstChild, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (!insertedPoint.IsSet()) {
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) "
"failed");
break;
}
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node to same
// position.
inserted = true;
if (firstChild->GetParentElement() == insertedPoint.GetContainer()) {
lastInsertedPoint.Set(firstChild);
pointToInsert = insertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSet());
}
}
}
// If a list element on the clipboard, and pasting it into a list or
// list item element, insert the appropriate children instead. I.e.,
// merge the list elements instead of pasting as a sublist.
else if (HTMLEditUtils::IsAnyListElement(content) &&
(HTMLEditUtils::IsAnyListElement(pointToInsert.GetContainer()) ||
HTMLEditUtils::IsListItem(pointToInsert.GetContainer()))) {
for (nsCOMPtr<nsIContent> firstChild = content->GetFirstChild();
firstChild; firstChild = content->GetFirstChild()) {
if (HTMLEditUtils::IsListItem(firstChild) ||
HTMLEditUtils::IsAnyListElement(firstChild)) {
// If we're pasting into empty list item, we should remove it
// and past current node into the parent list directly.
// XXX This creates invalid structure if current list item element
// is not proper child of the parent element, or current node
// is a list element.
if (HTMLEditUtils::IsListItem(pointToInsert.GetContainer()) &&
mHTMLEditor.IsEmptyNode(*pointToInsert.GetContainer(), true)) {
NS_WARNING_ASSERTION(pointToInsert.GetContainerParent(),
"Insertion point is out of the DOM tree");
if (pointToInsert.GetContainerParent()) {
pointToInsert.Set(pointToInsert.GetContainer());
MOZ_ASSERT(pointToInsert.IsSet());
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsert);
DebugOnly<nsresult> rvIgnored =
MOZ_KnownLive(mHTMLEditor)
.DeleteNodeWithTransaction(
MOZ_KnownLive(*pointToInsert.GetChild()));
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"HTMLEditor::DeleteNodeWithTransaction() "
"failed, but ignored");
}
}
EditorDOMPoint insertedPoint =
MOZ_KnownLive(mHTMLEditor)
.InsertNodeIntoProperAncestorWithTransaction(
*firstChild, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (!insertedPoint.IsSet()) {
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed");
break;
}
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node to
// same position.
inserted = true;
if (firstChild->GetParentElement() == insertedPoint.GetContainer()) {
lastInsertedPoint.Set(firstChild);
pointToInsert = insertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSet());
}
}
// If the child of current node is not list item nor list element,
// we should remove it from the DOM tree.
else {
AutoEditorDOMPointChildInvalidator lockOffset(pointToInsert);
IgnoredErrorResult ignoredError;
content->RemoveChild(*firstChild, ignoredError);
NS_WARNING_ASSERTION(!ignoredError.Failed(),
"nsINode::RemoveChild() failed, but ignored");
}
}
}
// If pasting into a `<pre>` element and current node is a `<pre>` element,
// move only its children.
else if (blockElement && HTMLEditUtils::IsPre(blockElement) &&
HTMLEditUtils::IsPre(content)) {
// Check for pre's going into pre's.
for (nsCOMPtr<nsIContent> firstChild = content->GetFirstChild();
firstChild; firstChild = content->GetFirstChild()) {
EditorDOMPoint insertedPoint =
MOZ_KnownLive(mHTMLEditor)
.InsertNodeIntoProperAncestorWithTransaction(
*firstChild, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
if (!insertedPoint.IsSet()) {
NS_WARNING(
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed");
break;
}
// If moving node is moved to different place, we should ignore
// this result and keep trying to insert next content node there.
inserted = true;
if (firstChild->GetParentElement() == insertedPoint.GetContainer()) {
lastInsertedPoint.Set(firstChild);
pointToInsert = insertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSet());
}
}
}
// If we haven't inserted current node nor its children, move current node
// to the insertion point.
if (!inserted) {
// MOZ_KnownLive because 'aArrayOfTopMostChildContents' is guaranteed to
// keep it alive.
EditorDOMPoint insertedPoint =
MOZ_KnownLive(mHTMLEditor)
.InsertNodeIntoProperAncestorWithTransaction(
MOZ_KnownLive(content), pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
NS_WARNING_ASSERTION(
insertedPoint.IsSet(),
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but ignored");
if (insertedPoint.IsSet()) {
// Moving node is moved to different place, we should keep trying to
// insert the next content to same position.
if (content->GetParentElement() == insertedPoint.GetContainer()) {
lastInsertedPoint.Set(content);
pointToInsert = insertedPoint;
}
} else {
// Assume failure means no legal parent in the document hierarchy,
// try again with the parent of content in the paste hierarchy.
// FYI: We cannot use `InclusiveAncestorOfType` here because of
// calling `InsertNodeIntoProperAncestorWithTransaction()`.
for (nsCOMPtr<nsIContent> childContent = content; childContent;
childContent = childContent->GetParent()) {
if (NS_WARN_IF(!childContent->GetParent()) ||
NS_WARN_IF(
childContent->GetParent()->IsHTMLElement(nsGkAtoms::body))) {
break;
}
OwningNonNull<nsIContent> oldParentContent(
*childContent->GetParent());
insertedPoint = MOZ_KnownLive(mHTMLEditor)
.InsertNodeIntoProperAncestorWithTransaction(
oldParentContent, pointToInsert,
SplitAtEdges::eDoNotCreateEmptyContainer);
NS_WARNING_ASSERTION(
insertedPoint.IsSet(),
"HTMLEditor::InsertNodeIntoProperAncestorWithTransaction("
"SplitAtEdges::eDoNotCreateEmptyContainer) failed, but ignored");
if (!insertedPoint.IsSet()) {
continue;
}
// Moving node is moved to different place, we should keep trying to
// insert the next content to same position.
if (oldParentContent == insertedPoint.GetContainer()) {
insertedContextParentContent = oldParentContent;
pointToInsert = insertedPoint;
}
break;
}
}
}
if (lastInsertedPoint.IsSet()) {
if (lastInsertedPoint.GetContainer() !=
lastInsertedPoint.GetChild()->GetParentNode()) {
NS_WARNING(
"HTMLEditor::DoInsertHTMLWithContext() got lost insertion point");
return Err(NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE);
}
pointToInsert = lastInsertedPoint.NextPoint();
MOZ_ASSERT(pointToInsert.IsSet());
}
}
return lastInsertedPoint;
}
nsresult HTMLEditor::HTMLWithContextInserter::MoveCaretOutsideOfLink(
Element& aLinkElement, const EditorDOMPoint& aPointToPutCaret) {
MOZ_ASSERT(HTMLEditUtils::IsLink(&aLinkElement));
// The reason why do that instead of just moving caret after it is, the
// link might have ended in an invisible `<br>` element. If so, the code
// above just placed selection inside that. So we need to split it instead.
// XXX Sounds like that it's not really expensive comparing with the reason
// to use SplitNodeDeepWithTransaction() here.
SplitNodeResult splitLinkResult =
MOZ_KnownLive(mHTMLEditor)
.SplitNodeDeepWithTransaction(
aLinkElement, aPointToPutCaret,
SplitAtEdges::eDoNotCreateEmptyContainer);
NS_WARNING_ASSERTION(
splitLinkResult.Succeeded(),
"HTMLEditor::SplitNodeDeepWithTransaction() failed, but ignored");
if (splitLinkResult.GetPreviousNode()) {
EditorRawDOMPoint afterLeftLink(splitLinkResult.GetPreviousNode());
if (afterLeftLink.AdvanceOffset()) {
nsresult rv =
MOZ_KnownLive(mHTMLEditor).CollapseSelectionTo(afterLeftLink);
if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
return NS_ERROR_EDITOR_DESTROYED;
}
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rv),
"HTMLEditor::CollapseSelectionTo() failed, but ignored");
}
}
return NS_OK;
}
// static
Element* HTMLEditor::GetLinkElement(nsINode* aNode) {
if (NS_WARN_IF(!aNode)) {
return nullptr;
}
nsINode* node = aNode;
while (node) {
if (HTMLEditUtils::IsLink(node)) {
return node->AsElement();
}
node = node->GetParentNode();
}
return nullptr;
}
// static
nsresult HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
nsIContent& aNode, NodesToRemove aNodesToRemove) {
if (aNode.TextIsOnlyWhitespace()) {
nsCOMPtr<nsINode> parent = aNode.GetParentNode();
// TODO: presumably, if the parent is a `<pre>` element, the node
// shouldn't be removed.
if (parent) {
if (aNodesToRemove == NodesToRemove::eAll ||
HTMLEditUtils::IsAnyListElement(parent)) {
ErrorResult error;
parent->RemoveChild(aNode, error);
NS_WARNING_ASSERTION(!error.Failed(), "nsINode::RemoveChild() failed");
return error.StealNSResult();
}
return NS_OK;
}
}
if (!aNode.IsHTMLElement(nsGkAtoms::pre)) {
nsCOMPtr<nsIContent> child = aNode.GetLastChild();
while (child) {
nsCOMPtr<nsIContent> previous = child->GetPreviousSibling();
nsresult rv = FragmentFromPasteCreator::
RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces(
*child, aNodesToRemove);
if (NS_FAILED(rv)) {
NS_WARNING(
"HTMLEditor::HTMLWithContextInserter::FragmentFromPasteCreator::"
"RemoveNonPreWhiteSpaceOnlyTextNodesForIgnoringInvisibleWhiteSpaces"
"() "
"failed");
return rv;
}
child = std::move(previous);
}
}
return NS_OK;
}
nsresult HTMLEditor::PrepareTransferable(nsITransferable** aTransferable) {
return NS_OK;
}
class MOZ_STACK_CLASS HTMLEditor::HTMLTransferablePreparer {
public:
HTMLTransferablePreparer(const HTMLEditor& aHTMLEditor,
nsITransferable** aTransferable);
nsresult Run();
private:
void AddDataFlavorsInBestOrder(nsITransferable& aTransferable) const;
const HTMLEditor& mHTMLEditor;
nsITransferable** mTransferable;
};
HTMLEditor::HTMLTransferablePreparer::HTMLTransferablePreparer(
const HTMLEditor& aHTMLEditor, nsITransferable** aTransferable)
: mHTMLEditor{aHTMLEditor}, mTransferable{aTransferable} {
MOZ_ASSERT(mTransferable);
MOZ_ASSERT(!*mTransferable);
}
nsresult HTMLEditor::PrepareHTMLTransferable(
nsITransferable** aTransferable) const {
HTMLTransferablePreparer htmlTransferablePreparer{*this, aTransferable};
return htmlTransferablePreparer.Run();
}
nsresult HTMLEditor::HTMLTransferablePreparer::Run() {
// Create generic Transferable for getting the data
nsresult rv;
RefPtr<nsITransferable> transferable =
do_CreateInstance("@mozilla.org/widget/transferable;1", &rv);
if (NS_FAILED(rv)) {
NS_WARNING("do_CreateInstance() failed to create nsITransferable instance");
return rv;
}
if (!transferable) {
NS_WARNING("do_CreateInstance() returned nullptr, but ignored");
return NS_OK;
}
// Get the nsITransferable interface for getting the data from the clipboard
RefPtr<Document> destdoc = mHTMLEditor.GetDocument();
nsILoadContext* loadContext = destdoc ? destdoc->GetLoadContext() : nullptr;
DebugOnly<nsresult> rvIgnored = transferable->Init(loadContext);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::Init() failed, but ignored");
// See `HTMLEditor::InsertFromTransferable`.
AddDataFlavorsInBestOrder(*transferable);
transferable.forget(mTransferable);
return NS_OK;
}
void HTMLEditor::HTMLTransferablePreparer::AddDataFlavorsInBestOrder(
nsITransferable& aTransferable) const {
// Create the desired DataFlavor for the type of data
// we want to get out of the transferable
// This should only happen in html editors, not plaintext
if (!mHTMLEditor.IsPlaintextEditor()) {
DebugOnly<nsresult> rvIgnored =
aTransferable.AddDataFlavor(kNativeHTMLMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kNativeHTMLMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kHTMLMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kHTMLMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kFileMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kFileMime) failed, but ignored");
switch (Preferences::GetInt("clipboard.paste_image_type", 1)) {
case 0: // prefer JPEG over PNG over GIF encoding
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
break;
case 1: // prefer PNG over JPEG over GIF encoding (default)
default:
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
break;
case 2: // prefer GIF over JPEG over PNG encoding
rvIgnored = aTransferable.AddDataFlavor(kGIFImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kGIFImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPEGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPEGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kJPGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kJPGImageMime) "
"failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kPNGImageMime);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kPNGImageMime) "
"failed, but ignored");
break;
}
}
DebugOnly<nsresult> rvIgnored = aTransferable.AddDataFlavor(kUnicodeMime);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kUnicodeMime) failed, but ignored");
rvIgnored = aTransferable.AddDataFlavor(kMozTextInternal);
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),
"nsITransferable::AddDataFlavor(kMozTextInternal) failed, but ignored");
}
bool FindIntegerAfterString(const char* aLeadingString, const nsCString& aCStr,
int32_t& foundNumber) {
// first obtain offsets from cfhtml str
int32_t numFront = aCStr.Find(aLeadingString);
if (numFront == -1) {
return false;
}
numFront += strlen(aLeadingString);
int32_t numBack = aCStr.FindCharInSet(CRLF, numFront);
if (numBack == -1) {
return false;
}
nsAutoCString numStr(Substring(aCStr, numFront, numBack - numFront));
nsresult errorCode;
foundNumber = numStr.ToInteger(&errorCode);
return true;
}
void RemoveFragComments(nsCString& aStr) {
// remove the StartFragment/EndFragment comments from the str, if present
int32_t startCommentIndx = aStr.Find("<!--StartFragment");
if (startCommentIndx >= 0) {
int32_t startCommentEnd = aStr.Find("-->", false, startCommentIndx);
if (startCommentEnd > startCommentIndx) {
aStr.Cut(startCommentIndx, (startCommentEnd + 3) - startCommentIndx);
}
}
int32_t endCommentIndx = aStr.Find("<!--EndFragment");
if (endCommentIndx >= 0) {
int32_t endCommentEnd = aStr.Find("-->", false, endCommentIndx);
if (endCommentEnd > endCommentIndx) {
aStr.Cut(endCommentIndx, (endCommentEnd + 3) - endCommentIndx);
}
}
}
nsresult HTMLEditor::ParseCFHTML(const nsCString& aCfhtml,
char16_t** aStuffToPaste,
char16_t** aCfcontext) {
// First obtain offsets from cfhtml str.
int32_t startHTML, endHTML, startFragment, endFragment;
if (!FindIntegerAfterString("StartHTML:", aCfhtml, startHTML) ||
startHTML < -1) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("EndHTML:", aCfhtml, endHTML) || endHTML < -1) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("StartFragment:", aCfhtml, startFragment) ||
startFragment < 0) {
return NS_ERROR_FAILURE;
}
if (!FindIntegerAfterString("EndFragment:", aCfhtml, endFragment) ||
startFragment < 0) {
return NS_ERROR_FAILURE;
}
// The StartHTML and EndHTML markers are allowed to be -1 to include
// everything.
// See Reference: MSDN doc entitled "HTML Clipboard Format"
if (startHTML == -1) {
startHTML = aCfhtml.Find("<!--StartFragment-->");
if (startHTML == -1) {
return NS_OK;
}
}
if (endHTML == -1) {
const char endFragmentMarker[] = "<!--EndFragment-->";
endHTML = aCfhtml.Find(endFragmentMarker);
if (endHTML == -1) {
return NS_OK;
}
endHTML += ArrayLength(endFragmentMarker) - 1;
}
// create context string
nsAutoCString contextUTF8(
Substring(aCfhtml, startHTML, startFragment - startHTML) +
"<!--" kInsertCookie "-->"_ns +
Substring(aCfhtml, endFragment, endHTML - endFragment));
// validate startFragment
// make sure it's not in the middle of a HTML tag
// see bug #228879 for more details
int32_t curPos = startFragment;
while (curPos > startHTML) {
if (aCfhtml[curPos] == '>') {
// working backwards, the first thing we see is the end of a tag
// so StartFragment is good, so do nothing.
break;
}
if (aCfhtml[curPos] == '<') {
// if we are at the start, then we want to see the '<'
if (curPos != startFragment) {
// working backwards, the first thing we see is the start of a tag
// so StartFragment is bad, so we need to update it.
NS_ERROR(
"StartFragment byte count in the clipboard looks bad, see bug "
"#228879");
startFragment = curPos - 1;
}
break;
}
curPos--;
}
// create fragment string
nsAutoCString fragmentUTF8(
Substring(aCfhtml, startFragment, endFragment - startFragment));
// remove the StartFragment/EndFragment comments from the fragment, if present
RemoveFragComments(fragmentUTF8);
// remove the StartFragment/EndFragment comments from the context, if present
RemoveFragComments(contextUTF8);
// convert both strings to usc2
const nsString& fragUcs2Str = NS_ConvertUTF8toUTF16(fragmentUTF8);
const nsString& cntxtUcs2Str = NS_ConvertUTF8toUTF16(contextUTF8);
// translate platform linebreaks for fragment
int32_t oldLengthInChars =
fragUcs2Str.Length() + 1; // +1 to include null terminator
int32_t newLengthInChars = 0;
*aStuffToPaste = nsLinebreakConverter::ConvertUnicharLineBreaks(
fragUcs2Str.get(), nsLinebreakConverter::eLinebreakAny,
nsLinebreakConverter::eLinebreakContent, oldLengthInChars,
&newLengthInChars);
if (!*aStuffToPaste) {
NS_WARNING("nsLinebreakConverter::ConvertUnicharLineBreaks() failed");
return NS_ERROR_FAILURE;
}
// translate platform linebreaks for context
oldLengthInChars =
cntxtUcs2Str.Length() + 1; // +1 to include null terminator
newLengthInChars = 0;
*aCfcontext = nsLinebreakConverter::ConvertUnicharLineBreaks(
cntxtUcs2Str.get(), nsLinebreakConverter::eLinebreakAny,
nsLinebreakConverter::eLinebreakContent, oldLengthInChars,
&newLengthInChars);
// it's ok for context to be empty. frag might be whole doc and contain all
// its context.
// we're done!
return NS_OK;
}
static nsresult ImgFromData(const nsACString& aType, const nsACString& aData,
nsString& aOutput) {
aOutput.AssignLiteral("<IMG src=\"data:");
AppendUTF8toUTF16(aType, aOutput);
aOutput.AppendLiteral(";base64,");
nsresult rv = Base64EncodeAppend(aData, aOutput);
if (NS_FAILED(rv)) {
NS_WARNING("Base64Encode() failed");
return rv;
}
aOutput.AppendLiteral("\" alt=\"\" >");
return NS_OK;
}
NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mBlob)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mHTMLEditor)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mSourceDoc)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mPointToInsert)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(HTMLEditor::BlobReader)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBlob)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mHTMLEditor)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSourceDoc)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPointToInsert)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(HTMLEditor::BlobReader, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(HTMLEditor::BlobReader, Release)
HTMLEditor::BlobReader::BlobReader(BlobImpl* aBlob, HTMLEditor* aHTMLEditor,
bool aIsSafe, Document* aSourceDoc,
const EditorDOMPoint& aPointToInsert,
bool aDoDeleteSelection)
: mBlob(aBlob),
mHTMLEditor(aHTMLEditor),
// "beforeinput" event should've been dispatched before we read blob,
// but anyway, we need to clone dataTransfer for "input" event.
mDataTransfer(mHTMLEditor->GetInputEventDataTransfer()),
mSourceDoc(aSourceDoc),
mPointToInsert(aPointToInsert),
mEditAction(aHTMLEditor->GetEditAction()),
mIsSafe(aIsSafe),
mDoDeleteSelection(aDoDeleteSelection),
mNeedsToDispatchBeforeInputEvent(
!mHTMLEditor->HasTriedToDispatchBeforeInputEvent()) {
MOZ_ASSERT(mBlob);
MOZ_ASSERT(mHTMLEditor);
MOZ_ASSERT(mHTMLEditor->IsEditActionDataAvailable());
MOZ_ASSERT(aPointToInsert.IsSet());
MOZ_ASSERT(mDataTransfer);
// Take only offset here since it's our traditional behavior.
AutoEditorDOMPointChildInvalidator storeOnlyWithOffset(mPointToInsert);
}
nsresult HTMLEditor::BlobReader::OnResult(const nsACString& aResult) {
AutoEditActionDataSetter editActionData(*mHTMLEditor, mEditAction);
editActionData.InitializeDataTransfer(mDataTransfer);
if (NS_WARN_IF(!editActionData.CanHandle())) {
return EditorBase::ToGenericNSResult(NS_ERROR_FAILURE);
}
if (NS_WARN_IF(mNeedsToDispatchBeforeInputEvent)) {
nsresult rv = editActionData.MaybeDispatchBeforeInputEvent();
if (NS_FAILED(rv)) {
NS_WARNING_ASSERTION(rv == NS_ERROR_EDITOR_ACTION_CANCELED,
"MaybeDispatchBeforeInputEvent(), failed");
return EditorBase::ToGenericNSResult(rv);
}
} else {
editActionData.MarkAsBeforeInputHasBeenDispatched();
}
nsString blobType;
mBlob->GetType(blobType);
// TODO: This does not work well.
// * If the data is not an image file, this inserts <img> element with odd
// data URI (bug 1610220).
// * If the data is valid image file data, an <img> file is inserted with
// data URI, but it's not loaded (bug 1610219).
NS_ConvertUTF16toUTF8 type(blobType);
nsAutoString stuffToPaste;
nsresult rv = ImgFromData(type, aResult, stuffToPaste);
if (NS_FAILED(rv)) {
NS_WARNING("ImgFormData() failed");
return EditorBase::ToGenericNSResult(rv);
}
AutoPlaceholderBatch treatAsOneTransaction(*mHTMLEditor,
ScrollSelectionIntoView::Yes);
RefPtr<Document> sourceDocument(mSourceDoc);
EditorDOMPoint pointToInsert(mPointToInsert);
rv = MOZ_KnownLive(mHTMLEditor)
->DoInsertHTMLWithContext(stuffToPaste, u""_ns, u""_ns,
NS_LITERAL_STRING_FROM_CSTRING(kFileMime),
sourceDocument, pointToInsert,
mDoDeleteSelection, mIsSafe, false);
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"HTMLEditor::DoInsertHTMLWithContext() failed");
return EditorBase::ToGenericNSResult(rv);
}
nsresult HTMLEditor::BlobReader::OnError(const nsAString& aError) {
AutoTArray<nsString, 1> error;
error.AppendElement(aError);
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Editor"_ns,
mPointToInsert.GetContainer()->OwnerDoc(),
nsContentUtils::eDOM_PROPERTIES,
"EditorFileDropFailed", error);
return NS_OK;
}
class SlurpBlobEventListener final : public nsIDOMEventListener {
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(SlurpBlobEventListener)
explicit SlurpBlobEventListener(HTMLEditor::BlobReader* aListener)
: mListener(aListener) {}
MOZ_CAN_RUN_SCRIPT NS_IMETHOD HandleEvent(Event* aEvent) override;
private:
~SlurpBlobEventListener() = default;
RefPtr<HTMLEditor::BlobReader> mListener;
};
NS_IMPL_CYCLE_COLLECTION(SlurpBlobEventListener, mListener)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(SlurpBlobEventListener)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(SlurpBlobEventListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(SlurpBlobEventListener)
NS_IMETHODIMP SlurpBlobEventListener::HandleEvent(Event* aEvent) {
EventTarget* target = aEvent->GetTarget();
if (!target || !mListener) {
return NS_OK;
}
RefPtr<FileReader> reader = do_QueryObject(target);
if (!reader) {
return NS_OK;
}
EventMessage message = aEvent->WidgetEventPtr()->mMessage;
RefPtr<HTMLEditor::BlobReader> listener(mListener);
if (message == eLoad) {
MOZ_ASSERT(reader->DataFormat() == FileReader::FILE_AS_BINARY);
// The original data has been converted from Latin1 to UTF-16, this just
// undoes that conversion.
DebugOnly<nsresult> rvIgnored =
listener->OnResult(NS_LossyConvertUTF16toASCII(reader->Result()));
NS_WARNING_ASSERTION(
NS_SUCCEEDED(rvIgnored),