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