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