/* -*- 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/TextEditRules.h" #include "HTMLEditRules.h" #include "TextEditUtils.h" #include "mozilla/Assertions.h" #include "mozilla/EditAction.h" #include "mozilla/EditorDOMPoint.h" #include "mozilla/EditorUtils.h" #include "mozilla/LookAndFeel.h" #include "mozilla/Preferences.h" #include "mozilla/TextComposition.h" #include "mozilla/TextEditor.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/NodeFilterBinding.h" #include "mozilla/dom/NodeIterator.h" #include "mozilla/dom/Selection.h" #include "nsAString.h" #include "nsCOMPtr.h" #include "nsCRT.h" #include "nsCRTGlue.h" #include "nsComponentManagerUtils.h" #include "nsContentUtils.h" #include "nsDebug.h" #include "nsError.h" #include "nsGkAtoms.h" #include "nsIContent.h" #include "nsIDocumentEncoder.h" #include "nsNameSpaceManager.h" #include "nsINode.h" #include "nsIPlaintextEditor.h" #include "nsISupportsBase.h" #include "nsLiteralString.h" #include "nsTextNode.h" #include "nsUnicharUtils.h" #include "nsIHTMLCollection.h" #include "nsPrintfCString.h" namespace mozilla { using namespace dom; template CreateElementResult TextEditRules::CreateBRInternal(const EditorDOMPoint& aPointToInsert, bool aCreateMozBR); template CreateElementResult TextEditRules::CreateBRInternal(const EditorRawDOMPoint& aPointToInsert, bool aCreateMozBR); #define CANCEL_OPERATION_IF_READONLY_OR_DISABLED \ if (IsReadonly() || IsDisabled()) {\ *aCancel = true; \ return NS_OK; \ } #define CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY_OF_DISABLED \ if (IsReadonly() || IsDisabled()) { \ return EditActionCanceled(NS_OK); \ } /******************************************************** * mozilla::TextEditRules ********************************************************/ TextEditRules::TextEditRules() : mTextEditor(nullptr) , mData(nullptr) , mPasswordIMEIndex(0) , mCachedSelectionOffset(0) , mActionNesting(0) , mLockRulesSniffing(false) , mDidExplicitlySetInterline(false) , mDeleteBidiImmediately(false) , mIsHTMLEditRules(false) , mTopLevelEditSubAction(EditSubAction::eNone) , mLastStart(0) , mLastLength(0) { InitFields(); } void TextEditRules::InitFields() { mTextEditor = nullptr; mPasswordText.Truncate(); mPasswordIMEText.Truncate(); mPasswordIMEIndex = 0; mBogusNode = nullptr; mCachedSelectionNode = nullptr; mCachedSelectionOffset = 0; mActionNesting = 0; mLockRulesSniffing = false; mDidExplicitlySetInterline = false; mDeleteBidiImmediately = false; mTopLevelEditSubAction = EditSubAction::eNone; mTimer = nullptr; mLastStart = 0; mLastLength = 0; } TextEditRules::~TextEditRules() { // do NOT delete mTextEditor here. We do not hold a ref count to // mTextEditor. mTextEditor owns our lifespan. if (mTimer) { mTimer->Cancel(); } } HTMLEditRules* TextEditRules::AsHTMLEditRules() { return mIsHTMLEditRules ? static_cast(this) : nullptr; } const HTMLEditRules* TextEditRules::AsHTMLEditRules() const { return mIsHTMLEditRules ? static_cast(this) : nullptr; } NS_IMPL_CYCLE_COLLECTION(TextEditRules, mBogusNode, mCachedSelectionNode) NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TextEditRules) NS_INTERFACE_MAP_ENTRY(nsITimerCallback) NS_INTERFACE_MAP_ENTRY(nsINamed) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsITimerCallback) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(TextEditRules) NS_IMPL_CYCLE_COLLECTING_RELEASE(TextEditRules) nsresult TextEditRules::Init(TextEditor* aTextEditor) { if (NS_WARN_IF(!aTextEditor)) { return NS_ERROR_INVALID_ARG; } Selection* selection = aTextEditor->GetSelection(); if (NS_WARN_IF(!selection)) { return NS_ERROR_FAILURE; } InitFields(); // We hold a non-refcounted reference back to our editor. mTextEditor = aTextEditor; AutoSafeEditorData setData(*this, *mTextEditor); // Put in a magic
if needed. This method handles null selection, // which should never happen anyway nsresult rv = CreateBogusNodeIfNeeded(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // If the selection hasn't been set up yet, set it up collapsed to the end of // our editable content. if (!SelectionRefPtr()->RangeCount()) { rv = TextEditorRef().CollapseSelectionToEnd(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } if (IsPlaintextEditor()) { // ensure trailing br node rv = CreateTrailingBRIfNeeded(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } // XXX We should use AddBoolVarCache and use "current" value at initializing. mDeleteBidiImmediately = Preferences::GetBool("bidi.edit.delete_immediately", false); return NS_OK; } nsresult TextEditRules::SetInitialValue(const nsAString& aValue) { if (IsPasswordEditor()) { mPasswordText = aValue; } return NS_OK; } nsresult TextEditRules::DetachEditor() { if (mTimer) { mTimer->Cancel(); } mTextEditor = nullptr; return NS_OK; } nsresult TextEditRules::BeforeEdit(EditSubAction aEditSubAction, nsIEditor::EDirection aDirection) { if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } if (mLockRulesSniffing) { return NS_OK; } AutoLockRulesSniffing lockIt(this); mDidExplicitlySetInterline = false; if (!mActionNesting) { // let rules remember the top level action mTopLevelEditSubAction = aEditSubAction; } mActionNesting++; if (aEditSubAction == EditSubAction::eSetText) { // setText replaces all text, so mCachedSelectionNode might be invalid on // AfterEdit. // Since this will be used as start position of spellchecker, we should // use root instead. mCachedSelectionNode = mTextEditor->GetRoot(); mCachedSelectionOffset = 0; } else { Selection* selection = mTextEditor->GetSelection(); if (NS_WARN_IF(!selection)) { return NS_ERROR_FAILURE; } mCachedSelectionNode = selection->GetAnchorNode(); mCachedSelectionOffset = selection->AnchorOffset(); } return NS_OK; } nsresult TextEditRules::AfterEdit(EditSubAction aEditSubAction, nsIEditor::EDirection aDirection) { if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } if (mLockRulesSniffing) { return NS_OK; } AutoLockRulesSniffing lockIt(this); MOZ_ASSERT(mActionNesting>0, "bad action nesting!"); if (!--mActionNesting) { AutoSafeEditorData setData(*this, *mTextEditor); nsresult rv = TextEditorRef().HandleInlineSpellCheck(aEditSubAction, mCachedSelectionNode, mCachedSelectionOffset, nullptr, 0, nullptr, 0); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // no longer uses mCachedSelectionNode, so release it. mCachedSelectionNode = nullptr; // if only trailing
remaining remove it rv = RemoveRedundantTrailingBR(); if (NS_FAILED(rv)) { return rv; } // detect empty doc rv = CreateBogusNodeIfNeeded(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // ensure trailing br node rv = CreateTrailingBRIfNeeded(); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Collapse the selection to the trailing moz-
if it's at the end of // our text node. rv = CollapseSelectionToTrailingBRIfNeeded(); if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) { return NS_ERROR_EDITOR_DESTROYED; } NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to selection to after the text node in TextEditor"); } return NS_OK; } nsresult TextEditRules::WillDoAction(EditSubActionInfo& aInfo, bool* aCancel, bool* aHandled) { if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } MOZ_ASSERT(aCancel); MOZ_ASSERT(aHandled); *aCancel = false; *aHandled = false; AutoSafeEditorData setData(*this, *mTextEditor); // my kingdom for dynamic cast switch (aInfo.mEditSubAction) { case EditSubAction::eInsertLineBreak: { UndefineCaretBidiLevel(); EditActionResult result = WillInsertLineBreak(aInfo.maxLength); if (NS_WARN_IF(result.Failed())) { return result.Rv(); } *aCancel = result.Canceled(); *aHandled = result.Handled(); MOZ_ASSERT(!result.Ignored()); return NS_OK; } case EditSubAction::eInsertText: case EditSubAction::eInsertTextComingFromIME: UndefineCaretBidiLevel(); return WillInsertText(aInfo.mEditSubAction, aCancel, aHandled, aInfo.inString, aInfo.outString, aInfo.maxLength); case EditSubAction::eSetText: UndefineCaretBidiLevel(); return WillSetText(aCancel, aHandled, aInfo.inString, aInfo.maxLength); case EditSubAction::eDeleteSelectedContent: return WillDeleteSelection(aInfo.collapsedAction, aCancel, aHandled); case EditSubAction::eUndo: return WillUndo(aCancel, aHandled); case EditSubAction::eRedo: return WillRedo(aCancel, aHandled); case EditSubAction::eSetTextProperty: return WillSetTextProperty(aCancel, aHandled); case EditSubAction::eRemoveTextProperty: return WillRemoveTextProperty(aCancel, aHandled); case EditSubAction::eComputeTextToOutput: return WillOutputText(aInfo.outputFormat, aInfo.outString, aInfo.flags, aCancel, aHandled); case EditSubAction::eInsertElement: // i had thought this would be html rules only. but we put pre elements // into plaintext mail when doing quoting for reply! doh! return WillInsert(aCancel); default: return NS_ERROR_FAILURE; } } nsresult TextEditRules::DidDoAction(EditSubActionInfo& aInfo, nsresult aResult) { if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } AutoSafeEditorData setData(*this, *mTextEditor); // don't let any txns in here move the selection around behind our back. // Note that this won't prevent explicit selection setting from working. AutoTransactionsConserveSelection dontChangeMySelection(TextEditorRef()); switch (aInfo.mEditSubAction) { case EditSubAction::eDeleteSelectedContent: return DidDeleteSelection(); case EditSubAction::eUndo: return DidUndo(aResult); case EditSubAction::eRedo: return DidRedo(aResult); default: // Don't fail on transactions we don't handle here! return NS_OK; } } bool TextEditRules::DocumentIsEmpty() { bool retVal = false; if (!mTextEditor || NS_FAILED(mTextEditor->IsEmpty(&retVal))) { retVal = true; } return retVal; } nsresult TextEditRules::WillInsert(bool* aCancel) { MOZ_ASSERT(IsEditorDataAvailable()); if (IsReadonly() || IsDisabled()) { if (aCancel) { *aCancel = true; } return NS_OK; } // initialize out param if (aCancel) { *aCancel = false; } // check for the magic content node and delete it if it exists if (!mBogusNode) { return NS_OK; } DebugOnly rv = TextEditorRef().DeleteNodeWithTransaction(*mBogusNode); if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to remove the bogus node"); mBogusNode = nullptr; return NS_OK; } EditActionResult TextEditRules::WillInsertLineBreak(int32_t aMaxLength) { MOZ_ASSERT(IsEditorDataAvailable()); MOZ_ASSERT(!IsSingleLineEditor()); CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY_OF_DISABLED // handle docs with a max length // NOTE, this function copies inString into outString for us. NS_NAMED_LITERAL_STRING(inString, "\n"); nsAutoString outString; bool didTruncate; nsresult rv = TruncateInsertionIfNeeded(&inString.AsString(), &outString, aMaxLength, &didTruncate); if (NS_WARN_IF(NS_FAILED(rv))) { return EditActionIgnored(rv); } if (didTruncate) { return EditActionCanceled(); } // if the selection isn't collapsed, delete it. if (!SelectionRefPtr()->IsCollapsed()) { rv = TextEditorRef().DeleteSelectionAsSubAction(nsIEditor::eNone, nsIEditor::eStrip); if (NS_WARN_IF(!CanHandleEditAction())) { return EditActionIgnored(NS_ERROR_EDITOR_DESTROYED); } if (NS_WARN_IF(NS_FAILED(rv))) { return EditActionIgnored(rv); } } rv = WillInsert(); if (NS_WARN_IF(NS_FAILED(rv))) { return EditActionIgnored(rv); } // get the (collapsed) selection location nsRange* firstRange = SelectionRefPtr()->GetRangeAt(0); if (NS_WARN_IF(!firstRange)) { return EditActionIgnored(NS_ERROR_FAILURE); } EditorRawDOMPoint pointToInsert(firstRange->StartRef()); if (NS_WARN_IF(!pointToInsert.IsSet())) { return EditActionIgnored(NS_ERROR_FAILURE); } MOZ_ASSERT(pointToInsert.IsSetAndValid()); // Don't put text in places that can't have it. if (!pointToInsert.IsInTextNode() && !TextEditorRef().CanContainTag(*pointToInsert.GetContainer(), *nsGkAtoms::textTagName)) { return EditActionIgnored(NS_ERROR_FAILURE); } nsCOMPtr doc = TextEditorRef().GetDocument(); if (NS_WARN_IF(!doc)) { return EditActionIgnored(NS_ERROR_NOT_INITIALIZED); } // Don't change my selection in sub-transactions. AutoTransactionsConserveSelection dontChangeMySelection(TextEditorRef()); // Insert a linefeed character. EditorRawDOMPoint pointAfterInsertedLineBreak; rv = TextEditorRef().InsertTextWithTransaction( *doc, NS_LITERAL_STRING("\n"), pointToInsert, &pointAfterInsertedLineBreak); if (NS_WARN_IF(!pointAfterInsertedLineBreak.IsSet())) { return EditActionIgnored(NS_ERROR_FAILURE); } if (NS_WARN_IF(NS_FAILED(rv))) { return EditActionIgnored(rv); } // set the selection to the correct location MOZ_ASSERT(!pointAfterInsertedLineBreak.GetChild(), "After inserting text into a text node, pointAfterInsertedLineBreak." "GetChild() should be nullptr"); rv = SelectionRefPtr()->Collapse(pointAfterInsertedLineBreak); if (NS_WARN_IF(NS_FAILED(rv))) { return EditActionIgnored(rv); } // see if we're at the end of the editor range EditorRawDOMPoint endPoint(EditorBase::GetEndPoint(*SelectionRefPtr())); if (endPoint == pointAfterInsertedLineBreak) { // SetInterlinePosition(true) means we want the caret to stick to the // content on the "right". We want the caret to stick to whatever is // past the break. This is because the break is on the same line we // were on, but the next content will be on the following line. SelectionRefPtr()->SetInterlinePosition(true, IgnoreErrors()); } return EditActionHandled(); } nsresult TextEditRules::CollapseSelectionToTrailingBRIfNeeded() { MOZ_ASSERT(IsEditorDataAvailable()); // we only need to execute the stuff below if we are a plaintext editor. // html editors have a different mechanism for putting in mozBR's // (because there are a bunch more places you have to worry about it in html) if (!IsPlaintextEditor()) { return NS_OK; } // If there is no selection ranges, we should set to the end of the editor. // This is usually performed in TextEditRules::Init(), however, if the // editor is reframed, this may be called by AfterEdit(). if (!SelectionRefPtr()->RangeCount()) { TextEditorRef().CollapseSelectionToEnd(); if (NS_WARN_IF(!CanHandleEditAction())) { return NS_ERROR_EDITOR_DESTROYED; } } // If we are at the end of the