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