File: HTMLEditorMutationObserver.cpp

package info (click to toggle)
firefox 146.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,653,260 kB
  • sloc: cpp: 7,587,892; javascript: 6,509,455; ansic: 3,755,295; python: 1,410,813; xml: 629,201; asm: 438,677; java: 186,096; sh: 62,697; makefile: 18,086; objc: 13,087; perl: 12,811; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (568 lines) | stat: -rw-r--r-- 21,588 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/* -*- 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 "HTMLEditor.h"

#include "EditAction.h"
#include "EditorDOMAPIWrapper.h"
#include "EditorUtils.h"
#include "HTMLEditorNestedClasses.h"

#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IMEStateManager.h"
#include "mozilla/Logging.h"
#include "mozilla/Maybe.h"
#include "mozilla/RefPtr.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/Element.h"
#include "mozInlineSpellChecker.h"
#include "nsContentUtils.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsIMutationObserver.h"
#include "nsINode.h"
#include "nsRange.h"
#include "nsThreadUtils.h"

namespace mozilla {

using namespace dom;

/******************************************************************************
 * DOM mutation logger
 ******************************************************************************/

// - HTMLEditorMutation:3: Logging only mutations in editable containers which
// is not expected.
// - HTMLEditorMutation:4: Logging only mutations in editable containers which
// is either expected or not expected.
// - HTMLEditorMutation:5: Logging any mutations including in
// non-editable containers.
LazyLogModule gHTMLEditorMutationLog("HTMLEditorMutation");

LogLevel HTMLEditor::MutationLogLevelOf(
    nsIContent* aContent,
    const CharacterDataChangeInfo* aCharacterDataChangeInfo,
    DOMMutationType aDOMMutationType) const {
  // Should be called only when the "info" level is enabled at least since we
  // shouldn't add any new unnecessary calls in the hot paths when the logging
  // is disabled.
  MOZ_ASSERT(MOZ_LOG_TEST(gHTMLEditorMutationLog, LogLevel::Info));

  if (MOZ_UNLIKELY(!aContent->IsInComposedDoc())) {
    return LogLevel::Disabled;
  }
  Element* const containerElement = aContent->GetAsElementOrParentElement();
  if (!containerElement || !containerElement->IsEditable()) {
    return MOZ_LOG_TEST(gHTMLEditorMutationLog, LogLevel::Verbose)
               ? LogLevel::Verbose
               : LogLevel::Disabled;
  }
  if (!mRunningDOMAPIWrapper) {
    return LogLevel::Info;
  }
  switch (aDOMMutationType) {
    case DOMMutationType::ContentAppended:
      return mRunningDOMAPIWrapper->IsExpectedContentAppended(aContent)
                 ? LogLevel::Debug
                 : LogLevel::Info;
    case DOMMutationType::ContentInserted:
      return mRunningDOMAPIWrapper->IsExpectedContentInserted(aContent)
                 ? LogLevel::Debug
                 : LogLevel::Info;
    case DOMMutationType::ContentWillBeRemoved:
      return mRunningDOMAPIWrapper->IsExpectedContentWillBeRemoved(aContent)
                 ? LogLevel::Debug
                 : LogLevel::Info;
    case DOMMutationType::CharacterDataChanged:
      MOZ_ASSERT(aCharacterDataChangeInfo);
      return mRunningDOMAPIWrapper->IsExpectedCharacterDataChanged(
                 aContent, *aCharacterDataChangeInfo)
                 ? LogLevel::Debug
                 : LogLevel::Info;
    default:
      MOZ_ASSERT_UNREACHABLE("Invalid DOMMutationType value");
      return LogLevel::Disabled;
  }
}

// - HTMLEditorAttrMutation:3: Logging only mutations of editable element which
// is not expected.
// - HTMLEditorAttrMutation:4: Logging only mutations of editable element which
// is either expected or not expected.
// - HTMLEditorAttrMutation:5: Logging any mutations including non-editable
// elements' attributes.
LazyLogModule gHTMLEditorAttrMutationLog("HTMLEditorAttrMutation");

LogLevel HTMLEditor::AttrMutationLogLevelOf(
    Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
    AttrModType aModType, const nsAttrValue* aOldValue) const {
  // Should be called only when the "info" level is enabled at least since we
  // shouldn't add any new unnecessary calls in the hot paths when the logging
  // is disabled.
  MOZ_ASSERT(MOZ_LOG_TEST(gHTMLEditorAttrMutationLog, LogLevel::Info));
  if (MOZ_UNLIKELY(!aElement->IsInComposedDoc())) {
    return LogLevel::Disabled;
  }
  if (!aElement->IsEditable()) {
    return MOZ_LOG_TEST(gHTMLEditorAttrMutationLog, LogLevel::Verbose)
               ? LogLevel::Verbose
               : LogLevel::Disabled;
  }
  if (!mRunningDOMAPIWrapper) {
    return LogLevel::Info;
  }
  return mRunningDOMAPIWrapper->IsExpectedAttributeChanged(
             aElement, aNameSpaceID, aAttribute, aModType, aOldValue)
             ? LogLevel::Debug
             : LogLevel::Info;
}

void HTMLEditor::MaybeLogContentAppended(nsIContent* aFirstNewContent) const {
  const LogLevel logLevel = MutationLogLevelOf(
      aFirstNewContent, nullptr, DOMMutationType::ContentAppended);
  if (logLevel == LogLevel::Disabled) {
    return;
  }
  MOZ_LOG(
      gHTMLEditorMutationLog, logLevel,
      ("%p %s ContentAppended: %s (previousSibling=%s, nextSibling=%s)", this,
       logLevel == LogLevel::Debug ? "HTMLEditor  " : "SomebodyElse",
       NodeToString(aFirstNewContent).get(),
       NodeToString(aFirstNewContent ? aFirstNewContent->GetPreviousSibling()
                                     : nullptr)
           .get(),
       NodeToString(aFirstNewContent ? aFirstNewContent->GetNextSibling()
                                     : nullptr)
           .get()));
}

void HTMLEditor::MaybeLogContentInserted(nsIContent* aChild) const {
  const LogLevel logLevel =
      MutationLogLevelOf(aChild, nullptr, DOMMutationType::ContentInserted);
  if (logLevel == LogLevel::Disabled) {
    return;
  }
  MOZ_LOG(gHTMLEditorMutationLog, logLevel,
          ("%p %s ContentInserted: %s (previousSibling=%s, nextSibling=%s)",
           this, logLevel == LogLevel::Debug ? "HTMLEditor  " : "SomebodyElse",
           NodeToString(aChild).get(),
           NodeToString(aChild ? aChild->GetPreviousSibling() : nullptr).get(),
           NodeToString(aChild ? aChild->GetNextSibling() : nullptr).get()));
}

void HTMLEditor::MaybeLogContentWillBeRemoved(nsIContent* aChild) const {
  const LogLevel logLevel = MutationLogLevelOf(
      aChild, nullptr, DOMMutationType::ContentWillBeRemoved);
  if (logLevel == LogLevel::Disabled) {
    return;
  }
  MOZ_LOG(
      gHTMLEditorMutationLog, logLevel,
      ("%p %s ContentWillBeRemoved: %s (previousSibling=%s, nextSibling=%s)",
       this, logLevel == LogLevel::Debug ? "HTMLEditor  " : "SomebodyElse",
       NodeToString(aChild).get(),
       NodeToString(aChild ? aChild->GetPreviousSibling() : nullptr).get(),
       NodeToString(aChild ? aChild->GetNextSibling() : nullptr).get()));
}

void HTMLEditor::MaybeLogCharacterDataChanged(
    nsIContent* aContent, const CharacterDataChangeInfo& aInfo) const {
  const LogLevel logLevel = MutationLogLevelOf(
      aContent, &aInfo, DOMMutationType::CharacterDataChanged);
  if (logLevel == LogLevel::Disabled) {
    return;
  }
  nsAutoString data;
  aContent->GetCharacterDataBuffer()->AppendTo(data);
  MarkSelectionAndShrinkLongString shrunkenData(
      data, aInfo.mChangeStart, aInfo.mChangeStart + aInfo.mReplaceLength);
  MakeHumanFriendly(shrunkenData);
  MOZ_LOG(
      gHTMLEditorMutationLog, logLevel,
      ("%p %s CharacterDataChanged: %s, data=\"%s\", (length=%u), aInfo=%s",
       this, logLevel == LogLevel::Debug ? "HTMLEditor  " : "SomebodyElse",
       ToString(*aContent).c_str(), NS_ConvertUTF16toUTF8(shrunkenData).get(),
       aContent->Length(), ToString(aInfo).c_str()));
}

void HTMLEditor::MaybeLogAttributeChanged(Element* aElement,
                                          int32_t aNameSpaceID,
                                          nsAtom* aAttribute,
                                          AttrModType aModType,
                                          const nsAttrValue* aOldValue) const {
  const LogLevel logLevel = AttrMutationLogLevelOf(
      aElement, aNameSpaceID, aAttribute, aModType, aOldValue);
  if (logLevel == LogLevel::Disabled) {
    return;
  }
  nsAutoString value;
  aElement->GetAttr(aAttribute, value);
  MOZ_LOG(
      gHTMLEditorAttrMutationLog, logLevel,
      ("%p %s AttributeChanged: %s of %s %s", this,
       logLevel == LogLevel::Debug ? "HTMLEditor  " : "SomebodyElse",
       nsAutoAtomCString(aAttribute).get(), NodeToString(aElement).get(),
       aModType == AttrModType::Removal
           ? "Removed"
           : nsPrintfCString("to \"%s\"", NS_ConvertUTF16toUTF8(value).get())
                 .get()));
}

/******************************************************************************
 * mozilla::HTMLEditor - Start/end of a DOM API call to modify the DOM
 ******************************************************************************/

const AutoDOMAPIWrapperBase* HTMLEditor::OnDOMAPICallStart(
    const AutoDOMAPIWrapperBase& aWrapperBase) {
  const AutoDOMAPIWrapperBase* const prevRunner = mRunningDOMAPIWrapper;
  mRunningDOMAPIWrapper = &aWrapperBase;
  MOZ_LOG(gHTMLEditorMutationLog, LogLevel::Warning,
          (">>>> %p Calling DOM API: %s", this,
           ToString(*mRunningDOMAPIWrapper).c_str()));
  return prevRunner;
}

void HTMLEditor::OnDOMAPICallEnd(const AutoDOMAPIWrapperBase* aPrevWrapper) {
  MOZ_LOG(gHTMLEditorMutationLog, LogLevel::Warning,
          ("<<<< %p Called DOM API: %s", this,
           ToString(mRunningDOMAPIWrapper->Type()).c_str()));
  mRunningDOMAPIWrapper = aPrevWrapper;
}

/******************************************************************************
 * mozilla::HTMLEditor - mutation observers/handlers
 ******************************************************************************/

void HTMLEditor::NotifyRootChanged() {
  MOZ_ASSERT(mPendingRootElementUpdatedRunner,
             "HTMLEditor::NotifyRootChanged() should be called via a runner");
  mPendingRootElementUpdatedRunner = nullptr;

  nsCOMPtr<nsIMutationObserver> kungFuDeathGrip(this);

  AutoEditActionDataSetter editActionData(*this, EditAction::eNotEditing);
  if (NS_WARN_IF(!editActionData.CanHandle())) {
    return;
  }

  RemoveEventListeners();
  nsresult rv = InstallEventListeners();
  if (NS_FAILED(rv)) {
    NS_WARNING("HTMLEditor::InstallEventListeners() failed, but ignored");
    return;
  }

  UpdateRootElement();

  if (MOZ_LIKELY(mRootElement)) {
    rv = MaybeCollapseSelectionAtFirstEditableNode(false);
    if (NS_FAILED(rv)) {
      NS_WARNING(
          "HTMLEditor::MaybeCollapseSelectionAtFirstEditableNode(false) "
          "failed, "
          "but ignored");
      return;
    }

    // When this editor has focus, we need to reset the selection limiter to
    // new root.  Otherwise, that is going to be done when this gets focus.
    nsCOMPtr<nsINode> node = GetFocusedNode();
    if (node) {
      DebugOnly<nsresult> rvIgnored = InitializeSelection(*node);
      NS_WARNING_ASSERTION(
          NS_SUCCEEDED(rvIgnored),
          "EditorBase::InitializeSelection() failed, but ignored");
    }

    SyncRealTimeSpell();
  }

  RefPtr<Element> newRootElement(mRootElement);
  IMEStateManager::OnUpdateHTMLEditorRootElement(*this, newRootElement);
}

// nsStubMutationObserver::ContentAppended override
MOZ_CAN_RUN_SCRIPT_BOUNDARY void HTMLEditor::ContentAppended(
    nsIContent* aFirstNewContent, const ContentAppendInfo&) {
  DoContentInserted(aFirstNewContent, ContentNodeIs::Appended);
}

// nsStubMutationObserver::ContentInserted override
MOZ_CAN_RUN_SCRIPT_BOUNDARY void HTMLEditor::ContentInserted(
    nsIContent* aChild, const ContentInsertInfo&) {
  DoContentInserted(aChild, ContentNodeIs::Inserted);
}

bool HTMLEditor::IsInObservedSubtree(nsIContent* aChild) {
  if (!aChild) {
    return false;
  }

  // FIXME(emilio, bug 1596856): This should probably work if the root is in the
  // same shadow tree as the child, probably? I don't know what the
  // contenteditable-in-shadow-dom situation is.
  if (Element* root = GetRoot()) {
    // To be super safe here, check both ChromeOnlyAccess and NAC / Shadow DOM.
    // That catches (also unbound) native anonymous content and ShadowDOM.
    if (root->ChromeOnlyAccess() != aChild->ChromeOnlyAccess() ||
        root->IsInNativeAnonymousSubtree() !=
            aChild->IsInNativeAnonymousSubtree() ||
        root->IsInShadowTree() != aChild->IsInShadowTree()) {
      return false;
    }
  }

  return !aChild->ChromeOnlyAccess() && !aChild->IsInShadowTree() &&
         !aChild->IsInNativeAnonymousSubtree();
}

bool HTMLEditor::ShouldReplaceRootElement() const {
  if (!mRootElement) {
    // If we don't know what is our root element, we should find our root.
    return true;
  }

  // If we temporary set document root element to mRootElement, but there is
  // body element now, we should replace the root element by the body element.
  return mRootElement != GetBodyElement();
}

void HTMLEditor::DoContentInserted(nsIContent* aChild,
                                   ContentNodeIs aContentNodeIs) {
  MOZ_ASSERT(aChild);
  nsINode* container = aChild->GetParentNode();
  MOZ_ASSERT(container);

  if (!IsInObservedSubtree(aChild)) {
    return;
  }

  if (MOZ_LOG_TEST(gHTMLEditorMutationLog, LogLevel::Info)) {
    if (aContentNodeIs == ContentNodeIs::Appended) {
      MaybeLogContentAppended(aChild);
    } else {
      MOZ_ASSERT(aContentNodeIs == ContentNodeIs::Inserted);
      MaybeLogContentInserted(aChild);
    }
  }

  // XXX Why do we need this? This method is a helper of mutation observer.
  //     So, the callers of mutation observer should guarantee that this won't
  //     be deleted at least during the call.
  RefPtr<HTMLEditor> kungFuDeathGrip(this);

  // Do not create AutoEditActionDataSetter here because it grabs `Selection`,
  // but that appear in the profile. If you need to create to it in some cases,
  // you should do it in the minimum scope.

  if (ShouldReplaceRootElement()) {
    // Forget maybe disconnected root element right now because nobody should
    // work with it.
    mRootElement = nullptr;
    if (mPendingRootElementUpdatedRunner) {
      return;
    }
    mPendingRootElementUpdatedRunner = NewRunnableMethod(
        "HTMLEditor::NotifyRootChanged", this, &HTMLEditor::NotifyRootChanged);
    nsContentUtils::AddScriptRunner(
        do_AddRef(mPendingRootElementUpdatedRunner));
    return;
  }

  // We don't need to handle our own modifications
  if (!GetTopLevelEditSubAction() && container->IsEditable()) {
    if (EditorUtils::IsPaddingBRElementForEmptyEditor(*aChild)) {
      // Ignore insertion of the padding <br> element.
      return;
    }
    nsresult rv = RunOrScheduleOnModifyDocument();
    if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
      return;
    }
    NS_WARNING_ASSERTION(
        NS_SUCCEEDED(rv),
        "HTMLEditor::RunOrScheduleOnModifyDocument() failed, but ignored");

    // Update spellcheck for only the newly-inserted node (bug 743819)
    if (mInlineSpellChecker) {
      nsIContent* endContent = aChild;
      if (aContentNodeIs == ContentNodeIs::Appended) {
        nsIContent* child = nullptr;
        for (child = aChild; child; child = child->GetNextSibling()) {
          if (child->InclusiveDescendantMayNeedSpellchecking(this)) {
            break;
          }
        }
        if (!child) {
          // No child needed spellchecking, return.
          return;
        }

        // Maybe more than 1 child was appended.
        endContent = container->GetLastChild();
      } else if (!aChild->InclusiveDescendantMayNeedSpellchecking(this)) {
        return;
      }

      RefPtr<nsRange> range = nsRange::Create(aChild);
      range->SelectNodesInContainer(container, aChild, endContent);
      DebugOnly<nsresult> rvIgnored =
          mInlineSpellChecker->SpellCheckRange(range);
      NS_WARNING_ASSERTION(
          rvIgnored == NS_ERROR_NOT_INITIALIZED || NS_SUCCEEDED(rvIgnored),
          "mozInlineSpellChecker::SpellCheckRange() failed, but ignored");
    }
  }
}

// nsStubMutationObserver::ContentWillBeRemoved override
MOZ_CAN_RUN_SCRIPT_BOUNDARY void HTMLEditor::ContentWillBeRemoved(
    nsIContent* aChild, const ContentRemoveInfo&) {
  if (mLastCollapsibleWhiteSpaceAppendedTextNode == aChild) {
    mLastCollapsibleWhiteSpaceAppendedTextNode = nullptr;
  }

  if (!IsInObservedSubtree(aChild)) {
    return;
  }

  if (MOZ_LOG_TEST(gHTMLEditorMutationLog, LogLevel::Info)) {
    MaybeLogContentWillBeRemoved(aChild);
  }

  // XXX Why do we need to do this?  This method is a mutation observer's
  //     method.  Therefore, the caller should guarantee that this won't be
  //     deleted during the call.
  RefPtr<HTMLEditor> kungFuDeathGrip(this);

  // Do not create AutoEditActionDataSetter here because it grabs `Selection`,
  // but that appear in the profile. If you need to create to it in some cases,
  // you should do it in the minimum scope.

  // FYI: mRootElement may be the <body> of the document or the root element.
  // Therefore, we don't need to check it across shadow DOM boundaries.
  if (mRootElement && mRootElement->IsInclusiveDescendantOf(aChild)) {
    // Forget the disconnected root element right now because nobody should work
    // with it.
    mRootElement = nullptr;
    if (mPendingRootElementUpdatedRunner) {
      return;
    }
    mPendingRootElementUpdatedRunner = NewRunnableMethod(
        "HTMLEditor::NotifyRootChanged", this, &HTMLEditor::NotifyRootChanged);
    nsContentUtils::AddScriptRunner(
        do_AddRef(mPendingRootElementUpdatedRunner));
    return;
  }

  // We don't need to handle our own modifications
  if (!GetTopLevelEditSubAction() && aChild->GetParentNode()->IsEditable()) {
    if (aChild && EditorUtils::IsPaddingBRElementForEmptyEditor(*aChild)) {
      // Ignore removal of the padding <br> element for empty editor.
      return;
    }

    nsresult rv = RunOrScheduleOnModifyDocument(aChild);
    if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
      return;
    }
    NS_WARNING_ASSERTION(
        NS_SUCCEEDED(rv),
        "HTMLEditor::RunOrScheduleOnModifyDocument() failed, but ignored");
  }
}

// nsStubMutationObserver::CharacterDataChanged override
MOZ_CAN_RUN_SCRIPT_BOUNDARY void HTMLEditor::CharacterDataChanged(
    nsIContent* aContent, const CharacterDataChangeInfo& aInfo) {
  if (!IsInObservedSubtree(aContent)) {
    return;
  }
  if (MOZ_LOG_TEST(gHTMLEditorMutationLog, LogLevel::Info)) {
    MaybeLogCharacterDataChanged(aContent, aInfo);
  }
  if (!mInlineSpellChecker || !aContent->IsEditable() ||
      GetTopLevelEditSubAction() != EditSubAction::eNone) {
    return;
  }

  nsIContent* parent = aContent->GetParent();
  if (!parent || !parent->InclusiveDescendantMayNeedSpellchecking(this)) {
    return;
  }

  RefPtr<nsRange> range = nsRange::Create(aContent);
  range->SelectNodesInContainer(parent, aContent, aContent);
  DebugOnly<nsresult> rvIgnored = mInlineSpellChecker->SpellCheckRange(range);
}

nsresult HTMLEditor::RunOrScheduleOnModifyDocument(
    const nsIContent* aContentWillBeRemoved /* = nullptr */) {
  if (mPendingDocumentModifiedRunner) {
    return NS_OK;  // We've already posted same runnable into the queue.
  }
  mPendingDocumentModifiedRunner = new DocumentModifiedEvent(*this);
  nsContentUtils::AddScriptRunner(do_AddRef(mPendingDocumentModifiedRunner));
  // Be aware, if OnModifyDocument() may be called synchronously, the
  // editor might have been destroyed here.
  return NS_WARN_IF(Destroyed()) ? NS_ERROR_EDITOR_DESTROYED : NS_OK;
}

// nsStubMutationObserver::AttributeChanged override
MOZ_CAN_RUN_SCRIPT_BOUNDARY void HTMLEditor::AttributeChanged(
    Element* aElement, int32_t aNameSpaceID, nsAtom* aAttribute,
    AttrModType aModType, const nsAttrValue* aOldValue) {
  if (MOZ_LOG_TEST(gHTMLEditorAttrMutationLog, LogLevel::Info) &&
      IsInObservedSubtree(aElement)) {
    MaybeLogAttributeChanged(aElement, aNameSpaceID, aAttribute, aModType,
                             aOldValue);
  }
}

nsresult HTMLEditor::OnModifyDocument(const DocumentModifiedEvent& aRunner) {
  MOZ_ASSERT(mPendingDocumentModifiedRunner,
             "HTMLEditor::OnModifyDocument() should be called via a runner");
  MOZ_ASSERT(&aRunner == mPendingDocumentModifiedRunner);
  mPendingDocumentModifiedRunner = nullptr;

  Maybe<AutoEditActionDataSetter> editActionData;
  if (!IsEditActionDataAvailable()) {
    editActionData.emplace(*this,
                           EditAction::eCreatePaddingBRElementForEmptyEditor);
    if (NS_WARN_IF(!editActionData->CanHandle())) {
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  // EnsureNoPaddingBRElementForEmptyEditor() below may cause a flush, which
  // could destroy the editor
  nsAutoScriptBlockerSuppressNodeRemoved scriptBlocker;

  // Delete our padding <br> element for empty editor, if we have one, since
  // the document might not be empty any more.
  nsresult rv = EnsureNoPaddingBRElementForEmptyEditor();
  if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
    return rv;
  }
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                       "EditorBase::EnsureNoPaddingBRElementForEmptyEditor() "
                       "failed, but ignored");

  // Try to recreate the padding <br> element for empty editor if needed.
  rv = MaybeCreatePaddingBRElementForEmptyEditor();
  if (NS_WARN_IF(rv == NS_ERROR_EDITOR_DESTROYED)) {
    return NS_ERROR_EDITOR_DESTROYED;
  }
  NS_WARNING_ASSERTION(
      NS_SUCCEEDED(rv),
      "EditorBase::MaybeCreatePaddingBRElementForEmptyEditor() failed");

  return rv;
}

}  // namespace mozilla