summaryrefslogtreecommitdiffstats
path: root/editor/libeditor/PendingStyles.cpp
blob: 12666c52897d1f210e8a866f10087d0259d42c04 (plain)
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
/* -*- 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 "PendingStyles.h"

#include <stddef.h>

#include "EditAction.h"
#include "EditorBase.h"
#include "HTMLEditHelpers.h"  // for EditorInlineStyle, EditorInlineStyleAndValue
#include "HTMLEditor.h"
#include "HTMLEditUtils.h"

#include "mozilla/mozalloc.h"
#include "mozilla/dom/AncestorIterator.h"
#include "mozilla/dom/MouseEvent.h"
#include "mozilla/dom/Selection.h"

#include "nsDebug.h"
#include "nsError.h"
#include "nsGkAtoms.h"
#include "nsINode.h"
#include "nsISupports.h"
#include "nsISupportsImpl.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsTArray.h"

namespace mozilla {

using namespace dom;

/********************************************************************
 * mozilla::PendingStyle
 *******************************************************************/

EditorInlineStyle PendingStyle::ToInlineStyle() const {
  return mTag ? EditorInlineStyle(*mTag, mAttribute)
              : EditorInlineStyle::RemoveAllStyles();
}

EditorInlineStyleAndValue PendingStyle::ToInlineStyleAndValue() const {
  MOZ_ASSERT(mTag);
  return mAttribute ? EditorInlineStyleAndValue(*mTag, *mAttribute,
                                                mAttributeValueOrCSSValue)
                    : EditorInlineStyleAndValue(*mTag);
}

/********************************************************************
 * mozilla::PendingStyleCache
 *******************************************************************/

EditorInlineStyle PendingStyleCache::ToInlineStyle() const {
  return EditorInlineStyle(mTag, mAttribute);
}

/********************************************************************
 * mozilla::PendingStyles
 *******************************************************************/

NS_IMPL_CYCLE_COLLECTION_CLASS(PendingStyles)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(PendingStyles)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mLastSelectionPoint)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(PendingStyles)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLastSelectionPoint)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

nsresult PendingStyles::UpdateSelState(const HTMLEditor& aHTMLEditor) {
  if (!aHTMLEditor.SelectionRef().IsCollapsed()) {
    return NS_OK;
  }

  mLastSelectionPoint =
      aHTMLEditor.GetFirstSelectionStartPoint<EditorDOMPoint>();
  if (!mLastSelectionPoint.IsSet()) {
    return NS_ERROR_FAILURE;
  }
  // We need to store only offset because referring child may be removed by
  // we'll check the point later.
  AutoEditorDOMPointChildInvalidator saveOnlyOffset(mLastSelectionPoint);
  return NS_OK;
}

void PendingStyles::PreHandleMouseEvent(const MouseEvent& aMouseDownOrUpEvent) {
  MOZ_ASSERT(aMouseDownOrUpEvent.WidgetEventPtr()->mMessage == eMouseDown ||
             aMouseDownOrUpEvent.WidgetEventPtr()->mMessage == eMouseUp);
  bool& eventFiredInLinkElement =
      aMouseDownOrUpEvent.WidgetEventPtr()->mMessage == eMouseDown
          ? mMouseDownFiredInLinkElement
          : mMouseUpFiredInLinkElement;
  eventFiredInLinkElement = false;
  if (aMouseDownOrUpEvent.DefaultPrevented()) {
    return;
  }
  // If mouse button is down or up in a link element, we shouldn't unlink
  // it when we get a notification of selection change.
  EventTarget* target = aMouseDownOrUpEvent.GetExplicitOriginalTarget();
  if (NS_WARN_IF(!target)) {
    return;
  }
  nsIContent* targetContent = nsIContent::FromEventTarget(target);
  if (NS_WARN_IF(!targetContent)) {
    return;
  }
  eventFiredInLinkElement =
      HTMLEditUtils::IsContentInclusiveDescendantOfLink(*targetContent);
}

void PendingStyles::PreHandleSelectionChangeCommand(Command aCommand) {
  mLastSelectionCommand = aCommand;
}

void PendingStyles::PostHandleSelectionChangeCommand(
    const HTMLEditor& aHTMLEditor, Command aCommand) {
  if (mLastSelectionCommand != aCommand) {
    return;
  }

  // If `OnSelectionChange()` hasn't been called for `mLastSelectionCommand`,
  // it means that it didn't cause selection change.
  if (!aHTMLEditor.SelectionRef().IsCollapsed() ||
      !aHTMLEditor.SelectionRef().RangeCount()) {
    return;
  }

  const auto caretPoint =
      aHTMLEditor.GetFirstSelectionStartPoint<EditorRawDOMPoint>();
  if (NS_WARN_IF(!caretPoint.IsSet())) {
    return;
  }

  if (!HTMLEditUtils::IsPointAtEdgeOfLink(caretPoint)) {
    return;
  }

  // If all styles are cleared or link style is explicitly set, we
  // shouldn't reset them without caret move.
  if (AreAllStylesCleared() || IsLinkStyleSet()) {
    return;
  }
  // And if non-link styles are cleared or some styles are set, we
  // shouldn't reset them too, but we may need to change the link
  // style.
  if (AreSomeStylesSet() ||
      (AreSomeStylesCleared() && !IsOnlyLinkStyleCleared())) {
    ClearLinkAndItsSpecifiedStyle();
    return;
  }

  Reset();
  ClearLinkAndItsSpecifiedStyle();
}

void PendingStyles::OnSelectionChange(const HTMLEditor& aHTMLEditor,
                                      int16_t aReason) {
  // XXX: Selection currently generates bogus selection changed notifications
  // XXX: (bug 140303). It can notify us when the selection hasn't actually
  // XXX: changed, and it notifies us more than once for the same change.
  // XXX:
  // XXX: The following code attempts to work around the bogus notifications,
  // XXX: and should probably be removed once bug 140303 is fixed.
  // XXX:
  // XXX: This code temporarily fixes the problem where clicking the mouse in
  // XXX: the same location clears the type-in-state.

  const bool causedByFrameSelectionMoveCaret =
      (aReason & (nsISelectionListener::KEYPRESS_REASON |
                  nsISelectionListener::COLLAPSETOSTART_REASON |
                  nsISelectionListener::COLLAPSETOEND_REASON)) &&
      !(aReason & nsISelectionListener::JS_REASON);

  Command lastSelectionCommand = mLastSelectionCommand;
  if (causedByFrameSelectionMoveCaret) {
    mLastSelectionCommand = Command::DoNothing;
  }

  bool mouseEventFiredInLinkElement = false;
  if (aReason & (nsISelectionListener::MOUSEDOWN_REASON |
                 nsISelectionListener::MOUSEUP_REASON)) {
    MOZ_ASSERT((aReason & (nsISelectionListener::MOUSEDOWN_REASON |
                           nsISelectionListener::MOUSEUP_REASON)) !=
               (nsISelectionListener::MOUSEDOWN_REASON |
                nsISelectionListener::MOUSEUP_REASON));
    bool& eventFiredInLinkElement =
        aReason & nsISelectionListener::MOUSEDOWN_REASON
            ? mMouseDownFiredInLinkElement
            : mMouseUpFiredInLinkElement;
    mouseEventFiredInLinkElement = eventFiredInLinkElement;
    eventFiredInLinkElement = false;
  }

  bool unlink = false;
  bool resetAllStyles = true;
  if (aHTMLEditor.SelectionRef().IsCollapsed() &&
      aHTMLEditor.SelectionRef().RangeCount()) {
    const auto selectionStartPoint =
        aHTMLEditor.GetFirstSelectionStartPoint<EditorDOMPoint>();
    if (MOZ_UNLIKELY(NS_WARN_IF(!selectionStartPoint.IsSet()))) {
      return;
    }

    if (mLastSelectionPoint == selectionStartPoint) {
      // If all styles are cleared or link style is explicitly set, we
      // shouldn't reset them without caret move.
      if (AreAllStylesCleared() || IsLinkStyleSet()) {
        return;
      }
      // And if non-link styles are cleared or some styles are set, we
      // shouldn't reset them too, but we may need to change the link
      // style.
      if (AreSomeStylesSet() ||
          (AreSomeStylesCleared() && !IsOnlyLinkStyleCleared())) {
        resetAllStyles = false;
      }
    }

    RefPtr<Element> linkElement;
    if (HTMLEditUtils::IsPointAtEdgeOfLink(selectionStartPoint,
                                           getter_AddRefs(linkElement))) {
      // If caret comes from outside of <a href> element, we should clear "link"
      // style after reset.
      if (causedByFrameSelectionMoveCaret) {
        MOZ_ASSERT(!(aReason & (nsISelectionListener::MOUSEDOWN_REASON |
                                nsISelectionListener::MOUSEUP_REASON)));
        // If caret is moves in a link per character, we should keep inserting
        // new text to the link because user may want to keep extending the link
        // text.  Otherwise, e.g., using `End` or `Home` key. we should insert
        // new text outside the link because it should be possible to user
        // choose it, and this is similar to the other browsers.
        switch (lastSelectionCommand) {
          case Command::CharNext:
          case Command::CharPrevious:
          case Command::MoveLeft:
          case Command::MoveLeft2:
          case Command::MoveRight:
          case Command::MoveRight2:
            // If selection becomes collapsed, we should unlink new text.
            if (!mLastSelectionPoint.IsSet()) {
              unlink = true;
              break;
            }
            // Special case, if selection isn't moved, it means that caret is
            // positioned at start or end of an editing host.  In this case,
            // we can unlink it even with arrow key press.
            // TODO: This does not work as expected for `ArrowLeft` key press
            //       at start of an editing host.
            if (mLastSelectionPoint == selectionStartPoint) {
              unlink = true;
              break;
            }
            // Otherwise, if selection is moved in a link element, we should
            // keep inserting new text into the link.  Note that this is our
            // traditional behavior, but different from the other browsers.
            // If this breaks some web apps, we should change our behavior,
            // but let's wait a report because our traditional behavior allows
            // user to type text into start/end of a link only when user
            // moves caret inside the link with arrow keys.
            unlink =
                !mLastSelectionPoint.GetContainer()->IsInclusiveDescendantOf(
                    linkElement);
            break;
          default:
            // If selection is moved without arrow keys, e.g., `Home` and
            // `End`, we should not insert new text into the link element.
            // This is important for web-compat especially when the link is
            // the last content in the block.
            unlink = true;
            break;
        }
      } else if (aReason & (nsISelectionListener::MOUSEDOWN_REASON |
                            nsISelectionListener::MOUSEUP_REASON)) {
        // If the corresponding mouse event is fired in a link element,
        // we should keep treating inputting content as content in the link,
        // but otherwise, i.e., clicked outside the link, we should stop
        // treating inputting content as content in the link.
        unlink = !mouseEventFiredInLinkElement;
      } else if (aReason & nsISelectionListener::JS_REASON) {
        // If this is caused by a call of Selection API or something similar
        // API, we should not contain new inserting content to the link.
        unlink = true;
      } else {
        switch (aHTMLEditor.GetEditAction()) {
          case EditAction::eDeleteBackward:
          case EditAction::eDeleteForward:
          case EditAction::eDeleteSelection:
          case EditAction::eDeleteToBeginningOfSoftLine:
          case EditAction::eDeleteToEndOfSoftLine:
          case EditAction::eDeleteWordBackward:
          case EditAction::eDeleteWordForward:
            // This selection change is caused by the editor and the edit
            // action is deleting content at edge of a link, we shouldn't
            // keep the link style for new inserted content.
            unlink = true;
            break;
          default:
            break;
        }
      }
    } else if (mLastSelectionPoint == selectionStartPoint) {
      return;
    }

    mLastSelectionPoint = selectionStartPoint;
    // We need to store only offset because referring child may be removed by
    // we'll check the point later.
    AutoEditorDOMPointChildInvalidator saveOnlyOffset(mLastSelectionPoint);
  } else {
    if (aHTMLEditor.SelectionRef().RangeCount()) {
      // If selection starts from a link, we shouldn't preserve the link style
      // unless the range is entirely in the link.
      EditorRawDOMRange firstRange(*aHTMLEditor.SelectionRef().GetRangeAt(0));
      if (firstRange.StartRef().IsInContentNode() &&
          HTMLEditUtils::IsContentInclusiveDescendantOfLink(
              *firstRange.StartRef().ContainerAs<nsIContent>())) {
        unlink = !HTMLEditUtils::IsRangeEntirelyInLink(firstRange);
      }
    }
    mLastSelectionPoint.Clear();
  }

  if (resetAllStyles) {
    Reset();
    if (unlink) {
      ClearLinkAndItsSpecifiedStyle();
    }
    return;
  }

  if (unlink == IsExplicitlyLinkStyleCleared()) {
    return;
  }

  // Even if we shouldn't touch existing style, we need to set/clear only link
  // style in some cases.
  if (unlink) {
    ClearLinkAndItsSpecifiedStyle();
    return;
  }
  CancelClearingStyle(*nsGkAtoms::a, nullptr);
}

void PendingStyles::PreserveStyles(
    const nsTArray<EditorInlineStyleAndValue>& aStylesToPreserve) {
  for (const EditorInlineStyleAndValue& styleToPreserve : aStylesToPreserve) {
    PreserveStyle(styleToPreserve.HTMLPropertyRef(), styleToPreserve.mAttribute,
                  styleToPreserve.mAttributeValue);
  }
}

void PendingStyles::PreserveStyle(nsStaticAtom& aHTMLProperty,
                                  nsAtom* aAttribute,
                                  const nsAString& aAttributeValueOrCSSValue) {
  // special case for big/small, these nest
  if (nsGkAtoms::big == &aHTMLProperty) {
    mRelativeFontSize++;
    return;
  }
  if (nsGkAtoms::small == &aHTMLProperty) {
    mRelativeFontSize--;
    return;
  }

  Maybe<size_t> index = IndexOfPreservingStyle(aHTMLProperty, aAttribute);
  if (index.isSome()) {
    // If it's already set, update the value
    mPreservingStyles[index.value()]->UpdateAttributeValueOrCSSValue(
        aAttributeValueOrCSSValue);
    return;
  }

  // font-size and font-family need to be applied outer-most because height of
  // outer inline elements of them are computed without these styles.  E.g.,
  // background-color may be applied bottom-half of the text.  Therefore, we
  // need to apply the font styles first.
  UniquePtr<PendingStyle> style = MakeUnique<PendingStyle>(
      &aHTMLProperty, aAttribute, aAttributeValueOrCSSValue);
  if (&aHTMLProperty == nsGkAtoms::font && aAttribute != nsGkAtoms::bgcolor) {
    MOZ_ASSERT(aAttribute == nsGkAtoms::color ||
               aAttribute == nsGkAtoms::face || aAttribute == nsGkAtoms::size);
    mPreservingStyles.InsertElementAt(0, std::move(style));
  } else {
    mPreservingStyles.AppendElement(std::move(style));
  }

  CancelClearingStyle(aHTMLProperty, aAttribute);
}

void PendingStyles::ClearStyles(
    const nsTArray<EditorInlineStyle>& aStylesToClear) {
  for (const EditorInlineStyle& styleToClear : aStylesToClear) {
    if (styleToClear.IsStyleToClearAllInlineStyles()) {
      ClearAllStyles();
      return;
    }
    if (styleToClear.mHTMLProperty == nsGkAtoms::href ||
        styleToClear.mHTMLProperty == nsGkAtoms::name) {
      ClearStyleInternal(nsGkAtoms::a, nullptr);
    } else {
      ClearStyleInternal(styleToClear.mHTMLProperty, styleToClear.mAttribute);
    }
  }
}

void PendingStyles::ClearStyleInternal(
    nsStaticAtom* aHTMLProperty, nsAtom* aAttribute,
    SpecifiedStyle aSpecifiedStyle /* = SpecifiedStyle::Preserve */) {
  if (IsStyleCleared(aHTMLProperty, aAttribute)) {
    return;
  }

  CancelPreservingStyle(aHTMLProperty, aAttribute);

  mClearingStyles.AppendElement(MakeUnique<PendingStyle>(
      aHTMLProperty, aAttribute, u""_ns, aSpecifiedStyle));
}

void PendingStyles::TakeAllPreservedStyles(
    nsTArray<EditorInlineStyleAndValue>& aOutStylesAndValues) {
  aOutStylesAndValues.SetCapacity(aOutStylesAndValues.Length() +
                                  mPreservingStyles.Length());
  for (const UniquePtr<PendingStyle>& preservedStyle : mPreservingStyles) {
    aOutStylesAndValues.AppendElement(
        preservedStyle->GetAttribute()
            ? EditorInlineStyleAndValue(
                  *preservedStyle->GetTag(), *preservedStyle->GetAttribute(),
                  preservedStyle->AttributeValueOrCSSValueRef())
            : EditorInlineStyleAndValue(*preservedStyle->GetTag()));
  }
  mPreservingStyles.Clear();
}

/**
 * TakeRelativeFontSize() hands back relative font value, which is then
 * cleared out.
 */
int32_t PendingStyles::TakeRelativeFontSize() {
  int32_t relSize = mRelativeFontSize;
  mRelativeFontSize = 0;
  return relSize;
}

PendingStyleState PendingStyles::GetStyleState(
    nsStaticAtom& aHTMLProperty, nsAtom* aAttribute /* = nullptr */,
    nsString* aOutNewAttributeValueOrCSSValue /* = nullptr */) const {
  if (IndexOfPreservingStyle(aHTMLProperty, aAttribute,
                             aOutNewAttributeValueOrCSSValue)
          .isSome()) {
    return PendingStyleState::BeingPreserved;
  }

  if (IsStyleCleared(&aHTMLProperty, aAttribute)) {
    return PendingStyleState::BeingCleared;
  }

  return PendingStyleState::NotUpdated;
}

void PendingStyles::CancelPreservingStyle(nsStaticAtom* aHTMLProperty,
                                          nsAtom* aAttribute) {
  if (!aHTMLProperty) {
    mPreservingStyles.Clear();
    mRelativeFontSize = 0;
    return;
  }
  Maybe<size_t> index = IndexOfPreservingStyle(*aHTMLProperty, aAttribute);
  if (index.isSome()) {
    mPreservingStyles.RemoveElementAt(index.value());
  }
}

void PendingStyles::CancelClearingStyle(nsStaticAtom& aHTMLProperty,
                                        nsAtom* aAttribute) {
  Maybe<size_t> index =
      IndexOfStyleInArray(&aHTMLProperty, aAttribute, nullptr, mClearingStyles);
  if (index.isSome()) {
    mClearingStyles.RemoveElementAt(index.value());
  }
}

Maybe<size_t> PendingStyles::IndexOfStyleInArray(
    nsStaticAtom* aHTMLProperty, nsAtom* aAttribute, nsAString* aOutValue,
    const nsTArray<UniquePtr<PendingStyle>>& aArray) {
  if (aAttribute == nsGkAtoms::_empty) {
    aAttribute = nullptr;
  }
  for (size_t i : IntegerRange(aArray.Length())) {
    const UniquePtr<PendingStyle>& item = aArray[i];
    if (item->GetTag() == aHTMLProperty && item->GetAttribute() == aAttribute) {
      if (aOutValue) {
        *aOutValue = item->AttributeValueOrCSSValueRef();
      }
      return Some(i);
    }
  }
  return Nothing();
}

}  // namespace mozilla