Add initial is<>() / downcast<>() support for any type of Nodes
[WebKit-https.git] / Source / WebCore / editing / FrameSelection.cpp
1 /*
2  * Copyright (C) 2004, 2008, 2009, 2010, 2014 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25   
26 #include "config.h"
27 #include "FrameSelection.h"
28
29 #include "CharacterData.h"
30 #include "DeleteSelectionCommand.h"
31 #include "Document.h"
32 #include "Editor.h"
33 #include "EditorClient.h"
34 #include "Element.h"
35 #include "ElementIterator.h"
36 #include "EventHandler.h"
37 #include "ExceptionCode.h"
38 #include "FloatQuad.h"
39 #include "FocusController.h"
40 #include "Frame.h"
41 #include "FrameTree.h"
42 #include "FrameView.h"
43 #include "GraphicsContext.h"
44 #include "HTMLBodyElement.h"
45 #include "HTMLFormElement.h"
46 #include "HTMLFrameElementBase.h"
47 #include "HTMLInputElement.h"
48 #include "HTMLSelectElement.h"
49 #include "HTMLNames.h"
50 #include "HitTestRequest.h"
51 #include "HitTestResult.h"
52 #include "InlineTextBox.h"
53 #include "Page.h"
54 #include "RenderText.h"
55 #include "RenderTextControl.h"
56 #include "RenderTheme.h"
57 #include "RenderView.h"
58 #include "RenderWidget.h"
59 #include "RenderedPosition.h"
60 #include "Settings.h"
61 #include "SpatialNavigation.h"
62 #include "StyleProperties.h"
63 #include "TypingCommand.h"
64 #include "VisibleUnits.h"
65 #include "htmlediting.h"
66 #include <stdio.h>
67 #include <wtf/text/CString.h>
68
69 #if PLATFORM(IOS)
70 #include "Chrome.h"
71 #include "ChromeClient.h"
72 #include "Color.h"
73 #include "RenderLayer.h"
74 #include "RenderObject.h"
75 #include "RenderStyle.h"
76 #endif
77
78 #define EDIT_DEBUG 0
79
80 namespace WebCore {
81
82 using namespace HTMLNames;
83
84 static inline LayoutUnit NoXPosForVerticalArrowNavigation()
85 {
86     return LayoutUnit::min();
87 }
88
89 CaretBase::CaretBase(CaretVisibility visibility)
90     : m_caretRectNeedsUpdate(true)
91     , m_caretVisibility(visibility)
92 {
93 }
94
95 DragCaretController::DragCaretController()
96     : CaretBase(Visible)
97 {
98 }
99
100 bool DragCaretController::isContentRichlyEditable() const
101 {
102     return isRichlyEditablePosition(m_position.deepEquivalent());
103 }
104
105 static inline bool shouldAlwaysUseDirectionalSelection(Frame* frame)
106 {
107     return !frame || frame->editor().behavior().shouldConsiderSelectionAsDirectional();
108 }
109
110 FrameSelection::FrameSelection(Frame* frame)
111     : m_frame(frame)
112     , m_xPosForVerticalArrowNavigation(NoXPosForVerticalArrowNavigation())
113     , m_granularity(CharacterGranularity)
114     , m_caretBlinkTimer(this, &FrameSelection::caretBlinkTimerFired)
115     , m_absCaretBoundsDirty(true)
116     , m_caretPaint(true)
117     , m_isCaretBlinkingSuspended(false)
118     , m_focused(frame && frame->page() && frame->page()->focusController().focusedFrame() == frame)
119     , m_shouldShowBlockCursor(false)
120     , m_pendingSelectionUpdate(false)
121     , m_shouldRevealSelection(false)
122     , m_alwaysAlignCursorOnScrollWhenRevealingSelection(false)
123 #if PLATFORM(IOS)
124     , m_updateAppearanceEnabled(false)
125     , m_caretBlinks(true)
126     , m_scrollingSuppressCount(0)
127 #endif
128 {
129     if (shouldAlwaysUseDirectionalSelection(m_frame))
130         m_selection.setIsDirectional(true);
131 }
132
133 Element* FrameSelection::rootEditableElementOrDocumentElement() const
134 {
135     Element* selectionRoot = m_selection.rootEditableElement();
136     return selectionRoot ? selectionRoot : m_frame->document()->documentElement();
137 }
138
139 void FrameSelection::moveTo(const VisiblePosition &pos, EUserTriggered userTriggered, CursorAlignOnScroll align)
140 {
141     setSelection(VisibleSelection(pos.deepEquivalent(), pos.deepEquivalent(), pos.affinity(), m_selection.isDirectional()),
142         defaultSetSelectionOptions(userTriggered), align);
143 }
144
145 void FrameSelection::moveTo(const VisiblePosition &base, const VisiblePosition &extent, EUserTriggered userTriggered)
146 {
147     const bool selectionHasDirection = true;
148     setSelection(VisibleSelection(base.deepEquivalent(), extent.deepEquivalent(), base.affinity(), selectionHasDirection), defaultSetSelectionOptions(userTriggered));
149 }
150
151 void FrameSelection::moveTo(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)
152 {
153     setSelection(VisibleSelection(pos, affinity, m_selection.isDirectional()), defaultSetSelectionOptions(userTriggered));
154 }
155
156 void FrameSelection::moveTo(const Range* range)
157 {
158     VisibleSelection selection = range ? VisibleSelection(range->startPosition(), range->endPosition()) : VisibleSelection();
159     setSelection(selection);
160 }
161
162 void FrameSelection::moveTo(const Position &base, const Position &extent, EAffinity affinity, EUserTriggered userTriggered)
163 {
164     const bool selectionHasDirection = true;
165     setSelection(VisibleSelection(base, extent, affinity, selectionHasDirection), defaultSetSelectionOptions(userTriggered));
166 }
167
168 void FrameSelection::moveWithoutValidationTo(const Position& base, const Position& extent, bool selectionHasDirection, bool shouldSetFocus)
169 {
170     VisibleSelection newSelection;
171     newSelection.setWithoutValidation(base, extent);
172     newSelection.setIsDirectional(selectionHasDirection);
173     setSelection(newSelection, defaultSetSelectionOptions() | (shouldSetFocus ? 0 : DoNotSetFocus));
174 }
175
176 void DragCaretController::setCaretPosition(const VisiblePosition& position)
177 {
178     if (Node* node = m_position.deepEquivalent().deprecatedNode())
179         invalidateCaretRect(node);
180     m_position = position;
181     setCaretRectNeedsUpdate();
182     Document* document = 0;
183     if (Node* node = m_position.deepEquivalent().deprecatedNode()) {
184         invalidateCaretRect(node);
185         document = &node->document();
186     }
187     if (m_position.isNull() || m_position.isOrphan())
188         clearCaretRect();
189     else
190         updateCaretRect(document, m_position);
191 }
192
193 static void adjustEndpointsAtBidiBoundary(VisiblePosition& visibleBase, VisiblePosition& visibleExtent)
194 {
195     RenderedPosition base(visibleBase);
196     RenderedPosition extent(visibleExtent);
197
198     if (base.isNull() || extent.isNull() || base.isEquivalent(extent))
199         return;
200
201     if (base.atLeftBoundaryOfBidiRun()) {
202         if (!extent.atRightBoundaryOfBidiRun(base.bidiLevelOnRight())
203             && base.isEquivalent(extent.leftBoundaryOfBidiRun(base.bidiLevelOnRight()))) {
204             visibleBase = base.positionAtLeftBoundaryOfBiDiRun();
205             return;
206         }
207         return;
208     }
209
210     if (base.atRightBoundaryOfBidiRun()) {
211         if (!extent.atLeftBoundaryOfBidiRun(base.bidiLevelOnLeft())
212             && base.isEquivalent(extent.rightBoundaryOfBidiRun(base.bidiLevelOnLeft()))) {
213             visibleBase = base.positionAtRightBoundaryOfBiDiRun();
214             return;
215         }
216         return;
217     }
218
219     if (extent.atLeftBoundaryOfBidiRun() && extent.isEquivalent(base.leftBoundaryOfBidiRun(extent.bidiLevelOnRight()))) {
220         visibleExtent = extent.positionAtLeftBoundaryOfBiDiRun();
221         return;
222     }
223
224     if (extent.atRightBoundaryOfBidiRun() && extent.isEquivalent(base.rightBoundaryOfBidiRun(extent.bidiLevelOnLeft()))) {
225         visibleExtent = extent.positionAtRightBoundaryOfBiDiRun();
226         return;
227     }
228 }
229
230 void FrameSelection::setSelectionByMouseIfDifferent(const VisibleSelection& passedNewSelection, TextGranularity granularity,
231     EndPointsAdjustmentMode endpointsAdjustmentMode)
232 {
233     VisibleSelection newSelection = passedNewSelection;
234     bool isDirectional = shouldAlwaysUseDirectionalSelection(m_frame) || newSelection.isDirectional();
235
236     VisiblePosition base = m_originalBase.isNotNull() ? m_originalBase : newSelection.visibleBase();
237     VisiblePosition newBase = base;
238     VisiblePosition extent = newSelection.visibleExtent();
239     VisiblePosition newExtent = extent;
240     if (endpointsAdjustmentMode == AdjustEndpointsAtBidiBoundary)
241         adjustEndpointsAtBidiBoundary(newBase, newExtent);
242
243     if (newBase != base || newExtent != extent) {
244         m_originalBase = base;
245         newSelection.setBase(newBase);
246         newSelection.setExtent(newExtent);
247     } else if (m_originalBase.isNotNull()) {
248         if (m_selection.base() == newSelection.base())
249             newSelection.setBase(m_originalBase);
250         m_originalBase.clear();
251     }
252
253     newSelection.setIsDirectional(isDirectional); // Adjusting base and extent will make newSelection always directional
254     if (m_selection == newSelection || !shouldChangeSelection(newSelection))
255         return;
256
257     setSelection(newSelection, defaultSetSelectionOptions() | FireSelectEvent, AlignCursorOnScrollIfNeeded, granularity);
258 }
259
260 bool FrameSelection::setSelectionWithoutUpdatingAppearance(const VisibleSelection& newSelectionPossiblyWithoutDirection, SetSelectionOptions options, CursorAlignOnScroll align, TextGranularity granularity)
261 {
262     bool closeTyping = options & CloseTyping;
263     bool shouldClearTypingStyle = options & ClearTypingStyle;
264
265     VisibleSelection newSelection = newSelectionPossiblyWithoutDirection;
266     if (shouldAlwaysUseDirectionalSelection(m_frame))
267         newSelection.setIsDirectional(true);
268
269     if (!m_frame) {
270         m_selection = newSelection;
271         return false;
272     }
273
274     // <http://bugs.webkit.org/show_bug.cgi?id=23464>: Infinite recursion at FrameSelection::setSelection
275     // if document->frame() == m_frame we can get into an infinite loop
276     if (Document* newSelectionDocument = newSelection.base().document()) {
277         if (RefPtr<Frame> newSelectionFrame = newSelectionDocument->frame()) {
278             if (newSelectionFrame != m_frame && newSelectionDocument != m_frame->document()) {
279                 newSelectionFrame->selection().setSelection(newSelection, options, align, granularity);
280                 // It's possible that during the above set selection, this FrameSelection has been modified by
281                 // selectFrameElementInParentIfFullySelected, but that the selection is no longer valid since
282                 // the frame is about to be destroyed. If this is the case, clear our selection.
283                 if (newSelectionFrame->hasOneRef() && !m_selection.isNonOrphanedCaretOrRange())
284                     clear();
285                 return false;
286             }
287         }
288     }
289
290     m_granularity = granularity;
291
292     if (closeTyping)
293         TypingCommand::closeTyping(m_frame);
294
295     if (shouldClearTypingStyle)
296         clearTypingStyle();
297
298     VisibleSelection oldSelection = m_selection;
299     m_selection = newSelection;
300
301     // Selection offsets should increase when LF is inserted before the caret in InsertLineBreakCommand. See <https://webkit.org/b/56061>.
302     if (HTMLTextFormControlElement* textControl = enclosingTextFormControl(newSelection.start()))
303         textControl->selectionChanged(options & FireSelectEvent);
304
305     if (oldSelection == newSelection)
306         return false;
307
308     setCaretRectNeedsUpdate();
309
310     if (!newSelection.isNone() && !(options & DoNotSetFocus))
311         setFocusedElementIfNeeded();
312
313     // Always clear the x position used for vertical arrow navigation.
314     // It will be restored by the vertical arrow navigation code if necessary.
315     m_xPosForVerticalArrowNavigation = NoXPosForVerticalArrowNavigation();
316     selectFrameElementInParentIfFullySelected();
317     m_frame->editor().respondToChangedSelection(oldSelection, options);
318     m_frame->document()->enqueueDocumentEvent(Event::create(eventNames().selectionchangeEvent, false, false));
319
320     return true;
321 }
322
323 void FrameSelection::setSelection(const VisibleSelection& selection, SetSelectionOptions options, CursorAlignOnScroll align, TextGranularity granularity)
324 {
325     if (!setSelectionWithoutUpdatingAppearance(selection, options, align, granularity))
326         return;
327
328     Document* document = m_frame->document();
329     if (!document)
330         return;
331
332     m_shouldRevealSelection = options & RevealSelection;
333     m_alwaysAlignCursorOnScrollWhenRevealingSelection = align == AlignCursorOnScrollAlways;
334
335     m_pendingSelectionUpdate = true;
336
337     if (document->hasPendingStyleRecalc())
338         return;
339
340     FrameView* frameView = document->view();
341     if (frameView && frameView->layoutPending())
342         return;
343
344     updateAndRevealSelection();
345 }
346
347 static void updateSelectionByUpdatingLayoutOrStyle(Frame& frame)
348 {
349 #if ENABLE(TEXT_CARET)
350     frame.document()->updateLayoutIgnorePendingStylesheets();
351 #else
352     frame.document()->updateStyleIfNeeded();
353 #endif
354 }
355
356 void FrameSelection::setNeedsSelectionUpdate()
357 {
358     m_pendingSelectionUpdate = true;
359     if (RenderView* view = m_frame->contentRenderer())
360         view->clearSelection();
361 }
362
363 void FrameSelection::updateAndRevealSelection()
364 {
365     if (!m_pendingSelectionUpdate)
366         return;
367
368     m_pendingSelectionUpdate = false;
369
370     updateAppearance();
371
372     if (m_shouldRevealSelection) {
373         ScrollAlignment alignment;
374
375         if (m_frame->editor().behavior().shouldCenterAlignWhenSelectionIsRevealed())
376             alignment = m_alwaysAlignCursorOnScrollWhenRevealingSelection ? ScrollAlignment::alignCenterAlways : ScrollAlignment::alignCenterIfNeeded;
377         else
378             alignment = m_alwaysAlignCursorOnScrollWhenRevealingSelection ? ScrollAlignment::alignTopAlways : ScrollAlignment::alignToEdgeIfNeeded;
379
380         revealSelection(alignment, RevealExtent);
381     }
382
383     notifyAccessibilityForSelectionChange();
384 }
385
386 void FrameSelection::updateDataDetectorsForSelection()
387 {
388 #if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
389     m_frame->editor().scanSelectionForTelephoneNumbers();
390 #endif
391 }
392
393 static bool removingNodeRemovesPosition(Node* node, const Position& position)
394 {
395     if (!position.anchorNode())
396         return false;
397
398     if (position.anchorNode() == node)
399         return true;
400
401     if (!node->isElementNode())
402         return false;
403
404     Element* element = toElement(node);
405     return element->containsIncludingShadowDOM(position.anchorNode());
406 }
407
408 static void clearRenderViewSelection(Node& node)
409 {
410     Ref<Document> document(node.document());
411     document->updateStyleIfNeeded();
412     if (RenderView* view = document->renderView())
413         view->clearSelection();
414 }
415
416 void DragCaretController::nodeWillBeRemoved(Node* node)
417 {
418     if (!hasCaret() || (node && !node->inDocument()))
419         return;
420
421     if (!removingNodeRemovesPosition(node, m_position.deepEquivalent()))
422         return;
423
424     clearRenderViewSelection(*node);
425     clear();
426 }
427
428 void FrameSelection::nodeWillBeRemoved(Node* node)
429 {
430     // There can't be a selection inside a fragment, so if a fragment's node is being removed,
431     // the selection in the document that created the fragment needs no adjustment.
432     if (isNone() || (node && !node->inDocument()))
433         return;
434
435     respondToNodeModification(node, removingNodeRemovesPosition(node, m_selection.base()), removingNodeRemovesPosition(node, m_selection.extent()),
436         removingNodeRemovesPosition(node, m_selection.start()), removingNodeRemovesPosition(node, m_selection.end()));
437 }
438
439 void FrameSelection::respondToNodeModification(Node* node, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved)
440 {
441     bool clearRenderTreeSelection = false;
442     bool clearDOMTreeSelection = false;
443
444     if (startRemoved || endRemoved) {
445         Position start = m_selection.start();
446         Position end = m_selection.end();
447         if (startRemoved)
448             updatePositionForNodeRemoval(start, node);
449         if (endRemoved)
450             updatePositionForNodeRemoval(end, node);
451
452         if (start.isNotNull() && end.isNotNull()) {
453             if (m_selection.isBaseFirst())
454                 m_selection.setWithoutValidation(start, end);
455             else
456                 m_selection.setWithoutValidation(end, start);
457         } else
458             clearDOMTreeSelection = true;
459
460         clearRenderTreeSelection = true;
461     } else if (baseRemoved || extentRemoved) {
462         // The base and/or extent are about to be removed, but the start and end aren't.
463         // Change the base and extent to the start and end, but don't re-validate the
464         // selection, since doing so could move the start and end into the node
465         // that is about to be removed.
466         if (m_selection.isBaseFirst())
467             m_selection.setWithoutValidation(m_selection.start(), m_selection.end());
468         else
469             m_selection.setWithoutValidation(m_selection.end(), m_selection.start());
470     } else if (RefPtr<Range> range = m_selection.firstRange()) {
471         ExceptionCode ec = 0;
472         Range::CompareResults compareResult = range->compareNode(node, ec);
473         if (!ec && (compareResult == Range::NODE_BEFORE_AND_AFTER || compareResult == Range::NODE_INSIDE)) {
474             // If we did nothing here, when this node's renderer was destroyed, the rect that it 
475             // occupied would be invalidated, but, selection gaps that change as a result of 
476             // the removal wouldn't be invalidated.
477             // FIXME: Don't do so much unnecessary invalidation.
478             clearRenderTreeSelection = true;
479         }
480     }
481
482     if (clearRenderTreeSelection) {
483         clearRenderViewSelection(*node);
484
485         // Trigger a selection update so the selection will be set again.
486         if (auto* renderView = node->document().renderView()) {
487             m_pendingSelectionUpdate = true;
488             renderView->setNeedsLayout();
489         }
490     }
491
492     if (clearDOMTreeSelection)
493         setSelection(VisibleSelection(), DoNotSetFocus);
494 }
495
496 static void updatePositionAfterAdoptingTextReplacement(Position& position, CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
497 {
498     if (!position.anchorNode() || position.anchorNode() != node || position.anchorType() != Position::PositionIsOffsetInAnchor)
499         return;
500
501     // See: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Mutation
502     ASSERT(position.offsetInContainerNode() >= 0);
503     unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());
504     // Replacing text can be viewed as a deletion followed by insertion.
505     if (positionOffset >= offset && positionOffset <= offset + oldLength)
506         position.moveToOffset(offset);
507
508     // Adjust the offset if the position is after the end of the deleted contents
509     // (positionOffset > offset + oldLength) to avoid having a stale offset.
510     if (positionOffset > offset + oldLength)
511         position.moveToOffset(positionOffset - oldLength + newLength);
512
513     ASSERT(static_cast<unsigned>(position.offsetInContainerNode()) <= node->length());
514 }
515
516 void FrameSelection::textWasReplaced(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
517 {
518     // The fragment check is a performance optimization. See http://trac.webkit.org/changeset/30062.
519     if (isNone() || !node || !node->inDocument())
520         return;
521
522     Position base = m_selection.base();
523     Position extent = m_selection.extent();
524     Position start = m_selection.start();
525     Position end = m_selection.end();
526     updatePositionAfterAdoptingTextReplacement(base, node, offset, oldLength, newLength);
527     updatePositionAfterAdoptingTextReplacement(extent, node, offset, oldLength, newLength);
528     updatePositionAfterAdoptingTextReplacement(start, node, offset, oldLength, newLength);
529     updatePositionAfterAdoptingTextReplacement(end, node, offset, oldLength, newLength);
530
531     if (base != m_selection.base() || extent != m_selection.extent() || start != m_selection.start() || end != m_selection.end()) {
532         VisibleSelection newSelection;
533         if (base != extent)
534             newSelection.setWithoutValidation(base, extent);
535         else if (m_selection.isDirectional() && !m_selection.isBaseFirst())
536             newSelection.setWithoutValidation(end, start);
537         else
538             newSelection.setWithoutValidation(start, end);
539
540         setSelection(newSelection, DoNotSetFocus);
541     }
542 }
543
544 TextDirection FrameSelection::directionOfEnclosingBlock()
545 {
546     return WebCore::directionOfEnclosingBlock(m_selection.extent());
547 }
548
549 TextDirection FrameSelection::directionOfSelection()
550 {
551     InlineBox* startBox = 0;
552     InlineBox* endBox = 0;
553     int unusedOffset;
554     // Cache the VisiblePositions because visibleStart() and visibleEnd()
555     // can cause layout, which has the potential to invalidate lineboxes.
556     VisiblePosition startPosition = m_selection.visibleStart();
557     VisiblePosition endPosition = m_selection.visibleEnd();
558     if (startPosition.isNotNull())
559         startPosition.getInlineBoxAndOffset(startBox, unusedOffset);
560     if (endPosition.isNotNull())
561         endPosition.getInlineBoxAndOffset(endBox, unusedOffset);
562     if (startBox && endBox && startBox->direction() == endBox->direction())
563         return startBox->direction();
564
565     return directionOfEnclosingBlock();
566 }
567
568 void FrameSelection::willBeModified(EAlteration alter, SelectionDirection direction)
569 {
570     if (alter != AlterationExtend)
571         return;
572
573     Position start = m_selection.start();
574     Position end = m_selection.end();
575
576     bool baseIsStart = true;
577
578     if (m_selection.isDirectional()) {
579         // Make base and extent match start and end so we extend the user-visible selection.
580         // This only matters for cases where base and extend point to different positions than
581         // start and end (e.g. after a double-click to select a word).
582         if (m_selection.isBaseFirst())
583             baseIsStart = true;
584         else
585             baseIsStart = false;
586     } else {
587         switch (direction) {
588         case DirectionRight:
589             if (directionOfSelection() == LTR)
590                 baseIsStart = true;
591             else
592                 baseIsStart = false;
593             break;
594         case DirectionForward:
595             baseIsStart = true;
596             break;
597         case DirectionLeft:
598             if (directionOfSelection() == LTR)
599                 baseIsStart = false;
600             else
601                 baseIsStart = true;
602             break;
603         case DirectionBackward:
604             baseIsStart = false;
605             break;
606         }
607     }
608     if (baseIsStart) {
609         m_selection.setBase(start);
610         m_selection.setExtent(end);
611     } else {
612         m_selection.setBase(end);
613         m_selection.setExtent(start);
614     }
615 }
616
617 VisiblePosition FrameSelection::positionForPlatform(bool isGetStart) const
618 {
619     if (m_frame && (m_frame->settings().editingBehaviorType() == EditingMacBehavior || m_frame->settings().editingBehaviorType() == EditingIOSBehavior))
620         return isGetStart ? m_selection.visibleStart() : m_selection.visibleEnd();
621     // Linux and Windows always extend selections from the extent endpoint.
622     // FIXME: VisibleSelection should be fixed to ensure as an invariant that
623     // base/extent always point to the same nodes as start/end, but which points
624     // to which depends on the value of isBaseFirst. Then this can be changed
625     // to just return m_sel.extent().
626     return m_selection.isBaseFirst() ? m_selection.visibleEnd() : m_selection.visibleStart();
627 }
628
629 VisiblePosition FrameSelection::startForPlatform() const
630 {
631     return positionForPlatform(true);
632 }
633
634 VisiblePosition FrameSelection::endForPlatform() const
635 {
636     return positionForPlatform(false);
637 }
638
639 VisiblePosition FrameSelection::nextWordPositionForPlatform(const VisiblePosition &originalPosition)
640 {
641     VisiblePosition positionAfterCurrentWord = nextWordPosition(originalPosition);
642
643     if (m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight()) {
644         // In order to skip spaces when moving right, we advance one
645         // word further and then move one word back. Given the
646         // semantics of previousWordPosition() this will put us at the
647         // beginning of the word following.
648         VisiblePosition positionAfterSpacingAndFollowingWord = nextWordPosition(positionAfterCurrentWord);
649         if (positionAfterSpacingAndFollowingWord != positionAfterCurrentWord)
650             positionAfterCurrentWord = previousWordPosition(positionAfterSpacingAndFollowingWord);
651
652         bool movingBackwardsMovedPositionToStartOfCurrentWord = positionAfterCurrentWord == previousWordPosition(nextWordPosition(originalPosition));
653         if (movingBackwardsMovedPositionToStartOfCurrentWord)
654             positionAfterCurrentWord = positionAfterSpacingAndFollowingWord;
655     }
656     return positionAfterCurrentWord;
657 }
658
659 #if ENABLE(USERSELECT_ALL)
660 static void adjustPositionForUserSelectAll(VisiblePosition& pos, bool isForward)
661 {
662     if (Node* rootUserSelectAll = Position::rootUserSelectAllForNode(pos.deepEquivalent().anchorNode()))
663         pos = isForward ? positionAfterNode(rootUserSelectAll).downstream(CanCrossEditingBoundary) : positionBeforeNode(rootUserSelectAll).upstream(CanCrossEditingBoundary);
664 }
665 #endif
666
667 VisiblePosition FrameSelection::modifyExtendingRight(TextGranularity granularity)
668 {
669     VisiblePosition pos(m_selection.extent(), m_selection.affinity());
670
671     // The difference between modifyExtendingRight and modifyExtendingForward is:
672     // modifyExtendingForward always extends forward logically.
673     // modifyExtendingRight behaves the same as modifyExtendingForward except for extending character or word,
674     // it extends forward logically if the enclosing block is LTR direction,
675     // but it extends backward logically if the enclosing block is RTL direction.
676     switch (granularity) {
677     case CharacterGranularity:
678         if (directionOfEnclosingBlock() == LTR)
679             pos = pos.next(CannotCrossEditingBoundary);
680         else
681             pos = pos.previous(CannotCrossEditingBoundary);
682         break;
683     case WordGranularity:
684         if (directionOfEnclosingBlock() == LTR)
685             pos = nextWordPositionForPlatform(pos);
686         else
687             pos = previousWordPosition(pos);
688         break;
689     case LineBoundary:
690         if (directionOfEnclosingBlock() == LTR)
691             pos = modifyExtendingForward(granularity);
692         else
693             pos = modifyExtendingBackward(granularity);
694         break;
695     case SentenceGranularity:
696     case LineGranularity:
697     case ParagraphGranularity:
698     case SentenceBoundary:
699     case ParagraphBoundary:
700     case DocumentBoundary:
701         // FIXME: implement all of the above?
702         pos = modifyExtendingForward(granularity);
703         break;
704     case DocumentGranularity:
705         ASSERT_NOT_REACHED();
706         break;
707     }
708 #if ENABLE(USERSELECT_ALL)
709     adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);
710 #endif
711     return pos;
712 }
713
714 VisiblePosition FrameSelection::modifyExtendingForward(TextGranularity granularity)
715 {
716     VisiblePosition pos(m_selection.extent(), m_selection.affinity());
717     switch (granularity) {
718     case CharacterGranularity:
719         pos = pos.next(CannotCrossEditingBoundary);
720         break;
721     case WordGranularity:
722         pos = nextWordPositionForPlatform(pos);
723         break;
724     case SentenceGranularity:
725         pos = nextSentencePosition(pos);
726         break;
727     case LineGranularity:
728         pos = nextLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));
729         break;
730     case ParagraphGranularity:
731         pos = nextParagraphPosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));
732         break;
733     case DocumentGranularity:
734         ASSERT_NOT_REACHED();
735         break;
736     case SentenceBoundary:
737         pos = endOfSentence(endForPlatform());
738         break;
739     case LineBoundary:
740         pos = logicalEndOfLine(endForPlatform());
741         break;
742     case ParagraphBoundary:
743         pos = endOfParagraph(endForPlatform());
744         break;
745     case DocumentBoundary:
746         pos = endForPlatform();
747         if (isEditablePosition(pos.deepEquivalent()))
748             pos = endOfEditableContent(pos);
749         else
750             pos = endOfDocument(pos);
751         break;
752     }
753 #if ENABLE(USERSELECT_ALL)
754      adjustPositionForUserSelectAll(pos, directionOfEnclosingBlock() == LTR);
755 #endif
756     return pos;
757 }
758
759 VisiblePosition FrameSelection::modifyMovingRight(TextGranularity granularity)
760 {
761     VisiblePosition pos;
762     switch (granularity) {
763     case CharacterGranularity:
764         if (isRange()) {
765             if (directionOfSelection() == LTR)
766                 pos = VisiblePosition(m_selection.end(), m_selection.affinity());
767             else
768                 pos = VisiblePosition(m_selection.start(), m_selection.affinity());
769         } else
770             pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).right(true);
771         break;
772     case WordGranularity: {
773         // Visual word movement relies on isWordTextBreak which is not implemented in WinCE and QT.
774         // https://bugs.webkit.org/show_bug.cgi?id=81136.
775         bool skipsSpaceWhenMovingRight = m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight();
776         pos = rightWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()), skipsSpaceWhenMovingRight);
777         break;
778     }
779     case SentenceGranularity:
780     case LineGranularity:
781     case ParagraphGranularity:
782     case SentenceBoundary:
783     case ParagraphBoundary:
784     case DocumentBoundary:
785         // FIXME: Implement all of the above.
786         pos = modifyMovingForward(granularity);
787         break;
788     case LineBoundary:
789         pos = rightBoundaryOfLine(startForPlatform(), directionOfEnclosingBlock());
790         break;
791     case DocumentGranularity:
792         ASSERT_NOT_REACHED();
793         break;
794     }
795     return pos;
796 }
797
798 VisiblePosition FrameSelection::modifyMovingForward(TextGranularity granularity)
799 {
800     VisiblePosition pos;
801     // FIXME: Stay in editable content for the less common granularities.
802     switch (granularity) {
803     case CharacterGranularity:
804         if (isRange())
805             pos = VisiblePosition(m_selection.end(), m_selection.affinity());
806         else
807             pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).next(CannotCrossEditingBoundary);
808         break;
809     case WordGranularity:
810         pos = nextWordPositionForPlatform(VisiblePosition(m_selection.extent(), m_selection.affinity()));
811         break;
812     case SentenceGranularity:
813         pos = nextSentencePosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));
814         break;
815     case LineGranularity: {
816         // down-arrowing from a range selection that ends at the start of a line needs
817         // to leave the selection at that line start (no need to call nextLinePosition!)
818         pos = endForPlatform();
819         if (!isRange() || !isStartOfLine(pos))
820             pos = nextLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(START));
821         break;
822     }
823     case ParagraphGranularity:
824         pos = nextParagraphPosition(endForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));
825         break;
826     case DocumentGranularity:
827         ASSERT_NOT_REACHED();
828         break;
829     case SentenceBoundary:
830         pos = endOfSentence(endForPlatform());
831         break;
832     case LineBoundary:
833         pos = logicalEndOfLine(endForPlatform());
834         break;
835     case ParagraphBoundary:
836         pos = endOfParagraph(endForPlatform());
837         break;
838     case DocumentBoundary:
839         pos = endForPlatform();
840         if (isEditablePosition(pos.deepEquivalent()))
841             pos = endOfEditableContent(pos);
842         else
843             pos = endOfDocument(pos);
844         break;
845     }
846     return pos;
847 }
848
849 VisiblePosition FrameSelection::modifyExtendingLeft(TextGranularity granularity)
850 {
851     VisiblePosition pos(m_selection.extent(), m_selection.affinity());
852
853     // The difference between modifyExtendingLeft and modifyExtendingBackward is:
854     // modifyExtendingBackward always extends backward logically.
855     // modifyExtendingLeft behaves the same as modifyExtendingBackward except for extending character or word,
856     // it extends backward logically if the enclosing block is LTR direction,
857     // but it extends forward logically if the enclosing block is RTL direction.
858     switch (granularity) {
859     case CharacterGranularity:
860         if (directionOfEnclosingBlock() == LTR)
861             pos = pos.previous(CannotCrossEditingBoundary);
862         else
863             pos = pos.next(CannotCrossEditingBoundary);
864         break;
865     case WordGranularity:
866         if (directionOfEnclosingBlock() == LTR)
867             pos = previousWordPosition(pos);
868         else
869             pos = nextWordPositionForPlatform(pos);
870         break;
871     case LineBoundary:
872         if (directionOfEnclosingBlock() == LTR)
873             pos = modifyExtendingBackward(granularity);
874         else
875             pos = modifyExtendingForward(granularity);
876         break;
877     case SentenceGranularity:
878     case LineGranularity:
879     case ParagraphGranularity:
880     case SentenceBoundary:
881     case ParagraphBoundary:
882     case DocumentBoundary:
883         pos = modifyExtendingBackward(granularity);
884         break;
885     case DocumentGranularity:
886         ASSERT_NOT_REACHED();
887         break;
888     }
889 #if ENABLE(USERSELECT_ALL)
890     adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));
891 #endif
892     return pos;
893 }
894        
895 VisiblePosition FrameSelection::modifyExtendingBackward(TextGranularity granularity)
896 {
897     VisiblePosition pos(m_selection.extent(), m_selection.affinity());
898
899     // Extending a selection backward by word or character from just after a table selects
900     // the table.  This "makes sense" from the user perspective, esp. when deleting.
901     // It was done here instead of in VisiblePosition because we want VPs to iterate
902     // over everything.
903     switch (granularity) {
904     case CharacterGranularity:
905         pos = pos.previous(CannotCrossEditingBoundary);
906         break;
907     case WordGranularity:
908         pos = previousWordPosition(pos);
909         break;
910     case SentenceGranularity:
911         pos = previousSentencePosition(pos);
912         break;
913     case LineGranularity:
914         pos = previousLinePosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));
915         break;
916     case ParagraphGranularity:
917         pos = previousParagraphPosition(pos, lineDirectionPointForBlockDirectionNavigation(EXTENT));
918         break;
919     case SentenceBoundary:
920         pos = startOfSentence(startForPlatform());
921         break;
922     case LineBoundary:
923         pos = logicalStartOfLine(startForPlatform());
924         break;
925     case ParagraphBoundary:
926         pos = startOfParagraph(startForPlatform());
927         break;
928     case DocumentBoundary:
929         pos = startForPlatform();
930         if (isEditablePosition(pos.deepEquivalent()))
931             pos = startOfEditableContent(pos);
932         else
933             pos = startOfDocument(pos);
934         break;
935     case DocumentGranularity:
936         ASSERT_NOT_REACHED();
937         break;
938     }
939 #if ENABLE(USERSELECT_ALL)
940     adjustPositionForUserSelectAll(pos, !(directionOfEnclosingBlock() == LTR));
941 #endif
942     return pos;
943 }
944
945 VisiblePosition FrameSelection::modifyMovingLeft(TextGranularity granularity)
946 {
947     VisiblePosition pos;
948     switch (granularity) {
949     case CharacterGranularity:
950         if (isRange())
951             if (directionOfSelection() == LTR)
952                 pos = VisiblePosition(m_selection.start(), m_selection.affinity());
953             else
954                 pos = VisiblePosition(m_selection.end(), m_selection.affinity());
955         else
956             pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).left(true);
957         break;
958     case WordGranularity: {
959         bool skipsSpaceWhenMovingRight = m_frame && m_frame->editor().behavior().shouldSkipSpaceWhenMovingRight();
960         pos = leftWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()), skipsSpaceWhenMovingRight);
961         break;
962     }
963     case SentenceGranularity:
964     case LineGranularity:
965     case ParagraphGranularity:
966     case SentenceBoundary:
967     case ParagraphBoundary:
968     case DocumentBoundary:
969         // FIXME: Implement all of the above.
970         pos = modifyMovingBackward(granularity);
971         break;
972     case LineBoundary:
973         pos = leftBoundaryOfLine(startForPlatform(), directionOfEnclosingBlock());
974         break;
975     case DocumentGranularity:
976         ASSERT_NOT_REACHED();
977         break;
978     }
979     return pos;
980 }
981
982 VisiblePosition FrameSelection::modifyMovingBackward(TextGranularity granularity)
983 {
984     VisiblePosition pos;
985     switch (granularity) {
986     case CharacterGranularity:
987         if (isRange())
988             pos = VisiblePosition(m_selection.start(), m_selection.affinity());
989         else
990             pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).previous(CannotCrossEditingBoundary);
991         break;
992     case WordGranularity:
993         pos = previousWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));
994         break;
995     case SentenceGranularity:
996         pos = previousSentencePosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));
997         break;
998     case LineGranularity:
999         pos = previousLinePosition(startForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));
1000         break;
1001     case ParagraphGranularity:
1002         pos = previousParagraphPosition(startForPlatform(), lineDirectionPointForBlockDirectionNavigation(START));
1003         break;
1004     case SentenceBoundary:
1005         pos = startOfSentence(startForPlatform());
1006         break;
1007     case LineBoundary:
1008         pos = logicalStartOfLine(startForPlatform());
1009         break;
1010     case ParagraphBoundary:
1011         pos = startOfParagraph(startForPlatform());
1012         break;
1013     case DocumentBoundary:
1014         pos = startForPlatform();
1015         if (isEditablePosition(pos.deepEquivalent()))
1016             pos = startOfEditableContent(pos);
1017         else
1018             pos = startOfDocument(pos);
1019         break;
1020     case DocumentGranularity:
1021         ASSERT_NOT_REACHED();
1022         break;
1023     }
1024     return pos;
1025 }
1026
1027 static bool isBoundary(TextGranularity granularity)
1028 {
1029     return granularity == LineBoundary || granularity == ParagraphBoundary || granularity == DocumentBoundary;
1030 }    
1031
1032 bool FrameSelection::modify(EAlteration alter, SelectionDirection direction, TextGranularity granularity, EUserTriggered userTriggered)
1033 {
1034     if (userTriggered == UserTriggered) {
1035         FrameSelection trialFrameSelection;
1036         trialFrameSelection.setSelection(m_selection);
1037         trialFrameSelection.modify(alter, direction, granularity, NotUserTriggered);
1038
1039         bool change = shouldChangeSelection(trialFrameSelection.selection());
1040         if (!change)
1041             return false;
1042
1043         if (trialFrameSelection.selection().isRange() && m_selection.isCaret() && !dispatchSelectStart())
1044             return false;
1045     }
1046
1047     willBeModified(alter, direction);
1048
1049     bool wasRange = m_selection.isRange();
1050     Position originalStartPosition = m_selection.start();
1051     VisiblePosition position;
1052     switch (direction) {
1053     case DirectionRight:
1054         if (alter == AlterationMove)
1055             position = modifyMovingRight(granularity);
1056         else
1057             position = modifyExtendingRight(granularity);
1058         break;
1059     case DirectionForward:
1060         if (alter == AlterationExtend)
1061             position = modifyExtendingForward(granularity);
1062         else
1063             position = modifyMovingForward(granularity);
1064         break;
1065     case DirectionLeft:
1066         if (alter == AlterationMove)
1067             position = modifyMovingLeft(granularity);
1068         else
1069             position = modifyExtendingLeft(granularity);
1070         break;
1071     case DirectionBackward:
1072         if (alter == AlterationExtend)
1073             position = modifyExtendingBackward(granularity);
1074         else
1075             position = modifyMovingBackward(granularity);
1076         break;
1077     }
1078
1079     if (position.isNull())
1080         return false;
1081
1082     if (isSpatialNavigationEnabled(m_frame))
1083         if (!wasRange && alter == AlterationMove && position == originalStartPosition)
1084             return false;
1085
1086     // Some of the above operations set an xPosForVerticalArrowNavigation.
1087     // Setting a selection will clear it, so save it to possibly restore later.
1088     // Note: the START position type is arbitrary because it is unused, it would be
1089     // the requested position type if there were no xPosForVerticalArrowNavigation set.
1090     LayoutUnit x = lineDirectionPointForBlockDirectionNavigation(START);
1091     m_selection.setIsDirectional(shouldAlwaysUseDirectionalSelection(m_frame) || alter == AlterationExtend);
1092
1093     switch (alter) {
1094     case AlterationMove:
1095         moveTo(position, userTriggered);
1096         break;
1097     case AlterationExtend:
1098
1099         if (!m_selection.isCaret()
1100             && (granularity == WordGranularity || granularity == ParagraphGranularity || granularity == LineGranularity)
1101             && m_frame && !m_frame->editor().behavior().shouldExtendSelectionByWordOrLineAcrossCaret()) {
1102             // Don't let the selection go across the base position directly. Needed to match mac
1103             // behavior when, for instance, word-selecting backwards starting with the caret in
1104             // the middle of a word and then word-selecting forward, leaving the caret in the
1105             // same place where it was, instead of directly selecting to the end of the word.
1106             VisibleSelection newSelection = m_selection;
1107             newSelection.setExtent(position);
1108             if (m_selection.isBaseFirst() != newSelection.isBaseFirst())
1109                 position = m_selection.base();
1110         }
1111
1112         // Standard Mac behavior when extending to a boundary is grow the selection rather than leaving the
1113         // base in place and moving the extent. Matches NSTextView.
1114         if (!m_frame || !m_frame->editor().behavior().shouldAlwaysGrowSelectionWhenExtendingToBoundary() || m_selection.isCaret() || !isBoundary(granularity))
1115             setExtent(position, userTriggered);
1116         else {
1117             TextDirection textDirection = directionOfEnclosingBlock();
1118             if (direction == DirectionForward || (textDirection == LTR && direction == DirectionRight) || (textDirection == RTL && direction == DirectionLeft))
1119                 setEnd(position, userTriggered);
1120             else
1121                 setStart(position, userTriggered);
1122         }
1123         break;
1124     }
1125     
1126     if (granularity == LineGranularity || granularity == ParagraphGranularity)
1127         m_xPosForVerticalArrowNavigation = x;
1128
1129     if (userTriggered == UserTriggered)
1130         m_granularity = CharacterGranularity;
1131
1132     setCaretRectNeedsUpdate();
1133
1134     return true;
1135 }
1136
1137 // FIXME: Maybe baseline would be better?
1138 static bool absoluteCaretY(const VisiblePosition &c, int &y)
1139 {
1140     IntRect rect = c.absoluteCaretBounds();
1141     if (rect.isEmpty())
1142         return false;
1143     y = rect.y() + rect.height() / 2;
1144     return true;
1145 }
1146
1147 bool FrameSelection::modify(EAlteration alter, unsigned verticalDistance, VerticalDirection direction, EUserTriggered userTriggered, CursorAlignOnScroll align)
1148 {
1149     if (!verticalDistance)
1150         return false;
1151
1152     if (userTriggered == UserTriggered) {
1153         FrameSelection trialFrameSelection;
1154         trialFrameSelection.setSelection(m_selection);
1155         trialFrameSelection.modify(alter, verticalDistance, direction, NotUserTriggered);
1156
1157         bool change = shouldChangeSelection(trialFrameSelection.selection());
1158         if (!change)
1159             return false;
1160     }
1161
1162     willBeModified(alter, direction == DirectionUp ? DirectionBackward : DirectionForward);
1163
1164     VisiblePosition pos;
1165     LayoutUnit xPos = 0;
1166     switch (alter) {
1167     case AlterationMove:
1168         pos = VisiblePosition(direction == DirectionUp ? m_selection.start() : m_selection.end(), m_selection.affinity());
1169         xPos = lineDirectionPointForBlockDirectionNavigation(direction == DirectionUp ? START : END);
1170         m_selection.setAffinity(direction == DirectionUp ? UPSTREAM : DOWNSTREAM);
1171         break;
1172     case AlterationExtend:
1173         pos = VisiblePosition(m_selection.extent(), m_selection.affinity());
1174         xPos = lineDirectionPointForBlockDirectionNavigation(EXTENT);
1175         m_selection.setAffinity(DOWNSTREAM);
1176         break;
1177     }
1178
1179     int startY;
1180     if (!absoluteCaretY(pos, startY))
1181         return false;
1182     if (direction == DirectionUp)
1183         startY = -startY;
1184     int lastY = startY;
1185
1186     VisiblePosition result;
1187     VisiblePosition next;
1188     for (VisiblePosition p = pos; ; p = next) {
1189         if (direction == DirectionUp)
1190             next = previousLinePosition(p, xPos);
1191         else
1192             next = nextLinePosition(p, xPos);
1193
1194         if (next.isNull() || next == p)
1195             break;
1196         int nextY;
1197         if (!absoluteCaretY(next, nextY))
1198             break;
1199         if (direction == DirectionUp)
1200             nextY = -nextY;
1201         if (nextY - startY > static_cast<int>(verticalDistance))
1202             break;
1203         if (nextY >= lastY) {
1204             lastY = nextY;
1205             result = next;
1206         }
1207     }
1208
1209     if (result.isNull())
1210         return false;
1211
1212     switch (alter) {
1213     case AlterationMove:
1214         moveTo(result, userTriggered, align);
1215         break;
1216     case AlterationExtend:
1217         setExtent(result, userTriggered);
1218         break;
1219     }
1220
1221     if (userTriggered == UserTriggered)
1222         m_granularity = CharacterGranularity;
1223
1224     m_selection.setIsDirectional(shouldAlwaysUseDirectionalSelection(m_frame) || alter == AlterationExtend);
1225
1226     return true;
1227 }
1228
1229 LayoutUnit FrameSelection::lineDirectionPointForBlockDirectionNavigation(EPositionType type)
1230 {
1231     LayoutUnit x = 0;
1232
1233     if (isNone())
1234         return x;
1235
1236     Position pos;
1237     switch (type) {
1238     case START:
1239         pos = m_selection.start();
1240         break;
1241     case END:
1242         pos = m_selection.end();
1243         break;
1244     case BASE:
1245         pos = m_selection.base();
1246         break;
1247     case EXTENT:
1248         pos = m_selection.extent();
1249         break;
1250     }
1251
1252     Frame* frame = pos.anchorNode()->document().frame();
1253     if (!frame)
1254         return x;
1255         
1256     if (m_xPosForVerticalArrowNavigation == NoXPosForVerticalArrowNavigation()) {
1257         VisiblePosition visiblePosition(pos, m_selection.affinity());
1258         // VisiblePosition creation can fail here if a node containing the selection becomes visibility:hidden
1259         // after the selection is created and before this function is called.
1260         x = visiblePosition.isNotNull() ? visiblePosition.lineDirectionPointForBlockDirectionNavigation() : 0;
1261         m_xPosForVerticalArrowNavigation = x;
1262     } else
1263         x = m_xPosForVerticalArrowNavigation;
1264         
1265     return x;
1266 }
1267
1268 void FrameSelection::clear()
1269 {
1270     m_granularity = CharacterGranularity;
1271     setSelection(VisibleSelection());
1272 }
1273
1274 void FrameSelection::prepareForDestruction()
1275 {
1276     m_granularity = CharacterGranularity;
1277
1278 #if ENABLE(TEXT_CARET)
1279     m_caretBlinkTimer.stop();
1280 #endif
1281
1282     RenderView* view = m_frame->contentRenderer();
1283     if (view)
1284         view->clearSelection();
1285
1286     setSelectionWithoutUpdatingAppearance(VisibleSelection(), defaultSetSelectionOptions(), AlignCursorOnScrollIfNeeded, CharacterGranularity);
1287     m_previousCaretNode.clear();
1288 }
1289
1290 void FrameSelection::setStart(const VisiblePosition &pos, EUserTriggered trigger)
1291 {
1292     if (m_selection.isBaseFirst())
1293         setBase(pos, trigger);
1294     else
1295         setExtent(pos, trigger);
1296 }
1297
1298 void FrameSelection::setEnd(const VisiblePosition &pos, EUserTriggered trigger)
1299 {
1300     if (m_selection.isBaseFirst())
1301         setExtent(pos, trigger);
1302     else
1303         setBase(pos, trigger);
1304 }
1305
1306 void FrameSelection::setBase(const VisiblePosition &pos, EUserTriggered userTriggered)
1307 {
1308     const bool selectionHasDirection = true;
1309     setSelection(VisibleSelection(pos.deepEquivalent(), m_selection.extent(), pos.affinity(), selectionHasDirection), defaultSetSelectionOptions(userTriggered));
1310 }
1311
1312 void FrameSelection::setExtent(const VisiblePosition &pos, EUserTriggered userTriggered)
1313 {
1314     const bool selectionHasDirection = true;
1315     setSelection(VisibleSelection(m_selection.base(), pos.deepEquivalent(), pos.affinity(), selectionHasDirection), defaultSetSelectionOptions(userTriggered));
1316 }
1317
1318 void FrameSelection::setBase(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)
1319 {
1320     const bool selectionHasDirection = true;
1321     setSelection(VisibleSelection(pos, m_selection.extent(), affinity, selectionHasDirection), defaultSetSelectionOptions(userTriggered));
1322 }
1323
1324 void FrameSelection::setExtent(const Position &pos, EAffinity affinity, EUserTriggered userTriggered)
1325 {
1326     const bool selectionHasDirection = true;
1327     setSelection(VisibleSelection(m_selection.base(), pos, affinity, selectionHasDirection), defaultSetSelectionOptions(userTriggered));
1328 }
1329
1330 void CaretBase::clearCaretRect()
1331 {
1332     m_caretLocalRect = LayoutRect();
1333 }
1334
1335 bool CaretBase::updateCaretRect(Document* document, const VisiblePosition& caretPosition)
1336 {
1337     document->updateLayoutIgnorePendingStylesheets();
1338     m_caretRectNeedsUpdate = false;
1339     RenderObject* renderer;
1340     m_caretLocalRect = localCaretRectInRendererForCaretPainting(caretPosition, renderer);
1341     return !m_caretLocalRect.isEmpty();
1342 }
1343
1344 RenderObject* FrameSelection::caretRendererWithoutUpdatingLayout() const
1345 {
1346     return rendererForCaretPainting(m_selection.start().deprecatedNode());
1347 }
1348
1349 RenderObject* DragCaretController::caretRenderer() const
1350 {
1351     return rendererForCaretPainting(m_position.deepEquivalent().deprecatedNode());
1352 }
1353
1354 static bool isNonOrphanedCaret(const VisibleSelection& selection)
1355 {
1356     return selection.isCaret() && !selection.start().isOrphan() && !selection.end().isOrphan();
1357 }
1358
1359 IntRect FrameSelection::absoluteCaretBounds()
1360 {
1361     if (!m_frame)
1362         return IntRect();
1363     updateSelectionByUpdatingLayoutOrStyle(*m_frame);
1364     recomputeCaretRect();
1365     return m_absCaretBounds;
1366 }
1367
1368 static void repaintCaretForLocalRect(Node* node, const LayoutRect& rect)
1369 {
1370     RenderObject* caretPainter = rendererForCaretPainting(node);
1371     if (!caretPainter)
1372         return;
1373
1374     caretPainter->repaintRectangle(rect);
1375 }
1376
1377 bool FrameSelection::recomputeCaretRect()
1378 {
1379     if (!shouldUpdateCaretRect())
1380         return false;
1381
1382     if (!m_frame)
1383         return false;
1384
1385     FrameView* v = m_frame->document()->view();
1386     if (!v)
1387         return false;
1388
1389     LayoutRect oldRect = localCaretRectWithoutUpdate();
1390
1391     RefPtr<Node> caretNode = m_previousCaretNode;
1392     if (shouldUpdateCaretRect()) {
1393         if (!isNonOrphanedCaret(m_selection))
1394             clearCaretRect();
1395         else {
1396             VisiblePosition visibleStart = m_selection.visibleStart();
1397             if (updateCaretRect(m_frame->document(), visibleStart)) {
1398                 caretNode = visibleStart.deepEquivalent().deprecatedNode();
1399                 m_absCaretBoundsDirty = true;
1400             }
1401         }
1402     }
1403     LayoutRect newRect = localCaretRectWithoutUpdate();
1404
1405     if (caretNode == m_previousCaretNode && oldRect == newRect && !m_absCaretBoundsDirty)
1406         return false;
1407
1408     IntRect oldAbsCaretBounds = m_absCaretBounds;
1409     m_absCaretBounds = absoluteBoundsForLocalCaretRect(rendererForCaretPainting(caretNode.get()), newRect);
1410
1411     if (m_absCaretBoundsDirty && m_selection.isCaret()) // We should be able to always assert this condition.
1412         ASSERT(m_absCaretBounds == m_selection.visibleStart().absoluteCaretBounds());
1413
1414     m_absCaretBoundsDirty = false;
1415
1416     if (caretNode == m_previousCaretNode && oldAbsCaretBounds == m_absCaretBounds)
1417         return false;
1418
1419 #if ENABLE(TEXT_CARET)
1420     if (RenderView* view = m_frame->document()->renderView()) {
1421         bool previousOrNewCaretNodeIsContentEditable = m_selection.isContentEditable() || (m_previousCaretNode && m_previousCaretNode->isContentEditable());
1422         if (shouldRepaintCaret(view, previousOrNewCaretNodeIsContentEditable)) {
1423             if (m_previousCaretNode)
1424                 repaintCaretForLocalRect(m_previousCaretNode.get(), oldRect);
1425             m_previousCaretNode = caretNode;
1426             repaintCaretForLocalRect(caretNode.get(), newRect);
1427         }
1428     }
1429 #endif
1430     return true;
1431 }
1432
1433 bool CaretBase::shouldRepaintCaret(const RenderView* view, bool isContentEditable) const
1434 {
1435     ASSERT(view);
1436     Frame* frame = &view->frameView().frame(); // The frame where the selection started.
1437     bool caretBrowsing = frame && frame->settings().caretBrowsingEnabled();
1438     return (caretBrowsing || isContentEditable);
1439 }
1440
1441 void FrameSelection::invalidateCaretRect()
1442 {
1443     if (!isCaret())
1444         return;
1445
1446     CaretBase::invalidateCaretRect(m_selection.start().deprecatedNode(), recomputeCaretRect());
1447 }
1448
1449 void CaretBase::invalidateCaretRect(Node* node, bool caretRectChanged)
1450 {
1451     // EDIT FIXME: This is an unfortunate hack.
1452     // Basically, we can't trust this layout position since we 
1453     // can't guarantee that the check to see if we are in unrendered 
1454     // content will work at this point. We may have to wait for
1455     // a layout and re-render of the document to happen. So, resetting this
1456     // flag will cause another caret layout to happen the first time
1457     // that we try to paint the caret after this call. That one will work since
1458     // it happens after the document has accounted for any editing
1459     // changes which may have been done.
1460     // And, we need to leave this layout here so the caret moves right 
1461     // away after clicking.
1462     m_caretRectNeedsUpdate = true;
1463
1464     if (caretRectChanged)
1465         return;
1466
1467     if (RenderView* view = node->document().renderView()) {
1468         if (shouldRepaintCaret(view, node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable)))
1469             repaintCaretForLocalRect(node, localCaretRectWithoutUpdate());
1470     }
1471 }
1472
1473 void FrameSelection::paintCaret(GraphicsContext* context, const LayoutPoint& paintOffset, const LayoutRect& clipRect)
1474 {
1475     if (m_selection.isCaret() && m_caretPaint)
1476         CaretBase::paintCaret(m_selection.start().deprecatedNode(), context, paintOffset, clipRect);
1477 }
1478
1479 void CaretBase::paintCaret(Node* node, GraphicsContext* context, const LayoutPoint& paintOffset, const LayoutRect& clipRect) const
1480 {
1481 #if ENABLE(TEXT_CARET)
1482     if (m_caretVisibility == Hidden)
1483         return;
1484
1485     LayoutRect drawingRect = localCaretRectWithoutUpdate();
1486     RenderObject* renderer = rendererForCaretPainting(node);
1487     if (renderer && renderer->isBox())
1488         toRenderBox(renderer)->flipForWritingMode(drawingRect);
1489     drawingRect.moveBy(roundedIntPoint(paintOffset));
1490     LayoutRect caret = intersection(drawingRect, clipRect);
1491     if (caret.isEmpty())
1492         return;
1493
1494     Color caretColor = Color::black;
1495     ColorSpace colorSpace = ColorSpaceDeviceRGB;
1496     Element* element = node->isElementNode() ? toElement(node) : node->parentElement();
1497     Element* rootEditableElement = node->rootEditableElement();
1498
1499     if (element && element->renderer()) {
1500         bool setToRootEditableElement = false;
1501         if (rootEditableElement && rootEditableElement->renderer()) {
1502             const auto& rootEditableStyle = rootEditableElement->renderer()->style();
1503             const auto& elementStyle = element->renderer()->style();
1504             if (rootEditableStyle.visitedDependentColor(CSSPropertyBackgroundColor) == elementStyle.visitedDependentColor(CSSPropertyBackgroundColor)) {
1505                 caretColor = rootEditableElement->renderer()->style().visitedDependentColor(CSSPropertyColor);
1506                 colorSpace = rootEditableElement->renderer()->style().colorSpace();
1507                 setToRootEditableElement = true;
1508             }
1509         }
1510         if (!setToRootEditableElement) {
1511             caretColor = element->renderer()->style().visitedDependentColor(CSSPropertyColor);
1512             colorSpace = element->renderer()->style().colorSpace();
1513         }
1514     }
1515
1516     context->fillRect(caret, caretColor, colorSpace);
1517 #else
1518     UNUSED_PARAM(node);
1519     UNUSED_PARAM(context);
1520     UNUSED_PARAM(paintOffset);
1521     UNUSED_PARAM(clipRect);
1522 #endif
1523 }
1524
1525 void FrameSelection::debugRenderer(RenderObject* r, bool selected) const
1526 {
1527     if (r->node()->isElementNode()) {
1528         Element* element = toElement(r->node());
1529         fprintf(stderr, "%s%s\n", selected ? "==> " : "    ", element->localName().string().utf8().data());
1530     } else if (r->isText()) {
1531         RenderText* textRenderer = toRenderText(r);
1532         if (!textRenderer->textLength() || !textRenderer->firstTextBox()) {
1533             fprintf(stderr, "%s#text (empty)\n", selected ? "==> " : "    ");
1534             return;
1535         }
1536         
1537         static const int max = 36;
1538         String text = textRenderer->text();
1539         int textLength = text.length();
1540         if (selected) {
1541             int offset = 0;
1542             if (r->node() == m_selection.start().containerNode())
1543                 offset = m_selection.start().computeOffsetInContainerNode();
1544             else if (r->node() == m_selection.end().containerNode())
1545                 offset = m_selection.end().computeOffsetInContainerNode();
1546
1547             int pos;
1548             InlineTextBox* box = textRenderer->findNextInlineTextBox(offset, pos);
1549             text = text.substring(box->start(), box->len());
1550             
1551             String show;
1552             int mid = max / 2;
1553             int caret = 0;
1554             
1555             // text is shorter than max
1556             if (textLength < max) {
1557                 show = text;
1558                 caret = pos;
1559             } else if (pos - mid < 0) {
1560                 // too few characters to left
1561                 show = text.left(max - 3) + "...";
1562                 caret = pos;
1563             } else if (pos - mid >= 0 && pos + mid <= textLength) {
1564                 // enough characters on each side
1565                 show = "..." + text.substring(pos - mid + 3, max - 6) + "...";
1566                 caret = mid;
1567             } else {
1568                 // too few characters on right
1569                 show = "..." + text.right(max - 3);
1570                 caret = pos - (textLength - show.length());
1571             }
1572             
1573             show.replace('\n', ' ');
1574             show.replace('\r', ' ');
1575             fprintf(stderr, "==> #text : \"%s\" at offset %d\n", show.utf8().data(), pos);
1576             fprintf(stderr, "           ");
1577             for (int i = 0; i < caret; i++)
1578                 fprintf(stderr, " ");
1579             fprintf(stderr, "^\n");
1580         } else {
1581             if ((int)text.length() > max)
1582                 text = text.left(max - 3) + "...";
1583             else
1584                 text = text.left(max);
1585             fprintf(stderr, "    #text : \"%s\"\n", text.utf8().data());
1586         }
1587     }
1588 }
1589
1590 bool FrameSelection::contains(const LayoutPoint& point)
1591 {
1592     // Treat a collapsed selection like no selection.
1593     if (!isRange())
1594         return false;
1595     
1596     RenderView* renderView = m_frame->contentRenderer();
1597     if (!renderView)
1598         return false;
1599     
1600     HitTestResult result(point);
1601     renderView->hitTest(HitTestRequest(), result);
1602     Node* innerNode = result.innerNode();
1603     if (!innerNode || !innerNode->renderer())
1604         return false;
1605     
1606     VisiblePosition visiblePos(innerNode->renderer()->positionForPoint(result.localPoint(), nullptr));
1607     if (visiblePos.isNull())
1608         return false;
1609         
1610     if (m_selection.visibleStart().isNull() || m_selection.visibleEnd().isNull())
1611         return false;
1612         
1613     Position start(m_selection.visibleStart().deepEquivalent());
1614     Position end(m_selection.visibleEnd().deepEquivalent());
1615     Position p(visiblePos.deepEquivalent());
1616
1617     return comparePositions(start, p) <= 0 && comparePositions(p, end) <= 0;
1618 }
1619
1620 // Workaround for the fact that it's hard to delete a frame.
1621 // Call this after doing user-triggered selections to make it easy to delete the frame you entirely selected.
1622 // Can't do this implicitly as part of every setSelection call because in some contexts it might not be good
1623 // for the focus to move to another frame. So instead we call it from places where we are selecting with the
1624 // mouse or the keyboard after setting the selection.
1625 void FrameSelection::selectFrameElementInParentIfFullySelected()
1626 {
1627     // Find the parent frame; if there is none, then we have nothing to do.
1628     Frame* parent = m_frame->tree().parent();
1629     if (!parent)
1630         return;
1631     Page* page = m_frame->page();
1632     if (!page)
1633         return;
1634
1635     // Check if the selection contains the entire frame contents; if not, then there is nothing to do.
1636     if (!isRange())
1637         return;
1638     if (!isStartOfDocument(selection().visibleStart()))
1639         return;
1640     if (!isEndOfDocument(selection().visibleEnd()))
1641         return;
1642
1643     // Get to the <iframe> or <frame> (or even <object>) element in the parent frame.
1644     Element* ownerElement = m_frame->ownerElement();
1645     if (!ownerElement)
1646         return;
1647     ContainerNode* ownerElementParent = ownerElement->parentNode();
1648     if (!ownerElementParent)
1649         return;
1650         
1651     // This method's purpose is it to make it easier to select iframes (in order to delete them).  Don't do anything if the iframe isn't deletable.
1652     if (!ownerElementParent->hasEditableStyle())
1653         return;
1654
1655     // Create compute positions before and after the element.
1656     unsigned ownerElementNodeIndex = ownerElement->computeNodeIndex();
1657     VisiblePosition beforeOwnerElement(VisiblePosition(Position(ownerElementParent, ownerElementNodeIndex, Position::PositionIsOffsetInAnchor)));
1658     VisiblePosition afterOwnerElement(VisiblePosition(Position(ownerElementParent, ownerElementNodeIndex + 1, Position::PositionIsOffsetInAnchor), VP_UPSTREAM_IF_POSSIBLE));
1659
1660     // Focus on the parent frame, and then select from before this element to after.
1661     VisibleSelection newSelection(beforeOwnerElement, afterOwnerElement);
1662     if (parent->selection().shouldChangeSelection(newSelection)) {
1663         page->focusController().setFocusedFrame(parent);
1664         parent->selection().setSelection(newSelection);
1665     }
1666 }
1667
1668 void FrameSelection::selectAll()
1669 {
1670     Document* document = m_frame->document();
1671
1672     Element* focusedElement = document->focusedElement();
1673     if (focusedElement && is<HTMLSelectElement>(focusedElement)) {
1674         HTMLSelectElement& selectElement = downcast<HTMLSelectElement>(*focusedElement);
1675         if (selectElement.canSelectAll()) {
1676             selectElement.selectAll();
1677             return;
1678         }
1679     }
1680
1681     RefPtr<Node> root;
1682     Node* selectStartTarget = nullptr;
1683     if (m_selection.isContentEditable()) {
1684         root = highestEditableRoot(m_selection.start());
1685         if (Node* shadowRoot = m_selection.nonBoundaryShadowTreeRootNode())
1686             selectStartTarget = shadowRoot->shadowHost();
1687         else
1688             selectStartTarget = root.get();
1689     } else {
1690         if (m_selection.isNone() && focusedElement) {
1691             if (focusedElement->isTextFormControl()) {
1692                 toHTMLTextFormControlElement(*focusedElement).select();
1693                 return;
1694             }
1695             root = focusedElement->nonBoundaryShadowTreeRootNode();
1696         } else
1697             root = m_selection.nonBoundaryShadowTreeRootNode();
1698
1699         if (root)
1700             selectStartTarget = root->shadowHost();
1701         else {
1702             root = document->documentElement();
1703             selectStartTarget = document->body();
1704         }
1705     }
1706     if (!root)
1707         return;
1708
1709     if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true)))
1710         return;
1711
1712     VisibleSelection newSelection(VisibleSelection::selectionFromContentsOfNode(root.get()));
1713
1714     if (shouldChangeSelection(newSelection))
1715         setSelection(newSelection, defaultSetSelectionOptions() | FireSelectEvent);
1716 }
1717
1718 bool FrameSelection::setSelectedRange(Range* range, EAffinity affinity, bool closeTyping)
1719 {
1720     if (!range || !range->startContainer() || !range->endContainer())
1721         return false;
1722     ASSERT(&range->startContainer()->document() == &range->endContainer()->document());
1723
1724     VisibleSelection newSelection(range, affinity);
1725
1726 #if PLATFORM(IOS)
1727     // FIXME: Why do we need this check only in iOS?
1728     if (range->startContainer() && range->endContainer() && newSelection.isNone())
1729         return false;
1730 #endif
1731
1732     setSelection(newSelection, ClearTypingStyle | (closeTyping ? CloseTyping : 0));
1733     return true;
1734 }
1735
1736 void FrameSelection::focusedOrActiveStateChanged()
1737 {
1738     bool activeAndFocused = isFocusedAndActive();
1739     Ref<Document> document(*m_frame->document());
1740
1741     document->updateStyleIfNeeded();
1742
1743 #if USE(UIKIT_EDITING)
1744     // Caret blinking (blinks | does not blink)
1745     if (activeAndFocused)
1746         setSelectionFromNone();
1747     setCaretVisible(activeAndFocused);
1748 #else
1749     // Because RenderObject::selectionBackgroundColor() and
1750     // RenderObject::selectionForegroundColor() check if the frame is active,
1751     // we have to update places those colors were painted.
1752     if (RenderView* view = document->renderView())
1753         view->repaintSelection();
1754
1755     // Caret appears in the active frame.
1756     if (activeAndFocused)
1757         setSelectionFromNone();
1758     setCaretVisibility(activeAndFocused ? Visible : Hidden);
1759
1760     // Update for caps lock state
1761     m_frame->eventHandler().capsLockStateMayHaveChanged();
1762
1763     // Because StyleResolver::checkOneSelector() and
1764     // RenderTheme::isFocused() check if the frame is active, we have to
1765     // update style and theme state that depended on those.
1766     if (Element* element = document->focusedElement()) {
1767         element->setNeedsStyleRecalc();
1768         if (RenderObject* renderer = element->renderer())
1769             if (renderer && renderer->style().hasAppearance())
1770                 renderer->theme().stateChanged(*renderer, ControlStates::FocusState);
1771     }
1772 #endif
1773 }
1774
1775 void FrameSelection::pageActivationChanged()
1776 {
1777     focusedOrActiveStateChanged();
1778 }
1779
1780 void FrameSelection::setFocused(bool flag)
1781 {
1782     if (m_focused == flag)
1783         return;
1784     m_focused = flag;
1785
1786     focusedOrActiveStateChanged();
1787 }
1788
1789 bool FrameSelection::isFocusedAndActive() const
1790 {
1791     return m_focused && m_frame->page() && m_frame->page()->focusController().isActive();
1792 }
1793
1794 #if ENABLE(TEXT_CARET)
1795 inline static bool shouldStopBlinkingDueToTypingCommand(Frame* frame)
1796 {
1797     return frame->editor().lastEditCommand() && frame->editor().lastEditCommand()->shouldStopCaretBlinking();
1798 }
1799 #endif
1800
1801 void FrameSelection::updateAppearance()
1802 {
1803 #if PLATFORM(IOS)
1804     if (!m_updateAppearanceEnabled)
1805         return;
1806 #endif
1807
1808     // Paint a block cursor instead of a caret in overtype mode unless the caret is at the end of a line (in this case
1809     // the FrameSelection will paint a blinking caret as usual).
1810     VisibleSelection oldSelection = selection();
1811     VisiblePosition forwardPosition;
1812     if (m_shouldShowBlockCursor && oldSelection.isCaret()) {
1813         forwardPosition = modifyExtendingForward(CharacterGranularity);
1814         m_caretPaint = forwardPosition.isNull();
1815     }
1816
1817 #if ENABLE(TEXT_CARET)
1818     bool caretRectChangedOrCleared = recomputeCaretRect();
1819
1820     bool caretBrowsing = m_frame->settings().caretBrowsingEnabled();
1821     bool shouldBlink = caretIsVisible() && isCaret() && (oldSelection.isContentEditable() || caretBrowsing) && forwardPosition.isNull();
1822
1823     // If the caret moved, stop the blink timer so we can restart with a
1824     // black caret in the new location.
1825     if (caretRectChangedOrCleared || !shouldBlink || shouldStopBlinkingDueToTypingCommand(m_frame))
1826         m_caretBlinkTimer.stop();
1827
1828     // Start blinking with a black caret. Be sure not to restart if we're
1829     // already blinking in the right location.
1830     if (shouldBlink && !m_caretBlinkTimer.isActive()) {
1831         if (double blinkInterval = m_frame->page()->theme().caretBlinkInterval())
1832             m_caretBlinkTimer.startRepeating(blinkInterval);
1833
1834         if (!m_caretPaint) {
1835             m_caretPaint = true;
1836             invalidateCaretRect();
1837         }
1838     }
1839 #endif
1840
1841     RenderView* view = m_frame->contentRenderer();
1842     if (!view)
1843         return;
1844
1845     // Construct a new VisibleSolution, since m_selection is not necessarily valid, and the following steps
1846     // assume a valid selection. See <https://bugs.webkit.org/show_bug.cgi?id=69563> and <rdar://problem/10232866>.
1847     VisibleSelection selection(oldSelection.visibleStart(), forwardPosition.isNotNull() ? forwardPosition : oldSelection.visibleEnd());
1848
1849     if (!selection.isRange()) {
1850         view->clearSelection();
1851         return;
1852     }
1853
1854     // Use the rightmost candidate for the start of the selection, and the leftmost candidate for the end of the selection.
1855     // Example: foo <a>bar</a>.  Imagine that a line wrap occurs after 'foo', and that 'bar' is selected.   If we pass [foo, 3]
1856     // as the start of the selection, the selection painting code will think that content on the line containing 'foo' is selected
1857     // and will fill the gap before 'bar'.
1858     Position startPos = selection.start();
1859     Position candidate = startPos.downstream();
1860     if (candidate.isCandidate())
1861         startPos = candidate;
1862     Position endPos = selection.end();
1863     candidate = endPos.upstream();
1864     if (candidate.isCandidate())
1865         endPos = candidate;
1866
1867     // We can get into a state where the selection endpoints map to the same VisiblePosition when a selection is deleted
1868     // because we don't yet notify the FrameSelection of text removal.
1869     if (startPos.isNotNull() && endPos.isNotNull() && selection.visibleStart() != selection.visibleEnd()) {
1870         RenderObject* startRenderer = startPos.deprecatedNode()->renderer();
1871         RenderObject* endRenderer = endPos.deprecatedNode()->renderer();
1872         view->setSelection(startRenderer, startPos.deprecatedEditingOffset(), endRenderer, endPos.deprecatedEditingOffset());
1873     }
1874 }
1875
1876 void FrameSelection::setCaretVisibility(CaretVisibility visibility)
1877 {
1878     if (caretVisibility() == visibility)
1879         return;
1880
1881     // FIXME: We shouldn't trigger a synchrnously layout here.
1882     if (m_frame)
1883         updateSelectionByUpdatingLayoutOrStyle(*m_frame);
1884
1885 #if ENABLE(TEXT_CARET)
1886     if (m_caretPaint) {
1887         m_caretPaint = false;
1888         invalidateCaretRect();
1889     }
1890     CaretBase::setCaretVisibility(visibility);
1891 #endif
1892
1893     updateAppearance();
1894 }
1895
1896 void FrameSelection::caretBlinkTimerFired(Timer<FrameSelection>&)
1897 {
1898 #if ENABLE(TEXT_CARET)
1899     ASSERT(caretIsVisible());
1900     ASSERT(isCaret());
1901     bool caretPaint = m_caretPaint;
1902     if (isCaretBlinkingSuspended() && caretPaint)
1903         return;
1904     m_caretPaint = !caretPaint;
1905     invalidateCaretRect();
1906 #endif
1907 }
1908
1909 // Helper function that tells whether a particular node is an element that has an entire
1910 // Frame and FrameView, a <frame>, <iframe>, or <object>.
1911 static bool isFrameElement(const Node* n)
1912 {
1913     if (!n)
1914         return false;
1915     RenderObject* renderer = n->renderer();
1916     if (!renderer || !renderer->isWidget())
1917         return false;
1918     Widget* widget = toRenderWidget(renderer)->widget();
1919     return widget && widget->isFrameView();
1920 }
1921
1922 void FrameSelection::setFocusedElementIfNeeded()
1923 {
1924     if (isNone() || !isFocused())
1925         return;
1926
1927     bool caretBrowsing = m_frame->settings().caretBrowsingEnabled();
1928     if (caretBrowsing) {
1929         if (Element* anchor = enclosingAnchorElement(m_selection.base())) {
1930             m_frame->page()->focusController().setFocusedElement(anchor, m_frame);
1931             return;
1932         }
1933     }
1934
1935     if (Element* target = m_selection.rootEditableElement()) {
1936         // Walk up the DOM tree to search for an element to focus.
1937         while (target) {
1938             // We don't want to set focus on a subframe when selecting in a parent frame,
1939             // so add the !isFrameElement check here. There's probably a better way to make this
1940             // work in the long term, but this is the safest fix at this time.
1941             if (target->isMouseFocusable() && !isFrameElement(target)) {
1942                 m_frame->page()->focusController().setFocusedElement(target, m_frame);
1943                 return;
1944             }
1945             target = target->parentOrShadowHostElement();
1946         }
1947         m_frame->document()->setFocusedElement(0);
1948     }
1949
1950     if (caretBrowsing)
1951         m_frame->page()->focusController().setFocusedElement(0, m_frame);
1952 }
1953
1954 void DragCaretController::paintDragCaret(Frame* frame, GraphicsContext* p, const LayoutPoint& paintOffset, const LayoutRect& clipRect) const
1955 {
1956 #if ENABLE(TEXT_CARET)
1957     if (m_position.deepEquivalent().deprecatedNode()->document().frame() == frame)
1958         paintCaret(m_position.deepEquivalent().deprecatedNode(), p, paintOffset, clipRect);
1959 #else
1960     UNUSED_PARAM(frame);
1961     UNUSED_PARAM(p);
1962     UNUSED_PARAM(paintOffset);
1963     UNUSED_PARAM(clipRect);
1964 #endif
1965 }
1966
1967 PassRefPtr<MutableStyleProperties> FrameSelection::copyTypingStyle() const
1968 {
1969     if (!m_typingStyle || !m_typingStyle->style())
1970         return 0;
1971     return m_typingStyle->style()->mutableCopy();
1972 }
1973
1974 bool FrameSelection::shouldDeleteSelection(const VisibleSelection& selection) const
1975 {
1976 #if PLATFORM(IOS)
1977     if (m_frame->selectionChangeCallbacksDisabled())
1978         return true;
1979 #endif
1980     return m_frame->editor().client()->shouldDeleteRange(selection.toNormalizedRange().get());
1981 }
1982
1983 FloatRect FrameSelection::selectionBounds(bool clipToVisibleContent) const
1984 {
1985     if (!m_frame->document())
1986         return LayoutRect();
1987
1988     updateSelectionByUpdatingLayoutOrStyle(*m_frame);
1989     RenderView* root = m_frame->contentRenderer();
1990     FrameView* view = m_frame->view();
1991     if (!root || !view)
1992         return LayoutRect();
1993
1994     LayoutRect selectionRect = root->selectionBounds(clipToVisibleContent);
1995     return clipToVisibleContent ? intersection(selectionRect, view->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect)) : selectionRect;
1996 }
1997
1998 void FrameSelection::getClippedVisibleTextRectangles(Vector<FloatRect>& rectangles) const
1999 {
2000     RenderView* root = m_frame->contentRenderer();
2001     if (!root)
2002         return;
2003
2004     FloatRect visibleContentRect = m_frame->view()->visibleContentRect(ScrollableArea::LegacyIOSDocumentVisibleRect);
2005
2006     Vector<FloatQuad> quads;
2007     toNormalizedRange()->textQuads(quads, true);
2008
2009     size_t size = quads.size();
2010     for (size_t i = 0; i < size; ++i) {
2011         FloatRect intersectionRect = intersection(quads[i].enclosingBoundingBox(), visibleContentRect);
2012         if (!intersectionRect.isEmpty())
2013             rectangles.append(intersectionRect);
2014     }
2015 }
2016
2017 // Scans logically forward from "start", including any child frames.
2018 static HTMLFormElement* scanForForm(Element* start)
2019 {
2020     if (!start)
2021         return nullptr;
2022
2023     auto descendants = descendantsOfType<HTMLElement>(start->document());
2024     for (auto it = descendants.from(*start), end = descendants.end(); it != end; ++it) {
2025         HTMLElement& element = *it;
2026         if (isHTMLFormElement(&element))
2027             return downcast<HTMLFormElement>(&element);
2028         if (is<HTMLFormControlElement>(element))
2029             return downcast<HTMLFormControlElement>(element).form();
2030         if (isHTMLFrameElementBase(element)) {
2031             Document* contentDocument = toHTMLFrameElementBase(element).contentDocument();
2032             if (!contentDocument)
2033                 continue;
2034             if (HTMLFormElement* frameResult = scanForForm(contentDocument->documentElement()))
2035                 return frameResult;
2036         }
2037     }
2038     return nullptr;
2039 }
2040
2041 // We look for either the form containing the current focus, or for one immediately after it
2042 HTMLFormElement* FrameSelection::currentForm() const
2043 {
2044     // Start looking either at the active (first responder) node, or where the selection is.
2045     Element* start = m_frame->document()->focusedElement();
2046     if (!start)
2047         start = m_selection.start().element();
2048     if (!start)
2049         return nullptr;
2050
2051     if (auto form = lineageOfType<HTMLFormElement>(*start).first())
2052         return form;
2053     if (auto formControl = lineageOfType<HTMLFormControlElement>(*start).first())
2054         return formControl->form();
2055
2056     // Try walking forward in the node tree to find a form element.
2057     return scanForForm(start);
2058 }
2059
2060 void FrameSelection::revealSelection(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
2061 {
2062     LayoutRect rect;
2063
2064     switch (m_selection.selectionType()) {
2065     case VisibleSelection::NoSelection:
2066         return;
2067     case VisibleSelection::CaretSelection:
2068         rect = absoluteCaretBounds();
2069         break;
2070     case VisibleSelection::RangeSelection:
2071         rect = revealExtentOption == RevealExtent ? VisiblePosition(m_selection.extent()).absoluteCaretBounds() : enclosingIntRect(selectionBounds(false));
2072         break;
2073     }
2074
2075     Position start = m_selection.start();
2076     ASSERT(start.deprecatedNode());
2077     if (start.deprecatedNode() && start.deprecatedNode()->renderer()) {
2078 #if PLATFORM(IOS)
2079         if (RenderLayer* layer = start.deprecatedNode()->renderer()->enclosingLayer()) {
2080             if (!m_scrollingSuppressCount) {
2081                 layer->setAdjustForIOSCaretWhenScrolling(true);
2082                 layer->scrollRectToVisible(rect, alignment, alignment);
2083                 layer->setAdjustForIOSCaretWhenScrolling(false);
2084                 updateAppearance();
2085                 if (m_frame->page())
2086                     m_frame->page()->chrome().client().notifyRevealedSelectionByScrollingFrame(m_frame);
2087             }
2088         }
2089 #else
2090         // FIXME: This code only handles scrolling the startContainer's layer, but
2091         // the selection rect could intersect more than just that.
2092         // See <rdar://problem/4799899>.
2093         if (start.deprecatedNode()->renderer()->scrollRectToVisible(rect, alignment, alignment))
2094             updateAppearance();
2095 #endif
2096     }
2097 }
2098
2099 void FrameSelection::setSelectionFromNone()
2100 {
2101     // Put a caret inside the body if the entire frame is editable (either the
2102     // entire WebView is editable or designMode is on for this document).
2103
2104     Document* document = m_frame->document();
2105 #if !PLATFORM(IOS)
2106     bool caretBrowsing = m_frame->settings().caretBrowsingEnabled();
2107     if (!isNone() || !(document->hasEditableStyle() || caretBrowsing))
2108         return;
2109 #else
2110     if (!document || !(isNone() || isStartOfDocument(VisiblePosition(m_selection.start(), m_selection.affinity()))) || !document->hasEditableStyle())
2111         return;
2112 #endif
2113
2114     auto* documentElement = document->documentElement();
2115     if (!documentElement)
2116         return;
2117     if (auto body = childrenOfType<HTMLBodyElement>(*documentElement).first())
2118         setSelection(VisibleSelection(firstPositionInOrBeforeNode(body), DOWNSTREAM));
2119 }
2120
2121 bool FrameSelection::shouldChangeSelection(const VisibleSelection& newSelection) const
2122 {
2123 #if PLATFORM(IOS)
2124     if (m_frame->selectionChangeCallbacksDisabled())
2125         return true;
2126 #endif
2127     return m_frame->editor().shouldChangeSelection(selection(), newSelection, newSelection.affinity(), false);
2128 }
2129
2130 bool FrameSelection::dispatchSelectStart()
2131 {
2132     Node* selectStartTarget = m_selection.extent().containerNode();
2133     if (!selectStartTarget)
2134         return true;
2135
2136     return selectStartTarget->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true));
2137 }
2138
2139 void FrameSelection::setShouldShowBlockCursor(bool shouldShowBlockCursor)
2140 {
2141     m_shouldShowBlockCursor = shouldShowBlockCursor;
2142
2143     m_frame->document()->updateLayoutIgnorePendingStylesheets();
2144
2145     updateAppearance();
2146 }
2147
2148 void FrameSelection::didLayout()
2149 {
2150     setCaretRectNeedsUpdate();
2151     updateAndRevealSelection();
2152     updateDataDetectorsForSelection();
2153 }
2154
2155 #ifndef NDEBUG
2156
2157 void FrameSelection::formatForDebugger(char* buffer, unsigned length) const
2158 {
2159     m_selection.formatForDebugger(buffer, length);
2160 }
2161
2162 void FrameSelection::showTreeForThis() const
2163 {
2164     m_selection.showTreeForThis();
2165 }
2166
2167 #endif
2168
2169 #if PLATFORM(IOS)
2170 void FrameSelection::expandSelectionToElementContainingCaretSelection()
2171 {
2172     RefPtr<Range> range = elementRangeContainingCaretSelection();
2173     if (!range)
2174         return;
2175     VisibleSelection selection(range.get(), DOWNSTREAM);
2176     setSelection(selection);
2177 }
2178
2179 PassRefPtr<Range> FrameSelection::elementRangeContainingCaretSelection() const
2180 {
2181     if (m_selection.isNone())
2182         return nullptr;
2183
2184     VisibleSelection selection = m_selection;
2185     if (selection.isNone())
2186         return nullptr;
2187
2188     VisiblePosition visiblePos(selection.start(), VP_DEFAULT_AFFINITY);
2189     if (visiblePos.isNull())
2190         return nullptr;
2191
2192     Node* node = visiblePos.deepEquivalent().deprecatedNode();
2193     Element* element = deprecatedEnclosingBlockFlowElement(node);
2194     if (!element)
2195         return nullptr;
2196
2197     Position startPos = createLegacyEditingPosition(element, 0);
2198     Position endPos = createLegacyEditingPosition(element, element->countChildNodes());
2199     
2200     VisiblePosition startVisiblePos(startPos, VP_DEFAULT_AFFINITY);
2201     VisiblePosition endVisiblePos(endPos, VP_DEFAULT_AFFINITY);
2202     if (startVisiblePos.isNull() || endVisiblePos.isNull())
2203         return nullptr;
2204
2205     selection.setBase(startVisiblePos);
2206     selection.setExtent(endVisiblePos);
2207
2208     return selection.toNormalizedRange();
2209 }
2210
2211 void FrameSelection::expandSelectionToWordContainingCaretSelection()
2212 {
2213     VisibleSelection selection(wordSelectionContainingCaretSelection(m_selection));        
2214     if (selection.isCaretOrRange())
2215         setSelection(selection);
2216 }
2217
2218 PassRefPtr<Range> FrameSelection::wordRangeContainingCaretSelection()
2219 {
2220     return wordSelectionContainingCaretSelection(m_selection).toNormalizedRange();
2221 }
2222
2223 void FrameSelection::expandSelectionToStartOfWordContainingCaretSelection()
2224 {
2225     if (m_selection.isNone() || isStartOfDocument(m_selection.start()))
2226         return;
2227
2228     VisiblePosition s1(m_selection.start());
2229     VisiblePosition e1(m_selection.end());
2230
2231     VisibleSelection expanded(wordSelectionContainingCaretSelection(m_selection));
2232     VisiblePosition s2(expanded.start());
2233
2234     // Don't allow the start to become greater after the expansion.
2235     if (s2.isNull() || s2 > s1)
2236         s2 = s1;
2237
2238     moveTo(s2, e1);
2239 }
2240
2241 UChar FrameSelection::characterInRelationToCaretSelection(int amount) const
2242 {
2243     if (m_selection.isNone())
2244         return 0;
2245
2246     VisibleSelection selection = m_selection;
2247     ASSERT(selection.isCaretOrRange());
2248
2249     VisiblePosition visiblePosition(selection.start(), VP_DEFAULT_AFFINITY);
2250
2251     if (amount < 0) {
2252         int count = abs(amount);
2253         for (int i = 0; i < count; i++)
2254             visiblePosition = visiblePosition.previous();    
2255         return visiblePosition.characterBefore();
2256     }
2257     for (int i = 0; i < amount; i++)
2258         visiblePosition = visiblePosition.next();    
2259     return visiblePosition.characterAfter();
2260 }
2261
2262 UChar FrameSelection::characterBeforeCaretSelection() const
2263 {
2264     if (m_selection.isNone())
2265         return 0;
2266
2267     VisibleSelection selection = m_selection;
2268     ASSERT(selection.isCaretOrRange());
2269
2270     VisiblePosition visiblePosition(selection.start(), VP_DEFAULT_AFFINITY);
2271     return visiblePosition.characterBefore();
2272 }
2273
2274 UChar FrameSelection::characterAfterCaretSelection() const
2275 {
2276     if (m_selection.isNone())
2277         return 0;
2278
2279     VisibleSelection selection = m_selection;
2280     ASSERT(selection.isCaretOrRange());
2281
2282     VisiblePosition visiblePosition(selection.end(), VP_DEFAULT_AFFINITY);
2283     return visiblePosition.characterAfter();
2284 }
2285
2286 int FrameSelection::wordOffsetInRange(const Range *range) const
2287 {
2288     if (!range)
2289         return -1;
2290
2291     VisibleSelection selection = m_selection;
2292     if (!selection.isCaret())
2293         return -1;
2294
2295     // FIXME: This will only work in cases where the selection remains in
2296     // the same node after it is expanded. Improve to handle more complicated
2297     // cases.
2298     ExceptionCode ec = 0;
2299     int result = selection.start().deprecatedEditingOffset() - range->startOffset(ec);
2300     ASSERT(!ec);
2301     if (result < 0)
2302         result = 0;
2303     return result;
2304 }
2305
2306 bool FrameSelection::spaceFollowsWordInRange(const Range *range) const
2307 {
2308     if (!range)
2309         return false;
2310     ExceptionCode ec = 0;
2311     Node* node = range->endContainer(ec);
2312     ASSERT(!ec);
2313     int endOffset = range->endOffset(ec);
2314     ASSERT(!ec);
2315     VisiblePosition pos(createLegacyEditingPosition(node, endOffset), VP_DEFAULT_AFFINITY);
2316     return isSpaceOrNewline(pos.characterAfter());
2317 }
2318
2319 bool FrameSelection::selectionAtDocumentStart() const
2320 {
2321     VisibleSelection selection = m_selection;
2322     if (selection.isNone())
2323         return false;
2324
2325     Position startPos(selection.start());
2326     VisiblePosition pos(createLegacyEditingPosition(startPos.deprecatedNode(), startPos.deprecatedEditingOffset()), VP_DEFAULT_AFFINITY);
2327     if (pos.isNull())
2328         return false;
2329
2330     return isStartOfDocument(pos);
2331 }
2332
2333 bool FrameSelection::selectionAtSentenceStart() const
2334 {
2335     VisibleSelection selection = m_selection;
2336     if (selection.isNone())
2337         return false;
2338
2339     return actualSelectionAtSentenceStart(selection);
2340 }
2341
2342 bool FrameSelection::selectionAtWordStart() const
2343 {
2344     VisibleSelection selection = m_selection;
2345     if (selection.isNone())
2346         return false;
2347
2348     Position startPos(selection.start());
2349     VisiblePosition pos(createLegacyEditingPosition(startPos.deprecatedNode(), startPos.deprecatedEditingOffset()), VP_DEFAULT_AFFINITY);
2350     if (pos.isNull())
2351         return false;
2352
2353     if (isStartOfParagraph(pos))
2354         return true;
2355         
2356     bool result = true;
2357     unsigned previousCount = 0;
2358     for (pos = pos.previous(); !pos.isNull(); pos = pos.previous()) {
2359         previousCount++;
2360         if (isStartOfParagraph(pos)) {
2361             if (previousCount == 1)
2362                 result = false;
2363             break;
2364         }
2365         UChar c(pos.characterAfter());
2366         if (c) {
2367             result = isSpaceOrNewline(c) || c == 0xA0 || (u_ispunct(c) && c != ',' && c != '-' && c != '\'');
2368             break;
2369         }
2370     }
2371
2372     return result;
2373 }
2374
2375 PassRefPtr<Range> FrameSelection::rangeByMovingCurrentSelection(int amount) const
2376 {
2377     return rangeByAlteringCurrentSelection(AlterationMove, amount);
2378 }
2379
2380 PassRefPtr<Range> FrameSelection::rangeByExtendingCurrentSelection(int amount) const
2381 {
2382     return rangeByAlteringCurrentSelection(AlterationExtend, amount);
2383 }
2384
2385 void FrameSelection::selectRangeOnElement(unsigned location, unsigned length, Node* node)
2386 {
2387     RefPtr<Range> resultRange = m_frame->document()->createRange();
2388     ExceptionCode ec = 0;
2389     resultRange->setStart(node, location, ec);
2390     ASSERT(!ec);
2391     resultRange->setEnd(node, location + length, ec);
2392     ASSERT(!ec);
2393     VisibleSelection selection = VisibleSelection(resultRange.get(), SEL_DEFAULT_AFFINITY);
2394     setSelection(selection, true);
2395 }
2396
2397 VisibleSelection FrameSelection::wordSelectionContainingCaretSelection(const VisibleSelection& selection)
2398 {
2399     if (selection.isNone())
2400         return VisibleSelection();
2401
2402     ASSERT(selection.isCaretOrRange());
2403     FrameSelection frameSelection;
2404     frameSelection.setSelection(selection);
2405
2406     Position startPosBeforeExpansion(selection.start());
2407     Position endPosBeforeExpansion(selection.end());
2408     VisiblePosition startVisiblePosBeforeExpansion(startPosBeforeExpansion, VP_DEFAULT_AFFINITY);
2409     VisiblePosition endVisiblePosBeforeExpansion(endPosBeforeExpansion, VP_DEFAULT_AFFINITY);
2410     if (endVisiblePosBeforeExpansion.isNull())
2411         return VisibleSelection();
2412
2413     if (isEndOfParagraph(endVisiblePosBeforeExpansion)) {
2414         UChar c(endVisiblePosBeforeExpansion.characterBefore());
2415         if (isSpaceOrNewline(c) || c == 0xA0) {
2416             // End of paragraph with space.
2417             return VisibleSelection();
2418         }
2419     }
2420
2421     // If at end of paragraph, move backwards one character.
2422     // This has the effect of selecting the word on the line (which is
2423     // what we want, rather than selecting past the end of the line).
2424     if (isEndOfParagraph(endVisiblePosBeforeExpansion) && !isStartOfParagraph(endVisiblePosBeforeExpansion))
2425         frameSelection.modify(FrameSelection::AlterationMove, DirectionBackward, CharacterGranularity);
2426
2427     VisibleSelection newSelection = frameSelection.selection();
2428     newSelection.expandUsingGranularity(WordGranularity);
2429     frameSelection.setSelection(newSelection, defaultSetSelectionOptions(), AlignCursorOnScrollIfNeeded, frameSelection.granularity());
2430
2431     Position startPos(frameSelection.selection().start());
2432     Position endPos(frameSelection.selection().end());
2433
2434     // Expansion cannot be allowed to change selection so that it is no longer
2435     // touches (or contains) the original, unexpanded selection.
2436     // Enforce this on the way into these additional calculations to give them
2437     // the best chance to yield a suitable answer.
2438     if (startPos > startPosBeforeExpansion)
2439         startPos = startPosBeforeExpansion;
2440     if (endPos < endPosBeforeExpansion)
2441         endPos = endPosBeforeExpansion;
2442
2443     VisiblePosition startVisiblePos(startPos, VP_DEFAULT_AFFINITY);
2444     VisiblePosition endVisiblePos(endPos, VP_DEFAULT_AFFINITY);
2445
2446     if (startVisiblePos.isNull() || endVisiblePos.isNull()) {
2447         // Start or end is nil
2448         return VisibleSelection();
2449     }
2450
2451     if (isEndOfLine(endVisiblePosBeforeExpansion)) {
2452         VisiblePosition previous(endVisiblePos.previous());
2453         if (previous == endVisiblePos) {
2454             // Empty document
2455             return VisibleSelection();
2456         }
2457         UChar c(previous.characterAfter());
2458         if (isSpaceOrNewline(c) || c == 0xA0) {
2459             // Space at end of line
2460             return VisibleSelection();
2461         }
2462     }
2463
2464     // Expansion has selected past end of line.
2465     // Try repositioning backwards.
2466     if (isEndOfLine(startVisiblePos) && isStartOfLine(endVisiblePos)) {
2467         VisiblePosition previous(startVisiblePos.previous());
2468         if (isEndOfLine(previous)) {
2469             // On empty line
2470             return VisibleSelection();
2471         }
2472         UChar c(previous.characterAfter());
2473         if (isSpaceOrNewline(c) || c == 0xA0) {
2474             // Space at end of line
2475             return VisibleSelection();
2476         }
2477         frameSelection.moveTo(startVisiblePos);
2478         frameSelection.modify(FrameSelection::AlterationExtend, DirectionBackward, WordGranularity);
2479         startPos = frameSelection.selection().start();
2480         endPos = frameSelection.selection().end();
2481         startVisiblePos = VisiblePosition(startPos, VP_DEFAULT_AFFINITY);
2482         endVisiblePos = VisiblePosition(endPos, VP_DEFAULT_AFFINITY);
2483         if (startVisiblePos.isNull() || endVisiblePos.isNull()) {
2484             // Start or end is nil
2485             return VisibleSelection();
2486         }
2487     }
2488
2489     // Now loop backwards until we find a non-space.
2490     while (endVisiblePos != startVisiblePos) {
2491         VisiblePosition previous(endVisiblePos.previous());
2492         UChar c(previous.characterAfter());
2493         if (!isSpaceOrNewline(c) && c != 0xA0)
2494             break;
2495         endVisiblePos = previous;
2496     }
2497
2498     // Expansion cannot be allowed to change selection so that it is no longer
2499     // touches (or contains) the original, unexpanded selection.
2500     // Enforce this on the way out of the function to preserve the invariant.
2501     if (startVisiblePos > startVisiblePosBeforeExpansion)
2502         startVisiblePos = startVisiblePosBeforeExpansion;
2503     if (endVisiblePos < endVisiblePosBeforeExpansion)
2504         endVisiblePos = endVisiblePosBeforeExpansion;
2505
2506     return VisibleSelection(startVisiblePos, endVisiblePos);    
2507 }
2508
2509 bool FrameSelection::actualSelectionAtSentenceStart(const VisibleSelection& sel) const
2510 {
2511     Position startPos(sel.start());
2512     VisiblePosition pos(createLegacyEditingPosition(startPos.deprecatedNode(), startPos.deprecatedEditingOffset()), VP_DEFAULT_AFFINITY);
2513     if (pos.isNull())
2514         return false;
2515
2516     if (isStartOfParagraph(pos))
2517         return true;
2518  
2519     bool result = true;
2520     bool sawSpace = false;
2521     unsigned previousCount = 0;
2522     for (pos = pos.previous(); !pos.isNull(); pos = pos.previous()) {
2523         previousCount++;
2524         if (isStartOfParagraph(pos)) {
2525             if (previousCount == 1 || (previousCount == 2 && sawSpace))
2526                 result = false;
2527             break;
2528         }
2529         UChar c(pos.characterAfter());
2530         if (c) {
2531             if (isSpaceOrNewline(c) || c == 0xA0) {
2532                 sawSpace = true;
2533             }
2534             else {
2535                 result = (c == '.' || c == '!' || c == '?');
2536                 break;
2537             }
2538         }
2539     }
2540     
2541     return result;
2542 }
2543
2544 PassRefPtr<Range> FrameSelection::rangeByAlteringCurrentSelection(EAlteration alteration, int amount) const
2545 {
2546     if (m_selection.isNone())
2547         return nullptr;
2548
2549     if (!amount)
2550         return toNormalizedRange();
2551
2552     FrameSelection frameSelection;
2553     frameSelection.setSelection(m_selection);
2554     SelectionDirection direction = amount > 0 ? DirectionForward : DirectionBackward;
2555     for (int i = 0; i < abs(amount); i++)
2556         frameSelection.modify(alteration, direction, CharacterGranularity);
2557     return frameSelection.toNormalizedRange();
2558 }
2559
2560 void FrameSelection::clearCurrentSelection()
2561 {
2562     setSelection(VisibleSelection());
2563 }
2564
2565 void FrameSelection::setCaretBlinks(bool caretBlinks)
2566 {
2567     if (m_caretBlinks == caretBlinks)
2568         return;
2569 #if ENABLE(TEXT_CARET)
2570     m_frame->document()->updateLayoutIgnorePendingStylesheets(); 
2571     if (m_caretPaint) {
2572         m_caretPaint = false; 
2573         invalidateCaretRect(); 
2574     }
2575 #endif
2576     if (caretBlinks)
2577         setFocusedElementIfNeeded();
2578     m_caretBlinks = caretBlinks;
2579     updateAppearance();
2580 }
2581
2582 void FrameSelection::setCaretColor(const Color& caretColor)
2583 {
2584     if (m_caretColor != caretColor) {
2585         m_caretColor = caretColor;
2586         if (caretIsVisible() && m_caretBlinks && isCaret())
2587             invalidateCaretRect();
2588     }
2589 }
2590 #endif // PLATFORM(IOS)
2591
2592 }
2593
2594 #ifndef NDEBUG
2595
2596 void showTree(const WebCore::FrameSelection& sel)
2597 {
2598     sel.showTreeForThis();
2599 }
2600
2601 void showTree(const WebCore::FrameSelection* sel)
2602 {
2603     if (sel)
2604         sel->showTreeForThis();
2605 }
2606
2607 #endif