File: IndentOutdentCommand.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (420 lines) | stat: -rw-r--r-- 17,891 bytes parent folder | download
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
/*
 * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "core/editing/commands/IndentOutdentCommand.h"

#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
#include "core/editing/EditingUtilities.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/commands/InsertListCommand.h"
#include "core/html/HTMLBRElement.h"
#include "core/html/HTMLElement.h"
#include "core/layout/LayoutObject.h"

namespace blink {

using namespace HTMLNames;

// Returns true if |node| is UL, OL, or BLOCKQUOTE with "display:block".
// "Outdent" command considers <BLOCKQUOTE style="display:inline"> makes
// indentation.
static bool isHTMLListOrBlockquoteElement(const Node* node) {
  if (!node || !node->isHTMLElement())
    return false;
  if (!node->layoutObject() || !node->layoutObject()->isLayoutBlock())
    return false;
  const HTMLElement& element = toHTMLElement(*node);
  // TODO(yosin): We should check OL/UL element has "list-style-type" CSS
  // property to make sure they layout contents as list.
  return isHTMLUListElement(element) || isHTMLOListElement(element) ||
         element.hasTagName(blockquoteTag);
}

IndentOutdentCommand::IndentOutdentCommand(Document& document,
                                           EIndentType typeOfAction)
    : ApplyBlockElementCommand(
          document,
          blockquoteTag,
          "margin: 0 0 0 40px; border: none; padding: 0px;"),
      m_typeOfAction(typeOfAction) {}

bool IndentOutdentCommand::tryIndentingAsListItem(const Position& start,
                                                  const Position& end,
                                                  EditingState* editingState) {
  // If our selection is not inside a list, bail out.
  Node* lastNodeInSelectedParagraph = start.anchorNode();
  HTMLElement* listElement = enclosingList(lastNodeInSelectedParagraph);
  if (!listElement)
    return false;

  // Find the block that we want to indent.  If it's not a list item (e.g., a
  // div inside a list item), we bail out.
  Element* selectedListItem = enclosingBlock(lastNodeInSelectedParagraph);

  // FIXME: we need to deal with the case where there is no li (malformed HTML)
  if (!isHTMLLIElement(selectedListItem))
    return false;

  // FIXME: previousElementSibling does not ignore non-rendered content like
  // <span></span>.  Should we?
  Element* previousList = ElementTraversal::previousSibling(*selectedListItem);
  Element* nextList = ElementTraversal::nextSibling(*selectedListItem);

  // We should calculate visible range in list item because inserting new
  // list element will change visibility of list item, e.g. :first-child
  // CSS selector.
  HTMLElement* newList = toHTMLElement(
      document().createElement(listElement->tagQName(), CreatedByCloneNode));
  insertNodeBefore(newList, selectedListItem, editingState);
  if (editingState->isAborted())
    return false;

  document().updateStyleAndLayoutIgnorePendingStylesheets();

  // We should clone all the children of the list item for indenting purposes.
  // However, in case the current selection does not encompass all its children,
  // we need to explicitally handle the same. The original list item too would
  // require proper deletion in that case.
  const bool shouldKeepSelectedList =
      end.anchorNode() == selectedListItem ||
      end.anchorNode()->isDescendantOf(selectedListItem->lastChild());

  const VisiblePosition& startOfParagraphToMove = createVisiblePosition(start);
  const VisiblePosition& endOfParagraphToMove =
      shouldKeepSelectedList
          ? createVisiblePosition(end)
          : VisiblePosition::afterNode(selectedListItem->lastChild());

  // The insertion of |newList| may change the computed style of other
  // elements, resulting in failure in visible canonicalization.
  if (startOfParagraphToMove.isNull() || endOfParagraphToMove.isNull()) {
    editingState->abort();
    return false;
  }

  moveParagraphWithClones(startOfParagraphToMove, endOfParagraphToMove, newList,
                          selectedListItem, editingState);
  if (editingState->isAborted())
    return false;

  if (!shouldKeepSelectedList) {
    removeNode(selectedListItem, editingState);
    if (editingState->isAborted())
      return false;
  }

  document().updateStyleAndLayoutIgnorePendingStylesheets();
  if (canMergeLists(previousList, newList)) {
    mergeIdenticalElements(previousList, newList, editingState);
    if (editingState->isAborted())
      return false;
  }

  document().updateStyleAndLayoutIgnorePendingStylesheets();
  if (canMergeLists(newList, nextList)) {
    mergeIdenticalElements(newList, nextList, editingState);
    if (editingState->isAborted())
      return false;
  }

  return true;
}

void IndentOutdentCommand::indentIntoBlockquote(const Position& start,
                                                const Position& end,
                                                HTMLElement*& targetBlockquote,
                                                EditingState* editingState) {
  Element* enclosingCell = toElement(enclosingNodeOfType(start, &isTableCell));
  Element* elementToSplitTo;
  if (enclosingCell)
    elementToSplitTo = enclosingCell;
  else if (enclosingList(start.computeContainerNode()))
    elementToSplitTo = enclosingBlock(start.computeContainerNode());
  else
    elementToSplitTo = rootEditableElementOf(start);

  if (!elementToSplitTo)
    return;

  Node* outerBlock =
      (start.computeContainerNode() == elementToSplitTo)
          ? start.computeContainerNode()
          : splitTreeToNode(start.computeContainerNode(), elementToSplitTo);

  document().updateStyleAndLayoutIgnorePendingStylesheets();
  VisiblePosition startOfContents = createVisiblePosition(start);
  if (!targetBlockquote) {
    // Create a new blockquote and insert it as a child of the root editable
    // element. We accomplish this by splitting all parents of the current
    // paragraph up to that point.
    targetBlockquote = createBlockElement();
    if (outerBlock == start.computeContainerNode()) {
      // When we apply indent to an empty <blockquote>, we should call
      // insertNodeAfter(). See http://crbug.com/625802 for more details.
      if (outerBlock->hasTagName(blockquoteTag))
        insertNodeAfter(targetBlockquote, outerBlock, editingState);
      else
        insertNodeAt(targetBlockquote, start, editingState);
    } else
      insertNodeBefore(targetBlockquote, outerBlock, editingState);
    if (editingState->isAborted())
      return;
    document().updateStyleAndLayoutIgnorePendingStylesheets();
    startOfContents = VisiblePosition::inParentAfterNode(*targetBlockquote);
  }

  VisiblePosition endOfContents = createVisiblePosition(end);
  if (startOfContents.isNull() || endOfContents.isNull())
    return;
  moveParagraphWithClones(startOfContents, endOfContents, targetBlockquote,
                          outerBlock, editingState);
}

void IndentOutdentCommand::outdentParagraph(EditingState* editingState) {
  VisiblePosition visibleStartOfParagraph =
      startOfParagraph(endingSelection().visibleStart());
  VisiblePosition visibleEndOfParagraph =
      endOfParagraph(visibleStartOfParagraph);

  HTMLElement* enclosingElement = toHTMLElement(
      enclosingNodeOfType(visibleStartOfParagraph.deepEquivalent(),
                          &isHTMLListOrBlockquoteElement));
  // We can't outdent if there is no place to go!
  if (!enclosingElement || !hasEditableStyle(*enclosingElement->parentNode()))
    return;

  // Use InsertListCommand to remove the selection from the list
  if (isHTMLOListElement(*enclosingElement)) {
    applyCommandToComposite(
        InsertListCommand::create(document(), InsertListCommand::OrderedList),
        editingState);
    return;
  }
  if (isHTMLUListElement(*enclosingElement)) {
    applyCommandToComposite(
        InsertListCommand::create(document(), InsertListCommand::UnorderedList),
        editingState);
    return;
  }

  // The selection is inside a blockquote i.e. enclosingNode is a blockquote
  VisiblePosition positionInEnclosingBlock =
      VisiblePosition::firstPositionInNode(enclosingElement);
  // If the blockquote is inline, the start of the enclosing block coincides
  // with positionInEnclosingBlock.
  VisiblePosition startOfEnclosingBlock =
      (enclosingElement->layoutObject() &&
       enclosingElement->layoutObject()->isInline())
          ? positionInEnclosingBlock
          : startOfBlock(positionInEnclosingBlock);
  VisiblePosition lastPositionInEnclosingBlock =
      VisiblePosition::lastPositionInNode(enclosingElement);
  VisiblePosition endOfEnclosingBlock =
      endOfBlock(lastPositionInEnclosingBlock);
  if (visibleStartOfParagraph.deepEquivalent() ==
          startOfEnclosingBlock.deepEquivalent() &&
      visibleEndOfParagraph.deepEquivalent() ==
          endOfEnclosingBlock.deepEquivalent()) {
    // The blockquote doesn't contain anything outside the paragraph, so it can
    // be totally removed.
    Node* splitPoint = enclosingElement->nextSibling();
    removeNodePreservingChildren(enclosingElement, editingState);
    if (editingState->isAborted())
      return;
    // outdentRegion() assumes it is operating on the first paragraph of an
    // enclosing blockquote, but if there are multiply nested blockquotes and
    // we've just removed one, then this assumption isn't true. By splitting the
    // next containing blockquote after this node, we keep this assumption true
    if (splitPoint) {
      if (Element* splitPointParent = splitPoint->parentElement()) {
        // We can't outdent if there is no place to go!
        if (splitPointParent->hasTagName(blockquoteTag) &&
            !splitPoint->hasTagName(blockquoteTag) &&
            hasEditableStyle(*splitPointParent->parentNode()))
          splitElement(splitPointParent, splitPoint);
      }
    }

    document().updateStyleAndLayoutIgnorePendingStylesheets();
    visibleStartOfParagraph =
        createVisiblePosition(visibleStartOfParagraph.deepEquivalent());
    if (visibleStartOfParagraph.isNotNull() &&
        !isStartOfParagraph(visibleStartOfParagraph)) {
      insertNodeAt(HTMLBRElement::create(document()),
                   visibleStartOfParagraph.deepEquivalent(), editingState);
      if (editingState->isAborted())
        return;
    }

    document().updateStyleAndLayoutIgnorePendingStylesheets();
    visibleEndOfParagraph =
        createVisiblePosition(visibleEndOfParagraph.deepEquivalent());
    if (visibleEndOfParagraph.isNotNull() &&
        !isEndOfParagraph(visibleEndOfParagraph))
      insertNodeAt(HTMLBRElement::create(document()),
                   visibleEndOfParagraph.deepEquivalent(), editingState);
    return;
  }

  Node* splitBlockquoteNode = enclosingElement;
  if (Element* enclosingBlockFlow = enclosingBlock(
          visibleStartOfParagraph.deepEquivalent().anchorNode())) {
    if (enclosingBlockFlow != enclosingElement) {
      splitBlockquoteNode =
          splitTreeToNode(enclosingBlockFlow, enclosingElement, true);
    } else {
      // We split the blockquote at where we start outdenting.
      Node* highestInlineNode = highestEnclosingNodeOfType(
          visibleStartOfParagraph.deepEquivalent(), isInline,
          CannotCrossEditingBoundary, enclosingBlockFlow);
      splitElement(enclosingElement,
                   highestInlineNode
                       ? highestInlineNode
                       : visibleStartOfParagraph.deepEquivalent().anchorNode());
    }

    document().updateStyleAndLayoutIgnorePendingStylesheets();

    // Re-canonicalize visible{Start,End}OfParagraph, make them valid again
    // after DOM change.
    // TODO(xiaochengh): We should not store a VisiblePosition and later inspect
    // its properties when it is already invalidated.
    visibleStartOfParagraph =
        createVisiblePosition(visibleStartOfParagraph.toPositionWithAffinity());
    visibleEndOfParagraph =
        createVisiblePosition(visibleEndOfParagraph.toPositionWithAffinity());
  }

  // TODO(xiaochengh): We should not store a VisiblePosition and later inspect
  // its properties when it is already invalidated.
  VisiblePosition startOfParagraphToMove =
      startOfParagraph(visibleStartOfParagraph);
  VisiblePosition endOfParagraphToMove = endOfParagraph(visibleEndOfParagraph);
  if (startOfParagraphToMove.isNull() || endOfParagraphToMove.isNull())
    return;
  HTMLBRElement* placeholder = HTMLBRElement::create(document());
  insertNodeBefore(placeholder, splitBlockquoteNode, editingState);
  if (editingState->isAborted())
    return;

  document().updateStyleAndLayoutIgnorePendingStylesheets();
  startOfParagraphToMove =
      createVisiblePosition(startOfParagraphToMove.toPositionWithAffinity());
  endOfParagraphToMove =
      createVisiblePosition(endOfParagraphToMove.toPositionWithAffinity());
  moveParagraph(startOfParagraphToMove, endOfParagraphToMove,
                VisiblePosition::beforeNode(placeholder), editingState,
                PreserveSelection);
}

// FIXME: We should merge this function with
// ApplyBlockElementCommand::formatSelection
void IndentOutdentCommand::outdentRegion(
    const VisiblePosition& startOfSelection,
    const VisiblePosition& endOfSelection,
    EditingState* editingState) {
  VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
  VisiblePosition endOfLastParagraph = endOfParagraph(endOfSelection);

  if (endOfCurrentParagraph.deepEquivalent() ==
      endOfLastParagraph.deepEquivalent()) {
    outdentParagraph(editingState);
    return;
  }

  Position originalSelectionEnd = endingSelection().end();
  Position endAfterSelection =
      endOfParagraph(nextPositionOf(endOfLastParagraph)).deepEquivalent();

  while (endOfCurrentParagraph.deepEquivalent() != endAfterSelection) {
    PositionWithAffinity endOfNextParagraph =
        endOfParagraph(nextPositionOf(endOfCurrentParagraph))
            .toPositionWithAffinity();
    if (endOfCurrentParagraph.deepEquivalent() ==
        endOfLastParagraph.deepEquivalent()) {
      SelectionInDOMTree::Builder builder;
      if (originalSelectionEnd.isNotNull())
        builder.collapse(originalSelectionEnd);
      setEndingSelection(builder.build());
    } else {
      setEndingSelection(SelectionInDOMTree::Builder()
                             .collapse(endOfCurrentParagraph.deepEquivalent())
                             .build());
    }

    outdentParagraph(editingState);
    if (editingState->isAborted())
      return;

    // outdentParagraph could move more than one paragraph if the paragraph
    // is in a list item. As a result, endAfterSelection and endOfNextParagraph
    // could refer to positions no longer in the document.
    if (endAfterSelection.isNotNull() && !endAfterSelection.isConnected())
      break;

    document().updateStyleAndLayoutIgnorePendingStylesheets();
    if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.isConnected()) {
      endOfCurrentParagraph = createVisiblePosition(endingSelection().end());
      endOfNextParagraph = endOfParagraph(nextPositionOf(endOfCurrentParagraph))
                               .toPositionWithAffinity();
    }
    endOfCurrentParagraph = createVisiblePosition(endOfNextParagraph);
  }
}

void IndentOutdentCommand::formatSelection(
    const VisiblePosition& startOfSelection,
    const VisiblePosition& endOfSelection,
    EditingState* editingState) {
  if (m_typeOfAction == Indent)
    ApplyBlockElementCommand::formatSelection(startOfSelection, endOfSelection,
                                              editingState);
  else
    outdentRegion(startOfSelection, endOfSelection, editingState);
}

void IndentOutdentCommand::formatRange(const Position& start,
                                       const Position& end,
                                       const Position&,
                                       HTMLElement*& blockquoteForNextIndent,
                                       EditingState* editingState) {
  bool indentingAsListItemResult =
      tryIndentingAsListItem(start, end, editingState);
  if (editingState->isAborted())
    return;
  if (indentingAsListItemResult)
    blockquoteForNextIndent = nullptr;
  else
    indentIntoBlockquote(start, end, blockquoteForNextIndent, editingState);
}

InputEvent::InputType IndentOutdentCommand::inputType() const {
  return m_typeOfAction == Indent ? InputEvent::InputType::FormatIndent
                                  : InputEvent::InputType::FormatOutdent;
}

}  // namespace blink