/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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 "mozilla/ComposerCommandsUpdater.h" #include "mozilla/DebugOnly.h" #include "mozilla/EditAction.h" #include "mozilla/EditorDOMPoint.h" #include "mozilla/EventStates.h" #include "mozilla/mozInlineSpellChecker.h" #include "mozilla/TextEvents.h" #include "nsCRT.h" #include "nsUnicharUtils.h" #include "HTMLEditorEventListener.h" #include "HTMLEditRules.h" #include "HTMLEditUtils.h" #include "HTMLURIRefObject.h" #include "StyleSheetTransactions.h" #include "TextEditUtils.h" #include "TypeInState.h" #include "nsIDOMDocument.h" #include "nsIDocumentInlines.h" #include "nsIDOMEventTarget.h" #include "nsISelectionController.h" #include "nsILinkHandler.h" #include "nsIInlineSpellChecker.h" #include "mozilla/css/Loader.h" #include "nsIContent.h" #include "nsIContentIterator.h" #include "nsIMutableArray.h" #include "nsContentUtils.h" #include "nsIDocumentEncoder.h" #include "nsGenericHTMLElement.h" #include "nsIPresShell.h" #include "nsPresContext.h" #include "nsFocusManager.h" #include "nsPIDOMWindow.h" // netwerk #include "nsIURI.h" #include "nsNetUtil.h" // Misc #include "mozilla/EditorUtils.h" #include "HTMLEditorObjectResizerUtils.h" #include "TextEditorTest.h" #include "WSRunObject.h" #include "nsGkAtoms.h" #include "nsIWidget.h" #include "nsIFrame.h" #include "mozilla/dom/Selection.h" #include "mozilla/dom/DocumentFragment.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/Event.h" #include "mozilla/dom/EventTarget.h" #include "mozilla/dom/HTMLBodyElement.h" #include "nsElementTable.h" #include "nsTextFragment.h" #include "nsContentList.h" #include "mozilla/StyleSheet.h" #include "mozilla/StyleSheetInlines.h" namespace mozilla { using namespace dom; using namespace widget; // Some utilities to handle overloading of "A" tag for link and named anchor. static bool IsLinkTag(const nsString& s) { return s.EqualsIgnoreCase("href"); } static bool IsNamedAnchorTag(const nsString& s) { return s.EqualsIgnoreCase("anchor") || s.EqualsIgnoreCase("namedanchor"); } template EditorDOMPoint HTMLEditor::InsertNodeIntoProperAncestor( nsIContent& aNode, const EditorDOMPoint& aPointToInsert, SplitAtEdges aSplitAtEdges); template EditorDOMPoint HTMLEditor::InsertNodeIntoProperAncestor( nsIContent& aNode, const EditorRawDOMPoint& aPointToInsert, SplitAtEdges aSplitAtEdges); HTMLEditor::HTMLEditor() : mCRInParagraphCreatesParagraph(false) , mCSSAware(false) , mSelectedCellIndex(0) , mIsObjectResizingEnabled(true) , mIsResizing(false) , mPreserveRatio(false) , mResizedObjectIsAnImage(false) , mIsAbsolutelyPositioningEnabled(true) , mResizedObjectIsAbsolutelyPositioned(false) , mGrabberClicked(false) , mIsMoving(false) , mSnapToGridEnabled(false) , mIsInlineTableEditingEnabled(true) , mOriginalX(0) , mOriginalY(0) , mResizedObjectX(0) , mResizedObjectY(0) , mResizedObjectWidth(0) , mResizedObjectHeight(0) , mResizedObjectMarginLeft(0) , mResizedObjectMarginTop(0) , mResizedObjectBorderLeft(0) , mResizedObjectBorderTop(0) , mXIncrementFactor(0) , mYIncrementFactor(0) , mWidthIncrementFactor(0) , mHeightIncrementFactor(0) , mInfoXIncrement(20) , mInfoYIncrement(20) , mPositionedObjectX(0) , mPositionedObjectY(0) , mPositionedObjectWidth(0) , mPositionedObjectHeight(0) , mPositionedObjectMarginLeft(0) , mPositionedObjectMarginTop(0) , mPositionedObjectBorderLeft(0) , mPositionedObjectBorderTop(0) , mGridSize(0) , mDefaultParagraphSeparator( Preferences::GetBool("editor.use_div_for_default_newlines", true) ? ParagraphSeparator::div : ParagraphSeparator::br) { mIsHTMLEditorClass = true; } HTMLEditor::~HTMLEditor() { if (mRules && mRules->AsHTMLEditRules()) { mRules->AsHTMLEditRules()->EndListeningToEditActions(); } mTypeInState = nullptr; if (mLinkHandler && IsInitialized()) { nsCOMPtr ps = GetPresShell(); if (ps && ps->GetPresContext()) { ps->GetPresContext()->SetLinkHandler(mLinkHandler); } } RemoveEventListeners(); HideAnonymousEditingUIs(); } void HTMLEditor::HideAnonymousEditingUIs() { if (mAbsolutelyPositionedObject) { HideGrabber(); } if (mInlineEditedCell) { HideInlineTableEditingUI(); } if (mResizedObject) { HideResizers(); } } NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLEditor) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLEditor, TextEditor) NS_IMPL_CYCLE_COLLECTION_UNLINK(mTypeInState) NS_IMPL_CYCLE_COLLECTION_UNLINK(mComposerCommandsUpdater) NS_IMPL_CYCLE_COLLECTION_UNLINK(mStyleSheets) tmp->HideAnonymousEditingUIs(); NS_IMPL_CYCLE_COLLECTION_UNLINK(mLinkHandler) NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLEditor, TextEditor) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTypeInState) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mComposerCommandsUpdater) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheets) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopLeftHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTopRightHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLeftHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRightHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomLeftHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBottomRightHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mActivatedHandle) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingShadow) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizingInfo) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizedObject) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMouseMotionListenerP) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mResizeEventListenerP) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAbsolutelyPositionedObject) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGrabber) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPositioningShadow) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInlineEditedCell) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnBeforeButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveColumnButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddColumnAfterButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowBeforeButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRemoveRowButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAddRowAfterButton) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLinkHandler) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_ADDREF_INHERITED(HTMLEditor, EditorBase) NS_IMPL_RELEASE_INHERITED(HTMLEditor, EditorBase) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(HTMLEditor) NS_INTERFACE_MAP_ENTRY(nsIHTMLEditor) NS_INTERFACE_MAP_ENTRY(nsIHTMLObjectResizer) NS_INTERFACE_MAP_ENTRY(nsIHTMLAbsPosEditor) NS_INTERFACE_MAP_ENTRY(nsIHTMLInlineTableEditor) NS_INTERFACE_MAP_ENTRY(nsITableEditor) NS_INTERFACE_MAP_ENTRY(nsIEditorStyleSheets) NS_INTERFACE_MAP_ENTRY(nsICSSLoaderObserver) NS_INTERFACE_MAP_ENTRY(nsIMutationObserver) NS_INTERFACE_MAP_END_INHERITING(TextEditor) nsresult HTMLEditor::Init(nsIDocument& aDoc, Element* aRoot, nsISelectionController* aSelCon, uint32_t aFlags, const nsAString& aInitialValue) { MOZ_ASSERT(aInitialValue.IsEmpty(), "Non-empty initial values not supported"); nsresult rulesRv = NS_OK; { // block to scope AutoEditInitRulesTrigger AutoEditInitRulesTrigger rulesTrigger(this, rulesRv); // Init the plaintext editor nsresult rv = TextEditor::Init(aDoc, aRoot, nullptr, aFlags, aInitialValue); if (NS_FAILED(rv)) { return rv; } // Init mutation observer aDoc.AddMutationObserverUnlessExists(this); if (!mRootElement) { UpdateRootElement(); } // disable Composer-only features if (IsMailEditor()) { SetAbsolutePositioningEnabled(false); SetSnapToGridEnabled(false); } // Init the HTML-CSS utils mCSSEditUtils = MakeUnique(this); // disable links nsCOMPtr presShell = GetPresShell(); NS_ENSURE_TRUE(presShell, NS_ERROR_FAILURE); nsPresContext *context = presShell->GetPresContext(); NS_ENSURE_TRUE(context, NS_ERROR_NULL_POINTER); if (!IsPlaintextEditor() && !IsInteractionAllowed()) { mLinkHandler = context->GetLinkHandler(); context->SetLinkHandler(nullptr); } // init the type-in state mTypeInState = new TypeInState(); if (!IsInteractionAllowed()) { // ignore any errors from this in case the file is missing AddOverrideStyleSheet(NS_LITERAL_STRING("resource://gre/res/EditorOverride.css")); } } NS_ENSURE_SUCCESS(rulesRv, rulesRv); return NS_OK; } NS_IMETHODIMP HTMLEditor::PreDestroy(bool aDestroyingFrames) { if (mDidPreDestroy) { return NS_OK; } nsCOMPtr document = GetDocument(); if (document) { document->RemoveMutationObserver(this); } while (!mStyleSheetURLs.IsEmpty()) { RemoveOverrideStyleSheet(mStyleSheetURLs[0]); } // Clean up after our anonymous content -- we don't want these nodes to // stay around (which they would, since the frames have an owning reference). HideAnonymousEditingUIs(); return TextEditor::PreDestroy(aDestroyingFrames); } NS_IMETHODIMP HTMLEditor::NotifySelectionChanged(nsIDOMDocument* aDOMDocument, nsISelection* aSelection, int16_t aReason) { if (NS_WARN_IF(!aDOMDocument) || NS_WARN_IF(!aSelection)) { return NS_ERROR_INVALID_ARG; } RefPtr selection = aSelection->AsSelection(); if (NS_WARN_IF(!selection)) { return NS_ERROR_UNEXPECTED; } if (mTypeInState) { RefPtr typeInState = mTypeInState; typeInState->OnSelectionChange(*selection); // We used a class which derived from nsISelectionListener to call // HTMLEditor::CheckSelectionStateForAnonymousButtons(). The lifetime of // the class was exactly same as mTypeInState. So, call it only when // mTypeInState is not nullptr. if ((aReason & (nsISelectionListener::MOUSEDOWN_REASON | nsISelectionListener::KEYPRESS_REASON | nsISelectionListener::SELECTALL_REASON)) && aSelection) { // the selection changed and we need to check if we have to // hide and/or redisplay resizing handles // FYI: This is an XPCOM method. So, the caller, Selection, guarantees // the lifetime of this instance. So, don't need to grab this with // local variable. CheckSelectionStateForAnonymousButtons(selection); } } if (mComposerCommandsUpdater) { RefPtr updater = mComposerCommandsUpdater; updater->OnSelectionChange(); } return EditorBase::NotifySelectionChanged(aDOMDocument, aSelection, aReason); } void HTMLEditor::UpdateRootElement() { // Use the HTML documents body element as the editor root if we didn't // get a root element during initialization. mRootElement = GetBodyElement(); if (!mRootElement) { nsCOMPtr doc = GetDocument(); if (doc) { // If there is no HTML body element, // we should use the document root element instead. mRootElement = doc->GetDocumentElement(); } // else leave it null, for lack of anything better. } } already_AddRefed HTMLEditor::FindSelectionRoot(nsINode* aNode) { if (NS_WARN_IF(!aNode)) { return nullptr; } NS_PRECONDITION(aNode->IsNodeOfType(nsINode::eDOCUMENT) || aNode->IsContent(), "aNode must be content or document node"); nsCOMPtr doc = aNode->GetComposedDoc(); if (!doc) { return nullptr; } nsCOMPtr content; if (aNode->IsInUncomposedDoc() && (doc->HasFlag(NODE_IS_EDITABLE) || !aNode->IsContent())) { content = doc->GetRootElement(); return content.forget(); } content = aNode->AsContent(); // XXX If we have readonly flag, shouldn't return the element which has // contenteditable="true"? However, such case isn't there without chrome // permission script. if (IsReadonly()) { // We still want to allow selection in a readonly editor. content = do_QueryInterface(GetRoot()); return content.forget(); } if (!content->HasFlag(NODE_IS_EDITABLE)) { // If the content is in read-write state but is not editable itself, // return it as the selection root. if (content->IsElement() && content->AsElement()->State().HasState(NS_EVENT_STATE_MOZ_READWRITE)) { return content.forget(); } return nullptr; } // For non-readonly editors we want to find the root of the editable subtree // containing aContent. content = content->GetEditingHost(); return content.forget(); } void HTMLEditor::CreateEventListeners() { // Don't create the handler twice if (!mEventListener) { mEventListener = new HTMLEditorEventListener(); } } nsresult HTMLEditor::InstallEventListeners() { if (NS_WARN_IF(!IsInitialized()) || NS_WARN_IF(!mEventListener)) { return NS_ERROR_NOT_INITIALIZED; } // NOTE: HTMLEditor doesn't need to initialize mEventTarget here because // the target must be document node and it must be referenced as weak pointer. HTMLEditorEventListener* listener = reinterpret_cast(mEventListener.get()); return listener->Connect(this); } void HTMLEditor::RemoveEventListeners() { if (!IsInitialized()) { return; } nsCOMPtr target = GetDOMEventTarget(); if (target) { // Both mMouseMotionListenerP and mResizeEventListenerP can be // registerd with other targets than the DOM event receiver that // we can reach from here. But nonetheless, unregister the event // listeners with the DOM event reveiver (if it's registerd with // other targets, it'll get unregisterd once the target goes // away). if (mMouseMotionListenerP) { // mMouseMotionListenerP might be registerd either as bubbling or // capturing, unregister by both. target->RemoveEventListener(NS_LITERAL_STRING("mousemove"), mMouseMotionListenerP, false); target->RemoveEventListener(NS_LITERAL_STRING("mousemove"), mMouseMotionListenerP, true); } if (mResizeEventListenerP) { target->RemoveEventListener(NS_LITERAL_STRING("resize"), mResizeEventListenerP, false); } } mMouseMotionListenerP = nullptr; mResizeEventListenerP = nullptr; TextEditor::RemoveEventListeners(); } NS_IMETHODIMP HTMLEditor::SetFlags(uint32_t aFlags) { nsresult rv = TextEditor::SetFlags(aFlags); NS_ENSURE_SUCCESS(rv, rv); // Sets mCSSAware to correspond to aFlags. This toggles whether CSS is // used to style elements in the editor. Note that the editor is only CSS // aware by default in Composer and in the mail editor. mCSSAware = !NoCSS() && !IsMailEditor(); return NS_OK; } NS_IMETHODIMP HTMLEditor::InitRules() { if (!mRules) { // instantiate the rules for the html editor mRules = new HTMLEditRules(); } return mRules->Init(this); } NS_IMETHODIMP HTMLEditor::BeginningOfDocument() { return MaybeCollapseSelectionAtFirstEditableNode(false); } void HTMLEditor::InitializeSelectionAncestorLimit(Selection& aSelection, nsIContent& aAncestorLimit) { // Hack for initializing selection. // HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode() will try to // collapse selection at first editable text node or inline element which // cannot have text nodes as its children. However, selection has already // set into the new editing host by user, we should not change it. For // solving this issue, we should do nothing if selection range is in active // editing host except it's not collapsed at start of the editing host since // aSelection.SetAncestorLimiter(aAncestorLimit) will collapse selection // at start of the new limiter if focus node of aSelection is outside of the // editing host. However, we need to check here if selection is already // collapsed at start of the editing host because it's possible JS to do it. // In such case, we should not modify selection with calling // MaybeCollapseSelectionAtFirstEditableNode(). // Basically, we should try to collapse selection at first editable node // in HTMLEditor. bool tryToCollapseSelectionAtFirstEditableNode = true; if (aSelection.RangeCount() == 1 && aSelection.IsCollapsed()) { Element* editingHost = GetActiveEditingHost(); nsRange* range = aSelection.GetRangeAt(0); if (range->GetStartContainer() == editingHost && !range->StartOffset()) { // JS or user operation has already collapsed selection at start of // the editing host. So, we don't need to try to change selection // in this case. tryToCollapseSelectionAtFirstEditableNode = false; } } EditorBase::InitializeSelectionAncestorLimit(aSelection, aAncestorLimit); // XXX Do we need to check if we still need to change selection? E.g., // we could have already lost focus while we're changing the ancestor // limiter because it may causes "selectionchange" event. if (tryToCollapseSelectionAtFirstEditableNode) { MaybeCollapseSelectionAtFirstEditableNode(true); } } nsresult HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode( bool aIgnoreIfSelectionInEditingHost) { // XXX Why doesn't this check if the document is alive? if (!IsInitialized()) { return NS_ERROR_NOT_INITIALIZED; } RefPtr selection = GetSelection(); if (NS_WARN_IF(!selection)) { return NS_ERROR_NOT_INITIALIZED; } // Use editing host. If you use root element here, selection may be // moved to element, e.g., if there is a text node in